@hashgraphonline/standards-sdk 0.0.112-canary.0 → 0.0.112-canary.2
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/index-BjSZGzAb.cjs +11 -0
- package/dist/cjs/index-BjSZGzAb.cjs.map +1 -0
- package/dist/cjs/{index-CHar8dVv-CUVf-if8.cjs → index-CHar8dVv-CRh6n7ac.cjs} +2 -2
- package/dist/cjs/{index-CHar8dVv-CUVf-if8.cjs.map → index-CHar8dVv-CRh6n7ac.cjs.map} +1 -1
- package/dist/cjs/services/mirror-node.d.ts +35 -16
- package/dist/cjs/services/mirror-node.d.ts.map +1 -1
- package/dist/cjs/services/types.d.ts +3 -3
- package/dist/cjs/services/types.d.ts.map +1 -1
- package/dist/cjs/standards-sdk.cjs +1 -1
- package/dist/es/services/mirror-node.d.ts +35 -16
- package/dist/es/services/mirror-node.d.ts.map +1 -1
- package/dist/es/services/types.d.ts +3 -3
- package/dist/es/services/types.d.ts.map +1 -1
- package/dist/es/standards-sdk.es21.js +170 -102
- package/dist/es/standards-sdk.es21.js.map +1 -1
- package/dist/umd/services/mirror-node.d.ts +35 -16
- package/dist/umd/services/mirror-node.d.ts.map +1 -1
- package/dist/umd/services/types.d.ts +3 -3
- package/dist/umd/services/types.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-BmPzMkW9.cjs +0 -11
- package/dist/cjs/index-BmPzMkW9.cjs.map +0 -1
|
@@ -146,7 +146,7 @@ read:function(e,t,r,n,o){var i,a,s=8*o-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?o-1:0,h=r?
|
|
|
146
146
|
* Copyright(c) 2014 Jonathan Ong
|
|
147
147
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
148
148
|
* MIT Licensed
|
|
149
|
-
*/function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,o=requireMimeDb(),i=requirePathBrowserify().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),r=t&&o[t[1].toLowerCase()];return r&&r.charset?r.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var r=-1===t.indexOf("/")?e.lookup(t):t;if(!r)return!1;if(-1===r.indexOf("charset")){var n=e.charset(r);n&&(r+="; charset="+n.toLowerCase())}return r},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var r=a.exec(t),n=r&&e.extensions[r[1].toLowerCase()];if(!n||!n.length)return!1;return n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var r=i("x."+t).toLowerCase().substr(1);if(!r)return!1;return e.types[r]||!1},e.types=Object.create(null),t=e.extensions,r=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach((function(e){var i=o[e],a=i.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(r[c]){var u=n.indexOf(o[r[c]].source),l=n.indexOf(i.source);if("application/octet-stream"!==r[c]&&(u>l||u===l&&"application/"===r[c].substr(0,12)))continue}r[c]=e}}}))}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes(),util$1,util2,objectUtil,objectUtil2;util2=util$1||(util$1={}),util2.assertEqual=e=>e,util2.assertIs=function(e){},util2.assertNever=function(e){throw new Error},util2.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},util2.getValidEnumValues=e=>{const t=util2.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),r={};for(const n of t)r[n]=e[n];return util2.objectValues(r)},util2.objectValues=e=>util2.objectKeys(e).map((function(t){return e[t]})),util2.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},util2.find=(e,t)=>{for(const r of e)if(t(r))return r},util2.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,util2.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},util2.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,objectUtil2=objectUtil||(objectUtil={}),objectUtil2.mergeShapes=(e,t)=>({...e,...t});const ZodParsedType=util$1.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=e=>{switch(typeof e){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(e)?ZodParsedType.array:null===e?ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util$1.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const o of e.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)r._errors.push(t(o));else{let e=r,n=0;for(;n<o.path.length;){const r=o.path[n];n===o.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(o))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util$1.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let r;switch(e.code){case ZodIssueCode.invalid_type:r=e.received===ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,util$1.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$1.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$1.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util$1.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:util$1.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ZodIssueCode.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case ZodIssueCode.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=t.defaultError,util$1.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function setErrorMap(e){overrideErrorMap=e}function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],a={...o,path:i};if(void 0!==o.message)return{...o,path:i,message:o.message};let s="";const c=n.filter((e=>!!e)).slice().reverse();for(const u of c)s=u(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}},EMPTY_PATH=[];function addIssueToContext(e,t){const r=getErrorMap(),n=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter((e=>!!e))});e.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const e=await n.key,t=await n.value;r.push({key:e,value:t})}return ParseStatus.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:o}=n;if("aborted"===t.status)return INVALID;if("aborted"===o.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===o.status&&e.dirty(),"__proto__"===t.value||void 0===o.value&&!n.alwaysSet||(r[t.value]=o.value)}return{status:e.value,value:r}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=e=>({status:"dirty",value:e}),OK=e=>({status:"valid",value:e}),isAborted=e=>"aborted"===e.status,isDirty=e=>"dirty"===e.status,isValid=e=>"valid"===e.status,isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise;function __classPrivateFieldGet(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function __classPrivateFieldSet(e,t,r,n,o){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var errorUtil,errorUtil2,_ZodEnum_cache,_ZodNativeEnum_cache;"function"==typeof SuppressedError&&SuppressedError,errorUtil2=errorUtil||(errorUtil={}),errorUtil2.errToObj=e=>"string"==typeof e?{message:e}:e||{},errorUtil2.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class ParseInputLazyPath{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:o};return{errorMap:(t,o)=>{var i,a;const{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:o.defaultError}:void 0===o.data?{message:null!==(i=null!=s?s:n)&&void 0!==i?i:o.defaultError}:"invalid_type"!==t.code?{message:o.defaultError}:{message:null!==(a=null!=s?s:r)&&void 0!==a?a:o.defaultError}},description:o}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},o=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,o)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(o){(null===(r=null===(t=null==o?void 0:o.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>isValid(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,o)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const o=e(t),i=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&o instanceof Promise?o.then((e=>!!e||(i(),!1))):!!o||(i(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function timeRegex(e){return new RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function isValidIP(e,t){return!("v4"!==t&&t||!ipv4Regex.test(e))||!("v6"!==t&&t||!ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return"object"==typeof o&&null!==o&&(!(!o.typ||!o.alg)&&(!t||o.alg===t))}catch(r){return!1}}function isValidCidr(e,t){return!("v4"!==t&&t||!ipv4CidrRegex.test(e))||!("v6"!==t&&t||!ipv6CidrRegex.test(e))}class ZodString extends ZodType{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ZodParsedType.string){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}const t=new ParseStatus;let r;for(const o of this._def.checks)if("min"===o.kind)e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("max"===o.kind)e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("length"===o.kind){const n=e.data.length>o.value,i=e.data.length<o.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),t.dirty())}else if("email"===o.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("emoji"===o.kind)emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("uuid"===o.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("nanoid"===o.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid"===o.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid2"===o.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("ulid"===o.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("url"===o.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()}else if("regex"===o.kind){o.regex.lastIndex=0;o.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty())}else if("trim"===o.kind)e.data=e.data.trim();else if("includes"===o.kind)e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),t.dirty());else if("toLowerCase"===o.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===o.kind)e.data=e.data.toUpperCase();else if("startsWith"===o.kind)e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),t.dirty());else if("endsWith"===o.kind)e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),t.dirty());else if("datetime"===o.kind){datetimeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),t.dirty())}else if("date"===o.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),t.dirty())}else if("time"===o.kind){timeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),t.dirty())}else"duration"===o.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"ip"===o.kind?isValidIP(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"jwt"===o.kind?isValidJWT(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"cidr"===o.kind?isValidCidr(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64"===o.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64url"===o.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):util$1.assertNever(o);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(r)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...errorUtil.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...errorUtil.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n;return parseInt(e.toFixed(o).replace(".",""))%parseInt(t.toFixed(o).replace(".",""))/Math.pow(10,o)}ZodString.create=e=>{var t;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType.number){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t;const r=new ParseStatus;for(const n of this._def.checks)if("int"===n.kind)util$1.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==floatSafeRemainder(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:n.message}),r.dirty()):util$1.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&util$1.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):util$1.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=e=>{var t;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodBoolean extends ZodType{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodDate extends ZodType{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType.date){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(isNaN(e.data.getTime())){return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID}const t=new ParseStatus;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util$1.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ZodDate.create=e=>new ZodDate({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(e||o)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:o?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new ParseInputLazyPath(t,e,t.path,r))))).then((e=>ParseStatus.mergeArray(r,e)));const o=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function deepPartialify(e){if(e instanceof ZodObject){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...e._def,shape:()=>t})}return e instanceof ZodArray?new ZodArray({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof ZodTuple?ZodTuple.create(e.items.map((e=>deepPartialify(e)))):e}ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util$1.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==ZodParsedType.object){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)o.includes(s)||i.push(s);const a=[];for(const s of o){const e=n[s],t=r.data[s];a.push({key:{status:"valid",value:s},value:e._parse(new ParseInputLazyPath(r,t,r.path,s)),alwaysSet:s in r.data})}if(this._def.catchall instanceof ZodNever){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>ParseStatus.mergeObjectSync(t,e))):ParseStatus.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,o,i,a;const s=null!==(i=null===(o=(n=this._def).errorMap)||void 0===o?void 0:o.call(n,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=errorUtil.errToObj(e).message)&&void 0!==a?a:s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};return util$1.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new ZodObject({...this._def,shape:()=>t})}required(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}})),new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util$1.objectKeys(this.shape))}}ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const r=e.map((e=>new ZodError(e.ctx.common.issues)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:r}),INVALID}));{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util$1.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;const r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const o of t){const t=getDiscriminator(o.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(n.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);n.set(r,o)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...processCreateParams(r)})}}function mergeValues(e,t){const r=getParsedType(e),n=getParsedType(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType.object&&n===ZodParsedType.object){const r=util$1.objectKeys(t),n=util$1.objectKeys(e).filter((e=>-1!==r.indexOf(e))),o={...e,...t};for(const i of n){const r=mergeValues(e[i],t[i]);if(!r.valid)return{valid:!1};o[i]=r.data}return{valid:!0,data:o}}if(r===ZodParsedType.array&&n===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const o=mergeValues(e[n],t[n]);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}return r===ZodParsedType.date&&n===ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted(e)||isAborted(n))return INVALID;const o=mergeValues(e.value,n.value);return o.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:o.data}):(addIssueToContext(r,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ZodIntersection.create=(e,t,r)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>ParseStatus.mergeArray(t,e))):ParseStatus.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const n=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)n.push({key:o._parse(new ParseInputLazyPath(r,a,r.path,a)),value:i._parse(new ParseInputLazyPath(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ParseStatus.mergeObjectAsync(t,n):ParseStatus.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ZodRecord(t instanceof ZodType?{keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)}:{keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;const n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[i,"key"])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,o=await r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,o=r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}}}ZodMap.create=(e,t,r)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const o=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return INVALID;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function r(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:r}})}function n(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:r}})}const o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ZodPromise){const e=this;return OK((async function(...t){const a=new ZodError([]),s=await e._def.args.parseAsync(t,o).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,s);return await e._def.returns._def.type.parseAsync(c,o).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return OK((function(...t){const a=e._def.args.safeParse(t,o);if(!a.success)throw new ZodError([r(t,a.error)]);const s=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(s,o);if(!c.success)throw new ZodError([n(s,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(r)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util$1.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:r}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}_ZodEnum_cache=new WeakMap,ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(e){const t=util$1.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util$1.objectValues(t);return addIssueToContext(r,{expected:util$1.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util$1.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(e.data)){const e=util$1.objectValues(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap,ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&!1===t.common.async)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const r=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){const e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return INVALID;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}));{if("aborted"===t.value)return INVALID;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return e;const i=n.transform(e.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}util$1.assertNever(n)}}ZodEffects.create=(e,t,r)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(e,t,r)=>new ZodEffects({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...processCreateParams(t)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...processCreateParams(t)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),r=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function cleanParams(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function custom(e,t={},r){return e?ZodAny.create().superRefine(((n,o)=>{var i,a;const s=e(n);if(s instanceof Promise)return s.then((e=>{var i,a;if(!e){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}}));if(!s){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}})):ZodAny.create()}ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind,ZodFirstPartyTypeKind2;ZodFirstPartyTypeKind2=ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}),ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly";const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom((t=>t instanceof e),t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:e=>ZodString.create({...e,coerce:!0}),number:e=>ZodNumber.create({...e,coerce:!0}),boolean:e=>ZodBoolean.create({...e,coerce:!0}),bigint:e=>ZodBigInt.create({...e,coerce:!0}),date:e=>ZodDate.create({...e,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap:setErrorMap,getErrorMap:getErrorMap,makeIssue:makeIssue,EMPTY_PATH:EMPTY_PATH,addIssueToContext:addIssueToContext,ParseStatus:ParseStatus,INVALID:INVALID,DIRTY:DIRTY,OK:OK,isAborted:isAborted,isDirty:isDirty,isValid:isValid,isAsync:isAsync,get util(){return util$1},get objectUtil(){return objectUtil},ZodParsedType:ZodParsedType,getParsedType:getParsedType,ZodType:ZodType,datetimeRegex:datetimeRegex,ZodString:ZodString,ZodNumber:ZodNumber,ZodBigInt:ZodBigInt,ZodBoolean:ZodBoolean,ZodDate:ZodDate,ZodSymbol:ZodSymbol,ZodUndefined:ZodUndefined,ZodNull:ZodNull,ZodAny:ZodAny,ZodUnknown:ZodUnknown,ZodNever:ZodNever,ZodVoid:ZodVoid,ZodArray:ZodArray,ZodObject:ZodObject,ZodUnion:ZodUnion,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodIntersection:ZodIntersection,ZodTuple:ZodTuple,ZodRecord:ZodRecord,ZodMap:ZodMap,ZodSet:ZodSet,ZodFunction:ZodFunction,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodEnum:ZodEnum,ZodNativeEnum:ZodNativeEnum,ZodPromise:ZodPromise,ZodEffects:ZodEffects,ZodTransformer:ZodEffects,ZodOptional:ZodOptional,ZodNullable:ZodNullable,ZodDefault:ZodDefault,ZodCatch:ZodCatch,ZodNaN:ZodNaN,BRAND:BRAND,ZodBranded:ZodBranded,ZodPipeline:ZodPipeline,ZodReadonly:ZodReadonly,custom:custom,Schema:ZodType,ZodSchema:ZodType,late:late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce:coerce,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean:oboolean,onumber:onumber,optional:optionalType,ostring:ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER:NEVER,ZodIssueCode:ZodIssueCode,quotelessJson:quotelessJson,ZodError:ZodError});function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf}=Object,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction=typeOfTest("function"),isNumber=typeOfTest("number"),isObject=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject(e)&&isFunction(e.pipe),isFormData=e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||isFunction(e.append)&&("formdata"===(t=kindOf(e))||"object"===t&&isFunction(e.toString)&&"[object FormData]"===e.toString()))},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),isArray(e))for(n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else{const o=r?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let a;for(n=0;n<i;n++)a=o[n],t.call(null,e[a],a,e)}}function findKey(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,o=r.length;for(;o-- >0;)if(n=r[o],t===n.toLowerCase())return n;return null}const _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global$2,isContextDefined=e=>!isUndefined(e)&&e!==_global;function merge(){const{caseless:e}=isContextDefined(this)&&this||{},t={},r=(r,n)=>{const o=e&&findKey(t,n)||n;isPlainObject(t[o])&&isPlainObject(r)?t[o]=merge(t[o],r):isPlainObject(r)?t[o]=merge({},r):isArray(r)?t[o]=r.slice():t[o]=r};for(let n=0,o=arguments.length;n<o;n++)arguments[n]&&forEach(arguments[n],r);return t}const extend=(e,t,r,{allOwnKeys:n}={})=>(forEach(t,((t,n)=>{r&&isFunction(t)?e[n]=bind(t,r):e[n]=t}),{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let o,i,a;const s={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],n&&!n(a,e,t)||s[a]||(t[a]=e[a],s[a]=!0);e=!1!==r&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray$1=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),hasOwnProperty=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,((r,o)=>{let i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,((t,r)=>{if(isFunction(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction(n)&&(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={},n=e=>{e.forEach((e=>{r[e]=!0}))};return isArray(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const o=isArray(e)?[]:{};return forEach(e,((e,t)=>{const i=r(e,n+1);!isUndefined(i)&&(o[t]=i)})),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject(e)||isFunction(e))&&isFunction(e.then)&&isFunction(e.catch),_setImmediate=((e,t)=>e?setImmediate:t?((e,t)=>(_global.addEventListener("message",(({source:r,data:n})=>{r===_global&&n===e&&t.length&&t.shift()()}),!1),r=>{t.push(r),_global.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))("function"==typeof setImmediate,isFunction(_global.postMessage)),asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):void 0!==process$1$1&&process$1$1.nextTick||_setImmediate,utils$1={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject,isPlainObject:isPlainObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray$1,isFileList:isFileList,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty,hasOwnProp:hasOwnProperty,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap};function AxiosError$1(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}utils$1.inherits(AxiosError$1,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:utils$1.toJSONObject(this.config),code:this.code,status:this.status}}});const prototype$1=AxiosError$1.prototype,descriptors={};["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=>{descriptors[e]={value:e}})),Object.defineProperties(AxiosError$1,descriptors),Object.defineProperty(prototype$1,"isAxiosError",{value:!0}),AxiosError$1.from=(e,t,r,n,o,i)=>{const a=Object.create(prototype$1);return utils$1.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),AxiosError$1.call(a,e.message,t,r,n,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};const httpAdapter=null;function isVisitable(e){return utils$1.isPlainObject(e)||utils$1.isArray(e)}function removeBrackets(e){return utils$1.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map((function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}function isFlatArray(e){return utils$1.isArray(e)&&!e.some(isVisitable)}const predicates=utils$1.toFlatObject(utils$1,{},null,(function(e){return/^is[A-Z]/.test(e)}));function toFormData$1(e,t,r){if(!utils$1.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$1.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!utils$1.isUndefined(t[e])}))).metaTokens,o=r.visitor||u,i=r.dots,a=r.indexes,s=(r.Blob||"undefined"!=typeof Blob&&Blob)&&utils$1.isSpecCompliantForm(t);if(!utils$1.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(utils$1.isDate(e))return e.toISOString();if(!s&&utils$1.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$1.isArrayBuffer(e)||utils$1.isTypedArray(e)?s&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,r,o){let s=e;if(e&&!o&&"object"==typeof e)if(utils$1.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$1.isArray(e)&&isFlatArray(e)||(utils$1.isFileList(e)||utils$1.endsWith(r,"[]"))&&(s=utils$1.toArray(e)))return r=removeBrackets(r),s.forEach((function(e,n){!utils$1.isUndefined(e)&&null!==e&&t.append(!0===a?renderKey([r],n,i):null===a?r:r+"[]",c(e))})),!1;return!!isVisitable(e)||(t.append(renderKey(o,r,i),c(e)),!1)}const l=[],d=Object.assign(predicates,{defaultVisitor:u,convertValue:c,isVisitable:isVisitable});if(!utils$1.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!utils$1.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),utils$1.forEach(r,(function(r,i){!0===(!(utils$1.isUndefined(r)||null===r)&&o.call(t,r,utils$1.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode;utils$1.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let i;if(i=o?o(t,r):utils$1.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class InterceptorManager{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){utils$1.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$1="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$1,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]},hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost",utils=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin},Symbol.toStringTag,{value:"Module"})),platform={...utils,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return platform.isNode&&utils$1.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}function parsePropPath(e){return utils$1.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}function arrayToObject(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n<o;n++)i=r[n],t[i]=e[i];return t}function formDataToJSON(e){function t(e,r,n,o){let i=e[o++];if("__proto__"===i)return!0;const a=Number.isFinite(+i),s=o>=e.length;if(i=!i&&utils$1.isArray(n)?n.length:i,s)return utils$1.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&utils$1.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],o)&&utils$1.isArray(n[i])&&(n[i]=arrayToObject(n[i])),!a}if(utils$1.isFormData(e)&&utils$1.isFunction(e.entries)){const r={};return utils$1.forEachEntry(e,((e,n)=>{t(parsePropPath(e),n,r,0)})),r}return null}function stringifySafely(e,t,r){if(utils$1.isString(e))try{return(t||JSON.parse)(e),utils$1.trim(e)}catch(n){if("SyntaxError"!==n.name)throw n}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=utils$1.isObject(e);o&&utils$1.isHTMLForm(e)&&(e=new FormData(e));if(utils$1.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$1.isArrayBuffer(e)||utils$1.isBuffer(e)||utils$1.isStream(e)||utils$1.isFile(e)||utils$1.isBlob(e)||utils$1.isReadableStream(e))return e;if(utils$1.isArrayBufferView(e))return e.buffer;if(utils$1.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,this.formSerializer).toString();if((i=utils$1.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return toFormData$1(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=this.transitional||defaults.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(utils$1.isResponse(e)||utils$1.isReadableStream(e))return e;if(e&&utils$1.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw AxiosError$1.from(o,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$1.forEach(["delete","get","head","post","put","patch"],(e=>{defaults.headers[e]={}}));const ignoreDuplicateOf=utils$1.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"]),parseHeaders=e=>{const t={};let r,n,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t},$internals=Symbol("internals");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return!1===e||null==e?e:utils$1.isArray(e)?e.map(normalizeValue):String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,o){return utils$1.isFunction(n)?n.call(this,t,r):(o&&(t=r),utils$1.isString(t)?utils$1.isString(n)?-1!==t.indexOf(n):utils$1.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}function buildAccessors(e,t){const r=utils$1.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})}))}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=normalizeHeader(t);if(!o)throw new Error("header name must be a non-empty string");const i=utils$1.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=normalizeValue(e))}const i=(e,t)=>utils$1.forEach(e,((e,r)=>o(e,r,t)));if(utils$1.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(utils$1.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))i(parseHeaders(e),t);else if(utils$1.isHeaders(e))for(const[a,s]of e.entries())o(s,a,r);else null!=e&&o(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$1.isFunction(t))return t.call(this,e,r);if(utils$1.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=normalizeHeader(e)){const o=utils$1.findKey(r,e);!o||t&&!matchHeaderValue(r,r[o],o,t)||(delete r[o],n=!0)}}return utils$1.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!matchHeaderValue(this,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return utils$1.forEach(this,((n,o)=>{const i=utils$1.findKey(r,o);if(i)return t[i]=normalizeValue(n),void delete t[o];const a=e?formatHeader(o):String(o).trim();a!==o&&delete t[o],t[a]=normalizeValue(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$1.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$1.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[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$1.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,o=AxiosHeaders$1.from(n.headers);let i=n.data;return utils$1.forEach(e,(function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function isCancel$1(e){return!(!e||!e.__CANCEL__)}function CanceledError$1(e,t,r){AxiosError$1.call(this,null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError"}function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,a=0;return t=void 0!==t?t:1e3,function(s){const c=Date.now(),u=n[a];o||(o=c),r[i]=s,n[i]=c;let l=a,d=0;for(;l!==i;)d+=r[l++],l%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),c-o<t)return;const h=u&&c-u;return h?Math.round(1e3*d/h):void 0}}function throttle(e,t){let r,n,o=0,i=1e3/t;const a=(t,i=Date.now())=>{o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),s=t-o;s>=i?a(e,t):(r=e,n||(n=setTimeout((()=>{n=null,a(r)}),i-s)))},()=>r&&a(r)]}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$1.reduceDescriptors(AxiosHeaders$1.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),utils$1.freezeMethods(AxiosHeaders$1),utils$1.inherits(CanceledError$1,AxiosError$1,{__CANCEL__:!0});const progressEventReducer=(e,t,r=3)=>{let n=0;const o=speedometer(50,250);return throttle((r=>{const i=r.loaded,a=r.lengthComputable?r.total:void 0,s=i-n,c=o(s);n=i;e({loaded:i,total:a,progress:a?i/a:void 0,bytes:s,rate:c||void 0,estimated:c&&a&&i<=a?(a-i)/c:void 0,event:r,lengthComputable:null!=a,[t?"download":"upload"]:!0})}),r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$1.asap((()=>e(...t))),isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,o,i){const a=[e+"="+encodeURIComponent(t)];utils$1.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),utils$1.isString(n)&&a.push("path="+n),utils$1.isString(o)&&a.push("domain="+o),!0===i&&a.push("secure"),document.cookie=a.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 isAbsoluteURL(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||0==r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$1(e,t){t=t||{};const r={};function n(e,t,r,n){return utils$1.isPlainObject(e)&&utils$1.isPlainObject(t)?utils$1.merge.call({caseless:n},e,t):utils$1.isPlainObject(t)?utils$1.merge({},t):utils$1.isArray(t)?t.slice():t}function o(e,t,r,o){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e,0,o):n(e,t,0,o)}function i(e,t){if(!utils$1.isUndefined(t))return n(void 0,t)}function a(e,t){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function s(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t,r)=>o(headersToObject(e),headersToObject(t),0,!0)};return utils$1.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||o,a=i(e[n],t[n],n);utils$1.isUndefined(a)&&i!==s||(r[n]=a)})),r}const resolveConfig=e=>{const t=mergeConfig$1({},e);let r,{data:n,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:a,headers:s,auth:c}=t;if(t.headers=s=AxiosHeaders$1.from(s),t.url=buildURL(buildFullPath(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&s.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),utils$1.isFormData(n))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(!1!==(r=s.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];s.setContentType([e||"multipart/form-data",...t].join("; "))}if(platform.hasStandardBrowserEnv&&(o&&utils$1.isFunction(o)&&(o=o(t)),o||!1!==o&&isURLSameOrigin(t.url))){const e=i&&a&&cookies.read(a);e&&s.set(i,e)}return t},isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest,xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise((function(t,r){const n=resolveConfig(e);let o=n.data;const i=AxiosHeaders$1.from(n.headers).normalize();let a,s,c,u,l,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){u&&u(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(a),n.signal&&n.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const o=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,o.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===o&&i.setContentType(null),"setRequestHeader"in m&&utils$1.forEach(i.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),utils$1.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,l]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([s,u]=progressEventReducer(h),m.upload.addEventListener("progress",s),m.upload.addEventListener("loadend",u)),(n.cancelToken||n.signal)&&(a=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(a),n.signal&&(n.signal.aborted?a():n.signal.addEventListener("abort",a)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(o||null)}))},composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const o=function(e){if(!r){r=!0,a();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,o(new AxiosError$1(`timeout ${t} of ms exceeded`,AxiosError$1.ETIMEDOUT))}),t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)})),e=null)};e.forEach((e=>e.addEventListener("abort",o)));const{signal:s}=n;return s.unsubscribe=()=>utils$1.asap(a),s}},streamChunk=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,o=0;for(;o<r;)n=o+t,yield e.slice(o,n),o=n},readBytes=async function*(e,t){for await(const r of readStream(e))yield*streamChunk(r,t)},readStream=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()}},trackStream=(e,t,r,n)=>{const o=readBytes(e,t);let i,a=0,s=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await o.next();if(t)return s(),void e.close();let i=n.byteLength;if(r){let e=a+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw s(t),t}},cancel:e=>(s(e),o.return())},{highWaterMark:2})},isFetchSupported="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,isReadableStreamSupported=isFetchSupported&&"function"==typeof ReadableStream,encodeText=isFetchSupported&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),test=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},supportsRequestStream=isReadableStreamSupported&&test((()=>{let e=!1;const t=new Request(platform.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),DEFAULT_CHUNK_SIZE=65536,supportsResponseStream=isReadableStreamSupported&&test((()=>utils$1.isReadableStream(new Response("").body))),resolvers={stream:supportsResponseStream&&(e=>e.body)};isFetchSupported&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach((t=>{!resolvers[t]&&(resolvers[t]=utils$1.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new AxiosError$1(`Response type '${t}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})}))})(new Response);const getBodyLength=async e=>{if(null==e)return 0;if(utils$1.isBlob(e))return e.size;if(utils$1.isSpecCompliantForm(e)){const t=new Request(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$1.isArrayBufferView(e)||utils$1.isArrayBuffer(e)?e.byteLength:(utils$1.isURLSearchParams(e)&&(e+=""),utils$1.isString(e)?(await encodeText(e)).byteLength:void 0)},resolveBodyLength=async(e,t)=>{const r=utils$1.toFiniteNumber(e.getContentLength());return null==r?getBodyLength(t):r},fetchAdapter=isFetchSupported&&(async e=>{let{url:t,method:r,data:n,signal:o,cancelToken:i,timeout:a,onDownloadProgress:s,onUploadProgress:c,responseType:u,headers:l,withCredentials:d="same-origin",fetchOptions:h}=resolveConfig(e);u=u?(u+"").toLowerCase():"text";let p,f=composeSignals([o,i&&i.toAbortSignal()],a);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&supportsRequestStream&&"get"!==r&&"head"!==r&&0!==(g=await resolveBodyLength(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(utils$1.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=progressEventDecorator(g,progressEventReducer(asyncDecorator(c)));n=trackStream(r.body,DEFAULT_CHUNK_SIZE,e,t)}}utils$1.isString(d)||(d=d?"include":"omit");const o="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:o?d:void 0});let i=await fetch(p);const a=supportsResponseStream&&("stream"===u||"response"===u);if(supportsResponseStream&&(s||a&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=utils$1.toFiniteNumber(i.headers.get("content-length")),[r,n]=s&&progressEventDecorator(t,progressEventReducer(asyncDecorator(s),!0))||[];i=new Response(trackStream(i.body,DEFAULT_CHUNK_SIZE,r,(()=>{n&&n(),m&&m()})),e)}u=u||"text";let y=await resolvers[utils$1.findKey(resolvers,u)||"text"](i,e);return!a&&m&&m(),await new Promise(((t,r)=>{settle(t,r,{data:y,headers:AxiosHeaders$1.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/fetch/i.test(y.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,p),{cause:y.cause||y});throw AxiosError$1.from(y,y&&y.code,e,p)}}),knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:fetchAdapter};utils$1.forEach(knownAdapters,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}}));const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$1.isFunction(e)||null===e||!1===e,adapters={getAdapter:e=>{e=utils$1.isArray(e)?e:[e];const{length:t}=e;let r,n;const o={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!isResolvedHandle(r)&&(n=knownAdapters[(t=String(r)).toLowerCase()],void 0===n))throw new AxiosError$1(`Unknown adapter '${t}'`);if(n)break;o[t||"#"+i]=n}if(!n){const e=Object.entries(o).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new AxiosError$1("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t}),(function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)}))}const VERSION$1="1.8.4",validators$1={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new AxiosError$1("option "+i+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new AxiosError$1("Unknown option "+i,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$1+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,i)=>{if(!1===e)throw new AxiosError$1(n(o," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[o]&&(deprecatedWarnings[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const validator={assertOptions:assertOptions,validators:validators$1},validators=validator.validators;let Axios$1=class{constructor(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}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(n){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$1(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;void 0!==r&&validator.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),null!=n&&(utils$1.isFunction(n)?t.paramsSerializer={serialize:n}:validator.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&utils$1.merge(o.common,o[t.method]);o&&utils$1.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=AxiosHeaders$1.concat(i,o);const a=[];let s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,a.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(!s){const e=[dispatchRequest.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);d<l;)u=u.then(e[d++],e[d++]);return u}l=a.length;let h=t;for(d=0;d<l;){const e=a[d++],t=a[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{u=dispatchRequest.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,l=c.length;d<l;)u=u.then(c[d++],c[d++]);return u}getUri(e){return buildURL(buildFullPath((e=mergeConfig$1(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,r){return this.request(mergeConfig$1(r||{},{method:e,url:t,data:(r||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,o){return this.request(mergeConfig$1(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));let CancelToken$1=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,o){r.reason||(r.reason=new CanceledError$1(e,n,o),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$1.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={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};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$1.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$1.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$1(e,t))},r}Object.entries(HttpStatusCode$1).forEach((([e,t])=>{HttpStatusCode$1[t]=e}));const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$1.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;class HederaMirrorNode{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 Logger$2({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 i$9.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.info(`Getting account memo for account ID: ${e}`);const t=this.constructUrl(`/api/v1/accounts/${e}`);try{const r=await this._requestWithRetry(t);return r?.memo?r.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(r){const t=r;return this.logger.error(`Failed to get account memo for ${e} after retries: ${t.message}`),null}}async getTopicInfo(e){try{const t=this.constructUrl(`/api/v1/topics/${e}`);this.logger.debug(`Fetching topic info from ${t}`);return await this._requestWithRetry(t)}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=`https://mainnet-public.mirrornode.hedera.com/api/v1/network/exchangerate?timestamp=${s$a.fromDate(e).toString()}`;this.logger.debug(`Fetching HBAR price from ${t}`);const r=await this._fetchWithRetry(t);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=this.constructUrl(`/api/v1/tokens/${e}`),r=await this._requestWithRetry(t);return r?(this.logger.trace(`Token info found for ${e}:`,r),r):(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=this.constructUrl(`/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,o;try{e=this.isServerEnvironment?Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),(e=>e.charCodeAt(0))))}catch(n){const e=`Error decoding message: ${n}`;this.logger.error(e);continue}try{o=JSON.parse(e)}catch(n){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}o.sequence_number=t.sequence_number,r.push({...o,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(n){const e=`Error processing message: ${n.message}`;this.logger.error(e)}t=e.links?.next?this.constructUrl(e.links.next):""}catch(o){const r=`Error querying topic messages for topic ${e} (URL: ${t}) after retries: ${o.message}`;throw this.logger.error(r),new Error(r)}return r}async requestAccount(e){try{const t=this.constructUrl(`/api/v1/accounts/${e}`);this.logger.debug(`Requesting account info from ${t}`);const r=await this._requestWithRetry(t);if(!r)throw new Error(`No data received from mirror node for account: ${e}`);return r}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=libExports.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=libExports.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(Buffer.from(e),t))return!0}catch(n){const e=`Error in nested key: ${n.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i$9.fromBytes(Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=`${this.baseUrl}/api/v1/schedules/${e}`,r=await this._requestWithRetry(t);return r||(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}`);const t=(e.includes("-"),`transactions/${e}`),r=`${this.baseUrl}/api/v1/${t}`;try{const t=await this._requestWithRetry(r);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(n){const t=n;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${t.message}`),null}}async _requestWithRetry(e,t){let r=0,n=this.initialDelayMs;const o={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(o.headers={...o.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await axios.get(e,o)).data}catch(i){r++;const t=r>=this.maxRetries,o=i.response?.status;if(o&&o>=400&&o<500&&429!==o)throw this.logger.error(`Client error for ${e} (status ${o}): ${i.message}. Not retrying.`),i;if(t)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${i.message}`),i;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${i.message}. Retrying in ${n}ms...`),await new Promise((e=>setTimeout(e,n))),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,n=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach(((e,t)=>{o[t]=e})):Array.isArray(t.headers)?t.headers.forEach((([e,t])=>{o[e]=t})):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const i={...t,headers:o};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(a){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${a.message}. Retrying in ${n}ms...`),await new Promise((e=>setTimeout(e,n))),n=Math.min(n*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=`${this.baseUrl}/api/v1/topics/${e}/messages`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.sequenceNumber&&n.append("sequencenumber",t.sequenceNumber),t?.startTime&&n.append("timestamp",`gte:${t.startTime}`),t?.endTime&&n.append("timestamp",`lt:${t.endTime}`),t?.order&&n.append("order",t.order);const o=n.toString();o&&(r+=`?${o}`);const i=[];let a=0;try{for(;r&&a<10;){a++;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?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(s){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const n={...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(n)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&i.length>=t.limit)break;r=e.links?.next?`${this.baseUrl}${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=[],n=`${this.baseUrl}/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);if(e&&e.tokens&&(r=r.concat(e.tokens)),n=e.links?.next?`${this.baseUrl}${e.links.next}`:"",!n||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);const t=`${this.baseUrl}/api/v1/transactions?timestamp=${e}&limit=1`;try{return(await this._requestWithRetry(t)).transactions}catch(r){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${r}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let n=[],o=`${this.baseUrl}/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map((e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?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}}));n=n.concat(t)}if(o=e.links?.next?`${this.baseUrl}${e.links.next}`:"",!o)break}return n}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 n=await this.getAccountNfts(e,t);if(n){return n.find((e=>e.token_id===t&&e.serial_number===r))||null}return null}catch(n){return this.logger.error(`Error validating NFT ownership: ${n.message}`),null}}async readSmartContractQuery(e,t,r,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const o=`${this.baseUrl}/api/v1/contracts/call`,i=e.startsWith("0x")?e:`0x${f.fromString(e).toSolidityAddress()}`,a=r.startsWith("0x")?r:`0x${f.fromString(r).toSolidityAddress()}`,s={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:a,to:i,gas:n?.gas,gasPrice:n?.gasPrice,value:n?.value||0};Object.keys(s).forEach((e=>{const t=e;void 0===s[t]&&delete s[t]}));try{return await this._fetchWithRetry(o,{method:"POST",body:JSON.stringify(s),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getTokenAirdrops(e,t=100){this.logger.info(`Getting token airdrops for account ${e}`);const r=`${this.baseUrl}/api/v1/accounts/${e}/airdrops/tokens?limit=${t}`;try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching token airdrops for account ${e}: ${n.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t=`${this.baseUrl}/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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);const t=`${this.baseUrl}/api/v1/blocks/${e}`;try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching block ${e}: ${r.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t=`${this.baseUrl}/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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`${this.baseUrl}/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching contract ${e}: ${n.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t=`${this.baseUrl}/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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`${this.baseUrl}/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching contract result for ${e}: ${n.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`${this.baseUrl}/api/v1/contracts/${e}/results`;const n=new URLSearchParams;t?.blockHash&&n.append("block.hash",t.blockHash),t?.blockNumber&&n.append("block.number",t.blockNumber),t?.from&&n.append("from",t.from),void 0!==t?.internal&&n.append("internal",t.internal.toString()),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.transactionIndex&&n.append("transaction.index",t.transactionIndex.toString());const o=n.toString();o&&(r+=`?${o}`);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=`${this.baseUrl}/api/v1/contracts/${e}/state`;const n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.slot&&n.append("slot",t.slot),t?.timestamp&&n.append("timestamp",t.timestamp);const o=n.toString();o&&(r+=`?${o}`);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=`${this.baseUrl}/api/v1/contracts/results/${e}/actions`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order);const o=n.toString();o&&(r+=`?${o}`);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=`${this.baseUrl}/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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`${this.baseUrl}/api/v1/contracts/${e}/results/logs`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.topic0&&n.append("topic0",t.topic0),t?.topic1&&n.append("topic1",t.topic1),t?.topic2&&n.append("topic2",t.topic2),t?.topic3&&n.append("topic3",t.topic3);const o=n.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(i){return this.logger.error(`Error fetching contract logs for ${e}: ${i.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let r=`${this.baseUrl}/api/v1/contracts/results/${e}/opcodes`;const n=new URLSearchParams;void 0!==t?.stack&&n.append("stack",t.stack.toString()),void 0!==t?.memory&&n.append("memory",t.memory.toString()),void 0!==t?.storage&&n.append("storage",t.storage.toString());const o=n.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching opcode traces for ${e}: ${i.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const r=`${this.baseUrl}/api/v1/tokens/${e}/nfts/${t}`;try{return(await this._requestWithRetry(r)).nft}catch(n){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${n.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`${this.baseUrl}/api/v1/tokens/${e}/nfts`;const n=new URLSearchParams;t?.accountId&&n.append("account.id",t.accountId),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.serialNumber&&n.append("serialnumber",t.serialNumber);const o=n.toString();o&&(r+=`?${o}`);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");const e=`${this.baseUrl}/api/v1/network/nodes`;try{return await this._requestWithRetry(e)}catch(t){return this.logger.error(`Error fetching network info: ${t.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t=`${this.baseUrl}/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=`${this.baseUrl}/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=`${this.baseUrl}/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}}}var ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(ProfileType||{}),AIAgentType=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(AIAgentType||{}),EndpointType=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(EndpointType||{}),AIAgentCapability=(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))(AIAgentCapability||{}),InboundTopicType=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(InboundTopicType||{});const SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],capabilityNameToCapabilityMap={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},SocialLinkSchema=z.object({platform:z.string().min(1),handle:z.string().min(1)}),AIAgentDetailsSchema=z.object({type:z.nativeEnum(AIAgentType),capabilities:z.array(z.nativeEnum(AIAgentCapability)).min(1),model:z.string().min(1),creator:z.string().optional()}),BaseProfileSchema=z.object({version:z.string().min(1),type:z.nativeEnum(ProfileType),display_name:z.string().min(1),alias:z.string().optional(),bio:z.string().optional(),socials:z.array(SocialLinkSchema).optional(),profileImage:z.string().optional(),properties:z.record(z.any()).optional(),inboundTopicId:z.string().optional(),outboundTopicId:z.string().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:z.literal(ProfileType.PERSONAL),language:z.string().optional(),timezone:z.string().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:z.literal(ProfileType.AI_AGENT),aiAgent:AIAgentDetailsSchema}),HCS11ProfileSchema=z.union([PersonalProfileSchema,AIAgentProfileSchema]);class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.auth=e.auth,this.network=e.network,this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey){const e=y.fromString(this.auth.privateKey);this.client.setOperator(this.auth.operatorId,e)}this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-11"})}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}createPersonalProfile(e,t){return{version:"1.0",type:ProfileType.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,n,o){const i=this.validateProfile({version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}}}validateProfile(e){const t=HCS11ProfileSchema.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map((e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`}))}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),r=await t.execute(this.client),n=await r.getReceipt(this.client);return n.status.toString()!==e$6.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,r=await e.freezeWithSigner(t),n=await r.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status.toString()!==e$6.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}: ${e$6.Success.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const i=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(o.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(o.verifying("Waiting for inscription confirmation",50,{jobId:s.result.jobId}),{imageTopicId:"",transactionId:s.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,n=new ProgressReporter({module:"HCS11-Profile",logger:this.logger,callback:r});n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const i=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(i,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};n.submitting("Submitting profile to Hedera network",30);const s=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},o):await inscribeWithSigner(r,this.auth.signer,o);if(!s.confirmed||!s.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=s.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:c,transactionId:s.result.transactionId}),{profileTopicId:c,transactionId:s.result.transactionId,success:!0}}catch(s){return n.failed(`Error inscribing profile: ${s.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:s.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),n=(new s$4).setAccountMemo(r).setAccountId(e);return this.executeTransaction(n)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const i=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[AIAgentCapability.TEXT_GENERATION];for(const r of e){const e=capabilityNameToCapabilityMap[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(AIAgentCapability.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?AIAgentType.AUTONOMOUS:AIAgentType.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${n}`),!n?.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: ${n}`);const o=n.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[n,i,a]=e,s=t||this.network||"mainnet";this.logger.info(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;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:a}}:{success:!1,error:`No profile data found for topic ${a}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class Registration{async checkRegistrationStatus(e,t,r,n){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,n=60,o=2e3,i){let a=0;for(;a<n;){i&&i.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,i);if("success"===s.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise((e=>setTimeout(e,o))),a++}return i&&i.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const r=new HCS11Client({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await sleep(5e3);const o=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const i=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 i.json();return i.ok?(n&&n.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(i){return{error:`Error during registration request: ${i.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach((e=>r.append("tags",e.toString()))),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const n=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}class HRLResolver{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=Logger$2.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:n,topicId:o}=r;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await axios.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await axios.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:o,isBinary:!0}}if("application/json"===r){const t=await axios.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:r,topicId:o,isBinary:!1}}const n=await axios.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let i;return i="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:i,contentType:r,topicId:o,isBinary:!1}}catch(i){const e=`Error resolving HRL reference: ${i.message}`;throw this.logger.error(e),new Error(e)}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint}),this.mirrorNode=new HederaMirrorNode(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=Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i$9.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return 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(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){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{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=HCS10Cache.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new HCS11Client({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),n=await t.fetchProfileByAccountId(e,this.network);if(!n?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,n?.error),{profile:null,success:!1,error:n?.error||`Failed to retrieve profile for account ID: ${e}`};const o=n.profile;let i=null;n.topicInfo?.inboundTopic&&n.topicInfo?.outboundTopic&&n.topicInfo?.profileTopicId&&(i={inboundTopic:n.topicInfo.inboundTopic,outboundTopic:n.topicInfo.outboundTopic,profileTopicId:n.topicInfo.profileTopicId});const a={profile:o,topicInfo:i,success:!0};return HCS10Cache.getInstance().set(r,a),a}catch(n){const e=`Failed to retrieve profile: ${n.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 n=r.profile;if(!n.inboundTopicId||!n.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 HRLResolver(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 HRLResolver(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 n=await this.getOperatorId(),o=r.accountId,i=await this.canSubmitToTopic(e,o);if(!i?.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const a=await this.retrieveInboundAccountId(e);if(!a)throw new Error("Failed to retrieve topic info account ID");const s={p:"hcs-10",op:"connection_request",operator_id:n,m:t},c=i.requiresFee,u=await this.submitPayload(e,s,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(o);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 h=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:h}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:n,connectionTopicId:o,operatorId:i,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:o,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:r,operator_id:i,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,r=60,n=2e3,o=!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 a=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)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},n=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.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 ${n}ms before retrying...`),await new Promise((e=>setTimeout(e,n))))}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 n=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=n,n}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(":"),n=r?.[4];if(!n)throw new Error("Failed to retrieve topic info account ID");return n}clearCache(){HCS10Cache.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 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)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(n){const e=n,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],n=t[1];if(!r)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e),n=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?n.slice(0,t):n}}class HCS10Cache{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return HCS10Cache.instance||(HCS10Cache.instance=new HCS10Cache),HCS10Cache.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 PayloadSizeError extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class AccountCreationError extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class TopicCreationError extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class ConnectionConfirmationError extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class AgentBuilder{constructor(){this.config={},this.logger=Logger$2.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=InboundTopicType.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===InboundTopicType.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class PersonBuilder{constructor(){this.config={version:"1.0",type:0},this.logger=Logger$2.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}}}async function accountIdsToExemptKeys(e,t,r){const n=new HederaMirrorNode(t,r),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${a}: ${i}`)}return o}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function toInteger(e){if(null===e||!0===e||!1===e)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function requiredArgs(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function toDate(e){requiredArgs(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||"object"===_typeof(e)&&"[object Date]"===t?new Date(e.getTime()):"number"==typeof e||"[object Number]"===t?new Date(e):("string"!=typeof e&&"[object String]"!==t||"undefined"==typeof console||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn((new Error).stack)),new Date(NaN))}function addMilliseconds(e,t){requiredArgs(2,arguments);var r=toDate(e).getTime(),n=toInteger(t);return new Date(r+n)}function addSeconds(e,t){return requiredArgs(2,arguments),addMilliseconds(e,1e3*toInteger(t))}class HCS10Client extends HCS10BaseClient{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode}),this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.operatorPrivateKey=y.fromString(e.operatorPrivateKey),this.network=e.network,this.client.setOperator(e.operatorId,this.operatorPrivateKey.toString()),this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-SDK"}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel})}getClient(){return this.client}async createAccount(e=50){this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=y.generate(),r=(new h).setKey(t.publicKey).setInitialBalance(new e$7(e));this.logger.debug("Executing account creation transaction");const n=await r.execute(this.client),o=(await n.getReceipt(this.client)).accountId;if(!o)throw this.logger.error("Account creation failed: accountId is null"),new AccountCreationError("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${o.toString()}`),{accountId:o.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,n){const o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let i,a;switch(t){case InboundTopicType.PUBLIC:i=!1;break;case InboundTopicType.CONTROLLED:i=!0;break;case InboundTopicType.FEE_BASED:if(i=!1,!n)throw new Error("Fee configuration builder is required for fee-based topics");n.customFees.forEach((t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)})),a=n.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,i,a)}async createAgent(e,t=60){const r=e.build(),n=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:t}),o=await this.createTopic(n,!0,!0);this.logger.info(`Created new outbound topic ID: ${o}`);const i=this.client.operatorAccountId?.toString();if(!i)throw new Error("Failed to retrieve operator account ID");const a=await this.createInboundTopic(i,r.inboundTopicType,t,r.inboundTopicType===InboundTopicType.FEE_BASED?r.feeConfig:void 0);let s=r.existingPfpTopicId||"";if(!s&&r.pfpBuffer&&r.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(r.pfpBuffer,r.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else r.existingPfpTopicId&&this.logger.info(`Using existing profile picture with topic ID: ${r.existingPfpTopicId}`);const c=(await this.storeHCS11Profile(r.name,r.bio,a,o,r.capabilities,r.metadata,r.pfpBuffer&&r.pfpBuffer.length>0?r.pfpBuffer:void 0,r.pfpFileName,r.existingPfpTopicId)).profileTopicId;return this.logger.info(`Profile stored with topic ID: ${c}`),{inboundTopicId:a,outboundTopicId:o,pfpTopicId:s,profileTopicId:c}}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,n,o=[],i,a,s,c){try{let u=c||"";if(!u&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);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,h=this.hcs11Client.createAIAgentProfile(e,l,o,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:n,creator:i.creator}),p=await this.hcs11Client.createAndInscribeProfile(h,!0);if(!p.success)throw this.logger.error(`Failed to inscribe profile: ${p.error}`),new Error(p.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${p.profileTopicId}, transaction ID: ${p.transactionId}`),{profileTopicId:p.profileTopicId,pfpTopicId:u,transactionId:p.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,r=[]){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 o=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 l).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(f.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(u$5.fromString(e.feeTokenId)),t}return null})).filter(Boolean);if(0===o.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const i=[...t.exemptAccounts||[],...r];return i.length>0&&(n=await this.setupExemptKeys(e,i)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(o)}async setupExemptKeys(e,t){let r=e;const n=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let o=[];if(n.length>0)try{o=await accountIdsToExemptKeys(n,this.network,this.logger)}catch(i){const e=`Error getting exempt keys: ${i.message}, continuing without exempt keys`;this.logger.warn(e)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,n,o=60){const i=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r});this.logger.info(`Handling connection request ${r} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let s=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(a);if(!c)throw new Error("Failed to retrieve public key");const u=new s$9([c,s],1);let l;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};l=await this.createTopic(i,u,u,t)}else l=await this.createTopic(i,u,u);this.logger.info(`Created new connection topic ID: ${l}`)}catch(g){const e=`Failed to create connection topic: ${g}`;throw this.logger.error(e),new TopicCreationError(e)}const d=`${e}@${a}`,h=await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),p=await this.retrieveCommunicationTopics(a),f=await this.retrieveCommunicationTopics(t),m=`${f.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:p.outboundTopic,requestorOutboundTopicId:f.outboundTopic,connectionRequestId:r,confirmedRequestId:h,connectionTopicId:l,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:l,confirmedConnectionSequenceNumber:h,operatorId:d}}async confirmConnection(e,t,r,n,o,i){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new ConnectionConfirmationError("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,n,o){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=JSON.stringify(a);if(Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=Buffer.from(t),r=`message-${Date.now()}.json`,n=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.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",a),await this.submitPayload(e,a,n,i.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const o=(new c).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(o.setAdminKey(this.client.operatorPublicKey),o.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$9||t instanceof s$9)&&(o.setAdminKey(t),this.client.operatorAccountId&&o.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?o.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$9||r instanceof s$9)&&o.setSubmitKey(r)),n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const i=await o.execute(this.client),a=await i.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,r,n=!1){const o="string"==typeof t?t:JSON.stringify(t),i=Buffer.byteLength(o,"utf8");if(i>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",i);const a=(new u).setTopicId(m$1.fromString(e)).setMessage(o);let s;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new e$7(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);s=await t.execute(this.client)}else s=await a.execute(this.client);const c=await s.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}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 n=mimeTypesExports.lookup(t)||"application/octet-stream",o=await InscriptionSDK.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"}},a=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:n},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},i,o);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,n=2e3,o=!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 a=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)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},n=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.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 ${n}ms before retrying...`),await new Promise((e=>setTimeout(e,n))))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){return{accountId:this.client.operatorAccountId.toString(),signer:this.operatorPrivateKey}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let i=t?.existingState||void 0;n&&n({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:i}});const a=r.existingAccount||await this.createAccount(t?.initialBalance);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:i,account:a}});const s=new HCS10Client({network:r.network,operatorId:a.accountId,operatorPrivateKey:a.privateKey,operatorPublicKey:y.fromString(a.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:o});n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:30,details:{state:i}});const{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=await s.createAgent(e);n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:i,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}});const h=`${u}@${a.accountId}`,p=await s.registerAgentWithGuardedRegistry(a.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:h,state:e.details?.state||i}})},existingState:i});return p.success?(n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:h,state:p.state}}),{...p,metadata:{accountId:a.accountId,privateKey:a.privateKey,operatorId:h,inboundTopicId:u,outboundTopicId:c,profileTopicId:d,pfpTopicId:l}}):p}catch(r){const e=r,t=`Failed to create and register agent: ${e.message}`;return this.logger.error(t),{error:e.message,success:!1}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,o=r?.delayMs??2e3,i=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};i&&i({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const s=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!s.success)return{...s,state:a};if(i&&i({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:s.transactionId,state:a}}),s.transaction){const e=P.fromBytes(Buffer.from(s.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}i&&i({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:s.transactionId,state:a}});const c=await this.waitForRegistrationConfirmation(s.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),i&&i({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:c,transactionId:s.transactionId,state:a}}),{...s,confirmed:c,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,n,o){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,i,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return InboundTopicType.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`),InboundTopicType.FEE_BASED}return InboundTopicType.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,r,n){this.logger.info("Creating scheduled transaction");const o=(new u$1).setScheduledTransaction(e).setPayerAccountId(n?f.fromString(n):this.client.operatorAccountId);if(t&&o.setScheduleMemo(t),r){const e=addSeconds(new Date,r),t=s$a.fromDate(e);o.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const i=await o.execute(this.client),a=await i.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 s=a.scheduleId.toString(),c=i.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${s}`),{scheduleId:s,transactionId:c}}async sendTransactionOperation(e,t,r,n,o){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,i.requiresFee)}async sendTransaction(e,t,r,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:i}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:o,transactionId:i,receipt:await this.sendTransactionOperation(e,o,r,n?.submitKey,{memo:n?.operationMemo})}}}const isBrowser="undefined"!=typeof window;class BrowserHCSClient extends HCS10BaseClient{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode}),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=Logger$2.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel})}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,n,o){this.logger.info("Sending message");const i={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),s=JSON.stringify(i);if(Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=Buffer.from(t),r=`message-${Date.now()}.json`,n=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.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,n,a.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const i=this.hwc.getAccountInfo().accountId;if(!i)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(i);if(!s)throw new Error("Failed to retrieve public key");const u=new s$9([s,a],1),l=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r}),d=(new c).setTopicMemo(l).setAutoRenewAccountId(f.fromString(i)).setAdminKey(u).setSubmitKey(u);this.logger.debug("Executing topic creation transaction");const h=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(h?.error)throw this.logger.error(h.error),new Error(h.error);const p=h?.result;if(!p?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const m=p.topicId.toString(),g=`${e}@${i}`,y=await this.confirmConnection(e,m,t,r,g,n),b=await this.retrieveCommunicationTopics(i),w=await this.retrieveCommunicationTopics(t),v=`${w.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:b.outboundTopic,requestorOutboundTopicId:w.outboundTopic,connectionRequestId:r,confirmedRequestId:y,connectionTopicId:m,operatorId:v,memo:`Connection established with ${t}`}),{connectionTopicId:m,confirmedConnectionSequenceNumber:y,operatorId:g}}async confirmConnection(e,t,r,n,o,i){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:n,m:i},s=await this.submitPayload(e,a);if(!s?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return s.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,n=new ProgressReporter({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof AgentBuilder;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");n.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:i,outboundTopicId:a,state:s}=await this.createCommunicationTopics(t,n);let c,u,l;if(o=s,r||(e.setInboundTopicId(i),e.setOutboundTopicId(a)),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,o,n):c&&(n.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,i,a,t,n),o.currentStage="complete",o.completedPercentage=100,n.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:i,outboundTopicId:a,pfpTopicId:c,state:o});let d="";o.outboundTopicId&&(d=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let p="";o.pfpTopicId&&(p=o.pfpTopicId);let f="";return o.profileTopicId&&(f=o.profileTopicId),{outboundTopicId:d,inboundTopicId:h,pfpTopicId:p,profileTopicId:f,success:!0,state:o}}catch(o){return n.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,n){r.currentStage="pfp",n.preparing("Creating profile picture",30,{state:r});const o=n.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),i=await this.inscribePfp(e,t,{progressCallback:e=>o.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 a=i.pfpTopicId;return r.pfpTopicId=a,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),n.preparing("Profile picture created",50,{state:r}),a}async createAndInscribeProfile(e,t,r,n,o,i,a,s){if(!this.hcs11Client)throw s&&s.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),n.profileTopicId)s&&s.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:n});else{s&&s.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=s?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let u;if(e){const e=t.build(),n=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:n,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:i,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:n,pfpFileName:a,...s}=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:o,outboundTopicId:i})}const l=await this.hcs11Client.createAndInscribeProfile(u,a?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!l.success){s&&s.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)}n.profileTopicId=l.profileTopicId,n.createdResources&&n.createdResources.push(`profile:${l.profileTopicId}`),s&&s.preparing("HCS-11 Profile stored",95,{state:n})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,o=this.initializeRegistrationState(n,r?.existingState),i=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});i.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:o};if(i.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=P.fromBytes(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:o};this.logger.info("Successfully processed registration transaction")}i.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const s=r?.maxAttempts??60,c=r?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,s,c,this.logger);return this.updateStateForCompletedRegistration(o,n),i.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}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(),n=t?.progressCallback,o=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,o.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);o.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}o.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:a}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.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(a,i.profileTopicId))}return o.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:a,operatorId:`${i.inboundTopicId}@${a}`,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,n,o=[],i={},a,s,c,u){try{const l=u?.progressCallback,d=new ProgressReporter({module:"StoreHCS11Profile",logger:this.logger,callback:l});d.preparing("Preparing agent profile data",0);let h=c;if(!h&&a&&s){const e=d.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(a,s,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?h=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 p=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const f=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,m=this.hcs11Client.createAIAgentProfile(e,p,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:h?`hcs://1/${h}`:void 0,socials:f,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:n,creator:i.creator}),g=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,!0,{progressCallback:e=>{g.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:h,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,r){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),i=(new c).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(i.setAdminKey(a),i.setAutoRenewAccountId(n)),r&&a&&i.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(i,!1),u=s.error;if(u)return this.logger.error(u),{success:!1,error:u};const l=s.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,r,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(e).setMessage(o);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount))),r){const{accountId:e,signer:t}=this.getAccountAndSigner();i.freezeWithSigner(t);const n=await i.sign(r);a=await this.hwc.executeTransactionWithErrorHandling(n,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(i,!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:n,signer:o}=this.getAccountAndSigner(),i=mimeTypesExports.lookup(t)||"application/octet-stream",a=await InscriptionSDK.createWithAuth({type:"client",accountId:n,signer:o,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},o,{...s,network:this.network},a);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 n=r?.progressCallback,o=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},a=await this.hcs11Client.inscribeImage(e,t,{progressCallback:i});if(!a.success){let e="Failed to inscribe profile picture";a.error&&(e=a.error);let t="";return a.transactionId&&(t=a.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return o.completed("Successfully inscribed profile picture",{pfpTopicId:a.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${a.imageTopicId}`),{pfpTopicId:a.imageTopicId,success:!0,transactionId:a.transactionId||""}}catch(n){return this.logger.error(`Error inscribing profile picture: ${n.message}`),{pfpTopicId:"",success:!1,error:n.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:n}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const o=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e?.ttl,accountId:n}),i=await this.createTopic(o,!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 o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{ttl:e?.ttl,accountId:n}),i=await this.createTopic(o,!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}}}class ConnectionsManager{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};if(this.logger=new Logger$2(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[n,o]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(n.messages||[],e),this.processInboundMessages(o.messages||[]);const i=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${n.messages?.length||0} outbound and ${o.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[n,o]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(n)).messages||[];let r=!1;for(const e of o){const n=e.connectionRequestId;if(!n)continue;const o=t.find((t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==n)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const n=r[1];if(t.operator_id&&t.operator_id===n)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0}));if(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let i=e.uniqueRequestKey;const a={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||e.created),profileInfo:e.profileInfo,connectionRequestId:n,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,a),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 ${n}:`,r),2===e)break;await new Promise((e=>setTimeout(e,500)))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter((e=>"pending"===e.status));this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter((e=>"pending"===e.status));if(Boolean(r?.length))for(const o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(n){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${n}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),n=(r.messages||[]).find((e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id));if(n?.connection_topic_id){const e=n.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${o.targetAccountId} on their inbound topic`),this.connections.set(o.connectionTopicId,{...o,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||o.created),lastActivity:new Date(n.created||o.created)})}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(n){this.logger.warn(`Error checking for confirmations on target inbound topic for ${o.targetAccountId}: ${n}`)}else this.logger.debug(`Skipping connection ${o.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map((async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}}));await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter((t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId));if(r.length>0&&t.inboundTopicId)for(const n of r){const e={...n,targetInboundTopicId:t.inboundTopicId};this.connections.set(n.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||"",n=this.baseClient.extractAccountFromOperatorId(r),o=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out outbound request to account: ${n}`);continue}const a=Array.from(this.connections.values()).some((t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===n)),s=`req-${e}:${r}`;if(!a&&!this.pendingRequests.has(s)){const a={id:e,requesterId:t,requesterTopicId:i.outbound_topic_id||"",targetAccountId:n,targetTopicId:o,operatorId:r,sequenceNumber:i.sequence_number,created:i.created||new Date,memo:i.m,status:"pending"};if(this.pendingRequests.set(s,a),!this.connections.has(s)){const t={connectionTopicId:s,targetAccountId:n,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:i.created||new Date,connectionRequestId:e,uniqueRequestKey:s,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m};this.connections.set(s,t)}}}const n=e.filter((e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id));for(const i of n){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 n=`req-${e}:${i.operator_id}`,o=this.pendingRequests.get(n);if(o&&(o.status="confirmed"),this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:n,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:n,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m})}const o=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const i of o){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 n of t){const e=n.sequence_number,t=n.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(t),i=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const a=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(a)||this.connections.set(a,{connectionTopicId:a,targetAccountId:o,targetInboundTopicId:i,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:a,originTopicId:i,processed:!1,memo:n.m})}for(const n of r){const e=n.connection_id,t=n.connection_topic_id,r=n.connected_account_id||"",o=n.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const i=`inb-${e}:${o}`;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:n.connection_topic_id,processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:i,originTopicId:n.connection_topic_id,processed:!1,memo:n.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 n=t.find((e=>"close_connection"===e.op));if(n){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:n.created||new Date,closedReason:n.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 n of r)this.connections.set(n.connectionTopicId,{...n,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[n,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(n,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(n,{...o,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const n=await this.baseClient.getTransactionRequests(e,t),o=[];for(const e of n)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}async getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const{messages:r}=await this.baseClient.getMessageStream(e),n=r.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===n.length)return;return n.sort(((e,t)=>t.created.getTime()-e.created.getTime())),n[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}function parseKey(e){if(e){if(e.contractID)return`ContractID: ${new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${Buffer$1$1.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${Buffer$1$1.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map((e=>parseKey(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=>parseKey(e))).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new v(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 HTSParser{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 f(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=libExports.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=libExports.proto.TokenSupplyType[e.supplyType]),t.adminKey=parseKey(e.adminKey),t.kycKey=parseKey(e.kycKey),t.freezeKey=parseKey(e.freezeKey),t.wipeKey=parseKey(e.wipeKey),t.supplyKey=parseKey(e.supplyKey),t.feeScheduleKey=parseKey(e.feeScheduleKey),t.pauseKey=parseKey(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new f(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map((e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new f(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:Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new u$5(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:Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new u$5(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:Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map((e=>Buffer$1$1.from(e).toString("base64")))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map((e=>Long.fromValue(e).toNumber()))),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(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 f(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=parseKey(e.adminKey),t.kycKey=parseKey(e.kycKey),t.freezeKey=parseKey(e.freezeKey),t.wipeKey=parseKey(e.wipeKey),t.supplyKey=parseKey(e.supplyKey),t.feeScheduleKey=parseKey(e.feeScheduleKey),t.pauseKey=parseKey(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new f(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new u$5(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 f(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:Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new u$5(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:Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new u$5(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:Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(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 u$5(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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=>Long.fromValue(e).toString()))),e.amount&&(t.amount=Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(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 f(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 u$5(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 f(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 u$5(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString()))),t}}class HCSParser{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=parseKey(e.adminKey),t.submitKey=parseKey(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new f(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=Buffer$1$1.from(e.message),n=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n)||n.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=n,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,n=e.chunkInfo.initialTransactionID.transactionValidStart;r&&n&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${n.seconds??0}.${n.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=parseKey(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=parseKey(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new f(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 FileParser{static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=parseKey({keyList:e.keys})),e.contents&&(t.contents=Buffer$1$1.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=Buffer$1$1.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=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=parseKey({keyList:e.keys})),e.contents&&(t.contents=Buffer$1$1.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 CryptoParser{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map((e=>{const t=new f(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=e$7.fromTinybars(Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(e$8.Hbar),isDecimal:!0}}))),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new u$5(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const n of r.transfers){const r=new f(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),o=Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:o})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new f(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new f(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=e$7.fromTinybars(Long.fromValue(e.initialBalance)).toString(e$8.Hbar)),e.key&&(t.key=parseKey(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=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 f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new f(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=parseKey(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${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=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 f(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=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 f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new f(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:e$7.fromTinybars(Long.fromValue(e.amount)).toString(e$8.Hbar)})))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map((e=>({tokenId:new u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new f(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount: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 u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new f(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=>Long.fromValue(e).toString()))),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new f(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 f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map((e=>Long.fromValue(e).toString())):[]})))),t}}class SCSParser{static parseContractCall(e){if(!e)return;const t=e$7.fromTinybars(Long.fromValue(e.amount??0)),r={contractId:new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(e$8.Hbar))};return e.functionParameters&&(r.functionParameters=Buffer$1$1.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=r.functionParameters.substring(0,8))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=e$7.fromTinybars(Long.fromValue(e.initialBalance)).toString(e$8.Hbar)),e.gas&&(t.gas=Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=parseKey(e.adminKey)),e.constructorParameters&&(t.constructorParameters=Buffer$1$1.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=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 u$6(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=Buffer$1$1.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=parseKey(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=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 f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=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 f(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 v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new f(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new v(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}}class UtilParser{static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}}class TransactionParser{static parseTransactionBody(e){try{const t=decodeBase64(e),r=libExports.proto.SchedulableTransactionBody.decode(t),n=this.getTransactionType(r),o={type:n,humanReadableType:this.getHumanReadableType(n),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(o.memo=r.memo),r.transactionFee){const e=e$7.fromTinybars(Long.fromValue(r.transactionFee));o.transactionFee=e.toString(e$8.Hbar)}return r.cryptoTransfer&&CryptoParser.parseCryptoTransfers(r.cryptoTransfer,o),r.cryptoDelete&&(o.cryptoDelete=CryptoParser.parseCryptoDelete(r.cryptoDelete)),r.cryptoCreateAccount&&(o.cryptoCreateAccount=CryptoParser.parseCryptoCreateAccount(r.cryptoCreateAccount)),r.cryptoUpdateAccount&&(o.cryptoUpdateAccount=CryptoParser.parseCryptoUpdateAccount(r.cryptoUpdateAccount)),r.cryptoApproveAllowance&&(o.cryptoApproveAllowance=CryptoParser.parseCryptoApproveAllowance(r.cryptoApproveAllowance)),r.cryptoDeleteAllowance&&(o.cryptoDeleteAllowance=CryptoParser.parseCryptoDeleteAllowance(r.cryptoDeleteAllowance)),r.contractCall&&(o.contractCall=SCSParser.parseContractCall(r.contractCall)),r.contractCreateInstance&&(o.contractCreate=SCSParser.parseContractCreate(r.contractCreateInstance)),r.contractUpdateInstance&&(o.contractUpdate=SCSParser.parseContractUpdate(r.contractUpdateInstance)),r.contractDeleteInstance&&(o.contractDelete=SCSParser.parseContractDelete(r.contractDeleteInstance)),r.tokenCreation&&(o.tokenCreation=HTSParser.parseTokenCreate(r.tokenCreation)),r.tokenMint&&(o.tokenMint=HTSParser.parseTokenMint(r.tokenMint)),r.tokenBurn&&(o.tokenBurn=HTSParser.parseTokenBurn(r.tokenBurn)),r.tokenUpdate&&(o.tokenUpdate=HTSParser.parseTokenUpdate(r.tokenUpdate)),r.tokenFeeScheduleUpdate&&(o.tokenFeeScheduleUpdate=HTSParser.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate)),r.tokenFreeze&&(o.tokenFreeze=HTSParser.parseTokenFreeze(r.tokenFreeze)),r.tokenUnfreeze&&(o.tokenUnfreeze=HTSParser.parseTokenUnfreeze(r.tokenUnfreeze)),r.tokenGrantKyc&&(o.tokenGrantKyc=HTSParser.parseTokenGrantKyc(r.tokenGrantKyc)),r.tokenRevokeKyc&&(o.tokenRevokeKyc=HTSParser.parseTokenRevokeKyc(r.tokenRevokeKyc)),r.tokenPause&&(o.tokenPause=HTSParser.parseTokenPause(r.tokenPause)),r.tokenUnpause&&(o.tokenUnpause=HTSParser.parseTokenUnpause(r.tokenUnpause)),r.tokenWipe&&(o.tokenWipeAccount=HTSParser.parseTokenWipeAccount(r.tokenWipe)),r.tokenDeletion&&(o.tokenDelete=HTSParser.parseTokenDelete(r.tokenDeletion)),r.tokenAssociate&&(o.tokenAssociate=HTSParser.parseTokenAssociate(r.tokenAssociate)),r.tokenDissociate&&(o.tokenDissociate=HTSParser.parseTokenDissociate(r.tokenDissociate)),r.consensusCreateTopic&&(o.consensusCreateTopic=HCSParser.parseConsensusCreateTopic(r.consensusCreateTopic)),r.consensusSubmitMessage&&(o.consensusSubmitMessage=HCSParser.parseConsensusSubmitMessage(r.consensusSubmitMessage)),r.consensusUpdateTopic&&(o.consensusUpdateTopic=HCSParser.parseConsensusUpdateTopic(r.consensusUpdateTopic)),r.consensusDeleteTopic&&(o.consensusDeleteTopic=HCSParser.parseConsensusDeleteTopic(r.consensusDeleteTopic)),r.fileCreate&&(o.fileCreate=FileParser.parseFileCreate(r.fileCreate)),r.fileAppend&&(o.fileAppend=FileParser.parseFileAppend(r.fileAppend)),r.fileUpdate&&(o.fileUpdate=FileParser.parseFileUpdate(r.fileUpdate)),r.fileDelete&&(o.fileDelete=FileParser.parseFileDelete(r.fileDelete)),r.utilPrng&&(o.utilPrng=UtilParser.parseUtilPrng(r.utilPrng)),o}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 n of e.transfers){const e=parseFloat(n.amount);let o=n.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${n.accountId} (${o} ℏ)`):e>0&&r.push(`${n.accountId} (${o} ℏ)`)}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 n of e.tokenTransfers)t[n.tokenId]||(t[n.tokenId]=[]),t[n.tokenId].push(n);const r=[];for(const[e,n]of Object.entries(t)){const t=[],o=[];for(const e of n){const r=parseFloat(e.amount.toString());r<0?t.push(`${e.accountId} (${Math.abs(r)})`):r>0&&o.push(`${e.accountId} (${r})`)}t.length>0&&o.length>0&&r.push(`Transfer of token ${e} from ${t.join(", ")} to ${o.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: ${Buffer$1$1.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 n of e.tokenTransfers)t[n.tokenId]||(t[n.tokenId]=[]),t[n.tokenId].push(n);const r=[];for(const[e,n]of Object.entries(t)){const t=n.filter((e=>e.amount<0)).map((e=>`${e.accountId} (${Math.abs(e.amount)})`)),o=n.filter((e=>e.amount>0)).map((e=>`${e.accountId} (${e.amount})`));t.length>0&&o.length>0?r.push(`Transfer of token ${e} from ${t.join(", ")} to ${o.join(", ")}`):o.length>0?r.push(`Token ${e} received by ${o.join(", ")}`):t.length>0&&r.push(`Token ${e} sent from ${t.join(", ")}`)}if(r.length>0)return r.join("; ")}return"Unknown Transaction"}}var CustomFeeType=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(CustomFeeType||{});class FeeConfigBuilder{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new HederaMirrorNode(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,n,o=[]){return new FeeConfigBuilder({network:r,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,n,o,i=[],a){const s=new FeeConfigBuilder({network:n,logger:o,defaultCollectorAccountId:r});return await s.addTokenFee(e,t,r,a,i),s}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:CustomFeeType.FIXED_FEE}),this}async addTokenFee(e,t,r,n,o=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let i=n;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(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),i=0}return this.customFees.push({feeAmount:{amount:e*10**i,decimals:i},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...o],type:CustomFeeType.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)}}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$2?global$2:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},r={byteLength:function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,d=s>0?a-4:a;for(r=0;r<d;r+=4)t=o[e.charCodeAt(r)]<<18|o[e.charCodeAt(r+1)]<<12|o[e.charCodeAt(r+2)]<<6|o[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},fromByteArray:function(e){for(var t,r=e.length,o=r%3,i=[],a=16383,s=0,c=r-o;s<c;s+=a)i.push(u(e,s,s+a>c?c:s+a));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")}},n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var o,i,a=[],s=t;s<r;s+=3)o=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(i=o)>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63;var l={
|
|
149
|
+
*/function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,o=requireMimeDb(),i=requirePathBrowserify().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),r=t&&o[t[1].toLowerCase()];return r&&r.charset?r.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var r=-1===t.indexOf("/")?e.lookup(t):t;if(!r)return!1;if(-1===r.indexOf("charset")){var n=e.charset(r);n&&(r+="; charset="+n.toLowerCase())}return r},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var r=a.exec(t),n=r&&e.extensions[r[1].toLowerCase()];if(!n||!n.length)return!1;return n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var r=i("x."+t).toLowerCase().substr(1);if(!r)return!1;return e.types[r]||!1},e.types=Object.create(null),t=e.extensions,r=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach((function(e){var i=o[e],a=i.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(r[c]){var u=n.indexOf(o[r[c]].source),l=n.indexOf(i.source);if("application/octet-stream"!==r[c]&&(u>l||u===l&&"application/"===r[c].substr(0,12)))continue}r[c]=e}}}))}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes(),util$1,util2,objectUtil,objectUtil2;util2=util$1||(util$1={}),util2.assertEqual=e=>e,util2.assertIs=function(e){},util2.assertNever=function(e){throw new Error},util2.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},util2.getValidEnumValues=e=>{const t=util2.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),r={};for(const n of t)r[n]=e[n];return util2.objectValues(r)},util2.objectValues=e=>util2.objectKeys(e).map((function(t){return e[t]})),util2.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},util2.find=(e,t)=>{for(const r of e)if(t(r))return r},util2.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,util2.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},util2.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,objectUtil2=objectUtil||(objectUtil={}),objectUtil2.mergeShapes=(e,t)=>({...e,...t});const ZodParsedType=util$1.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=e=>{switch(typeof e){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(e)?ZodParsedType.array:null===e?ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util$1.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const o of e.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)r._errors.push(t(o));else{let e=r,n=0;for(;n<o.path.length;){const r=o.path[n];n===o.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(o))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util$1.jsonStringifyReplacer,2)}get isEmpty(){return 0===this.issues.length}flatten(e=e=>e.message){const t={},r=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}ZodError.create=e=>new ZodError(e);const errorMap=(e,t)=>{let r;switch(e.code){case ZodIssueCode.invalid_type:r=e.received===ZodParsedType.undefined?"Required":`Expected ${e.expected}, received ${e.received}`;break;case ZodIssueCode.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,util$1.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$1.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$1.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util$1.joinValues(e.options)}, received '${e.received}'`;break;case ZodIssueCode.invalid_arguments:r="Invalid function arguments";break;case ZodIssueCode.invalid_return_type:r="Invalid function return type";break;case ZodIssueCode.invalid_date:r="Invalid date";break;case ZodIssueCode.invalid_string:"object"==typeof e.validation?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,"number"==typeof e.validation.position&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:util$1.assertNever(e.validation):r="regex"!==e.validation?`Invalid ${e.validation}`:"Invalid";break;case ZodIssueCode.too_small:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:"date"===e.type?`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:"Invalid input";break;case ZodIssueCode.too_big:r="array"===e.type?`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:"string"===e.type?`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:"number"===e.type?`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"bigint"===e.type?`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:"date"===e.type?`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:"Invalid input";break;case ZodIssueCode.custom:r="Invalid input";break;case ZodIssueCode.invalid_intersection_types:r="Intersection results could not be merged";break;case ZodIssueCode.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ZodIssueCode.not_finite:r="Number must be finite";break;default:r=t.defaultError,util$1.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function setErrorMap(e){overrideErrorMap=e}function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],a={...o,path:i};if(void 0!==o.message)return{...o,path:i,message:o.message};let s="";const c=n.filter((e=>!!e)).slice().reverse();for(const u of c)s=u(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}},EMPTY_PATH=[];function addIssueToContext(e,t){const r=getErrorMap(),n=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter((e=>!!e))});e.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const e=await n.key,t=await n.value;r.push({key:e,value:t})}return ParseStatus.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:o}=n;if("aborted"===t.status)return INVALID;if("aborted"===o.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===o.status&&e.dirty(),"__proto__"===t.value||void 0===o.value&&!n.alwaysSet||(r[t.value]=o.value)}return{status:e.value,value:r}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=e=>({status:"dirty",value:e}),OK=e=>({status:"valid",value:e}),isAborted=e=>"aborted"===e.status,isDirty=e=>"dirty"===e.status,isValid=e=>"valid"===e.status,isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise;function __classPrivateFieldGet(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function __classPrivateFieldSet(e,t,r,n,o){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var errorUtil,errorUtil2,_ZodEnum_cache,_ZodNativeEnum_cache;"function"==typeof SuppressedError&&SuppressedError,errorUtil2=errorUtil||(errorUtil={}),errorUtil2.errToObj=e=>"string"==typeof e?{message:e}:e||{},errorUtil2.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class ParseInputLazyPath{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:o};return{errorMap:(t,o)=>{var i,a;const{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:o.defaultError}:void 0===o.data?{message:null!==(i=null!=s?s:n)&&void 0!==i?i:o.defaultError}:"invalid_type"!==t.code?{message:o.defaultError}:{message:null!==(a=null!=s?s:r)&&void 0!==a?a:o.defaultError}},description:o}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},o=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,o)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(o){(null===(r=null===(t=null==o?void 0:o.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>isValid(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,o)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const o=e(t),i=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&o instanceof Promise?o.then((e=>!!e||(i(),!1))):!!o||(i(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`);return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${e.precision?"+":"?"}`}function timeRegex(e){return new RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function isValidIP(e,t){return!("v4"!==t&&t||!ipv4Regex.test(e))||!("v6"!==t&&t||!ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return"object"==typeof o&&null!==o&&(!(!o.typ||!o.alg)&&(!t||o.alg===t))}catch(r){return!1}}function isValidCidr(e,t){return!("v4"!==t&&t||!ipv4CidrRegex.test(e))||!("v6"!==t&&t||!ipv6CidrRegex.test(e))}class ZodString extends ZodType{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ZodParsedType.string){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}const t=new ParseStatus;let r;for(const o of this._def.checks)if("min"===o.kind)e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("max"===o.kind)e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("length"===o.kind){const n=e.data.length>o.value,i=e.data.length<o.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),t.dirty())}else if("email"===o.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("emoji"===o.kind)emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("uuid"===o.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("nanoid"===o.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid"===o.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid2"===o.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("ulid"===o.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("url"===o.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()}else if("regex"===o.kind){o.regex.lastIndex=0;o.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty())}else if("trim"===o.kind)e.data=e.data.trim();else if("includes"===o.kind)e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),t.dirty());else if("toLowerCase"===o.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===o.kind)e.data=e.data.toUpperCase();else if("startsWith"===o.kind)e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),t.dirty());else if("endsWith"===o.kind)e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),t.dirty());else if("datetime"===o.kind){datetimeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),t.dirty())}else if("date"===o.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),t.dirty())}else if("time"===o.kind){timeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),t.dirty())}else"duration"===o.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"ip"===o.kind?isValidIP(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"jwt"===o.kind?isValidJWT(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"cidr"===o.kind?isValidCidr(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64"===o.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64url"===o.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):util$1.assertNever(o);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(r)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...errorUtil.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...errorUtil.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n;return parseInt(e.toFixed(o).replace(".",""))%parseInt(t.toFixed(o).replace(".",""))/Math.pow(10,o)}ZodString.create=e=>{var t;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType.number){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t;const r=new ParseStatus;for(const n of this._def.checks)if("int"===n.kind)util$1.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty());else if("min"===n.kind){(n.inclusive?e.data<n.value:e.data<=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else if("max"===n.kind){(n.inclusive?e.data>n.value:e.data>=n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty())}else"multipleOf"===n.kind?0!==floatSafeRemainder(e.data,n.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):"finite"===n.kind?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_finite,message:n.message}),r.dirty()):util$1.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodNumber({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodNumber({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:errorUtil.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:errorUtil.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:errorUtil.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:errorUtil.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find((e=>"int"===e.kind||"multipleOf"===e.kind&&util$1.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):util$1.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=e=>{var t;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodBoolean extends ZodType{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodDate extends ZodType{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType.date){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(isNaN(e.data.getTime())){return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID}const t=new ParseStatus;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util$1.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ZodDate.create=e=>new ZodDate({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(e||o)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:o?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new ParseInputLazyPath(t,e,t.path,r))))).then((e=>ParseStatus.mergeArray(r,e)));const o=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function deepPartialify(e){if(e instanceof ZodObject){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...e._def,shape:()=>t})}return e instanceof ZodArray?new ZodArray({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof ZodTuple?ZodTuple.create(e.items.map((e=>deepPartialify(e)))):e}ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util$1.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==ZodParsedType.object){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)o.includes(s)||i.push(s);const a=[];for(const s of o){const e=n[s],t=r.data[s];a.push({key:{status:"valid",value:s},value:e._parse(new ParseInputLazyPath(r,t,r.path,s)),alwaysSet:s in r.data})}if(this._def.catchall instanceof ZodNever){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>ParseStatus.mergeObjectSync(t,e))):ParseStatus.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,o,i,a;const s=null!==(i=null===(o=(n=this._def).errorMap)||void 0===o?void 0:o.call(n,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=errorUtil.errToObj(e).message)&&void 0!==a?a:s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};return util$1.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new ZodObject({...this._def,shape:()=>t})}required(e){const t={};return util$1.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}})),new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util$1.objectKeys(this.shape))}}ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const r=e.map((e=>new ZodError(e.ctx.common.issues)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:r}),INVALID}));{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util$1.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;const r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const o of t){const t=getDiscriminator(o.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(n.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);n.set(r,o)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...processCreateParams(r)})}}function mergeValues(e,t){const r=getParsedType(e),n=getParsedType(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType.object&&n===ZodParsedType.object){const r=util$1.objectKeys(t),n=util$1.objectKeys(e).filter((e=>-1!==r.indexOf(e))),o={...e,...t};for(const i of n){const r=mergeValues(e[i],t[i]);if(!r.valid)return{valid:!1};o[i]=r.data}return{valid:!0,data:o}}if(r===ZodParsedType.array&&n===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const o=mergeValues(e[n],t[n]);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}return r===ZodParsedType.date&&n===ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted(e)||isAborted(n))return INVALID;const o=mergeValues(e.value,n.value);return o.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:o.data}):(addIssueToContext(r,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ZodIntersection.create=(e,t,r)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>ParseStatus.mergeArray(t,e))):ParseStatus.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const n=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)n.push({key:o._parse(new ParseInputLazyPath(r,a,r.path,a)),value:i._parse(new ParseInputLazyPath(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ParseStatus.mergeObjectAsync(t,n):ParseStatus.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ZodRecord(t instanceof ZodType?{keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)}:{keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;const n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[i,"key"])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,o=await r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,o=r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}}}ZodMap.create=(e,t,r)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const o=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return INVALID;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function r(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:r}})}function n(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:r}})}const o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ZodPromise){const e=this;return OK((async function(...t){const a=new ZodError([]),s=await e._def.args.parseAsync(t,o).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,s);return await e._def.returns._def.type.parseAsync(c,o).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return OK((function(...t){const a=e._def.args.safeParse(t,o);if(!a.success)throw new ZodError([r(t,a.error)]);const s=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(s,o);if(!c.success)throw new ZodError([n(s,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(r)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util$1.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:r}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}_ZodEnum_cache=new WeakMap,ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(e){const t=util$1.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util$1.objectValues(t);return addIssueToContext(r,{expected:util$1.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util$1.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(e.data)){const e=util$1.objectValues(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap,ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&!1===t.common.async)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const r=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){const e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return INVALID;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}));{if("aborted"===t.value)return INVALID;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return e;const i=n.transform(e.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}util$1.assertNever(n)}}ZodEffects.create=(e,t,r)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(e,t,r)=>new ZodEffects({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...processCreateParams(t)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...processCreateParams(t)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),r=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function cleanParams(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function custom(e,t={},r){return e?ZodAny.create().superRefine(((n,o)=>{var i,a;const s=e(n);if(s instanceof Promise)return s.then((e=>{var i,a;if(!e){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}}));if(!s){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}})):ZodAny.create()}ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind,ZodFirstPartyTypeKind2;ZodFirstPartyTypeKind2=ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}),ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly";const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom((t=>t instanceof e),t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:e=>ZodString.create({...e,coerce:!0}),number:e=>ZodNumber.create({...e,coerce:!0}),boolean:e=>ZodBoolean.create({...e,coerce:!0}),bigint:e=>ZodBigInt.create({...e,coerce:!0}),date:e=>ZodDate.create({...e,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap:setErrorMap,getErrorMap:getErrorMap,makeIssue:makeIssue,EMPTY_PATH:EMPTY_PATH,addIssueToContext:addIssueToContext,ParseStatus:ParseStatus,INVALID:INVALID,DIRTY:DIRTY,OK:OK,isAborted:isAborted,isDirty:isDirty,isValid:isValid,isAsync:isAsync,get util(){return util$1},get objectUtil(){return objectUtil},ZodParsedType:ZodParsedType,getParsedType:getParsedType,ZodType:ZodType,datetimeRegex:datetimeRegex,ZodString:ZodString,ZodNumber:ZodNumber,ZodBigInt:ZodBigInt,ZodBoolean:ZodBoolean,ZodDate:ZodDate,ZodSymbol:ZodSymbol,ZodUndefined:ZodUndefined,ZodNull:ZodNull,ZodAny:ZodAny,ZodUnknown:ZodUnknown,ZodNever:ZodNever,ZodVoid:ZodVoid,ZodArray:ZodArray,ZodObject:ZodObject,ZodUnion:ZodUnion,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodIntersection:ZodIntersection,ZodTuple:ZodTuple,ZodRecord:ZodRecord,ZodMap:ZodMap,ZodSet:ZodSet,ZodFunction:ZodFunction,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodEnum:ZodEnum,ZodNativeEnum:ZodNativeEnum,ZodPromise:ZodPromise,ZodEffects:ZodEffects,ZodTransformer:ZodEffects,ZodOptional:ZodOptional,ZodNullable:ZodNullable,ZodDefault:ZodDefault,ZodCatch:ZodCatch,ZodNaN:ZodNaN,BRAND:BRAND,ZodBranded:ZodBranded,ZodPipeline:ZodPipeline,ZodReadonly:ZodReadonly,custom:custom,Schema:ZodType,ZodSchema:ZodType,late:late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce:coerce,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean:oboolean,onumber:onumber,optional:optionalType,ostring:ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER:NEVER,ZodIssueCode:ZodIssueCode,quotelessJson:quotelessJson,ZodError:ZodError});function bind(e,t){return function(){return e.apply(t,arguments)}}const{toString:toString}=Object.prototype,{getPrototypeOf:getPrototypeOf}=Object,kindOf=(e=>t=>{const r=toString.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),kindOfTest=e=>(e=e.toLowerCase(),t=>kindOf(t)===e),typeOfTest=e=>t=>typeof t===e,{isArray:isArray}=Array,isUndefined=typeOfTest("undefined");function isBuffer(e){return null!==e&&!isUndefined(e)&&null!==e.constructor&&!isUndefined(e.constructor)&&isFunction(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const isArrayBuffer=kindOfTest("ArrayBuffer");function isArrayBufferView(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&isArrayBuffer(e.buffer),t}const isString=typeOfTest("string"),isFunction=typeOfTest("function"),isNumber=typeOfTest("number"),isObject=e=>null!==e&&"object"==typeof e,isBoolean=e=>!0===e||!1===e,isPlainObject=e=>{if("object"!==kindOf(e))return!1;const t=getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)},isDate=kindOfTest("Date"),isFile=kindOfTest("File"),isBlob=kindOfTest("Blob"),isFileList=kindOfTest("FileList"),isStream=e=>isObject(e)&&isFunction(e.pipe),isFormData=e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||isFunction(e.append)&&("formdata"===(t=kindOf(e))||"object"===t&&isFunction(e.toString)&&"[object FormData]"===e.toString()))},isURLSearchParams=kindOfTest("URLSearchParams"),[isReadableStream,isRequest,isResponse,isHeaders]=["ReadableStream","Request","Response","Headers"].map(kindOfTest),trim=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function forEach(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let n,o;if("object"!=typeof e&&(e=[e]),isArray(e))for(n=0,o=e.length;n<o;n++)t.call(null,e[n],n,e);else{const o=r?Object.getOwnPropertyNames(e):Object.keys(e),i=o.length;let a;for(n=0;n<i;n++)a=o[n],t.call(null,e[a],a,e)}}function findKey(e,t){t=t.toLowerCase();const r=Object.keys(e);let n,o=r.length;for(;o-- >0;)if(n=r[o],t===n.toLowerCase())return n;return null}const _global="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:global$2,isContextDefined=e=>!isUndefined(e)&&e!==_global;function merge(){const{caseless:e}=isContextDefined(this)&&this||{},t={},r=(r,n)=>{const o=e&&findKey(t,n)||n;isPlainObject(t[o])&&isPlainObject(r)?t[o]=merge(t[o],r):isPlainObject(r)?t[o]=merge({},r):isArray(r)?t[o]=r.slice():t[o]=r};for(let n=0,o=arguments.length;n<o;n++)arguments[n]&&forEach(arguments[n],r);return t}const extend=(e,t,r,{allOwnKeys:n}={})=>(forEach(t,((t,n)=>{r&&isFunction(t)?e[n]=bind(t,r):e[n]=t}),{allOwnKeys:n}),e),stripBOM=e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits=(e,t,r,n)=>{e.prototype=Object.create(t.prototype,n),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject=(e,t,r,n)=>{let o,i,a;const s={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),i=o.length;i-- >0;)a=o[i],n&&!n(a,e,t)||s[a]||(t[a]=e[a],s[a]=!0);e=!1!==r&&getPrototypeOf(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},endsWith=(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const n=e.indexOf(t,r);return-1!==n&&n===r},toArray=e=>{if(!e)return null;if(isArray(e))return e;let t=e.length;if(!isNumber(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},isTypedArray$1=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&getPrototypeOf(Uint8Array)),forEachEntry=(e,t)=>{const r=(e&&e[Symbol.iterator]).call(e);let n;for(;(n=r.next())&&!n.done;){const r=n.value;t.call(e,r[0],r[1])}},matchAll=(e,t)=>{let r;const n=[];for(;null!==(r=e.exec(t));)n.push(r);return n},isHTMLForm=kindOfTest("HTMLFormElement"),toCamelCase=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,(function(e,t,r){return t.toUpperCase()+r})),hasOwnProperty=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),isRegExp=kindOfTest("RegExp"),reduceDescriptors=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),n={};forEach(r,((r,o)=>{let i;!1!==(i=t(r,o,e))&&(n[o]=i||r)})),Object.defineProperties(e,n)},freezeMethods=e=>{reduceDescriptors(e,((t,r)=>{if(isFunction(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const n=e[r];isFunction(n)&&(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={},n=e=>{e.forEach((e=>{r[e]=!0}))};return isArray(e)?n(e):n(String(e).split(t)),r},noop=()=>{},toFiniteNumber=(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t;function isSpecCompliantForm(e){return!!(e&&isFunction(e.append)&&"FormData"===e[Symbol.toStringTag]&&e[Symbol.iterator])}const toJSONObject=e=>{const t=new Array(10),r=(e,n)=>{if(isObject(e)){if(t.indexOf(e)>=0)return;if(!("toJSON"in e)){t[n]=e;const o=isArray(e)?[]:{};return forEach(e,((e,t)=>{const i=r(e,n+1);!isUndefined(i)&&(o[t]=i)})),t[n]=void 0,o}}return e};return r(e,0)},isAsyncFn=kindOfTest("AsyncFunction"),isThenable=e=>e&&(isObject(e)||isFunction(e))&&isFunction(e.then)&&isFunction(e.catch),_setImmediate=((e,t)=>e?setImmediate:t?((e,t)=>(_global.addEventListener("message",(({source:r,data:n})=>{r===_global&&n===e&&t.length&&t.shift()()}),!1),r=>{t.push(r),_global.postMessage(e,"*")}))(`axios@${Math.random()}`,[]):e=>setTimeout(e))("function"==typeof setImmediate,isFunction(_global.postMessage)),asap="undefined"!=typeof queueMicrotask?queueMicrotask.bind(_global):void 0!==process$1$1&&process$1$1.nextTick||_setImmediate,utils$1={isArray:isArray,isArrayBuffer:isArrayBuffer,isBuffer:isBuffer,isFormData:isFormData,isArrayBufferView:isArrayBufferView,isString:isString,isNumber:isNumber,isBoolean:isBoolean,isObject:isObject,isPlainObject:isPlainObject,isReadableStream:isReadableStream,isRequest:isRequest,isResponse:isResponse,isHeaders:isHeaders,isUndefined:isUndefined,isDate:isDate,isFile:isFile,isBlob:isBlob,isRegExp:isRegExp,isFunction:isFunction,isStream:isStream,isURLSearchParams:isURLSearchParams,isTypedArray:isTypedArray$1,isFileList:isFileList,forEach:forEach,merge:merge,extend:extend,trim:trim,stripBOM:stripBOM,inherits:inherits,toFlatObject:toFlatObject,kindOf:kindOf,kindOfTest:kindOfTest,endsWith:endsWith,toArray:toArray,forEachEntry:forEachEntry,matchAll:matchAll,isHTMLForm:isHTMLForm,hasOwnProperty:hasOwnProperty,hasOwnProp:hasOwnProperty,reduceDescriptors:reduceDescriptors,freezeMethods:freezeMethods,toObjectSet:toObjectSet,toCamelCase:toCamelCase,noop:noop,toFiniteNumber:toFiniteNumber,findKey:findKey,global:_global,isContextDefined:isContextDefined,isSpecCompliantForm:isSpecCompliantForm,toJSONObject:toJSONObject,isAsyncFn:isAsyncFn,isThenable:isThenable,setImmediate:_setImmediate,asap:asap};function AxiosError$1(e,t,r,n,o){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),n&&(this.request=n),o&&(this.response=o,this.status=o.status?o.status:null)}utils$1.inherits(AxiosError$1,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:utils$1.toJSONObject(this.config),code:this.code,status:this.status}}});const prototype$1=AxiosError$1.prototype,descriptors={};["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=>{descriptors[e]={value:e}})),Object.defineProperties(AxiosError$1,descriptors),Object.defineProperty(prototype$1,"isAxiosError",{value:!0}),AxiosError$1.from=(e,t,r,n,o,i)=>{const a=Object.create(prototype$1);return utils$1.toFlatObject(e,a,(function(e){return e!==Error.prototype}),(e=>"isAxiosError"!==e)),AxiosError$1.call(a,e.message,t,r,n,o),a.cause=e,a.name=e.name,i&&Object.assign(a,i),a};const httpAdapter=null;function isVisitable(e){return utils$1.isPlainObject(e)||utils$1.isArray(e)}function removeBrackets(e){return utils$1.endsWith(e,"[]")?e.slice(0,-2):e}function renderKey(e,t,r){return e?e.concat(t).map((function(e,t){return e=removeBrackets(e),!r&&t?"["+e+"]":e})).join(r?".":""):t}function isFlatArray(e){return utils$1.isArray(e)&&!e.some(isVisitable)}const predicates=utils$1.toFlatObject(utils$1,{},null,(function(e){return/^is[A-Z]/.test(e)}));function toFormData$1(e,t,r){if(!utils$1.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const n=(r=utils$1.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,(function(e,t){return!utils$1.isUndefined(t[e])}))).metaTokens,o=r.visitor||u,i=r.dots,a=r.indexes,s=(r.Blob||"undefined"!=typeof Blob&&Blob)&&utils$1.isSpecCompliantForm(t);if(!utils$1.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(utils$1.isDate(e))return e.toISOString();if(!s&&utils$1.isBlob(e))throw new AxiosError$1("Blob is not supported. Use a Buffer instead.");return utils$1.isArrayBuffer(e)||utils$1.isTypedArray(e)?s&&"function"==typeof Blob?new Blob([e]):Buffer.from(e):e}function u(e,r,o){let s=e;if(e&&!o&&"object"==typeof e)if(utils$1.endsWith(r,"{}"))r=n?r:r.slice(0,-2),e=JSON.stringify(e);else if(utils$1.isArray(e)&&isFlatArray(e)||(utils$1.isFileList(e)||utils$1.endsWith(r,"[]"))&&(s=utils$1.toArray(e)))return r=removeBrackets(r),s.forEach((function(e,n){!utils$1.isUndefined(e)&&null!==e&&t.append(!0===a?renderKey([r],n,i):null===a?r:r+"[]",c(e))})),!1;return!!isVisitable(e)||(t.append(renderKey(o,r,i),c(e)),!1)}const l=[],d=Object.assign(predicates,{defaultVisitor:u,convertValue:c,isVisitable:isVisitable});if(!utils$1.isObject(e))throw new TypeError("data must be an object");return function e(r,n){if(!utils$1.isUndefined(r)){if(-1!==l.indexOf(r))throw Error("Circular reference detected in "+n.join("."));l.push(r),utils$1.forEach(r,(function(r,i){!0===(!(utils$1.isUndefined(r)||null===r)&&o.call(t,r,utils$1.isString(i)?i.trim():i,n,d))&&e(r,n?n.concat(i):[i])})),l.pop()}}(e),t}function encode$1(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,(function(e){return t[e]}))}function AxiosURLSearchParams(e,t){this._pairs=[],e&&toFormData$1(e,this,t)}const prototype=AxiosURLSearchParams.prototype;function encode(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function buildURL(e,t,r){if(!t)return e;const n=r&&r.encode||encode;utils$1.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let i;if(i=o?o(t,r):utils$1.isURLSearchParams(t)?t.toString():new AxiosURLSearchParams(t,r).toString(n),i){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+i}return e}prototype.append=function(e,t){this._pairs.push([e,t])},prototype.toString=function(e){const t=e?function(t){return e.call(this,t,encode$1)}:encode$1;return this._pairs.map((function(e){return t(e[0])+"="+t(e[1])}),"").join("&")};class InterceptorManager{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){utils$1.forEach(this.handlers,(function(t){null!==t&&e(t)}))}}const transitionalDefaults={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},URLSearchParams$1="undefined"!=typeof URLSearchParams?URLSearchParams:AxiosURLSearchParams,FormData$1="undefined"!=typeof FormData?FormData:null,Blob$1="undefined"!=typeof Blob?Blob:null,platform$1={isBrowser:!0,classes:{URLSearchParams:URLSearchParams$1,FormData:FormData$1,Blob:Blob$1},protocols:["http","https","file","blob","url","data"]},hasBrowserEnv="undefined"!=typeof window&&"undefined"!=typeof document,_navigator="object"==typeof navigator&&navigator||void 0,hasStandardBrowserEnv=hasBrowserEnv&&(!_navigator||["ReactNative","NativeScript","NS"].indexOf(_navigator.product)<0),hasStandardBrowserWebWorkerEnv="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,origin=hasBrowserEnv&&window.location.href||"http://localhost",utils=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:hasBrowserEnv,hasStandardBrowserEnv:hasStandardBrowserEnv,hasStandardBrowserWebWorkerEnv:hasStandardBrowserWebWorkerEnv,navigator:_navigator,origin:origin},Symbol.toStringTag,{value:"Module"})),platform={...utils,...platform$1};function toURLEncodedForm(e,t){return toFormData$1(e,new platform.classes.URLSearchParams,Object.assign({visitor:function(e,t,r,n){return platform.isNode&&utils$1.isBuffer(e)?(this.append(t,e.toString("base64")),!1):n.defaultVisitor.apply(this,arguments)}},t))}function parsePropPath(e){return utils$1.matchAll(/\w+|\[(\w*)]/g,e).map((e=>"[]"===e[0]?"":e[1]||e[0]))}function arrayToObject(e){const t={},r=Object.keys(e);let n;const o=r.length;let i;for(n=0;n<o;n++)i=r[n],t[i]=e[i];return t}function formDataToJSON(e){function t(e,r,n,o){let i=e[o++];if("__proto__"===i)return!0;const a=Number.isFinite(+i),s=o>=e.length;if(i=!i&&utils$1.isArray(n)?n.length:i,s)return utils$1.hasOwnProp(n,i)?n[i]=[n[i],r]:n[i]=r,!a;n[i]&&utils$1.isObject(n[i])||(n[i]=[]);return t(e,r,n[i],o)&&utils$1.isArray(n[i])&&(n[i]=arrayToObject(n[i])),!a}if(utils$1.isFormData(e)&&utils$1.isFunction(e.entries)){const r={};return utils$1.forEachEntry(e,((e,n)=>{t(parsePropPath(e),n,r,0)})),r}return null}function stringifySafely(e,t,r){if(utils$1.isString(e))try{return(t||JSON.parse)(e),utils$1.trim(e)}catch(n){if("SyntaxError"!==n.name)throw n}return(r||JSON.stringify)(e)}const defaults={transitional:transitionalDefaults,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",n=r.indexOf("application/json")>-1,o=utils$1.isObject(e);o&&utils$1.isHTMLForm(e)&&(e=new FormData(e));if(utils$1.isFormData(e))return n?JSON.stringify(formDataToJSON(e)):e;if(utils$1.isArrayBuffer(e)||utils$1.isBuffer(e)||utils$1.isStream(e)||utils$1.isFile(e)||utils$1.isBlob(e)||utils$1.isReadableStream(e))return e;if(utils$1.isArrayBufferView(e))return e.buffer;if(utils$1.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return toURLEncodedForm(e,this.formSerializer).toString();if((i=utils$1.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return toFormData$1(i?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||n?(t.setContentType("application/json",!1),stringifySafely(e)):e}],transformResponse:[function(e){const t=this.transitional||defaults.transitional,r=t&&t.forcedJSONParsing,n="json"===this.responseType;if(utils$1.isResponse(e)||utils$1.isReadableStream(e))return e;if(e&&utils$1.isString(e)&&(r&&!this.responseType||n)){const r=!(t&&t.silentJSONParsing)&&n;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw AxiosError$1.from(o,AxiosError$1.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:platform.classes.FormData,Blob:platform.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};utils$1.forEach(["delete","get","head","post","put","patch"],(e=>{defaults.headers[e]={}}));const ignoreDuplicateOf=utils$1.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"]),parseHeaders=e=>{const t={};let r,n,o;return e&&e.split("\n").forEach((function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),n=e.substring(o+1).trim(),!r||t[r]&&ignoreDuplicateOf[r]||("set-cookie"===r?t[r]?t[r].push(n):t[r]=[n]:t[r]=t[r]?t[r]+", "+n:n)})),t},$internals=Symbol("internals");function normalizeHeader(e){return e&&String(e).trim().toLowerCase()}function normalizeValue(e){return!1===e||null==e?e:utils$1.isArray(e)?e.map(normalizeValue):String(e)}function parseTokens(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=r.exec(e);)t[n[1]]=n[2];return t}const isValidHeaderName=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function matchHeaderValue(e,t,r,n,o){return utils$1.isFunction(n)?n.call(this,t,r):(o&&(t=r),utils$1.isString(t)?utils$1.isString(n)?-1!==t.indexOf(n):utils$1.isRegExp(n)?n.test(t):void 0:void 0)}function formatHeader(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,((e,t,r)=>t.toUpperCase()+r))}function buildAccessors(e,t){const r=utils$1.toCamelCase(" "+t);["get","set","has"].forEach((n=>{Object.defineProperty(e,n+r,{value:function(e,r,o){return this[n].call(this,t,e,r,o)},configurable:!0})}))}let AxiosHeaders$1=class{constructor(e){e&&this.set(e)}set(e,t,r){const n=this;function o(e,t,r){const o=normalizeHeader(t);if(!o)throw new Error("header name must be a non-empty string");const i=utils$1.findKey(n,o);(!i||void 0===n[i]||!0===r||void 0===r&&!1!==n[i])&&(n[i||t]=normalizeValue(e))}const i=(e,t)=>utils$1.forEach(e,((e,r)=>o(e,r,t)));if(utils$1.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(utils$1.isString(e)&&(e=e.trim())&&!isValidHeaderName(e))i(parseHeaders(e),t);else if(utils$1.isHeaders(e))for(const[a,s]of e.entries())o(s,a,r);else null!=e&&o(t,e,r);return this}get(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return parseTokens(e);if(utils$1.isFunction(t))return t.call(this,e,r);if(utils$1.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=normalizeHeader(e)){const r=utils$1.findKey(this,e);return!(!r||void 0===this[r]||t&&!matchHeaderValue(this,this[r],r,t))}return!1}delete(e,t){const r=this;let n=!1;function o(e){if(e=normalizeHeader(e)){const o=utils$1.findKey(r,e);!o||t&&!matchHeaderValue(r,r[o],o,t)||(delete r[o],n=!0)}}return utils$1.isArray(e)?e.forEach(o):o(e),n}clear(e){const t=Object.keys(this);let r=t.length,n=!1;for(;r--;){const o=t[r];e&&!matchHeaderValue(this,this[o],o,e,!0)||(delete this[o],n=!0)}return n}normalize(e){const t=this,r={};return utils$1.forEach(this,((n,o)=>{const i=utils$1.findKey(r,o);if(i)return t[i]=normalizeValue(n),void delete t[o];const a=e?formatHeader(o):String(o).trim();a!==o&&delete t[o],t[a]=normalizeValue(n),r[a]=!0})),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return utils$1.forEach(this,((r,n)=>{null!=r&&!1!==r&&(t[n]=e&&utils$1.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[$internals]=this[$internals]={accessors:{}}).accessors,r=this.prototype;function n(e){const n=normalizeHeader(e);t[n]||(buildAccessors(r,e),t[n]=!0)}return utils$1.isArray(e)?e.forEach(n):n(e),this}};function transformData(e,t){const r=this||defaults,n=t||r,o=AxiosHeaders$1.from(n.headers);let i=n.data;return utils$1.forEach(e,(function(e){i=e.call(r,i,o.normalize(),t?t.status:void 0)})),o.normalize(),i}function isCancel$1(e){return!(!e||!e.__CANCEL__)}function CanceledError$1(e,t,r){AxiosError$1.call(this,null==e?"canceled":e,AxiosError$1.ERR_CANCELED,t,r),this.name="CanceledError"}function settle(e,t,r){const n=r.config.validateStatus;r.status&&n&&!n(r.status)?t(new AxiosError$1("Request failed with status code "+r.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}function parseProtocol(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function speedometer(e,t){e=e||10;const r=new Array(e),n=new Array(e);let o,i=0,a=0;return t=void 0!==t?t:1e3,function(s){const c=Date.now(),u=n[a];o||(o=c),r[i]=s,n[i]=c;let l=a,d=0;for(;l!==i;)d+=r[l++],l%=e;if(i=(i+1)%e,i===a&&(a=(a+1)%e),c-o<t)return;const h=u&&c-u;return h?Math.round(1e3*d/h):void 0}}function throttle(e,t){let r,n,o=0,i=1e3/t;const a=(t,i=Date.now())=>{o=i,r=null,n&&(clearTimeout(n),n=null),e.apply(null,t)};return[(...e)=>{const t=Date.now(),s=t-o;s>=i?a(e,t):(r=e,n||(n=setTimeout((()=>{n=null,a(r)}),i-s)))},()=>r&&a(r)]}AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$1.reduceDescriptors(AxiosHeaders$1.prototype,(({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}})),utils$1.freezeMethods(AxiosHeaders$1),utils$1.inherits(CanceledError$1,AxiosError$1,{__CANCEL__:!0});const progressEventReducer=(e,t,r=3)=>{let n=0;const o=speedometer(50,250);return throttle((r=>{const i=r.loaded,a=r.lengthComputable?r.total:void 0,s=i-n,c=o(s);n=i;e({loaded:i,total:a,progress:a?i/a:void 0,bytes:s,rate:c||void 0,estimated:c&&a&&i<=a?(a-i)/c:void 0,event:r,lengthComputable:null!=a,[t?"download":"upload"]:!0})}),r)},progressEventDecorator=(e,t)=>{const r=null!=e;return[n=>t[0]({lengthComputable:r,total:e,loaded:n}),t[1]]},asyncDecorator=e=>(...t)=>utils$1.asap((()=>e(...t))),isURLSameOrigin=platform.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,platform.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(platform.origin),platform.navigator&&/(msie|trident)/i.test(platform.navigator.userAgent)):()=>!0,cookies=platform.hasStandardBrowserEnv?{write(e,t,r,n,o,i){const a=[e+"="+encodeURIComponent(t)];utils$1.isNumber(r)&&a.push("expires="+new Date(r).toGMTString()),utils$1.isString(n)&&a.push("path="+n),utils$1.isString(o)&&a.push("domain="+o),!0===i&&a.push("secure"),document.cookie=a.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 isAbsoluteURL(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function combineURLs(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function buildFullPath(e,t,r){let n=!isAbsoluteURL(t);return e&&(n||0==r)?combineURLs(e,t):t}const headersToObject=e=>e instanceof AxiosHeaders$1?{...e}:e;function mergeConfig$1(e,t){t=t||{};const r={};function n(e,t,r,n){return utils$1.isPlainObject(e)&&utils$1.isPlainObject(t)?utils$1.merge.call({caseless:n},e,t):utils$1.isPlainObject(t)?utils$1.merge({},t):utils$1.isArray(t)?t.slice():t}function o(e,t,r,o){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e,0,o):n(e,t,0,o)}function i(e,t){if(!utils$1.isUndefined(t))return n(void 0,t)}function a(e,t){return utils$1.isUndefined(t)?utils$1.isUndefined(e)?void 0:n(void 0,e):n(void 0,t)}function s(r,o,i){return i in t?n(r,o):i in e?n(void 0,r):void 0}const c={url:i,method:i,data:i,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:s,headers:(e,t,r)=>o(headersToObject(e),headersToObject(t),0,!0)};return utils$1.forEach(Object.keys(Object.assign({},e,t)),(function(n){const i=c[n]||o,a=i(e[n],t[n],n);utils$1.isUndefined(a)&&i!==s||(r[n]=a)})),r}const resolveConfig=e=>{const t=mergeConfig$1({},e);let r,{data:n,withXSRFToken:o,xsrfHeaderName:i,xsrfCookieName:a,headers:s,auth:c}=t;if(t.headers=s=AxiosHeaders$1.from(s),t.url=buildURL(buildFullPath(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&s.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),utils$1.isFormData(n))if(platform.hasStandardBrowserEnv||platform.hasStandardBrowserWebWorkerEnv)s.setContentType(void 0);else if(!1!==(r=s.getContentType())){const[e,...t]=r?r.split(";").map((e=>e.trim())).filter(Boolean):[];s.setContentType([e||"multipart/form-data",...t].join("; "))}if(platform.hasStandardBrowserEnv&&(o&&utils$1.isFunction(o)&&(o=o(t)),o||!1!==o&&isURLSameOrigin(t.url))){const e=i&&a&&cookies.read(a);e&&s.set(i,e)}return t},isXHRAdapterSupported="undefined"!=typeof XMLHttpRequest,xhrAdapter=isXHRAdapterSupported&&function(e){return new Promise((function(t,r){const n=resolveConfig(e);let o=n.data;const i=AxiosHeaders$1.from(n.headers).normalize();let a,s,c,u,l,{responseType:d,onUploadProgress:h,onDownloadProgress:p}=n;function f(){u&&u(),l&&l(),n.cancelToken&&n.cancelToken.unsubscribe(a),n.signal&&n.signal.removeEventListener("abort",a)}let m=new XMLHttpRequest;function g(){if(!m)return;const n=AxiosHeaders$1.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());settle((function(e){t(e),f()}),(function(e){r(e),f()}),{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:n,config:e,request:m}),m=null}m.open(n.method.toUpperCase(),n.url,!0),m.timeout=n.timeout,"onloadend"in m?m.onloadend=g:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(g)},m.onabort=function(){m&&(r(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=n.timeout?"timeout of "+n.timeout+"ms exceeded":"timeout exceeded";const o=n.transitional||transitionalDefaults;n.timeoutErrorMessage&&(t=n.timeoutErrorMessage),r(new AxiosError$1(t,o.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,e,m)),m=null},void 0===o&&i.setContentType(null),"setRequestHeader"in m&&utils$1.forEach(i.toJSON(),(function(e,t){m.setRequestHeader(t,e)})),utils$1.isUndefined(n.withCredentials)||(m.withCredentials=!!n.withCredentials),d&&"json"!==d&&(m.responseType=n.responseType),p&&([c,l]=progressEventReducer(p,!0),m.addEventListener("progress",c)),h&&m.upload&&([s,u]=progressEventReducer(h),m.upload.addEventListener("progress",s),m.upload.addEventListener("loadend",u)),(n.cancelToken||n.signal)&&(a=t=>{m&&(r(!t||t.type?new CanceledError$1(null,e,m):t),m.abort(),m=null)},n.cancelToken&&n.cancelToken.subscribe(a),n.signal&&(n.signal.aborted?a():n.signal.addEventListener("abort",a)));const y=parseProtocol(n.url);y&&-1===platform.protocols.indexOf(y)?r(new AxiosError$1("Unsupported protocol "+y+":",AxiosError$1.ERR_BAD_REQUEST,e)):m.send(o||null)}))},composeSignals=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,n=new AbortController;const o=function(e){if(!r){r=!0,a();const t=e instanceof Error?e:this.reason;n.abort(t instanceof AxiosError$1?t:new CanceledError$1(t instanceof Error?t.message:t))}};let i=t&&setTimeout((()=>{i=null,o(new AxiosError$1(`timeout ${t} of ms exceeded`,AxiosError$1.ETIMEDOUT))}),t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach((e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)})),e=null)};e.forEach((e=>e.addEventListener("abort",o)));const{signal:s}=n;return s.unsubscribe=()=>utils$1.asap(a),s}},streamChunk=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let n,o=0;for(;o<r;)n=o+t,yield e.slice(o,n),o=n},readBytes=async function*(e,t){for await(const r of readStream(e))yield*streamChunk(r,t)},readStream=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()}},trackStream=(e,t,r,n)=>{const o=readBytes(e,t);let i,a=0,s=e=>{i||(i=!0,n&&n(e))};return new ReadableStream({async pull(e){try{const{done:t,value:n}=await o.next();if(t)return s(),void e.close();let i=n.byteLength;if(r){let e=a+=i;r(e)}e.enqueue(new Uint8Array(n))}catch(t){throw s(t),t}},cancel:e=>(s(e),o.return())},{highWaterMark:2})},isFetchSupported="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,isReadableStreamSupported=isFetchSupported&&"function"==typeof ReadableStream,encodeText=isFetchSupported&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),test=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},supportsRequestStream=isReadableStreamSupported&&test((()=>{let e=!1;const t=new Request(platform.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t})),DEFAULT_CHUNK_SIZE=65536,supportsResponseStream=isReadableStreamSupported&&test((()=>utils$1.isReadableStream(new Response("").body))),resolvers={stream:supportsResponseStream&&(e=>e.body)};isFetchSupported&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach((t=>{!resolvers[t]&&(resolvers[t]=utils$1.isFunction(e[t])?e=>e[t]():(e,r)=>{throw new AxiosError$1(`Response type '${t}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,r)})}))})(new Response);const getBodyLength=async e=>{if(null==e)return 0;if(utils$1.isBlob(e))return e.size;if(utils$1.isSpecCompliantForm(e)){const t=new Request(platform.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return utils$1.isArrayBufferView(e)||utils$1.isArrayBuffer(e)?e.byteLength:(utils$1.isURLSearchParams(e)&&(e+=""),utils$1.isString(e)?(await encodeText(e)).byteLength:void 0)},resolveBodyLength=async(e,t)=>{const r=utils$1.toFiniteNumber(e.getContentLength());return null==r?getBodyLength(t):r},fetchAdapter=isFetchSupported&&(async e=>{let{url:t,method:r,data:n,signal:o,cancelToken:i,timeout:a,onDownloadProgress:s,onUploadProgress:c,responseType:u,headers:l,withCredentials:d="same-origin",fetchOptions:h}=resolveConfig(e);u=u?(u+"").toLowerCase():"text";let p,f=composeSignals([o,i&&i.toAbortSignal()],a);const m=f&&f.unsubscribe&&(()=>{f.unsubscribe()});let g;try{if(c&&supportsRequestStream&&"get"!==r&&"head"!==r&&0!==(g=await resolveBodyLength(l,n))){let e,r=new Request(t,{method:"POST",body:n,duplex:"half"});if(utils$1.isFormData(n)&&(e=r.headers.get("content-type"))&&l.setContentType(e),r.body){const[e,t]=progressEventDecorator(g,progressEventReducer(asyncDecorator(c)));n=trackStream(r.body,DEFAULT_CHUNK_SIZE,e,t)}}utils$1.isString(d)||(d=d?"include":"omit");const o="credentials"in Request.prototype;p=new Request(t,{...h,signal:f,method:r.toUpperCase(),headers:l.normalize().toJSON(),body:n,duplex:"half",credentials:o?d:void 0});let i=await fetch(p);const a=supportsResponseStream&&("stream"===u||"response"===u);if(supportsResponseStream&&(s||a&&m)){const e={};["status","statusText","headers"].forEach((t=>{e[t]=i[t]}));const t=utils$1.toFiniteNumber(i.headers.get("content-length")),[r,n]=s&&progressEventDecorator(t,progressEventReducer(asyncDecorator(s),!0))||[];i=new Response(trackStream(i.body,DEFAULT_CHUNK_SIZE,r,(()=>{n&&n(),m&&m()})),e)}u=u||"text";let y=await resolvers[utils$1.findKey(resolvers,u)||"text"](i,e);return!a&&m&&m(),await new Promise(((t,r)=>{settle(t,r,{data:y,headers:AxiosHeaders$1.from(i.headers),status:i.status,statusText:i.statusText,config:e,request:p})}))}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/fetch/i.test(y.message))throw Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,e,p),{cause:y.cause||y});throw AxiosError$1.from(y,y&&y.code,e,p)}}),knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:fetchAdapter};utils$1.forEach(knownAdapters,((e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}}));const renderReason=e=>`- ${e}`,isResolvedHandle=e=>utils$1.isFunction(e)||null===e||!1===e,adapters={getAdapter:e=>{e=utils$1.isArray(e)?e:[e];const{length:t}=e;let r,n;const o={};for(let i=0;i<t;i++){let t;if(r=e[i],n=r,!isResolvedHandle(r)&&(n=knownAdapters[(t=String(r)).toLowerCase()],void 0===n))throw new AxiosError$1(`Unknown adapter '${t}'`);if(n)break;o[t||"#"+i]=n}if(!n){const e=Object.entries(o).map((([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build")));throw new AxiosError$1("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(renderReason).join("\n"):" "+renderReason(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return n},adapters:knownAdapters};function throwIfCancellationRequested(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new CanceledError$1(null,e)}function dispatchRequest(e){throwIfCancellationRequested(e),e.headers=AxiosHeaders$1.from(e.headers),e.data=transformData.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return adapters.getAdapter(e.adapter||defaults.adapter)(e).then((function(t){return throwIfCancellationRequested(e),t.data=transformData.call(e,e.transformResponse,t),t.headers=AxiosHeaders$1.from(t.headers),t}),(function(t){return isCancel$1(t)||(throwIfCancellationRequested(e),t&&t.response&&(t.response.data=transformData.call(e,e.transformResponse,t.response),t.response.headers=AxiosHeaders$1.from(t.response.headers))),Promise.reject(t)}))}const VERSION$1="1.8.4",validators$1={};["object","boolean","number","function","string","symbol"].forEach(((e,t)=>{validators$1[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}}));const deprecatedWarnings={};function assertOptions(e,t,r){if("object"!=typeof e)throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const n=Object.keys(e);let o=n.length;for(;o-- >0;){const i=n[o],a=t[i];if(a){const t=e[i],r=void 0===t||a(t,i,e);if(!0!==r)throw new AxiosError$1("option "+i+" must be "+r,AxiosError$1.ERR_BAD_OPTION_VALUE)}else if(!0!==r)throw new AxiosError$1("Unknown option "+i,AxiosError$1.ERR_BAD_OPTION)}}validators$1.transitional=function(e,t,r){function n(e,t){return"[Axios v"+VERSION$1+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,i)=>{if(!1===e)throw new AxiosError$1(n(o," has been removed"+(t?" in "+t:"")),AxiosError$1.ERR_DEPRECATED);return t&&!deprecatedWarnings[o]&&(deprecatedWarnings[o]=!0,console.warn(n(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,i)}},validators$1.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const validator={assertOptions:assertOptions,validators:validators$1},validators=validator.validators;let Axios$1=class{constructor(e){this.defaults=e,this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}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(n){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=mergeConfig$1(this.defaults,t);const{transitional:r,paramsSerializer:n,headers:o}=t;void 0!==r&&validator.assertOptions(r,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),null!=n&&(utils$1.isFunction(n)?t.paramsSerializer={serialize:n}:validator.assertOptions(n,{encode:validators.function,serialize:validators.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),validator.assertOptions(t,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&utils$1.merge(o.common,o[t.method]);o&&utils$1.forEach(["delete","get","head","post","put","patch","common"],(e=>{delete o[e]})),t.headers=AxiosHeaders$1.concat(i,o);const a=[];let s=!0;this.interceptors.request.forEach((function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(s=s&&e.synchronous,a.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(!s){const e=[dispatchRequest.bind(this),void 0];for(e.unshift.apply(e,a),e.push.apply(e,c),l=e.length,u=Promise.resolve(t);d<l;)u=u.then(e[d++],e[d++]);return u}l=a.length;let h=t;for(d=0;d<l;){const e=a[d++],t=a[d++];try{h=e(h)}catch(p){t.call(this,p);break}}try{u=dispatchRequest.call(this,h)}catch(p){return Promise.reject(p)}for(d=0,l=c.length;d<l;)u=u.then(c[d++],c[d++]);return u}getUri(e){return buildURL(buildFullPath((e=mergeConfig$1(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};utils$1.forEach(["delete","get","head","options"],(function(e){Axios$1.prototype[e]=function(t,r){return this.request(mergeConfig$1(r||{},{method:e,url:t,data:(r||{}).data}))}})),utils$1.forEach(["post","put","patch"],(function(e){function t(t){return function(r,n,o){return this.request(mergeConfig$1(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:n}))}}Axios$1.prototype[e]=t(),Axios$1.prototype[e+"Form"]=t(!0)}));let CancelToken$1=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise((function(e){t=e}));const r=this;this.promise.then((e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null})),this.promise.then=e=>{let t;const n=new Promise((e=>{r.subscribe(e),t=e})).then(e);return n.cancel=function(){r.unsubscribe(t)},n},e((function(e,n,o){r.reason||(r.reason=new CanceledError$1(e,n,o),t(r.reason))}))}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e((function(e){t=e})),cancel:t}}};function spread$1(e){return function(t){return e.apply(null,t)}}function isAxiosError$1(e){return utils$1.isObject(e)&&!0===e.isAxiosError}const HttpStatusCode$1={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};function createInstance(e){const t=new Axios$1(e),r=bind(Axios$1.prototype.request,t);return utils$1.extend(r,Axios$1.prototype,t,{allOwnKeys:!0}),utils$1.extend(r,t,null,{allOwnKeys:!0}),r.create=function(t){return createInstance(mergeConfig$1(e,t))},r}Object.entries(HttpStatusCode$1).forEach((([e,t])=>{HttpStatusCode$1[t]=e}));const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(e){return Promise.all(e)},axios.spread=spread$1,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=e=>formDataToJSON(utils$1.isHTMLForm(e)?new FormData(e):e),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios:Axios,AxiosError:AxiosError,CanceledError:CanceledError,isCancel:isCancel,CancelToken:CancelToken,VERSION:VERSION,all:all,Cancel:Cancel,isAxiosError:isAxiosError,spread:spread,toFormData:toFormData,AxiosHeaders:AxiosHeaders,HttpStatusCode:HttpStatusCode,formToJSON:formToJSON,getAdapter:getAdapter,mergeConfig:mergeConfig}=axios;class HederaMirrorNode{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 Logger$2({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 i$9.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.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=s$a.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const r=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const r=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(r),null}}async getTopicMessages(e){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,o;try{e=this.isServerEnvironment?Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),(e=>e.charCodeAt(0))))}catch(n){const e=`Error decoding message: ${n}`;this.logger.error(e);continue}try{o=JSON.parse(e)}catch(n){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}o.sequence_number=t.sequence_number,r.push({...o,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(n){const e=`Error processing message: ${n.message}`;this.logger.error(e)}t=e.links?.next||""}catch(o){const r=`Error querying topic messages for topic ${e} (endpoint: ${t}) after retries: ${o.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=libExports.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=libExports.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(Buffer.from(e),t))return!0}catch(n){const e=`Error in nested key: ${n.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i$9.fromBytes(Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const r=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${r.message}`),null}}async _requestWithRetry(e,t){let r=0,n=this.initialDelayMs;const o=this.constructUrl(e),i={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(i.headers={...i.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await axios.get(o,i)).data}catch(a){r++;const e=r>=this.maxRetries,t=a.response?.status;if(t&&t>=400&&t<500&&429!==t)throw this.logger.error(`Client error for ${o} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${o}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${o}: ${a.message}. Retrying in ${n}ms...`),await new Promise((e=>setTimeout(e,n))),n=Math.min(n*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${o} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,n=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach(((e,t)=>{o[t]=e})):Array.isArray(t.headers)?t.headers.forEach((([e,t])=>{o[e]=t})):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const i={...t,headers:o};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(a){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${a.message}. Retrying in ${n}ms...`),await new Promise((e=>setTimeout(e,n))),n=Math.min(n*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 n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.sequenceNumber&&n.append("sequencenumber",t.sequenceNumber),t?.startTime&&n.append("timestamp",`gte:${t.startTime}`),t?.endTime&&n.append("timestamp",`lt:${t.endTime}`),t?.order&&n.append("order",t.order);const o=n.toString();o&&(r+=`?${o}`);const i=[];let a=0;try{for(;r&&a<10;){a++;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?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(s){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const n={...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(n)}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=[],n=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&n;e++){const e=await this._requestWithRetry(n);if(e&&e.tokens&&(r=r.concat(e.tokens)),n=e.links?.next||"",!n||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let n=[],o=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map((e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?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}}));n=n.concat(t)}if(o=e.links?.next||"",!o)break}return n}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 n=await this.getAccountNfts(e,t);if(n){return n.find((e=>e.token_id===t&&e.serial_number===r))||null}return null}catch(n){return this.logger.error(`Error validating NFT ownership: ${n.message}`),null}}async readSmartContractQuery(e,t,r,n){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const o=e.startsWith("0x")?e:`0x${f.fromString(e).toSolidityAddress()}`,i=r.startsWith("0x")?r:`0x${f.fromString(r).toSolidityAddress()}`,a={block:n?.block||"latest",data:t,estimate:n?.estimate||!1,from:i,to:o,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(s){return this.logger.error(`Error reading smart contract ${e}: ${s.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 n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.receiverId&&n.append("receiver.id",t.receiverId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(r+=`?${o}`);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 n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.senderId&&n.append("sender.id",t.senderId),t?.serialNumber&&n.append("serialnumber",t.serialNumber),t?.tokenId&&n.append("token.id",t.tokenId);const o=n.toString();o&&(r+=`?${o}`);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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const r=new URLSearchParams;e?.contractId&&r.append("contract.id",e.contractId),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order);const n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching contract ${e}: ${n.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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching contract result for ${e}: ${n.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const n=new URLSearchParams;t?.blockHash&&n.append("block.hash",t.blockHash),t?.blockNumber&&n.append("block.number",t.blockNumber),t?.from&&n.append("from",t.from),void 0!==t?.internal&&n.append("internal",t.internal.toString()),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.transactionIndex&&n.append("transaction.index",t.transactionIndex.toString());const o=n.toString();o&&(r+=`?${o}`);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 n=new URLSearchParams;t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.slot&&n.append("slot",t.slot),t?.timestamp&&n.append("timestamp",t.timestamp);const o=n.toString();o&&(r+=`?${o}`);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 n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order);const o=n.toString();o&&(r+=`?${o}`);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 n=r.toString();n&&(t+=`?${n}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const n=new URLSearchParams;t?.index&&n.append("index",t.index),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.timestamp&&n.append("timestamp",t.timestamp),t?.topic0&&n.append("topic0",t.topic0),t?.topic1&&n.append("topic1",t.topic1),t?.topic2&&n.append("topic2",t.topic2),t?.topic3&&n.append("topic3",t.topic3);const o=n.toString();o&&(r+=`?${o}`);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(n){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${n.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const n=new URLSearchParams;t?.accountId&&n.append("account.id",t.accountId),t?.limit&&n.append("limit",t.limit.toString()),t?.order&&n.append("order",t.order),t?.serialNumber&&n.append("serialnumber",t.serialNumber);const o=n.toString();o&&(r+=`?${o}`);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 n=new URLSearchParams;void 0!==t?.stack&&n.append("stack",t.stack.toString()),void 0!==t?.memory&&n.append("memory",t.memory.toString()),void 0!==t?.storage&&n.append("storage",t.storage.toString());const o=n.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching opcode traces for ${e}: ${i.message}`),null}}}var ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(ProfileType||{}),AIAgentType=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(AIAgentType||{}),EndpointType=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(EndpointType||{}),AIAgentCapability=(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))(AIAgentCapability||{}),InboundTopicType=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(InboundTopicType||{});const SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube","website","x"],capabilityNameToCapabilityMap={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},SocialLinkSchema=z.object({platform:z.string().min(1),handle:z.string().min(1)}),AIAgentDetailsSchema=z.object({type:z.nativeEnum(AIAgentType),capabilities:z.array(z.nativeEnum(AIAgentCapability)).min(1),model:z.string().min(1),creator:z.string().optional()}),BaseProfileSchema=z.object({version:z.string().min(1),type:z.nativeEnum(ProfileType),display_name:z.string().min(1),alias:z.string().optional(),bio:z.string().optional(),socials:z.array(SocialLinkSchema).optional(),profileImage:z.string().optional(),properties:z.record(z.any()).optional(),inboundTopicId:z.string().optional(),outboundTopicId:z.string().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:z.literal(ProfileType.PERSONAL),language:z.string().optional(),timezone:z.string().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:z.literal(ProfileType.AI_AGENT),aiAgent:AIAgentDetailsSchema}),HCS11ProfileSchema=z.union([PersonalProfileSchema,AIAgentProfileSchema]);class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.auth=e.auth,this.network=e.network,this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey){const e=y.fromString(this.auth.privateKey);this.client.setOperator(this.auth.operatorId,e)}this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-11"})}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}createPersonalProfile(e,t){return{version:"1.0",type:ProfileType.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,n,o){const i=this.validateProfile({version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}}}validateProfile(e){const t=HCS11ProfileSchema.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map((e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`}))}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),r=await t.execute(this.client),n=await r.getReceipt(this.client);return n.status.toString()!==e$6.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,r=await e.freezeWithSigner(t),n=await r.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status.toString()!==e$6.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}: ${e$6.Success.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const i=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(o.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(o.verifying("Waiting for inscription confirmation",50,{jobId:s.result.jobId}),{imageTopicId:"",transactionId:s.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,n=new ProgressReporter({module:"HCS11-Profile",logger:this.logger,callback:r});n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const i=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(i,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};n.submitting("Submitting profile to Hedera network",30);const s=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},o):await inscribeWithSigner(r,this.auth.signer,o);if(!s.confirmed||!s.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=s.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:c,transactionId:s.result.transactionId}),{profileTopicId:c,transactionId:s.result.transactionId,success:!0}}catch(s){return n.failed(`Error inscribing profile: ${s.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:s.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),n=(new s$4).setAccountMemo(r).setAccountId(e);return this.executeTransaction(n)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const i=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[AIAgentCapability.TEXT_GENERATION];for(const r of e){const e=capabilityNameToCapabilityMap[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(AIAgentCapability.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?AIAgentType.AUTONOMOUS:AIAgentType.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${n}`),!n?.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: ${n}`);const o=n.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[n,i,a]=e,s=t||this.network||"mainnet";this.logger.info(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;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:a}}:{success:!1,error:`No profile data found for topic ${a}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class Registration{async checkRegistrationStatus(e,t,r,n){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,n=60,o=2e3,i){let a=0;for(;a<n;){i&&i.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,i);if("success"===s.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise((e=>setTimeout(e,o))),a++}return i&&i.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const r=new HCS11Client({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await sleep(5e3);const o=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const i=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 i.json();return i.ok?(n&&n.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(i){return{error:`Error during registration request: ${i.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach((e=>r.append("tags",e.toString()))),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const n=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}class HRLResolver{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=Logger$2.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:n,topicId:o}=r;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await axios.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await axios.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:o,isBinary:!0}}if("application/json"===r){const t=await axios.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:r,topicId:o,isBinary:!1}}const n=await axios.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let i;return i="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:i,contentType:r,topicId:o,isBinary:!1}}catch(i){const e=`Error resolving HRL reference: ${i.message}`;throw this.logger.error(e),new Error(e)}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint}),this.mirrorNode=new HederaMirrorNode(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=Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i$9.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return 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(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){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{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=HCS10Cache.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new HCS11Client({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),n=await t.fetchProfileByAccountId(e,this.network);if(!n?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,n?.error),{profile:null,success:!1,error:n?.error||`Failed to retrieve profile for account ID: ${e}`};const o=n.profile;let i=null;n.topicInfo?.inboundTopic&&n.topicInfo?.outboundTopic&&n.topicInfo?.profileTopicId&&(i={inboundTopic:n.topicInfo.inboundTopic,outboundTopic:n.topicInfo.outboundTopic,profileTopicId:n.topicInfo.profileTopicId});const a={profile:o,topicInfo:i,success:!0};return HCS10Cache.getInstance().set(r,a),a}catch(n){const e=`Failed to retrieve profile: ${n.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 n=r.profile;if(!n.inboundTopicId||!n.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 HRLResolver(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 HRLResolver(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 n=await this.getOperatorId(),o=r.accountId,i=await this.canSubmitToTopic(e,o);if(!i?.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const a=await this.retrieveInboundAccountId(e);if(!a)throw new Error("Failed to retrieve topic info account ID");const s={p:"hcs-10",op:"connection_request",operator_id:n,m:t},c=i.requiresFee,u=await this.submitPayload(e,s,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(o);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 h=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:h}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:n,connectionTopicId:o,operatorId:i,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:o,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:r,operator_id:i,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,r=60,n=2e3,o=!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 a=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)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},n=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.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 ${n}ms before retrying...`),await new Promise((e=>setTimeout(e,n))))}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 n=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=n,n}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(":"),n=r?.[4];if(!n)throw new Error("Failed to retrieve topic info account ID");return n}clearCache(){HCS10Cache.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 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)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(n){const e=n,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],n=t[1];if(!r)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e),n=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?n.slice(0,t):n}}class HCS10Cache{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return HCS10Cache.instance||(HCS10Cache.instance=new HCS10Cache),HCS10Cache.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 PayloadSizeError extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class AccountCreationError extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class TopicCreationError extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class ConnectionConfirmationError extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class AgentBuilder{constructor(){this.config={},this.logger=Logger$2.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=InboundTopicType.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===InboundTopicType.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class PersonBuilder{constructor(){this.config={version:"1.0",type:0},this.logger=Logger$2.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}}}async function accountIdsToExemptKeys(e,t,r){const n=new HederaMirrorNode(t,r),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${a}: ${i}`)}return o}function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function toInteger(e){if(null===e||!0===e||!1===e)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}function requiredArgs(e,t){if(t.length<e)throw new TypeError(e+" argument"+(e>1?"s":"")+" required, but only "+t.length+" present")}function toDate(e){requiredArgs(1,arguments);var t=Object.prototype.toString.call(e);return e instanceof Date||"object"===_typeof(e)&&"[object Date]"===t?new Date(e.getTime()):"number"==typeof e||"[object Number]"===t?new Date(e):("string"!=typeof e&&"[object String]"!==t||"undefined"==typeof console||(console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"),console.warn((new Error).stack)),new Date(NaN))}function addMilliseconds(e,t){requiredArgs(2,arguments);var r=toDate(e).getTime(),n=toInteger(t);return new Date(r+n)}function addSeconds(e,t){return requiredArgs(2,arguments),addMilliseconds(e,1e3*toInteger(t))}class HCS10Client extends HCS10BaseClient{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode}),this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.operatorPrivateKey=y.fromString(e.operatorPrivateKey),this.network=e.network,this.client.setOperator(e.operatorId,this.operatorPrivateKey.toString()),this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-SDK"}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel})}getClient(){return this.client}async createAccount(e=50){this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=y.generate(),r=(new h).setKey(t.publicKey).setInitialBalance(new e$7(e));this.logger.debug("Executing account creation transaction");const n=await r.execute(this.client),o=(await n.getReceipt(this.client)).accountId;if(!o)throw this.logger.error("Account creation failed: accountId is null"),new AccountCreationError("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${o.toString()}`),{accountId:o.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,n){const o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let i,a;switch(t){case InboundTopicType.PUBLIC:i=!1;break;case InboundTopicType.CONTROLLED:i=!0;break;case InboundTopicType.FEE_BASED:if(i=!1,!n)throw new Error("Fee configuration builder is required for fee-based topics");n.customFees.forEach((t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)})),a=n.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,i,a)}async createAgent(e,t=60){const r=e.build(),n=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:t}),o=await this.createTopic(n,!0,!0);this.logger.info(`Created new outbound topic ID: ${o}`);const i=this.client.operatorAccountId?.toString();if(!i)throw new Error("Failed to retrieve operator account ID");const a=await this.createInboundTopic(i,r.inboundTopicType,t,r.inboundTopicType===InboundTopicType.FEE_BASED?r.feeConfig:void 0);let s=r.existingPfpTopicId||"";if(!s&&r.pfpBuffer&&r.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(r.pfpBuffer,r.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else r.existingPfpTopicId&&this.logger.info(`Using existing profile picture with topic ID: ${r.existingPfpTopicId}`);const c=(await this.storeHCS11Profile(r.name,r.bio,a,o,r.capabilities,r.metadata,r.pfpBuffer&&r.pfpBuffer.length>0?r.pfpBuffer:void 0,r.pfpFileName,r.existingPfpTopicId)).profileTopicId;return this.logger.info(`Profile stored with topic ID: ${c}`),{inboundTopicId:a,outboundTopicId:o,pfpTopicId:s,profileTopicId:c}}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,n,o=[],i,a,s,c){try{let u=c||"";if(!u&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);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,h=this.hcs11Client.createAIAgentProfile(e,l,o,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:n,creator:i.creator}),p=await this.hcs11Client.createAndInscribeProfile(h,!0);if(!p.success)throw this.logger.error(`Failed to inscribe profile: ${p.error}`),new Error(p.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${p.profileTopicId}, transaction ID: ${p.transactionId}`),{profileTopicId:p.profileTopicId,pfpTopicId:u,transactionId:p.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,r=[]){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 o=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 l).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(f.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(u$5.fromString(e.feeTokenId)),t}return null})).filter(Boolean);if(0===o.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const i=[...t.exemptAccounts||[],...r];return i.length>0&&(n=await this.setupExemptKeys(e,i)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(o)}async setupExemptKeys(e,t){let r=e;const n=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let o=[];if(n.length>0)try{o=await accountIdsToExemptKeys(n,this.network,this.logger)}catch(i){const e=`Error getting exempt keys: ${i.message}, continuing without exempt keys`;this.logger.warn(e)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,n,o=60){const i=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r});this.logger.info(`Handling connection request ${r} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let s=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(a);if(!c)throw new Error("Failed to retrieve public key");const u=new s$9([c,s],1);let l;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};l=await this.createTopic(i,u,u,t)}else l=await this.createTopic(i,u,u);this.logger.info(`Created new connection topic ID: ${l}`)}catch(g){const e=`Failed to create connection topic: ${g}`;throw this.logger.error(e),new TopicCreationError(e)}const d=`${e}@${a}`,h=await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),p=await this.retrieveCommunicationTopics(a),f=await this.retrieveCommunicationTopics(t),m=`${f.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:p.outboundTopic,requestorOutboundTopicId:f.outboundTopic,connectionRequestId:r,confirmedRequestId:h,connectionTopicId:l,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:l,confirmedConnectionSequenceNumber:h,operatorId:d}}async confirmConnection(e,t,r,n,o,i){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new ConnectionConfirmationError("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,n,o){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=JSON.stringify(a);if(Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=Buffer.from(t),r=`message-${Date.now()}.json`,n=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.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",a),await this.submitPayload(e,a,n,i.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const o=(new c).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(o.setAdminKey(this.client.operatorPublicKey),o.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$9||t instanceof s$9)&&(o.setAdminKey(t),this.client.operatorAccountId&&o.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?o.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$9||r instanceof s$9)&&o.setSubmitKey(r)),n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const i=await o.execute(this.client),a=await i.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,r,n=!1){const o="string"==typeof t?t:JSON.stringify(t),i=Buffer.byteLength(o,"utf8");if(i>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",i);const a=(new u).setTopicId(m$1.fromString(e)).setMessage(o);let s;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new e$7(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);s=await t.execute(this.client)}else s=await a.execute(this.client);const c=await s.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}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 n=mimeTypesExports.lookup(t)||"application/octet-stream",o=await InscriptionSDK.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"}},a=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:n},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},i,o);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,n=2e3,o=!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 a=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)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},n=this.extractAccountFromOperatorId(r.confirmedBy),i=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(i.accountId);return this.logger.info("Connection confirmation found",r),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.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 ${n}ms before retrying...`),await new Promise((e=>setTimeout(e,n))))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){return{accountId:this.client.operatorAccountId.toString(),signer:this.operatorPrivateKey}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let i=t?.existingState||void 0;n&&n({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:i}});const a=r.existingAccount||await this.createAccount(t?.initialBalance);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:i,account:a}});const s=new HCS10Client({network:r.network,operatorId:a.accountId,operatorPrivateKey:a.privateKey,operatorPublicKey:y.fromString(a.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:o});n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:30,details:{state:i}});const{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=await s.createAgent(e);n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:i,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}});const h=`${u}@${a.accountId}`,p=await s.registerAgentWithGuardedRegistry(a.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:h,state:e.details?.state||i}})},existingState:i});return p.success?(n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:h,state:p.state}}),{...p,metadata:{accountId:a.accountId,privateKey:a.privateKey,operatorId:h,inboundTopicId:u,outboundTopicId:c,profileTopicId:d,pfpTopicId:l}}):p}catch(r){const e=r,t=`Failed to create and register agent: ${e.message}`;return this.logger.error(t),{error:e.message,success:!1}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,o=r?.delayMs??2e3,i=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};i&&i({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const s=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!s.success)return{...s,state:a};if(i&&i({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:s.transactionId,state:a}}),s.transaction){const e=P.fromBytes(Buffer.from(s.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}i&&i({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:s.transactionId,state:a}});const c=await this.waitForRegistrationConfirmation(s.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),i&&i({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:c,transactionId:s.transactionId,state:a}}),{...s,confirmed:c,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,n,o){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,i,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return InboundTopicType.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`),InboundTopicType.FEE_BASED}return InboundTopicType.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,r,n){this.logger.info("Creating scheduled transaction");const o=(new u$1).setScheduledTransaction(e).setPayerAccountId(n?f.fromString(n):this.client.operatorAccountId);if(t&&o.setScheduleMemo(t),r){const e=addSeconds(new Date,r),t=s$a.fromDate(e);o.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const i=await o.execute(this.client),a=await i.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 s=a.scheduleId.toString(),c=i.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${s}`),{scheduleId:s,transactionId:c}}async sendTransactionOperation(e,t,r,n,o){const i=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,i.requiresFee)}async sendTransaction(e,t,r,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:i}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:o,transactionId:i,receipt:await this.sendTransactionOperation(e,o,r,n?.submitKey,{memo:n?.operationMemo})}}}const isBrowser="undefined"!=typeof window;class BrowserHCSClient extends HCS10BaseClient{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode}),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=Logger$2.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel})}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,n,o){this.logger.info("Sending message");const i={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),s=JSON.stringify(i);if(Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=Buffer.from(t),r=`message-${Date.now()}.json`,n=await this.inscribeFile(e,r,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.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,n,a.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const i=this.hwc.getAccountInfo().accountId;if(!i)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(i);if(!s)throw new Error("Failed to retrieve public key");const u=new s$9([s,a],1),l=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r}),d=(new c).setTopicMemo(l).setAutoRenewAccountId(f.fromString(i)).setAdminKey(u).setSubmitKey(u);this.logger.debug("Executing topic creation transaction");const h=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(h?.error)throw this.logger.error(h.error),new Error(h.error);const p=h?.result;if(!p?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const m=p.topicId.toString(),g=`${e}@${i}`,y=await this.confirmConnection(e,m,t,r,g,n),b=await this.retrieveCommunicationTopics(i),w=await this.retrieveCommunicationTopics(t),v=`${w.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:b.outboundTopic,requestorOutboundTopicId:w.outboundTopic,connectionRequestId:r,confirmedRequestId:y,connectionTopicId:m,operatorId:v,memo:`Connection established with ${t}`}),{connectionTopicId:m,confirmedConnectionSequenceNumber:y,operatorId:g}}async confirmConnection(e,t,r,n,o,i){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:n,m:i},s=await this.submitPayload(e,a);if(!s?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return s.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,n=new ProgressReporter({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof AgentBuilder;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");n.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:i,outboundTopicId:a,state:s}=await this.createCommunicationTopics(t,n);let c,u,l;if(o=s,r||(e.setInboundTopicId(i),e.setOutboundTopicId(a)),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,o,n):c&&(n.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,i,a,t,n),o.currentStage="complete",o.completedPercentage=100,n.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:i,outboundTopicId:a,pfpTopicId:c,state:o});let d="";o.outboundTopicId&&(d=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let p="";o.pfpTopicId&&(p=o.pfpTopicId);let f="";return o.profileTopicId&&(f=o.profileTopicId),{outboundTopicId:d,inboundTopicId:h,pfpTopicId:p,profileTopicId:f,success:!0,state:o}}catch(o){return n.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,n){r.currentStage="pfp",n.preparing("Creating profile picture",30,{state:r});const o=n.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),i=await this.inscribePfp(e,t,{progressCallback:e=>o.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 a=i.pfpTopicId;return r.pfpTopicId=a,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),n.preparing("Profile picture created",50,{state:r}),a}async createAndInscribeProfile(e,t,r,n,o,i,a,s){if(!this.hcs11Client)throw s&&s.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),n.profileTopicId)s&&s.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:n});else{s&&s.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=s?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let u;if(e){const e=t.build(),n=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:n,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:i,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:n,pfpFileName:a,...s}=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:o,outboundTopicId:i})}const l=await this.hcs11Client.createAndInscribeProfile(u,a?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!l.success){s&&s.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)}n.profileTopicId=l.profileTopicId,n.createdResources&&n.createdResources.push(`profile:${l.profileTopicId}`),s&&s.preparing("HCS-11 Profile stored",95,{state:n})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,o=this.initializeRegistrationState(n,r?.existingState),i=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});i.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:o};if(i.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=P.fromBytes(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:o};this.logger.info("Successfully processed registration transaction")}i.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const s=r?.maxAttempts??60,c=r?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,s,c,this.logger);return this.updateStateForCompletedRegistration(o,n),i.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}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(),n=t?.progressCallback,o=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,o.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);o.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}o.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:a}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.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(a,i.profileTopicId))}return o.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:a,operatorId:`${i.inboundTopicId}@${a}`,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,n,o=[],i={},a,s,c,u){try{const l=u?.progressCallback,d=new ProgressReporter({module:"StoreHCS11Profile",logger:this.logger,callback:l});d.preparing("Preparing agent profile data",0);let h=c;if(!h&&a&&s){const e=d.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(a,s,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?h=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 p=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const f=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,m=this.hcs11Client.createAIAgentProfile(e,p,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:h?`hcs://1/${h}`:void 0,socials:f,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:n,creator:i.creator}),g=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,!0,{progressCallback:e=>{g.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:h,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,r){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),i=(new c).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(i.setAdminKey(a),i.setAutoRenewAccountId(n)),r&&a&&i.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(i,!1),u=s.error;if(u)return this.logger.error(u),{success:!1,error:u};const l=s.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,r,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(e).setMessage(o);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount))),r){const{accountId:e,signer:t}=this.getAccountAndSigner();i.freezeWithSigner(t);const n=await i.sign(r);a=await this.hwc.executeTransactionWithErrorHandling(n,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(i,!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:n,signer:o}=this.getAccountAndSigner(),i=mimeTypesExports.lookup(t)||"application/octet-stream",a=await InscriptionSDK.createWithAuth({type:"client",accountId:n,signer:o,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},o,{...s,network:this.network},a);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 n=r?.progressCallback,o=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},a=await this.hcs11Client.inscribeImage(e,t,{progressCallback:i});if(!a.success){let e="Failed to inscribe profile picture";a.error&&(e=a.error);let t="";return a.transactionId&&(t=a.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return o.completed("Successfully inscribed profile picture",{pfpTopicId:a.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${a.imageTopicId}`),{pfpTopicId:a.imageTopicId,success:!0,transactionId:a.transactionId||""}}catch(n){return this.logger.error(`Error inscribing profile picture: ${n.message}`),{pfpTopicId:"",success:!1,error:n.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:n}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const o=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e?.ttl,accountId:n}),i=await this.createTopic(o,!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 o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{ttl:e?.ttl,accountId:n}),i=await this.createTopic(o,!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}}}class ConnectionsManager{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};if(this.logger=new Logger$2(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[n,o]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(n.messages||[],e),this.processInboundMessages(o.messages||[]);const i=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${n.messages?.length||0} outbound and ${o.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[n,o]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(n)).messages||[];let r=!1;for(const e of o){const n=e.connectionRequestId;if(!n)continue;const o=t.find((t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==n)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const n=r[1];if(t.operator_id&&t.operator_id===n)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0}));if(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let i=e.uniqueRequestKey;const a={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.created||e.created),profileInfo:e.profileInfo,connectionRequestId:n,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,a),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 ${n}:`,r),2===e)break;await new Promise((e=>setTimeout(e,500)))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter((e=>"pending"===e.status));this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter((e=>"pending"===e.status));if(Boolean(r?.length))for(const o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(n){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${n}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),n=(r.messages||[]).find((e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id));if(n?.connection_topic_id){const e=n.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${o.targetAccountId} on their inbound topic`),this.connections.set(o.connectionTopicId,{...o,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||o.created),lastActivity:new Date(n.created||o.created)})}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(n){this.logger.warn(`Error checking for confirmations on target inbound topic for ${o.targetAccountId}: ${n}`)}else this.logger.debug(`Skipping connection ${o.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map((async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}}));await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter((t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId));if(r.length>0&&t.inboundTopicId)for(const n of r){const e={...n,targetInboundTopicId:t.inboundTopicId};this.connections.set(n.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||"",n=this.baseClient.extractAccountFromOperatorId(r),o=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out outbound request to account: ${n}`);continue}const a=Array.from(this.connections.values()).some((t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===n)),s=`req-${e}:${r}`;if(!a&&!this.pendingRequests.has(s)){const a={id:e,requesterId:t,requesterTopicId:i.outbound_topic_id||"",targetAccountId:n,targetTopicId:o,operatorId:r,sequenceNumber:i.sequence_number,created:i.created||new Date,memo:i.m,status:"pending"};if(this.pendingRequests.set(s,a),!this.connections.has(s)){const t={connectionTopicId:s,targetAccountId:n,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:i.created||new Date,connectionRequestId:e,uniqueRequestKey:s,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m};this.connections.set(s,t)}}}const n=e.filter((e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id));for(const i of n){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 n=`req-${e}:${i.operator_id}`,o=this.pendingRequests.get(n);if(o&&(o.status="confirmed"),this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:i.confirmed_request_id,requesterOutboundTopicId:i.outbound_topic_id,uniqueRequestKey:n,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:n,originTopicId:i.outbound_topic_id||"",processed:!1,memo:i.m})}const o=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const i of o){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 n of t){const e=n.sequence_number,t=n.operator_id||"",o=this.baseClient.extractAccountFromOperatorId(t),i=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const a=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(a)||this.connections.set(a,{connectionTopicId:a,targetAccountId:o,targetInboundTopicId:i,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:a,originTopicId:i,processed:!1,memo:n.m})}for(const n of r){const e=n.connection_id,t=n.connection_topic_id,r=n.connected_account_id||"",o=n.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const i=`inb-${e}:${o}`;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:n.connection_topic_id,processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:i,originTopicId:n.connection_topic_id,processed:!1,memo:n.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 n=t.find((e=>"close_connection"===e.op));if(n){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:n.created||new Date,closedReason:n.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 n of r)this.connections.set(n.connectionTopicId,{...n,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[n,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(n,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(n,{...o,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const n=await this.baseClient.getTransactionRequests(e,t),o=[];for(const e of n)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}async getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const{messages:r}=await this.baseClient.getMessageStream(e),n=r.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===n.length)return;return n.sort(((e,t)=>t.created.getTime()-e.created.getTime())),n[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}function parseKey(e){if(e){if(e.contractID)return`ContractID: ${new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${Buffer$1$1.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${Buffer$1$1.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map((e=>parseKey(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=>parseKey(e))).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new v(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 HTSParser{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 f(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=libExports.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=libExports.proto.TokenSupplyType[e.supplyType]),t.adminKey=parseKey(e.adminKey),t.kycKey=parseKey(e.kycKey),t.freezeKey=parseKey(e.freezeKey),t.wipeKey=parseKey(e.wipeKey),t.supplyKey=parseKey(e.supplyKey),t.feeScheduleKey=parseKey(e.feeScheduleKey),t.pauseKey=parseKey(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new f(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map((e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new f(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:Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new u$5(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:Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new u$5(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:Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map((e=>Buffer$1$1.from(e).toString("base64")))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map((e=>Long.fromValue(e).toNumber()))),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(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 f(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=parseKey(e.adminKey),t.kycKey=parseKey(e.kycKey),t.freezeKey=parseKey(e.freezeKey),t.wipeKey=parseKey(e.wipeKey),t.supplyKey=parseKey(e.supplyKey),t.feeScheduleKey=parseKey(e.feeScheduleKey),t.pauseKey=parseKey(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new f(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new u$5(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 f(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:Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new u$5(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:Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new u$5(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:Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}}))),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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 u$5(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 u$5(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 u$5(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new f(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=>Long.fromValue(e).toString()))),e.amount&&(t.amount=Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new u$5(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 f(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 u$5(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 f(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 u$5(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString()))),t}}class HCSParser{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=parseKey(e.adminKey),t.submitKey=parseKey(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new f(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=Buffer$1$1.from(e.message),n=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n)||n.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=n,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,n=e.chunkInfo.initialTransactionID.transactionValidStart;r&&n&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${n.seconds??0}.${n.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=parseKey(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=parseKey(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new f(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 FileParser{static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=parseKey({keyList:e.keys})),e.contents&&(t.contents=Buffer$1$1.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=Buffer$1$1.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=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=parseKey({keyList:e.keys})),e.contents&&(t.contents=Buffer$1$1.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 CryptoParser{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map((e=>{const t=new f(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=e$7.fromTinybars(Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(e$8.Hbar),isDecimal:!0}}))),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new u$5(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const n of r.transfers){const r=new f(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),o=Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:o})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new f(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new f(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=e$7.fromTinybars(Long.fromValue(e.initialBalance)).toString(e$8.Hbar)),e.key&&(t.key=parseKey(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=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 f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new f(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=parseKey(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${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=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 f(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=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 f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new f(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:e$7.fromTinybars(Long.fromValue(e.amount)).toString(e$8.Hbar)})))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map((e=>({tokenId:new u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new f(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount: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 u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new f(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=>Long.fromValue(e).toString()))),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new f(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 f(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new u$5(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map((e=>Long.fromValue(e).toString())):[]})))),t}}class SCSParser{static parseContractCall(e){if(!e)return;const t=e$7.fromTinybars(Long.fromValue(e.amount??0)),r={contractId:new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(e$8.Hbar))};return e.functionParameters&&(r.functionParameters=Buffer$1$1.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=r.functionParameters.substring(0,8))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=e$7.fromTinybars(Long.fromValue(e.initialBalance)).toString(e$8.Hbar)),e.gas&&(t.gas=Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=parseKey(e.adminKey)),e.constructorParameters&&(t.constructorParameters=Buffer$1$1.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=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 u$6(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=Buffer$1$1.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=parseKey(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=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 f(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=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 f(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 v(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new f(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new v(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}}class UtilParser{static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}}class TransactionParser{static parseTransactionBody(e){try{const t=decodeBase64(e),r=libExports.proto.SchedulableTransactionBody.decode(t),n=this.getTransactionType(r),o={type:n,humanReadableType:this.getHumanReadableType(n),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(o.memo=r.memo),r.transactionFee){const e=e$7.fromTinybars(Long.fromValue(r.transactionFee));o.transactionFee=e.toString(e$8.Hbar)}return r.cryptoTransfer&&CryptoParser.parseCryptoTransfers(r.cryptoTransfer,o),r.cryptoDelete&&(o.cryptoDelete=CryptoParser.parseCryptoDelete(r.cryptoDelete)),r.cryptoCreateAccount&&(o.cryptoCreateAccount=CryptoParser.parseCryptoCreateAccount(r.cryptoCreateAccount)),r.cryptoUpdateAccount&&(o.cryptoUpdateAccount=CryptoParser.parseCryptoUpdateAccount(r.cryptoUpdateAccount)),r.cryptoApproveAllowance&&(o.cryptoApproveAllowance=CryptoParser.parseCryptoApproveAllowance(r.cryptoApproveAllowance)),r.cryptoDeleteAllowance&&(o.cryptoDeleteAllowance=CryptoParser.parseCryptoDeleteAllowance(r.cryptoDeleteAllowance)),r.contractCall&&(o.contractCall=SCSParser.parseContractCall(r.contractCall)),r.contractCreateInstance&&(o.contractCreate=SCSParser.parseContractCreate(r.contractCreateInstance)),r.contractUpdateInstance&&(o.contractUpdate=SCSParser.parseContractUpdate(r.contractUpdateInstance)),r.contractDeleteInstance&&(o.contractDelete=SCSParser.parseContractDelete(r.contractDeleteInstance)),r.tokenCreation&&(o.tokenCreation=HTSParser.parseTokenCreate(r.tokenCreation)),r.tokenMint&&(o.tokenMint=HTSParser.parseTokenMint(r.tokenMint)),r.tokenBurn&&(o.tokenBurn=HTSParser.parseTokenBurn(r.tokenBurn)),r.tokenUpdate&&(o.tokenUpdate=HTSParser.parseTokenUpdate(r.tokenUpdate)),r.tokenFeeScheduleUpdate&&(o.tokenFeeScheduleUpdate=HTSParser.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate)),r.tokenFreeze&&(o.tokenFreeze=HTSParser.parseTokenFreeze(r.tokenFreeze)),r.tokenUnfreeze&&(o.tokenUnfreeze=HTSParser.parseTokenUnfreeze(r.tokenUnfreeze)),r.tokenGrantKyc&&(o.tokenGrantKyc=HTSParser.parseTokenGrantKyc(r.tokenGrantKyc)),r.tokenRevokeKyc&&(o.tokenRevokeKyc=HTSParser.parseTokenRevokeKyc(r.tokenRevokeKyc)),r.tokenPause&&(o.tokenPause=HTSParser.parseTokenPause(r.tokenPause)),r.tokenUnpause&&(o.tokenUnpause=HTSParser.parseTokenUnpause(r.tokenUnpause)),r.tokenWipe&&(o.tokenWipeAccount=HTSParser.parseTokenWipeAccount(r.tokenWipe)),r.tokenDeletion&&(o.tokenDelete=HTSParser.parseTokenDelete(r.tokenDeletion)),r.tokenAssociate&&(o.tokenAssociate=HTSParser.parseTokenAssociate(r.tokenAssociate)),r.tokenDissociate&&(o.tokenDissociate=HTSParser.parseTokenDissociate(r.tokenDissociate)),r.consensusCreateTopic&&(o.consensusCreateTopic=HCSParser.parseConsensusCreateTopic(r.consensusCreateTopic)),r.consensusSubmitMessage&&(o.consensusSubmitMessage=HCSParser.parseConsensusSubmitMessage(r.consensusSubmitMessage)),r.consensusUpdateTopic&&(o.consensusUpdateTopic=HCSParser.parseConsensusUpdateTopic(r.consensusUpdateTopic)),r.consensusDeleteTopic&&(o.consensusDeleteTopic=HCSParser.parseConsensusDeleteTopic(r.consensusDeleteTopic)),r.fileCreate&&(o.fileCreate=FileParser.parseFileCreate(r.fileCreate)),r.fileAppend&&(o.fileAppend=FileParser.parseFileAppend(r.fileAppend)),r.fileUpdate&&(o.fileUpdate=FileParser.parseFileUpdate(r.fileUpdate)),r.fileDelete&&(o.fileDelete=FileParser.parseFileDelete(r.fileDelete)),r.utilPrng&&(o.utilPrng=UtilParser.parseUtilPrng(r.utilPrng)),o}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 n of e.transfers){const e=parseFloat(n.amount);let o=n.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${n.accountId} (${o} ℏ)`):e>0&&r.push(`${n.accountId} (${o} ℏ)`)}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 n of e.tokenTransfers)t[n.tokenId]||(t[n.tokenId]=[]),t[n.tokenId].push(n);const r=[];for(const[e,n]of Object.entries(t)){const t=[],o=[];for(const e of n){const r=parseFloat(e.amount.toString());r<0?t.push(`${e.accountId} (${Math.abs(r)})`):r>0&&o.push(`${e.accountId} (${r})`)}t.length>0&&o.length>0&&r.push(`Transfer of token ${e} from ${t.join(", ")} to ${o.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: ${Buffer$1$1.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 n of e.tokenTransfers)t[n.tokenId]||(t[n.tokenId]=[]),t[n.tokenId].push(n);const r=[];for(const[e,n]of Object.entries(t)){const t=n.filter((e=>e.amount<0)).map((e=>`${e.accountId} (${Math.abs(e.amount)})`)),o=n.filter((e=>e.amount>0)).map((e=>`${e.accountId} (${e.amount})`));t.length>0&&o.length>0?r.push(`Transfer of token ${e} from ${t.join(", ")} to ${o.join(", ")}`):o.length>0?r.push(`Token ${e} received by ${o.join(", ")}`):t.length>0&&r.push(`Token ${e} sent from ${t.join(", ")}`)}if(r.length>0)return r.join("; ")}return"Unknown Transaction"}}var CustomFeeType=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(CustomFeeType||{});class FeeConfigBuilder{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new HederaMirrorNode(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,n,o=[]){return new FeeConfigBuilder({network:r,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,n,o,i=[],a){const s=new FeeConfigBuilder({network:n,logger:o,defaultCollectorAccountId:r});return await s.addTokenFee(e,t,r,a,i),s}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:CustomFeeType.FIXED_FEE}),this}async addTokenFee(e,t,r,n,o=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let i=n;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(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),i=0}return this.customFees.push({feeAmount:{amount:e*10**i,decimals:i},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...o],type:CustomFeeType.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)}}}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$2?global$2:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},r={byteLength:function(e){var t=c(e),r=t[0],n=t[1];return 3*(r+n)/4-n},toByteArray:function(e){var t,r,n=c(e),a=n[0],s=n[1],u=new i(function(e,t,r){return 3*(t+r)/4-r}(0,a,s)),l=0,d=s>0?a-4:a;for(r=0;r<d;r+=4)t=o[e.charCodeAt(r)]<<18|o[e.charCodeAt(r+1)]<<12|o[e.charCodeAt(r+2)]<<6|o[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=o[e.charCodeAt(r)]<<2|o[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=o[e.charCodeAt(r)]<<10|o[e.charCodeAt(r+1)]<<4|o[e.charCodeAt(r+2)]>>2,u[l++]=t>>8&255,u[l++]=255&t);return u},fromByteArray:function(e){for(var t,r=e.length,o=r%3,i=[],a=16383,s=0,c=r-o;s<c;s+=a)i.push(u(e,s,s+a>c?c:s+a));1===o?(t=e[r-1],i.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[r-2]<<8)+e[r-1],i.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return i.join("")}},n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function u(e,t,r){for(var o,i,a=[],s=t;s<r;s+=3)o=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(i=o)>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63;var l={
|
|
150
150
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
151
151
|
read:function(e,t,r,n,o){var i,a,s=8*o-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?o-1:0,h=r?-1:1,p=e[t+d];for(d+=h,i=p&(1<<-l)-1,p>>=-l,l+=s;l>0;i=256*i+e[t+d],d+=h,l-=8);for(a=i&(1<<-l)-1,i>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=h,l-=8);if(0===i)i=1-u;else{if(i===c)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),i-=u}return(p?-1:1)*a*Math.pow(2,i-n)},write:function(e,t,r,n,o,i){var a,s,c,u=8*i-o-1,l=(1<<u)-1,d=l>>1,h=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:i-1,f=n?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+d>=1?h/c:h*Math.pow(2,1-d))*c>=2&&(a++,c/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*c-1)*Math.pow(2,o),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,o),a=0));o>=8;e[r+p]=255&s,p+=f,s/=256,o-=8);for(a=a<<o|s,u+=o;u>0;e[r+p]=255&a,p+=f,a/=256,u-=8);e[r+p-f]|=128*m}};
|
|
152
152
|
/*!
|