@hashgraphonline/standards-sdk 0.0.59 → 0.0.60

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/es/hcs-10/agent-builder.d.ts +2 -0
  2. package/dist/es/hcs-10/agent-builder.d.ts.map +1 -1
  3. package/dist/es/standards-sdk.es10.js +1 -1
  4. package/dist/es/standards-sdk.es13.js +1 -1
  5. package/dist/es/standards-sdk.es13.js.map +1 -1
  6. package/dist/es/standards-sdk.es14.js +5 -21
  7. package/dist/es/standards-sdk.es14.js.map +1 -1
  8. package/dist/es/standards-sdk.es17.js +1 -1
  9. package/dist/es/standards-sdk.es18.js +2 -2
  10. package/dist/es/standards-sdk.es22.js +36 -6627
  11. package/dist/es/standards-sdk.es22.js.map +1 -1
  12. package/dist/es/standards-sdk.es23.js +48 -36
  13. package/dist/es/standards-sdk.es23.js.map +1 -1
  14. package/dist/es/standards-sdk.es24.js +6600 -21
  15. package/dist/es/standards-sdk.es24.js.map +1 -1
  16. package/dist/es/standards-sdk.es26.js +5 -1041
  17. package/dist/es/standards-sdk.es26.js.map +1 -1
  18. package/dist/es/standards-sdk.es27.js +1041 -5
  19. package/dist/es/standards-sdk.es27.js.map +1 -1
  20. package/dist/es/standards-sdk.es36.js +5 -5
  21. package/dist/es/standards-sdk.es38.js +3 -3
  22. package/dist/es/standards-sdk.es4.js +1 -1
  23. package/dist/es/standards-sdk.es48.js +1 -1
  24. package/dist/es/standards-sdk.es49.js +3 -3
  25. package/dist/es/standards-sdk.es5.js +1 -1
  26. package/dist/es/standards-sdk.es52.js +3 -31
  27. package/dist/es/standards-sdk.es52.js.map +1 -1
  28. package/dist/es/standards-sdk.es53.js +25 -56
  29. package/dist/es/standards-sdk.es53.js.map +1 -1
  30. package/dist/es/standards-sdk.es54.js +58 -45
  31. package/dist/es/standards-sdk.es54.js.map +1 -1
  32. package/dist/es/standards-sdk.es55.js +48 -8
  33. package/dist/es/standards-sdk.es55.js.map +1 -1
  34. package/dist/es/standards-sdk.es56.js +8 -63
  35. package/dist/es/standards-sdk.es56.js.map +1 -1
  36. package/dist/es/standards-sdk.es57.js +64 -5
  37. package/dist/es/standards-sdk.es57.js.map +1 -1
  38. package/dist/es/standards-sdk.es58.js +6 -15
  39. package/dist/es/standards-sdk.es58.js.map +1 -1
  40. package/dist/es/standards-sdk.es59.js +15 -7
  41. package/dist/es/standards-sdk.es59.js.map +1 -1
  42. package/dist/es/standards-sdk.es60.js +6 -44
  43. package/dist/es/standards-sdk.es60.js.map +1 -1
  44. package/dist/es/standards-sdk.es61.js +45 -2
  45. package/dist/es/standards-sdk.es61.js.map +1 -1
  46. package/dist/es/standards-sdk.es62.js +2 -136
  47. package/dist/es/standards-sdk.es62.js.map +1 -1
  48. package/dist/es/standards-sdk.es63.js +123 -159
  49. package/dist/es/standards-sdk.es63.js.map +1 -1
  50. package/dist/es/standards-sdk.es64.js +172 -4
  51. package/dist/es/standards-sdk.es64.js.map +1 -1
  52. package/dist/es/standards-sdk.es7.js +5 -1
  53. package/dist/es/standards-sdk.es7.js.map +1 -1
  54. package/dist/es/standards-sdk.es74.js +3 -3
  55. package/dist/es/standards-sdk.es8.js +2 -2
  56. package/dist/es/standards-sdk.es82.js +1 -1
  57. package/dist/es/standards-sdk.es83.js +1 -1
  58. package/dist/es/utils/logger.d.ts.map +1 -1
  59. package/dist/umd/hcs-10/agent-builder.d.ts +2 -0
  60. package/dist/umd/hcs-10/agent-builder.d.ts.map +1 -1
  61. package/dist/umd/standards-sdk.umd.js +2 -2
  62. package/dist/umd/standards-sdk.umd.js.map +1 -1
  63. package/dist/umd/utils/logger.d.ts.map +1 -1
  64. package/package.json +4 -2
@@ -1,4 +1,4 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp2=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp2=(e,t,r)=>t in e?__defProp2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField2=(e,t,r)=>__defNormalProp2(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,n)=>({set _(n){__privateSet(e,t,n,r)},get _(){return __privateGet(e,t,n)}}),_a2,_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const n=t[r];if("string"!=typeof n&&!Array.isArray(n))for(const t in n)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(n,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$e={exports:{}},quickFormatUnescaped,hasRequiredQuickFormatUnescaped,hasRequiredBrowser$d;function requireQuickFormatUnescaped(){if(hasRequiredQuickFormatUnescaped)return quickFormatUnescaped;function e(e){try{return JSON.stringify(e)}catch(t){return'"[Circular]"'}}return hasRequiredQuickFormatUnescaped=1,quickFormatUnescaped=function(t,r,n){var o=n&&n.stringify||e;if("object"==typeof t&&null!==t){var i=r.length+1;if(1===i)return t;var a=new Array(i);a[0]=o(t);for(var s=1;s<i;s++)a[s]=o(r[s]);return a.join(" ")}if("string"!=typeof t)return t;var c=r.length;if(0===c)return t;for(var u="",l=0,d=-1,p=t&&t.length||0,h=0;h<p;){if(37===t.charCodeAt(h)&&h+1<p){switch(d=d>-1?d:0,t.charCodeAt(h+1)){case 100:case 102:if(l>=c)break;if(null==r[l])break;d<h&&(u+=t.slice(d,h)),u+=Number(r[l]),d=h+2,h++;break;case 105:if(l>=c)break;if(null==r[l])break;d<h&&(u+=t.slice(d,h)),u+=Math.floor(Number(r[l])),d=h+2,h++;break;case 79:case 111:case 106:if(l>=c)break;if(void 0===r[l])break;d<h&&(u+=t.slice(d,h));var f=typeof r[l];if("string"===f){u+="'"+r[l]+"'",d=h+2,h++;break}if("function"===f){u+=r[l].name||"<anonymous>",d=h+2,h++;break}u+=o(r[l]),d=h+2,h++;break;case 115:if(l>=c)break;d<h&&(u+=t.slice(d,h)),u+=String(r[l]),d=h+2,h++;break;case 37:d<h&&(u+=t.slice(d,h)),u+="%",d=h+2,h++,l--}++l}++h}if(-1===d)return t;d<p&&(u+=t.slice(d));return u}}function requireBrowser$d(){if(hasRequiredBrowser$d)return browser$e.exports;hasRequiredBrowser$d=1;const e=requireQuickFormatUnescaped();browser$e.exports=c;const t=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},r={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:f,res:f,err:p,errWithCause:p};function n(e,t){return"silent"===e?1/0:t.levels.values[e]}const o=Symbol("pino.logFuncs"),i=Symbol("pino.hierarchy"),a={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function s(e,t){const r={logger:t,parent:e[i]};t[i]=r}function c(e){(e=e||{}).browser=e.browser||{};const r=e.browser.transmit;if(r&&"function"!=typeof r.send)throw Error("pino: transmit option must have a send function");const i=e.browser.write||t;e.browser.write&&(e.browser.asObject=!0);const p=e.serializers||{},f=function(e,t){if(Array.isArray(e))return e.filter((function(e){return"!stdSerializers.err"!==e}));return!0===e&&Object.keys(t)}(e.browser.serialize,p);let m=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(m=!1);const g=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(g);"function"==typeof i&&b.forEach((function(e){i[e]=i})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const v=e.level||"info",w=Object.create(i);w.log||(w.log=y),function(e,r,n){const i={};r.forEach((e=>{i[e]=n[e]?n[e]:t[e]||t[a[e]||"log"]||y})),e[o]=i}(w,b,i),s({},w),Object.defineProperty(w,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,u(this,k,w,"error"),u(this,k,w,"fatal"),u(this,k,w,"warn"),u(this,k,w,"info"),u(this,k,w,"debug"),u(this,k,w,"trace"),g.forEach((e=>{u(this,k,w,e)}))}});const k={transmit:r,serialize:f,asObject:e.browser.asObject,formatters:e.browser.formatters,levels:b,timestamp:h(e),messageKey:e.messageKey||"msg",onChild:e.onChild||y};function _(t,n,o){if(!n)throw new Error("missing bindings for child Pino");o=o||{},f&&n.serializers&&(o.serializers=n.serializers);const i=o.serializers;if(f&&i){var a=Object.assign({},p,i),c=!0===e.browser.serialize?Object.keys(a):f;delete n.serializers,l([n],c,a,this._stdErrSerialize)}function u(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=c),r&&(this._logEvent=d([].concat(e._logEvent.bindings,n)))}u.prototype=this;const h=new u(this);return s(this,h),h.child=function(...e){return _.call(this,t,...e)},h.level=o.level||this.level,t.onChild(h),h}return w.levels=function(e){const t=e.customLevels||{},r=Object.assign({},c.levels.values,t),n=Object.assign({},c.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(r){t[e[r]]=r})),t}(t));return{values:r,labels:n}}(e),w.level=v,w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=y,w.serializers=p,w._serialize=f,w._stdErrSerialize=m,w.child=function(...e){return _.call(this,k,...e)},r&&(w._logEvent=d()),w}function u(r,a,s,c){if(Object.defineProperty(r,c,{value:n(r.level,s)>n(c,s)?y:s[o][c],writable:!0,enumerable:!0,configurable:!0}),r[c]===y){if(!a.transmit)return;const e=n(a.transmit.level||r.level,s);if(n(c,s)<e)return}r[c]=function(r,i,a,s){return function(o){return function(){const c=i.timestamp(),u=new Array(arguments.length),p=Object.getPrototypeOf&&Object.getPrototypeOf(this)===t?t:this;for(var h=0;h<u.length;h++)u[h]=arguments[h];var f=!1;if(i.serialize&&(l(u,this._serialize,this.serializers,this._stdErrSerialize),f=!0),i.asObject||i.formatters?o.call(p,function(t,r,n,o,i){const{level:a,log:s=e=>e}=i.formatters||{},c=n.slice();let u=c[0];const l={};o&&(l.time=o);if(a){const e=a(r,t.levels.values[r]);Object.assign(l,e)}else l.level=t.levels.values[r];let d=1+(0|t._childLevel);d<1&&(d=1);if(null!==u&&"object"==typeof u){for(;d--&&"object"==typeof c[0];)Object.assign(l,c.shift());u=c.length?e(c.shift(),c):void 0}else"string"==typeof u&&(u=e(c.shift(),c));void 0!==u&&(l[i.messageKey]=u);return s(l)}(this,s,u,c,i)):o.apply(p,u),i.transmit){const e=n(i.transmit.level||r._level,a),t=n(s,a);if(t<e)return;!function(e,t,r,n=!1){const o=t.send,i=t.ts,a=t.methodLevel,s=t.methodValue,c=t.val,u=e._logEvent.bindings;n||l(r,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize);e._logEvent.ts=i,e._logEvent.messages=r.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=a,e._logEvent.level.value=s,o(a,e._logEvent,c),e._logEvent=d(u)}(this,{ts:c,methodLevel:s,methodValue:t,transmitValue:a.levels.values[i.transmit.level||r._level],send:i.transmit.send,val:n(r._level,a)},u,f)}}}(r[o][s])}(r,a,s,c);const u=function(e){const t=[];e.bindings&&t.push(e.bindings);let r=e[i];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}(r);0!==u.length&&(r[c]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(u,r[c]))}function l(e,t,r,n){for(const o in e)if(n&&e[o]instanceof Error)e[o]=c.stdSerializers.err(e[o]);else if("object"==typeof e[o]&&!Array.isArray(e[o])&&t)for(const n in e[o])t.indexOf(n)>-1&&n in r&&(e[o][n]=r[n](e[o][n]))}function d(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function p(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}function h(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?g:b}function f(){return{}}function m(e){return e}function y(){}function g(){return!1}function b(){return Date.now()}return c.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},c.stdSerializers=r,c.stdTimeFunctions=Object.assign({},{nullTime:g,epochTime:b,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),browser$e.exports.default=c,browser$e.exports.pino=c,browser$e.exports}var browserExports$2=requireBrowser$d();const e$c=getDefaultExportFromCjs$2(browserExports$2);let Logger$2=(_a2=class{constructor(e={}){const t=e.level||"info";this.moduleContext=e.module||"app";const r={level:t,enabled:!e.silent,transport:!1!==e.prettyPrint?{target:"pino-pretty",options:{colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}}:void 0};this.logger=e$c(r)}static getInstance(e={}){const t=e.module||"default";return _a2.instances.has(t)||_a2.instances.set(t,new _a2(e)),_a2.instances.get(t)}setLogLevel(e){this.logger.level=e}setSilent(e){e&&(this.logger.level="silent")}setModule(e){this.moduleContext=e}debug(e,t){t?this.logger.debug({module:this.moduleContext,...t},e):this.logger.debug({module:this.moduleContext},e)}info(e,t){t?this.logger.info({module:this.moduleContext,...t},e):this.logger.info({module:this.moduleContext},e)}warn(e,t){t?this.logger.warn({module:this.moduleContext,...t},e):this.logger.warn({module:this.moduleContext},e)}error(e,t){t?this.logger.error({module:this.moduleContext,...t},e):this.logger.error({module:this.moduleContext},e)}},_a2.instances=new Map,_a2);const sleep$1=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$2.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[r]=n}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw n}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const n=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+n);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.getAttribute("type"),i=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===o){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(s){if(this.error("Failed to load "+o+": "+r,s),this.updateLoadingStatus(r,"failed"),i)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(n,t,o),a=await i.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),o)throw i}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,n),i=URL.createObjectURL(o);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(n){this.error("Failed to load image: "+r,n),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),n=r?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(n,r,o),a=URL.createObjectURL(i);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(o){this.error("Failed to load "+t+": "+n,o),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{o.setAttribute(e.name,e.value)})),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const i=await this.retrieveHCS1Data(r,t,n),a=URL.createObjectURL(i);o.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(n){this.error("Failed to load GLB: "+r,n),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((n=>{this.loadQueue.push({element:e,type:t,order:r,resolve:n}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),i=o.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(i,n,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(n){this.error("Failed to load CSS image: "+i,n)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:n,type:"video"},{elements:o,type:"audio"},{elements:i,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const n=new Audio(r);n.volume=t,this.LoadedAudios[e]=n,n.play().catch((e=>{console.error("Failed to play audio:",e)})),n.addEventListener("ended",(()=>{n.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=r,await n.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}const isServer="undefined"==typeof window;isServer||(window.HCS=new HCS,window.HCS.init().then((()=>{console.log("All HCS resources loaded"),"function"==typeof window.HCSReady&&(console.log("Running HCSReady..."),window.HCSReady())})));class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$2.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),n=t(r.length,1);return this.getUint8Memory().set(r,n),this.WASM_VECTOR_LEN=r.length,n}let n=this.textEncoder.encode(e).length,o=t(n,1);const i=this.getUint8Memory();let a=0;for(;a<n;a++){const t=e.charCodeAt(a);if(t>127)break;i[o+a]=t}if(a!==n){0!==a&&(e=e.slice(a)),o=r(o,n,n=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+a,o+n);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,o}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let n=[0,0];try{const o=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,o);const i=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return n=[i,a],this.getStringFromWasm(i,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(n[0],n[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const n=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${n}`),new Error(n)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const n=await WebAssembly.instantiate(t,r);return this.wasm=n.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(n){throw this.logger.error("Failed to initialize WASM module",n),n}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{const o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.values[0]):r[e]=this.getDefaultValueForType(n)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp2=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp2=(e,t,r)=>t in e?__defProp2(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField2=(e,t,r)=>__defNormalProp2(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,n)=>({set _(n){__privateSet(e,t,n,r)},get _(){return __privateGet(e,t,n)}}),_a2,_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const n=t[r];if("string"!=typeof n&&!Array.isArray(n))for(const t in n)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(n,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$e={exports:{}},quickFormatUnescaped,hasRequiredQuickFormatUnescaped,hasRequiredBrowser$d;function requireQuickFormatUnescaped(){if(hasRequiredQuickFormatUnescaped)return quickFormatUnescaped;function e(e){try{return JSON.stringify(e)}catch(t){return'"[Circular]"'}}return hasRequiredQuickFormatUnescaped=1,quickFormatUnescaped=function(t,r,n){var o=n&&n.stringify||e;if("object"==typeof t&&null!==t){var i=r.length+1;if(1===i)return t;var a=new Array(i);a[0]=o(t);for(var s=1;s<i;s++)a[s]=o(r[s]);return a.join(" ")}if("string"!=typeof t)return t;var c=r.length;if(0===c)return t;for(var u="",l=0,d=-1,p=t&&t.length||0,h=0;h<p;){if(37===t.charCodeAt(h)&&h+1<p){switch(d=d>-1?d:0,t.charCodeAt(h+1)){case 100:case 102:if(l>=c)break;if(null==r[l])break;d<h&&(u+=t.slice(d,h)),u+=Number(r[l]),d=h+2,h++;break;case 105:if(l>=c)break;if(null==r[l])break;d<h&&(u+=t.slice(d,h)),u+=Math.floor(Number(r[l])),d=h+2,h++;break;case 79:case 111:case 106:if(l>=c)break;if(void 0===r[l])break;d<h&&(u+=t.slice(d,h));var f=typeof r[l];if("string"===f){u+="'"+r[l]+"'",d=h+2,h++;break}if("function"===f){u+=r[l].name||"<anonymous>",d=h+2,h++;break}u+=o(r[l]),d=h+2,h++;break;case 115:if(l>=c)break;d<h&&(u+=t.slice(d,h)),u+=String(r[l]),d=h+2,h++;break;case 37:d<h&&(u+=t.slice(d,h)),u+="%",d=h+2,h++,l--}++l}++h}if(-1===d)return t;d<p&&(u+=t.slice(d));return u}}function requireBrowser$d(){if(hasRequiredBrowser$d)return browser$e.exports;hasRequiredBrowser$d=1;const e=requireQuickFormatUnescaped();browser$e.exports=c;const t=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},r={mapHttpRequest:f,mapHttpResponse:f,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:f,res:f,err:p,errWithCause:p};function n(e,t){return"silent"===e?1/0:t.levels.values[e]}const o=Symbol("pino.logFuncs"),i=Symbol("pino.hierarchy"),a={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function s(e,t){const r={logger:t,parent:e[i]};t[i]=r}function c(e){(e=e||{}).browser=e.browser||{};const r=e.browser.transmit;if(r&&"function"!=typeof r.send)throw Error("pino: transmit option must have a send function");const i=e.browser.write||t;e.browser.write&&(e.browser.asObject=!0);const p=e.serializers||{},f=function(e,t){if(Array.isArray(e))return e.filter((function(e){return"!stdSerializers.err"!==e}));return!0===e&&Object.keys(t)}(e.browser.serialize,p);let m=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(m=!1);const g=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(g);"function"==typeof i&&b.forEach((function(e){i[e]=i})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const v=e.level||"info",w=Object.create(i);w.log||(w.log=y),function(e,r,n){const i={};r.forEach((e=>{i[e]=n[e]?n[e]:t[e]||t[a[e]||"log"]||y})),e[o]=i}(w,b,i),s({},w),Object.defineProperty(w,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,u(this,k,w,"error"),u(this,k,w,"fatal"),u(this,k,w,"warn"),u(this,k,w,"info"),u(this,k,w,"debug"),u(this,k,w,"trace"),g.forEach((e=>{u(this,k,w,e)}))}});const k={transmit:r,serialize:f,asObject:e.browser.asObject,formatters:e.browser.formatters,levels:b,timestamp:h(e),messageKey:e.messageKey||"msg",onChild:e.onChild||y};function _(t,n,o){if(!n)throw new Error("missing bindings for child Pino");o=o||{},f&&n.serializers&&(o.serializers=n.serializers);const i=o.serializers;if(f&&i){var a=Object.assign({},p,i),c=!0===e.browser.serialize?Object.keys(a):f;delete n.serializers,l([n],c,a,this._stdErrSerialize)}function u(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=c),r&&(this._logEvent=d([].concat(e._logEvent.bindings,n)))}u.prototype=this;const h=new u(this);return s(this,h),h.child=function(...e){return _.call(this,t,...e)},h.level=o.level||this.level,t.onChild(h),h}return w.levels=function(e){const t=e.customLevels||{},r=Object.assign({},c.levels.values,t),n=Object.assign({},c.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(r){t[e[r]]=r})),t}(t));return{values:r,labels:n}}(e),w.level=v,w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=y,w.serializers=p,w._serialize=f,w._stdErrSerialize=m,w.child=function(...e){return _.call(this,k,...e)},r&&(w._logEvent=d()),w}function u(r,a,s,c){if(Object.defineProperty(r,c,{value:n(r.level,s)>n(c,s)?y:s[o][c],writable:!0,enumerable:!0,configurable:!0}),r[c]===y){if(!a.transmit)return;const e=n(a.transmit.level||r.level,s);if(n(c,s)<e)return}r[c]=function(r,i,a,s){return function(o){return function(){const c=i.timestamp(),u=new Array(arguments.length),p=Object.getPrototypeOf&&Object.getPrototypeOf(this)===t?t:this;for(var h=0;h<u.length;h++)u[h]=arguments[h];var f=!1;if(i.serialize&&(l(u,this._serialize,this.serializers,this._stdErrSerialize),f=!0),i.asObject||i.formatters?o.call(p,function(t,r,n,o,i){const{level:a,log:s=e=>e}=i.formatters||{},c=n.slice();let u=c[0];const l={};o&&(l.time=o);if(a){const e=a(r,t.levels.values[r]);Object.assign(l,e)}else l.level=t.levels.values[r];let d=1+(0|t._childLevel);d<1&&(d=1);if(null!==u&&"object"==typeof u){for(;d--&&"object"==typeof c[0];)Object.assign(l,c.shift());u=c.length?e(c.shift(),c):void 0}else"string"==typeof u&&(u=e(c.shift(),c));void 0!==u&&(l[i.messageKey]=u);return s(l)}(this,s,u,c,i)):o.apply(p,u),i.transmit){const e=n(i.transmit.level||r._level,a),t=n(s,a);if(t<e)return;!function(e,t,r,n=!1){const o=t.send,i=t.ts,a=t.methodLevel,s=t.methodValue,c=t.val,u=e._logEvent.bindings;n||l(r,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize);e._logEvent.ts=i,e._logEvent.messages=r.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=a,e._logEvent.level.value=s,o(a,e._logEvent,c),e._logEvent=d(u)}(this,{ts:c,methodLevel:s,methodValue:t,transmitValue:a.levels.values[i.transmit.level||r._level],send:i.transmit.send,val:n(r._level,a)},u,f)}}}(r[o][s])}(r,a,s,c);const u=function(e){const t=[];e.bindings&&t.push(e.bindings);let r=e[i];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}(r);0!==u.length&&(r[c]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(u,r[c]))}function l(e,t,r,n){for(const o in e)if(n&&e[o]instanceof Error)e[o]=c.stdSerializers.err(e[o]);else if("object"==typeof e[o]&&!Array.isArray(e[o])&&t)for(const n in e[o])t.indexOf(n)>-1&&n in r&&(e[o][n]=r[n](e[o][n]))}function d(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function p(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}function h(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?g:b}function f(){return{}}function m(e){return e}function y(){}function g(){return!1}function b(){return Date.now()}return c.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},c.stdSerializers=r,c.stdTimeFunctions=Object.assign({},{nullTime:g,epochTime:b,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),browser$e.exports.default=c,browser$e.exports.pino=c,browser$e.exports}var browserExports$2=requireBrowser$d();const e$c=getDefaultExportFromCjs$2(browserExports$2);let Logger$2=(_a2=class{constructor(e={}){const t=e.level||"info";this.moduleContext=e.module||"app";const r={level:t,enabled:!e.silent,transport:!1!==e.prettyPrint?{target:"pino-pretty",options:{colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}}:void 0};this.logger=e$c(r)}static getInstance(e={}){const t=e.module||"default";return _a2.instances.has(t)||_a2.instances.set(t,new _a2(e)),_a2.instances.get(t)}setLogLevel(e){this.logger.level=e}setSilent(e){e&&(this.logger.level="silent")}setModule(e){this.moduleContext=e}debug(e,t){this.logger.debug({module:this.moduleContext},e,t)}info(e,t){this.logger.info({module:this.moduleContext},e,t)}warn(e,t){this.logger.warn({module:this.moduleContext},e,t)}error(e,t){this.logger.error({module:this.moduleContext},e,t)}},_a2.instances=new Map,_a2);const sleep$1=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$2.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[r]=n}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw n}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const n=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+n);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.getAttribute("type"),i=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===o){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),i)throw e}}}catch(s){if(this.error("Failed to load "+o+": "+r,s),this.updateLoadingStatus(r,"failed"),i)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(n,t,o),a=await i.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(i){if(this.error("Failed to load stylesheet: "+r,i),this.updateLoadingStatus(r,"failed"),o)throw i}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,n),i=URL.createObjectURL(o);e.src=i,this.LoadedImages[r]=i,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(n){this.error("Failed to load image: "+r,n),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),n=r?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(n,r,o),a=URL.createObjectURL(i);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(o){this.error("Failed to load "+t+": "+n,o),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{o.setAttribute(e.name,e.value)})),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const i=await this.retrieveHCS1Data(r,t,n),a=URL.createObjectURL(i);o.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(n){this.error("Failed to load GLB: "+r,n),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((n=>{this.loadQueue.push({element:e,type:t,order:r,resolve:n}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),i=o.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(i,n,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[i]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(n){this.error("Failed to load CSS image: "+i,n)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),i=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:n,type:"video"},{elements:o,type:"audio"},{elements:i,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const n=new Audio(r);n.volume=t,this.LoadedAudios[e]=n,n.play().catch((e=>{console.error("Failed to play audio:",e)})),n.addEventListener("ended",(()=>{n.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=r,await n.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}const isServer="undefined"==typeof window;isServer||(window.HCS=new HCS,window.HCS.init().then((()=>{console.log("All HCS resources loaded"),"function"==typeof window.HCSReady&&(console.log("Running HCSReady..."),window.HCSReady())})));class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$2.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),n=t(r.length,1);return this.getUint8Memory().set(r,n),this.WASM_VECTOR_LEN=r.length,n}let n=this.textEncoder.encode(e).length,o=t(n,1);const i=this.getUint8Memory();let a=0;for(;a<n;a++){const t=e.charCodeAt(a);if(t>127)break;i[o+a]=t}if(a!==n){0!==a&&(e=e.slice(a)),o=r(o,n,n=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+a,o+n);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,o}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let n=[0,0];try{const o=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,o);const i=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return n=[i,a],this.getStringFromWasm(i,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(n[0],n[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const n=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${n}`),new Error(n)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const n=await WebAssembly.instantiate(t,r);return this.wasm=n.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(n){throw this.logger.error("Failed to initialize WASM module",n),n}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{const o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.values[0]):r[e]=this.getDefaultValueForType(n)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
2
2
  /**
3
3
  * @license
4
4
  * Copyright 2009 The Closure Library Authors
@@ -130,5 +130,5 @@ function utilFromBase(e,t){let r=0;if(1===e.length)return e[0];for(let n=e.lengt
130
130
  * Copyright(c) 2014 Jonathan Ong
131
131
  * Copyright(c) 2015 Douglas Christopher Wilson
132
132
  * MIT Licensed
133
- */function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,o=requireMimeDb(),i=requirePathBrowserify().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),r=t&&o[t[1].toLowerCase()];return r&&r.charset?r.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var r=-1===t.indexOf("/")?e.lookup(t):t;if(!r)return!1;if(-1===r.indexOf("charset")){var n=e.charset(r);n&&(r+="; charset="+n.toLowerCase())}return r},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var r=a.exec(t),n=r&&e.extensions[r[1].toLowerCase()];if(!n||!n.length)return!1;return n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var r=i("x."+t).toLowerCase().substr(1);if(!r)return!1;return e.types[r]||!1},e.types=Object.create(null),t=e.extensions,r=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach((function(e){var i=o[e],a=i.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(r[c]){var u=n.indexOf(o[r[c]].source),l=n.indexOf(i.source);if("application/octet-stream"!==r[c]&&(u>l||u===l&&"application/"===r[c].substr(0,12)))continue}r[c]=e}}}))}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes(),util,util2,objectUtil,objectUtil2;util2=util||(util={}),util2.assertEqual=e=>e,util2.assertIs=function(e){},util2.assertNever=function(e){throw new Error},util2.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},util2.getValidEnumValues=e=>{const t=util2.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),r={};for(const n of t)r[n]=e[n];return util2.objectValues(r)},util2.objectValues=e=>util2.objectKeys(e).map((function(t){return e[t]})),util2.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},util2.find=(e,t)=>{for(const r of e)if(t(r))return r},util2.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,util2.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},util2.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,objectUtil2=objectUtil||(objectUtil={}),objectUtil2.mergeShapes=(e,t)=>({...e,...t});const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=e=>{switch(typeof e){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(e)?ZodParsedType.array:null===e?ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const o of e.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)r._errors.push(t(o));else{let e=r,n=0;for(;n<o.path.length;){const r=o.path[n];n===o.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(o))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.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.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.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.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.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function setErrorMap(e){overrideErrorMap=e}function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],a={...o,path:i};if(void 0!==o.message)return{...o,path:i,message:o.message};let s="";const c=n.filter((e=>!!e)).slice().reverse();for(const u of c)s=u(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}},EMPTY_PATH=[];function addIssueToContext(e,t){const r=getErrorMap(),n=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter((e=>!!e))});e.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const e=await n.key,t=await n.value;r.push({key:e,value:t})}return ParseStatus.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:o}=n;if("aborted"===t.status)return INVALID;if("aborted"===o.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===o.status&&e.dirty(),"__proto__"===t.value||void 0===o.value&&!n.alwaysSet||(r[t.value]=o.value)}return{status:e.value,value:r}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=e=>({status:"dirty",value:e}),OK=e=>({status:"valid",value:e}),isAborted=e=>"aborted"===e.status,isDirty=e=>"dirty"===e.status,isValid=e=>"valid"===e.status,isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise;function __classPrivateFieldGet(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function __classPrivateFieldSet(e,t,r,n,o){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var errorUtil,errorUtil2,_ZodEnum_cache,_ZodNativeEnum_cache;"function"==typeof SuppressedError&&SuppressedError,errorUtil2=errorUtil||(errorUtil={}),errorUtil2.errToObj=e=>"string"==typeof e?{message:e}:e||{},errorUtil2.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class ParseInputLazyPath{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:o};return{errorMap:(t,o)=>{var i,a;const{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:o.defaultError}:void 0===o.data?{message:null!==(i=null!=s?s:n)&&void 0!==i?i:o.defaultError}:"invalid_type"!==t.code?{message:o.defaultError}:{message:null!==(a=null!=s?s:r)&&void 0!==a?a:o.defaultError}},description:o}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},o=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,o)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(o){(null===(r=null===(t=null==o?void 0:o.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>isValid(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,o)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const o=e(t),i=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&o instanceof Promise?o.then((e=>!!e||(i(),!1))):!!o||(i(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function timeRegex(e){return new RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function isValidIP(e,t){return!("v4"!==t&&t||!ipv4Regex.test(e))||!("v6"!==t&&t||!ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return"object"==typeof o&&null!==o&&(!(!o.typ||!o.alg)&&(!t||o.alg===t))}catch(r){return!1}}function isValidCidr(e,t){return!("v4"!==t&&t||!ipv4CidrRegex.test(e))||!("v6"!==t&&t||!ipv6CidrRegex.test(e))}class ZodString extends ZodType{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ZodParsedType.string){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}const t=new ParseStatus;let r;for(const o of this._def.checks)if("min"===o.kind)e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("max"===o.kind)e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("length"===o.kind){const n=e.data.length>o.value,i=e.data.length<o.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),t.dirty())}else if("email"===o.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("emoji"===o.kind)emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("uuid"===o.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("nanoid"===o.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid"===o.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid2"===o.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("ulid"===o.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("url"===o.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()}else if("regex"===o.kind){o.regex.lastIndex=0;o.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty())}else if("trim"===o.kind)e.data=e.data.trim();else if("includes"===o.kind)e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),t.dirty());else if("toLowerCase"===o.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===o.kind)e.data=e.data.toUpperCase();else if("startsWith"===o.kind)e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),t.dirty());else if("endsWith"===o.kind)e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),t.dirty());else if("datetime"===o.kind){datetimeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),t.dirty())}else if("date"===o.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),t.dirty())}else if("time"===o.kind){timeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),t.dirty())}else"duration"===o.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"ip"===o.kind?isValidIP(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"jwt"===o.kind?isValidJWT(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"cidr"===o.kind?isValidCidr(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64"===o.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64url"===o.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):util.assertNever(o);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(r)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...errorUtil.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...errorUtil.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n;return parseInt(e.toFixed(o).replace(".",""))%parseInt(t.toFixed(o).replace(".",""))/Math.pow(10,o)}ZodString.create=e=>{var t;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType.number){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t;const r=new ParseStatus;for(const n of this._def.checks)if("int"===n.kind)util.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.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.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):util.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=e=>{var t;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodBoolean extends ZodType{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodDate extends ZodType{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType.date){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(isNaN(e.data.getTime())){return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID}const t=new ParseStatus;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ZodDate.create=e=>new ZodDate({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(e||o)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:o?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new ParseInputLazyPath(t,e,t.path,r))))).then((e=>ParseStatus.mergeArray(r,e)));const o=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function deepPartialify(e){if(e instanceof ZodObject){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...e._def,shape:()=>t})}return e instanceof ZodArray?new ZodArray({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof ZodTuple?ZodTuple.create(e.items.map((e=>deepPartialify(e)))):e}ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==ZodParsedType.object){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)o.includes(s)||i.push(s);const a=[];for(const s of o){const e=n[s],t=r.data[s];a.push({key:{status:"valid",value:s},value:e._parse(new ParseInputLazyPath(r,t,r.path,s)),alwaysSet:s in r.data})}if(this._def.catchall instanceof ZodNever){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>ParseStatus.mergeObjectSync(t,e))):ParseStatus.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,o,i,a;const s=null!==(i=null===(o=(n=this._def).errorMap)||void 0===o?void 0:o.call(n,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=errorUtil.errToObj(e).message)&&void 0!==a?a:s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};return util.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};return util.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};return util.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new ZodObject({...this._def,shape:()=>t})}required(e){const t={};return util.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}})),new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const r=e.map((e=>new ZodError(e.ctx.common.issues)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:r}),INVALID}));{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;const r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const o of t){const t=getDiscriminator(o.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(n.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);n.set(r,o)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...processCreateParams(r)})}}function mergeValues(e,t){const r=getParsedType(e),n=getParsedType(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType.object&&n===ZodParsedType.object){const r=util.objectKeys(t),n=util.objectKeys(e).filter((e=>-1!==r.indexOf(e))),o={...e,...t};for(const i of n){const r=mergeValues(e[i],t[i]);if(!r.valid)return{valid:!1};o[i]=r.data}return{valid:!0,data:o}}if(r===ZodParsedType.array&&n===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const o=mergeValues(e[n],t[n]);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}return r===ZodParsedType.date&&n===ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted(e)||isAborted(n))return INVALID;const o=mergeValues(e.value,n.value);return o.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:o.data}):(addIssueToContext(r,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ZodIntersection.create=(e,t,r)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>ParseStatus.mergeArray(t,e))):ParseStatus.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const n=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)n.push({key:o._parse(new ParseInputLazyPath(r,a,r.path,a)),value:i._parse(new ParseInputLazyPath(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ParseStatus.mergeObjectAsync(t,n):ParseStatus.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ZodRecord(t instanceof ZodType?{keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)}:{keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;const n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[i,"key"])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,o=await r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,o=r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}}}ZodMap.create=(e,t,r)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const o=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return INVALID;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function r(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:r}})}function n(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:r}})}const o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ZodPromise){const e=this;return OK((async function(...t){const a=new ZodError([]),s=await e._def.args.parseAsync(t,o).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,s);return await e._def.returns._def.type.parseAsync(c,o).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return OK((function(...t){const a=e._def.args.safeParse(t,o);if(!a.success)throw new ZodError([r(t,a.error)]);const s=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(s,o);if(!c.success)throw new ZodError([n(s,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(r)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:r}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}_ZodEnum_cache=new WeakMap,ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(e){const t=util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util.objectValues(t);return addIssueToContext(r,{expected:util.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(e.data)){const e=util.objectValues(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap,ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&!1===t.common.async)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const r=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){const e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return INVALID;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}));{if("aborted"===t.value)return INVALID;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return e;const i=n.transform(e.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}util.assertNever(n)}}ZodEffects.create=(e,t,r)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(e,t,r)=>new ZodEffects({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...processCreateParams(t)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...processCreateParams(t)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),r=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function cleanParams(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function custom(e,t={},r){return e?ZodAny.create().superRefine(((n,o)=>{var i,a;const s=e(n);if(s instanceof Promise)return s.then((e=>{var i,a;if(!e){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}}));if(!s){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}})):ZodAny.create()}ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind,ZodFirstPartyTypeKind2;ZodFirstPartyTypeKind2=ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}),ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly";const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom((t=>t instanceof e),t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:e=>ZodString.create({...e,coerce:!0}),number:e=>ZodNumber.create({...e,coerce:!0}),boolean:e=>ZodBoolean.create({...e,coerce:!0}),bigint:e=>ZodBigInt.create({...e,coerce:!0}),date:e=>ZodDate.create({...e,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap:setErrorMap,getErrorMap:getErrorMap,makeIssue:makeIssue,EMPTY_PATH:EMPTY_PATH,addIssueToContext:addIssueToContext,ParseStatus:ParseStatus,INVALID:INVALID,DIRTY:DIRTY,OK:OK,isAborted:isAborted,isDirty:isDirty,isValid:isValid,isAsync:isAsync,get util(){return util},get objectUtil(){return objectUtil},ZodParsedType:ZodParsedType,getParsedType:getParsedType,ZodType:ZodType,datetimeRegex:datetimeRegex,ZodString:ZodString,ZodNumber:ZodNumber,ZodBigInt:ZodBigInt,ZodBoolean:ZodBoolean,ZodDate:ZodDate,ZodSymbol:ZodSymbol,ZodUndefined:ZodUndefined,ZodNull:ZodNull,ZodAny:ZodAny,ZodUnknown:ZodUnknown,ZodNever:ZodNever,ZodVoid:ZodVoid,ZodArray:ZodArray,ZodObject:ZodObject,ZodUnion:ZodUnion,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodIntersection:ZodIntersection,ZodTuple:ZodTuple,ZodRecord:ZodRecord,ZodMap:ZodMap,ZodSet:ZodSet,ZodFunction:ZodFunction,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodEnum:ZodEnum,ZodNativeEnum:ZodNativeEnum,ZodPromise:ZodPromise,ZodEffects:ZodEffects,ZodTransformer:ZodEffects,ZodOptional:ZodOptional,ZodNullable:ZodNullable,ZodDefault:ZodDefault,ZodCatch:ZodCatch,ZodNaN:ZodNaN,BRAND:BRAND,ZodBranded:ZodBranded,ZodPipeline:ZodPipeline,ZodReadonly:ZodReadonly,custom:custom,Schema:ZodType,ZodSchema:ZodType,late:late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce:coerce,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean:oboolean,onumber:onumber,optional:optionalType,ostring:ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER:NEVER,ZodIssueCode:ZodIssueCode,quotelessJson:quotelessJson,ZodError:ZodError}),ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(ProfileType||{}),AIAgentType=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(AIAgentType||{}),EndpointType=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(EndpointType||{}),AIAgentCapability=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(AIAgentCapability||{});const SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube"],SocialLinkSchema=z.object({platform:z.string().min(1),handle:z.string().min(1)}),AIAgentDetailsSchema=z.object({type:z.nativeEnum(AIAgentType),capabilities:z.array(z.nativeEnum(AIAgentCapability)).min(1),model:z.string().min(1),creator:z.string().optional()}),BaseProfileSchema=z.object({version:z.string().min(1),type:z.nativeEnum(ProfileType),display_name:z.string().min(1),alias:z.string().optional(),bio:z.string().optional(),socials:z.array(SocialLinkSchema).optional(),profileImage:z.string().optional(),properties:z.record(z.any()).optional(),inboundTopicId:z.string().optional(),outboundTopicId:z.string().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:z.literal(0),language:z.string().optional(),timezone:z.string().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:z.literal(1),aiAgent:AIAgentDetailsSchema}),HCS11ProfileSchema=z.union([PersonalProfileSchema,AIAgentProfileSchema]),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};class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.auth=e.auth,this.network=e.network,this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey){const e=y$2.fromString(this.auth.privateKey);this.client.setOperator(this.auth.operatorId,e)}this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-11"})}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}createPersonalProfile(e,t){return{version:"1.0",type:0,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,language:t?.language,timezone:t?.timezone,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId}}createAIAgentProfile(e,t,r,n,o){const i=this.validateProfile({version:"1.0",type:1,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:1,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}}}validateProfile(e){const t=HCS11ProfileSchema.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map((e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`}))}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:",t),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!==e$6.Success?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),n=await r.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status!==e$6.Success?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const i=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(o.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(o.verifying("Waiting for inscription confirmation",50,{jobId:s.result.jobId}),{imageTopicId:"",transactionId:s.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,n=new ProgressReporter({module:"HCS11-Profile",logger:this.logger,callback:r});n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const i=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(i,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};n.submitting("Submitting profile to Hedera network",30);const s=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},o):await inscribeWithSigner(r,this.auth.signer,o);if(!s.confirmed||!s.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=s.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:c,transactionId:s.result.transactionId}),{profileTopicId:c,transactionId:s.result.transactionId,success:!0}}catch(s){return n.failed(`Error inscribing profile: ${s.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:s.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),n=(new s$4).setAccountMemo(r).setAccountId(e);return this.executeTransaction(n)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const i=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[0];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(0),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?1:0}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${n}`),!n?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo`};this.logger.info(`Found HCS-11 memo: ${n}`);const o=n.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[n,i,a]=e,s=t||this.network||"mainnet";this.logger.info(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();return t?{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:a}}:{success:!1,error:`No profile data found for topic ${a}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class Registration{async checkRegistrationStatus(e,t,r,n){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,n=60,o=2e3,i){let a=0;for(;a<n;){i&&i.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,i);if("success"===s.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise((e=>setTimeout(e,o))),a++}return i&&i.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const r=new HCS11Client({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await sleep(5e3);const o=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const i=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),a=await i.json();return i.ok?(n&&n.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(i){return{error:`Error during registration request: ${i.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach((e=>r.append("tags",e))),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const n=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(e2){return{registrations:[],error:`Error fetching registrations: ${e2.message}`,success:!1}}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint}),this.mirrorNode=new HederaMirrorNode(e.network,this.logger),this.feeAmount=e.feeAmount||.001}async getMessageStream(e){try{const t=await this.mirrorNode.getTopicMessages(e),r=["message","close_connection"];return{messages:t.filter((e=>{if("hcs-10"!==e.p||!r.includes(e.op))return!1;if("message"===e.op){if(!e.data)return!1;if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}if("close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async 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$7.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){try{const t=await this.mirrorNode.getTopicMessages(e);return{messages:t.filter((e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async requestAccount(e){try{return await this.mirrorNode.requestAccount(e)}catch(e2){throw this.logger.error("Failed to fetch account",e2),e2}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e){this.logger.info(`Retrieving profile for account: ${e}`);try{const t=new HCS11Client({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),r=await t.fetchProfileByAccountId(e,this.network);if(!r?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,r?.error),{profile:null,success:!1,error:r?.error||`Failed to retrieve profile for account ID: ${e}`};const n=r.profile;let o=null;if(r.topicInfo?.inboundTopic&&r.topicInfo?.outboundTopic&&r.topicInfo?.profileTopicId){o={inboundTopic:r.topicInfo.inboundTopic,outboundTopic:r.topicInfo.outboundTopic,profileTopicId:r.topicInfo.profileTopicId};const t=`${e}-${this.network}`;HCS10Cache.getInstance().set(t,o)}return{profile:n,topicInfo:o,success:!0}}catch(t){return this.logger.error("Failed to retrieve profile:",t),{profile:null,success:!1,error:t instanceof Error?t.message:String(t)}}}async retrieveOutboundConnectTopic(e){this.logger.info(`Retrieving topics for account: ${e}`);try{const t=await this.retrieveProfile(e);if(!t?.success)throw new Error(t.error||"Failed to retrieve profile");const r=t.profile;if(!r.inboundTopicId||!r.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");const n={inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId},o=`${e}-${this.network}`;return HCS10Cache.getInstance().set(o,n),n}catch(t){throw this.logger.error("Failed to retrieve topic info:",t),t}}async retrieveOutboundMessages(e){try{const t=await this.retrieveOutboundConnectTopic(e);if(!t)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(t.outboundTopic)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(t){return this.logger.error("Failed to retrieve outbound messages:",t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveOutboundConnectTopic(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some((e=>"connection_created"===e.op&&e.connection_id===t))}catch(r){return this.logger.error("Failed to check connection created:",r),!1}}async getMessageContent(e){const t=e.match(/^hcs:\/\/(\d+)\/([0-9.]+)$/);if(!t)return e;const[r,n,o]=t;this.logger.info(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`https://kiloscribe.com/api/inscription-cdn/${o}?network=${this.network}`,t=await axios.get(e);if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return t.data.content||t.data.text||JSON.stringify(t.data)}catch(i){throw this.logger.error(`Error resolving HRL reference: ${i instanceof Error?i.message:"Unknown error"}`),new Error(`Failed to resolve HRL reference: ${i instanceof Error?i.message:"Unknown error"}`)}}async recordOutboundConnectionConfirmation({outboundTopicId:e,connectionRequestId:t,confirmedRequestId:r,connectionTopicId:n,operatorId:o,memo:i}){const a={p:"hcs-10",op:"connection_created",connection_topic_id:n,outbound_topic_id:e,confirmed_request_id:r,connection_request_id:t,operator_id:o,m:i};return await this.submitPayload(e,a)}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}clearCache(){HCS10Cache.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async checkRegistrationStatus(e,t,r){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(n){throw this.logger.error(`Error checking registration status: ${n}`),n}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],n=t[1];if(!r)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(r)}}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()}}var InboundTopicType=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(InboundTopicType||{});async function accountIdsToExemptKeys(e,t,r){const n=new HederaMirrorNode(t,r),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${a}: ${i}`)}return o}class FeeConfigBuilder{constructor(){this.feeAmount=0,this.decimals=0,this.feeCollectorAccountId="",this.exemptAccountIds=[]}static forHbar(e,t,r=[]){return(new FeeConfigBuilder).setHbarAmount(e).setFeeCollector(t).addExemptAccounts(r)}setHbarAmount(e){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.feeAmount=1e8*e,this.decimals=0,this}setFeeAmount(e,t=0){return this.feeAmount=e,this.decimals=t,this}setFeeCollector(e){return this.feeCollectorAccountId=e,this}addExemptAccount(e){return this.exemptAccountIds.includes(e)||this.exemptAccountIds.push(e),this}addExemptAccounts(e){for(const t of e)this.addExemptAccount(t);return this}build(){if(!this.feeCollectorAccountId)throw new Error("Fee collector account ID is required");if(this.feeAmount<=0)throw new Error("Fee amount must be greater than zero");return{feeAmount:{amount:this.feeAmount,decimals:this.decimals},feeCollectorAccountId:this.feeCollectorAccountId,exemptAccounts:this.exemptAccountIds}}}class HCS10Client extends HCS10BaseClient{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount}),this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.operatorPrivateKey=y$2.fromString(e.operatorPrivateKey),this.network=e.network,this.client.setOperator(e.operatorId,this.operatorPrivateKey.toString()),this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-SDK"}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel})}getClient(){return this.client}async createAccount(){this.logger.info("Creating new account");const e=y$2.generate(),t=(new l).setKey(e.publicKey).setInitialBalance(new e$7(10));this.logger.debug("Executing account creation transaction");const r=await t.execute(this.client),n=(await r.getReceipt(this.client)).accountId;if(!n)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: ${n.toString()}`),{accountId:n.toString(),privateKey:e.toString()}}async createInboundTopic(e,t,r=60,n){const o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let i,a;switch(t){case InboundTopicType.PUBLIC:i=!1;break;case InboundTopicType.CONTROLLED:i=!0;break;case InboundTopicType.FEE_BASED:if(i=!0,!n)throw new Error("Fee configuration builder is required for fee-based topics");a=n.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,i,a)}async createAgent(e,t=60){const r=e.build(),n=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:t}),o=await this.createTopic(n,!0,!0);this.logger.info(`Created new outbound topic ID: ${o}`);const i=this.client.operatorAccountId?.toString();if(!i)throw new Error("Failed to retrieve operator account ID");const a=await this.createInboundTopic(i,r.inboundTopicType,t,r.inboundTopicType===InboundTopicType.FEE_BASED?r.feeConfig:void 0);let s=r.existingPfpTopicId||"";if(!s&&r.pfpBuffer&&r.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(r.pfpBuffer,r.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else r.existingPfpTopicId&&this.logger.info(`Using existing profile picture with topic ID: ${r.existingPfpTopicId}`);const c=(await this.storeHCS11Profile(r.name,r.description,a,o,r.capabilities,r.metadata,r.pfpBuffer&&r.pfpBuffer.length>0?r.pfpBuffer:void 0,r.pfpFileName,r.existingPfpTopicId)).profileTopicId;return this.logger.info(`Profile stored with topic ID: ${c}`),{inboundTopicId:a,outboundTopicId:o,pfpTopicId:s,profileTopicId:c}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(r){return this.logger.error(`Error inscribing profile picture: ${r.message}`),{pfpTopicId:"",transactionId:"",success:!1,error:r.message}}}async storeHCS11Profile(e,t,r,n,o=[],i,a,s,c){try{let u=c||"";if(!u&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);e.success?u=e.pfpTopicId:this.logger.error("Failed to inscribe profile picture, continuing without PFP")}else c&&this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`);const l=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"}),d=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:"x"===e?"twitter":e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:i.properties,inboundTopicId:r,outboundTopicId:n,creator:i.creator}),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){return this.logger.error(`Error storing HCS-11 profile: ${u.message}`),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:u.message}}}async setupFees(e,t,r=[]){if(!this.client.operatorPublicKey)return;this.logger.info("Setting up topic with custom fees");const n=(new l$1).setAmount(Number(t.feeAmount.amount)).setFeeCollectorAccountId(f.fromString(t.feeCollectorAccountId));let o=[...t.exemptAccounts||[],...r];if(console.log("exemptAccountIds",o),o.length>0){const t=Array.from(new Set(o)).filter((e=>e!==this.client.operatorAccountId?.toString()));let r=[];if(t.length>0)try{r=await accountIdsToExemptKeys(t,this.network,this.logger)}catch(i){this.logger.warn(`Error getting exempt keys: ${i}, continuing without exempt keys`)}r.length>0&&e.setFeeExemptKeys(r)}e.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees([n])}async handleConnectionRequest(e,t,r,n,o=60){const i=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r});this.logger.info(`Handling connection request ${r} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let s=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(a);if(!c)throw new Error("Failed to retrieve public key");const u=new s$7([c,s],1);let l;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};l=await this.createTopic(i,u,u,t)}else l=await this.createTopic(i,u,u);this.logger.info(`Created new connection topic ID: ${l}`)}catch(p){throw this.logger.error(`Failed to create connection topic: ${p}`),new TopicCreationError(`Failed to create connection topic: ${p}`)}const d=`${e}@${a}`;return{connectionTopicId:l,confirmedConnectionSequenceNumber:await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),operatorId:d}}async confirmConnection(e,t,r,n,o,i){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new ConnectionConfirmationError("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),i={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=JSON.stringify(i);if(Buffer.from(a).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);if(!n?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.topic_id}`)}catch(s){throw this.logger.error("Error inscribing large message:",s),new Error(`Failed to handle large message: ${s instanceof Error?s.message:"Unknown error"}`)}}return this.logger.info("Submitting message to connection topic",i),await this.submitPayload(e,i,n,o.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const o=(new m$1).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(o.setAdminKey(this.client.operatorPublicKey),o.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$7||t instanceof s$7)&&(o.setAdminKey(t),this.client.operatorAccountId&&o.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?o.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$7||r instanceof s$7)&&o.setSubmitKey(r)),n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const i=await o.execute(this.client),a=await i.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,r,n=!1){const o="string"==typeof t?t:JSON.stringify(t),i=Buffer.byteLength(o,"utf8");if(i>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",i);const a=(new u).setTopicId(m$2.fromString(e)).setMessage(o);let s;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new e$7(this.feeAmount)),a.setTransactionMemo("HIP-991 Fee Payment")),r){const e=a.freezeWith(this.client),t=await e.sign(r);s=await t.execute(this.client)}else s=await a.execute(this.client);const c=await s.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r.accountId)throw new Error("Operator account ID is not set");const n=await this.getOperatorId(),o=r.accountId,i=await this.canSubmitToTopic(e,o);if(!i.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const a={p:"hcs-10",op:"connection_request",operator_id:n,m:t},s=i.requiresFee,c=await this.submitPayload(e,a,void 0,s);this.logger.info(`Submitted connection request to topic ID: ${e}`);const u=await this.retrieveOutboundConnectTopic(o),l=c.topicSequenceNumber?.toNumber();if(!l)throw new Error("Failed to get response sequence number");return await this.submitPayload(u.outboundTopic,{...a,outbound_topic_id:u.outboundTopic,connection_request_id:l}),c}async inscribeFile(e,t){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 r=mimeTypesExports.lookup(t)||"application/octet-stream",n=await InscriptionSDK.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),o=await n.inscribeAndExecute({file:{type:"base64",base64:e.toString("base64"),fileName:t,mimeType:r},holderId:this.client.operatorAccountId.toString(),mode:"file",network:this.network},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network});if(!o.transactionId||!o.jobId)throw this.logger.error("Failed to inscribe, no transaction ID or job ID."),new Error("Failed to inscribe, no transaction ID or job ID.");o.transactionId&&o.jobId&&this.logger.info(`Transaction ID: ${o.transactionId}, Job ID: ${o.jobId}`);return await n.waitForInscription(o.jobId,30,4e3,!0)}async waitForConnectionConfirmation(e,t,r=60,n=2e3){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 i=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${i.length} connection_created messages`),i.length>0)for(const e of i)if(Number(e.connection_id)===Number(t))return this.logger.info("Connection confirmation found"),{connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m};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(){return{accountId:this.client.operatorAccountId.toString(),signer:this.operatorPrivateKey}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let i=t?.existingState||void 0;n&&n({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:i}});const a=r.existingAccount||await this.createAccount();n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:i,account:a}});const s=new HCS10Client({network:r.network,operatorId:a.accountId,operatorPrivateKey:a.privateKey,operatorPublicKey:y$2.fromString(a.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:o});n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:30,details:{state:i}});const{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=await s.createAgent(e);n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:i,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}});const p=`${u}@${a.accountId}`,h=await s.registerAgentWithGuardedRegistry(a.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:p,state:e.details?.state||i}})},existingState:i});return h.success?(n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:p,state:h.state}}),{...h,metadata:{accountId:a.accountId,privateKey:a.privateKey,operatorId:p,inboundTopicId:u,outboundTopicId:c,profileTopicId:d,pfpTopicId:l}}):h}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{error:r.message,success:!1}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,o=r?.delayMs??2e3,i=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};i&&i({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const s=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!s.success)return{...s,state:a};if(i&&i({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:s.transactionId,state:a}}),s.transaction){const e=S.fromBytes(Buffer.from(s.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}i&&i({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:s.transactionId,state:a}});const c=await this.waitForRegistrationConfirmation(s.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),i&&i({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:c,transactionId:s.transactionId,state:a}}),{...s,confirmed:c,state:a}}catch(n){return this.logger.error(`Failed to register agent: ${n.message}`),{error:n.message,success:!1}}}async registerAgent(e,t,r,n,o){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,i,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return InboundTopicType.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),InboundTopicType.FEE_BASED}return InboundTopicType.CONTROLLED}catch(t){throw this.logger.error(`Error determining topic type: ${t.message}`),new Error(`Failed to determine topic type: ${t.message}`)}}getNetwork(){return this.network}getLogger(){return this.logger}}class AgentBuilder{constructor(){this.config={}}setName(e){return this.config.name=e,this}setDescription(e){return this.config.description=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}setModel(e){return this.config.metadata?this.config.metadata.model=e:this.config.metadata={type:"autonomous",model:e},this}setCreator(e){return this.config.metadata?this.config.metadata.creator=e:this.config.metadata={type:"autonomous",creator:e},this}addSocial(e,t){return this.config.metadata?this.config.metadata.socials||(this.config.metadata.socials={}):this.config.metadata={type:"autonomous",socials:{}},this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata?this.config.metadata.properties||(this.config.metadata.properties={}):this.config.metadata={type:"autonomous",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 name is required");if(!this.config.description)throw new Error("Agent description is required");if(!this.config.pfpBuffer||!this.config.pfpFileName)throw new Error("Profile picture is required");if(!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:"autonomous"}),this.config.inboundTopicType===InboundTopicType.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}const isBrowser="undefined"!=typeof window;class BrowserHCSClient extends HCS10BaseClient{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount}),this.hcs11Client=null,this.hwc=e.hwc,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-Browser",prettyPrint:e.prettyPrint}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel})}catch(t){this.logger.warn(`Failed to initialize HCS11Client: ${t}`)}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){this.logger.info("Sending message");const o={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},i=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(o);if(Buffer.from(a).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);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(s){throw this.logger.error("Error inscribing large message:",s),new Error(`Failed to handle large message: ${s instanceof Error?s.message:"Unknown error"}`)}}return await this.submitPayload(e,o,n,i.requiresFee)}async submitConnectionRequest(e,t){this.logger.info("Submitting connection request");const r=this.getAccountAndSigner();if(!r.accountId)throw new Error("Failed to retrieve user account ID");const n=await this.getOperatorId(),o=r.accountId,i={p:"hcs-10",op:"connection_request",operator_id:n,m:t},a=await this.submitPayload(e,i);this.logger.info(`Submitted connection request to topic ID: ${e}`);const s=await this.retrieveOutboundConnectTopic(o);if(!s?.outboundTopic)throw this.logger.error(`Failed to retrieve outbound topic for account ID: ${o}`),new Error(`Failed to retrieve outbound topic for account ID: ${o}`);this.logger.info(`Retrieved outbound topic ID: ${s.outboundTopic} for account ID: ${o}`);const c=a?.topicSequenceNumber?.toNumber();if(!c)throw new Error("Failed to get response sequence number");return await this.submitPayload(s.outboundTopic,{...i,outbound_topic_id:e,connection_request_id:c}),a}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const i=this.hwc.getAccountInfo().accountId;if(!i)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(i);if(!s)throw new Error("Failed to retrieve public key");const c=new s$7([s,a],1),u=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r}),l=(new m$1).setTopicMemo(u).setAdminKey(c).setSubmitKey(c);this.logger.debug("Executing topic creation transaction");const d=await this.hwc.executeTransactionWithErrorHandling(l,!1);if(d.error)throw this.logger.error(d.error),new Error(d.error);const p=d.result;if(!p?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const h=p.topicId.toString(),f=`${e}@${i}`;return{connectionTopicId:h,confirmedConnectionSequenceNumber:await this.confirmConnection(e,h,t,r,f,n),operatorId:f}}async confirmConnection(e,t,r,n,o,i){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:n,m:i},s=await this.submitPayload(e,a);if(!s?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return s.topicSequenceNumber.toNumber()}async createAgent(e,t,r,n,o,i,a,s){try{const c=s?.progressCallback,u=new ProgressReporter({module:"AgentCreate",logger:this.logger,callback:c});let l=s?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(l.outboundTopicId)u.preparing("Using existing outbound topic",20,{state:l});else{l.currentStage="topics",u.preparing("Creating agent outbound topic",0,{state:l});const e=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:s?.ttl}),t=await this.createTopic(e,!0,!0);if(!t.success||!t.topicId)return l.error=t.error||"Failed to create outbound topic",u.failed(`Failed to create outbound topic: ${l.error}`,{state:l}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.outboundTopicId=t.topicId,l.createdResources&&l.createdResources.push(`outbound:${l.outboundTopicId}`),u.preparing("Outbound topic created",20,{state:l})}const d=this.hwc.getAccountInfo().accountId;if(!d)throw new Error("Failed to retrieve user account ID");if(l.inboundTopicId)u.preparing("Using existing inbound topic",40,{state:l});else{const e=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:d,ttl:s?.ttl}),t=await this.createTopic(e,!0,!0);if(!t.success||!t.topicId)return l.error=t.error||"Failed to create inbound topic",u.failed(`Failed to create inbound topic: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.inboundTopicId=t.topicId,l.createdResources&&l.createdResources.push(`inbound:${l.inboundTopicId}`),u.preparing("Inbound topic created",40,{state:l})}if(l.pfpTopicId||a)l.pfpTopicId=a||l.pfpTopicId,u.preparing(`Using existing profile picture: ${l.pfpTopicId}`,60,{state:l});else{l.currentStage="pfp",u.preparing("Creating agent profile picture",40,{state:l});const r=u.createSubProgress({minPercent:40,maxPercent:60,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>{r.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:l}})}});if(!n.success)return l.error=n.error||"Failed to inscribe profile picture",u.failed(`Failed to inscribe profile picture: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.pfpTopicId=n.pfpTopicId,l.completedPercentage=60,l.createdResources&&l.createdResources.push(`pfp:${l.pfpTopicId}`),u.preparing("Profile picture created",60,{state:l})}if(l.profileTopicId)u.preparing("Using existing agent profile",100,{state:l}),"complete"!==l.currentStage&&(l.currentStage="complete",l.completedPercentage=100);else{l.currentStage="profile",u.preparing("Creating agent profile",60,{state:l});const e=u.createSubProgress({minPercent:60,maxPercent:100,logPrefix:"Profile"});if(!this.hcs11Client)return l.error="HCS11Client is not available in this environment",u.failed(l.error,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:"",success:!1,error:l.error,state:l};const t=await this.storeHCS11Profile(r,n,l.inboundTopicId,l.outboundTopicId,o,i,void 0,void 0,l.pfpTopicId,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:{...t.details,state:l}})}});if(!t.success)return l.error=t.error||"Failed to store agent profile",u.failed(`Failed to store agent profile: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:"",success:!1,error:l.error,state:l};l.profileTopicId=t.profileTopicId,l.createdResources&&l.createdResources.push(`profile:${l.profileTopicId}`),l.currentStage="complete",l.completedPercentage=100}return u.completed("Agent successfully created",{inboundTopicId:l.inboundTopicId,outboundTopicId:l.outboundTopicId,pfpTopicId:l.pfpTopicId,profileTopicId:l.profileTopicId,state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:l.profileTopicId||"",success:!0,state:l}}catch(c){return this.logger.error(`Error creating agent: ${c.message}`),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:`Error creating agent: ${c.message}`,state:{currentStage:"init",completedPercentage:0,error:c.message}}}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,o=this.initializeRegistrationState(n,r?.existingState),i=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});i.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:o};if(i.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=S.fromBytes(Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:o};this.logger.info("Successfully processed registration transaction")}i.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const s=r?.maxAttempts??60,c=r?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,s,c,this.logger);return this.updateStateForCompletedRegistration(o,n),i.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:i}),"complete"!==i.currentStage||!i.inboundTopicId||!i.outboundTopicId||!i.profileTopicId){const e=await this.createAgent(r.pfpBuffer||Buffer.from([]),r.pfpFileName||"default.png",r.name,r.description,r.capabilities,r.metadata,r.existingPfpTopicId,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},existingState:i});if(!e.success)throw new Error(e.error||"Failed to create agent with topics");i=e.state,i.agentMetadata=r.metadata}o.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:a}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:i});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");i=e.state}return o.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:a,operatorId:`${i.inboundTopicId}@${a}`,inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,profileTopicId:i.profileTopicId,pfpTopicId:i.pfpTopicId,privateKey:null,...i.agentMetadata}}}catch(r){throw new Error(`Failed to create and register agent: ${r.message}`)}}async storeHCS11Profile(e,t,r,n,o=[],i={},a,s,c,u){try{const l=u?.progressCallback,d=new ProgressReporter({module:"StoreHCS11Profile",logger:this.logger,callback:l});d.preparing("Preparing agent profile data",0);let 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);const h=this.hcs11Client?.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const f=[];if(i.socials&&(i.socials.twitter&&f.push({platform:"twitter",handle:i.socials.twitter}),i.socials.discord&&f.push({platform:"discord",handle:i.socials.discord}),i.socials.github&&f.push({platform:"github",handle:i.socials.github}),i.socials.website&&f.push({platform:"website",handle:i.socials.website}),i.socials.x&&f.push({platform:"twitter",handle:i.socials.x}),i.socials.linkedin&&f.push({platform:"linkedin",handle:i.socials.linkedin}),i.socials.youtube&&f.push({platform:"youtube",handle:i.socials.youtube}),i.socials.telegram&&f.push({platform:"telegram",handle:i.socials.telegram})),!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 m=this.hcs11Client.createAIAgentProfile(e,h,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:f.length>0?f:void 0,properties:{description:t,version:i.version||"1.0.0",creator:i.creator||"Unknown",supported_languages:i.supported_languages||["en"],permissions:i.permissions||[],model_details:i.model_details,training:i.training,capabilities_description:i.capabilities_description,...i},inboundTopicId:r,outboundTopicId:n,creator:i.creator}),y=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),g=await this.hcs11Client.createAndInscribeProfile(m,!0,{progressCallback:e=>{y.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return g.success?(d.completed("Profile stored successfully",{profileTopicId:g.profileTopicId}),{profileTopicId:g.profileTopicId,pfpTopicId:p,success:!0,transactionId:g.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:g.error||"Failed to inscribe profile",transactionId:g.transactionId||""})}catch(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),i=(new m$1).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(i.setAdminKey(a),i.setAutoRenewAccountId(n)),r&&a&&i.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(i,!1),c=s.error;if(c)return this.logger.error(c),{success:!1,error:c};const u=s.result;return u?.topicId?{success:!0,topicId:u.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,r,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(e).setMessage(o);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount)),i.setTransactionMemo("HIP-991 Fee Payment")),r){const{accountId:e,signer:t}=this.getAccountAndSigner();i.freezeWithSigner(t);const n=await i.sign(r);a=await this.hwc.executeTransactionWithErrorHandling(n,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(a?.error)throw this.logger.error(`Failed to submit payload: ${a.error}`),new Error(`Failed to submit payload: ${a.error}`);if(!a?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),a.result}async inscribeFile(e,t){const{accountId:r,signer:n}=this.getAccountAndSigner(),o=mimeTypesExports.lookup(t)||"application/octet-stream",i=await InscriptionSDK.createWithAuth({type:"client",accountId:r,signer:n,network:this.network}),a=await i.inscribe({file:{type:"base64",base64:e.toString("base64"),fileName:t,mimeType:o},holderId:r.toString(),mode:"file",network:this.network},n);if(!a.transactionId||!a.jobId)throw this.logger.error("Failed to inscribe, no transaction ID or job ID."),new Error("Failed to inscribe, no transaction ID or job ID.");a.transactionId&&a.jobId&&this.logger.info(`Transaction ID: ${a.transactionId}, Job ID: ${a.jobId}`);return await i.waitForInscription(a.jobId,30,4e3,!0)}getAccountAndSigner(){const e=this.hwc.getAccountInfo().accountId.toString(),t=this.hwc.dAppConnector.signers.find((t=>t.getAccountId().toString()===e));if(!t)throw this.logger.error("Failed to find signer"),new Error("Failed to find signer");return{accountId:e,signer:t}}async inscribePfp(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},a=await this.hcs11Client.inscribeImage(e,t,{progressCallback:i});return a.success?(o.completed("Successfully inscribed profile picture",{pfpTopicId:a.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${a.imageTopicId}`),{pfpTopicId:a.imageTopicId,success:!0,transactionId:a.transactionId||""}):(o.failed(`Failed to inscribe profile picture: ${a.error}`),this.logger.error(`Failed to inscribe profile picture: ${a.error}`),{pfpTopicId:"",success:!1,error:a.error||"Failed to inscribe profile picture",transactionId:a.transactionId||""})}catch(n){return this.logger.error(`Error inscribing profile picture: ${n.message}`),{pfpTopicId:"",success:!1,error:n.message,transactionId:""}}}}exports.AIAgentCapability=AIAgentCapability,exports.AIAgentType=AIAgentType,exports.AccountCreationError=AccountCreationError,exports.AgentBuilder=AgentBuilder,exports.BrowserHCSClient=BrowserHCSClient,exports.ConnectionConfirmationError=ConnectionConfirmationError,exports.EVMBridge=EVMBridge,exports.EndpointType=EndpointType,exports.FeeConfigBuilder=FeeConfigBuilder,exports.HCS=HCS,exports.HCS10BaseClient=HCS10BaseClient,exports.HCS10Cache=HCS10Cache,exports.HCS10Client=HCS10Client,exports.HCS11Client=HCS11Client,exports.Hcs10MemoType=Hcs10MemoType,exports.HederaMirrorNode=HederaMirrorNode,exports.InboundTopicType=InboundTopicType,exports.Logger=Logger$2,exports.PayloadSizeError=PayloadSizeError,exports.ProfileType=ProfileType,exports.ProgressReporter=ProgressReporter,exports.Registration=Registration,exports.SUPPORTED_SOCIAL_PLATFORMS=SUPPORTED_SOCIAL_PLATFORMS,exports.TopicCreationError=TopicCreationError,exports.WasmBridge=WasmBridge,exports.accountIdsToExemptKeys=accountIdsToExemptKeys,exports.capabilityNameToCapabilityMap=capabilityNameToCapabilityMap,exports.inscribe=inscribe,exports.inscribeWithSigner=inscribeWithSigner,exports.retrieveInscription=retrieveInscription,exports.sleep=sleep$1,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
133
+ */function requireMimeTypes(){return hasRequiredMimeTypes||(hasRequiredMimeTypes=1,function(e){var t,r,n,o=requireMimeDb(),i=requirePathBrowserify().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),r=t&&o[t[1].toLowerCase()];return r&&r.charset?r.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var r=-1===t.indexOf("/")?e.lookup(t):t;if(!r)return!1;if(-1===r.indexOf("charset")){var n=e.charset(r);n&&(r+="; charset="+n.toLowerCase())}return r},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var r=a.exec(t),n=r&&e.extensions[r[1].toLowerCase()];if(!n||!n.length)return!1;return n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var r=i("x."+t).toLowerCase().substr(1);if(!r)return!1;return e.types[r]||!1},e.types=Object.create(null),t=e.extensions,r=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach((function(e){var i=o[e],a=i.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(r[c]){var u=n.indexOf(o[r[c]].source),l=n.indexOf(i.source);if("application/octet-stream"!==r[c]&&(u>l||u===l&&"application/"===r[c].substr(0,12)))continue}r[c]=e}}}))}(mimeTypes)),mimeTypes}var mimeTypesExports=requireMimeTypes(),util,util2,objectUtil,objectUtil2;util2=util||(util={}),util2.assertEqual=e=>e,util2.assertIs=function(e){},util2.assertNever=function(e){throw new Error},util2.arrayToEnum=e=>{const t={};for(const r of e)t[r]=r;return t},util2.getValidEnumValues=e=>{const t=util2.objectKeys(e).filter((t=>"number"!=typeof e[e[t]])),r={};for(const n of t)r[n]=e[n];return util2.objectValues(r)},util2.objectValues=e=>util2.objectKeys(e).map((function(t){return e[t]})),util2.objectKeys="function"==typeof Object.keys?e=>Object.keys(e):e=>{const t=[];for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},util2.find=(e,t)=>{for(const r of e)if(t(r))return r},util2.isInteger="function"==typeof Number.isInteger?e=>Number.isInteger(e):e=>"number"==typeof e&&isFinite(e)&&Math.floor(e)===e,util2.joinValues=function(e,t=" | "){return e.map((e=>"string"==typeof e?`'${e}'`:e)).join(t)},util2.jsonStringifyReplacer=(e,t)=>"bigint"==typeof t?t.toString():t,objectUtil2=objectUtil||(objectUtil={}),objectUtil2.mergeShapes=(e,t)=>({...e,...t});const ZodParsedType=util.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),getParsedType=e=>{switch(typeof e){case"undefined":return ZodParsedType.undefined;case"string":return ZodParsedType.string;case"number":return isNaN(e)?ZodParsedType.nan:ZodParsedType.number;case"boolean":return ZodParsedType.boolean;case"function":return ZodParsedType.function;case"bigint":return ZodParsedType.bigint;case"symbol":return ZodParsedType.symbol;case"object":return Array.isArray(e)?ZodParsedType.array:null===e?ZodParsedType.null:e.then&&"function"==typeof e.then&&e.catch&&"function"==typeof e.catch?ZodParsedType.promise:"undefined"!=typeof Map&&e instanceof Map?ZodParsedType.map:"undefined"!=typeof Set&&e instanceof Set?ZodParsedType.set:"undefined"!=typeof Date&&e instanceof Date?ZodParsedType.date:ZodParsedType.object;default:return ZodParsedType.unknown}},ZodIssueCode=util.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),quotelessJson=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:");class ZodError extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(e){return e.message},r={_errors:[]},n=e=>{for(const o of e.issues)if("invalid_union"===o.code)o.unionErrors.map(n);else if("invalid_return_type"===o.code)n(o.returnTypeError);else if("invalid_arguments"===o.code)n(o.argumentsError);else if(0===o.path.length)r._errors.push(t(o));else{let e=r,n=0;for(;n<o.path.length;){const r=o.path[n];n===o.path.length-1?(e[r]=e[r]||{_errors:[]},e[r]._errors.push(t(o))):e[r]=e[r]||{_errors:[]},e=e[r],n++}}};return n(this),r}static assert(e){if(!(e instanceof ZodError))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,util.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.jsonStringifyReplacer)}`;break;case ZodIssueCode.unrecognized_keys:r=`Unrecognized key(s) in object: ${util.joinValues(e.keys,", ")}`;break;case ZodIssueCode.invalid_union:r="Invalid input";break;case ZodIssueCode.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${util.joinValues(e.options)}`;break;case ZodIssueCode.invalid_enum_value:r=`Invalid enum value. Expected ${util.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.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.assertNever(e)}return{message:r}};let overrideErrorMap=errorMap;function setErrorMap(e){overrideErrorMap=e}function getErrorMap(){return overrideErrorMap}const makeIssue=e=>{const{data:t,path:r,errorMaps:n,issueData:o}=e,i=[...r,...o.path||[]],a={...o,path:i};if(void 0!==o.message)return{...o,path:i,message:o.message};let s="";const c=n.filter((e=>!!e)).slice().reverse();for(const u of c)s=u(a,{data:t,defaultError:s}).message;return{...o,path:i,message:s}},EMPTY_PATH=[];function addIssueToContext(e,t){const r=getErrorMap(),n=makeIssue({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===errorMap?void 0:errorMap].filter((e=>!!e))});e.common.issues.push(n)}class ParseStatus{constructor(){this.value="valid"}dirty(){"valid"===this.value&&(this.value="dirty")}abort(){"aborted"!==this.value&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const n of t){if("aborted"===n.status)return INVALID;"dirty"===n.status&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const n of t){const e=await n.key,t=await n.value;r.push({key:e,value:t})}return ParseStatus.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const n of t){const{key:t,value:o}=n;if("aborted"===t.status)return INVALID;if("aborted"===o.status)return INVALID;"dirty"===t.status&&e.dirty(),"dirty"===o.status&&e.dirty(),"__proto__"===t.value||void 0===o.value&&!n.alwaysSet||(r[t.value]=o.value)}return{status:e.value,value:r}}}const INVALID=Object.freeze({status:"aborted"}),DIRTY=e=>({status:"dirty",value:e}),OK=e=>({status:"valid",value:e}),isAborted=e=>"aborted"===e.status,isDirty=e=>"dirty"===e.status,isValid=e=>"valid"===e.status,isAsync=e=>"undefined"!=typeof Promise&&e instanceof Promise;function __classPrivateFieldGet(e,t,r,n){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(e)}function __classPrivateFieldSet(e,t,r,n,o){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,r),r}var errorUtil,errorUtil2,_ZodEnum_cache,_ZodNativeEnum_cache;"function"==typeof SuppressedError&&SuppressedError,errorUtil2=errorUtil||(errorUtil={}),errorUtil2.errToObj=e=>"string"==typeof e?{message:e}:e||{},errorUtil2.toString=e=>"string"==typeof e?e:null==e?void 0:e.message;class ParseInputLazyPath{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const handleResult=(e,t)=>{if(isValid(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ZodError(e.common.issues);return this._error=t,this._error}}};function processCreateParams(e){if(!e)return{};const{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');if(t)return{errorMap:t,description:o};return{errorMap:(t,o)=>{var i,a;const{message:s}=e;return"invalid_enum_value"===t.code?{message:null!=s?s:o.defaultError}:void 0===o.data?{message:null!==(i=null!=s?s:n)&&void 0!==i?i:o.defaultError}:"invalid_type"!==t.code?{message:o.defaultError}:{message:null!==(a=null!=s?s:r)&&void 0!==a?a:o.defaultError}},description:o}}class ZodType{get description(){return this._def.description}_getType(e){return getParsedType(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ParseStatus,ctx:{common:e.parent.common,data:e.data,parsedType:getParsedType(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(isAsync(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;const n={common:{issues:[],async:null!==(r=null==t?void 0:t.async)&&void 0!==r&&r,contextualErrorMap:null==t?void 0:t.errorMap},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},o=this._parseSync({data:e,path:n.path,parent:n});return handleResult(n,o)}"~validate"(e){var t,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)};if(!this["~standard"].async)try{const t=this._parseSync({data:e,path:[],parent:n});return isValid(t)?{value:t.value}:{issues:n.common.issues}}catch(o){(null===(r=null===(t=null==o?void 0:o.message)||void 0===t?void 0:t.toLowerCase())||void 0===r?void 0:r.includes("encountered"))&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then((e=>isValid(e)?{value:e.value}:{issues:n.common.issues}))}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:null==t?void 0:t.errorMap,async:!0},path:(null==t?void 0:t.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:getParsedType(e)},n=this._parse({data:e,path:r.path,parent:r}),o=await(isAsync(n)?n:Promise.resolve(n));return handleResult(r,o)}refine(e,t){const r=e=>"string"==typeof t||void 0===t?{message:t}:"function"==typeof t?t(e):t;return this._refinement(((t,n)=>{const o=e(t),i=()=>n.addIssue({code:ZodIssueCode.custom,...r(t)});return"undefined"!=typeof Promise&&o instanceof Promise?o.then((e=>!!e||(i(),!1))):!!o||(i(),!1)}))}refinement(e,t){return this._refinement(((r,n)=>!!e(r)||(n.addIssue("function"==typeof t?t(r,n):t),!1)))}_refinement(e){return new ZodEffects({schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return ZodOptional.create(this,this._def)}nullable(){return ZodNullable.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ZodArray.create(this)}promise(){return ZodPromise.create(this,this._def)}or(e){return ZodUnion.create([this,e],this._def)}and(e){return ZodIntersection.create(this,e,this._def)}transform(e){return new ZodEffects({...processCreateParams(this._def),schema:this,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t="function"==typeof e?e:()=>e;return new ZodDefault({...processCreateParams(this._def),innerType:this,defaultValue:t,typeName:ZodFirstPartyTypeKind.ZodDefault})}brand(){return new ZodBranded({typeName:ZodFirstPartyTypeKind.ZodBranded,type:this,...processCreateParams(this._def)})}catch(e){const t="function"==typeof e?e:()=>e;return new ZodCatch({...processCreateParams(this._def),innerType:this,catchValue:t,typeName:ZodFirstPartyTypeKind.ZodCatch})}describe(e){return new(0,this.constructor)({...this._def,description:e})}pipe(e){return ZodPipeline.create(this,e)}readonly(){return ZodReadonly.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const cuidRegex=/^c[^\s-]{8,}$/i,cuid2Regex=/^[0-9a-z]+$/,ulidRegex=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uuidRegex=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,nanoidRegex=/^[a-z0-9_-]{21}$/i,jwtRegex=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,durationRegex=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,emailRegex=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,_emojiRegex="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let emojiRegex;const ipv4Regex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4CidrRegex=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6Regex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ipv6CidrRegex=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64Regex=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64urlRegex=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dateRegexSource="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dateRegex=new RegExp(`^${dateRegexSource}$`);function timeRegexSource(e){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return e.precision?t=`${t}\\.\\d{${e.precision}}`:null==e.precision&&(t=`${t}(\\.\\d+)?`),t}function timeRegex(e){return new RegExp(`^${timeRegexSource(e)}$`)}function datetimeRegex(e){let t=`${dateRegexSource}T${timeRegexSource(e)}`;const r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function isValidIP(e,t){return!("v4"!==t&&t||!ipv4Regex.test(e))||!("v6"!==t&&t||!ipv6Regex.test(e))}function isValidJWT(e,t){if(!jwtRegex.test(e))return!1;try{const[r]=e.split("."),n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return"object"==typeof o&&null!==o&&(!(!o.typ||!o.alg)&&(!t||o.alg===t))}catch(r){return!1}}function isValidCidr(e,t){return!("v4"!==t&&t||!ipv4CidrRegex.test(e))||!("v6"!==t&&t||!ipv6CidrRegex.test(e))}class ZodString extends ZodType{_parse(e){this._def.coerce&&(e.data=String(e.data));if(this._getType(e)!==ZodParsedType.string){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.string,received:t.parsedType}),INVALID}const t=new ParseStatus;let r;for(const o of this._def.checks)if("min"===o.kind)e.data.length<o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("max"===o.kind)e.data.length>o.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),t.dirty());else if("length"===o.kind){const n=e.data.length>o.value,i=e.data.length<o.value;(n||i)&&(r=this._getOrReturnCtx(e,r),n?addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),t.dirty())}else if("email"===o.kind)emailRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"email",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("emoji"===o.kind)emojiRegex||(emojiRegex=new RegExp(_emojiRegex,"u")),emojiRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"emoji",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("uuid"===o.kind)uuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"uuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("nanoid"===o.kind)nanoidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"nanoid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid"===o.kind)cuidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("cuid2"===o.kind)cuid2Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cuid2",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("ulid"===o.kind)ulidRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ulid",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty());else if("url"===o.kind)try{new URL(e.data)}catch(n){r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()}else if("regex"===o.kind){o.regex.lastIndex=0;o.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"regex",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty())}else if("trim"===o.kind)e.data=e.data.trim();else if("includes"===o.kind)e.data.includes(o.value,o.position)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),t.dirty());else if("toLowerCase"===o.kind)e.data=e.data.toLowerCase();else if("toUpperCase"===o.kind)e.data=e.data.toUpperCase();else if("startsWith"===o.kind)e.data.startsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{startsWith:o.value},message:o.message}),t.dirty());else if("endsWith"===o.kind)e.data.endsWith(o.value)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:{endsWith:o.value},message:o.message}),t.dirty());else if("datetime"===o.kind){datetimeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"datetime",message:o.message}),t.dirty())}else if("date"===o.kind){dateRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"date",message:o.message}),t.dirty())}else if("time"===o.kind){timeRegex(o).test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.invalid_string,validation:"time",message:o.message}),t.dirty())}else"duration"===o.kind?durationRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"duration",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"ip"===o.kind?isValidIP(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"ip",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"jwt"===o.kind?isValidJWT(e.data,o.alg)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"jwt",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"cidr"===o.kind?isValidCidr(e.data,o.version)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"cidr",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64"===o.kind?base64Regex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):"base64url"===o.kind?base64urlRegex.test(e.data)||(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{validation:"base64url",code:ZodIssueCode.invalid_string,message:o.message}),t.dirty()):util.assertNever(o);return{status:t.value,value:e.data}}_regex(e,t,r){return this.refinement((t=>e.test(t)),{validation:t,code:ZodIssueCode.invalid_string,...errorUtil.errToObj(r)})}_addCheck(e){return new ZodString({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...errorUtil.errToObj(e)})}url(e){return this._addCheck({kind:"url",...errorUtil.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...errorUtil.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...errorUtil.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...errorUtil.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...errorUtil.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...errorUtil.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...errorUtil.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...errorUtil.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...errorUtil.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...errorUtil.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...errorUtil.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...errorUtil.errToObj(e)})}datetime(e){var t,r;return"string"==typeof e?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,offset:null!==(t=null==e?void 0:e.offset)&&void 0!==t&&t,local:null!==(r=null==e?void 0:e.local)&&void 0!==r&&r,...errorUtil.errToObj(null==e?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return"string"==typeof e?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:void 0===(null==e?void 0:e.precision)?null:null==e?void 0:e.precision,...errorUtil.errToObj(null==e?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...errorUtil.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...errorUtil.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:null==t?void 0:t.position,...errorUtil.errToObj(null==t?void 0:t.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...errorUtil.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...errorUtil.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...errorUtil.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...errorUtil.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...errorUtil.errToObj(t)})}nonempty(e){return this.min(1,errorUtil.errToObj(e))}trim(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ZodString({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e=>"datetime"===e.kind))}get isDate(){return!!this._def.checks.find((e=>"date"===e.kind))}get isTime(){return!!this._def.checks.find((e=>"time"===e.kind))}get isDuration(){return!!this._def.checks.find((e=>"duration"===e.kind))}get isEmail(){return!!this._def.checks.find((e=>"email"===e.kind))}get isURL(){return!!this._def.checks.find((e=>"url"===e.kind))}get isEmoji(){return!!this._def.checks.find((e=>"emoji"===e.kind))}get isUUID(){return!!this._def.checks.find((e=>"uuid"===e.kind))}get isNANOID(){return!!this._def.checks.find((e=>"nanoid"===e.kind))}get isCUID(){return!!this._def.checks.find((e=>"cuid"===e.kind))}get isCUID2(){return!!this._def.checks.find((e=>"cuid2"===e.kind))}get isULID(){return!!this._def.checks.find((e=>"ulid"===e.kind))}get isIP(){return!!this._def.checks.find((e=>"ip"===e.kind))}get isCIDR(){return!!this._def.checks.find((e=>"cidr"===e.kind))}get isBase64(){return!!this._def.checks.find((e=>"base64"===e.kind))}get isBase64url(){return!!this._def.checks.find((e=>"base64url"===e.kind))}get minLength(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}function floatSafeRemainder(e,t){const r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n;return parseInt(e.toFixed(o).replace(".",""))%parseInt(t.toFixed(o).replace(".",""))/Math.pow(10,o)}ZodString.create=e=>{var t;return new ZodString({checks:[],typeName:ZodFirstPartyTypeKind.ZodString,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodNumber extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){this._def.coerce&&(e.data=Number(e.data));if(this._getType(e)!==ZodParsedType.number){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.number,received:t.parsedType}),INVALID}let t;const r=new ParseStatus;for(const n of this._def.checks)if("int"===n.kind)util.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.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.isInteger(e.value)))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if("finite"===r.kind||"int"===r.kind||"multipleOf"===r.kind)return!0;"min"===r.kind?(null===t||r.value>t)&&(t=r.value):"max"===r.kind&&(null===e||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}ZodNumber.create=e=>new ZodNumber({checks:[],typeName:ZodFirstPartyTypeKind.ZodNumber,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodBigInt extends ZodType{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch(n){return this._getInvalidInput(e)}if(this._getType(e)!==ZodParsedType.bigint)return this._getInvalidInput(e);let t;const r=new ParseStatus;for(const o of this._def.checks)if("min"===o.kind){(o.inclusive?e.data<o.value:e.data<=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else if("max"===o.kind){(o.inclusive?e.data>o.value:e.data>=o.value)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty())}else"multipleOf"===o.kind?e.data%o.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),addIssueToContext(t,{code:ZodIssueCode.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()):util.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.bigint,received:t.parsedType}),INVALID}gte(e,t){return this.setLimit("min",e,!0,errorUtil.toString(t))}gt(e,t){return this.setLimit("min",e,!1,errorUtil.toString(t))}lte(e,t){return this.setLimit("max",e,!0,errorUtil.toString(t))}lt(e,t){return this.setLimit("max",e,!1,errorUtil.toString(t))}setLimit(e,t,r,n){return new ZodBigInt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:errorUtil.toString(n)}]})}_addCheck(e){return new ZodBigInt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:errorUtil.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:errorUtil.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:errorUtil.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return e}}ZodBigInt.create=e=>{var t;return new ZodBigInt({checks:[],typeName:ZodFirstPartyTypeKind.ZodBigInt,coerce:null!==(t=null==e?void 0:e.coerce)&&void 0!==t&&t,...processCreateParams(e)})};class ZodBoolean extends ZodType{_parse(e){this._def.coerce&&(e.data=Boolean(e.data));if(this._getType(e)!==ZodParsedType.boolean){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.boolean,received:t.parsedType}),INVALID}return OK(e.data)}}ZodBoolean.create=e=>new ZodBoolean({typeName:ZodFirstPartyTypeKind.ZodBoolean,coerce:(null==e?void 0:e.coerce)||!1,...processCreateParams(e)});class ZodDate extends ZodType{_parse(e){this._def.coerce&&(e.data=new Date(e.data));if(this._getType(e)!==ZodParsedType.date){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.date,received:t.parsedType}),INVALID}if(isNaN(e.data.getTime())){return addIssueToContext(this._getOrReturnCtx(e),{code:ZodIssueCode.invalid_date}),INVALID}const t=new ParseStatus;let r;for(const n of this._def.checks)"min"===n.kind?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),t.dirty()):"max"===n.kind?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),addIssueToContext(r,{code:ZodIssueCode.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),t.dirty()):util.assertNever(n);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ZodDate({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:errorUtil.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:errorUtil.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)"min"===t.kind&&(null===e||t.value>e)&&(e=t.value);return null!=e?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)"max"===t.kind&&(null===e||t.value<e)&&(e=t.value);return null!=e?new Date(e):null}}ZodDate.create=e=>new ZodDate({checks:[],coerce:(null==e?void 0:e.coerce)||!1,typeName:ZodFirstPartyTypeKind.ZodDate,...processCreateParams(e)});class ZodSymbol extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.symbol){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.symbol,received:t.parsedType}),INVALID}return OK(e.data)}}ZodSymbol.create=e=>new ZodSymbol({typeName:ZodFirstPartyTypeKind.ZodSymbol,...processCreateParams(e)});class ZodUndefined extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.undefined,received:t.parsedType}),INVALID}return OK(e.data)}}ZodUndefined.create=e=>new ZodUndefined({typeName:ZodFirstPartyTypeKind.ZodUndefined,...processCreateParams(e)});class ZodNull extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.null){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.null,received:t.parsedType}),INVALID}return OK(e.data)}}ZodNull.create=e=>new ZodNull({typeName:ZodFirstPartyTypeKind.ZodNull,...processCreateParams(e)});class ZodAny extends ZodType{constructor(){super(...arguments),this._any=!0}_parse(e){return OK(e.data)}}ZodAny.create=e=>new ZodAny({typeName:ZodFirstPartyTypeKind.ZodAny,...processCreateParams(e)});class ZodUnknown extends ZodType{constructor(){super(...arguments),this._unknown=!0}_parse(e){return OK(e.data)}}ZodUnknown.create=e=>new ZodUnknown({typeName:ZodFirstPartyTypeKind.ZodUnknown,...processCreateParams(e)});class ZodNever extends ZodType{_parse(e){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.never,received:t.parsedType}),INVALID}}ZodNever.create=e=>new ZodNever({typeName:ZodFirstPartyTypeKind.ZodNever,...processCreateParams(e)});class ZodVoid extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.undefined){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.void,received:t.parsedType}),INVALID}return OK(e.data)}}ZodVoid.create=e=>new ZodVoid({typeName:ZodFirstPartyTypeKind.ZodVoid,...processCreateParams(e)});class ZodArray extends ZodType{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==ZodParsedType.array)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:t.parsedType}),INVALID;if(null!==n.exactLength){const e=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(e||o)&&(addIssueToContext(t,{code:e?ZodIssueCode.too_big:ZodIssueCode.too_small,minimum:o?n.exactLength.value:void 0,maximum:e?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(null!==n.minLength&&t.data.length<n.minLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),null!==n.maxLength&&t.data.length>n.maxLength.value&&(addIssueToContext(t,{code:ZodIssueCode.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map(((e,r)=>n.type._parseAsync(new ParseInputLazyPath(t,e,t.path,r))))).then((e=>ParseStatus.mergeArray(r,e)));const o=[...t.data].map(((e,r)=>n.type._parseSync(new ParseInputLazyPath(t,e,t.path,r))));return ParseStatus.mergeArray(r,o)}get element(){return this._def.type}min(e,t){return new ZodArray({...this._def,minLength:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodArray({...this._def,maxLength:{value:e,message:errorUtil.toString(t)}})}length(e,t){return new ZodArray({...this._def,exactLength:{value:e,message:errorUtil.toString(t)}})}nonempty(e){return this.min(1,e)}}function deepPartialify(e){if(e instanceof ZodObject){const t={};for(const r in e.shape){const n=e.shape[r];t[r]=ZodOptional.create(deepPartialify(n))}return new ZodObject({...e._def,shape:()=>t})}return e instanceof ZodArray?new ZodArray({...e._def,type:deepPartialify(e.element)}):e instanceof ZodOptional?ZodOptional.create(deepPartialify(e.unwrap())):e instanceof ZodNullable?ZodNullable.create(deepPartialify(e.unwrap())):e instanceof ZodTuple?ZodTuple.create(e.items.map((e=>deepPartialify(e)))):e}ZodArray.create=(e,t)=>new ZodArray({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ZodFirstPartyTypeKind.ZodArray,...processCreateParams(t)});class ZodObject extends ZodType{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(null!==this._cached)return this._cached;const e=this._def.shape(),t=util.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==ZodParsedType.object){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID}const{status:t,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof ZodNever&&"strip"===this._def.unknownKeys))for(const s in r.data)o.includes(s)||i.push(s);const a=[];for(const s of o){const e=n[s],t=r.data[s];a.push({key:{status:"valid",value:s},value:e._parse(new ParseInputLazyPath(r,t,r.path,s)),alwaysSet:s in r.data})}if(this._def.catchall instanceof ZodNever){const e=this._def.unknownKeys;if("passthrough"===e)for(const t of i)a.push({key:{status:"valid",value:t},value:{status:"valid",value:r.data[t]}});else if("strict"===e)i.length>0&&(addIssueToContext(r,{code:ZodIssueCode.unrecognized_keys,keys:i}),t.dirty());else if("strip"!==e)throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const e=this._def.catchall;for(const t of i){const n=r.data[t];a.push({key:{status:"valid",value:t},value:e._parse(new ParseInputLazyPath(r,n,r.path,t)),alwaysSet:t in r.data})}}return r.common.async?Promise.resolve().then((async()=>{const e=[];for(const t of a){const r=await t.key,n=await t.value;e.push({key:r,value:n,alwaysSet:t.alwaysSet})}return e})).then((e=>ParseStatus.mergeObjectSync(t,e))):ParseStatus.mergeObjectSync(t,a)}get shape(){return this._def.shape()}strict(e){return errorUtil.errToObj,new ZodObject({...this._def,unknownKeys:"strict",...void 0!==e?{errorMap:(t,r)=>{var n,o,i,a;const s=null!==(i=null===(o=(n=this._def).errorMap)||void 0===o?void 0:o.call(n,t,r).message)&&void 0!==i?i:r.defaultError;return"unrecognized_keys"===t.code?{message:null!==(a=errorUtil.errToObj(e).message)&&void 0!==a?a:s}:{message:s}}}:{}})}strip(){return new ZodObject({...this._def,unknownKeys:"strip"})}passthrough(){return new ZodObject({...this._def,unknownKeys:"passthrough"})}extend(e){return new ZodObject({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ZodObject({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ZodFirstPartyTypeKind.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ZodObject({...this._def,catchall:e})}pick(e){const t={};return util.objectKeys(e).forEach((r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}omit(e){const t={};return util.objectKeys(this.shape).forEach((r=>{e[r]||(t[r]=this.shape[r])})),new ZodObject({...this._def,shape:()=>t})}deepPartial(){return deepPartialify(this)}partial(e){const t={};return util.objectKeys(this.shape).forEach((r=>{const n=this.shape[r];e&&!e[r]?t[r]=n:t[r]=n.optional()})),new ZodObject({...this._def,shape:()=>t})}required(e){const t={};return util.objectKeys(this.shape).forEach((r=>{if(e&&!e[r])t[r]=this.shape[r];else{let e=this.shape[r];for(;e instanceof ZodOptional;)e=e._def.innerType;t[r]=e}})),new ZodObject({...this._def,shape:()=>t})}keyof(){return createZodEnum(util.objectKeys(this.shape))}}ZodObject.create=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.strictCreate=(e,t)=>new ZodObject({shape:()=>e,unknownKeys:"strict",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)}),ZodObject.lazycreate=(e,t)=>new ZodObject({shape:e,unknownKeys:"strip",catchall:ZodNever.create(),typeName:ZodFirstPartyTypeKind.ZodObject,...processCreateParams(t)});class ZodUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;if(t.common.async)return Promise.all(r.map((async e=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}}))).then((function(e){for(const t of e)if("valid"===t.result.status)return t.result;for(const n of e)if("dirty"===n.result.status)return t.common.issues.push(...n.ctx.common.issues),n.result;const r=e.map((e=>new ZodError(e.ctx.common.issues)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:r}),INVALID}));{let e;const n=[];for(const i of r){const r={...t,common:{...t.common,issues:[]},parent:null},o=i._parseSync({data:t.data,path:t.path,parent:r});if("valid"===o.status)return o;"dirty"!==o.status||e||(e={result:o,ctx:r}),r.common.issues.length&&n.push(r.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;const o=n.map((e=>new ZodError(e)));return addIssueToContext(t,{code:ZodIssueCode.invalid_union,unionErrors:o}),INVALID}}get options(){return this._def.options}}ZodUnion.create=(e,t)=>new ZodUnion({options:e,typeName:ZodFirstPartyTypeKind.ZodUnion,...processCreateParams(t)});const getDiscriminator=e=>e instanceof ZodLazy?getDiscriminator(e.schema):e instanceof ZodEffects?getDiscriminator(e.innerType()):e instanceof ZodLiteral?[e.value]:e instanceof ZodEnum?e.options:e instanceof ZodNativeEnum?util.objectValues(e.enum):e instanceof ZodDefault?getDiscriminator(e._def.innerType):e instanceof ZodUndefined?[void 0]:e instanceof ZodNull?[null]:e instanceof ZodOptional?[void 0,...getDiscriminator(e.unwrap())]:e instanceof ZodNullable?[null,...getDiscriminator(e.unwrap())]:e instanceof ZodBranded||e instanceof ZodReadonly?getDiscriminator(e.unwrap()):e instanceof ZodCatch?getDiscriminator(e._def.innerType):[];class ZodDiscriminatedUnion extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.object)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:t.parsedType}),INVALID;const r=this.discriminator,n=t.data[r],o=this.optionsMap.get(n);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(addIssueToContext(t,{code:ZodIssueCode.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),INVALID)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){const n=new Map;for(const o of t){const t=getDiscriminator(o.shape[e]);if(!t.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of t){if(n.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);n.set(r,o)}}return new ZodDiscriminatedUnion({typeName:ZodFirstPartyTypeKind.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...processCreateParams(r)})}}function mergeValues(e,t){const r=getParsedType(e),n=getParsedType(t);if(e===t)return{valid:!0,data:e};if(r===ZodParsedType.object&&n===ZodParsedType.object){const r=util.objectKeys(t),n=util.objectKeys(e).filter((e=>-1!==r.indexOf(e))),o={...e,...t};for(const i of n){const r=mergeValues(e[i],t[i]);if(!r.valid)return{valid:!1};o[i]=r.data}return{valid:!0,data:o}}if(r===ZodParsedType.array&&n===ZodParsedType.array){if(e.length!==t.length)return{valid:!1};const r=[];for(let n=0;n<e.length;n++){const o=mergeValues(e[n],t[n]);if(!o.valid)return{valid:!1};r.push(o.data)}return{valid:!0,data:r}}return r===ZodParsedType.date&&n===ZodParsedType.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}class ZodIntersection extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=(e,n)=>{if(isAborted(e)||isAborted(n))return INVALID;const o=mergeValues(e.value,n.value);return o.valid?((isDirty(e)||isDirty(n))&&t.dirty(),{status:t.value,value:o.data}):(addIssueToContext(r,{code:ZodIssueCode.invalid_intersection_types}),INVALID)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then((([e,t])=>n(e,t))):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}ZodIntersection.create=(e,t,r)=>new ZodIntersection({left:e,right:t,typeName:ZodFirstPartyTypeKind.ZodIntersection,...processCreateParams(r)});class ZodTuple extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.array)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.array,received:r.parsedType}),INVALID;if(r.data.length<this._def.items.length)return addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),INVALID;!this._def.rest&&r.data.length>this._def.items.length&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...r.data].map(((e,t)=>{const n=this._def.items[t]||this._def.rest;return n?n._parse(new ParseInputLazyPath(r,e,r.path,t)):null})).filter((e=>!!e));return r.common.async?Promise.all(n).then((e=>ParseStatus.mergeArray(t,e))):ParseStatus.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new ZodTuple({...this._def,rest:e})}}ZodTuple.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ZodTuple({items:e,typeName:ZodFirstPartyTypeKind.ZodTuple,rest:null,...processCreateParams(t)})};class ZodRecord extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.object)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.object,received:r.parsedType}),INVALID;const n=[],o=this._def.keyType,i=this._def.valueType;for(const a in r.data)n.push({key:o._parse(new ParseInputLazyPath(r,a,r.path,a)),value:i._parse(new ParseInputLazyPath(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?ParseStatus.mergeObjectAsync(t,n):ParseStatus.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){return new ZodRecord(t instanceof ZodType?{keyType:e,valueType:t,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(r)}:{keyType:ZodString.create(),valueType:e,typeName:ZodFirstPartyTypeKind.ZodRecord,...processCreateParams(t)})}}class ZodMap extends ZodType{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.map)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.map,received:r.parsedType}),INVALID;const n=this._def.keyType,o=this._def.valueType,i=[...r.data.entries()].map((([e,t],i)=>({key:n._parse(new ParseInputLazyPath(r,e,r.path,[i,"key"])),value:o._parse(new ParseInputLazyPath(r,t,r.path,[i,"value"]))})));if(r.common.async){const e=new Map;return Promise.resolve().then((async()=>{for(const r of i){const n=await r.key,o=await r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}))}{const e=new Map;for(const r of i){const n=r.key,o=r.value;if("aborted"===n.status||"aborted"===o.status)return INVALID;"dirty"!==n.status&&"dirty"!==o.status||t.dirty(),e.set(n.value,o.value)}return{status:t.value,value:e}}}}ZodMap.create=(e,t,r)=>new ZodMap({valueType:t,keyType:e,typeName:ZodFirstPartyTypeKind.ZodMap,...processCreateParams(r)});class ZodSet extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==ZodParsedType.set)return addIssueToContext(r,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.set,received:r.parsedType}),INVALID;const n=this._def;null!==n.minSize&&r.data.size<n.minSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),null!==n.maxSize&&r.data.size>n.maxSize.value&&(addIssueToContext(r,{code:ZodIssueCode.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const o=this._def.valueType;function i(e){const r=new Set;for(const n of e){if("aborted"===n.status)return INVALID;"dirty"===n.status&&t.dirty(),r.add(n.value)}return{status:t.value,value:r}}const a=[...r.data.values()].map(((e,t)=>o._parse(new ParseInputLazyPath(r,e,r.path,t))));return r.common.async?Promise.all(a).then((e=>i(e))):i(a)}min(e,t){return new ZodSet({...this._def,minSize:{value:e,message:errorUtil.toString(t)}})}max(e,t){return new ZodSet({...this._def,maxSize:{value:e,message:errorUtil.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}ZodSet.create=(e,t)=>new ZodSet({valueType:e,minSize:null,maxSize:null,typeName:ZodFirstPartyTypeKind.ZodSet,...processCreateParams(t)});class ZodFunction extends ZodType{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.function)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.function,received:t.parsedType}),INVALID;function r(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_arguments,argumentsError:r}})}function n(e,r){return makeIssue({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,getErrorMap(),errorMap].filter((e=>!!e)),issueData:{code:ZodIssueCode.invalid_return_type,returnTypeError:r}})}const o={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof ZodPromise){const e=this;return OK((async function(...t){const a=new ZodError([]),s=await e._def.args.parseAsync(t,o).catch((e=>{throw a.addIssue(r(t,e)),a})),c=await Reflect.apply(i,this,s);return await e._def.returns._def.type.parseAsync(c,o).catch((e=>{throw a.addIssue(n(c,e)),a}))}))}{const e=this;return OK((function(...t){const a=e._def.args.safeParse(t,o);if(!a.success)throw new ZodError([r(t,a.error)]);const s=Reflect.apply(i,this,a.data),c=e._def.returns.safeParse(s,o);if(!c.success)throw new ZodError([n(s,c.error)]);return c.data}))}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ZodFunction({...this._def,args:ZodTuple.create(e).rest(ZodUnknown.create())})}returns(e){return new ZodFunction({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new ZodFunction({args:e||ZodTuple.create([]).rest(ZodUnknown.create()),returns:t||ZodUnknown.create(),typeName:ZodFirstPartyTypeKind.ZodFunction,...processCreateParams(r)})}}class ZodLazy extends ZodType{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}ZodLazy.create=(e,t)=>new ZodLazy({getter:e,typeName:ZodFirstPartyTypeKind.ZodLazy,...processCreateParams(t)});class ZodLiteral extends ZodType{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_literal,expected:this._def.value}),INVALID}return{status:"valid",value:e.data}}get value(){return this._def.value}}function createZodEnum(e,t){return new ZodEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodEnum,...processCreateParams(t)})}ZodLiteral.create=(e,t)=>new ZodLiteral({value:e,typeName:ZodFirstPartyTypeKind.ZodLiteral,...processCreateParams(t)});class ZodEnum extends ZodType{constructor(){super(...arguments),_ZodEnum_cache.set(this,void 0)}_parse(e){if("string"!=typeof e.data){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{expected:util.joinValues(r),received:t.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodEnum_cache)||__classPrivateFieldSet(this,_ZodEnum_cache,new Set(this._def.values)),!__classPrivateFieldGet(this,_ZodEnum_cache).has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return addIssueToContext(t,{received:t.data,code:ZodIssueCode.invalid_enum_value,options:r}),INVALID}return OK(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return ZodEnum.create(e,{...this._def,...t})}exclude(e,t=this._def){return ZodEnum.create(this.options.filter((t=>!e.includes(t))),{...this._def,...t})}}_ZodEnum_cache=new WeakMap,ZodEnum.create=createZodEnum;class ZodNativeEnum extends ZodType{constructor(){super(...arguments),_ZodNativeEnum_cache.set(this,void 0)}_parse(e){const t=util.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==ZodParsedType.string&&r.parsedType!==ZodParsedType.number){const e=util.objectValues(t);return addIssueToContext(r,{expected:util.joinValues(e),received:r.parsedType,code:ZodIssueCode.invalid_type}),INVALID}if(__classPrivateFieldGet(this,_ZodNativeEnum_cache)||__classPrivateFieldSet(this,_ZodNativeEnum_cache,new Set(util.getValidEnumValues(this._def.values))),!__classPrivateFieldGet(this,_ZodNativeEnum_cache).has(e.data)){const e=util.objectValues(t);return addIssueToContext(r,{received:r.data,code:ZodIssueCode.invalid_enum_value,options:e}),INVALID}return OK(e.data)}get enum(){return this._def.values}}_ZodNativeEnum_cache=new WeakMap,ZodNativeEnum.create=(e,t)=>new ZodNativeEnum({values:e,typeName:ZodFirstPartyTypeKind.ZodNativeEnum,...processCreateParams(t)});class ZodPromise extends ZodType{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==ZodParsedType.promise&&!1===t.common.async)return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.promise,received:t.parsedType}),INVALID;const r=t.parsedType===ZodParsedType.promise?t.data:Promise.resolve(t.data);return OK(r.then((e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap}))))}}ZodPromise.create=(e,t)=>new ZodPromise({type:e,typeName:ZodFirstPartyTypeKind.ZodPromise,...processCreateParams(t)});class ZodEffects extends ZodType{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ZodFirstPartyTypeKind.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:e=>{addIssueToContext(r,e),e.fatal?t.abort():t.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),"preprocess"===n.type){const e=n.transform(r.data,o);if(r.common.async)return Promise.resolve(e).then((async e=>{if("aborted"===t.value)return INVALID;const n=await this._def.schema._parseAsync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}));{if("aborted"===t.value)return INVALID;const n=this._def.schema._parseSync({data:e,path:r.path,parent:r});return"aborted"===n.status?INVALID:"dirty"===n.status||"dirty"===t.value?DIRTY(n.value):n}}if("refinement"===n.type){const e=e=>{const t=n.refinement(e,o);if(r.common.async)return Promise.resolve(t);if(t instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return e};if(!1===r.common.async){const n=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===n.status?INVALID:("dirty"===n.status&&t.dirty(),e(n.value),{status:t.value,value:n.value})}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((r=>"aborted"===r.status?INVALID:("dirty"===r.status&&t.dirty(),e(r.value).then((()=>({status:t.value,value:r.value}))))))}if("transform"===n.type){if(!1===r.common.async){const e=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!isValid(e))return e;const i=n.transform(e.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((e=>isValid(e)?Promise.resolve(n.transform(e.value,o)).then((e=>({status:t.value,value:e}))):e))}util.assertNever(n)}}ZodEffects.create=(e,t,r)=>new ZodEffects({schema:e,typeName:ZodFirstPartyTypeKind.ZodEffects,effect:t,...processCreateParams(r)}),ZodEffects.createWithPreprocess=(e,t,r)=>new ZodEffects({schema:t,effect:{type:"preprocess",transform:e},typeName:ZodFirstPartyTypeKind.ZodEffects,...processCreateParams(r)});class ZodOptional extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.undefined?OK(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodOptional.create=(e,t)=>new ZodOptional({innerType:e,typeName:ZodFirstPartyTypeKind.ZodOptional,...processCreateParams(t)});class ZodNullable extends ZodType{_parse(e){return this._getType(e)===ZodParsedType.null?OK(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ZodNullable.create=(e,t)=>new ZodNullable({innerType:e,typeName:ZodFirstPartyTypeKind.ZodNullable,...processCreateParams(t)});class ZodDefault extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===ZodParsedType.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}ZodDefault.create=(e,t)=>new ZodDefault({innerType:e,typeName:ZodFirstPartyTypeKind.ZodDefault,defaultValue:"function"==typeof t.default?t.default:()=>t.default,...processCreateParams(t)});class ZodCatch extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return isAsync(n)?n.then((e=>({status:"valid",value:"valid"===e.status?e.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}))):{status:"valid",value:"valid"===n.status?n.value:this._def.catchValue({get error(){return new ZodError(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}ZodCatch.create=(e,t)=>new ZodCatch({innerType:e,typeName:ZodFirstPartyTypeKind.ZodCatch,catchValue:"function"==typeof t.catch?t.catch:()=>t.catch,...processCreateParams(t)});class ZodNaN extends ZodType{_parse(e){if(this._getType(e)!==ZodParsedType.nan){const t=this._getOrReturnCtx(e);return addIssueToContext(t,{code:ZodIssueCode.invalid_type,expected:ZodParsedType.nan,received:t.parsedType}),INVALID}return{status:"valid",value:e.data}}}ZodNaN.create=e=>new ZodNaN({typeName:ZodFirstPartyTypeKind.ZodNaN,...processCreateParams(e)});const BRAND=Symbol("zod_brand");class ZodBranded extends ZodType{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ZodPipeline extends ZodType{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async){return(async()=>{const e=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),DIRTY(e.value)):this._def.out._parseAsync({data:e.value,path:r.path,parent:r})})()}{const e=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return"aborted"===e.status?INVALID:"dirty"===e.status?(t.dirty(),{status:"dirty",value:e.value}):this._def.out._parseSync({data:e.value,path:r.path,parent:r})}}static create(e,t){return new ZodPipeline({in:e,out:t,typeName:ZodFirstPartyTypeKind.ZodPipeline})}}class ZodReadonly extends ZodType{_parse(e){const t=this._def.innerType._parse(e),r=e=>(isValid(e)&&(e.value=Object.freeze(e.value)),e);return isAsync(t)?t.then((e=>r(e))):r(t)}unwrap(){return this._def.innerType}}function cleanParams(e,t){const r="function"==typeof e?e(t):"string"==typeof e?{message:e}:e;return"string"==typeof r?{message:r}:r}function custom(e,t={},r){return e?ZodAny.create().superRefine(((n,o)=>{var i,a;const s=e(n);if(s instanceof Promise)return s.then((e=>{var i,a;if(!e){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}}));if(!s){const e=cleanParams(t,n),s=null===(a=null!==(i=e.fatal)&&void 0!==i?i:r)||void 0===a||a;o.addIssue({code:"custom",...e,fatal:s})}})):ZodAny.create()}ZodReadonly.create=(e,t)=>new ZodReadonly({innerType:e,typeName:ZodFirstPartyTypeKind.ZodReadonly,...processCreateParams(t)});const late={object:ZodObject.lazycreate};var ZodFirstPartyTypeKind,ZodFirstPartyTypeKind2;ZodFirstPartyTypeKind2=ZodFirstPartyTypeKind||(ZodFirstPartyTypeKind={}),ZodFirstPartyTypeKind2.ZodString="ZodString",ZodFirstPartyTypeKind2.ZodNumber="ZodNumber",ZodFirstPartyTypeKind2.ZodNaN="ZodNaN",ZodFirstPartyTypeKind2.ZodBigInt="ZodBigInt",ZodFirstPartyTypeKind2.ZodBoolean="ZodBoolean",ZodFirstPartyTypeKind2.ZodDate="ZodDate",ZodFirstPartyTypeKind2.ZodSymbol="ZodSymbol",ZodFirstPartyTypeKind2.ZodUndefined="ZodUndefined",ZodFirstPartyTypeKind2.ZodNull="ZodNull",ZodFirstPartyTypeKind2.ZodAny="ZodAny",ZodFirstPartyTypeKind2.ZodUnknown="ZodUnknown",ZodFirstPartyTypeKind2.ZodNever="ZodNever",ZodFirstPartyTypeKind2.ZodVoid="ZodVoid",ZodFirstPartyTypeKind2.ZodArray="ZodArray",ZodFirstPartyTypeKind2.ZodObject="ZodObject",ZodFirstPartyTypeKind2.ZodUnion="ZodUnion",ZodFirstPartyTypeKind2.ZodDiscriminatedUnion="ZodDiscriminatedUnion",ZodFirstPartyTypeKind2.ZodIntersection="ZodIntersection",ZodFirstPartyTypeKind2.ZodTuple="ZodTuple",ZodFirstPartyTypeKind2.ZodRecord="ZodRecord",ZodFirstPartyTypeKind2.ZodMap="ZodMap",ZodFirstPartyTypeKind2.ZodSet="ZodSet",ZodFirstPartyTypeKind2.ZodFunction="ZodFunction",ZodFirstPartyTypeKind2.ZodLazy="ZodLazy",ZodFirstPartyTypeKind2.ZodLiteral="ZodLiteral",ZodFirstPartyTypeKind2.ZodEnum="ZodEnum",ZodFirstPartyTypeKind2.ZodEffects="ZodEffects",ZodFirstPartyTypeKind2.ZodNativeEnum="ZodNativeEnum",ZodFirstPartyTypeKind2.ZodOptional="ZodOptional",ZodFirstPartyTypeKind2.ZodNullable="ZodNullable",ZodFirstPartyTypeKind2.ZodDefault="ZodDefault",ZodFirstPartyTypeKind2.ZodCatch="ZodCatch",ZodFirstPartyTypeKind2.ZodPromise="ZodPromise",ZodFirstPartyTypeKind2.ZodBranded="ZodBranded",ZodFirstPartyTypeKind2.ZodPipeline="ZodPipeline",ZodFirstPartyTypeKind2.ZodReadonly="ZodReadonly";const instanceOfType=(e,t={message:`Input not instance of ${e.name}`})=>custom((t=>t instanceof e),t),stringType=ZodString.create,numberType=ZodNumber.create,nanType=ZodNaN.create,bigIntType=ZodBigInt.create,booleanType=ZodBoolean.create,dateType=ZodDate.create,symbolType=ZodSymbol.create,undefinedType=ZodUndefined.create,nullType=ZodNull.create,anyType=ZodAny.create,unknownType=ZodUnknown.create,neverType=ZodNever.create,voidType=ZodVoid.create,arrayType=ZodArray.create,objectType=ZodObject.create,strictObjectType=ZodObject.strictCreate,unionType=ZodUnion.create,discriminatedUnionType=ZodDiscriminatedUnion.create,intersectionType=ZodIntersection.create,tupleType=ZodTuple.create,recordType=ZodRecord.create,mapType=ZodMap.create,setType=ZodSet.create,functionType=ZodFunction.create,lazyType=ZodLazy.create,literalType=ZodLiteral.create,enumType=ZodEnum.create,nativeEnumType=ZodNativeEnum.create,promiseType=ZodPromise.create,effectsType=ZodEffects.create,optionalType=ZodOptional.create,nullableType=ZodNullable.create,preprocessType=ZodEffects.createWithPreprocess,pipelineType=ZodPipeline.create,ostring=()=>stringType().optional(),onumber=()=>numberType().optional(),oboolean=()=>booleanType().optional(),coerce={string:e=>ZodString.create({...e,coerce:!0}),number:e=>ZodNumber.create({...e,coerce:!0}),boolean:e=>ZodBoolean.create({...e,coerce:!0}),bigint:e=>ZodBigInt.create({...e,coerce:!0}),date:e=>ZodDate.create({...e,coerce:!0})},NEVER=INVALID;var z=Object.freeze({__proto__:null,defaultErrorMap:errorMap,setErrorMap:setErrorMap,getErrorMap:getErrorMap,makeIssue:makeIssue,EMPTY_PATH:EMPTY_PATH,addIssueToContext:addIssueToContext,ParseStatus:ParseStatus,INVALID:INVALID,DIRTY:DIRTY,OK:OK,isAborted:isAborted,isDirty:isDirty,isValid:isValid,isAsync:isAsync,get util(){return util},get objectUtil(){return objectUtil},ZodParsedType:ZodParsedType,getParsedType:getParsedType,ZodType:ZodType,datetimeRegex:datetimeRegex,ZodString:ZodString,ZodNumber:ZodNumber,ZodBigInt:ZodBigInt,ZodBoolean:ZodBoolean,ZodDate:ZodDate,ZodSymbol:ZodSymbol,ZodUndefined:ZodUndefined,ZodNull:ZodNull,ZodAny:ZodAny,ZodUnknown:ZodUnknown,ZodNever:ZodNever,ZodVoid:ZodVoid,ZodArray:ZodArray,ZodObject:ZodObject,ZodUnion:ZodUnion,ZodDiscriminatedUnion:ZodDiscriminatedUnion,ZodIntersection:ZodIntersection,ZodTuple:ZodTuple,ZodRecord:ZodRecord,ZodMap:ZodMap,ZodSet:ZodSet,ZodFunction:ZodFunction,ZodLazy:ZodLazy,ZodLiteral:ZodLiteral,ZodEnum:ZodEnum,ZodNativeEnum:ZodNativeEnum,ZodPromise:ZodPromise,ZodEffects:ZodEffects,ZodTransformer:ZodEffects,ZodOptional:ZodOptional,ZodNullable:ZodNullable,ZodDefault:ZodDefault,ZodCatch:ZodCatch,ZodNaN:ZodNaN,BRAND:BRAND,ZodBranded:ZodBranded,ZodPipeline:ZodPipeline,ZodReadonly:ZodReadonly,custom:custom,Schema:ZodType,ZodSchema:ZodType,late:late,get ZodFirstPartyTypeKind(){return ZodFirstPartyTypeKind},coerce:coerce,any:anyType,array:arrayType,bigint:bigIntType,boolean:booleanType,date:dateType,discriminatedUnion:discriminatedUnionType,effect:effectsType,enum:enumType,function:functionType,instanceof:instanceOfType,intersection:intersectionType,lazy:lazyType,literal:literalType,map:mapType,nan:nanType,nativeEnum:nativeEnumType,never:neverType,null:nullType,nullable:nullableType,number:numberType,object:objectType,oboolean:oboolean,onumber:onumber,optional:optionalType,ostring:ostring,pipeline:pipelineType,preprocess:preprocessType,promise:promiseType,record:recordType,set:setType,strictObject:strictObjectType,string:stringType,symbol:symbolType,transformer:effectsType,tuple:tupleType,undefined:undefinedType,union:unionType,unknown:unknownType,void:voidType,NEVER:NEVER,ZodIssueCode:ZodIssueCode,quotelessJson:quotelessJson,ZodError:ZodError}),ProfileType=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e))(ProfileType||{}),AIAgentType=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(AIAgentType||{}),EndpointType=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(EndpointType||{}),AIAgentCapability=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(AIAgentCapability||{});const SUPPORTED_SOCIAL_PLATFORMS=["twitter","github","discord","telegram","linkedin","youtube"],SocialLinkSchema=z.object({platform:z.string().min(1),handle:z.string().min(1)}),AIAgentDetailsSchema=z.object({type:z.nativeEnum(AIAgentType),capabilities:z.array(z.nativeEnum(AIAgentCapability)).min(1),model:z.string().min(1),creator:z.string().optional()}),BaseProfileSchema=z.object({version:z.string().min(1),type:z.nativeEnum(ProfileType),display_name:z.string().min(1),alias:z.string().optional(),bio:z.string().optional(),socials:z.array(SocialLinkSchema).optional(),profileImage:z.string().optional(),properties:z.record(z.any()).optional(),inboundTopicId:z.string().optional(),outboundTopicId:z.string().optional()}),PersonalProfileSchema=BaseProfileSchema.extend({type:z.literal(0),language:z.string().optional(),timezone:z.string().optional()}),AIAgentProfileSchema=BaseProfileSchema.extend({type:z.literal(1),aiAgent:AIAgentDetailsSchema}),HCS11ProfileSchema=z.union([PersonalProfileSchema,AIAgentProfileSchema]),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};class HCS11Client{constructor(e){if(this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.auth=e.auth,this.network=e.network,this.mirrorNode=new HederaMirrorNode(this.network,this.logger),this.auth.privateKey){const e=y$2.fromString(this.auth.privateKey);this.client.setOperator(this.auth.operatorId,e)}this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-11"})}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}createPersonalProfile(e,t){return{version:"1.0",type:0,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,language:t?.language,timezone:t?.timezone,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId}}createAIAgentProfile(e,t,r,n,o){const i=this.validateProfile({version:"1.0",type:1,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}});if(!i.valid)throw new Error(`Invalid AI Agent Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:1,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,aiAgent:{type:t,capabilities:r,model:n,creator:o?.creator}}}validateProfile(e){const t=HCS11ProfileSchema.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map((e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`}))}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),r=await t.execute(this.client),n=await r.getReceipt(this.client);return n.status!==e$6.Success?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),n=await r.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status!==e$6.Success?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const i=mimeTypesExports.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let s;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),s=await inscribeWithSigner({type:"buffer",buffer:e,fileName:t,mimeType:i},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10),s=await inscribe({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}return s.confirmed?(o.completed("Image inscription completed",{topic_id:s.inscription.topic_id}),{imageTopicId:s.inscription.topic_id||"",transactionId:s.result.jobId,success:!0}):(o.verifying("Waiting for inscription confirmation",50,{jobId:s.result.jobId}),{imageTopicId:"",transactionId:s.result.jobId,success:!1,error:"Inscription not confirmed"})}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n.message||"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,n=new ProgressReporter({module:"HCS11-Profile",logger:this.logger,callback:r});n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const i=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=Buffer.from(i,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};n.submitting("Submitting profile to Hedera network",30);const s=this.auth.privateKey?await inscribe(r,{accountId:this.auth.operatorId,privateKey:this.auth.privateKey,network:this.network},o):await inscribeWithSigner(r,this.auth.signer,o);if(!s.confirmed||!s.inscription.topic_id)return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const c=s.inscription.topic_id;return n.completed("Profile inscription completed",{topicId:c,transactionId:s.result.transactionId}),{profileTopicId:c,transactionId:s.result.transactionId,success:!0}}catch(s){return n.failed(`Error inscribing profile: ${s.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:s.message||"Unknown error during inscription"}}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),n=(new s$4).setAccountMemo(r).setAccountId(e);return this.executeTransaction(n)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const n=r?.progressCallback,o=new ProgressReporter({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const i=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...r,progressCallback:e=>{i.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[0];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(0),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?1:0}async fetchProfileByAccountId(e,t){try{this.logger.info(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.info(`Got account memo: ${n}`),!n?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo`};this.logger.info(`Found HCS-11 memo: ${n}`);const o=n.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json();return{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:t.profileTopicId}}}if(o.startsWith("ar://")){const e=o.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json();return{success:!0,profile:r,topicInfo:{inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId}}}return{success:!1,error:`Invalid protocol reference format: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[n,i,a]=e,s=t||this.network||"mainnet";this.logger.info(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();return t?{success:!0,profile:t,topicInfo:{inboundTopic:t.inboundTopicId,outboundTopic:t.outboundTopicId,profileTopicId:a}}:{success:!1,error:`No profile data found for topic ${a}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}const sleep=e=>new Promise((t=>setTimeout(t,e)));class Registration{async checkRegistrationStatus(e,t,r,n){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,n=60,o=2e3,i){let a=0;for(;a<n;){i&&i.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,r,i);if("success"===s.status)return i&&i.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw i&&i.error("Registration confirmation failed"),new Error("Registration confirmation failed");i&&i.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise((e=>setTimeout(e,o))),a++}return i&&i.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const r=new HCS11Client({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await sleep(5e3);const o=await r.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const i=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),a=await i.json();return i.ok?(n&&n.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(i){return{error:`Error during registration request: ${i.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach((e=>r.append("tags",e))),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const n=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(e2){return{registrations:[],error:`Error fetching registrations: ${e2.message}`,success:!1}}}}var Hcs10MemoType=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e))(Hcs10MemoType||{});class HCS10BaseClient extends Registration{constructor(e){super(),this.network=e.network,this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint}),this.mirrorNode=new HederaMirrorNode(e.network,this.logger),this.feeAmount=e.feeAmount||.001}async getMessageStream(e){try{const t=await this.mirrorNode.getTopicMessages(e),r=["message","close_connection"];return{messages:t.filter((e=>{if("hcs-10"!==e.p||!r.includes(e.op))return!1;if("message"===e.op){if(!e.data)return!1;if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}if("close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async 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$7.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(r){const e=r instanceof Error?r.message:String(r);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e){try{const t=await this.mirrorNode.getTopicMessages(e);return{messages:t.filter((e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0}))}}catch(t){return this.logger&&this.logger.error(`Error fetching messages: ${t.message}`),{messages:[]}}}async requestAccount(e){try{return await this.mirrorNode.requestAccount(e)}catch(e2){throw this.logger.error("Failed to fetch account",e2),e2}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e){this.logger.info(`Retrieving profile for account: ${e}`);try{const t=new HCS11Client({network:this.network,auth:{operatorId:"0.0.0"},logLevel:"info"}),r=await t.fetchProfileByAccountId(e,this.network);if(!r?.success)return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,r?.error),{profile:null,success:!1,error:r?.error||`Failed to retrieve profile for account ID: ${e}`};const n=r.profile;let o=null;if(r.topicInfo?.inboundTopic&&r.topicInfo?.outboundTopic&&r.topicInfo?.profileTopicId){o={inboundTopic:r.topicInfo.inboundTopic,outboundTopic:r.topicInfo.outboundTopic,profileTopicId:r.topicInfo.profileTopicId};const t=`${e}-${this.network}`;HCS10Cache.getInstance().set(t,o)}return{profile:n,topicInfo:o,success:!0}}catch(t){return this.logger.error("Failed to retrieve profile:",t),{profile:null,success:!1,error:t instanceof Error?t.message:String(t)}}}async retrieveOutboundConnectTopic(e){this.logger.info(`Retrieving topics for account: ${e}`);try{const t=await this.retrieveProfile(e);if(!t?.success)throw new Error(t.error||"Failed to retrieve profile");const r=t.profile;if(!r.inboundTopicId||!r.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");const n={inboundTopic:r.inboundTopicId,outboundTopic:r.outboundTopicId,profileTopicId:r.profileTopicId},o=`${e}-${this.network}`;return HCS10Cache.getInstance().set(o,n),n}catch(t){throw this.logger.error("Failed to retrieve topic info:",t),t}}async retrieveOutboundMessages(e){try{const t=await this.retrieveOutboundConnectTopic(e);if(!t)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(t.outboundTopic)).messages.filter((e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op)))}catch(t){return this.logger.error("Failed to retrieve outbound messages:",t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveOutboundConnectTopic(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some((e=>"connection_created"===e.op&&e.connection_id===t))}catch(r){return this.logger.error("Failed to check connection created:",r),!1}}async getMessageContent(e){const t=e.match(/^hcs:\/\/(\d+)\/([0-9.]+)$/);if(!t)return e;const[r,n,o]=t;this.logger.info(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`https://kiloscribe.com/api/inscription-cdn/${o}?network=${this.network}`,t=await axios.get(e);if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return t.data.content||t.data.text||JSON.stringify(t.data)}catch(i){throw this.logger.error(`Error resolving HRL reference: ${i instanceof Error?i.message:"Unknown error"}`),new Error(`Failed to resolve HRL reference: ${i instanceof Error?i.message:"Unknown error"}`)}}async recordOutboundConnectionConfirmation({outboundTopicId:e,connectionRequestId:t,confirmedRequestId:r,connectionTopicId:n,operatorId:o,memo:i}){const a={p:"hcs-10",op:"connection_created",connection_topic_id:n,outbound_topic_id:e,confirmed_request_id:r,connection_request_id:t,operator_id:o,m:i};return await this.submitPayload(e,a)}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}clearCache(){HCS10Cache.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async checkRegistrationStatus(e,t,r){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(n){throw this.logger.error(`Error checking registration status: ${n}`),n}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],n=t[1];if(!r)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(r)}}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()}}var InboundTopicType=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(InboundTopicType||{});async function accountIdsToExemptKeys(e,t,r){const n=new HederaMirrorNode(t,r),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(i){r&&r.warn(`Could not get public key for account ${a}: ${i}`)}return o}class FeeConfigBuilder{constructor(){this.feeAmount=0,this.decimals=0,this.feeCollectorAccountId="",this.exemptAccountIds=[]}static forHbar(e,t,r=[]){return(new FeeConfigBuilder).setHbarAmount(e).setFeeCollector(t).addExemptAccounts(r)}setHbarAmount(e){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.feeAmount=1e8*e,this.decimals=0,this}setFeeAmount(e,t=0){return this.feeAmount=e,this.decimals=t,this}setFeeCollector(e){return this.feeCollectorAccountId=e,this}addExemptAccount(e){return this.exemptAccountIds.includes(e)||this.exemptAccountIds.push(e),this}addExemptAccounts(e){for(const t of e)this.addExemptAccount(t);return this}build(){if(!this.feeCollectorAccountId)throw new Error("Fee collector account ID is required");if(this.feeAmount<=0)throw new Error("Fee amount must be greater than zero");return{feeAmount:{amount:this.feeAmount,decimals:this.decimals},feeCollectorAccountId:this.feeCollectorAccountId,exemptAccounts:this.exemptAccountIds}}}class HCS10Client extends HCS10BaseClient{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount}),this.client="mainnet"===e.network?i$1.forMainnet():i$1.forTestnet(),this.operatorPrivateKey=y$2.fromString(e.operatorPrivateKey),this.network=e.network,this.client.setOperator(e.operatorId,this.operatorPrivateKey.toString()),this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-SDK"}),this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel})}getClient(){return this.client}async createAccount(){this.logger.info("Creating new account");const e=y$2.generate(),t=(new l).setKey(e.publicKey).setInitialBalance(new e$7(10));this.logger.debug("Executing account creation transaction");const r=await t.execute(this.client),n=(await r.getReceipt(this.client)).accountId;if(!n)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: ${n.toString()}`),{accountId:n.toString(),privateKey:e.toString()}}async createInboundTopic(e,t,r=60,n){const o=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:e,ttl:r});let i,a;switch(t){case InboundTopicType.PUBLIC:i=!1;break;case InboundTopicType.CONTROLLED:i=!0;break;case InboundTopicType.FEE_BASED:if(i=!0,!n)throw new Error("Fee configuration builder is required for fee-based topics");a=n.build();break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,i,a)}async createAgent(e,t=60){const r=e.build(),n=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:t}),o=await this.createTopic(n,!0,!0);this.logger.info(`Created new outbound topic ID: ${o}`);const i=this.client.operatorAccountId?.toString();if(!i)throw new Error("Failed to retrieve operator account ID");const a=await this.createInboundTopic(i,r.inboundTopicType,t,r.inboundTopicType===InboundTopicType.FEE_BASED?r.feeConfig:void 0);let s=r.existingPfpTopicId||"";if(!s&&r.pfpBuffer&&r.pfpBuffer.length>0){this.logger.info("Inscribing new profile picture");s=(await this.inscribePfp(r.pfpBuffer,r.pfpFileName)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${s}`)}else r.existingPfpTopicId&&this.logger.info(`Using existing profile picture with topic ID: ${r.existingPfpTopicId}`);const c=(await this.storeHCS11Profile(r.name,r.description,a,o,r.capabilities,r.metadata,r.pfpBuffer&&r.pfpBuffer.length>0?r.pfpBuffer:void 0,r.pfpFileName,r.existingPfpTopicId)).profileTopicId;return this.logger.info(`Profile stored with topic ID: ${c}`),{inboundTopicId:a,outboundTopicId:o,pfpTopicId:s,profileTopicId:c}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(r){return this.logger.error(`Error inscribing profile picture: ${r.message}`),{pfpTopicId:"",transactionId:"",success:!1,error:r.message}}}async storeHCS11Profile(e,t,r,n,o=[],i,a,s,c){try{let u=c||"";if(!u&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);e.success?u=e.pfpTopicId:this.logger.error("Failed to inscribe profile picture, continuing without PFP")}else c&&this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`);const l=this.hcs11Client.getAgentTypeFromMetadata({type:i.type||"autonomous"}),d=i.socials?Object.entries(i.socials).filter((([e,t])=>t)).map((([e,t])=>({platform:"x"===e?"twitter":e,handle:t}))):void 0,p=this.hcs11Client.createAIAgentProfile(e,l,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:u?`hcs://1/${u}`:void 0,socials:d,properties:i.properties,inboundTopicId:r,outboundTopicId:n,creator:i.creator}),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){return this.logger.error(`Error storing HCS-11 profile: ${u.message}`),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:u.message}}}async setupFees(e,t,r=[]){if(!this.client.operatorPublicKey)return;this.logger.info("Setting up topic with custom fees");const n=(new l$1).setAmount(Number(t.feeAmount.amount)).setFeeCollectorAccountId(f.fromString(t.feeCollectorAccountId));let o=[...t.exemptAccounts||[],...r];if(console.log("exemptAccountIds",o),o.length>0){const t=Array.from(new Set(o)).filter((e=>e!==this.client.operatorAccountId?.toString()));let r=[];if(t.length>0)try{r=await accountIdsToExemptKeys(t,this.network,this.logger)}catch(i){this.logger.warn(`Error getting exempt keys: ${i}, continuing without exempt keys`)}r.length>0&&e.setFeeExemptKeys(r)}e.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees([n])}async handleConnectionRequest(e,t,r,n,o=60){const i=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r});this.logger.info(`Handling connection request ${r} from ${t}`);const a=this.getClient().operatorAccountId?.toString();if(!a)throw new Error("Failed to retrieve operator account ID");let s=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(a);if(!c)throw new Error("Failed to retrieve public key");const u=new s$7([c,s],1);let l;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};l=await this.createTopic(i,u,u,t)}else l=await this.createTopic(i,u,u);this.logger.info(`Created new connection topic ID: ${l}`)}catch(p){throw this.logger.error(`Failed to create connection topic: ${p}`),new TopicCreationError(`Failed to create connection topic: ${p}`)}const d=`${e}@${a}`;return{connectionTopicId:l,confirmedConnectionSequenceNumber:await this.confirmConnection(e,l,t,r,"Connection accepted. Looking forward to collaborating!"),operatorId:d}}async confirmConnection(e,t,r,n,o,i){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),u=await this.submitPayload(e,s,i,c.requiresFee),l=u.topicSequenceNumber?.toNumber();if(!l)throw new ConnectionConfirmationError("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,r,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),i={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},a=JSON.stringify(i);if(Buffer.from(a).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);if(!n?.topic_id)throw new Error("Failed to inscribe large message content");i.data=`hcs://1/${n.topic_id}`,this.logger.info(`Large message inscribed with topic ID: ${n.topic_id}`)}catch(s){throw this.logger.error("Error inscribing large message:",s),new Error(`Failed to handle large message: ${s instanceof Error?s.message:"Unknown error"}`)}}return this.logger.info("Submitting message to connection topic",i),await this.submitPayload(e,i,n,o.requiresFee)}async createTopic(e,t,r,n){this.logger.info("Creating topic");const o=(new m$1).setTopicMemo(e);t&&("boolean"==typeof t&&t&&this.client.operatorPublicKey?(o.setAdminKey(this.client.operatorPublicKey),o.setAutoRenewAccountId(this.client.operatorAccountId)):(t instanceof i$7||t instanceof s$7)&&(o.setAdminKey(t),this.client.operatorAccountId&&o.setAutoRenewAccountId(this.client.operatorAccountId))),r&&("boolean"==typeof r&&r&&this.client.operatorPublicKey?o.setSubmitKey(this.client.operatorPublicKey):(r instanceof i$7||r instanceof s$7)&&o.setSubmitKey(r)),n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const i=await o.execute(this.client),a=await i.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,r,n=!1){const o="string"==typeof t?t:JSON.stringify(t),i=Buffer.byteLength(o,"utf8");if(i>1e3)throw new PayloadSizeError("Payload size exceeds 1000 bytes limit",i);const a=(new u).setTopicId(m$2.fromString(e)).setMessage(o);let s;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new e$7(this.feeAmount)),a.setTransactionMemo("HIP-991 Fee Payment")),r){const e=a.freezeWith(this.client),t=await e.sign(r);s=await t.execute(this.client)}else s=await a.execute(this.client);const c=await s.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r.accountId)throw new Error("Operator account ID is not set");const n=await this.getOperatorId(),o=r.accountId,i=await this.canSubmitToTopic(e,o);if(!i.canSubmit)throw new Error(`Cannot submit to topic: ${i.reason}`);const a={p:"hcs-10",op:"connection_request",operator_id:n,m:t},s=i.requiresFee,c=await this.submitPayload(e,a,void 0,s);this.logger.info(`Submitted connection request to topic ID: ${e}`);const u=await this.retrieveOutboundConnectTopic(o),l=c.topicSequenceNumber?.toNumber();if(!l)throw new Error("Failed to get response sequence number");return await this.submitPayload(u.outboundTopic,{...a,outbound_topic_id:u.outboundTopic,connection_request_id:l}),c}async inscribeFile(e,t){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 r=mimeTypesExports.lookup(t)||"application/octet-stream",n=await InscriptionSDK.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network}),o=await n.inscribeAndExecute({file:{type:"base64",base64:e.toString("base64"),fileName:t,mimeType:r},holderId:this.client.operatorAccountId.toString(),mode:"file",network:this.network},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network});if(!o.transactionId||!o.jobId)throw this.logger.error("Failed to inscribe, no transaction ID or job ID."),new Error("Failed to inscribe, no transaction ID or job ID.");o.transactionId&&o.jobId&&this.logger.info(`Transaction ID: ${o.transactionId}, Job ID: ${o.jobId}`);return await n.waitForInscription(o.jobId,30,4e3,!0)}async waitForConnectionConfirmation(e,t,r=60,n=2e3){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 i=(await this.mirrorNode.getTopicMessages(e)).filter((e=>"connection_created"===e.op));if(this.logger.info(`Found ${i.length} connection_created messages`),i.length>0)for(const e of i)if(Number(e.connection_id)===Number(t))return this.logger.info("Connection confirmation found"),{connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m};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(){return{accountId:this.client.operatorAccountId.toString(),signer:this.operatorPrivateKey}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let i=t?.existingState||void 0;n&&n({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:i}});const a=r.existingAccount||await this.createAccount();n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:i,account:a}});const s=new HCS10Client({network:r.network,operatorId:a.accountId,operatorPrivateKey:a.privateKey,operatorPublicKey:y$2.fromString(a.privateKey).publicKey.toString(),logLevel:"info",guardedRegistryBaseUrl:o});n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:30,details:{state:i}});const{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}=await s.createAgent(e);n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:i,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d}});const p=`${u}@${a.accountId}`,h=await s.registerAgentWithGuardedRegistry(a.accountId,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:p,state:e.details?.state||i}})},existingState:i});return h.success?(n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:c,inboundTopicId:u,pfpTopicId:l,profileTopicId:d,operatorId:p,state:h.state}}),{...h,metadata:{accountId:a.accountId,privateKey:a.privateKey,operatorId:p,inboundTopicId:u,outboundTopicId:c,profileTopicId:d,pfpTopicId:l}}):h}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{error:r.message,success:!1}}}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=r?.maxAttempts??60,o=r?.delayMs??2e3,i=r?.progressCallback;let a=r?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};i&&i({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const s=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!s.success)return{...s,state:a};if(i&&i({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:s.transactionId,state:a}}),s.transaction){const e=S.fromBytes(Buffer.from(s.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}i&&i({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:s.transactionId,state:a}});const c=await this.waitForRegistrationConfirmation(s.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),s.transactionId&&a.createdResources.push(`registration:${s.transactionId}`),i&&i({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:c,transactionId:s.transactionId,state:a}}),{...s,confirmed:c,state:a}}catch(n){return this.logger.error(`Failed to register agent: ${n.message}`),{error:n.message,success:!1}}}async registerAgent(e,t,r,n,o){this.logger.info("Registering agent");const i={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:r,m:n};await this.submitPayload(e,i,o)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return InboundTopicType.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),InboundTopicType.FEE_BASED}return InboundTopicType.CONTROLLED}catch(t){throw this.logger.error(`Error determining topic type: ${t.message}`),new Error(`Failed to determine topic type: ${t.message}`)}}getNetwork(){return this.network}getLogger(){return this.logger}}class AgentBuilder{constructor(){this.config={},this.logger=Logger$2.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setDescription(e){return this.config.description=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}setModel(e){return this.config.metadata?this.config.metadata.model=e:this.config.metadata={type:"autonomous",model:e},this}setCreator(e){return this.config.metadata?this.config.metadata.creator=e:this.config.metadata={type:"autonomous",creator:e},this}addSocial(e,t){return this.config.metadata?this.config.metadata.socials||(this.config.metadata.socials={}):this.config.metadata={type:"autonomous",socials:{}},this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata?this.config.metadata.properties||(this.config.metadata.properties={}):this.config.metadata={type:"autonomous",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 name is required");if(!this.config.description)throw new Error("Agent description is required");if(this.config.pfpBuffer&&this.config.pfpFileName||this.logger.warn("No profile picture provided, skipping..."),!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:"autonomous"}),this.config.inboundTopicType===InboundTopicType.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}const isBrowser="undefined"!=typeof window;class BrowserHCSClient extends HCS10BaseClient{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount}),this.hcs11Client=null,this.hwc=e.hwc,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.logger=Logger$2.getInstance({level:e.logLevel||"info",module:"HCS-Browser",prettyPrint:e.prettyPrint}),isBrowser)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new HCS11Client({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel})}catch(t){this.logger.warn(`Failed to initialize HCS11Client: ${t}`)}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){this.logger.info("Sending message");const o={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},i=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(o);if(Buffer.from(a).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);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(s){throw this.logger.error("Error inscribing large message:",s),new Error(`Failed to handle large message: ${s instanceof Error?s.message:"Unknown error"}`)}}return await this.submitPayload(e,o,n,i.requiresFee)}async submitConnectionRequest(e,t){this.logger.info("Submitting connection request");const r=this.getAccountAndSigner();if(!r.accountId)throw new Error("Failed to retrieve user account ID");const n=await this.getOperatorId(),o=r.accountId,i={p:"hcs-10",op:"connection_request",operator_id:n,m:t},a=await this.submitPayload(e,i);this.logger.info(`Submitted connection request to topic ID: ${e}`);const s=await this.retrieveOutboundConnectTopic(o);if(!s?.outboundTopic)throw this.logger.error(`Failed to retrieve outbound topic for account ID: ${o}`),new Error(`Failed to retrieve outbound topic for account ID: ${o}`);this.logger.info(`Retrieved outbound topic ID: ${s.outboundTopic} for account ID: ${o}`);const c=a?.topicSequenceNumber?.toNumber();if(!c)throw new Error("Failed to get response sequence number");return await this.submitPayload(s.outboundTopic,{...i,outbound_topic_id:e,connection_request_id:c}),a}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const i=this.hwc.getAccountInfo().accountId;if(!i)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),s=await this.mirrorNode.getPublicKey(i);if(!s)throw new Error("Failed to retrieve public key");const c=new s$7([s,a],1),u=this._generateHcs10Memo(Hcs10MemoType.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:r}),l=(new m$1).setTopicMemo(u).setAdminKey(c).setSubmitKey(c);this.logger.debug("Executing topic creation transaction");const d=await this.hwc.executeTransactionWithErrorHandling(l,!1);if(d.error)throw this.logger.error(d.error),new Error(d.error);const p=d.result;if(!p?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const h=p.topicId.toString(),f=`${e}@${i}`;return{connectionTopicId:h,confirmedConnectionSequenceNumber:await this.confirmConnection(e,h,t,r,f,n),operatorId:f}}async confirmConnection(e,t,r,n,o,i){this.logger.info("Confirming connection");const a={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:n,m:i},s=await this.submitPayload(e,a);if(!s?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return s.topicSequenceNumber.toNumber()}async createAgent(e,t,r,n,o,i,a,s){try{const c=s?.progressCallback,u=new ProgressReporter({module:"AgentCreate",logger:this.logger,callback:c});let l=s?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(l.outboundTopicId)u.preparing("Using existing outbound topic",20,{state:l});else{l.currentStage="topics",u.preparing("Creating agent outbound topic",0,{state:l});const e=this._generateHcs10Memo(Hcs10MemoType.OUTBOUND,{ttl:s?.ttl}),t=await this.createTopic(e,!0,!0);if(!t.success||!t.topicId)return l.error=t.error||"Failed to create outbound topic",u.failed(`Failed to create outbound topic: ${l.error}`,{state:l}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.outboundTopicId=t.topicId,l.createdResources&&l.createdResources.push(`outbound:${l.outboundTopicId}`),u.preparing("Outbound topic created",20,{state:l})}const d=this.hwc.getAccountInfo().accountId;if(!d)throw new Error("Failed to retrieve user account ID");if(l.inboundTopicId)u.preparing("Using existing inbound topic",40,{state:l});else{const e=this._generateHcs10Memo(Hcs10MemoType.INBOUND,{accountId:d,ttl:s?.ttl}),t=await this.createTopic(e,!0,!0);if(!t.success||!t.topicId)return l.error=t.error||"Failed to create inbound topic",u.failed(`Failed to create inbound topic: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.inboundTopicId=t.topicId,l.createdResources&&l.createdResources.push(`inbound:${l.inboundTopicId}`),u.preparing("Inbound topic created",40,{state:l})}if(l.pfpTopicId||a)l.pfpTopicId=a||l.pfpTopicId,u.preparing(`Using existing profile picture: ${l.pfpTopicId}`,60,{state:l});else{l.currentStage="pfp",u.preparing("Creating agent profile picture",40,{state:l});const r=u.createSubProgress({minPercent:40,maxPercent:60,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>{r.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:l}})}});if(!n.success)return l.error=n.error||"Failed to inscribe profile picture",u.failed(`Failed to inscribe profile picture: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:"",profileTopicId:"",success:!1,error:l.error,state:l};l.pfpTopicId=n.pfpTopicId,l.completedPercentage=60,l.createdResources&&l.createdResources.push(`pfp:${l.pfpTopicId}`),u.preparing("Profile picture created",60,{state:l})}if(l.profileTopicId)u.preparing("Using existing agent profile",100,{state:l}),"complete"!==l.currentStage&&(l.currentStage="complete",l.completedPercentage=100);else{l.currentStage="profile",u.preparing("Creating agent profile",60,{state:l});const e=u.createSubProgress({minPercent:60,maxPercent:100,logPrefix:"Profile"});if(!this.hcs11Client)return l.error="HCS11Client is not available in this environment",u.failed(l.error,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:"",success:!1,error:l.error,state:l};const t=await this.storeHCS11Profile(r,n,l.inboundTopicId,l.outboundTopicId,o,i,void 0,void 0,l.pfpTopicId,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:{...t.details,state:l}})}});if(!t.success)return l.error=t.error||"Failed to store agent profile",u.failed(`Failed to store agent profile: ${l.error}`,{state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:"",success:!1,error:l.error,state:l};l.profileTopicId=t.profileTopicId,l.createdResources&&l.createdResources.push(`profile:${l.profileTopicId}`),l.currentStage="complete",l.completedPercentage=100}return u.completed("Agent successfully created",{inboundTopicId:l.inboundTopicId,outboundTopicId:l.outboundTopicId,pfpTopicId:l.pfpTopicId,profileTopicId:l.profileTopicId,state:l}),{outboundTopicId:l.outboundTopicId||"",inboundTopicId:l.inboundTopicId||"",pfpTopicId:l.pfpTopicId||"",profileTopicId:l.profileTopicId||"",success:!0,state:l}}catch(c){return this.logger.error(`Error creating agent: ${c.message}`),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:`Error creating agent: ${c.message}`,state:{currentStage:"init",completedPercentage:0,error:c.message}}}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,r){try{this.logger.info("Registering agent with guarded registry");const n=(await this.retrieveProfile(e)).topicInfo.inboundTopic,o=this.initializeRegistrationState(n,r?.existingState),i=new ProgressReporter({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});i.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:o};if(i.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=S.fromBytes(Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:o};this.logger.info("Successfully processed registration transaction")}i.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const s=r?.maxAttempts??60,c=r?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,s,c,this.logger);return this.updateStateForCompletedRegistration(o,n),i.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),n=t?.progressCallback,o=new ProgressReporter({module:"AgentCreateRegister",logger:this.logger,callback:n});let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:i}),"complete"!==i.currentStage||!i.inboundTopicId||!i.outboundTopicId||!i.profileTopicId){const e=await this.createAgent(r.pfpBuffer||Buffer.from([]),r.pfpFileName||"default.png",r.name,r.description,r.capabilities,r.metadata,r.existingPfpTopicId,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},existingState:i});if(!e.success)throw new Error(e.error||"Failed to create agent with topics");i=e.state,i.agentMetadata=r.metadata}o.preparing(`Agent creation status: ${i.currentStage}, ${i.completedPercentage}%`,30,{state:i});const{accountId:a}=this.getAccountAndSigner();if("complete"!==i.currentStage||!i.createdResources?.includes(`registration:${i.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(a,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,state:e.details?.state||i}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:i});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");i=e.state}return o.completed("Agent creation and registration complete",{state:i}),{success:!0,state:i,metadata:{accountId:a,operatorId:`${i.inboundTopicId}@${a}`,inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,profileTopicId:i.profileTopicId,pfpTopicId:i.pfpTopicId,privateKey:null,...i.agentMetadata}}}catch(r){throw new Error(`Failed to create and register agent: ${r.message}`)}}async storeHCS11Profile(e,t,r,n,o=[],i={},a,s,c,u){try{const l=u?.progressCallback,d=new ProgressReporter({module:"StoreHCS11Profile",logger:this.logger,callback:l});d.preparing("Preparing agent profile data",0);let 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);const h=this.hcs11Client?.getAgentTypeFromMetadata({type:i.type||"autonomous"});d.preparing("Building agent profile",65);const f=[];if(i.socials&&(i.socials.twitter&&f.push({platform:"twitter",handle:i.socials.twitter}),i.socials.discord&&f.push({platform:"discord",handle:i.socials.discord}),i.socials.github&&f.push({platform:"github",handle:i.socials.github}),i.socials.website&&f.push({platform:"website",handle:i.socials.website}),i.socials.x&&f.push({platform:"twitter",handle:i.socials.x}),i.socials.linkedin&&f.push({platform:"linkedin",handle:i.socials.linkedin}),i.socials.youtube&&f.push({platform:"youtube",handle:i.socials.youtube}),i.socials.telegram&&f.push({platform:"telegram",handle:i.socials.telegram})),!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 m=this.hcs11Client.createAIAgentProfile(e,h,o,i.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:f.length>0?f:void 0,properties:{description:t,version:i.version||"1.0.0",creator:i.creator||"Unknown",supported_languages:i.supported_languages||["en"],permissions:i.permissions||[],model_details:i.model_details,training:i.training,capabilities_description:i.capabilities_description,...i},inboundTopicId:r,outboundTopicId:n,creator:i.creator}),y=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),g=await this.hcs11Client.createAndInscribeProfile(m,!0,{progressCallback:e=>{y.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return g.success?(d.completed("Profile stored successfully",{profileTopicId:g.profileTopicId}),{profileTopicId:g.profileTopicId,pfpTopicId:p,success:!0,transactionId:g.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:g.error||"Failed to inscribe profile",transactionId:g.transactionId||""})}catch(l){return this.logger.error(`Error storing HCS11 profile: ${l.message}`),{profileTopicId:"",success:!1,error:l.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),i=(new m$1).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(i.setAdminKey(a),i.setAutoRenewAccountId(n)),r&&a&&i.setSubmitKey(a);const s=await this.hwc.executeTransactionWithErrorHandling(i,!1),c=s.error;if(c)return this.logger.error(c),{success:!1,error:c};const u=s.result;return u?.topicId?{success:!0,topicId:u.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,r,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const i=(new u).setTopicId(e).setMessage(o);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),i.setMaxTransactionFee(new e$7(this.feeAmount)),i.setTransactionMemo("HIP-991 Fee Payment")),r){const{accountId:e,signer:t}=this.getAccountAndSigner();i.freezeWithSigner(t);const n=await i.sign(r);a=await this.hwc.executeTransactionWithErrorHandling(n,!0)}else a=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(a?.error)throw this.logger.error(`Failed to submit payload: ${a.error}`),new Error(`Failed to submit payload: ${a.error}`);if(!a?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),a.result}async inscribeFile(e,t){const{accountId:r,signer:n}=this.getAccountAndSigner(),o=mimeTypesExports.lookup(t)||"application/octet-stream",i=await InscriptionSDK.createWithAuth({type:"client",accountId:r,signer:n,network:this.network}),a=await i.inscribe({file:{type:"base64",base64:e.toString("base64"),fileName:t,mimeType:o},holderId:r.toString(),mode:"file",network:this.network},n);if(!a.transactionId||!a.jobId)throw this.logger.error("Failed to inscribe, no transaction ID or job ID."),new Error("Failed to inscribe, no transaction ID or job ID.");a.transactionId&&a.jobId&&this.logger.info(`Transaction ID: ${a.transactionId}, Job ID: ${a.jobId}`);return await i.waitForInscription(a.jobId,30,4e3,!0)}getAccountAndSigner(){const e=this.hwc.getAccountInfo().accountId.toString(),t=this.hwc.dAppConnector.signers.find((t=>t.getAccountId().toString()===e));if(!t)throw this.logger.error("Failed to find signer"),new Error("Failed to find signer");return{accountId:e,signer:t}}async inscribePfp(e,t,r){try{const n=r?.progressCallback,o=new ProgressReporter({module:"PFP-Inscription",logger:this.logger,callback:n});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const i=e=>{o.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},a=await this.hcs11Client.inscribeImage(e,t,{progressCallback:i});return a.success?(o.completed("Successfully inscribed profile picture",{pfpTopicId:a.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${a.imageTopicId}`),{pfpTopicId:a.imageTopicId,success:!0,transactionId:a.transactionId||""}):(o.failed(`Failed to inscribe profile picture: ${a.error}`),this.logger.error(`Failed to inscribe profile picture: ${a.error}`),{pfpTopicId:"",success:!1,error:a.error||"Failed to inscribe profile picture",transactionId:a.transactionId||""})}catch(n){return this.logger.error(`Error inscribing profile picture: ${n.message}`),{pfpTopicId:"",success:!1,error:n.message,transactionId:""}}}}exports.AIAgentCapability=AIAgentCapability,exports.AIAgentType=AIAgentType,exports.AccountCreationError=AccountCreationError,exports.AgentBuilder=AgentBuilder,exports.BrowserHCSClient=BrowserHCSClient,exports.ConnectionConfirmationError=ConnectionConfirmationError,exports.EVMBridge=EVMBridge,exports.EndpointType=EndpointType,exports.FeeConfigBuilder=FeeConfigBuilder,exports.HCS=HCS,exports.HCS10BaseClient=HCS10BaseClient,exports.HCS10Cache=HCS10Cache,exports.HCS10Client=HCS10Client,exports.HCS11Client=HCS11Client,exports.Hcs10MemoType=Hcs10MemoType,exports.HederaMirrorNode=HederaMirrorNode,exports.InboundTopicType=InboundTopicType,exports.Logger=Logger$2,exports.PayloadSizeError=PayloadSizeError,exports.ProfileType=ProfileType,exports.ProgressReporter=ProgressReporter,exports.Registration=Registration,exports.SUPPORTED_SOCIAL_PLATFORMS=SUPPORTED_SOCIAL_PLATFORMS,exports.TopicCreationError=TopicCreationError,exports.WasmBridge=WasmBridge,exports.accountIdsToExemptKeys=accountIdsToExemptKeys,exports.capabilityNameToCapabilityMap=capabilityNameToCapabilityMap,exports.inscribe=inscribe,exports.inscribeWithSigner=inscribeWithSigner,exports.retrieveInscription=retrieveInscription,exports.sleep=sleep$1,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
134
134
  //# sourceMappingURL=standards-sdk.umd.js.map