@hashgraphonline/standards-sdk 0.0.134 → 0.0.136
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/hcs-10/connections-manager.d.ts +6 -0
- package/dist/cjs/hcs-10/connections-manager.d.ts.map +1 -1
- package/dist/cjs/{index-VOcWhzLh.cjs → index-16CauCnf.cjs} +3 -3
- package/dist/cjs/{index-VOcWhzLh.cjs.map → index-16CauCnf.cjs.map} +1 -1
- package/dist/cjs/{index-U-8_6nvw-D6N0eu0v.cjs → index-U-8_6nvw-EslFeCRa.cjs} +2 -2
- package/dist/cjs/{index-U-8_6nvw-D6N0eu0v.cjs.map → index-U-8_6nvw-EslFeCRa.cjs.map} +1 -1
- package/dist/cjs/standards-sdk.cjs +1 -1
- package/dist/cjs/{standards-sdk.es34-ChBjKBbQ-DvtLNZWB.cjs → standards-sdk.es34-ChBjKBbQ-Bo07Nkwz.cjs} +2 -2
- package/dist/cjs/{standards-sdk.es34-ChBjKBbQ-DvtLNZWB.cjs.map → standards-sdk.es34-ChBjKBbQ-Bo07Nkwz.cjs.map} +1 -1
- package/dist/es/hcs-10/connections-manager.d.ts +6 -0
- package/dist/es/hcs-10/connections-manager.d.ts.map +1 -1
- package/dist/es/standards-sdk.es10.js +10 -0
- package/dist/es/standards-sdk.es10.js.map +1 -1
- package/dist/es/standards-sdk.es20.js +1 -1
- package/dist/es/standards-sdk.es28.js +1 -1
- package/dist/es/standards-sdk.es38.js +21519 -2
- package/dist/es/standards-sdk.es38.js.map +1 -1
- package/dist/es/standards-sdk.es39.js +2 -21519
- package/dist/es/standards-sdk.es39.js.map +1 -1
- package/dist/es/standards-sdk.es41.js +1 -1
- package/dist/es/standards-sdk.es42.js +1 -1
- package/dist/es/standards-sdk.es7.js +1 -1
- package/dist/es/standards-sdk.es8.js +1 -1
- package/dist/es/standards-sdk.es9.js +1 -1
- package/dist/umd/hcs-10/connections-manager.d.ts +6 -0
- package/dist/umd/hcs-10/connections-manager.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 +2 -2
|
@@ -167,7 +167,7 @@ read:function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,p=r?
|
|
|
167
167
|
* Copyright(c) 2014 Jonathan Ong
|
|
168
168
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
169
169
|
* MIT Licensed
|
|
170
|
-
*/function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,i=requireMimeDb(),o=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&&i[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=o("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(i).forEach((function(e){var o=i[e],a=o.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(i[r[c]].source),l=n.indexOf(o.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$2,objectUtil;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.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},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(util$2||(util$2={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(objectUtil||(objectUtil={}));const ZodParsedType=util$2.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 Number.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$2.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"]);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 i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):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$2.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$2.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$2.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$2.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util$2.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$2.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$2.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(void 0!==i.message)return{...i,path:o,message:i.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{...i,path:o,message:s}};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:i}=n;if("aborted"===t.status)return INVALID;if("aborted"===i.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.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;var errorUtil;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(errorUtil||(errorUtil={}));var __classPrivateFieldGet=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},__classPrivateFieldSet=function(e,t,r,n,i){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!i)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!i:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?i.call(e,r):i?i.value=r:t.set(e,r),r},_ZodEnum_cache,_ZodNativeEnum_cache;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||(Array.isArray(this._key)?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:i}=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:i};return{errorMap:(t,i)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??i.defaultError}:void 0===i.data?{message:o??n??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:o??r??i.defaultError}},description:i}}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){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parseSync({data:e,path:r.path,parent:r});return handleResult(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return isValid(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>isValid(e)?{value:e.value}:{issues:t.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:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,i)}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 i=e(t),o=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then((e=>!!e||(o(),!1))):!!i||(o(),!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,"="),i=JSON.parse(atob(n));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{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 n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(r=this._getOrReturnCtx(e,r),i?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.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:n.message}),t.dirty());else if("uuid"===n.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){datetimeRegex(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){timeRegex(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?isValidIP(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?isValidJWT(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?isValidCidr(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):util$2.assertNever(n);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){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(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===e?.precision?null:e?.precision,...errorUtil.errToObj(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:t?.position,...errorUtil.errToObj(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,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...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$2.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$2.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$2.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: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{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const n of this._def.checks)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,type:"bigint",minimum:n.value,inclusive:n.inclusive,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,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):util$2.assertNever(n);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=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...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: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(Number.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$2.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: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,i=t.data.length<n.exactLength.value;(e||i)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:i?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 i=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,i)}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$2.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_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:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)i.includes(s)||o.push(s);const a=[];for(const s of i){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 o)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)o.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:o}),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 o){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)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:errorUtil.errToObj(e).message??n}:{message:n}}}:{}})}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={};for(const r of util$2.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const r of util$2.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const r of util$2.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const r of util$2.objectKeys(this.shape))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}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util$2.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 o of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=o._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,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 i=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:i}),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$2.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],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._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 i of t){const t=getDiscriminator(i.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,i)}}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$2.objectKeys(t),n=util$2.objectKeys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const o of n){const r=mergeValues(e[o],t[o]);if(!r.valid)return{valid:!1};i[o]=r.data}return{valid:!0,data:i}}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 i=mergeValues(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.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 i=mergeValues(e.value,n.value);return i.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:i.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=[],i=this._def.keyType,o=this._def.valueType;for(const a in r.data)n.push({key:i._parse(new ParseInputLazyPath(r,a,r.path,a)),value:o._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,i=this._def.valueType,o=[...r.data.entries()].map((([e,t],o)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[o,"key"])),value:i._parse(new ParseInputLazyPath(r,t,r.path,[o,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of o){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return INVALID;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of o){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return INVALID;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.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 i=this._def.valueType;function o(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)=>i._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>o(e))):o(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 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$2.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache,"f")||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values),"f"),!__classPrivateFieldGet(this,_ZodEnum_cache,"f").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$2.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util$2.objectValues(t);return addIssueToContext(r,{expected:util$2.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache,"f")||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util$2.getValidEnumValues(this._def.values)),"f"),!__classPrivateFieldGet(this,_ZodNativeEnum_cache,"f").has(e.data)){const e=util$2.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,i={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);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,i);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 o=n.transform(e.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,i)).then((e=>({status:t.value,value:e}))):e))}util$2.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)});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}}var ZodFirstPartyTypeKind;ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,booleanType=ZodBoolean.create,anyType=ZodAny.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create;ZodIntersection.create,ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;var ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",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||{}),MCPServerCapability=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(MCPServerCapability||{}),VerificationType=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(VerificationType||{}),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},mcpServiceNameToCapabilityMap={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},SocialLinkSchema=objectType({platform:stringType().min(1),handle:stringType().min(1)}),AIAgentDetailsSchema=objectType({type:nativeEnumType(AIAgentType),capabilities:arrayType(nativeEnumType(AIAgentCapability)).min(1),model:stringType().min(1),creator:stringType().optional()}),MCPServerConnectionInfoSchema=objectType({url:stringType().min(1),transport:enumType(["stdio","sse"])}),MCPServerVerificationSchema=objectType({type:nativeEnumType(VerificationType),value:stringType(),dns_field:stringType().optional(),challenge_path:stringType().optional()}),MCPServerHostSchema=objectType({minVersion:stringType().optional()}),MCPServerResourceSchema=objectType({name:stringType().min(1),description:stringType().min(1)}),MCPServerToolSchema=objectType({name:stringType().min(1),description:stringType().min(1)}),MCPServerDetailsSchema=objectType({version:stringType().min(1),connectionInfo:MCPServerConnectionInfoSchema,services:arrayType(nativeEnumType(MCPServerCapability)).min(1),description:stringType().min(1),verification:MCPServerVerificationSchema.optional(),host:MCPServerHostSchema.optional(),capabilities:arrayType(stringType()).optional(),resources:arrayType(MCPServerResourceSchema).optional(),tools:arrayType(MCPServerToolSchema).optional(),maintainer:stringType().optional(),repository:stringType().optional(),docs:stringType().optional()}),BaseProfileSchema=objectType({version:stringType().min(1),type:nativeEnumType(ProfileType),display_name:stringType().min(1),alias:stringType().optional(),bio:stringType().optional(),socials:arrayType(SocialLinkSchema).optional(),profileImage:stringType().optional(),properties:recordType(anyType()).optional(),inboundTopicId:stringType().optional(),outboundTopicId:stringType().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.PERSONAL),language:stringType().optional(),timezone:stringType().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.AI_AGENT),aiAgent:AIAgentDetailsSchema}),MCPServerProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.MCP_SERVER),mcpServer:MCPServerDetailsSchema}),HCS11ProfileSchema=unionType([PersonalProfileSchema,AIAgentProfileSchema,MCPServerProfileSchema]);class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$2.forMainnet():i$2.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=detectKeyTypeFromString(this.auth.privateKey);this.keyType=e.detectedType,this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":(t&&t.includes("ED25519"),this.keyType="ed25519"),this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?g.fromStringECDSA(this.auth.privateKey):g.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}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,i){const o=this.validateProfile({version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:i?.creator}});if(!o.valid)throw new Error(`Invalid AI Agent Profile: ${o.errors.join(", ")}`);return{version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:i?.creator}}}createMCPServerProfile(e,t,r){const n=this.validateProfile({version:"1.0",type:ProfileType.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!n.valid)throw new Error(`Invalid MCP Server Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:ProfileType.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=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),i=await n.getReceiptWithSigner(t);return i.status.toString()!==e$6.Success.toString()?{success:!1,error:`Transaction failed: ${i.status.toString()}: ${e$6.Success.toString()}`}:{success:!0,result:i}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,i=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});i.preparing("Preparing to inscribe image",0);const o=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw i.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");i.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:o},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);i.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw i.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");i.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:o},{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);i.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(i.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(i.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 i=this.validateProfile(e);if(!i.valid)return n.failed(`Invalid profile: ${i.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${i.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const o=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(o,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},i={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="ed25519"===this.keyType?g.fromStringED25519(this.auth.privateKey):g.fromStringECDSA(this.auth.privateKey),c=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:s,network:this.network},i):await inscribeWithSigner(r,this.auth.signer,i);if(!c.confirmed||!c.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const u=c.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:u,transactionId:c.result.transactionId}),{profileTopicId:u,transactionId:c.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,i=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});i.preparing("Starting profile creation process",0);const o=i.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{o.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return i.failed("Profile inscription failed",{error:a?.error}),a;if(i.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return i.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return i.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 i=n.substring(7);if(!i?.startsWith("hcs://")){if(i.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${i.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(i.startsWith("ar://")){const e=i.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: ${i}`}}{const e=i.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${i}`};const[n,o,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 i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok){const e=`Failed to confirm registration: ${i.statusText}`;throw n&&n.error(e),new Error(e)}return await i.json()}catch(i){throw n&&n.error(`Error checking registration status: ${i.message}`),i}}async waitForRegistrationConfirmation(e,t,r,n=60,i=2e3,o){let a=0;for(;a<n;){o&&o.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,o);if("success"===s.status)return o&&o.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw o&&o.error("Registration confirmation failed"),new Error("Registration confirmation failed");o&&o.info(`Registration still pending. Waiting ${i}ms before next attempt`),await new Promise((e=>setTimeout(e,i))),a++}return o&&o.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 i=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",i),i?.error)return n?.error("Error fetching profile",i.error),{error:i.error,success:!1};if(!i?.success||!i?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!i.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!i.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: ${i.profile.inboundTopicId}, Outbound topic: ${i.profile.outboundTopicId}`)}catch(i){return n&&n.error(`Error validating profile: ${i.message}`),{error:`Error validating profile: ${i.message}`,success:!1}}const o=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 o.json();return o.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(o){return{error:`Error during registration request: ${o.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 i=await n.json();return i.error?{registrations:[],error:i.error,success:!1}:{registrations:i.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),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,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),n=["message","close_connection","transaction"];return{messages:r.filter((e=>{if("hcs-10"!==e.p||!n.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const 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$a.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,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter((e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(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 i=n.profile;let o=null;n.topicInfo?.inboundTopic&&n.topicInfo?.outboundTopic&&n.topicInfo?.profileTopicId&&(o={inboundTopic:n.topicInfo.inboundTopic,outboundTopic:n.topicInfo.outboundTopic,profileTopicId:n.topicInfo.profileTopicId});const a={profile:i,topicInfo:o,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,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(r){const e=`Failed to retrieve outbound messages: ${r.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(),i=r.accountId,o=await this.canSubmitToTopic(e,i);if(!o?.canSubmit)throw new Error(`Cannot submit to topic: ${o.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=o.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(i);if(!l)throw new Error("Failed to retrieve outbound topic");const d=u.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:p}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:n,connectionTopicId:i,operatorId:o,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:i,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:r,operator_id:o,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,r=60,n=2e3,i=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).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),o=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),i&&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}o<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 getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const n=r.split(":");if(n.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const i=n[3];switch(i){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${i} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const 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 i=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!i.test(n)&&!!i.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),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?.limit?n.slice(0,t.limit):n}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,n;switch(t.op){case"register":r="0",n="0";break;case"delete":r="1",n="0";break;case"migrate":r="2",n="0";break;case"connection_request":r="3",n=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",n=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",n=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",n="3";break;case"close_connection":r="5",n="3"}return`hcs-10:op:${r}:${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$3.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$3.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}}}class MCPServerBuilder{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=Logger$3.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:VerificationType.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:VerificationType.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:VerificationType.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find((t=>t.platform===e));if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}}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){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.client="mainnet"===e.network?i$2.forMainnet():i$2.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorAccountId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=detectKeyTypeFromString(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t.privateKey),this.keyType=t.detectedType}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}this.network=e.network,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorAccountId),t=e?.key?._type;t.includes("ECDSA")?this.keyType="ecdsa":(t.includes("ED25519"),this.keyType="ed25519");const r="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorAccountId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorAccountId,r),{accountId:this.operatorAccountId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=g.generateED25519(),r=(new h).setKeyWithoutAlias(t.publicKey).setInitialBalance(new e$7(e));this.logger.debug("Executing account creation transaction");const n=await r.execute(this.client),i=(await n.getReceipt(this.client)).accountId;if(!i)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: ${i.toString()}`),{accountId:i.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,n){this.keyType||await this.initializeOperator();const i=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let o,a;switch(t){case InboundTopicType.PUBLIC:o=!1;break;case InboundTopicType.CONTROLLED:o=!0;break;case InboundTopicType.FEE_BASED:if(o=!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(i,!0,o,a)}async createAgent(e,t=60,r,n){this.keyType||await this.initializeOperator();const i=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||i.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,i.inboundTopicType,i.feeConfig,i.pfpBuffer,i.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{n&&n({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(i.name,i.bio,a.inboundTopicId,a.outboundTopicId,i.capabilities,i.metadata,i.pfpBuffer&&i.pfpBuffer.length>0&&!a.pfpTopicId?i.pfpBuffer:void 0,i.pfpFileName,a.pfpTopicId);a.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${a.profileTopicId}`),n&&n({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(r){const e=r,t=`Error inscribing profile picture: ${e.message}`;return this.logger.error(t),{pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async storeHCS11Profile(e,t,r,n,i=[],o,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:o.type||"autonomous"}),d=o.socials?Object.entries(o.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,i,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:o.properties,inboundTopicId:r,outboundTopicId:n,creator:o.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:u,transactionId:h.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 i=t.customFees.map((e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new 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===i.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const o=[...t.exemptAccounts||[],...r];return o.length>0&&(n=await this.setupExemptKeys(e,o)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(i)}async setupExemptKeys(e,t){let r=e;const n=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let i=[];if(n.length>0)try{i=await accountIdsToExemptKeys(n,this.network,this.logger)}catch(o){const e=`Error getting exempt keys: ${o.message}, continuing without exempt keys`;this.logger.warn(e)}return i.length>0&&(r=r.setFeeExemptKeys(i)),r}async handleConnectionRequest(e,t,r,n,i=60){const o=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:i,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(o,u,u,t)}else l=await this.createTopic(o,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}`,p=await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(a),f=await this.retrieveCommunicationTopics(t),m=`${f.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:f.outboundTopic,connectionRequestId:r,confirmedRequestId:p,connectionTopicId:l,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:l,confirmedConnectionSequenceNumber:p,operatorId:d}}async confirmConnection(e,t,r,n,i,o){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:i},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,o,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,i){const o=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:i?.progressCallback,waitMaxAttempts:i?.waitMaxAttempts,waitIntervalMs:i?.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,o.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const i=(new c).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(i.setAdminKey(this.client.operatorPublicKey),i.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$a||t instanceof s$9)&&(i.setAdminKey(t),this.client.operatorAccountId&&i.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?i.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$a||r instanceof s$9)&&i.setSubmitKey(r)),n&&await this.setupFees(i,n),this.logger.debug("Executing topic creation transaction");const o=await i.execute(this.client),a=await o.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 i="string"==typeof t?t:JSON.stringify(t),o=Buffer.byteLength(i,"utf8");if(o>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",o);const a=(new u).setTopicId(m$1.fromString(e)).setMessage(i),s=this.getHcs10TransactionMemo(t);let c;if(s&&a.setTransactionMemo(s),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);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.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",i=await InscriptionSDK.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),o={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},o,i);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,n=2e3,i=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+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),o=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),i&&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}o<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(){const e="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};o.agentMetadata=r.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:o}});let a,s=r.existingAccount;if(o.inboundTopicId&&o.outboundTopicId&&o.profileTopicId){if(s=s||r.existingAccount,!s)throw new Error("Cannot resume registration without account information");a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:g.fromString(s.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),this.logger.info("Resuming registration with existing state",{inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId})}else{if(!s)if(o.createdResources&&o.createdResources.some((e=>e.startsWith("account:")))){const e=o.createdResources.find((e=>e.startsWith("account:"))),n=e?.split(":")[1];n&&r.existingAccount?(s=r.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`))}else s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:o,account:s}});const c=detectKeyTypeFromString(s.privateKey),u=("ed25519"===c.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:u,keyType:c.detectedType,logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:o}});let l=o.outboundTopicId,d=o.inboundTopicId,p=o.pfpTopicId,h=o.profileTopicId;if(!l||!d||!h){p&&e.setExistingProfilePicture(p);const t=await a.createAgent(e,60,o,(e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...o,...e.details?.state}}})}));l=t.outboundTopicId,d=t.inboundTopicId,p=t.pfpTopicId,h=t.profileTopicId,o.outboundTopicId=l,o.inboundTopicId=d,o.pfpTopicId=p,o.profileTopicId=h,o.createdResources||(o.createdResources=[]),p&&!o.createdResources.includes(`pfp:${p}`)&&o.createdResources.push(`pfp:${p}`),o.createdResources.includes(`inbound:${d}`)||o.createdResources.push(`inbound:${d}`),o.createdResources.includes(`outbound:${l}`)||o.createdResources.push(`outbound:${l}`),o.createdResources.includes(`profile:${h}`)||o.createdResources.push(`profile:${h}`)}o.currentStage="profile",o.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:o,outboundTopicId:l,inboundTopicId:d,pfpTopicId:p,profileTopicId:h}})}const c=`${o.inboundTopicId}@${s.accountId}`;if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(s.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:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:e.details?.state||o}})},existingState:o});if(!e.success)return{...e,state:o};o=e.state||o}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:o}}),{success:!0,state:o,metadata:{accountId:s.accountId,privateKey:s.privateKey,operatorId:c,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId}}}catch(r){const e=r,n=`Failed to create and register agent: ${e.message}`;return this.logger.error(n),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,i=r?.delayMs??2e3,o=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};o&&o({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(o&&o({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")}o&&o({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,i,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),o&&o({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,i){this.logger.info("Registering agent");const o={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,o,i)}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 i=(new u$1).setScheduledTransaction(e).setPayerAccountId(n?f.fromString(n):this.client.operatorAccountId);if(t&&i.setScheduleMemo(t),r){const e=addSeconds(new Date,r),t=s$a.fromDate(e);i.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const o=await i.execute(this.client),a=await o.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=o.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${s}`),{scheduleId:s,transactionId:c}}async sendTransactionOperation(e,t,r,n,i){const o=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:i?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,o.requiresFee)}async sendTransaction(e,t,r,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:i,transactionId:o}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:i,transactionId:o,receipt:await this.sendTransactionOperation(e,i,r,n?.submitKey,{memo:n?.operationMemo})}}async createMCPServer(e,t=60,r,n){this.keyType||await this.initializeOperator();const i=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||i.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,InboundTopicType.PUBLIC,void 0,i.pfpBuffer,i.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),n&&n({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(i.name,i.mcpServer,{alias:i.alias,bio:i.bio,socials:i.socials||[],inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileImage:a.pfpTopicId?`hcs://1/${a.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");a.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${a.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(o,a.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),n&&n({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async _createEntityTopics(e,t,r,n,i,o,a,s){let{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e});c=await this.createTopic(t,!0,!0),this.logger.info(`Created new outbound topic ID: ${c}`),s&&s({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(u?this.logger.info(`Using existing inbound topic ID: ${u}`):(u=await this.createInboundTopic(r,n,e,n===InboundTopicType.FEE_BASED?i:void 0),this.logger.info(`Created new inbound topic ID: ${u}`),s&&s({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:u,state:{currentStage:"topics",completedPercentage:40}}})),!l&&o&&o.length>0&&a){this.logger.info("Inscribing new profile picture"),s&&s({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:u,state:{currentStage:"pfp",completedPercentage:50}}});l=(await this.inscribePfp(o,a)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${l}`),s&&s({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,state:{currentStage:"pfp",completedPercentage:55}}})}else l&&this.logger.info(`Using existing profile picture with topic ID: ${l}`);return{inboundTopicId:u,outboundTopicId:c,pfpTopicId:l,profileTopicId:d}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};o.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:o}});let a,s=r.existingAccount;if(o.inboundTopicId&&o.outboundTopicId&&o.profileTopicId){if(s=s||r.existingAccount,!s)throw new Error("Cannot resume registration without account information");const e=detectKeyTypeFromString(s.privateKey),t=("ed25519"===e.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:i}),this.logger.info("Resuming registration with existing state",{inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId})}else{if(!s)if(o.createdResources&&o.createdResources.some((e=>e.startsWith("account:")))){const e=o.createdResources.find((e=>e.startsWith("account:"))),n=e?.split(":")[1];n&&r.existingAccount?(s=r.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`))}else s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:o,account:s}});const c=detectKeyTypeFromString(s.privateKey);e.setExistingAccount(s.accountId,s.privateKey);const u=("ed25519"===c.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:o}});let l=o.outboundTopicId,d=o.inboundTopicId,p=o.pfpTopicId,h=o.profileTopicId;if(!l||!d||!h){p&&e.setExistingProfilePicture(p);const t=await a.createMCPServer(e,60,o,(e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...o,...e.details?.state}}})}));l=t.outboundTopicId,d=t.inboundTopicId,p=t.pfpTopicId,h=t.profileTopicId,o.outboundTopicId=l,o.inboundTopicId=d,o.pfpTopicId=p,o.profileTopicId=h,o.createdResources||(o.createdResources=[]),p&&!o.createdResources.includes(`pfp:${p}`)&&o.createdResources.push(`pfp:${p}`),o.createdResources.includes(`inbound:${d}`)||o.createdResources.push(`inbound:${d}`),o.createdResources.includes(`outbound:${l}`)||o.createdResources.push(`outbound:${l}`),o.createdResources.includes(`profile:${h}`)||o.createdResources.push(`profile:${h}`)}o.currentStage="profile",o.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:o,outboundTopicId:l,inboundTopicId:d,pfpTopicId:p,profileTopicId:h}})}const c=`${o.inboundTopicId}@${s.accountId}`;if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(s.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:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:e.details?.state||o}})},existingState:o});if(!e.success)return{...e,state:o};o=e.state||o}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:o}}),{success:!0,state:o,metadata:{accountId:s.accountId,privateKey:s.privateKey,operatorId:c,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId}}}catch(r){const e=r,n=`Failed to create and register MCP server: ${e.message}`;return this.logger.error(n),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}}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,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=Logger$3.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(r){this.logger.warn(`Failed to initialize HCS11Client: ${r}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,n,i){this.logger.info("Sending message");const o={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(o);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:i?.progressCallback,waitMaxAttempts:i?.waitMaxAttempts,waitIntervalMs:i?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");o.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,o,n,a.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",i=60){this.logger.info("Handling connection request");const o=this.hwc.getAccountInfo().accountId;if(!o)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(o);if(!s)throw new Error("Failed to retrieve public key");const u=new s$9([s,a],1),l=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:r}),d=(new c).setTopicMemo(l).setAutoRenewAccountId(f.fromString(o)).setAdminKey(u).setSubmitKey(u);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const m=h.topicId.toString(),g=`${e}@${o}`,y=await this.confirmConnection(e,m,t,r,g,n),b=await this.retrieveCommunicationTopics(o),v=await this.retrieveCommunicationTopics(t),w=`${v.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:b.outboundTopic,requestorOutboundTopicId:v.outboundTopic,connectionRequestId:r,confirmedRequestId:y,connectionTopicId:m,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:m,confirmedConnectionSequenceNumber:y,operatorId:g}}async confirmConnection(e,t,r,n,i,o){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:i,connection_id:n,m:o},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 i;if(i=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();i.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");n.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:i});const{inboundTopicId:o,outboundTopicId:a,state:s}=await this.createCommunicationTopics(t,n);let c,u,l;if(i=s,r||(e.setInboundTopicId(o),e.setOutboundTopicId(a)),r){const t=e.build();c=t.existingPfpTopicId||i.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=i.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,i,n):c&&(n.preparing(`Using existing profile picture: ${c}`,50,{state:i}),i.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,i,o,a,t,n),i.currentStage="complete",i.completedPercentage=100,n.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:i.profileTopicId,inboundTopicId:o,outboundTopicId:a,pfpTopicId:c,state:i});let d="";i.outboundTopicId&&(d=i.outboundTopicId);let p="";i.inboundTopicId&&(p=i.inboundTopicId);let h="";i.pfpTopicId&&(h=i.pfpTopicId);let f="";return i.profileTopicId&&(f=i.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:f,success:!0,state:i}}catch(i){return n.failed("Error during profile creation",{error:i.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:i.message,state:{currentStage:"init",completedPercentage:0,error:i.message}}}}async handleProfilePictureCreation(e,t,r,n){r.currentStage="pfp",n.preparing("Creating profile picture",30,{state:r});const i=n.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),o=await this.inscribePfp(e,t,{progressCallback:e=>i.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const a=o.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,i,o,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:i,outboundTopicId:o,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:i,outboundTopicId:o})}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,i=this.initializeRegistrationState(n,r?.existingState),o=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});o.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:i};if(o.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:i};this.logger.info("Successfully processed registration transaction")}o.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(i,n),o.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:i,confirmed:u}),{...a,confirmed:u,state:i}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,i=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(o.agentMetadata=r.metadata,i.preparing("Starting agent creation process",0,{state:o}),"complete"!==o.currentStage||!o.inboundTopicId||!o.outboundTopicId||!o.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);i.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},existingState:o,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");o=t.state,o.agentMetadata=r.metadata}i.preparing(`Agent creation status: ${o.currentStage}, ${o.completedPercentage}%`,30,{state:o});const{accountId:a}=this.getAccountAndSigner();if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);i.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:o});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");o=e.state,o.profileTopicId&&await(this.hcs11Client?.updateAccountMemoWithProfile(a,o.profileTopicId))}return i.completed("Agent creation and registration complete",{state:o}),{success:!0,state:o,metadata:{accountId:a,operatorId:`${o.inboundTopicId}@${a}`,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId,privateKey:null,...o.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,i=[],o={},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 p=c;if(!p&&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?p=t.pfpTopicId:d.failed("Failed to inscribe profile picture, continuing without PFP")}else c?d.preparing(`Using existing profile picture: ${c}`,30):d.preparing("No profile picture provided",30);if(!this.hcs11Client)return d.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"});d.preparing("Building agent profile",65);const f=o.socials?Object.entries(o.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,i,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:f,properties:{version:o.version||"1.0.0",creator:o.creator||"Unknown",supported_languages:o.supported_languages||["en"],permissions:o.permissions||[],model_details:o.model_details,training:o.training,capabilities_description:o.capabilities_description,...o},inboundTopicId:r,outboundTopicId:n,creator:o.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:p,success:!0,transactionId:y.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:n,signer:i}=this.getAccountAndSigner(),o=(new c).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(o.setAdminKey(a),o.setAutoRenewAccountId(n)),r&&a&&o.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(o,!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 i;this.logger.debug(`Submitting payload to topic ${e}`),i="string"==typeof t?t:JSON.stringify(t);const o=(new u).setTopicId(e).setMessage(i),a=this.getHcs10TransactionMemo(t);let s;if(a&&o.setTransactionMemo(a),n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),o.setMaxTransactionFee(new e$7(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();o.freezeWithSigner(e);const t=await o.sign(r);s=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else s=await this.hwc.executeTransactionWithErrorHandling(o,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}async inscribeFile(e,t,r){const{accountId:n,signer:i}=this.getAccountAndSigner(),o=mimeTypesExports.lookup(t)||"application/octet-stream",a=await InscriptionSDK.createWithAuth({type:"client",accountId:n,signer:i,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:o},i,{...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,i=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return i.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};i.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const o=e=>{i.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:o});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 i.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 i=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e?.ttl,accountId:n}),o=await this.createTopic(i,!0,!0);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create outbound topic");r.outboundTopicId=o.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 i=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{ttl:e?.ttl,accountId:n}),o=await this.createTopic(i,!0,!1);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create inbound topic");r.inboundTopicId=o.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,silent:e?.silent};if(this.logger=new Logger$3(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,i]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(n.messages||[],e),this.processInboundMessages(i.messages||[]);const o=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${n.messages?.length||0} outbound and ${i.messages?.length||0} inbound messages. Found ${o} 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,i]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 i){const n=e.connectionRequestId;if(!n)continue;const i=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(i?.connection_topic_id){r=!0;const t=i.connection_topic_id;let o=e.uniqueRequestKey;const a={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.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),o&&this.connections.delete(o),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 i of r){if(this.logger.debug(`Processing pending connection: ${i.connectionTopicId}`),!i.targetAccountId){this.logger.debug(`Skipping connection ${i.connectionTopicId} - no targetAccountId`);continue}let e=i.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(i.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${i.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(i.connectionTopicId,{...i,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${i.connectionTopicId} with inbound topic ID: ${e}`)}catch(n){this.logger.debug(`Error fetching profile for ${i.targetAccountId}: ${n}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=i.connectionRequestId||i.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 ${i.targetAccountId} on their inbound topic`),this.connections.set(i.connectionTopicId,{...i,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||i.created),lastActivity:new Date(n.created||i.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 ${i.targetAccountId}: ${n}`)}else this.logger.debug(`Skipping connection ${i.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 o of r){const e=o.connection_request_id,r=o.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(r),i=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:o.outbound_topic_id||"",targetAccountId:n,targetTopicId:i,operatorId:r,sequenceNumber:o.sequence_number,created:o.created||new Date,memo:o.m,status:"pending"};if(this.pendingRequests.set(s,a),!this.connections.has(s)){const t={connectionTopicId:s,targetAccountId:n,targetInboundTopicId:i,status:"pending",isPending:!0,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,uniqueRequestKey:s,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.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 o of n){const e=o.connection_request_id,t=o.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(o.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const n=`req-${e}:${o.operator_id}`,i=this.pendingRequests.get(n);if(i&&(i.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:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:n,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:n,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}const i=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const o of i){const e=o.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=o.connection_request_id&&o.operator_id?`req-${o.connection_request_id}:${o.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:o.created||new Date,closedReason:o.reason,closeMethod:o.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:o.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||"",i=this.baseClient.extractAccountFromOperatorId(t),o=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out request from account: ${i}`);continue}const a=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${i} as it has already been confirmed`):this.connections.has(a)||this.connections.set(a,{connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:a,originTopicId:o,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||"",i=n.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const o=`inb-${e}:${i}`;if(this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:o,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:o,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,i]of this.connections.entries())i.originTopicId===e&&i.inboundRequestId===t&&(this.connections.set(n,{...i,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),i.originTopicId===e&&i.connectionRequestId===t&&(this.connections.set(n,{...i,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?{...t}:void 0),i=[];for(const e of n)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||i.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),i.push(e)}return i}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===r.length)return;return r.sort(((e,t)=>t.created.getTime()-e.created.getTime())),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}const HCS20_CONSTANTS={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},HederaAccountIdSchema=stringType().regex(HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),NumberStringSchema=stringType().regex(/^\d+$/,"Must be a valid number").max(HCS20_CONSTANTS.MAX_NUMBER_LENGTH,`Max ${HCS20_CONSTANTS.MAX_NUMBER_LENGTH} digits`),TickSchema=stringType().min(1,"Tick cannot be empty").transform((e=>e.toLowerCase().trim())),HCS20BaseMessageSchema=objectType({p:literalType("hcs-20"),m:stringType().optional()}),HCS20DeployMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("deploy"),name:stringType().min(1).max(HCS20_CONSTANTS.MAX_NAME_LENGTH),tick:TickSchema,max:NumberStringSchema,lim:NumberStringSchema.optional(),metadata:stringType().max(HCS20_CONSTANTS.MAX_METADATA_LENGTH).optional()}),HCS20MintMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("mint"),tick:TickSchema,amt:NumberStringSchema,to:HederaAccountIdSchema}),HCS20BurnMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("burn"),tick:TickSchema,amt:NumberStringSchema,from:HederaAccountIdSchema}),HCS20TransferMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("transfer"),tick:TickSchema,amt:NumberStringSchema,from:HederaAccountIdSchema,to:HederaAccountIdSchema}),HCS20RegisterMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("register"),name:stringType().min(1).max(HCS20_CONSTANTS.MAX_NAME_LENGTH),metadata:stringType().max(HCS20_CONSTANTS.MAX_METADATA_LENGTH).optional(),private:booleanType(),t_id:HederaAccountIdSchema}),HCS20MessageSchema=discriminatedUnionType("op",[HCS20DeployMessageSchema,HCS20MintMessageSchema,HCS20BurnMessageSchema,HCS20TransferMessageSchema,HCS20RegisterMessageSchema]);class HCS20Error extends Error{constructor(e){super(e),this.name="HCS20Error"}}class PointsDeploymentError extends HCS20Error{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class PointsMintError extends HCS20Error{constructor(e,t,r,n){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=n,this.name="PointsMintError"}}class PointsTransferError extends HCS20Error{constructor(e,t,r,n,i,o){super(e),this.tick=t,this.from=r,this.to=n,this.amount=i,this.availableBalance=o,this.name="PointsTransferError"}}class PointsBurnError extends HCS20Error{constructor(e,t,r,n,i){super(e),this.tick=t,this.from=r,this.amount=n,this.availableBalance=i,this.name="PointsBurnError"}}class PointsValidationError extends HCS20Error{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class PointsNotFoundError extends HCS20Error{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}}class TopicRegistrationError extends HCS20Error{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class InsufficientBalanceError extends HCS20Error{constructor(e,t,r,n){super(`Insufficient balance for ${t}: required ${r}, available ${n}`),this.accountId=e,this.tick=t,this.required=r,this.available=n,this.name="InsufficientBalanceError"}}class SupplyLimitExceededError extends HCS20Error{constructor(e,t,r,n){super(`Supply limit exceeded for ${e}: max ${r}, current ${n}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=n,this.name="SupplyLimitExceededError"}}class MintLimitExceededError extends HCS20Error{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}}class InvalidMessageFormatError extends HCS20Error{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}}class InvalidAccountFormatError extends HCS20Error{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class InvalidTickFormatError extends HCS20Error{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}}class InvalidNumberFormatError extends HCS20Error{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}}class HCS20BaseClient{constructor(e){this.logger=e.logger||new Logger$3({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new HederaMirrorNode(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID}validateMessage(e){try{return HCS20MessageSchema.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map((e=>`${e.path.join(".")}: ${e.message}`))}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX.test(e))throw new InvalidAccountFormatError(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX.test(e))throw new InvalidAccountFormatError(e);return e}return e.toString()}}class BrowserHCS20Client extends HCS20BaseClient{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let n;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const r=await this.mirrorNode.getPublicKey(t),i=(new c).setTopicMemo(e.topicMemo||`HCS-20: ${e.name}`).setSubmitKey(r).setAdminKey(r).setAutoRenewAccountId(f.fromString(t)),o=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(o?.error)throw new Error(o.error);const a=o?.result;if(!a?.topicId)throw new Error("Failed to create topic: topicId is null");n=a.topicId.toString(),this.logger.info(`Created private topic: ${n}`)}else n=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:n});const i={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(i);if(!o.valid)throw new PointsValidationError("Invalid deploy message",o.errors);const a=await this.submitPayload(n,i,e.usePrivateTopic),s=a.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:n,deployTxId:s}),await new Promise((e=>setTimeout(e,2e3))),r?.({stage:"complete",percentage:100,topicId:n,deployTxId:s}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:n,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(n){throw r?.({stage:"complete",percentage:100,error:n instanceof Error?n.message:"Unknown error"}),n}}async mintPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,mintTxId:o}),{id:o,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,transferTxId:o}),{id:o,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,burnTxId:o}),{id:o,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},n=this.validateMessage(r);if(!n.valid)throw new PointsValidationError("Invalid register message",n.errors);t?.({stage:"submitting",percentage:50});const i=await this.submitPayload(this.registryTopicId,r,!1),o=i.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,registerTxId:o})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new TopicRegistrationError(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(m$1.fromString(e)).setMessage(n);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount)));const o=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(o?.error)throw this.logger.error(`Failed to submit payload: ${o.error}`),new Error(`Failed to submit payload: ${o.error}`);if(!o?.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"),o.result}}class HCS20Client extends HCS20BaseClient{constructor(e){super(e),this.initialized=!1,this.operatorId="string"==typeof e.operatorId?f.fromString(e.operatorId):e.operatorId,this.operatorKeyString=e.operatorKey,this.client="mainnet"===this.network?i$2.forMainnet():i$2.forTestnet();try{const{privateKey:t,detectedType:r}=detectKeyTypeFromString(e.operatorKey);this.operatorKey=t,this.keyType=r,this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0}catch(t){this.logger.debug("Failed to detect key type from string, will initialize later")}}async initializeOperator(){if(!this.initialized)try{const e=await this.mirrorNode.requestAccount(this.operatorId.toString()),t=e?.key?._type;t?.includes("ECDSA")?this.keyType="ecdsa":(t?.includes("ED25519"),this.keyType="ed25519"),this.operatorKey="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorKeyString):g.fromStringED25519(this.operatorKeyString),this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0,this.logger.debug(`Initialized operator with key type: ${this.keyType}`)}catch(e){this.logger.warn("Failed to query mirror node for key type, using ED25519"),this.keyType="ed25519",this.operatorKey=g.fromStringED25519(this.operatorKeyString),this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0}}async ensureInitialized(){this.initialized||await this.initializeOperator()}async submitPayload(e,t,r){const n="string"==typeof t?t:JSON.stringify(t),i=(new u).setTopicId(m$1.fromString(e)).setMessage(n);let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const a=await o.getReceipt(this.client);if(!a||a.status!==e$6.Success)throw new Error("Failed to submit message to topic");return{receipt:a,transactionId:o.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new c).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==e$6.Success||!r.topicId)throw new Error("Failed to create public topic");const n=r.topicId.toString();return this.logger.info(`Created public topic: ${n}`),this.publicTopicId=n,n}async createRegistryTopic(e){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const t=await(new c).setTopicMemo(e||"HCS-20 Registry").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==e$6.Success||!r.topicId)throw new Error("Failed to create registry topic");const n=r.topicId.toString();return this.logger.info(`Created registry topic: ${n}`),this.registryTopicId=n,n}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;if(t?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const t=await(new c).setTopicMemo(e.topicMemo||`HCS-20: ${e.name}`).setSubmitKey(this.operatorKey.publicKey).setAdminKey(this.operatorKey.publicKey).execute(this.client),n=await t.getReceipt(this.client);if(n.status!==e$6.Success||!n.topicId)throw new PointsDeploymentError("Failed to create topic",e.tick);r=n.topicId.toString(),this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},i=this.validateMessage(n);if(!i.valid)throw new PointsValidationError("Invalid deploy message",i.errors);const{transactionId:o}=await this.submitPayload(r,n);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:o}),await this.waitForMirrorNodeConfirmation(r,o),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:o});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId.toString(),currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const n={p:"hcs-20",op:"mint",tick:r,amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,{transactionId:o}=await this.submitPayload(i,n);t?.({stage:"confirming",percentage:80,mintTxId:o}),await this.waitForMirrorNodeConfirmation(i,o),t?.({stage:"complete",percentage:100,mintTxId:o});return{id:o,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),n=this.accountToString(e.from),i=this.accountToString(e.to);if(n!==this.operatorId.toString())throw new PointsTransferError("For public topics, transaction payer must match sender",e.tick,n,i,e.amount);t?.({stage:"submitting",percentage:50});const o={p:"hcs-20",op:"transfer",tick:r,amt:e.amount,from:n,to:i,m:e.memo},a=e.topicId||this.publicTopicId,{transactionId:s}=await this.submitPayload(a,o);t?.({stage:"confirming",percentage:80,transferTxId:s}),await this.waitForMirrorNodeConfirmation(a,s),t?.({stage:"complete",percentage:100,transferTxId:s});return{id:s,operation:"transfer",tick:r,amount:e.amount,from:n,to:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:a,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),n=this.accountToString(e.from);if(n!==this.operatorId.toString())throw new PointsBurnError("For public topics, transaction payer must match burner",e.tick,n,e.amount);t?.({stage:"submitting",percentage:50});const i={p:"hcs-20",op:"burn",tick:r,amt:e.amount,from:n,m:e.memo},o=e.topicId||this.publicTopicId,{transactionId:a}=await this.submitPayload(o,i);t?.({stage:"confirming",percentage:80,burnTxId:a}),await this.waitForMirrorNodeConfirmation(o,a),t?.({stage:"complete",percentage:100,burnTxId:a});return{id:a,operation:"burn",tick:r,amount:e.amount,from:n,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},n=this.validateMessage(r);if(!n.valid)throw new PointsValidationError("Invalid register message",n.errors);t?.({stage:"submitting",percentage:50});const{transactionId:i}=await this.submitPayload(this.registryTopicId,r);t?.({stage:"confirming",percentage:80,registerTxId:i}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,i),t?.({stage:"complete",percentage:100,registerTxId:i}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let i=0;i<r;i++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some((e=>e.consensus_timestamp)))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(n){this.logger.debug(`Mirror node check attempt ${i+1} failed:`,n)}await sleep(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}}class HCS20PointsIndexer{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new Logger$3({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new HederaMirrorNode(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),n=this.state.balances.get(r);if(!n)return"0";const i=n.get(t);return i?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=e?.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID,r=e?.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID,n=e?.pollInterval||3e4;await this.indexTopics(t,r,e?.privateTopics);const i=async()=>{if(this.isProcessing){try{await this.indexTopics(t,r,e?.privateTopics)}catch(o){this.logger.error("Polling error:",o)}this.isProcessing&&setTimeout(i,n)}};setTimeout(i,n)}async indexOnce(e){const t=e?.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID,r=e?.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID;await this.indexTopics(t,r,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),await this.indexTopic(e,!1);const n=[...await this.getRegisteredTopics(t),...r||[]];for(const i of n)await this.indexTopic(i,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{const n=await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"});for(const e of n)try{const r=e.data||e;r&&"object"==typeof r&&"hcs-20"===r.p&&"register"===r.op&&r.t_id&&t.push(r.t_id)}catch(r){continue}}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const n=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${n||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:n?n+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let o=n||0;for(const a of i)try{const r=a;if(!r.p||"hcs-20"!==r.p)continue;const n=r,i=r.sequence_number||0;this.logger.debug(`Found HCS-20 message: op=${n.op}, sequence=${i}`),i>o&&(o=i);const s={consensus_timestamp:r.consensus_timestamp||"",sequence_number:i,payer_account_id:r.payer_account_id||"",transaction_id:r.transaction_id||""};this.processMessage(n,s,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=r.consensus_timestamp||""}catch(r){this.logger.debug(`Failed to process message: ${r}`);continue}o>(n||0)&&this.lastIndexedSequence.set(e,o)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,n){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,n);break;case"mint":this.processMintMessage(e,t,r,n);break;case"transfer":this.processTransferMessage(e,t,r,n);break;case"burn":this.processBurnMessage(e,t,r,n)}}processDeployMessage(e,t,r,n){const i=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(i))return;const o={name:e.name,tick:i,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:n};this.state.deployedPoints.set(i,o),this.logger.info(`Deployed points: ${i}`)}processMintMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(i);if(!o)return;const a=BigInt(e.amt),s=BigInt(o.currentSupply);if(s+a>BigInt(o.maxSupply))return;if(o.limitPerMint&&a>BigInt(o.limitPerMint))return;o.currentSupply=(s+a).toString();let c=this.state.balances.get(i);c||(c=new Map,this.state.balances.set(i,c));const u=c.get(e.to),l=u?(BigInt(u.balance)+a).toString():e.amt;c.set(e.to,{tick:i,accountId:e.to,balance:l,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:i,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.balances.get(i);if(!o)return;if(!n&&t.payer_account_id!==e.from)return;const a=o.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const s=BigInt(e.amt);a.balance=(BigInt(a.balance)-s).toString(),a.lastUpdated=t.consensus_timestamp;const c=o.get(e.to);c?(c.balance=(BigInt(c.balance)+s).toString(),c.lastUpdated=t.consensus_timestamp):o.set(e.to,{tick:i,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:i,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(i),a=this.state.balances.get(i);if(!o||!a)return;if(!n&&t.payer_account_id!==e.from)return;const s=a.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);s.balance=(BigInt(s.balance)-c).toString(),s.lastUpdated=t.consensus_timestamp,o.currentSupply=(BigInt(o.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:i,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}}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,i=[]){return new FeeConfigBuilder({network:r,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,i)}static async forToken(e,t,r,n,i,o=[],a){const s=new FeeConfigBuilder({network:n,logger:i,defaultCollectorAccountId:r});return await s.addTokenFee(e,t,r,a,o),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,i=[]){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 o=n;if(void 0===o)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(o=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${o}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),o=0)}catch(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),o=0}return this.customFees.push({feeAmount:{amount:e*10**o,decimals:o},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...i],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$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$1?global$1:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist$1={},hasRequiredDist$1;function requireDist$1(){return hasRequiredDist$1||(hasRequiredDist$1=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 o(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=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[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,i=r%3,o=[],a=16383,s=0,c=r-i;s<c;s+=a)o.push(u(e,s,s+a>c?c:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")}},n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],i[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 i,o,a=[],s=t;s<r;s+=3)i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(o=i)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63;var l={
|
|
170
|
+
*/function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,i=requireMimeDb(),o=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&&i[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=o("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(i).forEach((function(e){var o=i[e],a=o.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(i[r[c]].source),l=n.indexOf(o.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$2,objectUtil;!function(e){e.assertEqual=e=>{},e.assertIs=function(e){},e.assertNever=function(e){throw new Error},e.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},e.getValidEnumValues=t=>{const r=e.objectKeys(t).filter((e=>"number"!=typeof t[t[e]])),n={};for(const e of r)n[e]=t[e];return e.objectValues(n)},e.objectValues=t=>e.objectKeys(t).map((function(e){return t[e]})),e.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},e.find=(e,t)=>{for(const r of e)if(t(r))return r},e.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&Number.isFinite(e)&&Math.floor(e)===e,e.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},e.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t}(util$2||(util$2={})),function(e){e.mergeShapes=(e,t)=>({...e,...t})}(objectUtil||(objectUtil={}));const ZodParsedType=util$2.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 Number.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$2.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"]);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 i of e.issues)if("invalid_union"===i.code)i.unionErrors.map(n);else if("invalid_return_type"===i.code)n(i.returnTypeError);else if("invalid_arguments"===i.code)n(i.argumentsError);else if(0===i.path.length)r._errors.push(t(i));else{let e=r,n=0;for(;n<i.path.length;){const r=i.path[n];n===i.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(i))):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$2.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$2.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util$2.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util$2.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util$2.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$2.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$2.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],a={...i,path:o};if(void 0!==i.message)return{...i,path:o,message:i.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{...i,path:o,message:s}};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:i}=n;if("aborted"===t.status)return INVALID;if("aborted"===i.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===i.status&&e.dirty(),"__proto__"===t.value||void 0===i.value&&!n.alwaysSet||(r[t.value]=i.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;var errorUtil;!function(e){e.errToObj=e=>"string"==typeof e?{message:e}:e||{},e.toString=e=>"string"==typeof e?e:e?.message}(errorUtil||(errorUtil={}));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||(Array.isArray(this._key)?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:i}=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:i};return{errorMap:(t,i)=>{const{message:o}=e;return"invalid_enum_value"===t.code?{message:o??i.defaultError}:void 0===i.data?{message:o??n??i.defaultError}:"invalid_type"!==t.code?{message:i.defaultError}:{message:o??r??i.defaultError}},description:i}}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){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parseSync({data:e,path:r.path,parent:r});return handleResult(r,n)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return isValid(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((e=>isValid(e)?{value:e.value}:{issues:t.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:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,i)}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 i=e(t),o=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&i instanceof Promise?i.then((e=>!!e||(o(),!1))):!!i||(o(),!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,"="),i=JSON.parse(atob(n));return"object"==typeof i&&null!==i&&((!("typ"in i)||"JWT"===i?.typ)&&(!!i.alg&&(!t||i.alg===t)))}catch{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 n of this._def.checks)if("min"===n.kind)e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("max"===n.kind)e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),t.dirty());else if("length"===n.kind){const i=e.data.length>n.value,o=e.data.length<n.value;(i||o)&&(r=this._getOrReturnCtx(e,r),i?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),t.dirty())}else if("email"===n.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("emoji"===n.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:n.message}),t.dirty());else if("uuid"===n.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("nanoid"===n.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("cuid"===n.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("cuid2"===n.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("ulid"===n.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty());else if("url"===n.kind)try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()}else if("regex"===n.kind){n.regex.lastIndex=0;n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty())}else if("trim"===n.kind)e.data=e.data.trim();else if("includes"===n.kind)e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),t.dirty());else if("toLowerCase"===n.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===n.kind)e.data=e.data.toUpperCase();else if("startsWith"===n.kind)e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:n.value},message:n.message}),t.dirty());else if("endsWith"===n.kind)e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:n.value},message:n.message}),t.dirty());else if("datetime"===n.kind){datetimeRegex(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:n.message}),t.dirty())}else if("date"===n.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:n.message}),t.dirty())}else if("time"===n.kind){timeRegex(n).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:n.message}),t.dirty())}else"duration"===n.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"ip"===n.kind?isValidIP(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"jwt"===n.kind?isValidJWT(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"cidr"===n.kind?isValidCidr(e.data,n.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"base64"===n.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):"base64url"===n.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:n.message}),t.dirty()):util$2.assertNever(n);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){return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===e?.precision?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...errorUtil.errToObj(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===e?.precision?null:e?.precision,...errorUtil.errToObj(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:t?.position,...errorUtil.errToObj(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,i=r>n?r:n;return Number.parseInt(e.toFixed(i).replace(".",""))%Number.parseInt(t.toFixed(i).replace(".",""))/10**i}ZodString.create=e=>new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:e?.coerce??!1,...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$2.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$2.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$2.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: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{return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const n of this._def.checks)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,type:"bigint",minimum:n.value,inclusive:n.inclusive,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,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty())}else"multipleOf"===n.kind?e.data%n.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):util$2.assertNever(n);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=>new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:e?.coerce??!1,...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: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(Number.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$2.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: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,i=t.data.length<n.exactLength.value;(e||i)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:i?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 i=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,i)}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$2.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_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:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)i.includes(s)||o.push(s);const a=[];for(const s of i){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 o)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)o.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:o}),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 o){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)=>{const n=this._def.errorMap?.(t,r).message??r.defaultError;return"unrecognized_keys"===t.code?{message:errorUtil.errToObj(e).message??n}:{message:n}}}:{}})}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={};for(const r of util$2.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};for(const r of util$2.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};for(const r of util$2.objectKeys(this.shape)){const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()}return new ZodObject({...this._def,shape:()=>t})}required(e){const t={};for(const r of util$2.objectKeys(this.shape))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}return new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util$2.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 o of r){const r={...t,common:{...t.common,issues:[]},parent:null},i=o._parseSync({data:t.data,path:t.path,parent:r});if("valid"===i.status)return i;"dirty"!==i.status||e||(e={result:i,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 i=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:i}),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$2.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],i=this.optionsMap.get(n);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._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 i of t){const t=getDiscriminator(i.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,i)}}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$2.objectKeys(t),n=util$2.objectKeys(e).filter((e=>-1!==r.indexOf(e))),i={...e,...t};for(const o of n){const r=mergeValues(e[o],t[o]);if(!r.valid)return{valid:!1};i[o]=r.data}return{valid:!0,data:i}}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 i=mergeValues(e[n],t[n]);if(!i.valid)return{valid:!1};r.push(i.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 i=mergeValues(e.value,n.value);return i.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:i.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=[],i=this._def.keyType,o=this._def.valueType;for(const a in r.data)n.push({key:i._parse(new ParseInputLazyPath(r,a,r.path,a)),value:o._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,i=this._def.valueType,o=[...r.data.entries()].map((([e,t],o)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[o,"key"])),value:i._parse(new ParseInputLazyPath(r,t,r.path,[o,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of o){const n=await r.key,i=await r.value;if("aborted"===n.status||"aborted"===i.status)return INVALID;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of o){const n=r.key,i=r.value;if("aborted"===n.status||"aborted"===i.status)return INVALID;"dirty"!==n.status&&"dirty"!==i.status||t.dirty(),e.set(n.value,i.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 i=this._def.valueType;function o(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)=>i._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>o(e))):o(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 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{_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util$2.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(this._def.values)),!this._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.create=createZodEnum;class ZodNativeEnum extends ZodType{_parse(e){const t=util$2.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util$2.objectValues(t);return addIssueToContext(r,{expected:util$2.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(this._cache||(this._cache=new Set(util$2.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const e=util$2.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.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,i={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),"preprocess"===n.type){const e=n.transform(r.data,i);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,i);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 INVALID;const o=n.transform(e.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,i)).then((e=>({status:t.value,value:e}))):INVALID))}util$2.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)});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}}var ZodFirstPartyTypeKind;ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)}),function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"}(ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}));const stringType=ZodString.create,booleanType=ZodBoolean.create,anyType=ZodAny.create;ZodNever.create;const arrayType=ZodArray.create,objectType=ZodObject.create,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create;ZodIntersection.create,ZodTuple.create;const recordType=ZodRecord.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create;ZodPromise.create,ZodOptional.create,ZodNullable.create;var ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",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||{}),MCPServerCapability=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(MCPServerCapability||{}),VerificationType=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(VerificationType||{}),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},mcpServiceNameToCapabilityMap={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},SocialLinkSchema=objectType({platform:stringType().min(1),handle:stringType().min(1)}),AIAgentDetailsSchema=objectType({type:nativeEnumType(AIAgentType),capabilities:arrayType(nativeEnumType(AIAgentCapability)).min(1),model:stringType().min(1),creator:stringType().optional()}),MCPServerConnectionInfoSchema=objectType({url:stringType().min(1),transport:enumType(["stdio","sse"])}),MCPServerVerificationSchema=objectType({type:nativeEnumType(VerificationType),value:stringType(),dns_field:stringType().optional(),challenge_path:stringType().optional()}),MCPServerHostSchema=objectType({minVersion:stringType().optional()}),MCPServerResourceSchema=objectType({name:stringType().min(1),description:stringType().min(1)}),MCPServerToolSchema=objectType({name:stringType().min(1),description:stringType().min(1)}),MCPServerDetailsSchema=objectType({version:stringType().min(1),connectionInfo:MCPServerConnectionInfoSchema,services:arrayType(nativeEnumType(MCPServerCapability)).min(1),description:stringType().min(1),verification:MCPServerVerificationSchema.optional(),host:MCPServerHostSchema.optional(),capabilities:arrayType(stringType()).optional(),resources:arrayType(MCPServerResourceSchema).optional(),tools:arrayType(MCPServerToolSchema).optional(),maintainer:stringType().optional(),repository:stringType().optional(),docs:stringType().optional()}),BaseProfileSchema=objectType({version:stringType().min(1),type:nativeEnumType(ProfileType),display_name:stringType().min(1),alias:stringType().optional(),bio:stringType().optional(),socials:arrayType(SocialLinkSchema).optional(),profileImage:stringType().optional(),properties:recordType(anyType()).optional(),inboundTopicId:stringType().optional(),outboundTopicId:stringType().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.PERSONAL),language:stringType().optional(),timezone:stringType().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.AI_AGENT),aiAgent:AIAgentDetailsSchema}),MCPServerProfileSchema=BaseProfileSchema.extend({type:literalType(ProfileType.MCP_SERVER),mcpServer:MCPServerDetailsSchema}),HCS11ProfileSchema=unionType([PersonalProfileSchema,AIAgentProfileSchema,MCPServerProfileSchema]);class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$2.forMainnet():i$2.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=detectKeyTypeFromString(this.auth.privateKey);this.keyType=e.detectedType,this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":(t&&t.includes("ED25519"),this.keyType="ed25519"),this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?g.fromStringECDSA(this.auth.privateKey):g.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}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,i){const o=this.validateProfile({version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:i?.creator}});if(!o.valid)throw new Error(`Invalid AI Agent Profile: ${o.errors.join(", ")}`);return{version:"1.0",type:ProfileType.AI_AGENT,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:i?.creator}}}createMCPServerProfile(e,t,r){const n=this.validateProfile({version:"1.0",type:ProfileType.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!n.valid)throw new Error(`Invalid MCP Server Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:ProfileType.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=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),i=await n.getReceiptWithSigner(t);return i.status.toString()!==e$6.Success.toString()?{success:!1,error:`Transaction failed: ${i.status.toString()}: ${e$6.Success.toString()}`}:{success:!0,result:i}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,i=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});i.preparing("Preparing to inscribe image",0);const o=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw i.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");i.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:o},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);i.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw i.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");i.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:o},{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);i.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(i.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(i.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 i=this.validateProfile(e);if(!i.valid)return n.failed(`Invalid profile: ${i.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${i.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const o=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(o,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},i={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="ed25519"===this.keyType?g.fromStringED25519(this.auth.privateKey):g.fromStringECDSA(this.auth.privateKey),c=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:s,network:this.network},i):await inscribeWithSigner(r,this.auth.signer,i);if(!c.confirmed||!c.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const u=c.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:u,transactionId:c.result.transactionId}),{profileTopicId:u,transactionId:c.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,i=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});i.preparing("Starting profile creation process",0);const o=i.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{o.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return i.failed("Profile inscription failed",{error:a?.error}),a;if(i.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return i.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return i.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 i=n.substring(7);if(!i?.startsWith("hcs://")){if(i.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${i.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(i.startsWith("ar://")){const e=i.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: ${i}`}}{const e=i.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${i}`};const[n,o,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 i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok){const e=`Failed to confirm registration: ${i.statusText}`;throw n&&n.error(e),new Error(e)}return await i.json()}catch(i){throw n&&n.error(`Error checking registration status: ${i.message}`),i}}async waitForRegistrationConfirmation(e,t,r,n=60,i=2e3,o){let a=0;for(;a<n;){o&&o.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,o);if("success"===s.status)return o&&o.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw o&&o.error("Registration confirmation failed"),new Error("Registration confirmation failed");o&&o.info(`Registration still pending. Waiting ${i}ms before next attempt`),await new Promise((e=>setTimeout(e,i))),a++}return o&&o.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 i=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",i),i?.error)return n?.error("Error fetching profile",i.error),{error:i.error,success:!1};if(!i?.success||!i?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!i.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!i.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: ${i.profile.inboundTopicId}, Outbound topic: ${i.profile.outboundTopicId}`)}catch(i){return n&&n.error(`Error validating profile: ${i.message}`),{error:`Error validating profile: ${i.message}`,success:!1}}const o=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 o.json();return o.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(o){return{error:`Error during registration request: ${o.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 i=await n.json();return i.error?{registrations:[],error:i.error,success:!1}:{registrations:i.registrations||[],success:!0}}catch(r){return{registrations:[],error:`Error fetching registrations: ${r.message}`,success:!1}}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),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,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),n=["message","close_connection","transaction"];return{messages:r.filter((e=>{if("hcs-10"!==e.p||!n.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const 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$a.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,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter((e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(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 i=n.profile;let o=null;n.topicInfo?.inboundTopic&&n.topicInfo?.outboundTopic&&n.topicInfo?.profileTopicId&&(o={inboundTopic:n.topicInfo.inboundTopic,outboundTopic:n.topicInfo.outboundTopic,profileTopicId:n.topicInfo.profileTopicId});const a={profile:i,topicInfo:o,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,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(r){const e=`Failed to retrieve outbound messages: ${r.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(),i=r.accountId,o=await this.canSubmitToTopic(e,i);if(!o?.canSubmit)throw new Error(`Cannot submit to topic: ${o.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=o.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(i);if(!l)throw new Error("Failed to retrieve outbound topic");const d=u.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:d,operator_id:p}),u}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:n,connectionTopicId:i,operatorId:o,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:i,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:r,operator_id:o,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,r=60,n=2e3,i=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).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),o=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),i&&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}o<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 getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const n=r.split(":");if(n.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const i=n[3];switch(i){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${i} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const 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 i=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!i.test(n)&&!!i.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),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?.limit?n.slice(0,t.limit):n}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,n;switch(t.op){case"register":r="0",n="0";break;case"delete":r="1",n="0";break;case"migrate":r="2",n="0";break;case"connection_request":r="3",n=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",n=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",n=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",n="3";break;case"close_connection":r="5",n="3"}return`hcs-10:op:${r}:${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$3.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$3.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}}}class MCPServerBuilder{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=Logger$3.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:VerificationType.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:VerificationType.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:VerificationType.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find((t=>t.platform===e));if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}}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){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.client="mainnet"===e.network?i$2.forMainnet():i$2.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorAccountId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=detectKeyTypeFromString(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t.privateKey),this.keyType=t.detectedType}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ed25519"}this.initializeOperator()}this.network=e.network,this.logger=Logger$3.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorAccountId),t=e?.key?._type;t.includes("ECDSA")?this.keyType="ecdsa":(t.includes("ED25519"),this.keyType="ed25519");const r="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorAccountId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorAccountId,r),{accountId:this.operatorAccountId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=g.generateED25519(),r=(new h).setKeyWithoutAlias(t.publicKey).setInitialBalance(new e$7(e));this.logger.debug("Executing account creation transaction");const n=await r.execute(this.client),i=(await n.getReceipt(this.client)).accountId;if(!i)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: ${i.toString()}`),{accountId:i.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,n){this.keyType||await this.initializeOperator();const i=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let o,a;switch(t){case InboundTopicType.PUBLIC:o=!1;break;case InboundTopicType.CONTROLLED:o=!0;break;case InboundTopicType.FEE_BASED:if(o=!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(i,!0,o,a)}async createAgent(e,t=60,r,n){this.keyType||await this.initializeOperator();const i=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||i.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,i.inboundTopicType,i.feeConfig,i.pfpBuffer,i.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{n&&n({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(i.name,i.bio,a.inboundTopicId,a.outboundTopicId,i.capabilities,i.metadata,i.pfpBuffer&&i.pfpBuffer.length>0&&!a.pfpTopicId?i.pfpBuffer:void 0,i.pfpFileName,a.pfpTopicId);a.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${a.profileTopicId}`),n&&n({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(r){const e=r,t=`Error inscribing profile picture: ${e.message}`;return this.logger.error(t),{pfpTopicId:"",transactionId:"",success:!1,error:e.message}}}async storeHCS11Profile(e,t,r,n,i=[],o,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:o.type||"autonomous"}),d=o.socials?Object.entries(o.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,i,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:o.properties,inboundTopicId:r,outboundTopicId:n,creator:o.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:u,transactionId:h.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 i=t.customFees.map((e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new 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===i.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const o=[...t.exemptAccounts||[],...r];return o.length>0&&(n=await this.setupExemptKeys(e,o)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(i)}async setupExemptKeys(e,t){let r=e;const n=Array.from(new Set(t)).filter((e=>e!==this.client.operatorAccountId?.toString()));let i=[];if(n.length>0)try{i=await accountIdsToExemptKeys(n,this.network,this.logger)}catch(o){const e=`Error getting exempt keys: ${o.message}, continuing without exempt keys`;this.logger.warn(e)}return i.length>0&&(r=r.setFeeExemptKeys(i)),r}async handleConnectionRequest(e,t,r,n,i=60){const o=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:i,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(o,u,u,t)}else l=await this.createTopic(o,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}`,p=await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(a),f=await this.retrieveCommunicationTopics(t),m=`${f.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:f.outboundTopic,connectionRequestId:r,confirmedRequestId:p,connectionTopicId:l,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:l,confirmedConnectionSequenceNumber:p,operatorId:d}}async confirmConnection(e,t,r,n,i,o){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:i},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,o,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,i){const o=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:i?.progressCallback,waitMaxAttempts:i?.waitMaxAttempts,waitIntervalMs:i?.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,o.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const i=(new c).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(i.setAdminKey(this.client.operatorPublicKey),i.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$a||t instanceof s$9)&&(i.setAdminKey(t),this.client.operatorAccountId&&i.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?i.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$a||r instanceof s$9)&&i.setSubmitKey(r)),n&&await this.setupFees(i,n),this.logger.debug("Executing topic creation transaction");const o=await i.execute(this.client),a=await o.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 i="string"==typeof t?t:JSON.stringify(t),o=Buffer.byteLength(i,"utf8");if(o>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",o);const a=(new u).setTopicId(m$1.fromString(e)).setMessage(i),s=this.getHcs10TransactionMemo(t);let c;if(s&&a.setTransactionMemo(s),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);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.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",i=await InscriptionSDK.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),o={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},o,i);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,n=2e3,i=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+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),o=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),i&&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}o<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(){const e="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorPrivateKey):g.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};o.agentMetadata=r.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:o}});let a,s=r.existingAccount;if(o.inboundTopicId&&o.outboundTopicId&&o.profileTopicId){if(s=s||r.existingAccount,!s)throw new Error("Cannot resume registration without account information");a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:g.fromString(s.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:i}),this.logger.info("Resuming registration with existing state",{inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId})}else{if(!s)if(o.createdResources&&o.createdResources.some((e=>e.startsWith("account:")))){const e=o.createdResources.find((e=>e.startsWith("account:"))),n=e?.split(":")[1];n&&r.existingAccount?(s=r.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`))}else s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:o,account:s}});const c=detectKeyTypeFromString(s.privateKey),u=("ed25519"===c.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:u,keyType:c.detectedType,logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:o}});let l=o.outboundTopicId,d=o.inboundTopicId,p=o.pfpTopicId,h=o.profileTopicId;if(!l||!d||!h){p&&e.setExistingProfilePicture(p);const t=await a.createAgent(e,60,o,(e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...o,...e.details?.state}}})}));l=t.outboundTopicId,d=t.inboundTopicId,p=t.pfpTopicId,h=t.profileTopicId,o.outboundTopicId=l,o.inboundTopicId=d,o.pfpTopicId=p,o.profileTopicId=h,o.createdResources||(o.createdResources=[]),p&&!o.createdResources.includes(`pfp:${p}`)&&o.createdResources.push(`pfp:${p}`),o.createdResources.includes(`inbound:${d}`)||o.createdResources.push(`inbound:${d}`),o.createdResources.includes(`outbound:${l}`)||o.createdResources.push(`outbound:${l}`),o.createdResources.includes(`profile:${h}`)||o.createdResources.push(`profile:${h}`)}o.currentStage="profile",o.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:o,outboundTopicId:l,inboundTopicId:d,pfpTopicId:p,profileTopicId:h}})}const c=`${o.inboundTopicId}@${s.accountId}`;if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(s.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:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:e.details?.state||o}})},existingState:o});if(!e.success)return{...e,state:o};o=e.state||o}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:o}}),{success:!0,state:o,metadata:{accountId:s.accountId,privateKey:s.privateKey,operatorId:c,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId}}}catch(r){const e=r,n=`Failed to create and register agent: ${e.message}`;return this.logger.error(n),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,i=r?.delayMs??2e3,o=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};o&&o({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(o&&o({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")}o&&o({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,i,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),o&&o({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,i){this.logger.info("Registering agent");const o={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,o,i)}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 i=(new u$1).setScheduledTransaction(e).setPayerAccountId(n?f.fromString(n):this.client.operatorAccountId);if(t&&i.setScheduleMemo(t),r){const e=addSeconds(new Date,r),t=s$a.fromDate(e);i.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const o=await i.execute(this.client),a=await o.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=o.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${s}`),{scheduleId:s,transactionId:c}}async sendTransactionOperation(e,t,r,n,i){const o=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:i?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,o.requiresFee)}async sendTransaction(e,t,r,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:i,transactionId:o}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:i,transactionId:o,receipt:await this.sendTransactionOperation(e,i,r,n?.submitKey,{memo:n?.operationMemo})}}async createMCPServer(e,t=60,r,n){this.keyType||await this.initializeOperator();const i=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||i.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,InboundTopicType.PUBLIC,void 0,i.pfpBuffer,i.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),n&&n({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(i.name,i.mcpServer,{alias:i.alias,bio:i.bio,socials:i.socials||[],inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileImage:a.pfpTopicId?`hcs://1/${a.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");a.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${a.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(o,a.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),n&&n({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async _createEntityTopics(e,t,r,n,i,o,a,s){let{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e});c=await this.createTopic(t,!0,!0),this.logger.info(`Created new outbound topic ID: ${c}`),s&&s({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(u?this.logger.info(`Using existing inbound topic ID: ${u}`):(u=await this.createInboundTopic(r,n,e,n===InboundTopicType.FEE_BASED?i:void 0),this.logger.info(`Created new inbound topic ID: ${u}`),s&&s({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:u,state:{currentStage:"topics",completedPercentage:40}}})),!l&&o&&o.length>0&&a){this.logger.info("Inscribing new profile picture"),s&&s({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:u,state:{currentStage:"pfp",completedPercentage:50}}});l=(await this.inscribePfp(o,a)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${l}`),s&&s({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,state:{currentStage:"pfp",completedPercentage:55}}})}else l&&this.logger.info(`Using existing profile picture with topic ID: ${l}`);return{inboundTopicId:u,outboundTopicId:c,pfpTopicId:l,profileTopicId:d}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),n=t?.progressCallback,i=t?.baseUrl||this.guardedRegistryBaseUrl;let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};o.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:o}});let a,s=r.existingAccount;if(o.inboundTopicId&&o.outboundTopicId&&o.profileTopicId){if(s=s||r.existingAccount,!s)throw new Error("Cannot resume registration without account information");const e=detectKeyTypeFromString(s.privateKey),t=("ed25519"===e.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:i}),this.logger.info("Resuming registration with existing state",{inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId})}else{if(!s)if(o.createdResources&&o.createdResources.some((e=>e.startsWith("account:")))){const e=o.createdResources.find((e=>e.startsWith("account:"))),n=e?.split(":")[1];n&&r.existingAccount?(s=r.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`))}else s=await this.createAccount(t?.initialBalance),o.createdResources=o.createdResources||[],o.createdResources.push(`account:${s.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:o,account:s}});const c=detectKeyTypeFromString(s.privateKey);e.setExistingAccount(s.accountId,s.privateKey);const u=("ed25519"===c.detectedType?g.fromStringED25519(s.privateKey):g.fromStringECDSA(s.privateKey)).publicKey.toString();a=new HCS10Client({network:r.network,operatorId:s.accountId,operatorPrivateKey:s.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:i}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:o}});let l=o.outboundTopicId,d=o.inboundTopicId,p=o.pfpTopicId,h=o.profileTopicId;if(!l||!d||!h){p&&e.setExistingProfilePicture(p);const t=await a.createMCPServer(e,60,o,(e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...o,...e.details?.state}}})}));l=t.outboundTopicId,d=t.inboundTopicId,p=t.pfpTopicId,h=t.profileTopicId,o.outboundTopicId=l,o.inboundTopicId=d,o.pfpTopicId=p,o.profileTopicId=h,o.createdResources||(o.createdResources=[]),p&&!o.createdResources.includes(`pfp:${p}`)&&o.createdResources.push(`pfp:${p}`),o.createdResources.includes(`inbound:${d}`)||o.createdResources.push(`inbound:${d}`),o.createdResources.includes(`outbound:${l}`)||o.createdResources.push(`outbound:${l}`),o.createdResources.includes(`profile:${h}`)||o.createdResources.push(`profile:${h}`)}o.currentStage="profile",o.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:o,outboundTopicId:l,inboundTopicId:d,pfpTopicId:p,profileTopicId:h}})}const c=`${o.inboundTopicId}@${s.accountId}`;if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(s.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:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:e.details?.state||o}})},existingState:o});if(!e.success)return{...e,state:o};o=e.state||o}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:o.outboundTopicId,inboundTopicId:o.inboundTopicId,pfpTopicId:o.pfpTopicId,profileTopicId:o.profileTopicId,operatorId:c,state:o}}),{success:!0,state:o,metadata:{accountId:s.accountId,privateKey:s.privateKey,operatorId:c,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId}}}catch(r){const e=r,n=`Failed to create and register MCP server: ${e.message}`;return this.logger.error(n),{error:e.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:e.message}}}}}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,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=Logger$3.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(r){this.logger.warn(`Failed to initialize HCS11Client: ${r}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,n,i){this.logger.info("Sending message");const o={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(o);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:i?.progressCallback,waitMaxAttempts:i?.waitMaxAttempts,waitIntervalMs:i?.waitIntervalMs});if(!n?.topic_id)throw new Error("Failed to inscribe large message content");o.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,o,n,a.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",i=60){this.logger.info("Handling connection request");const o=this.hwc.getAccountInfo().accountId;if(!o)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(o);if(!s)throw new Error("Failed to retrieve public key");const u=new s$9([s,a],1),l=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:i,inboundTopicId:e,connectionId:r}),d=(new c).setTopicMemo(l).setAutoRenewAccountId(f.fromString(o)).setAdminKey(u).setSubmitKey(u);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const m=h.topicId.toString(),g=`${e}@${o}`,y=await this.confirmConnection(e,m,t,r,g,n),b=await this.retrieveCommunicationTopics(o),v=await this.retrieveCommunicationTopics(t),w=`${v.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:b.outboundTopic,requestorOutboundTopicId:v.outboundTopic,connectionRequestId:r,confirmedRequestId:y,connectionTopicId:m,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:m,confirmedConnectionSequenceNumber:y,operatorId:g}}async confirmConnection(e,t,r,n,i,o){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:i,connection_id:n,m:o},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 i;if(i=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();i.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");n.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:i});const{inboundTopicId:o,outboundTopicId:a,state:s}=await this.createCommunicationTopics(t,n);let c,u,l;if(i=s,r||(e.setInboundTopicId(o),e.setOutboundTopicId(a)),r){const t=e.build();c=t.existingPfpTopicId||i.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName||"pfp.png"}else{const t=e.build();c=i.pfpTopicId,u=t.pfpBuffer,l=t.pfpFileName}!c&&u&&l?c=await this.handleProfilePictureCreation(u,l,i,n):c&&(n.preparing(`Using existing profile picture: ${c}`,50,{state:i}),i.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,i,o,a,t,n),i.currentStage="complete",i.completedPercentage=100,n.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:i.profileTopicId,inboundTopicId:o,outboundTopicId:a,pfpTopicId:c,state:i});let d="";i.outboundTopicId&&(d=i.outboundTopicId);let p="";i.inboundTopicId&&(p=i.inboundTopicId);let h="";i.pfpTopicId&&(h=i.pfpTopicId);let f="";return i.profileTopicId&&(f=i.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:f,success:!0,state:i}}catch(i){return n.failed("Error during profile creation",{error:i.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:i.message,state:{currentStage:"init",completedPercentage:0,error:i.message}}}}async handleProfilePictureCreation(e,t,r,n){r.currentStage="pfp",n.preparing("Creating profile picture",30,{state:r});const i=n.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),o=await this.inscribePfp(e,t,{progressCallback:e=>i.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const a=o.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,i,o,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:i,outboundTopicId:o,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:i,outboundTopicId:o})}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,i=this.initializeRegistrationState(n,r?.existingState),o=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});o.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:i};if(o.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:i};this.logger.info("Successfully processed registration transaction")}o.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(i,n),o.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:i,confirmed:u}),{...a,confirmed:u,state:i}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,i=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(o.agentMetadata=r.metadata,i.preparing("Starting agent creation process",0,{state:o}),"complete"!==o.currentStage||!o.inboundTopicId||!o.outboundTopicId||!o.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);i.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},existingState:o,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");o=t.state,o.agentMetadata=r.metadata}i.preparing(`Agent creation status: ${o.currentStage}, ${o.completedPercentage}%`,30,{state:o});const{accountId:a}=this.getAccountAndSigner();if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);i.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:o});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");o=e.state,o.profileTopicId&&await(this.hcs11Client?.updateAccountMemoWithProfile(a,o.profileTopicId))}return i.completed("Agent creation and registration complete",{state:o}),{success:!0,state:o,metadata:{accountId:a,operatorId:`${o.inboundTopicId}@${a}`,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId,privateKey:null,...o.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,i=[],o={},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 p=c;if(!p&&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?p=t.pfpTopicId:d.failed("Failed to inscribe profile picture, continuing without PFP")}else c?d.preparing(`Using existing profile picture: ${c}`,30):d.preparing("No profile picture provided",30);if(!this.hcs11Client)return d.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"});d.preparing("Building agent profile",65);const f=o.socials?Object.entries(o.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:e,handle:t}))):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,i,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:f,properties:{version:o.version||"1.0.0",creator:o.creator||"Unknown",supported_languages:o.supported_languages||["en"],permissions:o.permissions||[],model_details:o.model_details,training:o.training,capabilities_description:o.capabilities_description,...o},inboundTopicId:r,outboundTopicId:n,creator:o.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:p,success:!0,transactionId:y.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:n,signer:i}=this.getAccountAndSigner(),o=(new c).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(o.setAdminKey(a),o.setAutoRenewAccountId(n)),r&&a&&o.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(o,!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 i;this.logger.debug(`Submitting payload to topic ${e}`),i="string"==typeof t?t:JSON.stringify(t);const o=(new u).setTopicId(e).setMessage(i),a=this.getHcs10TransactionMemo(t);let s;if(a&&o.setTransactionMemo(a),n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),o.setMaxTransactionFee(new e$7(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();o.freezeWithSigner(e);const t=await o.sign(r);s=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else s=await this.hwc.executeTransactionWithErrorHandling(o,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}async inscribeFile(e,t,r){const{accountId:n,signer:i}=this.getAccountAndSigner(),o=mimeTypesExports.lookup(t)||"application/octet-stream",a=await InscriptionSDK.createWithAuth({type:"client",accountId:n,signer:i,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:o},i,{...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,i=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return i.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};i.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const o=e=>{i.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:o});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 i.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 i=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:e?.ttl,accountId:n}),o=await this.createTopic(i,!0,!0);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create outbound topic");r.outboundTopicId=o.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 i=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{ttl:e?.ttl,accountId:n}),o=await this.createTopic(i,!0,!1);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create inbound topic");r.inboundTopicId=o.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,silent:e?.silent};if(this.logger=new Logger$3(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,i]=await Promise.all([this.baseClient.getMessages(t.outboundTopic),this.baseClient.getMessages(t.inboundTopic)]);this.processOutboundMessages(n.messages||[],e),this.processInboundMessages(i.messages||[]);const o=Array.from(this.connections.values()).filter((e=>"pending"===e.status||e.isPending)).length;return this.logger.debug(`Processed ${n.messages?.length||0} outbound and ${i.messages?.length||0} inbound messages. Found ${o} 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,i]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 i){const n=e.connectionRequestId;if(!n)continue;const i=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(i?.connection_topic_id){r=!0;const t=i.connection_topic_id;let o=e.uniqueRequestKey;const a={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.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),o&&this.connections.delete(o),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 i of r){if(this.logger.debug(`Processing pending connection: ${i.connectionTopicId}`),!i.targetAccountId){this.logger.debug(`Skipping connection ${i.connectionTopicId} - no targetAccountId`);continue}let e=i.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(i.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${i.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(i.connectionTopicId,{...i,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${i.connectionTopicId} with inbound topic ID: ${e}`)}catch(n){this.logger.debug(`Error fetching profile for ${i.targetAccountId}: ${n}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=i.connectionRequestId||i.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 ${i.targetAccountId} on their inbound topic`),this.connections.set(i.connectionTopicId,{...i,connectionTopicId:e,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||i.created),lastActivity:new Date(n.created||i.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 ${i.targetAccountId}: ${n}`)}else this.logger.debug(`Skipping connection ${i.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 o of r){const e=o.connection_request_id,r=o.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(r),i=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:o.outbound_topic_id||"",targetAccountId:n,targetTopicId:i,operatorId:r,sequenceNumber:o.sequence_number,created:o.created||new Date,memo:o.m,status:"pending"};if(this.pendingRequests.set(s,a),!this.connections.has(s)){const t={connectionTopicId:s,targetAccountId:n,targetInboundTopicId:i,status:"pending",isPending:!0,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,uniqueRequestKey:s,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.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 o of n){const e=o.connection_request_id,t=o.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(o.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const n=`req-${e}:${o.operator_id}`,i=this.pendingRequests.get(n);if(i&&(i.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:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:n,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:n,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}const i=e.filter((e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id));for(const o of i){const e=o.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=o.connection_request_id&&o.operator_id?`req-${o.connection_request_id}:${o.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:o.created||new Date,closedReason:o.reason,closeMethod:o.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:o.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||"",i=this.baseClient.extractAccountFromOperatorId(t),o=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out request from account: ${i}`);continue}const a=`inb-${e}:${t}`;r.some((t=>t.connection_id===e))?this.logger.debug(`Skipping request from ${i} as it has already been confirmed`):this.connections.has(a)||this.connections.set(a,{connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:n.created||new Date,inboundRequestId:e,uniqueRequestKey:a,originTopicId:o,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||"",i=n.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const o=`inb-${e}:${i}`;if(this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:o,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:o,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)}getConnectionByIdentifier(e){return Array.from(this.connections.values()).find((t=>t.uniqueRequestKey===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,i]of this.connections.entries())i.originTopicId===e&&i.inboundRequestId===t&&(this.connections.set(n,{...i,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),i.originTopicId===e&&i.connectionRequestId===t&&(this.connections.set(n,{...i,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?{...t}:void 0),i=[];for(const e of n)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||i.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),i.push(e)}return i}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter((e=>e.operator_id&&e.operator_id.includes(t)&&e.created));if(0===r.length)return;return r.sort(((e,t)=>t.created.getTime()-e.created.getTime())),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}const HCS20_CONSTANTS={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},HederaAccountIdSchema=stringType().regex(HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),NumberStringSchema=stringType().regex(/^\d+$/,"Must be a valid number").max(HCS20_CONSTANTS.MAX_NUMBER_LENGTH,`Max ${HCS20_CONSTANTS.MAX_NUMBER_LENGTH} digits`),TickSchema=stringType().min(1,"Tick cannot be empty").transform((e=>e.toLowerCase().trim())),HCS20BaseMessageSchema=objectType({p:literalType("hcs-20"),m:stringType().optional()}),HCS20DeployMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("deploy"),name:stringType().min(1).max(HCS20_CONSTANTS.MAX_NAME_LENGTH),tick:TickSchema,max:NumberStringSchema,lim:NumberStringSchema.optional(),metadata:stringType().max(HCS20_CONSTANTS.MAX_METADATA_LENGTH).optional()}),HCS20MintMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("mint"),tick:TickSchema,amt:NumberStringSchema,to:HederaAccountIdSchema}),HCS20BurnMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("burn"),tick:TickSchema,amt:NumberStringSchema,from:HederaAccountIdSchema}),HCS20TransferMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("transfer"),tick:TickSchema,amt:NumberStringSchema,from:HederaAccountIdSchema,to:HederaAccountIdSchema}),HCS20RegisterMessageSchema=HCS20BaseMessageSchema.extend({op:literalType("register"),name:stringType().min(1).max(HCS20_CONSTANTS.MAX_NAME_LENGTH),metadata:stringType().max(HCS20_CONSTANTS.MAX_METADATA_LENGTH).optional(),private:booleanType(),t_id:HederaAccountIdSchema}),HCS20MessageSchema=discriminatedUnionType("op",[HCS20DeployMessageSchema,HCS20MintMessageSchema,HCS20BurnMessageSchema,HCS20TransferMessageSchema,HCS20RegisterMessageSchema]);class HCS20Error extends Error{constructor(e){super(e),this.name="HCS20Error"}}class PointsDeploymentError extends HCS20Error{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class PointsMintError extends HCS20Error{constructor(e,t,r,n){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=n,this.name="PointsMintError"}}class PointsTransferError extends HCS20Error{constructor(e,t,r,n,i,o){super(e),this.tick=t,this.from=r,this.to=n,this.amount=i,this.availableBalance=o,this.name="PointsTransferError"}}class PointsBurnError extends HCS20Error{constructor(e,t,r,n,i){super(e),this.tick=t,this.from=r,this.amount=n,this.availableBalance=i,this.name="PointsBurnError"}}class PointsValidationError extends HCS20Error{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class PointsNotFoundError extends HCS20Error{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}}class TopicRegistrationError extends HCS20Error{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class InsufficientBalanceError extends HCS20Error{constructor(e,t,r,n){super(`Insufficient balance for ${t}: required ${r}, available ${n}`),this.accountId=e,this.tick=t,this.required=r,this.available=n,this.name="InsufficientBalanceError"}}class SupplyLimitExceededError extends HCS20Error{constructor(e,t,r,n){super(`Supply limit exceeded for ${e}: max ${r}, current ${n}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=n,this.name="SupplyLimitExceededError"}}class MintLimitExceededError extends HCS20Error{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}}class InvalidMessageFormatError extends HCS20Error{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}}class InvalidAccountFormatError extends HCS20Error{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class InvalidTickFormatError extends HCS20Error{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}}class InvalidNumberFormatError extends HCS20Error{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}}class HCS20BaseClient{constructor(e){this.logger=e.logger||new Logger$3({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new HederaMirrorNode(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID}validateMessage(e){try{return HCS20MessageSchema.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map((e=>`${e.path.join(".")}: ${e.message}`))}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX.test(e))throw new InvalidAccountFormatError(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!HCS20_CONSTANTS.HEDERA_ACCOUNT_REGEX.test(e))throw new InvalidAccountFormatError(e);return e}return e.toString()}}class BrowserHCS20Client extends HCS20BaseClient{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let n;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const r=await this.mirrorNode.getPublicKey(t),i=(new c).setTopicMemo(e.topicMemo||`HCS-20: ${e.name}`).setSubmitKey(r).setAdminKey(r).setAutoRenewAccountId(f.fromString(t)),o=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(o?.error)throw new Error(o.error);const a=o?.result;if(!a?.topicId)throw new Error("Failed to create topic: topicId is null");n=a.topicId.toString(),this.logger.info(`Created private topic: ${n}`)}else n=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:n});const i={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(i);if(!o.valid)throw new PointsValidationError("Invalid deploy message",o.errors);const a=await this.submitPayload(n,i,e.usePrivateTopic),s=a.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:n,deployTxId:s}),await new Promise((e=>setTimeout(e,2e3))),r?.({stage:"complete",percentage:100,topicId:n,deployTxId:s}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:n,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(n){throw r?.({stage:"complete",percentage:100,error:n instanceof Error?n.message:"Unknown error"}),n}}async mintPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,mintTxId:o}),{id:o,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,transferTxId:o}),{id:o,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){this.getOperatorId();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},n=e.topicId||this.publicTopicId,i=await this.submitPayload(n,r,!1),o=i.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,burnTxId:o}),{id:o,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},n=this.validateMessage(r);if(!n.valid)throw new PointsValidationError("Invalid register message",n.errors);t?.({stage:"submitting",percentage:50});const i=await this.submitPayload(this.registryTopicId,r,!1),o=i.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:o}),await new Promise((e=>setTimeout(e,2e3))),t?.({stage:"complete",percentage:100,registerTxId:o})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new TopicRegistrationError(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(m$1.fromString(e)).setMessage(n);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount)));const o=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(o?.error)throw this.logger.error(`Failed to submit payload: ${o.error}`),new Error(`Failed to submit payload: ${o.error}`);if(!o?.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"),o.result}}class HCS20Client extends HCS20BaseClient{constructor(e){super(e),this.initialized=!1,this.operatorId="string"==typeof e.operatorId?f.fromString(e.operatorId):e.operatorId,this.operatorKeyString=e.operatorKey,this.client="mainnet"===this.network?i$2.forMainnet():i$2.forTestnet();try{const{privateKey:t,detectedType:r}=detectKeyTypeFromString(e.operatorKey);this.operatorKey=t,this.keyType=r,this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0}catch(t){this.logger.debug("Failed to detect key type from string, will initialize later")}}async initializeOperator(){if(!this.initialized)try{const e=await this.mirrorNode.requestAccount(this.operatorId.toString()),t=e?.key?._type;t?.includes("ECDSA")?this.keyType="ecdsa":(t?.includes("ED25519"),this.keyType="ed25519"),this.operatorKey="ecdsa"===this.keyType?g.fromStringECDSA(this.operatorKeyString):g.fromStringED25519(this.operatorKeyString),this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0,this.logger.debug(`Initialized operator with key type: ${this.keyType}`)}catch(e){this.logger.warn("Failed to query mirror node for key type, using ED25519"),this.keyType="ed25519",this.operatorKey=g.fromStringED25519(this.operatorKeyString),this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0}}async ensureInitialized(){this.initialized||await this.initializeOperator()}async submitPayload(e,t,r){const n="string"==typeof t?t:JSON.stringify(t),i=(new u).setTopicId(m$1.fromString(e)).setMessage(n);let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const a=await o.getReceipt(this.client);if(!a||a.status!==e$6.Success)throw new Error("Failed to submit message to topic");return{receipt:a,transactionId:o.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new c).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==e$6.Success||!r.topicId)throw new Error("Failed to create public topic");const n=r.topicId.toString();return this.logger.info(`Created public topic: ${n}`),this.publicTopicId=n,n}async createRegistryTopic(e){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const t=await(new c).setTopicMemo(e||"HCS-20 Registry").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==e$6.Success||!r.topicId)throw new Error("Failed to create registry topic");const n=r.topicId.toString();return this.logger.info(`Created registry topic: ${n}`),this.registryTopicId=n,n}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;if(t?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const t=await(new c).setTopicMemo(e.topicMemo||`HCS-20: ${e.name}`).setSubmitKey(this.operatorKey.publicKey).setAdminKey(this.operatorKey.publicKey).execute(this.client),n=await t.getReceipt(this.client);if(n.status!==e$6.Success||!n.topicId)throw new PointsDeploymentError("Failed to create topic",e.tick);r=n.topicId.toString(),this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},i=this.validateMessage(n);if(!i.valid)throw new PointsValidationError("Invalid deploy message",i.errors);const{transactionId:o}=await this.submitPayload(r,n);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:o}),await this.waitForMirrorNodeConfirmation(r,o),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:o});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId.toString(),currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const n={p:"hcs-20",op:"mint",tick:r,amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,{transactionId:o}=await this.submitPayload(i,n);t?.({stage:"confirming",percentage:80,mintTxId:o}),await this.waitForMirrorNodeConfirmation(i,o),t?.({stage:"complete",percentage:100,mintTxId:o});return{id:o,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),n=this.accountToString(e.from),i=this.accountToString(e.to);if(n!==this.operatorId.toString())throw new PointsTransferError("For public topics, transaction payer must match sender",e.tick,n,i,e.amount);t?.({stage:"submitting",percentage:50});const o={p:"hcs-20",op:"transfer",tick:r,amt:e.amount,from:n,to:i,m:e.memo},a=e.topicId||this.publicTopicId,{transactionId:s}=await this.submitPayload(a,o);t?.({stage:"confirming",percentage:80,transferTxId:s}),await this.waitForMirrorNodeConfirmation(a,s),t?.({stage:"complete",percentage:100,transferTxId:s});return{id:s,operation:"transfer",tick:r,amount:e.amount,from:n,to:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:a,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),n=this.accountToString(e.from);if(n!==this.operatorId.toString())throw new PointsBurnError("For public topics, transaction payer must match burner",e.tick,n,e.amount);t?.({stage:"submitting",percentage:50});const i={p:"hcs-20",op:"burn",tick:r,amt:e.amount,from:n,m:e.memo},o=e.topicId||this.publicTopicId,{transactionId:a}=await this.submitPayload(o,i);t?.({stage:"confirming",percentage:80,burnTxId:a}),await this.waitForMirrorNodeConfirmation(o,a),t?.({stage:"complete",percentage:100,burnTxId:a});return{id:a,operation:"burn",tick:r,amount:e.amount,from:n,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},n=this.validateMessage(r);if(!n.valid)throw new PointsValidationError("Invalid register message",n.errors);t?.({stage:"submitting",percentage:50});const{transactionId:i}=await this.submitPayload(this.registryTopicId,r);t?.({stage:"confirming",percentage:80,registerTxId:i}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,i),t?.({stage:"complete",percentage:100,registerTxId:i}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let i=0;i<r;i++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some((e=>e.consensus_timestamp)))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(n){this.logger.debug(`Mirror node check attempt ${i+1} failed:`,n)}await sleep(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}}class HCS20PointsIndexer{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new Logger$3({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new HederaMirrorNode(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),n=this.state.balances.get(r);if(!n)return"0";const i=n.get(t);return i?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=e?.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID,r=e?.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID,n=e?.pollInterval||3e4;await this.indexTopics(t,r,e?.privateTopics);const i=async()=>{if(this.isProcessing){try{await this.indexTopics(t,r,e?.privateTopics)}catch(o){this.logger.error("Polling error:",o)}this.isProcessing&&setTimeout(i,n)}};setTimeout(i,n)}async indexOnce(e){const t=e?.publicTopicId||HCS20_CONSTANTS.PUBLIC_TOPIC_ID,r=e?.registryTopicId||HCS20_CONSTANTS.REGISTRY_TOPIC_ID;await this.indexTopics(t,r,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),await this.indexTopic(e,!1);const n=[...await this.getRegisteredTopics(t),...r||[]];for(const i of n)await this.indexTopic(i,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{const n=await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"});for(const e of n)try{const r=e.data||e;r&&"object"==typeof r&&"hcs-20"===r.p&&"register"===r.op&&r.t_id&&t.push(r.t_id)}catch(r){continue}}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const n=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${n||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:n?n+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let o=n||0;for(const a of i)try{const r=a;if(!r.p||"hcs-20"!==r.p)continue;const n=r,i=r.sequence_number||0;this.logger.debug(`Found HCS-20 message: op=${n.op}, sequence=${i}`),i>o&&(o=i);const s={consensus_timestamp:r.consensus_timestamp||"",sequence_number:i,payer_account_id:r.payer_account_id||"",transaction_id:r.transaction_id||""};this.processMessage(n,s,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=r.consensus_timestamp||""}catch(r){this.logger.debug(`Failed to process message: ${r}`);continue}o>(n||0)&&this.lastIndexedSequence.set(e,o)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,n){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,n);break;case"mint":this.processMintMessage(e,t,r,n);break;case"transfer":this.processTransferMessage(e,t,r,n);break;case"burn":this.processBurnMessage(e,t,r,n)}}processDeployMessage(e,t,r,n){const i=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(i))return;const o={name:e.name,tick:i,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:n};this.state.deployedPoints.set(i,o),this.logger.info(`Deployed points: ${i}`)}processMintMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(i);if(!o)return;const a=BigInt(e.amt),s=BigInt(o.currentSupply);if(s+a>BigInt(o.maxSupply))return;if(o.limitPerMint&&a>BigInt(o.limitPerMint))return;o.currentSupply=(s+a).toString();let c=this.state.balances.get(i);c||(c=new Map,this.state.balances.set(i,c));const u=c.get(e.to),l=u?(BigInt(u.balance)+a).toString():e.amt;c.set(e.to,{tick:i,accountId:e.to,balance:l,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:i,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.balances.get(i);if(!o)return;if(!n&&t.payer_account_id!==e.from)return;const a=o.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const s=BigInt(e.amt);a.balance=(BigInt(a.balance)-s).toString(),a.lastUpdated=t.consensus_timestamp;const c=o.get(e.to);c?(c.balance=(BigInt(c.balance)+s).toString(),c.lastUpdated=t.consensus_timestamp):o.set(e.to,{tick:i,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:i,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,n){const i=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(i),a=this.state.balances.get(i);if(!o||!a)return;if(!n&&t.payer_account_id!==e.from)return;const s=a.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);s.balance=(BigInt(s.balance)-c).toString(),s.lastUpdated=t.consensus_timestamp,o.currentSupply=(BigInt(o.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:i,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}}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,i=[]){return new FeeConfigBuilder({network:r,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,i)}static async forToken(e,t,r,n,i,o=[],a){const s=new FeeConfigBuilder({network:n,logger:i,defaultCollectorAccountId:r});return await s.addTokenFee(e,t,r,a,o),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,i=[]){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 o=n;if(void 0===o)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(o=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${o}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),o=0)}catch(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),o=0}return this.customFees.push({feeAmount:{amount:e*10**o,decimals:o},feeCollectorAccountId:r||"",feeTokenId:t,exemptAccounts:[...i],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$1="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==global$1?global$1:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$1(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var dist$1={},hasRequiredDist$1;function requireDist$1(){return hasRequiredDist$1||(hasRequiredDist$1=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 o(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=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],u[l++]=t>>16&255,u[l++]=t>>8&255,u[l++]=255&t;2===s&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,u[l++]=255&t);1===s&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[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,i=r%3,o=[],a=16383,s=0,c=r-i;s<c;s+=a)o.push(u(e,s,s+a>c?c:s+a));1===i?(t=e[r-1],o.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return o.join("")}},n=[],i=[],o="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],i[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 i,o,a=[],s=t;s<r;s+=3)i=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[(o=i)>>18&63]+n[o>>12&63]+n[o>>6&63]+n[63&o]);return a.join("")}i["-".charCodeAt(0)]=62,i["_".charCodeAt(0)]=63;var l={
|
|
171
171
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
172
172
|
read:function(e,t,r,n,i){var o,a,s=8*i-n-1,c=(1<<s)-1,u=c>>1,l=-7,d=r?i-1:0,p=r?-1:1,h=e[t+d];for(d+=p,o=h&(1<<-l)-1,h>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=p,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=p,l-=8);if(0===o)o=1-u;else{if(o===c)return a?NaN:1/0*(h?-1:1);a+=Math.pow(2,n),o-=u}return(h?-1:1)*a*Math.pow(2,o-n)},write:function(e,t,r,n,i,o){var a,s,c,u=8*o-i-1,l=(1<<u)-1,d=l>>1,p=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:o-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?p/c:p*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,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+h]=255&s,h+=f,s/=256,i-=8);for(a=a<<i|s,u+=i;u>0;e[r+h]=255&a,h+=f,a/=256,u-=8);e[r+h-f]|=128*m}};
|
|
173
173
|
/*!
|