@hashgraphonline/standards-sdk 0.0.116 → 0.0.117
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.
- package/dist/cjs/hcs-10/sdk.d.ts +1 -0
- package/dist/cjs/hcs-10/sdk.d.ts.map +1 -1
- package/dist/cjs/{index-qpugvUCd.cjs → index-CHS2J8pS.cjs} +2 -2
- package/dist/cjs/index-CHS2J8pS.cjs.map +1 -0
- package/dist/cjs/{index-CHar8dVv-BQYxSvOg.cjs → index-CHar8dVv-B2IK-7-2.cjs} +2 -2
- package/dist/cjs/{index-CHar8dVv-BQYxSvOg.cjs.map → index-CHar8dVv-B2IK-7-2.cjs.map} +1 -1
- package/dist/cjs/standards-sdk.cjs +1 -1
- package/dist/es/hcs-10/sdk.d.ts +1 -0
- package/dist/es/hcs-10/sdk.d.ts.map +1 -1
- package/dist/es/standards-sdk.es7.js +7 -5
- package/dist/es/standards-sdk.es7.js.map +1 -1
- package/dist/umd/hcs-10/sdk.d.ts +1 -0
- package/dist/umd/hcs-10/sdk.d.ts.map +1 -1
- package/dist/umd/standards-sdk.umd.js +1 -1
- package/dist/umd/standards-sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/dist/cjs/index-qpugvUCd.cjs.map +0 -1
|
@@ -7,5 +7,5 @@ read:function(e,t,r,o,n){var i,s,a=8*n-o-1,c=(1<<a)-1,u=c>>1,l=-7,d=r?n-1:0,p=r?
|
|
|
7
7
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
8
8
|
* @license MIT
|
|
9
9
|
*/
|
|
10
|
-
!function(e){const t=w,r=x,o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=u,e.SlowBuffer=function(e){+e!=e&&(e=0);return u.alloc(+e)},e.INSPECT_MAX_BYTES=50;const n=2147483647;e.kMaxLength=n;const{Uint8Array:i,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new i(e);return Object.setPrototypeOf(t,u.prototype),t}function u(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 l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let o=c(r);const n=o.write(e,t);n!==r&&(o=o.slice(0,n));return o}(e,t);if(s.isView(e))return function(e){if(Q(e,i)){const t=new i(e);return h(t.buffer,t.byteOffset,t.byteLength)}return f(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(Q(e,s)||e&&Q(e.buffer,s))return h(e,t,r);if(void 0!==a&&(Q(e,a)||e&&Q(e.buffer,a)))return h(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return u.from(o,t,r);const n=function(e){if(u.isBuffer(e)){const t=0|g(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||Z(e.length)?c(0):f(e);if("Buffer"===e.type&&Array.isArray(e.data))return f(e.data)}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.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|g(e))}function f(e){const t=e.length<0?0:0|g(e.length),r=c(t);for(let o=0;o<t;o+=1)r[o]=255&e[o];return r}function h(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 o;return o=void 0===t&&void 0===r?new i(e):void 0===r?new i(e,t):new i(e,t,r),Object.setPrototypeOf(o,u.prototype),o}function g(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function m(e,t){if(u.isBuffer(e))return e.length;if(s.isView(e)||Q(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,o=arguments.length>2&&!0===arguments[2];if(!o&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return J(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(e).length;default:if(n)return o?-1:J(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){let o=!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 F(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return $(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return C(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,r);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function b(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function I(e,t,r,o,n){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,o)),u.isBuffer(t))return 0===t.length?-1:k(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof i.prototype.indexOf?n?i.prototype.indexOf.call(e,t,r):i.prototype.lastIndexOf.call(e,t,r):k(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function k(e,t,r,o,n){let i,s=1,a=e.length,c=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let o=-1;for(i=r;i<a;i++)if(u(e,i)===u(t,-1===o?0:i-o)){if(-1===o&&(o=i),i-o+1===c)return o*s}else-1!==o&&(i-=i-o),o=-1}else for(r+c>a&&(r=a-c),i=r;i>=0;i--){let r=!0;for(let o=0;o<c;o++)if(u(e,i+o)!==u(t,o)){r=!1;break}if(r)return i}return-1}function T(e,t,r,o){r=Number(r)||0;const n=e.length-r;o?(o=Number(o))>n&&(o=n):o=n;const i=t.length;let s;for(o>i/2&&(o=i/2),s=0;s<o;++s){const o=parseInt(t.substr(2*s,2),16);if(Z(o))return s;e[r+s]=o}return s}function A(e,t,r,o){return Y(J(t,e.length-r),e,r,o)}function S(e,t,r,o){return Y(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,o)}function v(e,t,r,o){return Y(X(t),e,r,o)}function E(e,t,r,o){return Y(function(e,t){let r,o,n;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),o=r>>8,n=r%256,i.push(n),i.push(o);return i}(t,e.length-r),e,r,o)}function C(e,r,o){return 0===r&&o===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,o))}function R(e,t,r){r=Math.min(e.length,r);const o=[];let n=t;for(;n<r;){const t=e[n];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(n+s<=r){let r,o,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:r=e[n+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(i=c));break;case 3:r=e[n+1],o=e[n+2],128==(192&r)&&128==(192&o)&&(c=(15&t)<<12|(63&r)<<6|63&o,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:r=e[n+1],o=e[n+2],a=e[n+3],128==(192&r)&&128==(192&o)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&o)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,o.push(i>>>10&1023|55296),i=56320|1023&i),o.push(i),n+=s}return function(e){const t=e.length;if(t<=N)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=N));return r}(o)}u.TYPED_ARRAY_SUPPORT=function(){try{const e=new i(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,i.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),u.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(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(u.prototype,i.prototype),Object.setPrototypeOf(u,i),u.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)},u.allocUnsafe=function(e){return p(e)},u.allocUnsafeSlow=function(e){return p(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(Q(e,i)&&(e=u.from(e,e.offset,e.byteLength)),Q(t,i)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.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,o=t.length;for(let n=0,i=Math.min(r,o);n<i;++n)if(e[n]!==t[n]){r=e[n],o=t[n];break}return r<o?-1:o<r?1:0},u.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}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const o=u.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(Q(t,i))n+t.length>o.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(o,n)):i.prototype.set.call(o,t,n);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(o,n)}n+=t.length}return o},u.byteLength=m,u.prototype._isBuffer=!0,u.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},u.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},u.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},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):y.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.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+">"},o&&(u.prototype[o]=u.prototype.inspect),u.prototype.compare=function(e,t,r,o,n){if(Q(e,i)&&(e=u.from(e,e.offset,e.byteLength)),!u.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===o&&(o=0),void 0===n&&(n=this.length),t<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(o>=n&&t>=r)return 0;if(o>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(n>>>=0)-(o>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),l=this.slice(o,n),d=e.slice(t,r);for(let i=0;i<c;++i)if(l[i]!==d[i]){s=l[i],a=d[i];break}return s<a?-1:a<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return I(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return I(this,e,t,r,!1)},u.prototype.write=function(e,t,r,o){if(void 0===t)o="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)o=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===o&&(o="utf8")):(o=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let i=!1;for(;;)switch(o){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return A(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const N=4096;function $(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(127&e[n]);return o}function P(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(e[n]);return o}function F(e,t,r){const o=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>o)&&(r=o);let n="";for(let i=t;i<r;++i)n+=ee[e[i]];return n}function _(e,t,r){const o=e.slice(t,r);let n="";for(let i=0;i<o.length-1;i+=2)n+=String.fromCharCode(o[i]+256*o[i+1]);return n}function L(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 D(e,t,r,o,n,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw new RangeError('"value" argument is out of bounds');if(r+o>e.length)throw new RangeError("Index out of range")}function O(e,t,r,o,n){W(t,o,n,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;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 U(e,t,r,o,n){W(t,o,n,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function B(e,t,r,o,n,i){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,o,n,i){return t=+t,o>>>=0,i||B(e,0,o,4),r.write(e,t,o,n,23,4),o+4}function q(e,t,o,n,i){return t=+t,o>>>=0,i||B(e,0,o,8),r.write(e,t,o,n,52,8),o+8}u.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 o=this.subarray(e,t);return Object.setPrototypeOf(o,u.prototype),o},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e],n=1,i=0;for(;++i<t&&(n*=256);)o+=this[e+i]*n;return o},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e+--t],n=1;for(;t>0&&(n*=256);)o+=this[e+--t]*n;return o},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(o)+(BigInt(n)<<BigInt(32))})),u.prototype.readBigUInt64BE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(o)<<BigInt(32))+BigInt(n)})),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e],n=1,i=0;for(;++i<t&&(n*=256);)o+=this[e+i]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=t,n=1,i=this[e+--o];for(;o>0&&(n*=256);)i+=this[e+--o]*n;return n*=128,i>=n&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||L(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||L(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),u.prototype.readBigInt64BE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,o){if(e=+e,t>>>=0,r>>>=0,!o){D(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=1,i=0;for(this[t]=255&e;++i<r&&(n*=256);)this[t+i]=e/n&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,o){if(e=+e,t>>>=0,r>>>=0,!o){D(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=r-1,i=1;for(this[t+n]=255&e;--n>=0&&(i*=256);)this[t+n]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeBigUInt64LE=te((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=te((function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);D(this,e,t,r,o-1,-o)}let n=0,i=1,s=0;for(this[t]=255&e;++n<r&&(i*=256);)e<0&&0===s&&0!==this[t+n-1]&&(s=1),this[t+n]=(e/i|0)-s&255;return t+r},u.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);D(this,e,t,r,o-1,-o)}let n=r-1,i=1,s=0;for(this[t+n]=255&e;--n>=0&&(i*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/i|0)-s&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeBigInt64LE=te((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=te((function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return q(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return q(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,o){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o<r&&(o=r),o===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(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t<o-r&&(o=e.length-t+r);const n=o-r;return this===e&&"function"==typeof i.prototype.copyWithin?this.copyWithin(t,r,o):i.prototype.set.call(e,this.subarray(r,o),t),n},u.prototype.fill=function(e,t,r,o){if("string"==typeof e){if("string"==typeof t?(o=t,t=0,r=this.length):"string"==typeof r&&(o=r,r=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!u.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===e.length){const t=e.charCodeAt(0);("utf8"===o&&t<128||"latin1"===o)&&(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 n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const i=u.isBuffer(e)?e:u.from(e,o),s=i.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=i[n%s]}return this};const K={};function j(e,t,r){K[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 z(e){let t="",r=e.length;const o="-"===e[0]?1:0;for(;r>=o+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,o,n,i){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let o;throw o=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(i+1)}${r}`:`>= -(2${r} ** ${8*(i+1)-1}${r}) and < 2 ** ${8*(i+1)-1}${r}`,new K.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){H(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(o,n,i)}function H(e,t){if("number"!=typeof e)throw new K.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw H(e,r),new K.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new K.ERR_BUFFER_OUT_OF_BOUNDS;throw new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}j("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),j("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),j("ERR_OUT_OF_RANGE",(function(e,t,r){let o=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=z(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=z(n)),n+="n"),o+=` It must be ${t}. Received ${n}`,o}),RangeError);const G=/[^+/0-9A-Za-z-_]/g;function J(e,t){let r;t=t||1/0;const o=e.length;let n=null;const i=[];for(let s=0;s<o;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===o){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.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;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function X(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,r,o){let n;for(n=0;n<o&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const o=16*r;for(let n=0;n<16;++n)t[o+n]=e[r]+e[n]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}(y);const E=y.Buffer,C=y.Buffer,R=globalThis||self;function N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $,P,F={exports:{}},_=F.exports={};function L(){throw new Error("setTimeout has not been defined")}function D(){throw new Error("clearTimeout has not been defined")}function O(e){if($===setTimeout)return setTimeout(e,0);if(($===L||!$)&&setTimeout)return $=setTimeout,setTimeout(e,0);try{return $(e,0)}catch(t){try{return $.call(null,e,0)}catch(r){return $.call(this,e,0)}}}!function(){try{$="function"==typeof setTimeout?setTimeout:L}catch(e){$=L}try{P="function"==typeof clearTimeout?clearTimeout:D}catch(e){P=D}}();var U,B=[],M=!1,q=-1;function K(){M&&U&&(M=!1,U.length?B=U.concat(B):q=-1,B.length&&j())}function j(){if(!M){var e=O(K);M=!0;for(var t=B.length;t;){for(U=B,B=[];++q<t;)U&&U[q].run();q=-1,t=B.length}U=null,M=!1,function(e){if(P===clearTimeout)return clearTimeout(e);if((P===D||!P)&&clearTimeout)return P=clearTimeout,clearTimeout(e);try{return P(e)}catch(t){try{return P.call(null,e)}catch(r){return P.call(this,e)}}}(e)}}function z(e,t){this.fun=e,this.array=t}function W(){}_.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];B.push(new z(e,t)),1!==B.length||M||O(j)},z.prototype.run=function(){this.fun.apply(null,this.array)},_.title="browser",_.browser=!0,_.env={},_.argv=[],_.version="",_.versions={},_.on=W,_.addListener=W,_.once=W,_.off=W,_.removeListener=W,_.removeAllListeners=W,_.emit=W,_.prependListener=W,_.prependOnceListener=W,_.listeners=function(e){return[]},_.binding=function(e){throw new Error("process.binding is not supported")},_.cwd=function(){return"/"},_.chdir=function(e){throw new Error("process.chdir is not supported")},_.umask=function(){return 0};const H=N(F.exports);function V(e,t){return function(){return e.apply(t,arguments)}}const{toString:G}=Object.prototype,{getPrototypeOf:J}=Object,X=(e=>t=>{const r=G.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Y=e=>(e=e.toLowerCase(),t=>X(t)===e),Q=e=>t=>typeof t===e,{isArray:Z}=Array,ee=Q("undefined");const te=Y("ArrayBuffer");const re=Q("string"),oe=Q("function"),ne=Q("number"),ie=e=>null!==e&&"object"==typeof e,se=e=>{if("object"!==X(e))return!1;const t=J(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},ae=Y("Date"),ce=Y("File"),ue=Y("Blob"),le=Y("FileList"),de=Y("URLSearchParams"),[pe,fe,he,ge]=["ReadableStream","Request","Response","Headers"].map(Y);function me(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let o,n;if("object"!=typeof e&&(e=[e]),Z(e))for(o=0,n=e.length;o<n;o++)t.call(null,e[o],o,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),i=n.length;let s;for(o=0;o<i;o++)s=n[o],t.call(null,e[s],s,e)}}function ye(e,t){t=t.toLowerCase();const r=Object.keys(e);let o,n=r.length;for(;n-- >0;)if(o=r[n],t===o.toLowerCase())return o;return null}const we="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:R,be=e=>!ee(e)&&e!==we;const Ie=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&J(Uint8Array)),ke=Y("HTMLFormElement"),Te=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ae=Y("RegExp"),Se=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),o={};me(r,((r,n)=>{let i;!1!==(i=t(r,n,e))&&(o[n]=i||r)})),Object.defineProperties(e,o)};const ve=Y("AsyncFunction"),xe=(Ee="function"==typeof setImmediate,Ce=oe(we.postMessage),Ee?setImmediate:Ce?(Re=`axios@${Math.random()}`,Ne=[],we.addEventListener("message",(({source:e,data:t})=>{e===we&&t===Re&&Ne.length&&Ne.shift()()}),!1),e=>{Ne.push(e),we.postMessage(Re,"*")}):e=>setTimeout(e));var Ee,Ce,Re,Ne;const $e="undefined"!=typeof queueMicrotask?queueMicrotask.bind(we):void 0!==H&&H.nextTick||xe,Pe={isArray:Z,isArrayBuffer:te,isBuffer:function(e){return null!==e&&!ee(e)&&null!==e.constructor&&!ee(e.constructor)&&oe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||oe(e.append)&&("formdata"===(t=X(e))||"object"===t&&oe(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&te(e.buffer),t},isString:re,isNumber:ne,isBoolean:e=>!0===e||!1===e,isObject:ie,isPlainObject:se,isReadableStream:pe,isRequest:fe,isResponse:he,isHeaders:ge,isUndefined:ee,isDate:ae,isFile:ce,isBlob:ue,isRegExp:Ae,isFunction:oe,isStream:e=>ie(e)&&oe(e.pipe),isURLSearchParams:de,isTypedArray:Ie,isFileList:le,forEach:me,merge:function e(){const{caseless:t}=be(this)&&this||{},r={},o=(o,n)=>{const i=t&&ye(r,n)||n;se(r[i])&&se(o)?r[i]=e(r[i],o):se(o)?r[i]=e({},o):Z(o)?r[i]=o.slice():r[i]=o};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&me(arguments[n],o);return r},extend:(e,t,r,{allOwnKeys:o}={})=>(me(t,((t,o)=>{r&&oe(t)?e[o]=V(t,r):e[o]=t}),{allOwnKeys:o}),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,o)=>{e.prototype=Object.create(t.prototype,o),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,o)=>{let n,i,s;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),i=n.length;i-- >0;)s=n[i],o&&!o(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&J(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:X,kindOfTest:Y,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const o=e.indexOf(t,r);return-1!==o&&o===r},toArray:e=>{if(!e)return null;if(Z(e))return e;let t=e.length;if(!ne(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const r=o.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const o=[];for(;null!==(r=e.exec(t));)o.push(r);return o},isHTMLForm:ke,hasOwnProperty:Te,hasOwnProp:Te,reduceDescriptors:Se,freezeMethods:e=>{Se(e,((t,r)=>{if(oe(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const o=e[r];oe(o)&&(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={},o=e=>{e.forEach((e=>{r[e]=!0}))};return Z(e)?o(e):o(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:ye,global:we,isContextDefined:be,isSpecCompliantForm:function(e){return!!(e&&oe(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,o)=>{if(ie(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[o]=e;const n=Z(e)?[]:{};return me(e,((e,t)=>{const i=r(e,o+1);!ee(i)&&(n[t]=i)})),t[o]=void 0,n}}return e};return r(e,0)},isAsyncFn:ve,isThenable:e=>e&&(ie(e)||oe(e))&&oe(e.then)&&oe(e.catch),setImmediate:xe,asap:$e};function Fe(e,t,r,o,n){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),o&&(this.request=o),n&&(this.response=n,this.status=n.status?n.status:null)}Pe.inherits(Fe,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:Pe.toJSONObject(this.config),code:this.code,status:this.status}}});const _e=Fe.prototype,Le={};["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=>{Le[e]={value:e}})),Object.defineProperties(Fe,Le),Object.defineProperty(_e,"isAxiosError",{value:!0}),Fe.from=(e,t,r,o,n,i)=>{const s=Object.create(_e);return Pe.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Fe.call(s,e.message,t,r,o,n),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};function De(e){return Pe.isPlainObject(e)||Pe.isArray(e)}function Oe(e){return Pe.endsWith(e,"[]")?e.slice(0,-2):e}function Ue(e,t,r){return e?e.concat(t).map((function(e,t){return e=Oe(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Be=Pe.toFlatObject(Pe,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Me(e,t,r){if(!Pe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const o=(r=Pe.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Pe.isUndefined(t[e])}))).metaTokens,n=r.visitor||u,i=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Pe.isSpecCompliantForm(t);if(!Pe.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Pe.isDate(e))return e.toISOString();if(!a&&Pe.isBlob(e))throw new Fe("Blob is not supported. Use a Buffer instead.");return Pe.isArrayBuffer(e)||Pe.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):E.from(e):e}function u(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(Pe.endsWith(r,"{}"))r=o?r:r.slice(0,-2),e=JSON.stringify(e);else if(Pe.isArray(e)&&function(e){return Pe.isArray(e)&&!e.some(De)}(e)||(Pe.isFileList(e)||Pe.endsWith(r,"[]"))&&(a=Pe.toArray(e)))return r=Oe(r),a.forEach((function(e,o){!Pe.isUndefined(e)&&null!==e&&t.append(!0===s?Ue([r],o,i):null===s?r:r+"[]",c(e))})),!1;return!!De(e)||(t.append(Ue(n,r,i),c(e)),!1)}const l=[],d=Object.assign(Be,{defaultVisitor:u,convertValue:c,isVisitable:De});if(!Pe.isObject(e))throw new TypeError("data must be an object");return function e(r,o){if(!Pe.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+o.join("."));l.push(r),Pe.forEach(r,(function(r,i){!0===(!(Pe.isUndefined(r)||null===r)&&n.call(t,r,Pe.isString(i)?i.trim():i,o,d))&&e(r,o?o.concat(i):[i])})),l.pop()}}(e),t}function qe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Ke(e,t){this._pairs=[],e&&Me(e,this,t)}const je=Ke.prototype;function ze(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function We(e,t,r){if(!t)return e;const o=r&&r.encode||ze;Pe.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let i;if(i=n?n(t,r):Pe.isURLSearchParams(t)?t.toString():new Ke(t,r).toString(o),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}je.append=function(e,t){this._pairs.push([e,t])},je.toString=function(e){const t=e?function(t){return e.call(this,t,qe)}:qe;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class He{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){Pe.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const Ve={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ge={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ke,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Je="undefined"!=typeof window&&"undefined"!=typeof document,Xe="object"==typeof navigator&&navigator||void 0,Ye=Je&&(!Xe||["ReactNative","NativeScript","NS"].indexOf(Xe.product)<0),Qe="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ze=Je&&window.location.href||"http://localhost",et={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Je,hasStandardBrowserEnv:Ye,hasStandardBrowserWebWorkerEnv:Qe,navigator:Xe,origin:Ze},Symbol.toStringTag,{value:"Module"})),...Ge};function tt(e){function t(e,r,o,n){let i=e[n++];if("__proto__"===i)return!0;const s=Number.isFinite(+i),a=n>=e.length;if(i=!i&&Pe.isArray(o)?o.length:i,a)return Pe.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!s;o[i]&&Pe.isObject(o[i])||(o[i]=[]);return t(e,r,o[i],n)&&Pe.isArray(o[i])&&(o[i]=function(e){const t={},r=Object.keys(e);let o;const n=r.length;let i;for(o=0;o<n;o++)i=r[o],t[i]=e[i];return t}(o[i])),!s}if(Pe.isFormData(e)&&Pe.isFunction(e.entries)){const r={};return Pe.forEachEntry(e,((e,o)=>{t(function(e){return Pe.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),o,r,0)})),r}return null}const rt={transitional:Ve,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",o=r.indexOf("application/json")>-1,n=Pe.isObject(e);n&&Pe.isHTMLForm(e)&&(e=new FormData(e));if(Pe.isFormData(e))return o?JSON.stringify(tt(e)):e;if(Pe.isArrayBuffer(e)||Pe.isBuffer(e)||Pe.isStream(e)||Pe.isFile(e)||Pe.isBlob(e)||Pe.isReadableStream(e))return e;if(Pe.isArrayBufferView(e))return e.buffer;if(Pe.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Me(e,new et.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,o){return et.isNode&&Pe.isBuffer(e)?(this.append(t,e.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=Pe.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||o?(t.setContentType("application/json",!1),function(e,t){if(Pe.isString(e))try{return(t||JSON.parse)(e),Pe.trim(e)}catch(r){if("SyntaxError"!==r.name)throw r}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||rt.transitional,r=t&&t.forcedJSONParsing,o="json"===this.responseType;if(Pe.isResponse(e)||Pe.isReadableStream(e))return e;if(e&&Pe.isString(e)&&(r&&!this.responseType||o)){const r=!(t&&t.silentJSONParsing)&&o;try{return JSON.parse(e)}catch(n){if(r){if("SyntaxError"===n.name)throw Fe.from(n,Fe.ERR_BAD_RESPONSE,this,null,this.response);throw n}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:et.classes.FormData,Blob:et.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Pe.forEach(["delete","get","head","post","put","patch"],(e=>{rt.headers[e]={}}));const ot=Pe.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"]),nt=Symbol("internals");function it(e){return e&&String(e).trim().toLowerCase()}function st(e){return!1===e||null==e?e:Pe.isArray(e)?e.map(st):String(e)}function at(e,t,r,o,n){return Pe.isFunction(o)?o.call(this,t,r):(n&&(t=r),Pe.isString(t)?Pe.isString(o)?-1!==t.indexOf(o):Pe.isRegExp(o)?o.test(t):void 0:void 0)}class ct{constructor(e){e&&this.set(e)}set(e,t,r){const o=this;function n(e,t,r){const n=it(t);if(!n)throw new Error("header name must be a non-empty string");const i=Pe.findKey(o,n);(!i||void 0===o[i]||!0===r||void 0===r&&!1!==o[i])&&(o[i||t]=st(e))}const i=(e,t)=>Pe.forEach(e,((e,r)=>n(e,r,t)));if(Pe.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(Pe.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,o,n;return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),o=e.substring(n+1).trim(),!r||t[r]&&ot[r]||("set-cookie"===r?t[r]?t[r].push(o):t[r]=[o]:t[r]=t[r]?t[r]+", "+o:o)})),t})(e),t);else if(Pe.isHeaders(e))for(const[s,a]of e.entries())n(a,s,r);else null!=e&&n(t,e,r);return this}get(e,t){if(e=it(e)){const r=Pe.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 o;for(;o=r.exec(e);)t[o[1]]=o[2];return t}(e);if(Pe.isFunction(t))return t.call(this,e,r);if(Pe.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=it(e)){const r=Pe.findKey(this,e);return!(!r||void 0===this[r]||t&&!at(0,this[r],r,t))}return!1}delete(e,t){const r=this;let o=!1;function n(e){if(e=it(e)){const n=Pe.findKey(r,e);!n||t&&!at(0,r[n],n,t)||(delete r[n],o=!0)}}return Pe.isArray(e)?e.forEach(n):n(e),o}clear(e){const t=Object.keys(this);let r=t.length,o=!1;for(;r--;){const n=t[r];e&&!at(0,this[n],n,e,!0)||(delete this[n],o=!0)}return o}normalize(e){const t=this,r={};return Pe.forEach(this,((o,n)=>{const i=Pe.findKey(r,n);if(i)return t[i]=st(o),void delete t[n];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(n):String(n).trim();s!==n&&delete t[n],t[s]=st(o),r[s]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Pe.forEach(this,((r,o)=>{null!=r&&!1!==r&&(t[o]=e&&Pe.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")}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[nt]=this[nt]={accessors:{}}).accessors,r=this.prototype;function o(e){const o=it(e);t[o]||(!function(e,t){const r=Pe.toCamelCase(" "+t);["get","set","has"].forEach((o=>{Object.defineProperty(e,o+r,{value:function(e,r,n){return this[o].call(this,t,e,r,n)},configurable:!0})}))}(r,e),t[o]=!0)}return Pe.isArray(e)?e.forEach(o):o(e),this}}function ut(e,t){const r=this||rt,o=t||r,n=ct.from(o.headers);let i=o.data;return Pe.forEach(e,(function(e){i=e.call(r,i,n.normalize(),t?t.status:void 0)})),n.normalize(),i}function lt(e){return!(!e||!e.__CANCEL__)}function dt(e,t,r){Fe.call(this,null==e?"canceled":e,Fe.ERR_CANCELED,t,r),this.name="CanceledError"}function pt(e,t,r){const o=r.config.validateStatus;r.status&&o&&!o(r.status)?t(new Fe("Request failed with status code "+r.status,[Fe.ERR_BAD_REQUEST,Fe.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}ct.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Pe.reduceDescriptors(ct.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),Pe.freezeMethods(ct),Pe.inherits(dt,Fe,{__CANCEL__:!0});const ft=(e,t,r=3)=>{let o=0;const n=function(e,t){e=e||10;const r=new Array(e),o=new Array(e);let n,i=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=o[s];n||(n=c),r[i]=a,o[i]=c;let l=s,d=0;for(;l!==i;)d+=r[l++],l%=e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),c-n<t)return;const p=u&&c-u;return p?Math.round(1e3*d/p):void 0}}(50,250);return function(e,t){let r,o,n=0,i=1e3/t;const s=(t,i=Date.now())=>{n=i,r=null,o&&(clearTimeout(o),o=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=i?s(e,t):(r=e,o||(o=setTimeout((()=>{o=null,s(r)}),i-a)))},()=>r&&s(r)]}((r=>{const i=r.loaded,s=r.lengthComputable?r.total:void 0,a=i-o,c=n(a);o=i;e({loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&i<=s?(s-i)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),r)},ht=(e,t)=>{const r=null!=e;return[o=>t[0]({lengthComputable:r,total:e,loaded:o}),t[1]]},gt=e=>(...t)=>Pe.asap((()=>e(...t))),mt=et.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,et.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(et.origin),et.navigator&&/(msie|trident)/i.test(et.navigator.userAgent)):()=>!0,yt=et.hasStandardBrowserEnv?{write(e,t,r,o,n,i){const s=[e+"="+encodeURIComponent(t)];Pe.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),Pe.isString(o)&&s.push("path="+o),Pe.isString(n)&&s.push("domain="+n),!0===i&&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 wt(e,t,r){let o=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(o||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const bt=e=>e instanceof ct?{...e}:e;function It(e,t){t=t||{};const r={};function o(e,t,r,o){return Pe.isPlainObject(e)&&Pe.isPlainObject(t)?Pe.merge.call({caseless:o},e,t):Pe.isPlainObject(t)?Pe.merge({},t):Pe.isArray(t)?t.slice():t}function n(e,t,r,n){return Pe.isUndefined(t)?Pe.isUndefined(e)?void 0:o(void 0,e,0,n):o(e,t,0,n)}function i(e,t){if(!Pe.isUndefined(t))return o(void 0,t)}function s(e,t){return Pe.isUndefined(t)?Pe.isUndefined(e)?void 0:o(void 0,e):o(void 0,t)}function a(r,n,i){return i in t?o(r,n):i in e?o(void 0,r):void 0}const c={url:i,method:i,data:i,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)=>n(bt(e),bt(t),0,!0)};return Pe.forEach(Object.keys(Object.assign({},e,t)),(function(o){const i=c[o]||n,s=i(e[o],t[o],o);Pe.isUndefined(s)&&i!==a||(r[o]=s)})),r}const kt=e=>{const t=It({},e);let r,{data:o,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=ct.from(a),t.url=We(wt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Pe.isFormData(o))if(et.hasStandardBrowserEnv||et.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(et.hasStandardBrowserEnv&&(n&&Pe.isFunction(n)&&(n=n(t)),n||!1!==n&&mt(t.url))){const e=i&&s&&yt.read(s);e&&a.set(i,e)}return t},Tt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const o=kt(e);let n=o.data;const i=ct.from(o.headers).normalize();let s,a,c,u,l,{responseType:d,onUploadProgress:p,onDownloadProgress:f}=o;function h(){u&&u(),l&&l(),o.cancelToken&&o.cancelToken.unsubscribe(s),o.signal&&o.signal.removeEventListener("abort",s)}let g=new XMLHttpRequest;function m(){if(!g)return;const o=ct.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());pt((function(e){t(e),h()}),(function(e){r(e),h()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:o,config:e,request:g}),g=null}g.open(o.method.toUpperCase(),o.url,!0),g.timeout=o.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new Fe("Request aborted",Fe.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new Fe("Network Error",Fe.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const n=o.transitional||Ve;o.timeoutErrorMessage&&(t=o.timeoutErrorMessage),r(new Fe(t,n.clarifyTimeoutError?Fe.ETIMEDOUT:Fe.ECONNABORTED,e,g)),g=null},void 0===n&&i.setContentType(null),"setRequestHeader"in g&&Pe.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),Pe.isUndefined(o.withCredentials)||(g.withCredentials=!!o.withCredentials),d&&"json"!==d&&(g.responseType=o.responseType),f&&([c,l]=ft(f,!0),g.addEventListener("progress",c)),p&&g.upload&&([a,u]=ft(p),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",u)),(o.cancelToken||o.signal)&&(s=t=>{g&&(r(!t||t.type?new dt(null,e,g):t),g.abort(),g=null)},o.cancelToken&&o.cancelToken.subscribe(s),o.signal&&(o.signal.aborted?s():o.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(o.url);y&&-1===et.protocols.indexOf(y)?r(new Fe("Unsupported protocol "+y+":",Fe.ERR_BAD_REQUEST,e)):g.send(n||null)}))},At=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,o=new AbortController;const n=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;o.abort(t instanceof Fe?t:new dt(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,n(new Fe(`timeout ${t} of ms exceeded`,Fe.ETIMEDOUT))}),t);const s=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)})),e=null)};e.forEach((e=>e.addEventListener("abort",n)));const{signal:a}=o;return a.unsubscribe=()=>Pe.asap(s),a}},St=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let o,n=0;for(;n<r;)o=n+t,yield e.slice(n,o),n=o},vt=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()}},xt=(e,t,r,o)=>{const n=async function*(e,t){for await(const r of vt(e))yield*St(r,t)}(e,t);let i,s=0,a=e=>{i||(i=!0,o&&o(e))};return new ReadableStream({async pull(e){try{const{done:t,value:o}=await n.next();if(t)return a(),void e.close();let i=o.byteLength;if(r){let e=s+=i;r(e)}e.enqueue(new Uint8Array(o))}catch(t){throw a(t),t}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},Et="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Ct=Et&&"function"==typeof ReadableStream,Rt=Et&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Nt=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},$t=Ct&&Nt((()=>{let e=!1;const t=new Request(et.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Pt=Ct&&Nt((()=>Pe.isReadableStream(new Response("").body))),Ft={stream:Pt&&(e=>e.body)};var _t;Et&&(_t=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!Ft[e]&&(Ft[e]=Pe.isFunction(_t[e])?t=>t[e]():(t,r)=>{throw new Fe(`Response type '${e}' is not supported`,Fe.ERR_NOT_SUPPORT,r)})})));const Lt=async(e,t)=>{const r=Pe.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Pe.isBlob(e))return e.size;if(Pe.isSpecCompliantForm(e)){const t=new Request(et.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Pe.isArrayBufferView(e)||Pe.isArrayBuffer(e)?e.byteLength:(Pe.isURLSearchParams(e)&&(e+=""),Pe.isString(e)?(await Rt(e)).byteLength:void 0)})(t):r},Dt={http:null,xhr:Tt,fetch:Et&&(async e=>{let{url:t,method:r,data:o,signal:n,cancelToken:i,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:u,headers:l,withCredentials:d="same-origin",fetchOptions:p}=kt(e);u=u?(u+"").toLowerCase():"text";let f,h=At([n,i&&i.toAbortSignal()],s);const g=h&&h.unsubscribe&&(()=>{h.unsubscribe()});let m;try{if(c&&$t&&"get"!==r&&"head"!==r&&0!==(m=await Lt(l,o))){let e,r=new Request(t,{method:"POST",body:o,duplex:"half"});if(Pe.isFormData(o)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=ht(m,ft(gt(c)));o=xt(r.body,65536,e,t)}}Pe.isString(d)||(d=d?"include":"omit");const n="credentials"in Request.prototype;f=new Request(t,{...p,signal:h,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:o,duplex:"half",credentials:n?d:void 0});let i=await fetch(f);const s=Pt&&("stream"===u||"response"===u);if(Pt&&(a||s&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=Pe.toFiniteNumber(i.headers.get("content-length")),[r,o]=a&&ht(t,ft(gt(a),!0))||[];i=new Response(xt(i.body,65536,r,(()=>{o&&o(),g&&g()})),e)}u=u||"text";let y=await Ft[Pe.findKey(Ft,u)||"text"](i,e);return!s&&g&&g(),await new Promise(((t,r)=>{pt(t,r,{data:y,headers:ct.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:f})}))}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/fetch/i.test(y.message))throw Object.assign(new Fe("Network Error",Fe.ERR_NETWORK,e,f),{cause:y.cause||y});throw Fe.from(y,y&&y.code,e,f)}})};Pe.forEach(Dt,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}}));const Ot=e=>`- ${e}`,Ut=e=>Pe.isFunction(e)||null===e||!1===e,Bt=e=>{e=Pe.isArray(e)?e:[e];const{length:t}=e;let r,o;const n={};for(let i=0;i<t;i++){let t;if(r=e[i],o=r,!Ut(r)&&(o=Dt[(t=String(r)).toLowerCase()],void 0===o))throw new Fe(`Unknown adapter '${t}'`);if(o)break;n[t||"#"+i]=o}if(!o){const e=Object.entries(n).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new Fe("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Ot).join("\n"):" "+Ot(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return o};function Mt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dt(null,e)}function qt(e){Mt(e),e.headers=ct.from(e.headers),e.data=ut.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Bt(e.adapter||rt.adapter)(e).then((function(t){return Mt(e),t.data=ut.call(e,e.transformResponse,t),t.headers=ct.from(t.headers),t}),(function(t){return lt(t)||(Mt(e),t&&t.response&&(t.response.data=ut.call(e,e.transformResponse,t.response),t.response.headers=ct.from(t.response.headers))),Promise.reject(t)}))}const Kt="1.8.4",jt={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{jt[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const zt={};jt.transitional=function(e,t,r){function o(e,t){return"[Axios v1.8.4] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,i)=>{if(!1===e)throw new Fe(o(n," has been removed"+(t?" in "+t:"")),Fe.ERR_DEPRECATED);return t&&!zt[n]&&(zt[n]=!0,console.warn(o(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,i)}},jt.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Wt={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Fe("options must be an object",Fe.ERR_BAD_OPTION_VALUE);const o=Object.keys(e);let n=o.length;for(;n-- >0;){const i=o[n],s=t[i];if(s){const t=e[i],r=void 0===t||s(t,i,e);if(!0!==r)throw new Fe("option "+i+" must be "+r,Fe.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new Fe("Unknown option "+i,Fe.ERR_BAD_OPTION)}},validators:jt},Ht=Wt.validators;class Vt{constructor(e){this.defaults=e,this.interceptors={request:new He,response:new He}}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(o){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=It(this.defaults,t);const{transitional:r,paramsSerializer:o,headers:n}=t;void 0!==r&&Wt.assertOptions(r,{silentJSONParsing:Ht.transitional(Ht.boolean),forcedJSONParsing:Ht.transitional(Ht.boolean),clarifyTimeoutError:Ht.transitional(Ht.boolean)},!1),null!=o&&(Pe.isFunction(o)?t.paramsSerializer={serialize:o}:Wt.assertOptions(o,{encode:Ht.function,serialize:Ht.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Wt.assertOptions(t,{baseUrl:Ht.spelling("baseURL"),withXsrfToken:Ht.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=n&&Pe.merge(n.common,n[t.method]);n&&Pe.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete n[e]})),t.headers=ct.concat(i,n);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 u;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,d=0;if(!a){const e=[qt.bind(this),void 0];for(e.unshift.apply(e,s),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);d<l;)u=u.then(e[d++],e[d++]);return u}l=s.length;let p=t;for(d=0;d<l;){const e=s[d++],t=s[d++];try{p=e(p)}catch(f){t.call(this,f);break}}try{u=qt.call(this,p)}catch(f){return Promise.reject(f)}for(d=0,l=c.length;d<l;)u=u.then(c[d++],c[d++]);return u}getUri(e){return We(wt((e=It(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Pe.forEach(["delete","get","head","options"],(function(e){Vt.prototype[e]=function(t,r){return this.request(It(r||{},{method:e,url:t,data:(r||{}).data}))}})),Pe.forEach(["post","put","patch"],(function(e){function t(t){return function(r,o,n){return this.request(It(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Vt.prototype[e]=t(),Vt.prototype[e+"Form"]=t(!0)}));class Gt{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 o=new Promise((e=>{r.subscribe(e),t=e})).then(e);return o.cancel=function(){r.unsubscribe(t)},o},e((function(e,o,n){r.reason||(r.reason=new dt(e,o,n),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 e;return{token:new Gt((function(t){e=t})),cancel:e}}}const Jt={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(Jt).forEach((([e,t])=>{Jt[t]=e}));const Xt=function e(t){const r=new Vt(t),o=V(Vt.prototype.request,r);return Pe.extend(o,Vt.prototype,r,{allOwnKeys:!0}),Pe.extend(o,r,null,{allOwnKeys:!0}),o.create=function(r){return e(It(t,r))},o}(rt);Xt.Axios=Vt,Xt.CanceledError=dt,Xt.CancelToken=Gt,Xt.isCancel=lt,Xt.VERSION=Kt,Xt.toFormData=Me,Xt.AxiosError=Fe,Xt.Cancel=Xt.CanceledError,Xt.all=function(e){return Promise.all(e)},Xt.spread=function(e){return function(t){return e.apply(null,t)}},Xt.isAxiosError=function(e){return Pe.isObject(e)&&!0===e.isAxiosError},Xt.mergeConfig=It,Xt.AxiosHeaders=ct,Xt.formToJSON=e=>tt(Pe.isHTMLForm(e)?new FormData(e):e),Xt.getAdapter=Bt,Xt.HttpStatusCode=Jt,Xt.default=Xt;const Yt=class e{constructor(){m(this,"isProduction"),this.isProduction="production"===H.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)}};m(Yt,"instance");let Qt=Yt;class Zt extends Error{constructor(e){super(e),this.name="ValidationError"}}class er{constructor(e){m(this,"accountId"),m(this,"privateKey"),m(this,"baseUrl"),m(this,"network"),this.accountId=e.accountId,this.privateKey=r.PrivateKey.fromStringED25519(e.privateKey),this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const o=await Xt.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=o.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=o.data.message,i=await this.signMessage(n),s=await Xt.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:i,data:n,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 C.from(r).toString("hex")}}class tr{constructor(e){m(this,"accountId"),m(this,"signer"),m(this,"baseUrl"),m(this,"network"),m(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 o=await Xt.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=o.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=o.data.message,i=await this.signMessage(JSON.stringify(n)),s=await Xt.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:i,data:n,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 C.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 rr(e){return new DataView(e.buffer,e.byteOffset)}const or={len:1,get:(e,t)=>rr(e).getUint8(t),put:(e,t,r)=>(rr(e).setUint8(t,r),t+1)},nr={len:2,get:(e,t)=>rr(e).getUint16(t,!0),put:(e,t,r)=>(rr(e).setUint16(t,r,!0),t+2)},ir={len:2,get:(e,t)=>rr(e).getUint16(t),put:(e,t,r)=>(rr(e).setUint16(t,r),t+2)},sr={len:4,get:(e,t)=>rr(e).getUint32(t,!0),put:(e,t,r)=>(rr(e).setUint32(t,r,!0),t+4)},ar={len:4,get:(e,t)=>rr(e).getUint32(t),put:(e,t,r)=>(rr(e).setUint32(t,r),t+4)},cr={len:4,get:(e,t)=>rr(e).getInt32(t),put:(e,t,r)=>(rr(e).setInt32(t,r),t+4)},ur={len:8,get:(e,t)=>rr(e).getBigUint64(t,!0),put:(e,t,r)=>(rr(e).setBigUint64(t,r,!0),t+8)};class lr{constructor(e,t){this.len=e,this.encoding=t}get(e,t){return C.from(e).toString(this.encoding,t,t+this.len)}}class dr extends Error{constructor(){super("End-Of-Stream")}}class pr{constructor(){this.resolve=()=>null,this.reject=()=>null,this.promise=new Promise(((e,t)=>{this.reject=t,this.resolve=e}))}}class fr{constructor(){this.maxStreamReadSize=1048576,this.endOfStream=!1,this.peekQueue=[]}async peek(e,t,r){const o=await this.read(e,t,r);return this.peekQueue.push(e.subarray(t,t+o)),o}async read(e,t,r){if(0===r)return 0;let o=this.readFromPeekBuffer(e,t,r);if(o+=await this.readRemainderFromStream(e,t+o,r-o),0===o)throw new dr;return o}readFromPeekBuffer(e,t,r){let o=r,n=0;for(;this.peekQueue.length>0&&o>0;){const r=this.peekQueue.pop();if(!r)throw new Error("peekData should be defined");const i=Math.min(r.length,o);e.set(r.subarray(0,i),t+n),n+=i,o-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t,r){let o=r,n=0;for(;o>0&&!this.endOfStream;){const r=Math.min(o,this.maxStreamReadSize),i=await this.readFromStream(e,t+n,r);if(0===i)break;n+=i,o-=i}return n}}class hr extends fr{constructor(e){if(super(),this.s=e,this.deferred=null,!e.read||!e.once)throw new Error("Expected an instance of stream.Readable");this.s.once("end",(()=>this.reject(new dr))),this.s.once("error",(e=>this.reject(e))),this.s.once("close",(()=>this.reject(new Error("Stream closed"))))}async readFromStream(e,t,r){if(this.endOfStream)return 0;const o=this.s.read(r);if(o)return e.set(o,t),o.length;const n={buffer:e,offset:t,length:r,deferred:new pr};return this.deferred=n.deferred,this.s.once("readable",(()=>{this.readDeferred(n)})),n.deferred.promise}readDeferred(e){const t=this.s.read(e.length);t?(e.buffer.set(t,e.offset),e.deferred.resolve(t.length),this.deferred=null):this.s.once("readable",(()=>{this.readDeferred(e)}))}reject(e){this.endOfStream=!0,this.deferred&&(this.deferred.reject(e),this.deferred=null)}async abort(){this.reject(new Error("abort"))}async close(){return this.abort()}}class gr{constructor(e){this.position=0,this.numBuffer=new Uint8Array(8),this.fileInfo=e||{}}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new dr;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 dr;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new dr;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new dr;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(){}normalizeOptions(e,t){if(t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return t?{mayBeLess:!0===t.mayBeLess,offset:t.offset?t.offset:0,length:t.length?t.length:e.length-(t.offset?t.offset:0),position:t.position?t.position:this.position}:{mayBeLess:!1,offset:0,length:e.length,position:this.position}}}class mr extends gr{constructor(e,t){super(t),this.streamReader=e}async getFileInfo(){return this.fileInfo}async readBuffer(e,t){const r=this.normalizeOptions(e,t),o=r.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const n=await this.streamReader.read(e,r.offset,r.length);if(this.position+=n,(!t||!t.mayBeLess)&&n<r.length)throw new dr;return n}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let o=0;if(r.position){const t=r.position-this.position;if(t>0){const n=new Uint8Array(r.length+t);return o=await this.peekBuffer(n,{mayBeLess:r.mayBeLess}),e.set(n.subarray(t),r.offset),o-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{o=await this.streamReader.peek(e,r.offset,r.length)}catch(n){if(t&&t.mayBeLess&&n instanceof dr)return 0;throw n}if(!r.mayBeLess&&o<r.length)throw new dr}return o}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let o=0;for(;o<e;){const n=e-o,i=await this.readBuffer(r,{length:Math.min(t,n)});if(i<0)return i;o+=i}return o}}class yr extends gr{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo.size=this.fileInfo.size?this.fileInfo.size:e.length}async readBuffer(e,t){if(t&&t.position){if(t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.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),o=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&o<r.length)throw new dr;return e.set(this.uint8Array.subarray(r.position,r.position+o),r.offset),o}async close(){}}const wr={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},br=4100;function Ir(e,t,r){r={offset:0,...r};for(const[o,n]of t.entries())if(r.mask){if(n!==(r.mask[o]&e[o+r.offset]))return!1}else if(n!==e[o+r.offset])return!1;return!0}class kr{constructor(e){this.detectors=null==e?void 0:e.customDetectors,this.fromTokenizer=this.fromTokenizer.bind(this),this.fromBuffer=this.fromBuffer.bind(this),this.parse=this.parse.bind(this)}async fromTokenizer(e){const t=e.position;for(const r of this.detectors||[]){const o=await r(e);if(o)return o;if(t!==e.position)return}return this.parse(e)}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r;if((null==t?void 0:t.length)>1)return this.fromTokenizer(new yr(t,r))}async fromBlob(e){const t=await e.arrayBuffer();return this.fromBuffer(new Uint8Array(t))}async fromStream(e){const t=await function(e,t){return t=t||{},new mr(new hr(e),t)}(e);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t={}){const{default:r}=await Promise.resolve().then((()=>require("./index-CHar8dVv-BQYxSvOg.cjs"))).then((e=>e.i)),{sampleSize:o=br}=t;return new Promise(((t,n)=>{e.on("error",n),e.once("readable",(()=>{(async()=>{try{const s=new r.PassThrough,a=r.pipeline?r.pipeline(e,s,(()=>{})):e.pipe(s),c=e.read(o)??e.read()??C.alloc(0);try{s.fileType=await this.fromBuffer(c)}catch(i){i instanceof dr?s.fileType=void 0:n(i)}t(a)}catch(i){n(i)}})()}))}))}check(e,t){return Ir(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map((e=>e.charCodeAt(0)))),t);var r}async parse(e){if(this.buffer=C.alloc(br),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.parse(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 r=await e.readToken(wr);return e.position+r>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(r),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("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};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])){try{for(;e.position+30<e.fileInfo.size;){await e.readBuffer(this.buffer,{length:30});const o={compressedSize:this.buffer.readUInt32LE(18),uncompressedSize:this.buffer.readUInt32LE(22),filenameLength:this.buffer.readUInt16LE(26),extraFieldLength:this.buffer.readUInt16LE(28)};if(o.filename=await e.readToken(new lr(o.filenameLength,"utf-8")),await e.ignore(o.extraFieldLength),"META-INF/mozilla.rsa"===o.filename)return{ext:"xpi",mime:"application/x-xpinstall"};if(o.filename.endsWith(".rels")||o.filename.endsWith(".xml")){switch(o.filename.split("/")[0]){case"_rels":default:break;case"word":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"ppt":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"xl":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}}}if(o.filename.startsWith("xl/"))return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(o.filename.startsWith("3D/")&&o.filename.endsWith(".model"))return{ext:"3mf",mime:"model/3mf"};if("mimetype"===o.filename&&o.compressedSize===o.uncompressedSize){let n=await e.readToken(new lr(o.compressedSize,"utf-8"));switch(n=n.trim(),n){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"}}}if(0===o.compressedSize){let i=-1;for(;i<0&&e.position<e.fileInfo.size;)await e.peekBuffer(this.buffer,{mayBeLess:!0}),i=this.buffer.indexOf("504B0304",0,"hex"),await e.ignore(i>=0?i:this.buffer.length)}else await e.ignore(o.compressedSize)}}catch(t){if(!(t instanceof dr))throw t}return{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const s=C.alloc(8);return await e.readBuffer(s),Ir(s,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/opus"}:Ir(s,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Ir(s,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Ir(s,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Ir(s,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Ir(s,[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("ftyp",{offset:4})&&96&this.buffer[8]){const a=this.buffer.toString("binary",8,12).replace("\0"," ").trim();switch(a){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 a.startsWith("3g")?a.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}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/x-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")){try{await e.ignore(1350);const c=10485760,u=C.alloc(Math.min(c,e.fileInfo.size));if(await e.readBuffer(u,{mayBeLess:!0}),u.includes(C.from("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}catch(t){if(!(t instanceof dr))throw t}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 l=await this.readTiffHeader(!1);if(l)return l}if(this.check([77,77])){const d=await this.readTiffHeader(!0);if(d)return d}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function p(){const t=await e.peekNumber(or);let r=128,o=0;for(;!(t&r)&&0!==r;)++o,r>>=1;const n=C.alloc(o+1);return await e.readBuffer(n),n}async function f(){const e=await p(),t=await p();t[0]^=128>>t.length-1;const r=Math.min(6,t.length);return{id:e.readUIntBE(0,e.length),len:t.readUIntBE(t.length-r,r)}}async function h(t){for(;t>0;){const r=await f();if(17026===r.id){return(await e.readToken(new lr(r.len,"utf-8"))).replace(/\00.*$/g,"")}await e.ignore(r.len),--t}}const g=await f();switch(await h(g.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.check([82,73,70,70])){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/vnd.wave"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}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"))return{ext:"parquet",mime:"application/x-parquet"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};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.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 m=this.buffer.toString("binary",2,6);if(m.match("^d*")&&m>=1e3&&m<=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 lr(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("**ACE",{offset:7})&&(await e.peekBuffer(this.buffer,{length:14,mayBeLess:!0}),this.checkString("**",{offset:12})))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.check([137,80,78,71,13,10,26,10])){async function y(){return{length:await e.readToken(cr),type:await e.readToken(new lr(4,"binary"))}}await e.ignore(8);do{const w=await y();if(w.length<0)return;switch(w.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(w.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/x-apache-arrow"};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.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 b(){const t=C.alloc(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(ur))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const I=await b();let k=I.size-24;if(Ir(I.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const T=C.alloc(16);if(k-=await e.readBuffer(T),Ir(T,[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(Ir(T,[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(k)}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 lr(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([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(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("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 A=this.buffer.readUInt32LE(12);if(A>12&&this.buffer.length>=A+16)try{const S=this.buffer.slice(16,A+16).toString();if(JSON.parse(S).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(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})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),function(e,t=0){const r=Number.parseInt(e.toString("utf8",148,154).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let o=256;for(let n=t;n<t+148;n++)o+=e[n];for(let n=t+156;n<t+512;n++)o+=e[n];return r===o}(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return 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;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}async readTiffTag(e){const t=await this.tokenizer.readToken(e?ir:nr);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?ir:nr);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?ir:nr).get(this.buffer,2),r=(e?ar:sr).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&&(this.check([28,0,254,0],{offset:8})||this.check([31,0,11,0],{offset:8})))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"}}}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","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","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx"]),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.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/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/vnd.wave","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","audio/opus","video/ogg","audio/ogg","application/ogg","audio/x-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","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","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/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx"]);const Tr=class e{constructor(e){if(m(this,"client"),m(this,"config"),m(this,"logger",Qt.getInstance()),this.config=e,!e.apiKey)throw new Zt("API key is required");if(!e.network)throw new Zt("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Xt.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=Qt.getInstance()}async getFileMetadata(e){try{const t=await Xt.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 Zt("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new Zt("File must have an extension");const o=e.VALID_MIME_TYPES[r];if(!o)throw new Zt(`Unsupported file type: ${r}`);return o}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Zt("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Zt(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Zt("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Zt("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 Zt("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new Zt(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const o=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(o))throw new Zt("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 Zt("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=E.from(t,"base64"),o=await async function(e){return(new kr).fromBuffer(e)}(r);return(null==o?void 0:o.mime)||"application/octet-stream"}catch(t){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,o;try{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const o=await this.getFileMetadata(t.file.url);if(r=o.mimeType||r,o.size>e.MAX_URL_FILE_SIZE)throw new Zt(`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 Zt("JSON file must be of type application/json")}const o={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 n;return n="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...o,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...o,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),n.data}catch(n){if(n instanceof Zt)throw n;if(Xt.isAxiosError(n))throw new Error((null==(o=null==(r=n.response)?void 0:r.data)?void 0:o.message)||"Failed to start inscription");throw n}}async executeTransaction(e,t){try{const o="mainnet"===t.network?r.Client.forMainnet():r.Client.forTestnet(),n=r.PrivateKey.fromString(t.privateKey);o.setOperator(t.accountId,n);const i=r.TransferTransaction.fromBytes(E.from(e,"base64")),s=await i.sign(n),a=await s.execute(o),c=(await a.getReceipt(o)).status.toString();if("SUCCESS"!==c)throw new Error(`Transaction failed with status: ${c}`);return a.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const o=r.TransferTransaction.fromBytes(E.from(e,"base64")),n=await o.executeWithSigner(t),i=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==i)throw new Error(`Transaction failed with status: ${i}`);return n.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async inscribeAndExecute(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 o=await this.executeTransaction(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:o}}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 o=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:o}}async retryWithBackoff(e,t=3,r=1e3){for(let n=0;n<t;n++)try{return await e()}catch(o){if(n===t-1)throw o;const e=r*Math.pow(2,n);await new Promise((t=>setTimeout(t,e))),this.logger.debug(`Retry attempt ${n+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new Zt("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 er(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new tr({...t,logger:Qt.getInstance()}):new er(t),{apiKey:o}=await r.authenticate();return new e({apiKey:o,network:t.network||"mainnet"})}async waitForInscription(e,t=30,r=4e3,o=!1,n){var i;let s=0,a=0;const c=(r,o,i,c)=>{if(n)try{a=Math.max(a,i),n({stage:r,message:o,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(u){this.logger.warn(`Error in progress callback: ${u}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const n=await this.retrieveInscription(e);if(n.error)throw c("verifying",`Error: ${n.error}`,100,{error:n.error}),new Error(n.error);let a=5;void 0!==n.messages&&void 0!==n.maxMessages&&n.maxMessages>0?(a=Math.min(95,5+n.messages/n.maxMessages*90),n.completed&&(a=100)):"processing"===n.status?a=10:n.completed&&(a=100),c(n.completed?"completed":"confirming",n.completed?"Inscription completed successfully":`Processing inscription (${n.status})`,a,{status:n.status,messagesProcessed:n.messages,maxMessages:n.maxMessages,messageCount:n.messages,completed:n.completed,confirmedMessages:n.confirmedMessages,result:n});const u="hashinal"===n.mode,l="6"===(null==(i=n.fileStandard)?void 0:i.toString());if(u&&n.topic_id&&n.jsonTopicId&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;if(!u&&!l&&n.topic_id&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;if(l&&n.topic_id&&n.jsonTopicId&&n.registryTopicId&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;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 Zt("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(o){if(this.logger.error("Failed to fetch holder inscriptions:",o),Xt.isAxiosError(o))throw new Error((null==(r=null==(t=o.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw o}}};m(Tr,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),m(Tr,"MAX_BASE64_SIZE",2097152),m(Tr,"MAX_URL_FILE_SIZE",104857600),m(Tr,"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"});let Ar=Tr;class Sr{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 Sr.instance?(e.callback&&Sr.instance.setCallback(e.callback),e.module&&Sr.instance.setModule(e.module),e.logger&&Sr.instance.setLogger(e.logger),void 0!==e.minPercent&&Sr.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&Sr.instance.setMaxPercent(e.maxPercent)):Sr.instance=new Sr(e),Sr.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 Sr({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback((t=>{const o=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let n=t.message;r&&!n.startsWith(r)&&(n=`${r}: ${n}`),this.report({stage:t.stage,message:n,progressPercent:o,details:t.details})})),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),o=this.scalePercent(r,0,100),n=Date.now();if(o===this.lastReportedPercent&&n-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=o,this.lastReportedTime=n;const i={...e,progressPercent:o};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${o.toFixed(1)}%)`,e.details),this.callback)try{this.callback(i)}catch(s){this.logger.warn(`Error in progress callback: ${s}`)}}scalePercent(e,t,r){const o=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*o}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})}}async function vr(e,t,r,o){const n=p.getInstance({module:"Inscriber",...r.logging});n.info("Starting inscription process",{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{let i;"hashinal"===r.mode&&r.metadata&&Er(r.metadata,n),o?(n.debug("Using existing InscriptionSDK instance"),i=o):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),i=new Ar({apiKey:r.apiKey,network:t.network||"mainnet"})):(n.debug("Initializing InscriptionSDK with server auth"),i=await Ar.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"}));const s={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",chunkSize:r.chunkSize};let a;switch(e.type){case"url":a={...s,file:{type:"url",url:e.url}};break;case"file":a={...s,file:{type:"path",path:e.path}};break;case"buffer":a={...s,file:{type:"base64",base64:globalThis.Buffer.from(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)),n.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const c=await i.inscribeAndExecute(a,t);if(n.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:c.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:c.jobId,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Cr(i,c.jobId,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:c.jobId}),{confirmed:!0,result:c,inscription:e,sdk:i}}return{confirmed:!1,result:c,sdk:i}}catch(i){throw n.error("Error during inscription process",i),i}}async function xr(e,t,r,o){const n=p.getInstance({module:"Inscriber",...r.logging});n.info("Starting inscription process with signer",{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{"hashinal"===r.mode&&r.metadata&&Er(r.metadata,n);const i=t.getAccountId().toString();let s;n.debug("Using account ID from signer",{accountId:i}),o?(n.debug("Using existing InscriptionSDK instance"),s=o):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),s=new Ar({apiKey:r.apiKey,network:r.network||"mainnet"})):(n.debug("Initializing InscriptionSDK with client auth"),s=await Ar.createWithAuth({type:"client",accountId:i,signer:t,network:r.network||"mainnet"}));const a={holderId:i,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":c={...a,file:{type:"path",path:e.path}};break;case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||i,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Preparing to inscribe content with signer",{type:e.type,mode:r.mode||"file",holderId:i});const u=await s.inscribe({...c,holderId:i},t);if(n.info("Inscription started",{type:e.type,mode:r.mode||"file",transactionId:u.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:u.jobId,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Cr(s,u.jobId,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:u.jobId}),{confirmed:!0,result:u,inscription:e,sdk:s}}return{confirmed:!1,result:u,sdk:s}}catch(i){throw n.error("Error during inscription process",i),i}}function Er(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 Cr(e,t,r=30,o=4e3,n){const i=p.getInstance({module:"Inscriber"}),s=new Sr({module:"Inscriber",logger:i,callback:n});try{i.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:o}),s.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:r,intervalMs:o});try{const n=e.waitForInscription.bind(e),i=e=>{const t=e.stage||"confirming",r=e.message||"Processing inscription",o=e.progressPercent||50;s.report({stage:t,message:r,progressPercent:o,details:{}})};return await n(t,r,o,!0,i)}catch(a){return console.log(a),i.debug("Falling back to standard waitForInscription method",{error:a}),s.verifying("Verifying inscription status",50,{error:a}),await e.waitForInscription(t,r,o,!0)}}catch(c){throw i.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:o,error:c}),s.failed("Inscription confirmation failed",{transactionId:t,error:c}),c}}class Rr{constructor(e,t,r){this.maxRetries=3,this.initialDelayMs=1e3,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.info(`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 r.PublicKey.fromString(t.key.key)}catch(o){const e=`Error fetching public key from Mirror Node: ${o.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.info(`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=r.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const o=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(o?.current_rate?.cent_equivalent)/Number(o?.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){this.logger.trace(`Querying messages for topic ${e}`);let t=`/api/v1/topics/${e}/messages`;const r=[];for(;t;)try{const e=await this._requestWithRetry(t);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,n;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(o){const e=`Error decoding message: ${o}`;this.logger.error(e);continue}try{n=JSON.parse(e)}catch(o){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}n.sequence_number=t.sequence_number,r.push({...n,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(o){const e=`Error processing message: ${o.message}`;this.logger.error(e)}t=e.links?.next||""}catch(n){const r=`Error querying topic messages for topic ${e} (endpoint: ${t}) after retries: ${n.message}`;throw this.logger.error(r),new Error(r)}return r}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=i.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 n of r)if(n)if(n.ed25519){if(this.compareEd25519Key(n.ed25519,t))return!0}else if(n.keyList||n.thresholdKey)try{const e=i.proto.Key.encode({...n.keyList?{keyList:n.keyList}:{},...n.thresholdKey?{thresholdKey:n.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(o){const e=`Error in nested key: ${o.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return r.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(o){const e=`Error comparing Ed25519 key: ${o.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,o=this.initialDelayMs;const i=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 n.get(i,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 ${i} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${i}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${i}: ${a.message}. Retrying in ${o}ms...`),await new Promise((e=>setTimeout(e,o))),o=Math.min(o*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${i} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,o=this.initialDelayMs;const n={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach(((e,t)=>{n[t]=e})):Array.isArray(t.headers)?t.headers.forEach((([e,t])=>{n[e]=t})):Object.assign(n,t.headers)),this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`,n["X-API-Key"]=this.apiKey);const i={...t,headers:n};for(;r<this.maxRetries;)try{const t=await fetch(e,i);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 ${o}ms...`),await new Promise((e=>setTimeout(e,o))),o=Math.min(o*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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.sequenceNumber&&o.append("sequencenumber",t.sequenceNumber),t?.startTime&&o.append("timestamp",`gte:${t.startTime}`),t?.endTime&&o.append("timestamp",`lt:${t.endTime}`),t?.order&&o.append("order",t.order);const n=o.toString();n&&(r+=`?${n}`);const i=[];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 o={...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};i.push(o)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&i.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return i}catch(u){const t=u;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=[],o=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.tokens&&(r=r.concat(e.tokens)),o=e.links?.next||"",!o||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(n){return this.logger.error(`Error fetching tokens for account ${e}: ${n.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 o=[],n=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(n+=`&token.id=${t}`);try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);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}}));o=o.concat(t)}if(n=e.links?.next||"",!n)break}return o}catch(i){return this.logger.error(`Error fetching NFTs for account ${e}: ${i.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const o=await this.getAccountNfts(e,t);if(o){return o.find((e=>e.token_id===t&&e.serial_number===r))||null}return null}catch(o){return this.logger.error(`Error validating NFT ownership: ${o.message}`),null}}async readSmartContractQuery(e,t,o,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const i=e.startsWith("0x")?e:`0x${r.AccountId.fromString(e).toSolidityAddress()}`,s=o.startsWith("0x")?o:`0x${r.AccountId.fromString(o).toSolidityAddress()}`,a={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:s,to:i,gas:n?.gas,gasPrice:n?.gasPrice,value:n?.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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.receiverId&&o.append("receiver.id",t.receiverId),t?.serialNumber&&o.append("serialnumber",t.serialNumber),t?.tokenId&&o.append("token.id",t.tokenId);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(i){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${i.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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.senderId&&o.append("sender.id",t.senderId),t?.serialNumber&&o.append("serialnumber",t.serialNumber),t?.tokenId&&o.append("token.id",t.tokenId);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(i){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${i.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(n){return this.logger.error(`Error fetching blocks: ${n.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(n){return this.logger.error(`Error fetching contracts: ${n.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(o){return this.logger.error(`Error fetching contract ${e}: ${o.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).results||[]}catch(n){return this.logger.error(`Error fetching contract results: ${n.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(o){return this.logger.error(`Error fetching contract result for ${e}: ${o.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const o=new URLSearchParams;t?.blockHash&&o.append("block.hash",t.blockHash),t?.blockNumber&&o.append("block.number",t.blockNumber),t?.from&&o.append("from",t.from),void 0!==t?.internal&&o.append("internal",t.internal.toString()),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.timestamp&&o.append("timestamp",t.timestamp),t?.transactionIndex&&o.append("transaction.index",t.transactionIndex.toString());const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).results||[]}catch(i){return this.logger.error(`Error fetching contract results for ${e}: ${i.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.slot&&o.append("slot",t.slot),t?.timestamp&&o.append("timestamp",t.timestamp);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).state||[]}catch(i){return this.logger.error(`Error fetching contract state for ${e}: ${i.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const o=new URLSearchParams;t?.index&&o.append("index",t.index),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(i){return this.logger.error(`Error fetching contract actions for ${e}: ${i.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs: ${n.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const o=new URLSearchParams;t?.index&&o.append("index",t.index),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.timestamp&&o.append("timestamp",t.timestamp),t?.topic0&&o.append("topic0",t.topic0),t?.topic1&&o.append("topic1",t.topic1),t?.topic2&&o.append("topic2",t.topic2),t?.topic3&&o.append("topic3",t.topic3);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(i){return this.logger.error(`Error fetching contract logs for ${e}: ${i.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(o){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${o.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const o=new URLSearchParams;t?.accountId&&o.append("account.id",t.accountId),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.serialNumber&&o.append("serialnumber",t.serialNumber);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(i){return this.logger.error(`Error fetching NFTs for token ${e}: ${i.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 o=new URLSearchParams;void 0!==t?.stack&&o.append("stack",t.stack.toString()),void 0!==t?.memory&&o.append("memory",t.memory.toString()),void 0!==t?.storage&&o.append("storage",t.storage.toString());const n=o.toString();n&&(r+=`?${n}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching opcode traces for ${e}: ${i.message}`),null}}}async function Nr(e,t,r){const o=new Rr(t,r),n=[];for(const s of e)try{const e=await o.getPublicKey(s);n.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${s}: ${i}`)}return n}class $r{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)}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(r){const e=`Error resolving HRL for content and type: ${r.message}`;throw this.logger.error(e),new Error(e)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:o,topicId:i}=r;this.logger.debug(`Resolving HRL reference: standard=${o}, topicId=${i}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${i}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await n.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await n.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:i,isBinary:!0}}if("application/json"===r){const t=await n.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${i}`);return{content:t.data,contentType:r,topicId:i,isBinary:!1}}const o=await n.get(e);if(!o.data)throw new Error(`Failed to fetch content from topic: ${i}`);let s;return s="object"==typeof o.data?o.data.content||o.data.text||JSON.stringify(o.data):o.data,{content:s,contentType:r,topicId:i,isBinary:!1}}catch(s){const e=`Error resolving HRL reference: ${s.message}`;throw this.logger.error(e),new Error(e)}}}function Pr(e){if(e){if(e.contractID)return`ContractID: ${new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${s.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${s.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map((e=>Pr(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=>Pr(e))).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new r.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"}}class Fr{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 r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=r.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=r.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=r.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=i.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=i.proto.TokenSupplyType[e.supplyType]),t.adminKey=Pr(e.adminKey),t.kycKey=Pr(e.kycKey),t.freezeKey=Pr(e.freezeKey),t.wipeKey=Pr(e.wipeKey),t.supplyKey=Pr(e.supplyKey),t.feeScheduleKey=Pr(e.feeScheduleKey),t.pauseKey=Pr(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map((e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.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:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.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:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let o;return e.royaltyFee.fallbackFee&&(o={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.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:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:o}}}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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map((e=>s.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map((e=>r.Long.fromValue(e).toNumber()))),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.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 r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=Pr(e.adminKey),t.kycKey=Pr(e.kycKey),t.freezeKey=Pr(e.freezeKey),t.wipeKey=Pr(e.wipeKey),t.supplyKey=Pr(e.supplyKey),t.feeScheduleKey=Pr(e.feeScheduleKey),t.pauseKey=Pr(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${r.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new r.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 r.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:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.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:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let o;return e.royaltyFee.fallbackFee&&(o={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.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:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:o}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.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 r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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=>r.Long.fromValue(e).toString()))),e.amount&&(t.amount=r.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.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 r.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 r.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 r.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 r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString()))),t}}class _r{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=Pr(e.adminKey),t.submitKey=Pr(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.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=s.Buffer.from(e.message),o=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o)||o.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=o,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,o=e.chunkInfo.initialTransactionID.transactionValidStart;r&&o&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${o.seconds??0}.${o.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=Pr(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=Pr(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.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}}class Lr{static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Pr({keyList:e.keys})),e.contents&&(t.contents=s.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=s.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=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Pr({keyList:e.keys})),e.contents&&(t.contents=s.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}}class Dr{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map((e=>{const t=new r.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),o=r.Hbar.fromTinybars(r.Long.fromValue(e.amount));return{accountId:t.toString(),amount:o.toString(r.HbarUnit.Hbar),isDecimal:!0}}))),e.tokenTransfers)for(const o of e.tokenTransfers){const e=new r.TokenId(o.token.shardNum??0,o.token.realmNum??0,o.token.tokenNum??0);if(o.transfers)for(const n of o.transfers){const o=new r.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),i=r.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:o.toString(),amount:i})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new r.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new r.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=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.key&&(t.key=Pr(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.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 r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.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 r.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=Pr(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${r.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=r.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 r.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=r.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 r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Hbar.fromTinybars(r.Long.fromValue(e.amount)).toString(r.HbarUnit.Hbar)})))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map((e=>({tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.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 r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new r.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=>r.Long.fromValue(e).toString()))),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new r.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 r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map((e=>r.Long.fromValue(e).toString())):[]})))),t}}class Or{static parseContractCall(e){if(!e)return;const t=r.Hbar.fromTinybars(r.Long.fromValue(e.amount??0)),o={contractId:new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:r.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(r.HbarUnit.Hbar))};return e.functionParameters&&(o.functionParameters=s.Buffer.from(e.functionParameters).toString("hex"),o.functionParameters.length>=8&&(o.functionName=o.functionParameters.substring(0,8))),o}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.gas&&(t.gas=r.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=Pr(e.adminKey)),e.constructorParameters&&(t.constructorParameters=s.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.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 r.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=s.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=Pr(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&r.hasOwnProperty("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 r.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&&r.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=r.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 r.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 r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new r.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}}class Ur{static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}}function Br(e){let t="ed25519";e.startsWith("0x")?t="ecdsa":e.startsWith("302e020100300506032b6570")?t="ed25519":e.startsWith("3030020100300706052b8104000a")?t="ecdsa":96===e.length?t="ed25519":88===e.length&&(t="ecdsa");try{return{detectedType:t,privateKey:"ecdsa"===t?r.PrivateKey.fromStringECDSA(e):r.PrivateKey.fromStringED25519(e)}}catch(o){const i="ecdsa"===t?"ed25519":"ecdsa";try{return{detectedType:i,privateKey:"ecdsa"===i?r.PrivateKey.fromStringECDSA(e):r.PrivateKey.fromStringED25519(e)}}catch(n){throw new Error(`Failed to parse private key as either ED25519 or ECDSA: ${o}`)}}}var Mr=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(Mr||{}),qr=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(qr||{}),Kr=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(Kr||{}),jr=(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))(jr||{}),zr=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(zr||{});const Wr={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},Hr=c.z.object({platform:c.z.string().min(1),handle:c.z.string().min(1)}),Vr=c.z.object({type:c.z.nativeEnum(qr),capabilities:c.z.array(c.z.nativeEnum(jr)).min(1),model:c.z.string().min(1),creator:c.z.string().optional()}),Gr=c.z.object({version:c.z.string().min(1),type:c.z.nativeEnum(Mr),display_name:c.z.string().min(1),alias:c.z.string().optional(),bio:c.z.string().optional(),socials:c.z.array(Hr).optional(),profileImage:c.z.string().optional(),properties:c.z.record(c.z.any()).optional(),inboundTopicId:c.z.string().optional(),outboundTopicId:c.z.string().optional()}),Jr=Gr.extend({type:c.z.literal(Mr.PERSONAL),language:c.z.string().optional(),timezone:c.z.string().optional()}),Xr=Gr.extend({type:c.z.literal(Mr.AI_AGENT),aiAgent:Vr}),Yr=c.z.union([Jr,Xr]);class Qr{constructor(e){if(this.client="mainnet"===e.network?r.Client.forMainnet():r.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 Rr(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=Br(this.auth.privateKey);this.keyType=e.detectedType,this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":(t&&t.includes("ED25519"),this.keyType="ed25519"),this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}createPersonalProfile(e,t){return{version:"1.0",type:Mr.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}}createAIAgentProfile(e,t,r,o,n){const i=this.validateProfile({version:"1.0",type:Mr.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:o,creator:n?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:Mr.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:o,creator:n?.creator}}}validateProfile(e){const t=Yr.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),o=await t.execute(this.client),n=await o.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,o=await e.freezeWithSigner(t),n=await o.executeWithSigner(t),i=await n.getReceiptWithSigner(t);return i.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${i.status.toString()}: ${r.Status.Success.toString()}`}:{success:!0,result:i}}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 Sr({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const i=d.lookup(t)||"application/octet-stream",s=r?.waitForConfirmation??!0;let a;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),a=await xr({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:s,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),a=await vr({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:s,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})}})}return a.confirmed?(n.completed("Image inscription completed",{topic_id:a.inscription.topic_id}),{imageTopicId:a.inscription.topic_id||"",transactionId:a.result.jobId,success:!0}):(n.verifying("Waiting for inscription confirmation",50,{jobId:a.result.jobId}),{imageTopicId:"",transactionId:a.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new Sr({module:"HCS11-Profile",logger:this.logger,callback:r});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 i=this.profileToJSONString(e),s=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(i,"utf-8"),t="application/json";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:s,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})}};o.submitting("Submitting profile to Hedera network",30);const a=this.auth.privateKey?await vr(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},n):await xr(r,this.auth.signer,n);if(!a.confirmed||!a.inscription.topic_id)return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=a.inscription.topic_id;return o.completed("Profile inscription completed",{topicId:c,transactionId:a.result.transactionId}),{profileTopicId:c,transactionId:a.result.transactionId,success:!0}}catch(a){return o.failed(`Error inscribing profile: ${a.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:a.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const o=this.setProfileForAccountMemo(t),n=(new r.AccountUpdateTransaction).setAccountMemo(o).setAccountId(e);return this.executeTransaction(n)}catch(o){return this.logger.error(`Error updating account memo: ${o instanceof Error?o.message:"Unknown error"}`),{success:!1,error:o instanceof Error?o.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const o=r?.progressCallback,n=new Sr({module:"HCS11-ProfileCreation",logger:this.logger,callback:o});n.preparing("Starting profile creation process",0);const i=n.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return n.failed("Profile inscription failed",{error:s?.error}),s;if(n.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return n.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return n.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[jr.TEXT_GENERATION];for(const r of e){const e=Wr[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(jr.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?qr.AUTONOMOUS:qr.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const o=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${o}`),!o?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo`};this.logger.info(`Found HCS-11 memo: ${o}`);const n=o.substring(7);if(!n?.startsWith("hcs://")){if(n.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${n.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(n.startsWith("ar://")){const e=n.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();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${n}`}}{const e=n.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${n}`};const[o,i,s]=e,a=t||this.network||"mainnet";this.logger.info(`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();return t?{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:s}}:{success:!1,error:`No profile data found 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(o){return this.logger.error(`Error fetching profile: ${o.message}`),{success:!1,error:`Error fetching profile: ${o.message}`}}}}class Zr{async checkRegistrationStatus(e,t,r,o){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok){const e=`Failed to confirm registration: ${n.statusText}`;throw o&&o.error(e),new Error(e)}return await n.json()}catch(n){throw o&&o.error(`Error checking registration status: ${n.message}`),n}}async waitForRegistrationConfirmation(e,t,r,o=60,n=2e3,i){let s=0;for(;s<o;){i&&i.info(`Checking registration status. Attempt ${s+1}/${o}`);const a=await this.checkRegistrationStatus(e,t,r,i);if("success"===a.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${n}ms before next attempt`),await new Promise((e=>setTimeout(e,n))),s++}return i&&i.warn(`Registration not confirmed after ${o} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",o){try{o&&o.info("Registering agent with guarded registry");try{const r=new Qr({network:t,auth:{operatorId:"0.0.0"}});o?.info(`Fetching profile by account ID ${e} on ${t}`),await(n=5e3,new Promise((e=>setTimeout(e,n))));const i=await r.fetchProfileByAccountId(e,t);if(o?.info("Profile fetched",i),i?.error)return o?.error("Error fetching profile",i.error),{error:i.error,success:!1};if(!i?.success||!i?.profile)return o&&o.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!i.profile.inboundTopicId)return o&&o.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!i.profile.outboundTopicId)return o&&o.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};o&&o.info(`Profile validation successful. Inbound topic: ${i.profile.inboundTopicId}, Outbound topic: ${i.profile.outboundTopicId}`)}catch(i){return o&&o.error(`Error validating profile: ${i.message}`),{error:`Error validating profile: ${i.message}`,success:!1}}const s=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})}),a=await s.json();return s.ok?(o&&o.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(s){return{error:`Error during registration request: ${s.message}`,success:!1}}var n}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 o=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!o.ok){return{registrations:[],error:await o.text()||"Failed to fetch registrations",success:!1}}const n=await o.json();return n.error?{registrations:[],error:n.error,success:!1}:{registrations:n.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}var eo=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(eo||{});class to extends Zr{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 Rr(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){try{const t=await this.mirrorNode.getTopicMessages(e),r=["message","close_connection","transaction"];return{messages:t.filter((e=>{if("hcs-10"!==e.p||!r.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(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.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 n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=r.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(o){this.logger.error(`Key validation error: ${o instanceof Error?o.message:String(o)}`)}return n.fee_schedule_key?.key&&n.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(o){const e=o instanceof Error?o.message:String(o);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){try{const t=await this.mirrorNode.getTopicMessages(e);return{messages:t.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(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(t){throw this.logger.error("Failed to fetch account",t),t}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t){this.logger.debug(`Retrieving profile for account: ${e}`);const r=`${e}-${this.network}`;if(!t){const t=ro.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Qr({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),o=await t.fetchProfileByAccountId(e,this.network);if(!o?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,o?.error),{profile:null,success:!1,error:o?.error||`Failed to retrieve profile for account ID: ${e}`};const n=o.profile;let i=null;o.topicInfo?.inboundTopic&&o.topicInfo?.outboundTopic&&o.topicInfo?.profileTopicId&&(i={inboundTopic:o.topicInfo.inboundTopic,outboundTopic:o.topicInfo.outboundTopic,profileTopicId:o.topicInfo.profileTopicId});const s={profile:n,topicInfo:i,success:!0};return ro.getInstance().set(r,s),s}catch(o){const e=`Failed to retrieve profile: ${o.message}`;return this.logger.error(e),{profile:null,success:!1,error:e}}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t){try{const r=await this.retrieveProfile(e,t);if(!r?.success)throw new Error(r.error||"Failed to retrieve profile");const o=r.profile;if(!o.inboundTopicId||!o.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!r.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return r.topicInfo}catch(r){const e=r,t=`Failed to retrieve topic info: ${e.message}`;throw this.logger.error(t),e}}async retrieveOutboundMessages(e){try{const t=await this.retrieveCommunicationTopics(e);if(!t)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(t.outboundTopic)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(t){const e=`Failed to retrieve outbound messages: ${t.message}`;return this.logger.error(e),[]}}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(r){const e=`Failed to check connection created: ${r.message}`;return this.logger.error(e),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new $r(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(r){const e=`Error resolving HRL reference: ${r.message}`;throw this.logger.error(e),new Error(e)}}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 $r(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(r){const e=`Error resolving HRL reference with type: ${r.message}`;throw this.logger.error(e),new Error(e)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const o=await this.getOperatorId(),n=r.accountId,i=await this.canSubmitToTopic(e,n);if(!i?.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a={p:"hcs-10",op:"connection_request",operator_id:o,m:t},c=i.requiresFee,u=await this.submitPayload(e,a,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(n);if(!l)throw new Error("Failed to retrieve outbound topic");const d=u.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`;return await this.submitPayload(l.outboundTopic,{...a,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:p}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:o,connectionTopicId:n,operatorId:i,memo:s}){const a={p:"hcs-10",op:"connection_created",connection_topic_id:n,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:o,connection_request_id:r,operator_id:i,m:s};return await this.submitPayload(e,a)}async waitForConnectionConfirmation(e,t,r=60,o=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let i=0;i<r;i++){this.logger.info(`Attempt ${i+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},o=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(o),a=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),n&&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}i<r-1&&(this.logger.info(`No matching confirmation found, waiting ${o}ms before retrying...`),await new Promise((e=>setTimeout(e,o))))}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");const o=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=o,o}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(":"),o=r?.[4];if(!o)throw new Error("Failed to retrieve topic info account ID");return o}clearCache(){ro.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 checkRegistrationStatus(e,t,r){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)throw new Error(`Failed to confirm registration: ${o.statusText}`);return await o.json()}catch(o){const e=o,t=`Error checking registration status: ${e.message}`;throw this.logger.error(t),e}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],o=t[1];if(!r)return!1;if(!o)return!1;const n=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!n.test(o)&&!!n.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e),o=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?o.slice(0,t):o}}class ro{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return ro.instance||(ro.instance=new ro),ro.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 oo extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class no extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class io extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class so extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class ao{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}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=zr.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===zr.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class co extends to{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.client="mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=Br(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t.privateKey),this.keyType=t.detectedType}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}this.network=e.network,this.logger=p.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Qr({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorId),t=e?.key?._type;t.includes("ECDSA")?this.keyType="ecdsa":(t.includes("ED25519"),this.keyType="ed25519");const o="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorId,o),{accountId:this.operatorId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=r.PrivateKey.generateED25519(),o=(new r.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new r.Hbar(e));this.logger.debug("Executing account creation transaction");const n=await o.execute(this.client),i=(await n.getReceipt(this.client)).accountId;if(!i)throw this.logger.error("Account creation failed: accountId is null"),new no("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${i.toString()}`),{accountId:i.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,o){this.keyType||await this.initializeOperator();const n=this._generateHcs10Memo(eo.INBOUND,{accountId:e,ttl:r});let i,s;switch(t){case zr.PUBLIC:i=!1;break;case zr.CONTROLLED:i=!0;break;case zr.FEE_BASED:if(i=!1,!o)throw new Error("Fee configuration builder is required for fee-based topics");o.customFees.forEach((t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)})),s=o.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(n,!0,i,s)}async createAgent(e,t=60,r){this.keyType||await this.initializeOperator();const o=e.build();let n=r?.outboundTopicId||"",i=r?.inboundTopicId||"",s=r?.pfpTopicId||o.existingPfpTopicId||"",a=r?.profileTopicId||"";const c=this.client.operatorAccountId?.toString();if(!c)throw new Error("Failed to retrieve operator account ID");if(n)this.logger.info(`Using existing outbound topic ID: ${n}`);else{const e=this._generateHcs10Memo(eo.OUTBOUND,{ttl:t});n=await this.createTopic(e,!0,!0),this.logger.info(`Created new outbound topic ID: ${n}`)}if(i?this.logger.info(`Using existing inbound topic ID: ${i}`):(i=await this.createInboundTopic(c,o.inboundTopicType,t,o.inboundTopicType===zr.FEE_BASED?o.feeConfig:void 0),this.logger.info(`Created new inbound topic ID: ${i}`)),!s&&o.pfpBuffer&&o.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(o.pfpBuffer,o.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else s&&this.logger.info(`Using existing profile picture with topic ID: ${s}`);if(a)this.logger.info(`Using existing profile topic ID: ${a}`);else{a=(await this.storeHCS11Profile(o.name,o.bio,i,n,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s?o.pfpBuffer:void 0,o.pfpFileName,s)).profileTopicId,this.logger.info(`Profile stored with topic ID: ${a}`)}return{inboundTopicId:i,outboundTopicId:n,pfpTopicId:s,profileTopicId:a}}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(r){const e=r,t=`Error inscribing profile picture: ${e.message}`;return this.logger.error(t),{pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async storeHCS11Profile(e,t,r,o,n=[],i,s,a,c){try{let u=c||"";if(!u&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?u=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`),u=c);const l=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"}),d=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,n,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:i.properties,inboundTopicId:r,outboundTopicId:o,creator:i.creator}),f=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!f.success)throw this.logger.error(`Failed to inscribe profile: ${f.error}`),new Error(f.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${f.profileTopicId}, transaction ID: ${f.transactionId}`),{profileTopicId:f.profileTopicId,pfpTopicId:u,transactionId:f.transactionId,success:!0}}catch(u){const e=u,t=`Error storing HCS-11 profile: ${e.message}`;return this.logger.error(t),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async setupFees(e,t,o=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;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 i=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 r.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.feeTokenId)),t}return null})).filter(Boolean);if(0===i.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const s=[...t.exemptAccounts||[],...o];return s.length>0&&(n=await this.setupExemptKeys(e,s)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(i)}async setupExemptKeys(e,t){let r=e;const o=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let n=[];if(o.length>0)try{n=await Nr(o,this.network,this.logger)}catch(i){const e=`Error getting exempt keys: ${i.message}, continuing without exempt keys`;this.logger.warn(e)}return n.length>0&&(r=r.setFeeExemptKeys(n)),r}async handleConnectionRequest(e,t,o,n,i=60){const s=this._generateHcs10Memo(eo.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:o});this.logger.info(`Handling connection request ${o} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let c=await this.mirrorNode.getPublicKey(t);const u=await this.mirrorNode.getPublicKey(a);if(!u)throw new Error("Failed to retrieve public key");const l=new r.KeyList([u,c],1);let d;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};d=await this.createTopic(s,l,l,t)}else d=await this.createTopic(s,l,l);this.logger.info(`Created new connection topic ID: ${d}`)}catch(y){const e=`Failed to create connection topic: ${y}`;throw this.logger.error(e),new io(e)}const p=`${e}@${a}`,f=await this.confirmConnection(e,d,t,o,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(a),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:o,confirmedRequestId:f,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:f,operatorId:p}}async confirmConnection(e,t,r,o,n,i){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${o}`);const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:s,connection_id:o,m:n},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,a,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new so("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,o,n){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=JSON.stringify(s);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`,o=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!o?.topic_id)throw new Error("Failed to inscribe large message content");s.data=`hcs://1/${o.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${o.topic_id}`)}catch(c){const e=`Error inscribing large message: ${c.message}`;throw this.logger.error(e),new Error(e)}}return this.logger.info("Submitting message to connection topic",s),await this.submitPayload(e,s,o,i.requiresFee)}async createTopic(e,t,o,n){this.logger.info("Creating topic");const i=(new r.TopicCreateTransaction).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(i.setAdminKey(this.client.operatorPublicKey),i.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof r.PublicKey||t instanceof r.KeyList)&&(i.setAdminKey(t),this.client.operatorAccountId&&i.setAutoRenewAccountId(this.client.operatorAccountId))),o&&("boolean"==typeof o&&o&&this.client.operatorPublicKey?i.setSubmitKey(this.client.operatorPublicKey):(o instanceof r.PublicKey||o instanceof r.KeyList)&&i.setSubmitKey(o)),n&&await this.setupFees(i,n),this.logger.debug("Executing topic creation transaction");const s=await i.execute(this.client),a=await s.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,o,n=!1){const i="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(i,"utf8");if(s>1e3)throw new oo("Payload size exceeds 1000 bytes limit",s);const a=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(i);let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new r.Hbar(this.feeAmount))),o){const e=a.freezeWith(this.client),t=await e.sign(o);c=await t.execute(this.client)}else c=await a.execute(this.client);const u=await c.getReceipt(this.client);if(!u)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"),u}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.operatorPrivateKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const o=d.lookup(t)||"application/octet-stream",n=await Ar.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),i={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 vr({type:"buffer",buffer:e,fileName:t,mimeType:o},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},i,n);if(!s.confirmed||!s.inscription)throw new Error("Inscription was not confirmed");return s.inscription}async waitForConnectionConfirmation(e,t,r=60,o=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let i=0;i<r;i++){this.logger.info(`Attempt ${i+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},o=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(o),a=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),n&&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}i<r-1&&(this.logger.info(`No matching confirmation found, waiting ${o}ms before retrying...`),await new Promise((e=>setTimeout(e,o))))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const o=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=o.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=o.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||o.existingAccount,!c)throw new Error("Cannot resume registration without account information");a=new co({network:o.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:r.PrivateKey.fromString(c.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),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:"))),r=e?.split(":")[1];r&&o.existingAccount?(c=o.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(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}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}}),a=new co({network:o.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:r.PrivateKey.fromString(c.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,l=s.inboundTopicId,d=s.pfpTopicId,p=s.profileTopicId;if(!u||!l||!p){d&&e.setExistingProfilePicture(d);const t=await a.createAgent(e,60,s);u=t.outboundTopicId,l=t.inboundTopicId,d=t.pfpTopicId,p=t.profileTopicId,s.outboundTopicId=u,s.inboundTopicId=l,s.pfpTopicId=d,s.profileTopicId=p,s.createdResources||(s.createdResources=[]),d&&!s.createdResources.includes(`pfp:${d}`)&&s.createdResources.push(`pfp:${d}`),s.createdResources.includes(`inbound:${l}`)||s.createdResources.push(`inbound:${l}`),s.createdResources.includes(`outbound:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${p}`)||s.createdResources.push(`profile:${p}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,inboundTopicId:l,pfpTopicId:d,profileTopicId:p}})}const u=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,o.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:u,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:u,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:u,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(o){const e=o,r=`Failed to create and register agent: ${e.message}`;return this.logger.error(r),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,o){try{this.logger.info("Registering agent with guarded registry");const n=o?.maxAttempts??60,i=o?.delayMs??2e3,s=o?.progressCallback;let a=o?.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=r.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 u=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,i,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:u,transactionId:c.transactionId,state:a}}),{...c,confirmed:u,state:a}}catch(n){const e=n,t=`Failed to register agent: ${e.message}`;return this.logger.error(t),{error:e.message,success:!1}}}async registerAgent(e,t,r,o,n){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:o};await this.submitPayload(e,i,n)}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 zr.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`),zr.FEE_BASED}return zr.CONTROLLED}catch(t){const e=`Error determining topic type: ${t.message}`;throw this.logger.error(e),new Error(e)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,o,n){this.logger.info("Creating scheduled transaction");const i=(new r.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?r.AccountId.fromString(n):this.client.operatorAccountId);if(t&&i.setScheduleMemo(t),o){const e=u.addSeconds(new Date,o),t=r.Timestamp.fromDate(e);i.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const s=await i.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,o,n){const i=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:n?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,o,i.requiresFee)}async sendTransaction(e,t,r,o){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:n,transactionId:i}=await this.createScheduledTransaction(t,o?.scheduleMemo,o?.expirationTime,o?.schedulePayerAccountId);return{scheduleId:n,transactionId:i,receipt:await this.sendTransactionOperation(e,n,r,o?.submitKey,{memo:o?.operationMemo})}}}const uo="undefined"!=typeof window;var lo=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(lo||{});class po{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new Rr(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,o,n=[]){return new po({network:r,logger:o,defaultCollectorAccountId:t}).addHbarFee(e,t,n)}static async forToken(e,t,r,o,n,i=[],s){const a=new po({network:o,logger:n,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,i),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||"",feeTokenId:void 0,exemptAccounts:[...r],type:lo.FIXED_FEE}),this}async addTokenFee(e,t,r,o,n=[]){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 i=o;if(void 0===i)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(i=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${i}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),i=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),i=0}return this.customFees.push({feeAmount:{amount:e*10**i,decimals:i},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...n],type:lo.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;return this.customFees.forEach((t=>{t.exemptAccounts.forEach((t=>e.add(t)))})),{customFees:this.customFees,exemptAccounts:Array.from(e)}}}exports.AIAgentCapability=jr,exports.AIAgentType=qr,exports.AccountCreationError=no,exports.AgentBuilder=ao,exports.BrowserHCSClient=class extends to{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}),uo)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Qr({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(r){this.logger.warn(`Failed to initialize HCS11Client: ${r}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,o,n){this.logger.info("Sending message");const i={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(i);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`,o=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!o?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${o.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${o.topic_id}`)}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,i,o,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,o,n="Connection accepted. Looking forward to collaborating!",i=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 u=new r.KeyList([c,a],1),l=this._generateHcs10Memo(eo.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:o}),d=(new r.TopicCreateTransaction).setTopicMemo(l).setAutoRenewAccountId(r.AccountId.fromString(s)).setAdminKey(u).setSubmitKey(u);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 f=p?.result;if(!f?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const h=f.topicId.toString(),g=`${e}@${s}`,m=await this.confirmConnection(e,h,t,o,g,n),y=await this.retrieveCommunicationTopics(s),w=await this.retrieveCommunicationTopics(t),b=`${w.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:w.outboundTopic,connectionRequestId:o,confirmedRequestId:m,connectionTopicId:h,operatorId:b,memo:`Connection established with ${t}`}),{connectionTopicId:h,confirmedConnectionSequenceNumber:m,operatorId:g}}async confirmConnection(e,t,r,o,n,i){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:n,connection_id:o,m:i},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,o=new Sr({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof ao;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");o.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const{inboundTopicId:i,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,o);let c,u,l;if(n=a,r||(e.setInboundTopicId(i),e.setOutboundTopicId(s)),r){const t=e.build();c=t.existingPfpTopicId||n.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=n.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,n,o):c&&(o.preparing(`Using existing profile picture: ${c}`,50,{state:n}),n.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,n,i,s,t,o),n.currentStage="complete",n.completedPercentage=100,o.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:i,outboundTopicId:s,pfpTopicId:c,state:n});let d="";n.outboundTopicId&&(d=n.outboundTopicId);let p="";n.inboundTopicId&&(p=n.inboundTopicId);let f="";n.pfpTopicId&&(f=n.pfpTopicId);let h="";return n.profileTopicId&&(h=n.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:f,profileTopicId:h,success:!0,state:n}}catch(n){return o.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async handleProfilePictureCreation(e,t,r,o){r.currentStage="pfp",o.preparing("Creating profile picture",30,{state:r});const n=o.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),i=await this.inscribePfp(e,t,{progressCallback:e=>n.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!i.success){let e="Failed to inscribe profile picture";throw i.error&&(e=i.error),new Error(e)}const s=i.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),o.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,o,n,i,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"),o.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:o});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let u;if(e){const e=t.build(),o=e.metadata?.socials?Object.entries(e.metadata.socials).map((([e,t])=>({platform:e,handle:t}))):[];u=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:o,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:i,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:o,pfpFileName:s,...a}=e;u=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:n,outboundTopicId:i})}const l=await this.hcs11Client.createAndInscribeProfile(u,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??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)}o.profileTopicId=l.profileTopicId,o.createdResources&&o.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:o})}}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,o){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,i=this.initializeRegistrationState(n,o?.existingState),s=new Sr({module:"AgentRegistration",logger:this.logger,callback:o?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:i};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=r.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:i};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const c=o?.maxAttempts??60,u=o?.delayMs??2e3,l=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,u,this.logger);return this.updateStateForCompletedRegistration(i,n),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:i,confirmed:l}),{...a,confirmed:l,state:i}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),o=t?.progressCallback,n=new Sr({module:"AgentCreateRegister",logger:this.logger,callback:o});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,n.preparing("Starting agent creation process",0,{state:i}),"complete"!==i.currentStage||!i.inboundTopicId||!i.outboundTopicId||!i.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},existingState:i,updateAccountMemo:!1});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");i=t.state,i.agentMetadata=r.metadata}n.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:s}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:i});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");i=e.state,i.profileTopicId&&await(this.hcs11Client?.updateAccountMemoWithProfile(s,i.profileTopicId))}return n.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:s,operatorId:`${i.inboundTopicId}@${s}`,inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,profileTopicId:i.profileTopicId,pfpTopicId:i.pfpTopicId,privateKey:null,...i.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,o,n=[],i={},s,a,c,u){try{const l=u?.progressCallback,d=new Sr({module:"StoreHCS11Profile",logger:this.logger,callback:l});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 f=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const h=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,g=this.hcs11Client.createAIAgentProfile(e,f,n,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:h,properties:{version:i.version||"1.0.0",creator:i.creator||"Unknown",supported_languages:i.supported_languages||["en"],permissions:i.permissions||[],model_details:i.model_details,training:i.training,capabilities_description:i.capabilities_description,...i},inboundTopicId:r,outboundTopicId:o,creator:i.creator}),m=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(g,!0,{progressCallback:e=>{m.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(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,o){this.logger.info("Creating topic");const{accountId:n,signer:i}=this.getAccountAndSigner(),s=(new r.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(n)),o&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),u=c.error;if(u)return this.logger.error(u),{success:!1,error:u};const l=c.result;return l?.topicId?{success:!0,topicId:l.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,o,n){let i;this.logger.debug(`Submitting payload to topic ${e}`),i="string"==typeof t?t:JSON.stringify(t);const s=(new r.TopicMessageSubmitTransaction).setTopicId(e).setMessage(i);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new r.Hbar(this.feeAmount))),o){const{accountId:e,signer:t}=this.getAccountAndSigner();s.freezeWithSigner(t);const r=await s.sign(o);a=await this.hwc.executeTransactionWithErrorHandling(r,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(a?.error)throw this.logger.error(`Failed to submit payload: ${a.error}`),new Error(`Failed to submit payload: ${a.error}`);if(!a?.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"),a.result}async inscribeFile(e,t,r){const{accountId:o,signer:n}=this.getAccountAndSigner(),i=d.lookup(t)||"application/octet-stream",s=await Ar.createWithAuth({type:"client",accountId:o,signer:n,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 xr({type:"buffer",buffer:e,fileName:t,mimeType:i},n,{...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 o=r?.progressCallback,n=new Sr({module:"PFP-Inscription",logger:this.logger,callback:o});if(!this.hcs11Client)return n.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};n.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{n.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:i});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 n.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(o){return this.logger.error(`Error inscribing profile picture: ${o.message}`),{pfpTopicId:"",success:!1,error:o.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:o}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const n=this._generateHcs10Memo(eo.OUTBOUND,{ttl:e?.ttl,accountId:o}),i=await this.createTopic(n,!0,!0);if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create outbound topic");r.outboundTopicId=i.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 n=this._generateHcs10Memo(eo.INBOUND,{ttl:e?.ttl,accountId:o}),i=await this.createTopic(n,!0,!1);if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create inbound topic");r.inboundTopicId=i.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.ConnectionConfirmationError=so,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=new p(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[o,n]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(o.messages||[],e),this.processInboundMessages(n.messages||[]);const i=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${o.messages?.length||0} outbound and ${n.messages?.length||0} inbound messages. Found ${i} 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[o,n]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(o)).messages||[];let r=!1;for(const e of n){const o=e.connectionRequestId;if(!o)continue;const n=t.find((t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==o)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const o=r[1];if(t.operator_id&&t.operator_id===o)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0}));if(n?.connection_topic_id){r=!0;const t=n.connection_topic_id;let i=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||e.created),profileInfo:e.profileInfo,connectionRequestId:o,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),i&&this.connections.delete(i),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 ${o}:`,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 n of r){if(this.logger.debug(`Processing pending connection: ${n.connectionTopicId}`),!n.targetAccountId){this.logger.debug(`Skipping connection ${n.connectionTopicId} - no targetAccountId`);continue}let e=n.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(n.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${n.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(n.connectionTopicId,{...n,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${n.connectionTopicId} with inbound topic ID: ${e}`)}catch(o){this.logger.debug(`Error fetching profile for ${n.targetAccountId}: ${o}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=n.connectionRequestId||n.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),o=(r.messages||[]).find((e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id));if(o?.connection_topic_id){const e=o.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${n.targetAccountId} on their inbound topic`),this.connections.set(n.connectionTopicId,{...n,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||n.created),lastActivity:new Date(o.created||n.created)})}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(o){this.logger.warn(`Error checking for confirmations on target inbound topic for ${n.targetAccountId}: ${o}`)}else this.logger.debug(`Skipping connection ${n.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 o of r){const e={...o,targetInboundTopicId:t.inboundTopicId};this.connections.set(o.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 i of r){const e=i.connection_request_id,r=i.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(r),n=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out outbound request to account: ${o}`);continue}const s=Array.from(this.connections.values()).some((t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===o)),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:i.outbound_topic_id||"",targetAccountId:o,targetTopicId:n,operatorId:r,sequenceNumber:i.sequence_number,created:i.created||new Date,memo:i.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:o,targetInboundTopicId:n,status:"pending",isPending:!0,needsConfirmation:!1,created:i.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m};this.connections.set(a,t)}}}const o=e.filter((e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id));for(const i of o){const e=i.connection_request_id,t=i.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(i.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const o=`req-${e}:${i.operator_id}`,n=this.pendingRequests.get(o);if(n&&(n.status="confirmed"),this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:o,originTopicId:i.outbound_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,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:o,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m})}const n=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const i of n){const e=i.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=i.connection_request_id&&i.operator_id?`req-${i.connection_request_id}:${i.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:i.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:i.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 o of t){const e=o.sequence_number,t=o.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(t),i=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out request from account: ${n}`);continue}const s=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${n} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:n,targetInboundTopicId:i,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:o.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:i,processed:!1,memo:o.m})}for(const o of r){const e=o.connection_id,t=o.connection_topic_id,r=o.connected_account_id||"",n=o.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const i=`inb-${e}:${n}`;if(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,inboundRequestId:e,uniqueRequestKey:i,originTopicId:o.connection_topic_id,processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,inboundRequestId:e,uniqueRequestKey:i,originTopicId:o.connection_topic_id,processed:!1,memo:o.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 o=t.find((e=>"close_connection"===e.op));if(o){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:o.created||new Date,closedReason:o.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 o of r)this.connections.set(o.connectionTopicId,{...o,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[o,n]of this.connections.entries())n.originTopicId===e&&n.inboundRequestId===t&&(this.connections.set(o,{...n,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),n.originTopicId===e&&n.connectionRequestId===t&&(this.connections.set(o,{...n,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 o=await this.baseClient.getTransactionRequests(e,t),n=[];for(const e of o)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||n.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),n.push(e)}return n}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}async getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const{messages:r}=await this.baseClient.getMessageStream(e),o=r.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===o.length)return;return o.sort(((e,t)=>t.created.getTime()-e.created.getTime())),o[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}},exports.CustomFeeType=lo,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 f,this.logger=p.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let n={...t};const i={};for(const a of e){const e=`${a.c.contractAddress}-${a.c.abi.name}`,t=await this.cache.get(e);if(t)i[a.c.abi.name]=JSON.parse(t),Object.assign(n,i[a.c.abi.name]);else try{const t=new o.ethers.Interface([{...a.c.abi}]),s=t.encodeFunctionData(a.c.abi.name),c=r.ContractId.fromSolidityAddress(a.c.contractAddress),u=await this.readFromMirrorNode(s,r.AccountId.fromString("0.0.800"),c);if(this.logger.info(`Result for ${a.c.contractAddress}:`,u?.result),!u?.result){this.logger.warn(`Failed to get result from mirror node for ${a.c.contractAddress}`),i[a.c.abi.name]="0",Object.assign(n,i[a.c.abi.name]);continue}const l=t?.decodeFunctionResult(a.c.abi.name,u.result);let d={values:[]};l&&a.c.abi.outputs?.forEach(((e,t)=>{const r=h(l[t],e.type);d.values.push(r),e.name&&(d[e.name]=r)})),await this.cache.set(e,JSON.stringify(d)),i[a.c.abi.name]=d,n[a.c.abi.name]=d}catch(s){this.logger.error(`Error executing command for ${a.c.contractAddress}:`,s),i[a.c.abi.name]="0",Object.assign(n,i[a.c.abi.name])}}return{results:i,stateData:n}}async executeCommand(e,t={}){const{results:r,stateData:o}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:o}}async readFromMirrorNode(e,t,r){try{const o=r.toSolidityAddress(),n=t.toSolidityAddress(),i=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:n.startsWith("0x")?n:`0x${n}`,to:o?.startsWith("0x")?o:`0x${o}`,value:0})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}catch(o){return this.logger.error("Error reading from mirror node:",o),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=Kr,exports.FeeConfigBuilder=po,exports.HCS=class{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 o=e.dataset[t];"true"===o&&(o=!0),"false"===o&&(o=!1),isNaN(Number(o))||""===o||(o=Number(o)),this.config[r]=o}})),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(o){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 o}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const o=r.replace(/['"]+/g,""),n=await this.fetchWithRetry(t+e+"?network="+o);return await n.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.getAttribute("type"),i=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(o||"")){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(o,t,a);if("wasm"===n){const t=await c.arrayBuffer(),o=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(o,{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 "+n+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(a){if(this.error("Failed to load "+n+": "+r,a),this.updateLoadingStatus(r,"failed"),i)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{return await import(r)}catch(o){throw this.error("Failed to import module",o),o}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.hasAttribute("data-required");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,t,n),s=await i.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(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),n)throw i}}}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,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(r,t,o),i=URL.createObjectURL(n);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(o){this.error("Failed to load image: "+r,o),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),o=r?.split("/").pop();this.log("Loading "+t+": "+o),this.updateLoadingStatus(t+": "+o,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,r,n),s=URL.createObjectURL(i);e.src=s,"video"===t?this.LoadedVideos[o]=s:this.LoadedAudioUrls[o]=s,this.updateLoadingStatus(t+": "+o,"loaded"),this.log("Loaded "+t+": "+o)}catch(n){this.error("Failed to load "+t+": "+o,n),this.updateLoadingStatus(t+": "+o,"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,o=e.getAttribute("data-network")||this.config.network;let n;"model-viewer"!==e.tagName.toLowerCase()?(n=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{n.setAttribute(e.name,e.value)})),n.setAttribute("camera-controls",""),n.setAttribute("auto-rotate",""),n.setAttribute("ar",""),e.parentNode?.replaceChild(n,e)):n=e;const i=await this.retrieveHCS1Data(r,t,o),s=URL.createObjectURL(i);n.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(o){this.error("Failed to load GLB: "+r,o),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((o=>{this.loadQueue.push({element:e,type:t,order:r,resolve:o}),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 n=t.substring(r,e),i=n.split("/").pop();try{const o=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(i,o,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+n+" with "+c)}catch(o){this.error("Failed to load CSS image: "+i,o)}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://"]'),o=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),n=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=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:o,type:"video"},{elements:n,type:"audio"},{elements:i,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(),o=t.getAttribute("src");switch(o?.startsWith("hcs://")&&(t.setAttribute("data-src",o),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 o=new Audio(r);o.volume=t,this.LoadedAudios[e]=o,o.play().catch((e=>{console.error("Failed to play audio:",e)})),o.addEventListener("ended",(()=>{o.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 o=document.querySelector('audio[data-topic-id="'+e+'"]');if(o)o.volume=r,await o.play();else{const n=document.createElement("audio");n.volume=r,t&&n.setAttribute("autoplay","autoplay"),n.setAttribute("data-topic-id",e),n.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(n),await this.loadMedia(n,"audio"),o=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await o.play()}}},exports.HCS10BaseClient=to,exports.HCS10Cache=ro,exports.HCS10Client=co,exports.HCS11Client=Qr,exports.HRLResolver=$r,exports.Hcs10MemoType=eo,exports.HederaMirrorNode=Rr,exports.InboundTopicType=zr,exports.Logger=p,exports.PayloadSizeError=oo,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.ProfileType=Mr,exports.ProgressReporter=Sr,exports.Registration=Zr,exports.SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.TopicCreationError=io,exports.TransactionParser=class{static parseTransactionBody(e){try{const t=o.ethers.decodeBase64(e),n=i.proto.SchedulableTransactionBody.decode(t),s=this.getTransactionType(n),a={type:s,humanReadableType:this.getHumanReadableType(s),transfers:[],tokenTransfers:[],raw:n};if(n.memo&&(a.memo=n.memo),n.transactionFee){const e=r.Hbar.fromTinybars(r.Long.fromValue(n.transactionFee));a.transactionFee=e.toString(r.HbarUnit.Hbar)}return n.cryptoTransfer&&Dr.parseCryptoTransfers(n.cryptoTransfer,a),n.cryptoDelete&&(a.cryptoDelete=Dr.parseCryptoDelete(n.cryptoDelete)),n.cryptoCreateAccount&&(a.cryptoCreateAccount=Dr.parseCryptoCreateAccount(n.cryptoCreateAccount)),n.cryptoUpdateAccount&&(a.cryptoUpdateAccount=Dr.parseCryptoUpdateAccount(n.cryptoUpdateAccount)),n.cryptoApproveAllowance&&(a.cryptoApproveAllowance=Dr.parseCryptoApproveAllowance(n.cryptoApproveAllowance)),n.cryptoDeleteAllowance&&(a.cryptoDeleteAllowance=Dr.parseCryptoDeleteAllowance(n.cryptoDeleteAllowance)),n.contractCall&&(a.contractCall=Or.parseContractCall(n.contractCall)),n.contractCreateInstance&&(a.contractCreate=Or.parseContractCreate(n.contractCreateInstance)),n.contractUpdateInstance&&(a.contractUpdate=Or.parseContractUpdate(n.contractUpdateInstance)),n.contractDeleteInstance&&(a.contractDelete=Or.parseContractDelete(n.contractDeleteInstance)),n.tokenCreation&&(a.tokenCreation=Fr.parseTokenCreate(n.tokenCreation)),n.tokenMint&&(a.tokenMint=Fr.parseTokenMint(n.tokenMint)),n.tokenBurn&&(a.tokenBurn=Fr.parseTokenBurn(n.tokenBurn)),n.tokenUpdate&&(a.tokenUpdate=Fr.parseTokenUpdate(n.tokenUpdate)),n.tokenFeeScheduleUpdate&&(a.tokenFeeScheduleUpdate=Fr.parseTokenFeeScheduleUpdate(n.tokenFeeScheduleUpdate)),n.tokenFreeze&&(a.tokenFreeze=Fr.parseTokenFreeze(n.tokenFreeze)),n.tokenUnfreeze&&(a.tokenUnfreeze=Fr.parseTokenUnfreeze(n.tokenUnfreeze)),n.tokenGrantKyc&&(a.tokenGrantKyc=Fr.parseTokenGrantKyc(n.tokenGrantKyc)),n.tokenRevokeKyc&&(a.tokenRevokeKyc=Fr.parseTokenRevokeKyc(n.tokenRevokeKyc)),n.tokenPause&&(a.tokenPause=Fr.parseTokenPause(n.tokenPause)),n.tokenUnpause&&(a.tokenUnpause=Fr.parseTokenUnpause(n.tokenUnpause)),n.tokenWipe&&(a.tokenWipeAccount=Fr.parseTokenWipeAccount(n.tokenWipe)),n.tokenDeletion&&(a.tokenDelete=Fr.parseTokenDelete(n.tokenDeletion)),n.tokenAssociate&&(a.tokenAssociate=Fr.parseTokenAssociate(n.tokenAssociate)),n.tokenDissociate&&(a.tokenDissociate=Fr.parseTokenDissociate(n.tokenDissociate)),n.consensusCreateTopic&&(a.consensusCreateTopic=_r.parseConsensusCreateTopic(n.consensusCreateTopic)),n.consensusSubmitMessage&&(a.consensusSubmitMessage=_r.parseConsensusSubmitMessage(n.consensusSubmitMessage)),n.consensusUpdateTopic&&(a.consensusUpdateTopic=_r.parseConsensusUpdateTopic(n.consensusUpdateTopic)),n.consensusDeleteTopic&&(a.consensusDeleteTopic=_r.parseConsensusDeleteTopic(n.consensusDeleteTopic)),n.fileCreate&&(a.fileCreate=Lr.parseFileCreate(n.fileCreate)),n.fileAppend&&(a.fileAppend=Lr.parseFileAppend(n.fileAppend)),n.fileUpdate&&(a.fileUpdate=Lr.parseFileUpdate(n.fileUpdate)),n.fileDelete&&(a.fileDelete=Lr.parseFileDelete(n.fileDelete)),n.utilPrng&&(a.utilPrng=Ur.parseUtilPrng(n.utilPrng)),a}catch(t){throw new Error(`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`)}}static parseScheduleResponse(e){if(!e.transaction_body)throw new Error("Schedule response missing transaction_body");const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){let t="unknown";return e.cryptoTransfer?t="cryptoTransfer":e.cryptoCreateAccount?t="cryptoCreateAccount":e.cryptoUpdateAccount?t="cryptoUpdateAccount":e.cryptoApproveAllowance?t="cryptoApproveAllowance":e.cryptoDeleteAllowance?t="cryptoDeleteAllowance":e.cryptoDelete?t="cryptoDelete":e.consensusCreateTopic?t="consensusCreateTopic":e.consensusUpdateTopic?t="consensusUpdateTopic":e.consensusSubmitMessage?t="consensusSubmitMessage":e.consensusDeleteTopic?t="consensusDeleteTopic":e.fileCreate?t="fileCreate":e.fileAppend?t="fileAppend":e.fileUpdate?t="fileUpdate":e.fileDelete?t="fileDelete":e.contractCall?t="contractCall":e.contractCreateInstance?t="contractCreate":e.contractUpdateInstance?t="contractUpdate":e.contractDeleteInstance?t="contractDelete":e.tokenCreation?t="tokenCreate":e.tokenUpdate?t="tokenUpdate":e.tokenDeletion?t="tokenDelete":e.tokenAssociate?t="tokenAssociate":e.tokenDissociate?t="tokenDissociate":e.tokenMint?t="tokenMint":e.tokenBurn?t="tokenBurn":e.tokenFeeScheduleUpdate?t="tokenFeeScheduleUpdate":e.tokenFreeze?t="tokenFreeze":e.tokenUnfreeze?t="tokenUnfreeze":e.tokenGrantKyc?t="tokenGrantKyc":e.tokenRevokeKyc?t="tokenRevokeKyc":e.tokenPause?t="tokenPause":e.tokenUnpause?t="tokenUnpause":e.tokenWipe?t="tokenWipe":e.utilPrng&&(t="utilPrng"),t}static getHumanReadableType(e){const t={cryptoTransfer:"HBAR Transfer",cryptoCreateAccount:"Create Account",cryptoUpdateAccount:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoApproveAllowance:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",cryptoDelete:"Delete Account",consensusCreateTopic:"Create Topic",consensusUpdateTopic:"Update Topic",consensusSubmitMessage:"Submit Message",consensusDeleteTopic:"Delete Topic",fileCreate:"Create File",fileAppend:"Append File",fileUpdate:"Update File",fileDelete:"Delete File",contractCall:"Contract Call",contractCreate:"Create Contract",contractUpdate:"Update Contract",contractDelete:"Delete Contract",ethereumTransaction:"Ethereum Transaction",tokenCreate:"Create Token",tokenUpdate:"Update Token",tokenDelete:"Delete Token",tokenAssociate:"Associate Token",tokenDissociate:"Dissociate Token",tokenMint:"Mint Token",tokenBurn:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",tokenUnfreeze:"Unfreeze Token",tokenGrantKyc:"Grant KYC",tokenRevokeKyc:"Revoke KYC",tokenPause:"Pause Token",tokenUnpause:"Unpause Token",tokenWipe:"Wipe Token",scheduleCreate:"Create Schedule",scheduleSign:"Sign Schedule",utilPrng:"Generate Random Number",unknown:"Unknown Transaction"};let r;return r=t[e]?t[e]:"Unknown Transaction",r}static getTransactionSummary(e){if("cryptoTransfer"===e.type){const t=[],r=[];for(const o of e.transfers){const e=parseFloat(o.amount);let n=o.amount;n.startsWith("-")&&(n=n.substring(1)),n=n.replace(/\s*ℏ$/,""),e<0?t.push(`${o.accountId} (${n} ℏ)`):e>0&&r.push(`${o.accountId} (${n} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType}if(e.contractCall){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}if(e.tokenMint)return`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`;if(e.tokenBurn)return`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`;if(e.tokenCreation){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?.length&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t}if(e.tokenTransfers.length>0){const t={};for(const o of e.tokenTransfers)t[o.tokenId]||(t[o.tokenId]=[]),t[o.tokenId].push(o);const r=[];for(const[e,o]of Object.entries(t)){const t=[],n=[];for(const e of o){const r=parseFloat(e.amount.toString());r<0?t.push(`${e.accountId} (${Math.abs(r)})`):r>0&&n.push(`${e.accountId} (${r})`)}t.length>0&&n.length>0&&r.push(`Transfer of token ${e} from ${t.join(", ")} to ${n.join(", ")}`)}return r.length>0?r.join("; "):e.humanReadableType}if(e.consensusCreateTopic){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}if(e.consensusSubmitMessage){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: ${s.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`;return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t}if(e.fileCreate){let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t}if(e.fileAppend)return`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`;if(e.fileUpdate)return`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`;if(e.fileDelete)return`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`;if(e.consensusUpdateTopic)return`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`;if(e.consensusDeleteTopic)return`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`;if(e.tokenUpdate)return`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`;if(e.tokenFeeScheduleUpdate)return`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`;if(e.utilPrng){let t="Generate Random Number";return e.utilPrng.range&&e.utilPrng.range>0&&(t+=` (range up to ${e.utilPrng.range-1})`),t}if(e.tokenFreeze)return`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`;if(e.tokenUnfreeze)return`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`;if(e.tokenGrantKyc)return`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`;if(e.tokenRevokeKyc)return`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`;if(e.tokenPause)return`Pause Token ${e.tokenPause.tokenId}`;if(e.tokenUnpause)return`Unpause Token ${e.tokenUnpause.tokenId}`;if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers?.length&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}if(e.tokenDelete)return`Delete Token ${e.tokenDelete.tokenId}`;if(e.tokenAssociate)return`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${e.tokenAssociate.tokenIds?.join(", ")}`;if(e.tokenDissociate)return`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${e.tokenDissociate.tokenIds?.join(", ")}`;if(e.cryptoDelete)return`Delete Account ${e.cryptoDelete.deleteAccountId}`;if(e.cryptoCreateAccount){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}if(e.cryptoUpdateAccount)return`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`;if(e.cryptoApproveAllowance){return`Approve ${(e.cryptoApproveAllowance.hbarAllowances?.length||0)+(e.cryptoApproveAllowance.tokenAllowances?.length||0)+(e.cryptoApproveAllowance.nftAllowances?.length||0)} Crypto Allowance(s)`}if(e.cryptoDeleteAllowance)return`Delete ${e.cryptoDeleteAllowance.nftAllowancesToRemove?.length||0} NFT Crypto Allowance(s)`;if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}if(e.contractUpdate)return`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`;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}if(e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType)return e.humanReadableType;if(e.tokenTransfers.length>0){const t={};for(const o of e.tokenTransfers)t[o.tokenId]||(t[o.tokenId]=[]),t[o.tokenId].push(o);const r=[];for(const[e,o]of Object.entries(t)){const t=o.filter((e=>e.amount<0)).map((e=>`${e.accountId} (${Math.abs(e.amount)})`)),n=o.filter((e=>e.amount>0)).map((e=>`${e.accountId} (${e.amount})`));t.length>0&&n.length>0?r.push(`Transfer of token ${e} from ${t.join(", ")} to ${n.join(", ")}`):n.length>0?r.push(`Token ${e} received by ${n.join(", ")}`):t.length>0&&r.push(`Token ${e} sent from ${t.join(", ")}`)}if(r.length>0)return r.join("; ")}return"Unknown Transaction"}},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),o=t(r.length,1);return this.getUint8Memory().set(r,o),this.WASM_VECTOR_LEN=r.length,o}let o=this.textEncoder.encode(e).length,n=t(o,1);const i=this.getUint8Memory();let s=0;for(;s<o;s++){const t=e.charCodeAt(s);if(t>127)break;i[n+s]=t}if(s!==o){0!==s&&(e=e.slice(s)),n=r(n,o,o=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+s,n+o);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,n}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 o=[0,0];try{const n=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,n);const i=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return o=[i,s],this.getStringFromWasm(i,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(o[0],o[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const o=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${o}`),new Error(o)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const o=await WebAssembly.instantiate(t,r);return this.wasm=o.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(o){throw this.logger.error("Failed to initialize WASM module",o),o}}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,o])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(o)}))),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.accountIdsToExemptKeys=Nr,exports.capabilityNameToCapabilityMap=Wr,exports.detectKeyTypeFromString=Br,exports.inscribe=vr,exports.inscribeWithSigner=xr,exports.process$1=H,exports.retrieveInscription=async function(e,t){const r=p.getInstance({module:"Inscriber",...t?.logging||{}}),o=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:o});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new Ar({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 Ar.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:o,network:t.network||"mainnet"});const n=await e.retrieveInscription(o);return r.info("Successfully retrieved inscription",{formattedTransactionId:o}),n}catch(n){throw r.error("Error retrieving inscription",{formattedTransactionId:o,error:n}),n}},exports.sleep=e=>new Promise((t=>setTimeout(t,e))),exports.waitForInscriptionConfirmation=Cr;
|
|
11
|
-
//# sourceMappingURL=index-
|
|
10
|
+
!function(e){const t=w,r=x,o="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=u,e.SlowBuffer=function(e){+e!=e&&(e=0);return u.alloc(+e)},e.INSPECT_MAX_BYTES=50;const n=2147483647;e.kMaxLength=n;const{Uint8Array:i,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new i(e);return Object.setPrototypeOf(t,u.prototype),t}function u(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 l(e,t,r)}function l(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!u.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|m(e,t);let o=c(r);const n=o.write(e,t);n!==r&&(o=o.slice(0,n));return o}(e,t);if(s.isView(e))return function(e){if(Q(e,i)){const t=new i(e);return h(t.buffer,t.byteOffset,t.byteLength)}return f(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(Q(e,s)||e&&Q(e.buffer,s))return h(e,t,r);if(void 0!==a&&(Q(e,a)||e&&Q(e.buffer,a)))return h(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const o=e.valueOf&&e.valueOf();if(null!=o&&o!==e)return u.from(o,t,r);const n=function(e){if(u.isBuffer(e)){const t=0|g(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||Z(e.length)?c(0):f(e);if("Buffer"===e.type&&Array.isArray(e.data))return f(e.data)}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return u.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|g(e))}function f(e){const t=e.length<0?0:0|g(e.length),r=c(t);for(let o=0;o<t;o+=1)r[o]=255&e[o];return r}function h(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 o;return o=void 0===t&&void 0===r?new i(e):void 0===r?new i(e,t):new i(e,t,r),Object.setPrototypeOf(o,u.prototype),o}function g(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function m(e,t){if(u.isBuffer(e))return e.length;if(s.isView(e)||Q(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,o=arguments.length>2&&!0===arguments[2];if(!o&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return J(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return X(e).length;default:if(n)return o?-1:J(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){let o=!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 F(this,t,r);case"utf8":case"utf-8":return R(this,t,r);case"ascii":return $(this,t,r);case"latin1":case"binary":return P(this,t,r);case"base64":return C(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,r);default:if(o)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),o=!0}}function b(e,t,r){const o=e[t];e[t]=e[r],e[r]=o}function I(e,t,r,o,n){if(0===e.length)return-1;if("string"==typeof r?(o=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Z(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=u.from(t,o)),u.isBuffer(t))return 0===t.length?-1:k(e,t,r,o,n);if("number"==typeof t)return t&=255,"function"==typeof i.prototype.indexOf?n?i.prototype.indexOf.call(e,t,r):i.prototype.lastIndexOf.call(e,t,r):k(e,[t],r,o,n);throw new TypeError("val must be string, number or Buffer")}function k(e,t,r,o,n){let i,s=1,a=e.length,c=t.length;if(void 0!==o&&("ucs2"===(o=String(o).toLowerCase())||"ucs-2"===o||"utf16le"===o||"utf-16le"===o)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function u(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let o=-1;for(i=r;i<a;i++)if(u(e,i)===u(t,-1===o?0:i-o)){if(-1===o&&(o=i),i-o+1===c)return o*s}else-1!==o&&(i-=i-o),o=-1}else for(r+c>a&&(r=a-c),i=r;i>=0;i--){let r=!0;for(let o=0;o<c;o++)if(u(e,i+o)!==u(t,o)){r=!1;break}if(r)return i}return-1}function T(e,t,r,o){r=Number(r)||0;const n=e.length-r;o?(o=Number(o))>n&&(o=n):o=n;const i=t.length;let s;for(o>i/2&&(o=i/2),s=0;s<o;++s){const o=parseInt(t.substr(2*s,2),16);if(Z(o))return s;e[r+s]=o}return s}function A(e,t,r,o){return Y(J(t,e.length-r),e,r,o)}function S(e,t,r,o){return Y(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,o)}function v(e,t,r,o){return Y(X(t),e,r,o)}function E(e,t,r,o){return Y(function(e,t){let r,o,n;const i=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),o=r>>8,n=r%256,i.push(n),i.push(o);return i}(t,e.length-r),e,r,o)}function C(e,r,o){return 0===r&&o===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,o))}function R(e,t,r){r=Math.min(e.length,r);const o=[];let n=t;for(;n<r;){const t=e[n];let i=null,s=t>239?4:t>223?3:t>191?2:1;if(n+s<=r){let r,o,a,c;switch(s){case 1:t<128&&(i=t);break;case 2:r=e[n+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(i=c));break;case 3:r=e[n+1],o=e[n+2],128==(192&r)&&128==(192&o)&&(c=(15&t)<<12|(63&r)<<6|63&o,c>2047&&(c<55296||c>57343)&&(i=c));break;case 4:r=e[n+1],o=e[n+2],a=e[n+3],128==(192&r)&&128==(192&o)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&o)<<6|63&a,c>65535&&c<1114112&&(i=c))}}null===i?(i=65533,s=1):i>65535&&(i-=65536,o.push(i>>>10&1023|55296),i=56320|1023&i),o.push(i),n+=s}return function(e){const t=e.length;if(t<=N)return String.fromCharCode.apply(String,e);let r="",o=0;for(;o<t;)r+=String.fromCharCode.apply(String,e.slice(o,o+=N));return r}(o)}u.TYPED_ARRAY_SUPPORT=function(){try{const e=new i(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,i.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),u.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(u.prototype,"parent",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.buffer}}),Object.defineProperty(u.prototype,"offset",{enumerable:!0,get:function(){if(u.isBuffer(this))return this.byteOffset}}),u.poolSize=8192,u.from=function(e,t,r){return l(e,t,r)},Object.setPrototypeOf(u.prototype,i.prototype),Object.setPrototypeOf(u,i),u.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)},u.allocUnsafe=function(e){return p(e)},u.allocUnsafeSlow=function(e){return p(e)},u.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==u.prototype},u.compare=function(e,t){if(Q(e,i)&&(e=u.from(e,e.offset,e.byteLength)),Q(t,i)&&(t=u.from(t,t.offset,t.byteLength)),!u.isBuffer(e)||!u.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,o=t.length;for(let n=0,i=Math.min(r,o);n<i;++n)if(e[n]!==t[n]){r=e[n],o=t[n];break}return r<o?-1:o<r?1:0},u.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}},u.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const o=u.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(Q(t,i))n+t.length>o.length?(u.isBuffer(t)||(t=u.from(t)),t.copy(o,n)):i.prototype.set.call(o,t,n);else{if(!u.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(o,n)}n+=t.length}return o},u.byteLength=m,u.prototype._isBuffer=!0,u.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},u.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},u.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},u.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):y.apply(this,arguments)},u.prototype.toLocaleString=u.prototype.toString,u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.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+">"},o&&(u.prototype[o]=u.prototype.inspect),u.prototype.compare=function(e,t,r,o,n){if(Q(e,i)&&(e=u.from(e,e.offset,e.byteLength)),!u.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===o&&(o=0),void 0===n&&(n=this.length),t<0||r>e.length||o<0||n>this.length)throw new RangeError("out of range index");if(o>=n&&t>=r)return 0;if(o>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(n>>>=0)-(o>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),l=this.slice(o,n),d=e.slice(t,r);for(let i=0;i<c;++i)if(l[i]!==d[i]){s=l[i],a=d[i];break}return s<a?-1:a<s?1:0},u.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},u.prototype.indexOf=function(e,t,r){return I(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return I(this,e,t,r,!1)},u.prototype.write=function(e,t,r,o){if(void 0===t)o="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)o=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===o&&(o="utf8")):(o=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");o||(o="utf8");let i=!1;for(;;)switch(o){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return A(this,e,t,r);case"ascii":case"latin1":case"binary":return S(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(i)throw new TypeError("Unknown encoding: "+o);o=(""+o).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const N=4096;function $(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(127&e[n]);return o}function P(e,t,r){let o="";r=Math.min(e.length,r);for(let n=t;n<r;++n)o+=String.fromCharCode(e[n]);return o}function F(e,t,r){const o=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>o)&&(r=o);let n="";for(let i=t;i<r;++i)n+=ee[e[i]];return n}function _(e,t,r){const o=e.slice(t,r);let n="";for(let i=0;i<o.length-1;i+=2)n+=String.fromCharCode(o[i]+256*o[i+1]);return n}function L(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 D(e,t,r,o,n,i){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<i)throw new RangeError('"value" argument is out of bounds');if(r+o>e.length)throw new RangeError("Index out of range")}function O(e,t,r,o,n){W(t,o,n,e,r,7);let i=Number(t&BigInt(4294967295));e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i,i>>=8,e[r++]=i;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 U(e,t,r,o,n){W(t,o,n,e,r,7);let i=Number(t&BigInt(4294967295));e[r+7]=i,i>>=8,e[r+6]=i,i>>=8,e[r+5]=i,i>>=8,e[r+4]=i;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function B(e,t,r,o,n,i){if(r+o>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,o,n,i){return t=+t,o>>>=0,i||B(e,0,o,4),r.write(e,t,o,n,23,4),o+4}function q(e,t,o,n,i){return t=+t,o>>>=0,i||B(e,0,o,8),r.write(e,t,o,n,52,8),o+8}u.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 o=this.subarray(e,t);return Object.setPrototypeOf(o,u.prototype),o},u.prototype.readUintLE=u.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e],n=1,i=0;for(;++i<t&&(n*=256);)o+=this[e+i]*n;return o},u.prototype.readUintBE=u.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e+--t],n=1;for(;t>0&&(n*=256);)o+=this[e+--t]*n;return o},u.prototype.readUint8=u.prototype.readUInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),this[e]},u.prototype.readUint16LE=u.prototype.readUInt16LE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUint16BE=u.prototype.readUInt16BE=function(e,t){return e>>>=0,t||L(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUint32LE=u.prototype.readUInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUint32BE=u.prototype.readUInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readBigUInt64LE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(o)+(BigInt(n)<<BigInt(32))})),u.prototype.readBigUInt64BE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(o)<<BigInt(32))+BigInt(n)})),u.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=this[e],n=1,i=0;for(;++i<t&&(n*=256);)o+=this[e+i]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},u.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||L(e,t,this.length);let o=t,n=1,i=this[e+--o];for(;o>0&&(n*=256);)i+=this[e+--o]*n;return n*=128,i>=n&&(i-=Math.pow(2,8*t)),i},u.prototype.readInt8=function(e,t){return e>>>=0,t||L(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},u.prototype.readInt16LE=function(e,t){e>>>=0,t||L(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){e>>>=0,t||L(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return e>>>=0,t||L(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readBigInt64LE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(o)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),u.prototype.readBigInt64BE=te((function(e){H(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||V(e,this.length-8);const o=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(o)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)})),u.prototype.readFloatLE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return e>>>=0,t||L(e,4,this.length),r.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return e>>>=0,t||L(e,8,this.length),r.read(this,e,!1,52,8)},u.prototype.writeUintLE=u.prototype.writeUIntLE=function(e,t,r,o){if(e=+e,t>>>=0,r>>>=0,!o){D(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=1,i=0;for(this[t]=255&e;++i<r&&(n*=256);)this[t+i]=e/n&255;return t+r},u.prototype.writeUintBE=u.prototype.writeUIntBE=function(e,t,r,o){if(e=+e,t>>>=0,r>>>=0,!o){D(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=r-1,i=1;for(this[t+n]=255&e;--n>=0&&(i*=256);)this[t+n]=e/i&255;return t+r},u.prototype.writeUint8=u.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,255,0),this[t]=255&e,t+1},u.prototype.writeUint16LE=u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeUint16BE=u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeUint32LE=u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeUint32BE=u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeBigUInt64LE=te((function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeBigUInt64BE=te((function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),u.prototype.writeIntLE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);D(this,e,t,r,o-1,-o)}let n=0,i=1,s=0;for(this[t]=255&e;++n<r&&(i*=256);)e<0&&0===s&&0!==this[t+n-1]&&(s=1),this[t+n]=(e/i|0)-s&255;return t+r},u.prototype.writeIntBE=function(e,t,r,o){if(e=+e,t>>>=0,!o){const o=Math.pow(2,8*r-1);D(this,e,t,r,o-1,-o)}let n=r-1,i=1,s=0;for(this[t+n]=255&e;--n>=0&&(i*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/i|0)-s&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||D(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},u.prototype.writeBigInt64LE=te((function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeBigInt64BE=te((function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),u.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return q(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return q(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,o){if(!u.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),o||0===o||(o=this.length),t>=e.length&&(t=e.length),t||(t=0),o>0&&o<r&&(o=r),o===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(o<0)throw new RangeError("sourceEnd out of bounds");o>this.length&&(o=this.length),e.length-t<o-r&&(o=e.length-t+r);const n=o-r;return this===e&&"function"==typeof i.prototype.copyWithin?this.copyWithin(t,r,o):i.prototype.set.call(e,this.subarray(r,o),t),n},u.prototype.fill=function(e,t,r,o){if("string"==typeof e){if("string"==typeof t?(o=t,t=0,r=this.length):"string"==typeof r&&(o=r,r=this.length),void 0!==o&&"string"!=typeof o)throw new TypeError("encoding must be a string");if("string"==typeof o&&!u.isEncoding(o))throw new TypeError("Unknown encoding: "+o);if(1===e.length){const t=e.charCodeAt(0);("utf8"===o&&t<128||"latin1"===o)&&(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 n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const i=u.isBuffer(e)?e:u.from(e,o),s=i.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=i[n%s]}return this};const K={};function j(e,t,r){K[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 z(e){let t="",r=e.length;const o="-"===e[0]?1:0;for(;r>=o+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function W(e,t,r,o,n,i){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let o;throw o=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(i+1)}${r}`:`>= -(2${r} ** ${8*(i+1)-1}${r}) and < 2 ** ${8*(i+1)-1}${r}`,new K.ERR_OUT_OF_RANGE("value",o,e)}!function(e,t,r){H(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||V(t,e.length-(r+1))}(o,n,i)}function H(e,t){if("number"!=typeof e)throw new K.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,r){if(Math.floor(e)!==e)throw H(e,r),new K.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new K.ERR_BUFFER_OUT_OF_BOUNDS;throw new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}j("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),j("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),j("ERR_OUT_OF_RANGE",(function(e,t,r){let o=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=z(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=z(n)),n+="n"),o+=` It must be ${t}. Received ${n}`,o}),RangeError);const G=/[^+/0-9A-Za-z-_]/g;function J(e,t){let r;t=t||1/0;const o=e.length;let n=null;const i=[];for(let s=0;s<o;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&i.push(239,191,189);continue}if(s+1===o){(t-=3)>-1&&i.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&i.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&i.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;i.push(r)}else if(r<2048){if((t-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;i.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;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function X(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,r,o){let n;for(n=0;n<o&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Z(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const o=16*r;for(let n=0;n<16;++n)t[o+n]=e[r]+e[n]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}(y);const E=y.Buffer,C=y.Buffer,R=globalThis||self;function N(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var $,P,F={exports:{}},_=F.exports={};function L(){throw new Error("setTimeout has not been defined")}function D(){throw new Error("clearTimeout has not been defined")}function O(e){if($===setTimeout)return setTimeout(e,0);if(($===L||!$)&&setTimeout)return $=setTimeout,setTimeout(e,0);try{return $(e,0)}catch(t){try{return $.call(null,e,0)}catch(r){return $.call(this,e,0)}}}!function(){try{$="function"==typeof setTimeout?setTimeout:L}catch(e){$=L}try{P="function"==typeof clearTimeout?clearTimeout:D}catch(e){P=D}}();var U,B=[],M=!1,q=-1;function K(){M&&U&&(M=!1,U.length?B=U.concat(B):q=-1,B.length&&j())}function j(){if(!M){var e=O(K);M=!0;for(var t=B.length;t;){for(U=B,B=[];++q<t;)U&&U[q].run();q=-1,t=B.length}U=null,M=!1,function(e){if(P===clearTimeout)return clearTimeout(e);if((P===D||!P)&&clearTimeout)return P=clearTimeout,clearTimeout(e);try{return P(e)}catch(t){try{return P.call(null,e)}catch(r){return P.call(this,e)}}}(e)}}function z(e,t){this.fun=e,this.array=t}function W(){}_.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];B.push(new z(e,t)),1!==B.length||M||O(j)},z.prototype.run=function(){this.fun.apply(null,this.array)},_.title="browser",_.browser=!0,_.env={},_.argv=[],_.version="",_.versions={},_.on=W,_.addListener=W,_.once=W,_.off=W,_.removeListener=W,_.removeAllListeners=W,_.emit=W,_.prependListener=W,_.prependOnceListener=W,_.listeners=function(e){return[]},_.binding=function(e){throw new Error("process.binding is not supported")},_.cwd=function(){return"/"},_.chdir=function(e){throw new Error("process.chdir is not supported")},_.umask=function(){return 0};const H=N(F.exports);function V(e,t){return function(){return e.apply(t,arguments)}}const{toString:G}=Object.prototype,{getPrototypeOf:J}=Object,X=(e=>t=>{const r=G.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Y=e=>(e=e.toLowerCase(),t=>X(t)===e),Q=e=>t=>typeof t===e,{isArray:Z}=Array,ee=Q("undefined");const te=Y("ArrayBuffer");const re=Q("string"),oe=Q("function"),ne=Q("number"),ie=e=>null!==e&&"object"==typeof e,se=e=>{if("object"!==X(e))return!1;const t=J(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},ae=Y("Date"),ce=Y("File"),ue=Y("Blob"),le=Y("FileList"),de=Y("URLSearchParams"),[pe,fe,he,ge]=["ReadableStream","Request","Response","Headers"].map(Y);function me(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let o,n;if("object"!=typeof e&&(e=[e]),Z(e))for(o=0,n=e.length;o<n;o++)t.call(null,e[o],o,e);else{const n=r?Object.getOwnPropertyNames(e):Object.keys(e),i=n.length;let s;for(o=0;o<i;o++)s=n[o],t.call(null,e[s],s,e)}}function ye(e,t){t=t.toLowerCase();const r=Object.keys(e);let o,n=r.length;for(;n-- >0;)if(o=r[n],t===o.toLowerCase())return o;return null}const we="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:R,be=e=>!ee(e)&&e!==we;const Ie=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&J(Uint8Array)),ke=Y("HTMLFormElement"),Te=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ae=Y("RegExp"),Se=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),o={};me(r,((r,n)=>{let i;!1!==(i=t(r,n,e))&&(o[n]=i||r)})),Object.defineProperties(e,o)};const ve=Y("AsyncFunction"),xe=(Ee="function"==typeof setImmediate,Ce=oe(we.postMessage),Ee?setImmediate:Ce?(Re=`axios@${Math.random()}`,Ne=[],we.addEventListener("message",(({source:e,data:t})=>{e===we&&t===Re&&Ne.length&&Ne.shift()()}),!1),e=>{Ne.push(e),we.postMessage(Re,"*")}):e=>setTimeout(e));var Ee,Ce,Re,Ne;const $e="undefined"!=typeof queueMicrotask?queueMicrotask.bind(we):void 0!==H&&H.nextTick||xe,Pe={isArray:Z,isArrayBuffer:te,isBuffer:function(e){return null!==e&&!ee(e)&&null!==e.constructor&&!ee(e.constructor)&&oe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)},isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||oe(e.append)&&("formdata"===(t=X(e))||"object"===t&&oe(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&te(e.buffer),t},isString:re,isNumber:ne,isBoolean:e=>!0===e||!1===e,isObject:ie,isPlainObject:se,isReadableStream:pe,isRequest:fe,isResponse:he,isHeaders:ge,isUndefined:ee,isDate:ae,isFile:ce,isBlob:ue,isRegExp:Ae,isFunction:oe,isStream:e=>ie(e)&&oe(e.pipe),isURLSearchParams:de,isTypedArray:Ie,isFileList:le,forEach:me,merge:function e(){const{caseless:t}=be(this)&&this||{},r={},o=(o,n)=>{const i=t&&ye(r,n)||n;se(r[i])&&se(o)?r[i]=e(r[i],o):se(o)?r[i]=e({},o):Z(o)?r[i]=o.slice():r[i]=o};for(let n=0,i=arguments.length;n<i;n++)arguments[n]&&me(arguments[n],o);return r},extend:(e,t,r,{allOwnKeys:o}={})=>(me(t,((t,o)=>{r&&oe(t)?e[o]=V(t,r):e[o]=t}),{allOwnKeys:o}),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,o)=>{e.prototype=Object.create(t.prototype,o),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,o)=>{let n,i,s;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),i=n.length;i-- >0;)s=n[i],o&&!o(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&J(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:X,kindOfTest:Y,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const o=e.indexOf(t,r);return-1!==o&&o===r},toArray:e=>{if(!e)return null;if(Z(e))return e;let t=e.length;if(!ne(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let o;for(;(o=r.next())&&!o.done;){const r=o.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const o=[];for(;null!==(r=e.exec(t));)o.push(r);return o},isHTMLForm:ke,hasOwnProperty:Te,hasOwnProp:Te,reduceDescriptors:Se,freezeMethods:e=>{Se(e,((t,r)=>{if(oe(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const o=e[r];oe(o)&&(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={},o=e=>{e.forEach((e=>{r[e]=!0}))};return Z(e)?o(e):o(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:ye,global:we,isContextDefined:be,isSpecCompliantForm:function(e){return!!(e&&oe(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])},toJSONObject:e=>{const t=new Array(10),r=(e,o)=>{if(ie(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[o]=e;const n=Z(e)?[]:{};return me(e,((e,t)=>{const i=r(e,o+1);!ee(i)&&(n[t]=i)})),t[o]=void 0,n}}return e};return r(e,0)},isAsyncFn:ve,isThenable:e=>e&&(ie(e)||oe(e))&&oe(e.then)&&oe(e.catch),setImmediate:xe,asap:$e};function Fe(e,t,r,o,n){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),o&&(this.request=o),n&&(this.response=n,this.status=n.status?n.status:null)}Pe.inherits(Fe,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:Pe.toJSONObject(this.config),code:this.code,status:this.status}}});const _e=Fe.prototype,Le={};["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=>{Le[e]={value:e}})),Object.defineProperties(Fe,Le),Object.defineProperty(_e,"isAxiosError",{value:!0}),Fe.from=(e,t,r,o,n,i)=>{const s=Object.create(_e);return Pe.toFlatObject(e,s,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),Fe.call(s,e.message,t,r,o,n),s.cause=e,s.name=e.name,i&&Object.assign(s,i),s};function De(e){return Pe.isPlainObject(e)||Pe.isArray(e)}function Oe(e){return Pe.endsWith(e,"[]")?e.slice(0,-2):e}function Ue(e,t,r){return e?e.concat(t).map((function(e,t){return e=Oe(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}const Be=Pe.toFlatObject(Pe,{},null,(function(e){return/^is[A-Z]/.test(e)}));function Me(e,t,r){if(!Pe.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const o=(r=Pe.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!Pe.isUndefined(t[e])}))).metaTokens,n=r.visitor||u,i=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Pe.isSpecCompliantForm(t);if(!Pe.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Pe.isDate(e))return e.toISOString();if(!a&&Pe.isBlob(e))throw new Fe("Blob is not supported. Use a Buffer instead.");return Pe.isArrayBuffer(e)||Pe.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):E.from(e):e}function u(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(Pe.endsWith(r,"{}"))r=o?r:r.slice(0,-2),e=JSON.stringify(e);else if(Pe.isArray(e)&&function(e){return Pe.isArray(e)&&!e.some(De)}(e)||(Pe.isFileList(e)||Pe.endsWith(r,"[]"))&&(a=Pe.toArray(e)))return r=Oe(r),a.forEach((function(e,o){!Pe.isUndefined(e)&&null!==e&&t.append(!0===s?Ue([r],o,i):null===s?r:r+"[]",c(e))})),!1;return!!De(e)||(t.append(Ue(n,r,i),c(e)),!1)}const l=[],d=Object.assign(Be,{defaultVisitor:u,convertValue:c,isVisitable:De});if(!Pe.isObject(e))throw new TypeError("data must be an object");return function e(r,o){if(!Pe.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+o.join("."));l.push(r),Pe.forEach(r,(function(r,i){!0===(!(Pe.isUndefined(r)||null===r)&&n.call(t,r,Pe.isString(i)?i.trim():i,o,d))&&e(r,o?o.concat(i):[i])})),l.pop()}}(e),t}function qe(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function Ke(e,t){this._pairs=[],e&&Me(e,this,t)}const je=Ke.prototype;function ze(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function We(e,t,r){if(!t)return e;const o=r&&r.encode||ze;Pe.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let i;if(i=n?n(t,r):Pe.isURLSearchParams(t)?t.toString():new Ke(t,r).toString(o),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}je.append=function(e,t){this._pairs.push([e,t])},je.toString=function(e){const t=e?function(t){return e.call(this,t,qe)}:qe;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class He{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){Pe.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const Ve={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ge={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Ke,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Je="undefined"!=typeof window&&"undefined"!=typeof document,Xe="object"==typeof navigator&&navigator||void 0,Ye=Je&&(!Xe||["ReactNative","NativeScript","NS"].indexOf(Xe.product)<0),Qe="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Ze=Je&&window.location.href||"http://localhost",et={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Je,hasStandardBrowserEnv:Ye,hasStandardBrowserWebWorkerEnv:Qe,navigator:Xe,origin:Ze},Symbol.toStringTag,{value:"Module"})),...Ge};function tt(e){function t(e,r,o,n){let i=e[n++];if("__proto__"===i)return!0;const s=Number.isFinite(+i),a=n>=e.length;if(i=!i&&Pe.isArray(o)?o.length:i,a)return Pe.hasOwnProp(o,i)?o[i]=[o[i],r]:o[i]=r,!s;o[i]&&Pe.isObject(o[i])||(o[i]=[]);return t(e,r,o[i],n)&&Pe.isArray(o[i])&&(o[i]=function(e){const t={},r=Object.keys(e);let o;const n=r.length;let i;for(o=0;o<n;o++)i=r[o],t[i]=e[i];return t}(o[i])),!s}if(Pe.isFormData(e)&&Pe.isFunction(e.entries)){const r={};return Pe.forEachEntry(e,((e,o)=>{t(function(e){return Pe.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}(e),o,r,0)})),r}return null}const rt={transitional:Ve,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",o=r.indexOf("application/json")>-1,n=Pe.isObject(e);n&&Pe.isHTMLForm(e)&&(e=new FormData(e));if(Pe.isFormData(e))return o?JSON.stringify(tt(e)):e;if(Pe.isArrayBuffer(e)||Pe.isBuffer(e)||Pe.isStream(e)||Pe.isFile(e)||Pe.isBlob(e)||Pe.isReadableStream(e))return e;if(Pe.isArrayBufferView(e))return e.buffer;if(Pe.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Me(e,new et.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,o){return et.isNode&&Pe.isBuffer(e)?(this.append(t,e.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},t))}(e,this.formSerializer).toString();if((i=Pe.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Me(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||o?(t.setContentType("application/json",!1),function(e,t){if(Pe.isString(e))try{return(t||JSON.parse)(e),Pe.trim(e)}catch(r){if("SyntaxError"!==r.name)throw r}return(0,JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||rt.transitional,r=t&&t.forcedJSONParsing,o="json"===this.responseType;if(Pe.isResponse(e)||Pe.isReadableStream(e))return e;if(e&&Pe.isString(e)&&(r&&!this.responseType||o)){const r=!(t&&t.silentJSONParsing)&&o;try{return JSON.parse(e)}catch(n){if(r){if("SyntaxError"===n.name)throw Fe.from(n,Fe.ERR_BAD_RESPONSE,this,null,this.response);throw n}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:et.classes.FormData,Blob:et.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Pe.forEach(["delete","get","head","post","put","patch"],(e=>{rt.headers[e]={}}));const ot=Pe.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"]),nt=Symbol("internals");function it(e){return e&&String(e).trim().toLowerCase()}function st(e){return!1===e||null==e?e:Pe.isArray(e)?e.map(st):String(e)}function at(e,t,r,o,n){return Pe.isFunction(o)?o.call(this,t,r):(n&&(t=r),Pe.isString(t)?Pe.isString(o)?-1!==t.indexOf(o):Pe.isRegExp(o)?o.test(t):void 0:void 0)}class ct{constructor(e){e&&this.set(e)}set(e,t,r){const o=this;function n(e,t,r){const n=it(t);if(!n)throw new Error("header name must be a non-empty string");const i=Pe.findKey(o,n);(!i||void 0===o[i]||!0===r||void 0===r&&!1!==o[i])&&(o[i||t]=st(e))}const i=(e,t)=>Pe.forEach(e,((e,r)=>n(e,r,t)));if(Pe.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(Pe.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))i((e=>{const t={};let r,o,n;return e&&e.split("\n").forEach((function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),o=e.substring(n+1).trim(),!r||t[r]&&ot[r]||("set-cookie"===r?t[r]?t[r].push(o):t[r]=[o]:t[r]=t[r]?t[r]+", "+o:o)})),t})(e),t);else if(Pe.isHeaders(e))for(const[s,a]of e.entries())n(a,s,r);else null!=e&&n(t,e,r);return this}get(e,t){if(e=it(e)){const r=Pe.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 o;for(;o=r.exec(e);)t[o[1]]=o[2];return t}(e);if(Pe.isFunction(t))return t.call(this,e,r);if(Pe.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=it(e)){const r=Pe.findKey(this,e);return!(!r||void 0===this[r]||t&&!at(0,this[r],r,t))}return!1}delete(e,t){const r=this;let o=!1;function n(e){if(e=it(e)){const n=Pe.findKey(r,e);!n||t&&!at(0,r[n],n,t)||(delete r[n],o=!0)}}return Pe.isArray(e)?e.forEach(n):n(e),o}clear(e){const t=Object.keys(this);let r=t.length,o=!1;for(;r--;){const n=t[r];e&&!at(0,this[n],n,e,!0)||(delete this[n],o=!0)}return o}normalize(e){const t=this,r={};return Pe.forEach(this,((o,n)=>{const i=Pe.findKey(r,n);if(i)return t[i]=st(o),void delete t[n];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}(n):String(n).trim();s!==n&&delete t[n],t[s]=st(o),r[s]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Pe.forEach(this,((r,o)=>{null!=r&&!1!==r&&(t[o]=e&&Pe.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")}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[nt]=this[nt]={accessors:{}}).accessors,r=this.prototype;function o(e){const o=it(e);t[o]||(!function(e,t){const r=Pe.toCamelCase(" "+t);["get","set","has"].forEach((o=>{Object.defineProperty(e,o+r,{value:function(e,r,n){return this[o].call(this,t,e,r,n)},configurable:!0})}))}(r,e),t[o]=!0)}return Pe.isArray(e)?e.forEach(o):o(e),this}}function ut(e,t){const r=this||rt,o=t||r,n=ct.from(o.headers);let i=o.data;return Pe.forEach(e,(function(e){i=e.call(r,i,n.normalize(),t?t.status:void 0)})),n.normalize(),i}function lt(e){return!(!e||!e.__CANCEL__)}function dt(e,t,r){Fe.call(this,null==e?"canceled":e,Fe.ERR_CANCELED,t,r),this.name="CanceledError"}function pt(e,t,r){const o=r.config.validateStatus;r.status&&o&&!o(r.status)?t(new Fe("Request failed with status code "+r.status,[Fe.ERR_BAD_REQUEST,Fe.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}ct.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Pe.reduceDescriptors(ct.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),Pe.freezeMethods(ct),Pe.inherits(dt,Fe,{__CANCEL__:!0});const ft=(e,t,r=3)=>{let o=0;const n=function(e,t){e=e||10;const r=new Array(e),o=new Array(e);let n,i=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),u=o[s];n||(n=c),r[i]=a,o[i]=c;let l=s,d=0;for(;l!==i;)d+=r[l++],l%=e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),c-n<t)return;const p=u&&c-u;return p?Math.round(1e3*d/p):void 0}}(50,250);return function(e,t){let r,o,n=0,i=1e3/t;const s=(t,i=Date.now())=>{n=i,r=null,o&&(clearTimeout(o),o=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=i?s(e,t):(r=e,o||(o=setTimeout((()=>{o=null,s(r)}),i-a)))},()=>r&&s(r)]}((r=>{const i=r.loaded,s=r.lengthComputable?r.total:void 0,a=i-o,c=n(a);o=i;e({loaded:i,total:s,progress:s?i/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&i<=s?(s-i)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})}),r)},ht=(e,t)=>{const r=null!=e;return[o=>t[0]({lengthComputable:r,total:e,loaded:o}),t[1]]},gt=e=>(...t)=>Pe.asap((()=>e(...t))),mt=et.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,et.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(et.origin),et.navigator&&/(msie|trident)/i.test(et.navigator.userAgent)):()=>!0,yt=et.hasStandardBrowserEnv?{write(e,t,r,o,n,i){const s=[e+"="+encodeURIComponent(t)];Pe.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),Pe.isString(o)&&s.push("path="+o),Pe.isString(n)&&s.push("domain="+n),!0===i&&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 wt(e,t,r){let o=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(o||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const bt=e=>e instanceof ct?{...e}:e;function It(e,t){t=t||{};const r={};function o(e,t,r,o){return Pe.isPlainObject(e)&&Pe.isPlainObject(t)?Pe.merge.call({caseless:o},e,t):Pe.isPlainObject(t)?Pe.merge({},t):Pe.isArray(t)?t.slice():t}function n(e,t,r,n){return Pe.isUndefined(t)?Pe.isUndefined(e)?void 0:o(void 0,e,0,n):o(e,t,0,n)}function i(e,t){if(!Pe.isUndefined(t))return o(void 0,t)}function s(e,t){return Pe.isUndefined(t)?Pe.isUndefined(e)?void 0:o(void 0,e):o(void 0,t)}function a(r,n,i){return i in t?o(r,n):i in e?o(void 0,r):void 0}const c={url:i,method:i,data:i,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)=>n(bt(e),bt(t),0,!0)};return Pe.forEach(Object.keys(Object.assign({},e,t)),(function(o){const i=c[o]||n,s=i(e[o],t[o],o);Pe.isUndefined(s)&&i!==a||(r[o]=s)})),r}const kt=e=>{const t=It({},e);let r,{data:o,withXSRFToken:n,xsrfHeaderName:i,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=ct.from(a),t.url=We(wt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Pe.isFormData(o))if(et.hasStandardBrowserEnv||et.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(et.hasStandardBrowserEnv&&(n&&Pe.isFunction(n)&&(n=n(t)),n||!1!==n&&mt(t.url))){const e=i&&s&&yt.read(s);e&&a.set(i,e)}return t},Tt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise((function(t,r){const o=kt(e);let n=o.data;const i=ct.from(o.headers).normalize();let s,a,c,u,l,{responseType:d,onUploadProgress:p,onDownloadProgress:f}=o;function h(){u&&u(),l&&l(),o.cancelToken&&o.cancelToken.unsubscribe(s),o.signal&&o.signal.removeEventListener("abort",s)}let g=new XMLHttpRequest;function m(){if(!g)return;const o=ct.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders());pt((function(e){t(e),h()}),(function(e){r(e),h()}),{data:d&&"text"!==d&&"json"!==d?g.response:g.responseText,status:g.status,statusText:g.statusText,headers:o,config:e,request:g}),g=null}g.open(o.method.toUpperCase(),o.url,!0),g.timeout=o.timeout,"onloadend"in g?g.onloadend=m:g.onreadystatechange=function(){g&&4===g.readyState&&(0!==g.status||g.responseURL&&0===g.responseURL.indexOf("file:"))&&setTimeout(m)},g.onabort=function(){g&&(r(new Fe("Request aborted",Fe.ECONNABORTED,e,g)),g=null)},g.onerror=function(){r(new Fe("Network Error",Fe.ERR_NETWORK,e,g)),g=null},g.ontimeout=function(){let t=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const n=o.transitional||Ve;o.timeoutErrorMessage&&(t=o.timeoutErrorMessage),r(new Fe(t,n.clarifyTimeoutError?Fe.ETIMEDOUT:Fe.ECONNABORTED,e,g)),g=null},void 0===n&&i.setContentType(null),"setRequestHeader"in g&&Pe.forEach(i.toJSON(),(function(e,t){g.setRequestHeader(t,e)})),Pe.isUndefined(o.withCredentials)||(g.withCredentials=!!o.withCredentials),d&&"json"!==d&&(g.responseType=o.responseType),f&&([c,l]=ft(f,!0),g.addEventListener("progress",c)),p&&g.upload&&([a,u]=ft(p),g.upload.addEventListener("progress",a),g.upload.addEventListener("loadend",u)),(o.cancelToken||o.signal)&&(s=t=>{g&&(r(!t||t.type?new dt(null,e,g):t),g.abort(),g=null)},o.cancelToken&&o.cancelToken.subscribe(s),o.signal&&(o.signal.aborted?s():o.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(o.url);y&&-1===et.protocols.indexOf(y)?r(new Fe("Unsupported protocol "+y+":",Fe.ERR_BAD_REQUEST,e)):g.send(n||null)}))},At=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,o=new AbortController;const n=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;o.abort(t instanceof Fe?t:new dt(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,n(new Fe(`timeout ${t} of ms exceeded`,Fe.ETIMEDOUT))}),t);const s=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)})),e=null)};e.forEach((e=>e.addEventListener("abort",n)));const{signal:a}=o;return a.unsubscribe=()=>Pe.asap(s),a}},St=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let o,n=0;for(;n<r;)o=n+t,yield e.slice(n,o),n=o},vt=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()}},xt=(e,t,r,o)=>{const n=async function*(e,t){for await(const r of vt(e))yield*St(r,t)}(e,t);let i,s=0,a=e=>{i||(i=!0,o&&o(e))};return new ReadableStream({async pull(e){try{const{done:t,value:o}=await n.next();if(t)return a(),void e.close();let i=o.byteLength;if(r){let e=s+=i;r(e)}e.enqueue(new Uint8Array(o))}catch(t){throw a(t),t}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},Et="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Ct=Et&&"function"==typeof ReadableStream,Rt=Et&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Nt=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},$t=Ct&&Nt((()=>{let e=!1;const t=new Request(et.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),Pt=Ct&&Nt((()=>Pe.isReadableStream(new Response("").body))),Ft={stream:Pt&&(e=>e.body)};var _t;Et&&(_t=new Response,["text","arrayBuffer","blob","formData","stream"].forEach((e=>{!Ft[e]&&(Ft[e]=Pe.isFunction(_t[e])?t=>t[e]():(t,r)=>{throw new Fe(`Response type '${e}' is not supported`,Fe.ERR_NOT_SUPPORT,r)})})));const Lt=async(e,t)=>{const r=Pe.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Pe.isBlob(e))return e.size;if(Pe.isSpecCompliantForm(e)){const t=new Request(et.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Pe.isArrayBufferView(e)||Pe.isArrayBuffer(e)?e.byteLength:(Pe.isURLSearchParams(e)&&(e+=""),Pe.isString(e)?(await Rt(e)).byteLength:void 0)})(t):r},Dt={http:null,xhr:Tt,fetch:Et&&(async e=>{let{url:t,method:r,data:o,signal:n,cancelToken:i,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:u,headers:l,withCredentials:d="same-origin",fetchOptions:p}=kt(e);u=u?(u+"").toLowerCase():"text";let f,h=At([n,i&&i.toAbortSignal()],s);const g=h&&h.unsubscribe&&(()=>{h.unsubscribe()});let m;try{if(c&&$t&&"get"!==r&&"head"!==r&&0!==(m=await Lt(l,o))){let e,r=new Request(t,{method:"POST",body:o,duplex:"half"});if(Pe.isFormData(o)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=ht(m,ft(gt(c)));o=xt(r.body,65536,e,t)}}Pe.isString(d)||(d=d?"include":"omit");const n="credentials"in Request.prototype;f=new Request(t,{...p,signal:h,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:o,duplex:"half",credentials:n?d:void 0});let i=await fetch(f);const s=Pt&&("stream"===u||"response"===u);if(Pt&&(a||s&&g)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=Pe.toFiniteNumber(i.headers.get("content-length")),[r,o]=a&&ht(t,ft(gt(a),!0))||[];i=new Response(xt(i.body,65536,r,(()=>{o&&o(),g&&g()})),e)}u=u||"text";let y=await Ft[Pe.findKey(Ft,u)||"text"](i,e);return!s&&g&&g(),await new Promise(((t,r)=>{pt(t,r,{data:y,headers:ct.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:f})}))}catch(y){if(g&&g(),y&&"TypeError"===y.name&&/fetch/i.test(y.message))throw Object.assign(new Fe("Network Error",Fe.ERR_NETWORK,e,f),{cause:y.cause||y});throw Fe.from(y,y&&y.code,e,f)}})};Pe.forEach(Dt,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}}));const Ot=e=>`- ${e}`,Ut=e=>Pe.isFunction(e)||null===e||!1===e,Bt=e=>{e=Pe.isArray(e)?e:[e];const{length:t}=e;let r,o;const n={};for(let i=0;i<t;i++){let t;if(r=e[i],o=r,!Ut(r)&&(o=Dt[(t=String(r)).toLowerCase()],void 0===o))throw new Fe(`Unknown adapter '${t}'`);if(o)break;n[t||"#"+i]=o}if(!o){const e=Object.entries(n).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new Fe("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(Ot).join("\n"):" "+Ot(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return o};function Mt(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new dt(null,e)}function qt(e){Mt(e),e.headers=ct.from(e.headers),e.data=ut.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Bt(e.adapter||rt.adapter)(e).then((function(t){return Mt(e),t.data=ut.call(e,e.transformResponse,t),t.headers=ct.from(t.headers),t}),(function(t){return lt(t)||(Mt(e),t&&t.response&&(t.response.data=ut.call(e,e.transformResponse,t.response),t.response.headers=ct.from(t.response.headers))),Promise.reject(t)}))}const Kt="1.8.4",jt={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{jt[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const zt={};jt.transitional=function(e,t,r){function o(e,t){return"[Axios v1.8.4] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,i)=>{if(!1===e)throw new Fe(o(n," has been removed"+(t?" in "+t:"")),Fe.ERR_DEPRECATED);return t&&!zt[n]&&(zt[n]=!0,console.warn(o(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,i)}},jt.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Wt={assertOptions:function(e,t,r){if("object"!=typeof e)throw new Fe("options must be an object",Fe.ERR_BAD_OPTION_VALUE);const o=Object.keys(e);let n=o.length;for(;n-- >0;){const i=o[n],s=t[i];if(s){const t=e[i],r=void 0===t||s(t,i,e);if(!0!==r)throw new Fe("option "+i+" must be "+r,Fe.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new Fe("Unknown option "+i,Fe.ERR_BAD_OPTION)}},validators:jt},Ht=Wt.validators;class Vt{constructor(e){this.defaults=e,this.interceptors={request:new He,response:new He}}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(o){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=It(this.defaults,t);const{transitional:r,paramsSerializer:o,headers:n}=t;void 0!==r&&Wt.assertOptions(r,{silentJSONParsing:Ht.transitional(Ht.boolean),forcedJSONParsing:Ht.transitional(Ht.boolean),clarifyTimeoutError:Ht.transitional(Ht.boolean)},!1),null!=o&&(Pe.isFunction(o)?t.paramsSerializer={serialize:o}:Wt.assertOptions(o,{encode:Ht.function,serialize:Ht.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Wt.assertOptions(t,{baseUrl:Ht.spelling("baseURL"),withXsrfToken:Ht.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=n&&Pe.merge(n.common,n[t.method]);n&&Pe.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete n[e]})),t.headers=ct.concat(i,n);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 u;this.interceptors.response.forEach((function(e){c.push(e.fulfilled,e.rejected)}));let l,d=0;if(!a){const e=[qt.bind(this),void 0];for(e.unshift.apply(e,s),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);d<l;)u=u.then(e[d++],e[d++]);return u}l=s.length;let p=t;for(d=0;d<l;){const e=s[d++],t=s[d++];try{p=e(p)}catch(f){t.call(this,f);break}}try{u=qt.call(this,p)}catch(f){return Promise.reject(f)}for(d=0,l=c.length;d<l;)u=u.then(c[d++],c[d++]);return u}getUri(e){return We(wt((e=It(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}}Pe.forEach(["delete","get","head","options"],(function(e){Vt.prototype[e]=function(t,r){return this.request(It(r||{},{method:e,url:t,data:(r||{}).data}))}})),Pe.forEach(["post","put","patch"],(function(e){function t(t){return function(r,o,n){return this.request(It(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:o}))}}Vt.prototype[e]=t(),Vt.prototype[e+"Form"]=t(!0)}));class Gt{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 o=new Promise((e=>{r.subscribe(e),t=e})).then(e);return o.cancel=function(){r.unsubscribe(t)},o},e((function(e,o,n){r.reason||(r.reason=new dt(e,o,n),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 e;return{token:new Gt((function(t){e=t})),cancel:e}}}const Jt={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(Jt).forEach((([e,t])=>{Jt[t]=e}));const Xt=function e(t){const r=new Vt(t),o=V(Vt.prototype.request,r);return Pe.extend(o,Vt.prototype,r,{allOwnKeys:!0}),Pe.extend(o,r,null,{allOwnKeys:!0}),o.create=function(r){return e(It(t,r))},o}(rt);Xt.Axios=Vt,Xt.CanceledError=dt,Xt.CancelToken=Gt,Xt.isCancel=lt,Xt.VERSION=Kt,Xt.toFormData=Me,Xt.AxiosError=Fe,Xt.Cancel=Xt.CanceledError,Xt.all=function(e){return Promise.all(e)},Xt.spread=function(e){return function(t){return e.apply(null,t)}},Xt.isAxiosError=function(e){return Pe.isObject(e)&&!0===e.isAxiosError},Xt.mergeConfig=It,Xt.AxiosHeaders=ct,Xt.formToJSON=e=>tt(Pe.isHTMLForm(e)?new FormData(e):e),Xt.getAdapter=Bt,Xt.HttpStatusCode=Jt,Xt.default=Xt;const Yt=class e{constructor(){m(this,"isProduction"),this.isProduction="production"===H.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)}};m(Yt,"instance");let Qt=Yt;class Zt extends Error{constructor(e){super(e),this.name="ValidationError"}}class er{constructor(e){m(this,"accountId"),m(this,"privateKey"),m(this,"baseUrl"),m(this,"network"),this.accountId=e.accountId,this.privateKey=r.PrivateKey.fromStringED25519(e.privateKey),this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const o=await Xt.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=o.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=o.data.message,i=await this.signMessage(n),s=await Xt.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:i,data:n,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 C.from(r).toString("hex")}}class tr{constructor(e){m(this,"accountId"),m(this,"signer"),m(this,"baseUrl"),m(this,"network"),m(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 o=await Xt.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=o.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=o.data.message,i=await this.signMessage(JSON.stringify(n)),s=await Xt.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:i,data:n,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 C.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 rr(e){return new DataView(e.buffer,e.byteOffset)}const or={len:1,get:(e,t)=>rr(e).getUint8(t),put:(e,t,r)=>(rr(e).setUint8(t,r),t+1)},nr={len:2,get:(e,t)=>rr(e).getUint16(t,!0),put:(e,t,r)=>(rr(e).setUint16(t,r,!0),t+2)},ir={len:2,get:(e,t)=>rr(e).getUint16(t),put:(e,t,r)=>(rr(e).setUint16(t,r),t+2)},sr={len:4,get:(e,t)=>rr(e).getUint32(t,!0),put:(e,t,r)=>(rr(e).setUint32(t,r,!0),t+4)},ar={len:4,get:(e,t)=>rr(e).getUint32(t),put:(e,t,r)=>(rr(e).setUint32(t,r),t+4)},cr={len:4,get:(e,t)=>rr(e).getInt32(t),put:(e,t,r)=>(rr(e).setInt32(t,r),t+4)},ur={len:8,get:(e,t)=>rr(e).getBigUint64(t,!0),put:(e,t,r)=>(rr(e).setBigUint64(t,r,!0),t+8)};class lr{constructor(e,t){this.len=e,this.encoding=t}get(e,t){return C.from(e).toString(this.encoding,t,t+this.len)}}class dr extends Error{constructor(){super("End-Of-Stream")}}class pr{constructor(){this.resolve=()=>null,this.reject=()=>null,this.promise=new Promise(((e,t)=>{this.reject=t,this.resolve=e}))}}class fr{constructor(){this.maxStreamReadSize=1048576,this.endOfStream=!1,this.peekQueue=[]}async peek(e,t,r){const o=await this.read(e,t,r);return this.peekQueue.push(e.subarray(t,t+o)),o}async read(e,t,r){if(0===r)return 0;let o=this.readFromPeekBuffer(e,t,r);if(o+=await this.readRemainderFromStream(e,t+o,r-o),0===o)throw new dr;return o}readFromPeekBuffer(e,t,r){let o=r,n=0;for(;this.peekQueue.length>0&&o>0;){const r=this.peekQueue.pop();if(!r)throw new Error("peekData should be defined");const i=Math.min(r.length,o);e.set(r.subarray(0,i),t+n),n+=i,o-=i,i<r.length&&this.peekQueue.push(r.subarray(i))}return n}async readRemainderFromStream(e,t,r){let o=r,n=0;for(;o>0&&!this.endOfStream;){const r=Math.min(o,this.maxStreamReadSize),i=await this.readFromStream(e,t+n,r);if(0===i)break;n+=i,o-=i}return n}}class hr extends fr{constructor(e){if(super(),this.s=e,this.deferred=null,!e.read||!e.once)throw new Error("Expected an instance of stream.Readable");this.s.once("end",(()=>this.reject(new dr))),this.s.once("error",(e=>this.reject(e))),this.s.once("close",(()=>this.reject(new Error("Stream closed"))))}async readFromStream(e,t,r){if(this.endOfStream)return 0;const o=this.s.read(r);if(o)return e.set(o,t),o.length;const n={buffer:e,offset:t,length:r,deferred:new pr};return this.deferred=n.deferred,this.s.once("readable",(()=>{this.readDeferred(n)})),n.deferred.promise}readDeferred(e){const t=this.s.read(e.length);t?(e.buffer.set(t,e.offset),e.deferred.resolve(t.length),this.deferred=null):this.s.once("readable",(()=>{this.readDeferred(e)}))}reject(e){this.endOfStream=!0,this.deferred&&(this.deferred.reject(e),this.deferred=null)}async abort(){this.reject(new Error("abort"))}async close(){return this.abort()}}class gr{constructor(e){this.position=0,this.numBuffer=new Uint8Array(8),this.fileInfo=e||{}}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new dr;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 dr;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new dr;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new dr;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(){}normalizeOptions(e,t){if(t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return t?{mayBeLess:!0===t.mayBeLess,offset:t.offset?t.offset:0,length:t.length?t.length:e.length-(t.offset?t.offset:0),position:t.position?t.position:this.position}:{mayBeLess:!1,offset:0,length:e.length,position:this.position}}}class mr extends gr{constructor(e,t){super(t),this.streamReader=e}async getFileInfo(){return this.fileInfo}async readBuffer(e,t){const r=this.normalizeOptions(e,t),o=r.position-this.position;if(o>0)return await this.ignore(o),this.readBuffer(e,t);if(o<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const n=await this.streamReader.read(e,r.offset,r.length);if(this.position+=n,(!t||!t.mayBeLess)&&n<r.length)throw new dr;return n}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let o=0;if(r.position){const t=r.position-this.position;if(t>0){const n=new Uint8Array(r.length+t);return o=await this.peekBuffer(n,{mayBeLess:r.mayBeLess}),e.set(n.subarray(t),r.offset),o-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{o=await this.streamReader.peek(e,r.offset,r.length)}catch(n){if(t&&t.mayBeLess&&n instanceof dr)return 0;throw n}if(!r.mayBeLess&&o<r.length)throw new dr}return o}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let o=0;for(;o<e;){const n=e-o,i=await this.readBuffer(r,{length:Math.min(t,n)});if(i<0)return i;o+=i}return o}}class yr extends gr{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo.size=this.fileInfo.size?this.fileInfo.size:e.length}async readBuffer(e,t){if(t&&t.position){if(t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.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),o=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&o<r.length)throw new dr;return e.set(this.uint8Array.subarray(r.position,r.position+o),r.offset),o}async close(){}}const wr={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},br=4100;function Ir(e,t,r){r={offset:0,...r};for(const[o,n]of t.entries())if(r.mask){if(n!==(r.mask[o]&e[o+r.offset]))return!1}else if(n!==e[o+r.offset])return!1;return!0}class kr{constructor(e){this.detectors=null==e?void 0:e.customDetectors,this.fromTokenizer=this.fromTokenizer.bind(this),this.fromBuffer=this.fromBuffer.bind(this),this.parse=this.parse.bind(this)}async fromTokenizer(e){const t=e.position;for(const r of this.detectors||[]){const o=await r(e);if(o)return o;if(t!==e.position)return}return this.parse(e)}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`Buffer\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r;if((null==t?void 0:t.length)>1)return this.fromTokenizer(new yr(t,r))}async fromBlob(e){const t=await e.arrayBuffer();return this.fromBuffer(new Uint8Array(t))}async fromStream(e){const t=await function(e,t){return t=t||{},new mr(new hr(e),t)}(e);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t={}){const{default:r}=await Promise.resolve().then((()=>require("./index-CHar8dVv-B2IK-7-2.cjs"))).then((e=>e.i)),{sampleSize:o=br}=t;return new Promise(((t,n)=>{e.on("error",n),e.once("readable",(()=>{(async()=>{try{const s=new r.PassThrough,a=r.pipeline?r.pipeline(e,s,(()=>{})):e.pipe(s),c=e.read(o)??e.read()??C.alloc(0);try{s.fileType=await this.fromBuffer(c)}catch(i){i instanceof dr?s.fileType=void 0:n(i)}t(a)}catch(i){n(i)}})()}))}))}check(e,t){return Ir(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map((e=>e.charCodeAt(0)))),t);var r}async parse(e){if(this.buffer=C.alloc(br),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.parse(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 r=await e.readToken(wr);return e.position+r>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(r),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("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};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])){try{for(;e.position+30<e.fileInfo.size;){await e.readBuffer(this.buffer,{length:30});const o={compressedSize:this.buffer.readUInt32LE(18),uncompressedSize:this.buffer.readUInt32LE(22),filenameLength:this.buffer.readUInt16LE(26),extraFieldLength:this.buffer.readUInt16LE(28)};if(o.filename=await e.readToken(new lr(o.filenameLength,"utf-8")),await e.ignore(o.extraFieldLength),"META-INF/mozilla.rsa"===o.filename)return{ext:"xpi",mime:"application/x-xpinstall"};if(o.filename.endsWith(".rels")||o.filename.endsWith(".xml")){switch(o.filename.split("/")[0]){case"_rels":default:break;case"word":return{ext:"docx",mime:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"};case"ppt":return{ext:"pptx",mime:"application/vnd.openxmlformats-officedocument.presentationml.presentation"};case"xl":return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}}}if(o.filename.startsWith("xl/"))return{ext:"xlsx",mime:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};if(o.filename.startsWith("3D/")&&o.filename.endsWith(".model"))return{ext:"3mf",mime:"model/3mf"};if("mimetype"===o.filename&&o.compressedSize===o.uncompressedSize){let n=await e.readToken(new lr(o.compressedSize,"utf-8"));switch(n=n.trim(),n){case"application/epub+zip":return{ext:"epub",mime:"application/epub+zip"};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:"application/vnd.oasis.opendocument.text"};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:"application/vnd.oasis.opendocument.spreadsheet"};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:"application/vnd.oasis.opendocument.presentation"}}}if(0===o.compressedSize){let i=-1;for(;i<0&&e.position<e.fileInfo.size;)await e.peekBuffer(this.buffer,{mayBeLess:!0}),i=this.buffer.indexOf("504B0304",0,"hex"),await e.ignore(i>=0?i:this.buffer.length)}else await e.ignore(o.compressedSize)}}catch(t){if(!(t instanceof dr))throw t}return{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const s=C.alloc(8);return await e.readBuffer(s),Ir(s,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/opus"}:Ir(s,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Ir(s,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Ir(s,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Ir(s,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Ir(s,[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("ftyp",{offset:4})&&96&this.buffer[8]){const a=this.buffer.toString("binary",8,12).replace("\0"," ").trim();switch(a){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 a.startsWith("3g")?a.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}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/x-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")){try{await e.ignore(1350);const c=10485760,u=C.alloc(Math.min(c,e.fileInfo.size));if(await e.readBuffer(u,{mayBeLess:!0}),u.includes(C.from("AIPrivateData")))return{ext:"ai",mime:"application/postscript"}}catch(t){if(!(t instanceof dr))throw t}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 l=await this.readTiffHeader(!1);if(l)return l}if(this.check([77,77])){const d=await this.readTiffHeader(!0);if(d)return d}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function p(){const t=await e.peekNumber(or);let r=128,o=0;for(;!(t&r)&&0!==r;)++o,r>>=1;const n=C.alloc(o+1);return await e.readBuffer(n),n}async function f(){const e=await p(),t=await p();t[0]^=128>>t.length-1;const r=Math.min(6,t.length);return{id:e.readUIntBE(0,e.length),len:t.readUIntBE(t.length-r,r)}}async function h(t){for(;t>0;){const r=await f();if(17026===r.id){return(await e.readToken(new lr(r.len,"utf-8"))).replace(/\00.*$/g,"")}await e.ignore(r.len),--t}}const g=await f();switch(await h(g.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/x-matroska"};default:return}}if(this.check([82,73,70,70])){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/vnd.wave"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}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"))return{ext:"parquet",mime:"application/x-parquet"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};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.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 m=this.buffer.toString("binary",2,6);if(m.match("^d*")&&m>=1e3&&m<=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 lr(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("**ACE",{offset:7})&&(await e.peekBuffer(this.buffer,{length:14,mayBeLess:!0}),this.checkString("**",{offset:12})))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.check([137,80,78,71,13,10,26,10])){async function y(){return{length:await e.readToken(cr),type:await e.readToken(new lr(4,"binary"))}}await e.ignore(8);do{const w=await y();if(w.length<0)return;switch(w.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(w.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/x-apache-arrow"};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.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 b(){const t=C.alloc(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(ur))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const I=await b();let k=I.size-24;if(Ir(I.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const T=C.alloc(16);if(k-=await e.readBuffer(T),Ir(T,[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(Ir(T,[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(k)}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 lr(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([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(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("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 A=this.buffer.readUInt32LE(12);if(A>12&&this.buffer.length>=A+16)try{const S=this.buffer.slice(16,A+16).toString();if(JSON.parse(S).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}if(this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2]))return{ext:"mxf",mime:"application/mxf"};if(this.checkString("SCRM",{offset:44}))return{ext:"s3m",mime:"audio/x-s3m"};if(this.check([71])&&this.check([71],{offset:188}))return{ext:"mts",mime:"video/mp2t"};if(this.check([71],{offset:4})&&this.check([71],{offset:196}))return{ext:"mts",mime:"video/mp2t"};if(this.check([66,79,79,75,77,79,66,73],{offset:60}))return{ext:"mobi",mime:"application/x-mobipocket-ebook"};if(this.check([68,73,67,77],{offset:128}))return{ext:"dcm",mime:"application/dicom"};if(this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70]))return{ext:"lnk",mime:"application/x.ms.shortcut"};if(this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0]))return{ext:"alias",mime:"application/x.apple.alias"};if(this.checkString("Kaydara FBX Binary \0"))return{ext:"fbx",mime:"application/x.autodesk.fbx"};if(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})))return{ext:"eot",mime:"application/vnd.ms-fontobject"};if(this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29]))return{ext:"indd",mime:"application/x-indesign"};if(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),function(e,t=0){const r=Number.parseInt(e.toString("utf8",148,154).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let o=256;for(let n=t;n<t+148;n++)o+=e[n];for(let n=t+156;n<t+512;n++)o+=e[n];return r===o}(this.buffer))return{ext:"tar",mime:"application/x-tar"};if(this.check([255,254]))return 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;if(this.checkString("-----BEGIN PGP MESSAGE-----"))return{ext:"pgp",mime:"application/pgp-encrypted"};if(this.buffer.length>=2&&this.check([255,224],{offset:0,mask:[255,224]})){if(this.check([16],{offset:1,mask:[22]}))return this.check([8],{offset:1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}async readTiffTag(e){const t=await this.tokenizer.readToken(e?ir:nr);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?ir:nr);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?ir:nr).get(this.buffer,2),r=(e?ar:sr).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&&(this.check([28,0,254,0],{offset:8})||this.check([31,0,11,0],{offset:8})))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"}}}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","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","ai","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx"]),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.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/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/x-apache-arrow","video/mp4","audio/midi","video/x-matroska","video/webm","video/quicktime","video/vnd.avi","audio/vnd.wave","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","audio/opus","video/ogg","audio/ogg","application/ogg","audio/x-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","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","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/x-parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx"]);const Tr=class e{constructor(e){if(m(this,"client"),m(this,"config"),m(this,"logger",Qt.getInstance()),this.config=e,!e.apiKey)throw new Zt("API key is required");if(!e.network)throw new Zt("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Xt.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=Qt.getInstance()}async getFileMetadata(e){try{const t=await Xt.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 Zt("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new Zt("File must have an extension");const o=e.VALID_MIME_TYPES[r];if(!o)throw new Zt(`Unsupported file type: ${r}`);return o}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Zt("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Zt(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Zt("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Zt("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 Zt("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new Zt(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const o=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(o))throw new Zt("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 Zt("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=E.from(t,"base64"),o=await async function(e){return(new kr).fromBuffer(e)}(r);return(null==o?void 0:o.mime)||"application/octet-stream"}catch(t){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,o;try{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const o=await this.getFileMetadata(t.file.url);if(r=o.mimeType||r,o.size>e.MAX_URL_FILE_SIZE)throw new Zt(`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 Zt("JSON file must be of type application/json")}const o={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 n;return n="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...o,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...o,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),n.data}catch(n){if(n instanceof Zt)throw n;if(Xt.isAxiosError(n))throw new Error((null==(o=null==(r=n.response)?void 0:r.data)?void 0:o.message)||"Failed to start inscription");throw n}}async executeTransaction(e,t){try{const o="mainnet"===t.network?r.Client.forMainnet():r.Client.forTestnet(),n=r.PrivateKey.fromString(t.privateKey);o.setOperator(t.accountId,n);const i=r.TransferTransaction.fromBytes(E.from(e,"base64")),s=await i.sign(n),a=await s.execute(o),c=(await a.getReceipt(o)).status.toString();if("SUCCESS"!==c)throw new Error(`Transaction failed with status: ${c}`);return a.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const o=r.TransferTransaction.fromBytes(E.from(e,"base64")),n=await o.executeWithSigner(t),i=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==i)throw new Error(`Transaction failed with status: ${i}`);return n.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async inscribeAndExecute(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 o=await this.executeTransaction(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:o}}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 o=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:o}}async retryWithBackoff(e,t=3,r=1e3){for(let n=0;n<t;n++)try{return await e()}catch(o){if(n===t-1)throw o;const e=r*Math.pow(2,n);await new Promise((t=>setTimeout(t,e))),this.logger.debug(`Retry attempt ${n+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new Zt("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 er(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new tr({...t,logger:Qt.getInstance()}):new er(t),{apiKey:o}=await r.authenticate();return new e({apiKey:o,network:t.network||"mainnet"})}async waitForInscription(e,t=30,r=4e3,o=!1,n){var i;let s=0,a=0;const c=(r,o,i,c)=>{if(n)try{a=Math.max(a,i),n({stage:r,message:o,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(u){this.logger.warn(`Error in progress callback: ${u}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const n=await this.retrieveInscription(e);if(n.error)throw c("verifying",`Error: ${n.error}`,100,{error:n.error}),new Error(n.error);let a=5;void 0!==n.messages&&void 0!==n.maxMessages&&n.maxMessages>0?(a=Math.min(95,5+n.messages/n.maxMessages*90),n.completed&&(a=100)):"processing"===n.status?a=10:n.completed&&(a=100),c(n.completed?"completed":"confirming",n.completed?"Inscription completed successfully":`Processing inscription (${n.status})`,a,{status:n.status,messagesProcessed:n.messages,maxMessages:n.maxMessages,messageCount:n.messages,completed:n.completed,confirmedMessages:n.confirmedMessages,result:n});const u="hashinal"===n.mode,l="6"===(null==(i=n.fileStandard)?void 0:i.toString());if(u&&n.topic_id&&n.jsonTopicId&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;if(!u&&!l&&n.topic_id&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;if(l&&n.topic_id&&n.jsonTopicId&&n.registryTopicId&&(!o||n.completed))return c("completed","Inscription verification complete",100,{result:n}),n;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 Zt("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(o){if(this.logger.error("Failed to fetch holder inscriptions:",o),Xt.isAxiosError(o))throw new Error((null==(r=null==(t=o.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw o}}};m(Tr,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),m(Tr,"MAX_BASE64_SIZE",2097152),m(Tr,"MAX_URL_FILE_SIZE",104857600),m(Tr,"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"});let Ar=Tr;class Sr{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 Sr.instance?(e.callback&&Sr.instance.setCallback(e.callback),e.module&&Sr.instance.setModule(e.module),e.logger&&Sr.instance.setLogger(e.logger),void 0!==e.minPercent&&Sr.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&Sr.instance.setMaxPercent(e.maxPercent)):Sr.instance=new Sr(e),Sr.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 Sr({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback((t=>{const o=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let n=t.message;r&&!n.startsWith(r)&&(n=`${r}: ${n}`),this.report({stage:t.stage,message:n,progressPercent:o,details:t.details})})),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),o=this.scalePercent(r,0,100),n=Date.now();if(o===this.lastReportedPercent&&n-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=o,this.lastReportedTime=n;const i={...e,progressPercent:o};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${o.toFixed(1)}%)`,e.details),this.callback)try{this.callback(i)}catch(s){this.logger.warn(`Error in progress callback: ${s}`)}}scalePercent(e,t,r){const o=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*o}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})}}async function vr(e,t,r,o){const n=p.getInstance({module:"Inscriber",...r.logging});n.info("Starting inscription process",{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{let i;"hashinal"===r.mode&&r.metadata&&Er(r.metadata,n),o?(n.debug("Using existing InscriptionSDK instance"),i=o):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),i=new Ar({apiKey:r.apiKey,network:t.network||"mainnet"})):(n.debug("Initializing InscriptionSDK with server auth"),i=await Ar.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"}));const s={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",chunkSize:r.chunkSize};let a;switch(e.type){case"url":a={...s,file:{type:"url",url:e.url}};break;case"file":a={...s,file:{type:"path",path:e.path}};break;case"buffer":a={...s,file:{type:"base64",base64:globalThis.Buffer.from(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)),n.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const c=await i.inscribeAndExecute(a,t);if(n.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:c.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:c.jobId,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Cr(i,c.jobId,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:c.jobId}),{confirmed:!0,result:c,inscription:e,sdk:i}}return{confirmed:!1,result:c,sdk:i}}catch(i){throw n.error("Error during inscription process",i),i}}async function xr(e,t,r,o){const n=p.getInstance({module:"Inscriber",...r.logging});n.info("Starting inscription process with signer",{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{"hashinal"===r.mode&&r.metadata&&Er(r.metadata,n);const i=t.getAccountId().toString();let s;n.debug("Using account ID from signer",{accountId:i}),o?(n.debug("Using existing InscriptionSDK instance"),s=o):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),s=new Ar({apiKey:r.apiKey,network:r.network||"mainnet"})):(n.debug("Initializing InscriptionSDK with client auth"),s=await Ar.createWithAuth({type:"client",accountId:i,signer:t,network:r.network||"mainnet"}));const a={holderId:i,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":c={...a,file:{type:"path",path:e.path}};break;case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||i,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Preparing to inscribe content with signer",{type:e.type,mode:r.mode||"file",holderId:i});const u=await s.inscribe({...c,holderId:i},t);if(n.info("Inscription started",{type:e.type,mode:r.mode||"file",transactionId:u.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:u.jobId,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await Cr(s,u.jobId,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:u.jobId}),{confirmed:!0,result:u,inscription:e,sdk:s}}return{confirmed:!1,result:u,sdk:s}}catch(i){throw n.error("Error during inscription process",i),i}}function Er(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 Cr(e,t,r=30,o=4e3,n){const i=p.getInstance({module:"Inscriber"}),s=new Sr({module:"Inscriber",logger:i,callback:n});try{i.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:o}),s.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:r,intervalMs:o});try{const n=e.waitForInscription.bind(e),i=e=>{const t=e.stage||"confirming",r=e.message||"Processing inscription",o=e.progressPercent||50;s.report({stage:t,message:r,progressPercent:o,details:{}})};return await n(t,r,o,!0,i)}catch(a){return console.log(a),i.debug("Falling back to standard waitForInscription method",{error:a}),s.verifying("Verifying inscription status",50,{error:a}),await e.waitForInscription(t,r,o,!0)}}catch(c){throw i.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:o,error:c}),s.failed("Inscription confirmation failed",{transactionId:t,error:c}),c}}class Rr{constructor(e,t,r){this.maxRetries=3,this.initialDelayMs=1e3,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.info(`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 r.PublicKey.fromString(t.key.key)}catch(o){const e=`Error fetching public key from Mirror Node: ${o.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.info(`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=r.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const o=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(o?.current_rate?.cent_equivalent)/Number(o?.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){this.logger.trace(`Querying messages for topic ${e}`);let t=`/api/v1/topics/${e}/messages`;const r=[];for(;t;)try{const e=await this._requestWithRetry(t);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,n;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(o){const e=`Error decoding message: ${o}`;this.logger.error(e);continue}try{n=JSON.parse(e)}catch(o){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}n.sequence_number=t.sequence_number,r.push({...n,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(o){const e=`Error processing message: ${o.message}`;this.logger.error(e)}t=e.links?.next||""}catch(n){const r=`Error querying topic messages for topic ${e} (endpoint: ${t}) after retries: ${n.message}`;throw this.logger.error(r),new Error(r)}return r}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=i.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 n of r)if(n)if(n.ed25519){if(this.compareEd25519Key(n.ed25519,t))return!0}else if(n.keyList||n.thresholdKey)try{const e=i.proto.Key.encode({...n.keyList?{keyList:n.keyList}:{},...n.thresholdKey?{thresholdKey:n.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(o){const e=`Error in nested key: ${o.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return r.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(o){const e=`Error comparing Ed25519 key: ${o.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,o=this.initialDelayMs;const i=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 n.get(i,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 ${i} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${i}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${i}: ${a.message}. Retrying in ${o}ms...`),await new Promise((e=>setTimeout(e,o))),o=Math.min(o*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${i} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,o=this.initialDelayMs;const n={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach(((e,t)=>{n[t]=e})):Array.isArray(t.headers)?t.headers.forEach((([e,t])=>{n[e]=t})):Object.assign(n,t.headers)),this.apiKey&&(n.Authorization=`Bearer ${this.apiKey}`,n["X-API-Key"]=this.apiKey);const i={...t,headers:n};for(;r<this.maxRetries;)try{const t=await fetch(e,i);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 ${o}ms...`),await new Promise((e=>setTimeout(e,o))),o=Math.min(o*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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.sequenceNumber&&o.append("sequencenumber",t.sequenceNumber),t?.startTime&&o.append("timestamp",`gte:${t.startTime}`),t?.endTime&&o.append("timestamp",`lt:${t.endTime}`),t?.order&&o.append("order",t.order);const n=o.toString();n&&(r+=`?${n}`);const i=[];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 o={...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};i.push(o)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&i.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return i}catch(u){const t=u;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=[],o=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.tokens&&(r=r.concat(e.tokens)),o=e.links?.next||"",!o||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(n){return this.logger.error(`Error fetching tokens for account ${e}: ${n.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 o=[],n=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(n+=`&token.id=${t}`);try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);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}}));o=o.concat(t)}if(n=e.links?.next||"",!n)break}return o}catch(i){return this.logger.error(`Error fetching NFTs for account ${e}: ${i.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const o=await this.getAccountNfts(e,t);if(o){return o.find((e=>e.token_id===t&&e.serial_number===r))||null}return null}catch(o){return this.logger.error(`Error validating NFT ownership: ${o.message}`),null}}async readSmartContractQuery(e,t,o,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const i=e.startsWith("0x")?e:`0x${r.AccountId.fromString(e).toSolidityAddress()}`,s=o.startsWith("0x")?o:`0x${r.AccountId.fromString(o).toSolidityAddress()}`,a={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:s,to:i,gas:n?.gas,gasPrice:n?.gasPrice,value:n?.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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.receiverId&&o.append("receiver.id",t.receiverId),t?.serialNumber&&o.append("serialnumber",t.serialNumber),t?.tokenId&&o.append("token.id",t.tokenId);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(i){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${i.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 o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.senderId&&o.append("sender.id",t.senderId),t?.serialNumber&&o.append("serialnumber",t.serialNumber),t?.tokenId&&o.append("token.id",t.tokenId);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(i){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${i.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(n){return this.logger.error(`Error fetching blocks: ${n.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(n){return this.logger.error(`Error fetching contracts: ${n.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(o){return this.logger.error(`Error fetching contract ${e}: ${o.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).results||[]}catch(n){return this.logger.error(`Error fetching contract results: ${n.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(o){return this.logger.error(`Error fetching contract result for ${e}: ${o.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const o=new URLSearchParams;t?.blockHash&&o.append("block.hash",t.blockHash),t?.blockNumber&&o.append("block.number",t.blockNumber),t?.from&&o.append("from",t.from),void 0!==t?.internal&&o.append("internal",t.internal.toString()),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.timestamp&&o.append("timestamp",t.timestamp),t?.transactionIndex&&o.append("transaction.index",t.transactionIndex.toString());const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).results||[]}catch(i){return this.logger.error(`Error fetching contract results for ${e}: ${i.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const o=new URLSearchParams;t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.slot&&o.append("slot",t.slot),t?.timestamp&&o.append("timestamp",t.timestamp);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).state||[]}catch(i){return this.logger.error(`Error fetching contract state for ${e}: ${i.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const o=new URLSearchParams;t?.index&&o.append("index",t.index),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(i){return this.logger.error(`Error fetching contract actions for ${e}: ${i.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 o=r.toString();o&&(t+=`?${o}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs: ${n.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const o=new URLSearchParams;t?.index&&o.append("index",t.index),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.timestamp&&o.append("timestamp",t.timestamp),t?.topic0&&o.append("topic0",t.topic0),t?.topic1&&o.append("topic1",t.topic1),t?.topic2&&o.append("topic2",t.topic2),t?.topic3&&o.append("topic3",t.topic3);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(i){return this.logger.error(`Error fetching contract logs for ${e}: ${i.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(o){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${o.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const o=new URLSearchParams;t?.accountId&&o.append("account.id",t.accountId),t?.limit&&o.append("limit",t.limit.toString()),t?.order&&o.append("order",t.order),t?.serialNumber&&o.append("serialnumber",t.serialNumber);const n=o.toString();n&&(r+=`?${n}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(i){return this.logger.error(`Error fetching NFTs for token ${e}: ${i.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 o=new URLSearchParams;void 0!==t?.stack&&o.append("stack",t.stack.toString()),void 0!==t?.memory&&o.append("memory",t.memory.toString()),void 0!==t?.storage&&o.append("storage",t.storage.toString());const n=o.toString();n&&(r+=`?${n}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching opcode traces for ${e}: ${i.message}`),null}}}async function Nr(e,t,r){const o=new Rr(t,r),n=[];for(const s of e)try{const e=await o.getPublicKey(s);n.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${s}: ${i}`)}return n}class $r{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)}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(r){const e=`Error resolving HRL for content and type: ${r.message}`;throw this.logger.error(e),new Error(e)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:o,topicId:i}=r;this.logger.debug(`Resolving HRL reference: standard=${o}, topicId=${i}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${i}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await n.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await n.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:i,isBinary:!0}}if("application/json"===r){const t=await n.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${i}`);return{content:t.data,contentType:r,topicId:i,isBinary:!1}}const o=await n.get(e);if(!o.data)throw new Error(`Failed to fetch content from topic: ${i}`);let s;return s="object"==typeof o.data?o.data.content||o.data.text||JSON.stringify(o.data):o.data,{content:s,contentType:r,topicId:i,isBinary:!1}}catch(s){const e=`Error resolving HRL reference: ${s.message}`;throw this.logger.error(e),new Error(e)}}}function Pr(e){if(e){if(e.contractID)return`ContractID: ${new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${s.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${s.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map((e=>Pr(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=>Pr(e))).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new r.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"}}class Fr{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 r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=r.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=r.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=r.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=i.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=i.proto.TokenSupplyType[e.supplyType]),t.adminKey=Pr(e.adminKey),t.kycKey=Pr(e.kycKey),t.freezeKey=Pr(e.freezeKey),t.wipeKey=Pr(e.wipeKey),t.supplyKey=Pr(e.supplyKey),t.feeScheduleKey=Pr(e.feeScheduleKey),t.pauseKey=Pr(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map((e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.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:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.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:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let o;return e.royaltyFee.fallbackFee&&(o={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.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:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:o}}}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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map((e=>s.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map((e=>r.Long.fromValue(e).toNumber()))),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.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 r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=Pr(e.adminKey),t.kycKey=Pr(e.kycKey),t.freezeKey=Pr(e.freezeKey),t.wipeKey=Pr(e.wipeKey),t.supplyKey=Pr(e.supplyKey),t.feeScheduleKey=Pr(e.feeScheduleKey),t.pauseKey=Pr(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${r.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new r.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 r.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:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.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:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let o;return e.royaltyFee.fallbackFee&&(o={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.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:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:o}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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 r.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 r.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 r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.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=>r.Long.fromValue(e).toString()))),e.amount&&(t.amount=r.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.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 r.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 r.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 r.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 r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString()))),t}}class _r{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=Pr(e.adminKey),t.submitKey=Pr(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.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=s.Buffer.from(e.message),o=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o)||o.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=o,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,o=e.chunkInfo.initialTransactionID.transactionValidStart;r&&o&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${o.seconds??0}.${o.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=Pr(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=Pr(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.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}}class Lr{static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Pr({keyList:e.keys})),e.contents&&(t.contents=s.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=s.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=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Pr({keyList:e.keys})),e.contents&&(t.contents=s.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}}class Dr{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map((e=>{const t=new r.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),o=r.Hbar.fromTinybars(r.Long.fromValue(e.amount));return{accountId:t.toString(),amount:o.toString(r.HbarUnit.Hbar),isDecimal:!0}}))),e.tokenTransfers)for(const o of e.tokenTransfers){const e=new r.TokenId(o.token.shardNum??0,o.token.realmNum??0,o.token.tokenNum??0);if(o.transfers)for(const n of o.transfers){const o=new r.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),i=r.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:o.toString(),amount:i})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new r.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new r.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=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.key&&(t.key=Pr(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.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 r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.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 r.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=Pr(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${r.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=r.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 r.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=r.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 r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Hbar.fromTinybars(r.Long.fromValue(e.amount)).toString(r.HbarUnit.Hbar)})))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map((e=>({tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.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 r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new r.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=>r.Long.fromValue(e).toString()))),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new r.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 r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map((e=>r.Long.fromValue(e).toString())):[]})))),t}}class Or{static parseContractCall(e){if(!e)return;const t=r.Hbar.fromTinybars(r.Long.fromValue(e.amount??0)),o={contractId:new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:r.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(r.HbarUnit.Hbar))};return e.functionParameters&&(o.functionParameters=s.Buffer.from(e.functionParameters).toString("hex"),o.functionParameters.length>=8&&(o.functionName=o.functionParameters.substring(0,8))),o}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.gas&&(t.gas=r.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=Pr(e.adminKey)),e.constructorParameters&&(t.constructorParameters=s.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.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 r.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=s.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=Pr(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&r.hasOwnProperty("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 r.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&&r.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=r.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 r.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 r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new r.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}}class Ur{static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}}function Br(e){let t="ed25519";e.startsWith("0x")?t="ecdsa":e.startsWith("302e020100300506032b6570")?t="ed25519":e.startsWith("3030020100300706052b8104000a")?t="ecdsa":96===e.length?t="ed25519":88===e.length&&(t="ecdsa");try{return{detectedType:t,privateKey:"ecdsa"===t?r.PrivateKey.fromStringECDSA(e):r.PrivateKey.fromStringED25519(e)}}catch(o){const i="ecdsa"===t?"ed25519":"ecdsa";try{return{detectedType:i,privateKey:"ecdsa"===i?r.PrivateKey.fromStringECDSA(e):r.PrivateKey.fromStringED25519(e)}}catch(n){throw new Error(`Failed to parse private key as either ED25519 or ECDSA: ${o}`)}}}var Mr=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(Mr||{}),qr=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(qr||{}),Kr=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(Kr||{}),jr=(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))(jr||{}),zr=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(zr||{});const Wr={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},Hr=c.z.object({platform:c.z.string().min(1),handle:c.z.string().min(1)}),Vr=c.z.object({type:c.z.nativeEnum(qr),capabilities:c.z.array(c.z.nativeEnum(jr)).min(1),model:c.z.string().min(1),creator:c.z.string().optional()}),Gr=c.z.object({version:c.z.string().min(1),type:c.z.nativeEnum(Mr),display_name:c.z.string().min(1),alias:c.z.string().optional(),bio:c.z.string().optional(),socials:c.z.array(Hr).optional(),profileImage:c.z.string().optional(),properties:c.z.record(c.z.any()).optional(),inboundTopicId:c.z.string().optional(),outboundTopicId:c.z.string().optional()}),Jr=Gr.extend({type:c.z.literal(Mr.PERSONAL),language:c.z.string().optional(),timezone:c.z.string().optional()}),Xr=Gr.extend({type:c.z.literal(Mr.AI_AGENT),aiAgent:Vr}),Yr=c.z.union([Jr,Xr]);class Qr{constructor(e){if(this.client="mainnet"===e.network?r.Client.forMainnet():r.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 Rr(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=Br(this.auth.privateKey);this.keyType=e.detectedType,this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":(t&&t.includes("ED25519"),this.keyType="ed25519"),this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}createPersonalProfile(e,t){return{version:"1.0",type:Mr.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}}createAIAgentProfile(e,t,r,o,n){const i=this.validateProfile({version:"1.0",type:Mr.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:o,creator:n?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:Mr.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:o,creator:n?.creator}}}validateProfile(e){const t=Yr.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),o=await t.execute(this.client),n=await o.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,o=await e.freezeWithSigner(t),n=await o.executeWithSigner(t),i=await n.getReceiptWithSigner(t);return i.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${i.status.toString()}: ${r.Status.Success.toString()}`}:{success:!0,result:i}}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 Sr({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const i=d.lookup(t)||"application/octet-stream",s=r?.waitForConfirmation??!0;let a;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),a=await xr({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:s,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),a=await vr({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:s,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})}})}return a.confirmed?(n.completed("Image inscription completed",{topic_id:a.inscription.topic_id}),{imageTopicId:a.inscription.topic_id||"",transactionId:a.result.jobId,success:!0}):(n.verifying("Waiting for inscription confirmation",50,{jobId:a.result.jobId}),{imageTopicId:"",transactionId:a.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new Sr({module:"HCS11-Profile",logger:this.logger,callback:r});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 i=this.profileToJSONString(e),s=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(i,"utf-8"),t="application/json";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:s,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})}};o.submitting("Submitting profile to Hedera network",30);const a=this.auth.privateKey?await vr(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},n):await xr(r,this.auth.signer,n);if(!a.confirmed||!a.inscription.topic_id)return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=a.inscription.topic_id;return o.completed("Profile inscription completed",{topicId:c,transactionId:a.result.transactionId}),{profileTopicId:c,transactionId:a.result.transactionId,success:!0}}catch(a){return o.failed(`Error inscribing profile: ${a.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:a.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const o=this.setProfileForAccountMemo(t),n=(new r.AccountUpdateTransaction).setAccountMemo(o).setAccountId(e);return this.executeTransaction(n)}catch(o){return this.logger.error(`Error updating account memo: ${o instanceof Error?o.message:"Unknown error"}`),{success:!1,error:o instanceof Error?o.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const o=r?.progressCallback,n=new Sr({module:"HCS11-ProfileCreation",logger:this.logger,callback:o});n.preparing("Starting profile creation process",0);const i=n.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return n.failed("Profile inscription failed",{error:s?.error}),s;if(n.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return n.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return n.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[jr.TEXT_GENERATION];for(const r of e){const e=Wr[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(jr.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?qr.AUTONOMOUS:qr.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const o=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${o}`),!o?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo`};this.logger.info(`Found HCS-11 memo: ${o}`);const n=o.substring(7);if(!n?.startsWith("hcs://")){if(n.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${n.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(n.startsWith("ar://")){const e=n.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();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${n}`}}{const e=n.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${n}`};const[o,i,s]=e,a=t||this.network||"mainnet";this.logger.info(`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();return t?{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:s}}:{success:!1,error:`No profile data found 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(o){return this.logger.error(`Error fetching profile: ${o.message}`),{success:!1,error:`Error fetching profile: ${o.message}`}}}}class Zr{async checkRegistrationStatus(e,t,r,o){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok){const e=`Failed to confirm registration: ${n.statusText}`;throw o&&o.error(e),new Error(e)}return await n.json()}catch(n){throw o&&o.error(`Error checking registration status: ${n.message}`),n}}async waitForRegistrationConfirmation(e,t,r,o=60,n=2e3,i){let s=0;for(;s<o;){i&&i.info(`Checking registration status. Attempt ${s+1}/${o}`);const a=await this.checkRegistrationStatus(e,t,r,i);if("success"===a.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${n}ms before next attempt`),await new Promise((e=>setTimeout(e,n))),s++}return i&&i.warn(`Registration not confirmed after ${o} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",o){try{o&&o.info("Registering agent with guarded registry");try{const r=new Qr({network:t,auth:{operatorId:"0.0.0"}});o?.info(`Fetching profile by account ID ${e} on ${t}`),await(n=5e3,new Promise((e=>setTimeout(e,n))));const i=await r.fetchProfileByAccountId(e,t);if(o?.info("Profile fetched",i),i?.error)return o?.error("Error fetching profile",i.error),{error:i.error,success:!1};if(!i?.success||!i?.profile)return o&&o.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!i.profile.inboundTopicId)return o&&o.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!i.profile.outboundTopicId)return o&&o.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};o&&o.info(`Profile validation successful. Inbound topic: ${i.profile.inboundTopicId}, Outbound topic: ${i.profile.outboundTopicId}`)}catch(i){return o&&o.error(`Error validating profile: ${i.message}`),{error:`Error validating profile: ${i.message}`,success:!1}}const s=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})}),a=await s.json();return s.ok?(o&&o.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(s){return{error:`Error during registration request: ${s.message}`,success:!1}}var n}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 o=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!o.ok){return{registrations:[],error:await o.text()||"Failed to fetch registrations",success:!1}}const n=await o.json();return n.error?{registrations:[],error:n.error,success:!1}:{registrations:n.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}var eo=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(eo||{});class to extends Zr{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 Rr(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){try{const t=await this.mirrorNode.getTopicMessages(e),r=["message","close_connection","transaction"];return{messages:t.filter((e=>{if("hcs-10"!==e.p||!r.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(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.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 n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=r.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(o){this.logger.error(`Key validation error: ${o instanceof Error?o.message:String(o)}`)}return n.fee_schedule_key?.key&&n.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(o){const e=o instanceof Error?o.message:String(o);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){try{const t=await this.mirrorNode.getTopicMessages(e);return{messages:t.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(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(t){throw this.logger.error("Failed to fetch account",t),t}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t){this.logger.debug(`Retrieving profile for account: ${e}`);const r=`${e}-${this.network}`;if(!t){const t=ro.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Qr({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),o=await t.fetchProfileByAccountId(e,this.network);if(!o?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,o?.error),{profile:null,success:!1,error:o?.error||`Failed to retrieve profile for account ID: ${e}`};const n=o.profile;let i=null;o.topicInfo?.inboundTopic&&o.topicInfo?.outboundTopic&&o.topicInfo?.profileTopicId&&(i={inboundTopic:o.topicInfo.inboundTopic,outboundTopic:o.topicInfo.outboundTopic,profileTopicId:o.topicInfo.profileTopicId});const s={profile:n,topicInfo:i,success:!0};return ro.getInstance().set(r,s),s}catch(o){const e=`Failed to retrieve profile: ${o.message}`;return this.logger.error(e),{profile:null,success:!1,error:e}}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t){try{const r=await this.retrieveProfile(e,t);if(!r?.success)throw new Error(r.error||"Failed to retrieve profile");const o=r.profile;if(!o.inboundTopicId||!o.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!r.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return r.topicInfo}catch(r){const e=r,t=`Failed to retrieve topic info: ${e.message}`;throw this.logger.error(t),e}}async retrieveOutboundMessages(e){try{const t=await this.retrieveCommunicationTopics(e);if(!t)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(t.outboundTopic)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(t){const e=`Failed to retrieve outbound messages: ${t.message}`;return this.logger.error(e),[]}}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(r){const e=`Failed to check connection created: ${r.message}`;return this.logger.error(e),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new $r(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(r){const e=`Error resolving HRL reference: ${r.message}`;throw this.logger.error(e),new Error(e)}}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 $r(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(r){const e=`Error resolving HRL reference with type: ${r.message}`;throw this.logger.error(e),new Error(e)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const o=await this.getOperatorId(),n=r.accountId,i=await this.canSubmitToTopic(e,n);if(!i?.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a={p:"hcs-10",op:"connection_request",operator_id:o,m:t},c=i.requiresFee,u=await this.submitPayload(e,a,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(n);if(!l)throw new Error("Failed to retrieve outbound topic");const d=u.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`;return await this.submitPayload(l.outboundTopic,{...a,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:p}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:o,connectionTopicId:n,operatorId:i,memo:s}){const a={p:"hcs-10",op:"connection_created",connection_topic_id:n,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:o,connection_request_id:r,operator_id:i,m:s};return await this.submitPayload(e,a)}async waitForConnectionConfirmation(e,t,r=60,o=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let i=0;i<r;i++){this.logger.info(`Attempt ${i+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},o=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(o),a=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),n&&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}i<r-1&&(this.logger.info(`No matching confirmation found, waiting ${o}ms before retrying...`),await new Promise((e=>setTimeout(e,o))))}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");const o=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=o,o}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(":"),o=r?.[4];if(!o)throw new Error("Failed to retrieve topic info account ID");return o}clearCache(){ro.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 checkRegistrationStatus(e,t,r){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)throw new Error(`Failed to confirm registration: ${o.statusText}`);return await o.json()}catch(o){const e=o,t=`Error checking registration status: ${e.message}`;throw this.logger.error(t),e}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],o=t[1];if(!r)return!1;if(!o)return!1;const n=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!n.test(o)&&!!n.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e),o=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?o.slice(0,t):o}}class ro{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return ro.instance||(ro.instance=new ro),ro.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 oo extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class no extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class io extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class so extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class ao{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}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=zr.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===zr.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class co extends to{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.client="mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorAccountId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=Br(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t.privateKey),this.keyType=t.detectedType}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}this.network=e.network,this.logger=p.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Qr({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorAccountId),t=e?.key?._type;t.includes("ECDSA")?this.keyType="ecdsa":(t.includes("ED25519"),this.keyType="ed25519");const o="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorAccountId,o),{accountId:this.operatorAccountId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=r.PrivateKey.generateED25519(),o=(new r.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new r.Hbar(e));this.logger.debug("Executing account creation transaction");const n=await o.execute(this.client),i=(await n.getReceipt(this.client)).accountId;if(!i)throw this.logger.error("Account creation failed: accountId is null"),new no("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${i.toString()}`),{accountId:i.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,o){this.keyType||await this.initializeOperator();const n=this._generateHcs10Memo(eo.INBOUND,{accountId:e,ttl:r});let i,s;switch(t){case zr.PUBLIC:i=!1;break;case zr.CONTROLLED:i=!0;break;case zr.FEE_BASED:if(i=!1,!o)throw new Error("Fee configuration builder is required for fee-based topics");o.customFees.forEach((t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)})),s=o.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(n,!0,i,s)}async createAgent(e,t=60,r){this.keyType||await this.initializeOperator();const o=e.build();let n=r?.outboundTopicId||"",i=r?.inboundTopicId||"",s=r?.pfpTopicId||o.existingPfpTopicId||"",a=r?.profileTopicId||"";const c=this.client.operatorAccountId?.toString();if(!c)throw new Error("Failed to retrieve operator account ID");if(n)this.logger.info(`Using existing outbound topic ID: ${n}`);else{const e=this._generateHcs10Memo(eo.OUTBOUND,{ttl:t});n=await this.createTopic(e,!0,!0),this.logger.info(`Created new outbound topic ID: ${n}`)}if(i?this.logger.info(`Using existing inbound topic ID: ${i}`):(i=await this.createInboundTopic(c,o.inboundTopicType,t,o.inboundTopicType===zr.FEE_BASED?o.feeConfig:void 0),this.logger.info(`Created new inbound topic ID: ${i}`)),!s&&o.pfpBuffer&&o.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(o.pfpBuffer,o.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else s&&this.logger.info(`Using existing profile picture with topic ID: ${s}`);if(a)this.logger.info(`Using existing profile topic ID: ${a}`);else{a=(await this.storeHCS11Profile(o.name,o.bio,i,n,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s?o.pfpBuffer:void 0,o.pfpFileName,s)).profileTopicId,this.logger.info(`Profile stored with topic ID: ${a}`)}return{inboundTopicId:i,outboundTopicId:n,pfpTopicId:s,profileTopicId:a}}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(r){const e=r,t=`Error inscribing profile picture: ${e.message}`;return this.logger.error(t),{pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async storeHCS11Profile(e,t,r,o,n=[],i,s,a,c){try{let u=c||"";if(!u&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?u=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`),u=c);const l=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"}),d=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,n,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:i.properties,inboundTopicId:r,outboundTopicId:o,creator:i.creator}),f=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!f.success)throw this.logger.error(`Failed to inscribe profile: ${f.error}`),new Error(f.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${f.profileTopicId}, transaction ID: ${f.transactionId}`),{profileTopicId:f.profileTopicId,pfpTopicId:u,transactionId:f.transactionId,success:!0}}catch(u){const e=u,t=`Error storing HCS-11 profile: ${e.message}`;return this.logger.error(t),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async setupFees(e,t,o=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;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 i=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 r.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.feeTokenId)),t}return null})).filter(Boolean);if(0===i.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const s=[...t.exemptAccounts||[],...o];return s.length>0&&(n=await this.setupExemptKeys(e,s)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(i)}async setupExemptKeys(e,t){let r=e;const o=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let n=[];if(o.length>0)try{n=await Nr(o,this.network,this.logger)}catch(i){const e=`Error getting exempt keys: ${i.message}, continuing without exempt keys`;this.logger.warn(e)}return n.length>0&&(r=r.setFeeExemptKeys(n)),r}async handleConnectionRequest(e,t,o,n,i=60){const s=this._generateHcs10Memo(eo.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:o});this.logger.info(`Handling connection request ${o} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let c=await this.mirrorNode.getPublicKey(t);const u=await this.mirrorNode.getPublicKey(a);if(!u)throw new Error("Failed to retrieve public key");const l=new r.KeyList([u,c],1);let d;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};d=await this.createTopic(s,l,l,t)}else d=await this.createTopic(s,l,l);this.logger.info(`Created new connection topic ID: ${d}`)}catch(y){const e=`Failed to create connection topic: ${y}`;throw this.logger.error(e),new io(e)}const p=`${e}@${a}`,f=await this.confirmConnection(e,d,t,o,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(a),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:o,confirmedRequestId:f,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:f,operatorId:p}}async confirmConnection(e,t,r,o,n,i){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${o}`);const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:s,connection_id:o,m:n},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,a,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new so("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,o,n){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=JSON.stringify(s);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`,o=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!o?.topic_id)throw new Error("Failed to inscribe large message content");s.data=`hcs://1/${o.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${o.topic_id}`)}catch(c){const e=`Error inscribing large message: ${c.message}`;throw this.logger.error(e),new Error(e)}}return this.logger.info("Submitting message to connection topic",s),await this.submitPayload(e,s,o,i.requiresFee)}async createTopic(e,t,o,n){this.logger.info("Creating topic");const i=(new r.TopicCreateTransaction).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(i.setAdminKey(this.client.operatorPublicKey),i.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof r.PublicKey||t instanceof r.KeyList)&&(i.setAdminKey(t),this.client.operatorAccountId&&i.setAutoRenewAccountId(this.client.operatorAccountId))),o&&("boolean"==typeof o&&o&&this.client.operatorPublicKey?i.setSubmitKey(this.client.operatorPublicKey):(o instanceof r.PublicKey||o instanceof r.KeyList)&&i.setSubmitKey(o)),n&&await this.setupFees(i,n),this.logger.debug("Executing topic creation transaction");const s=await i.execute(this.client),a=await s.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,o,n=!1){const i="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(i,"utf8");if(s>1e3)throw new oo("Payload size exceeds 1000 bytes limit",s);const a=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(i);let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new r.Hbar(this.feeAmount))),o){const e=a.freezeWith(this.client),t=await e.sign(o);c=await t.execute(this.client)}else c=await a.execute(this.client);const u=await c.getReceipt(this.client);if(!u)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"),u}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.operatorPrivateKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const o=d.lookup(t)||"application/octet-stream",n=await Ar.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),i={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 vr({type:"buffer",buffer:e,fileName:t,mimeType:o},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},i,n);if(!s.confirmed||!s.inscription)throw new Error("Inscription was not confirmed");return s.inscription}async waitForConnectionConfirmation(e,t,r=60,o=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let i=0;i<r;i++){this.logger.info(`Attempt ${i+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},o=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(o),a=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),n&&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}i<r-1&&(this.logger.info(`No matching confirmation found, waiting ${o}ms before retrying...`),await new Promise((e=>setTimeout(e,o))))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.operatorPrivateKey):r.PrivateKey.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const o=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=o.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=o.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||o.existingAccount,!c)throw new Error("Cannot resume registration without account information");a=new co({network:o.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:r.PrivateKey.fromString(c.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),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:"))),r=e?.split(":")[1];r&&o.existingAccount?(c=o.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(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}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}}),a=new co({network:o.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:r.PrivateKey.fromString(c.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,l=s.inboundTopicId,d=s.pfpTopicId,p=s.profileTopicId;if(!u||!l||!p){d&&e.setExistingProfilePicture(d);const t=await a.createAgent(e,60,s);u=t.outboundTopicId,l=t.inboundTopicId,d=t.pfpTopicId,p=t.profileTopicId,s.outboundTopicId=u,s.inboundTopicId=l,s.pfpTopicId=d,s.profileTopicId=p,s.createdResources||(s.createdResources=[]),d&&!s.createdResources.includes(`pfp:${d}`)&&s.createdResources.push(`pfp:${d}`),s.createdResources.includes(`inbound:${l}`)||s.createdResources.push(`inbound:${l}`),s.createdResources.includes(`outbound:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${p}`)||s.createdResources.push(`profile:${p}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,inboundTopicId:l,pfpTopicId:d,profileTopicId:p}})}const u=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,o.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:u,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:u,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:u,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(o){const e=o,r=`Failed to create and register agent: ${e.message}`;return this.logger.error(r),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,o){try{this.logger.info("Registering agent with guarded registry");const n=o?.maxAttempts??60,i=o?.delayMs??2e3,s=o?.progressCallback;let a=o?.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=r.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 u=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,i,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:u,transactionId:c.transactionId,state:a}}),{...c,confirmed:u,state:a}}catch(n){const e=n,t=`Failed to register agent: ${e.message}`;return this.logger.error(t),{error:e.message,success:!1}}}async registerAgent(e,t,r,o,n){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:o};await this.submitPayload(e,i,n)}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 zr.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`),zr.FEE_BASED}return zr.CONTROLLED}catch(t){const e=`Error determining topic type: ${t.message}`;throw this.logger.error(e),new Error(e)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,o,n){this.logger.info("Creating scheduled transaction");const i=(new r.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?r.AccountId.fromString(n):this.client.operatorAccountId);if(t&&i.setScheduleMemo(t),o){const e=u.addSeconds(new Date,o),t=r.Timestamp.fromDate(e);i.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const s=await i.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,o,n){const i=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:n?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,o,i.requiresFee)}async sendTransaction(e,t,r,o){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:n,transactionId:i}=await this.createScheduledTransaction(t,o?.scheduleMemo,o?.expirationTime,o?.schedulePayerAccountId);return{scheduleId:n,transactionId:i,receipt:await this.sendTransactionOperation(e,n,r,o?.submitKey,{memo:o?.operationMemo})}}}const uo="undefined"!=typeof window;var lo=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(lo||{});class po{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new Rr(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,o,n=[]){return new po({network:r,logger:o,defaultCollectorAccountId:t}).addHbarFee(e,t,n)}static async forToken(e,t,r,o,n,i=[],s){const a=new po({network:o,logger:n,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,i),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||"",feeTokenId:void 0,exemptAccounts:[...r],type:lo.FIXED_FEE}),this}async addTokenFee(e,t,r,o,n=[]){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 i=o;if(void 0===i)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(i=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${i}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),i=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),i=0}return this.customFees.push({feeAmount:{amount:e*10**i,decimals:i},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...n],type:lo.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;return this.customFees.forEach((t=>{t.exemptAccounts.forEach((t=>e.add(t)))})),{customFees:this.customFees,exemptAccounts:Array.from(e)}}}exports.AIAgentCapability=jr,exports.AIAgentType=qr,exports.AccountCreationError=no,exports.AgentBuilder=ao,exports.BrowserHCSClient=class extends to{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}),uo)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Qr({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(r){this.logger.warn(`Failed to initialize HCS11Client: ${r}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,o,n){this.logger.info("Sending message");const i={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(i);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`,o=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!o?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${o.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${o.topic_id}`)}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,i,o,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,o,n="Connection accepted. Looking forward to collaborating!",i=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 u=new r.KeyList([c,a],1),l=this._generateHcs10Memo(eo.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:o}),d=(new r.TopicCreateTransaction).setTopicMemo(l).setAutoRenewAccountId(r.AccountId.fromString(s)).setAdminKey(u).setSubmitKey(u);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 f=p?.result;if(!f?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const h=f.topicId.toString(),g=`${e}@${s}`,m=await this.confirmConnection(e,h,t,o,g,n),y=await this.retrieveCommunicationTopics(s),w=await this.retrieveCommunicationTopics(t),b=`${w.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:w.outboundTopic,connectionRequestId:o,confirmedRequestId:m,connectionTopicId:h,operatorId:b,memo:`Connection established with ${t}`}),{connectionTopicId:h,confirmedConnectionSequenceNumber:m,operatorId:g}}async confirmConnection(e,t,r,o,n,i){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:n,connection_id:o,m:i},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,o=new Sr({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof ao;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");o.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const{inboundTopicId:i,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,o);let c,u,l;if(n=a,r||(e.setInboundTopicId(i),e.setOutboundTopicId(s)),r){const t=e.build();c=t.existingPfpTopicId||n.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=n.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,n,o):c&&(o.preparing(`Using existing profile picture: ${c}`,50,{state:n}),n.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,n,i,s,t,o),n.currentStage="complete",n.completedPercentage=100,o.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:i,outboundTopicId:s,pfpTopicId:c,state:n});let d="";n.outboundTopicId&&(d=n.outboundTopicId);let p="";n.inboundTopicId&&(p=n.inboundTopicId);let f="";n.pfpTopicId&&(f=n.pfpTopicId);let h="";return n.profileTopicId&&(h=n.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:f,profileTopicId:h,success:!0,state:n}}catch(n){return o.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async handleProfilePictureCreation(e,t,r,o){r.currentStage="pfp",o.preparing("Creating profile picture",30,{state:r});const n=o.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),i=await this.inscribePfp(e,t,{progressCallback:e=>n.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!i.success){let e="Failed to inscribe profile picture";throw i.error&&(e=i.error),new Error(e)}const s=i.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),o.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,o,n,i,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"),o.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:o});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let u;if(e){const e=t.build(),o=e.metadata?.socials?Object.entries(e.metadata.socials).map((([e,t])=>({platform:e,handle:t}))):[];u=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:o,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:i,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:o,pfpFileName:s,...a}=e;u=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:n,outboundTopicId:i})}const l=await this.hcs11Client.createAndInscribeProfile(u,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??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)}o.profileTopicId=l.profileTopicId,o.createdResources&&o.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:o})}}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,o){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,i=this.initializeRegistrationState(n,o?.existingState),s=new Sr({module:"AgentRegistration",logger:this.logger,callback:o?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:i};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=r.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:i};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const c=o?.maxAttempts??60,u=o?.delayMs??2e3,l=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,u,this.logger);return this.updateStateForCompletedRegistration(i,n),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:i,confirmed:l}),{...a,confirmed:l,state:i}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),o=t?.progressCallback,n=new Sr({module:"AgentCreateRegister",logger:this.logger,callback:o});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,n.preparing("Starting agent creation process",0,{state:i}),"complete"!==i.currentStage||!i.inboundTopicId||!i.outboundTopicId||!i.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},existingState:i,updateAccountMemo:!1});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");i=t.state,i.agentMetadata=r.metadata}n.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:s}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:i});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");i=e.state,i.profileTopicId&&await(this.hcs11Client?.updateAccountMemoWithProfile(s,i.profileTopicId))}return n.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:s,operatorId:`${i.inboundTopicId}@${s}`,inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,profileTopicId:i.profileTopicId,pfpTopicId:i.pfpTopicId,privateKey:null,...i.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,o,n=[],i={},s,a,c,u){try{const l=u?.progressCallback,d=new Sr({module:"StoreHCS11Profile",logger:this.logger,callback:l});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 f=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const h=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,g=this.hcs11Client.createAIAgentProfile(e,f,n,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:h,properties:{version:i.version||"1.0.0",creator:i.creator||"Unknown",supported_languages:i.supported_languages||["en"],permissions:i.permissions||[],model_details:i.model_details,training:i.training,capabilities_description:i.capabilities_description,...i},inboundTopicId:r,outboundTopicId:o,creator:i.creator}),m=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(g,!0,{progressCallback:e=>{m.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(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,o){this.logger.info("Creating topic");const{accountId:n,signer:i}=this.getAccountAndSigner(),s=(new r.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(n)),o&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),u=c.error;if(u)return this.logger.error(u),{success:!1,error:u};const l=c.result;return l?.topicId?{success:!0,topicId:l.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,o,n){let i;this.logger.debug(`Submitting payload to topic ${e}`),i="string"==typeof t?t:JSON.stringify(t);const s=(new r.TopicMessageSubmitTransaction).setTopicId(e).setMessage(i);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new r.Hbar(this.feeAmount))),o){const{accountId:e,signer:t}=this.getAccountAndSigner();s.freezeWithSigner(t);const r=await s.sign(o);a=await this.hwc.executeTransactionWithErrorHandling(r,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(a?.error)throw this.logger.error(`Failed to submit payload: ${a.error}`),new Error(`Failed to submit payload: ${a.error}`);if(!a?.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"),a.result}async inscribeFile(e,t,r){const{accountId:o,signer:n}=this.getAccountAndSigner(),i=d.lookup(t)||"application/octet-stream",s=await Ar.createWithAuth({type:"client",accountId:o,signer:n,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 xr({type:"buffer",buffer:e,fileName:t,mimeType:i},n,{...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 o=r?.progressCallback,n=new Sr({module:"PFP-Inscription",logger:this.logger,callback:o});if(!this.hcs11Client)return n.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};n.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{n.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:i});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 n.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(o){return this.logger.error(`Error inscribing profile picture: ${o.message}`),{pfpTopicId:"",success:!1,error:o.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:o}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const n=this._generateHcs10Memo(eo.OUTBOUND,{ttl:e?.ttl,accountId:o}),i=await this.createTopic(n,!0,!0);if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create outbound topic");r.outboundTopicId=i.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 n=this._generateHcs10Memo(eo.INBOUND,{ttl:e?.ttl,accountId:o}),i=await this.createTopic(n,!0,!1);if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create inbound topic");r.inboundTopicId=i.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.ConnectionConfirmationError=so,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=new p(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[o,n]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(o.messages||[],e),this.processInboundMessages(n.messages||[]);const i=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${o.messages?.length||0} outbound and ${n.messages?.length||0} inbound messages. Found ${i} 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[o,n]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(o)).messages||[];let r=!1;for(const e of n){const o=e.connectionRequestId;if(!o)continue;const n=t.find((t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==o)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const o=r[1];if(t.operator_id&&t.operator_id===o)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0}));if(n?.connection_topic_id){r=!0;const t=n.connection_topic_id;let i=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||e.created),profileInfo:e.profileInfo,connectionRequestId:o,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),i&&this.connections.delete(i),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 ${o}:`,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 n of r){if(this.logger.debug(`Processing pending connection: ${n.connectionTopicId}`),!n.targetAccountId){this.logger.debug(`Skipping connection ${n.connectionTopicId} - no targetAccountId`);continue}let e=n.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(n.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${n.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(n.connectionTopicId,{...n,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${n.connectionTopicId} with inbound topic ID: ${e}`)}catch(o){this.logger.debug(`Error fetching profile for ${n.targetAccountId}: ${o}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=n.connectionRequestId||n.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),o=(r.messages||[]).find((e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id));if(o?.connection_topic_id){const e=o.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${n.targetAccountId} on their inbound topic`),this.connections.set(n.connectionTopicId,{...n,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||n.created),lastActivity:new Date(o.created||n.created)})}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(o){this.logger.warn(`Error checking for confirmations on target inbound topic for ${n.targetAccountId}: ${o}`)}else this.logger.debug(`Skipping connection ${n.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 o of r){const e={...o,targetInboundTopicId:t.inboundTopicId};this.connections.set(o.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 i of r){const e=i.connection_request_id,r=i.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(r),n=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out outbound request to account: ${o}`);continue}const s=Array.from(this.connections.values()).some((t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===o)),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:i.outbound_topic_id||"",targetAccountId:o,targetTopicId:n,operatorId:r,sequenceNumber:i.sequence_number,created:i.created||new Date,memo:i.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:o,targetInboundTopicId:n,status:"pending",isPending:!0,needsConfirmation:!1,created:i.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m};this.connections.set(a,t)}}}const o=e.filter((e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id));for(const i of o){const e=i.connection_request_id,t=i.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(i.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const o=`req-${e}:${i.operator_id}`,n=this.pendingRequests.get(o);if(n&&(n.status="confirmed"),this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:o,originTopicId:i.outbound_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,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:o,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m})}const n=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const i of n){const e=i.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=i.connection_request_id&&i.operator_id?`req-${i.connection_request_id}:${i.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:i.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:i.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 o of t){const e=o.sequence_number,t=o.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(t),i=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out request from account: ${n}`);continue}const s=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${n} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:n,targetInboundTopicId:i,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:o.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:i,processed:!1,memo:o.m})}for(const o of r){const e=o.connection_id,t=o.connection_topic_id,r=o.connected_account_id||"",n=o.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const i=`inb-${e}:${n}`;if(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,inboundRequestId:e,uniqueRequestKey:i,originTopicId:o.connection_topic_id,processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,inboundRequestId:e,uniqueRequestKey:i,originTopicId:o.connection_topic_id,processed:!1,memo:o.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 o=t.find((e=>"close_connection"===e.op));if(o){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:o.created||new Date,closedReason:o.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 o of r)this.connections.set(o.connectionTopicId,{...o,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[o,n]of this.connections.entries())n.originTopicId===e&&n.inboundRequestId===t&&(this.connections.set(o,{...n,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),n.originTopicId===e&&n.connectionRequestId===t&&(this.connections.set(o,{...n,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 o=await this.baseClient.getTransactionRequests(e,t),n=[];for(const e of o)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||n.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),n.push(e)}return n}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}async getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const{messages:r}=await this.baseClient.getMessageStream(e),o=r.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===o.length)return;return o.sort(((e,t)=>t.created.getTime()-e.created.getTime())),o[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}},exports.CustomFeeType=lo,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 f,this.logger=p.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let n={...t};const i={};for(const a of e){const e=`${a.c.contractAddress}-${a.c.abi.name}`,t=await this.cache.get(e);if(t)i[a.c.abi.name]=JSON.parse(t),Object.assign(n,i[a.c.abi.name]);else try{const t=new o.ethers.Interface([{...a.c.abi}]),s=t.encodeFunctionData(a.c.abi.name),c=r.ContractId.fromSolidityAddress(a.c.contractAddress),u=await this.readFromMirrorNode(s,r.AccountId.fromString("0.0.800"),c);if(this.logger.info(`Result for ${a.c.contractAddress}:`,u?.result),!u?.result){this.logger.warn(`Failed to get result from mirror node for ${a.c.contractAddress}`),i[a.c.abi.name]="0",Object.assign(n,i[a.c.abi.name]);continue}const l=t?.decodeFunctionResult(a.c.abi.name,u.result);let d={values:[]};l&&a.c.abi.outputs?.forEach(((e,t)=>{const r=h(l[t],e.type);d.values.push(r),e.name&&(d[e.name]=r)})),await this.cache.set(e,JSON.stringify(d)),i[a.c.abi.name]=d,n[a.c.abi.name]=d}catch(s){this.logger.error(`Error executing command for ${a.c.contractAddress}:`,s),i[a.c.abi.name]="0",Object.assign(n,i[a.c.abi.name])}}return{results:i,stateData:n}}async executeCommand(e,t={}){const{results:r,stateData:o}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:o}}async readFromMirrorNode(e,t,r){try{const o=r.toSolidityAddress(),n=t.toSolidityAddress(),i=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:n.startsWith("0x")?n:`0x${n}`,to:o?.startsWith("0x")?o:`0x${o}`,value:0})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}catch(o){return this.logger.error("Error reading from mirror node:",o),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=Kr,exports.FeeConfigBuilder=po,exports.HCS=class{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 o=e.dataset[t];"true"===o&&(o=!0),"false"===o&&(o=!1),isNaN(Number(o))||""===o||(o=Number(o)),this.config[r]=o}})),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(o){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 o}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const o=r.replace(/['"]+/g,""),n=await this.fetchWithRetry(t+e+"?network="+o);return await n.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.getAttribute("type"),i=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(o||"")){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(o,t,a);if("wasm"===n){const t=await c.arrayBuffer(),o=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(o,{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 "+n+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(a){if(this.error("Failed to load "+n+": "+r,a),this.updateLoadingStatus(r,"failed"),i)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{return await import(r)}catch(o){throw this.error("Failed to import module",o),o}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),o=t?.split("/").pop(),n=e.hasAttribute("data-required");if(!this.isDuplicate(o||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,t,n),s=await i.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(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),n)throw i}}}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,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(r,t,o),i=URL.createObjectURL(n);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(o){this.error("Failed to load image: "+r,o),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),o=r?.split("/").pop();this.log("Loading "+t+": "+o),this.updateLoadingStatus(t+": "+o,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(o,r,n),s=URL.createObjectURL(i);e.src=s,"video"===t?this.LoadedVideos[o]=s:this.LoadedAudioUrls[o]=s,this.updateLoadingStatus(t+": "+o,"loaded"),this.log("Loaded "+t+": "+o)}catch(n){this.error("Failed to load "+t+": "+o,n),this.updateLoadingStatus(t+": "+o,"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,o=e.getAttribute("data-network")||this.config.network;let n;"model-viewer"!==e.tagName.toLowerCase()?(n=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{n.setAttribute(e.name,e.value)})),n.setAttribute("camera-controls",""),n.setAttribute("auto-rotate",""),n.setAttribute("ar",""),e.parentNode?.replaceChild(n,e)):n=e;const i=await this.retrieveHCS1Data(r,t,o),s=URL.createObjectURL(i);n.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(o){this.error("Failed to load GLB: "+r,o),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((o=>{this.loadQueue.push({element:e,type:t,order:r,resolve:o}),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 n=t.substring(r,e),i=n.split("/").pop();try{const o=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(i,o,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+n+" with "+c)}catch(o){this.error("Failed to load CSS image: "+i,o)}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://"]'),o=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),n=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=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:o,type:"video"},{elements:n,type:"audio"},{elements:i,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(),o=t.getAttribute("src");switch(o?.startsWith("hcs://")&&(t.setAttribute("data-src",o),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 o=new Audio(r);o.volume=t,this.LoadedAudios[e]=o,o.play().catch((e=>{console.error("Failed to play audio:",e)})),o.addEventListener("ended",(()=>{o.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 o=document.querySelector('audio[data-topic-id="'+e+'"]');if(o)o.volume=r,await o.play();else{const n=document.createElement("audio");n.volume=r,t&&n.setAttribute("autoplay","autoplay"),n.setAttribute("data-topic-id",e),n.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(n),await this.loadMedia(n,"audio"),o=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await o.play()}}},exports.HCS10BaseClient=to,exports.HCS10Cache=ro,exports.HCS10Client=co,exports.HCS11Client=Qr,exports.HRLResolver=$r,exports.Hcs10MemoType=eo,exports.HederaMirrorNode=Rr,exports.InboundTopicType=zr,exports.Logger=p,exports.PayloadSizeError=oo,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.ProfileType=Mr,exports.ProgressReporter=Sr,exports.Registration=Zr,exports.SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.TopicCreationError=io,exports.TransactionParser=class{static parseTransactionBody(e){try{const t=o.ethers.decodeBase64(e),n=i.proto.SchedulableTransactionBody.decode(t),s=this.getTransactionType(n),a={type:s,humanReadableType:this.getHumanReadableType(s),transfers:[],tokenTransfers:[],raw:n};if(n.memo&&(a.memo=n.memo),n.transactionFee){const e=r.Hbar.fromTinybars(r.Long.fromValue(n.transactionFee));a.transactionFee=e.toString(r.HbarUnit.Hbar)}return n.cryptoTransfer&&Dr.parseCryptoTransfers(n.cryptoTransfer,a),n.cryptoDelete&&(a.cryptoDelete=Dr.parseCryptoDelete(n.cryptoDelete)),n.cryptoCreateAccount&&(a.cryptoCreateAccount=Dr.parseCryptoCreateAccount(n.cryptoCreateAccount)),n.cryptoUpdateAccount&&(a.cryptoUpdateAccount=Dr.parseCryptoUpdateAccount(n.cryptoUpdateAccount)),n.cryptoApproveAllowance&&(a.cryptoApproveAllowance=Dr.parseCryptoApproveAllowance(n.cryptoApproveAllowance)),n.cryptoDeleteAllowance&&(a.cryptoDeleteAllowance=Dr.parseCryptoDeleteAllowance(n.cryptoDeleteAllowance)),n.contractCall&&(a.contractCall=Or.parseContractCall(n.contractCall)),n.contractCreateInstance&&(a.contractCreate=Or.parseContractCreate(n.contractCreateInstance)),n.contractUpdateInstance&&(a.contractUpdate=Or.parseContractUpdate(n.contractUpdateInstance)),n.contractDeleteInstance&&(a.contractDelete=Or.parseContractDelete(n.contractDeleteInstance)),n.tokenCreation&&(a.tokenCreation=Fr.parseTokenCreate(n.tokenCreation)),n.tokenMint&&(a.tokenMint=Fr.parseTokenMint(n.tokenMint)),n.tokenBurn&&(a.tokenBurn=Fr.parseTokenBurn(n.tokenBurn)),n.tokenUpdate&&(a.tokenUpdate=Fr.parseTokenUpdate(n.tokenUpdate)),n.tokenFeeScheduleUpdate&&(a.tokenFeeScheduleUpdate=Fr.parseTokenFeeScheduleUpdate(n.tokenFeeScheduleUpdate)),n.tokenFreeze&&(a.tokenFreeze=Fr.parseTokenFreeze(n.tokenFreeze)),n.tokenUnfreeze&&(a.tokenUnfreeze=Fr.parseTokenUnfreeze(n.tokenUnfreeze)),n.tokenGrantKyc&&(a.tokenGrantKyc=Fr.parseTokenGrantKyc(n.tokenGrantKyc)),n.tokenRevokeKyc&&(a.tokenRevokeKyc=Fr.parseTokenRevokeKyc(n.tokenRevokeKyc)),n.tokenPause&&(a.tokenPause=Fr.parseTokenPause(n.tokenPause)),n.tokenUnpause&&(a.tokenUnpause=Fr.parseTokenUnpause(n.tokenUnpause)),n.tokenWipe&&(a.tokenWipeAccount=Fr.parseTokenWipeAccount(n.tokenWipe)),n.tokenDeletion&&(a.tokenDelete=Fr.parseTokenDelete(n.tokenDeletion)),n.tokenAssociate&&(a.tokenAssociate=Fr.parseTokenAssociate(n.tokenAssociate)),n.tokenDissociate&&(a.tokenDissociate=Fr.parseTokenDissociate(n.tokenDissociate)),n.consensusCreateTopic&&(a.consensusCreateTopic=_r.parseConsensusCreateTopic(n.consensusCreateTopic)),n.consensusSubmitMessage&&(a.consensusSubmitMessage=_r.parseConsensusSubmitMessage(n.consensusSubmitMessage)),n.consensusUpdateTopic&&(a.consensusUpdateTopic=_r.parseConsensusUpdateTopic(n.consensusUpdateTopic)),n.consensusDeleteTopic&&(a.consensusDeleteTopic=_r.parseConsensusDeleteTopic(n.consensusDeleteTopic)),n.fileCreate&&(a.fileCreate=Lr.parseFileCreate(n.fileCreate)),n.fileAppend&&(a.fileAppend=Lr.parseFileAppend(n.fileAppend)),n.fileUpdate&&(a.fileUpdate=Lr.parseFileUpdate(n.fileUpdate)),n.fileDelete&&(a.fileDelete=Lr.parseFileDelete(n.fileDelete)),n.utilPrng&&(a.utilPrng=Ur.parseUtilPrng(n.utilPrng)),a}catch(t){throw new Error(`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`)}}static parseScheduleResponse(e){if(!e.transaction_body)throw new Error("Schedule response missing transaction_body");const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){let t="unknown";return e.cryptoTransfer?t="cryptoTransfer":e.cryptoCreateAccount?t="cryptoCreateAccount":e.cryptoUpdateAccount?t="cryptoUpdateAccount":e.cryptoApproveAllowance?t="cryptoApproveAllowance":e.cryptoDeleteAllowance?t="cryptoDeleteAllowance":e.cryptoDelete?t="cryptoDelete":e.consensusCreateTopic?t="consensusCreateTopic":e.consensusUpdateTopic?t="consensusUpdateTopic":e.consensusSubmitMessage?t="consensusSubmitMessage":e.consensusDeleteTopic?t="consensusDeleteTopic":e.fileCreate?t="fileCreate":e.fileAppend?t="fileAppend":e.fileUpdate?t="fileUpdate":e.fileDelete?t="fileDelete":e.contractCall?t="contractCall":e.contractCreateInstance?t="contractCreate":e.contractUpdateInstance?t="contractUpdate":e.contractDeleteInstance?t="contractDelete":e.tokenCreation?t="tokenCreate":e.tokenUpdate?t="tokenUpdate":e.tokenDeletion?t="tokenDelete":e.tokenAssociate?t="tokenAssociate":e.tokenDissociate?t="tokenDissociate":e.tokenMint?t="tokenMint":e.tokenBurn?t="tokenBurn":e.tokenFeeScheduleUpdate?t="tokenFeeScheduleUpdate":e.tokenFreeze?t="tokenFreeze":e.tokenUnfreeze?t="tokenUnfreeze":e.tokenGrantKyc?t="tokenGrantKyc":e.tokenRevokeKyc?t="tokenRevokeKyc":e.tokenPause?t="tokenPause":e.tokenUnpause?t="tokenUnpause":e.tokenWipe?t="tokenWipe":e.utilPrng&&(t="utilPrng"),t}static getHumanReadableType(e){const t={cryptoTransfer:"HBAR Transfer",cryptoCreateAccount:"Create Account",cryptoUpdateAccount:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoApproveAllowance:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",cryptoDelete:"Delete Account",consensusCreateTopic:"Create Topic",consensusUpdateTopic:"Update Topic",consensusSubmitMessage:"Submit Message",consensusDeleteTopic:"Delete Topic",fileCreate:"Create File",fileAppend:"Append File",fileUpdate:"Update File",fileDelete:"Delete File",contractCall:"Contract Call",contractCreate:"Create Contract",contractUpdate:"Update Contract",contractDelete:"Delete Contract",ethereumTransaction:"Ethereum Transaction",tokenCreate:"Create Token",tokenUpdate:"Update Token",tokenDelete:"Delete Token",tokenAssociate:"Associate Token",tokenDissociate:"Dissociate Token",tokenMint:"Mint Token",tokenBurn:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",tokenUnfreeze:"Unfreeze Token",tokenGrantKyc:"Grant KYC",tokenRevokeKyc:"Revoke KYC",tokenPause:"Pause Token",tokenUnpause:"Unpause Token",tokenWipe:"Wipe Token",scheduleCreate:"Create Schedule",scheduleSign:"Sign Schedule",utilPrng:"Generate Random Number",unknown:"Unknown Transaction"};let r;return r=t[e]?t[e]:"Unknown Transaction",r}static getTransactionSummary(e){if("cryptoTransfer"===e.type){const t=[],r=[];for(const o of e.transfers){const e=parseFloat(o.amount);let n=o.amount;n.startsWith("-")&&(n=n.substring(1)),n=n.replace(/\s*ℏ$/,""),e<0?t.push(`${o.accountId} (${n} ℏ)`):e>0&&r.push(`${o.accountId} (${n} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType}if(e.contractCall){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}if(e.tokenMint)return`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`;if(e.tokenBurn)return`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`;if(e.tokenCreation){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?.length&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t}if(e.tokenTransfers.length>0){const t={};for(const o of e.tokenTransfers)t[o.tokenId]||(t[o.tokenId]=[]),t[o.tokenId].push(o);const r=[];for(const[e,o]of Object.entries(t)){const t=[],n=[];for(const e of o){const r=parseFloat(e.amount.toString());r<0?t.push(`${e.accountId} (${Math.abs(r)})`):r>0&&n.push(`${e.accountId} (${r})`)}t.length>0&&n.length>0&&r.push(`Transfer of token ${e} from ${t.join(", ")} to ${n.join(", ")}`)}return r.length>0?r.join("; "):e.humanReadableType}if(e.consensusCreateTopic){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}if(e.consensusSubmitMessage){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: ${s.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`;return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t}if(e.fileCreate){let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t}if(e.fileAppend)return`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`;if(e.fileUpdate)return`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`;if(e.fileDelete)return`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`;if(e.consensusUpdateTopic)return`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`;if(e.consensusDeleteTopic)return`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`;if(e.tokenUpdate)return`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`;if(e.tokenFeeScheduleUpdate)return`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`;if(e.utilPrng){let t="Generate Random Number";return e.utilPrng.range&&e.utilPrng.range>0&&(t+=` (range up to ${e.utilPrng.range-1})`),t}if(e.tokenFreeze)return`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`;if(e.tokenUnfreeze)return`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`;if(e.tokenGrantKyc)return`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`;if(e.tokenRevokeKyc)return`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`;if(e.tokenPause)return`Pause Token ${e.tokenPause.tokenId}`;if(e.tokenUnpause)return`Unpause Token ${e.tokenUnpause.tokenId}`;if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers?.length&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}if(e.tokenDelete)return`Delete Token ${e.tokenDelete.tokenId}`;if(e.tokenAssociate)return`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${e.tokenAssociate.tokenIds?.join(", ")}`;if(e.tokenDissociate)return`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${e.tokenDissociate.tokenIds?.join(", ")}`;if(e.cryptoDelete)return`Delete Account ${e.cryptoDelete.deleteAccountId}`;if(e.cryptoCreateAccount){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}if(e.cryptoUpdateAccount)return`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`;if(e.cryptoApproveAllowance){return`Approve ${(e.cryptoApproveAllowance.hbarAllowances?.length||0)+(e.cryptoApproveAllowance.tokenAllowances?.length||0)+(e.cryptoApproveAllowance.nftAllowances?.length||0)} Crypto Allowance(s)`}if(e.cryptoDeleteAllowance)return`Delete ${e.cryptoDeleteAllowance.nftAllowancesToRemove?.length||0} NFT Crypto Allowance(s)`;if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}if(e.contractUpdate)return`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`;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}if(e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType)return e.humanReadableType;if(e.tokenTransfers.length>0){const t={};for(const o of e.tokenTransfers)t[o.tokenId]||(t[o.tokenId]=[]),t[o.tokenId].push(o);const r=[];for(const[e,o]of Object.entries(t)){const t=o.filter((e=>e.amount<0)).map((e=>`${e.accountId} (${Math.abs(e.amount)})`)),n=o.filter((e=>e.amount>0)).map((e=>`${e.accountId} (${e.amount})`));t.length>0&&n.length>0?r.push(`Transfer of token ${e} from ${t.join(", ")} to ${n.join(", ")}`):n.length>0?r.push(`Token ${e} received by ${n.join(", ")}`):t.length>0&&r.push(`Token ${e} sent from ${t.join(", ")}`)}if(r.length>0)return r.join("; ")}return"Unknown Transaction"}},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),o=t(r.length,1);return this.getUint8Memory().set(r,o),this.WASM_VECTOR_LEN=r.length,o}let o=this.textEncoder.encode(e).length,n=t(o,1);const i=this.getUint8Memory();let s=0;for(;s<o;s++){const t=e.charCodeAt(s);if(t>127)break;i[n+s]=t}if(s!==o){0!==s&&(e=e.slice(s)),n=r(n,o,o=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+s,n+o);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,n}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 o=[0,0];try{const n=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,n);const i=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return o=[i,s],this.getStringFromWasm(i,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(o[0],o[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const o=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${o}`),new Error(o)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const o=await WebAssembly.instantiate(t,r);return this.wasm=o.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(o){throw this.logger.error("Failed to initialize WASM module",o),o}}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,o])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,o])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(o)}))),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.accountIdsToExemptKeys=Nr,exports.capabilityNameToCapabilityMap=Wr,exports.detectKeyTypeFromString=Br,exports.inscribe=vr,exports.inscribeWithSigner=xr,exports.process$1=H,exports.retrieveInscription=async function(e,t){const r=p.getInstance({module:"Inscriber",...t?.logging||{}}),o=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:o});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new Ar({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 Ar.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:o,network:t.network||"mainnet"});const n=await e.retrieveInscription(o);return r.info("Successfully retrieved inscription",{formattedTransactionId:o}),n}catch(n){throw r.error("Error retrieving inscription",{formattedTransactionId:o,error:n}),n}},exports.sleep=e=>new Promise((t=>setTimeout(t,e))),exports.waitForInscriptionConfirmation=Cr;
|
|
11
|
+
//# sourceMappingURL=index-CHS2J8pS.cjs.map
|