@botuyo/chat-widget-standalone 1.0.32 → 1.0.33
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/botuyo-chat.es.js +2 -2
- package/dist/botuyo-chat.es.js.map +1 -1
- package/dist/botuyo-chat.umd.js +1 -1
- package/dist/botuyo-chat.umd.js.map +1 -1
- package/dist/src/chat-widget/hooks/useChatSocket.d.ts +1 -0
- package/dist/src/chat-widget/hooks/useChatSocket.d.ts.map +1 -1
- package/dist/src/chat-widget/hooks/useChatState.d.ts.map +1 -1
- package/dist/src/chat-widget/hooks/useChatWidget.d.ts.map +1 -1
- package/dist/stats-umd.html +1 -1
- package/dist/stats.html +1 -1
- package/package.json +2 -1
package/dist/botuyo-chat.es.js
CHANGED
|
@@ -12,7 +12,7 @@ return N("div",{className:b("flex items-center w-fit transition-all duration-500
|
|
|
12
12
|
/* @__PURE__ */$("div",{className:"text-6xl mb-4",children:"⚠️"}),
|
|
13
13
|
/* @__PURE__ */$("h2",{className:"text-xl font-bold text-foreground mb-2",children:"Algo salió mal"}),
|
|
14
14
|
/* @__PURE__ */$("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:this.state.error?.message||"Ocurrió un error inesperado"}),
|
|
15
|
-
/* @__PURE__ */$("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const L={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},R={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},W={text:"text-primary-foreground"};const B=(t,e)=>e.some(e=>t instanceof e);let J,V;const q=/* @__PURE__ */new WeakMap,G=/* @__PURE__ */new WeakMap,K=/* @__PURE__ */new WeakMap;let H={get(t,e,r){if(t instanceof IDBTransaction){if("done"===e)return q.get(t);if("store"===e)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Q(t[e])},set:(t,e,r)=>(t[e]=r,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function Y(t){H=t(H)}function X(t){return"function"==typeof t?(e=t,(V||(V=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(tt(this),t),Q(this.request)}:function(...t){return Q(e.apply(tt(this),t))}):(t instanceof IDBTransaction&&function(t){if(q.has(t))return;const e=new Promise((e,r)=>{const o=()=>{t.removeEventListener("complete",n),t.removeEventListener("error",a),t.removeEventListener("abort",a)},n=()=>{e(),o()},a=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",n),t.addEventListener("error",a),t.addEventListener("abort",a)});q.set(t,e)}(t),B(t,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,H):t);var e}function Q(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,r)=>{const o=()=>{t.removeEventListener("success",n),t.removeEventListener("error",a)},n=()=>{e(Q(t.result)),o()},a=()=>{r(t.error),o()};t.addEventListener("success",n),t.addEventListener("error",a)});return K.set(e,t),e}(t);if(G.has(t))return G.get(t);const e=X(t);return e!==t&&(G.set(t,e),K.set(e,t)),e}const tt=t=>K.get(t),et=["get","getKey","getAll","getAllKeys","count"],rt=["put","add","delete","clear"],ot=/* @__PURE__ */new Map;function nt(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(ot.get(e))return ot.get(e);const r=e.replace(/FromIndex$/,""),o=e!==r,n=rt.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!n&&!et.includes(r))return;const a=async function(t,...e){const a=this.transaction(t,n?"readwrite":"readonly");let i=a.store;return o&&(i=i.index(e.shift())),(await Promise.all([i[r](...e),n&&a.done]))[0]};return ot.set(e,a),a}Y(t=>({...t,get:(e,r,o)=>nt(e,r)||t.get(e,r,o),has:(e,r)=>!!nt(e,r)||t.has(e,r)}));const at=["continue","continuePrimaryKey","advance"],it={},st=/* @__PURE__ */new WeakMap,ct=/* @__PURE__ */new WeakMap,lt={get(t,e){if(!at.includes(e))return t[e];let r=it[e];return r||(r=it[e]=function(...t){st.set(this,ct.get(this)[e](...t))}),r}};async function*dt(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;const r=new Proxy(e,lt);for(ct.set(r,e),K.set(r,tt(e));e;)yield r,e=await(st.get(r)||e.continue()),st.delete(r)}function ut(t,e){return e===Symbol.asyncIterator&&B(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===e&&B(t,[IDBIndex,IDBObjectStore])}Y(t=>({...t,get:(e,r,o)=>ut(e,r)?dt:t.get(e,r,o),has:(e,r)=>ut(e,r)||t.has(e,r)}));class pt{db=null;DB_NAME;DB_VERSION=1;constructor(t="default"){this.DB_NAME=`botuyo-chat-${t}`}async init(){try{this.db=await function(t,e,{blocked:r,upgrade:o,blocking:n,terminated:a}={}){const i=indexedDB.open(t,e),s=Q(i);return o&&i.addEventListener("upgradeneeded",t=>{o(Q(i.result),t.oldVersion,t.newVersion,Q(i.transaction),t)}),r&&i.addEventListener("blocked",t=>r(t.oldVersion,t.newVersion,t)),s.then(t=>{a&&t.addEventListener("close",()=>a()),n&&t.addEventListener("versionchange",t=>n(t.oldVersion,t.newVersion,t))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(t){t.objectStoreNames.contains("messages")||t.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),t.objectStoreNames.contains("metadata")||t.createObjectStore("metadata")}}),x.info("IndexedDB initialized")}catch(t){throw x.error("Failed to initialize IndexedDB:",t),t}}async saveMessage(t){this.db||await this.init();try{await this.db.put("messages",t)}catch(e){x.error("Failed to save message:",e)}}async saveMessages(t){this.db||await this.init();try{const e=this.db.transaction("messages","readwrite");await Promise.all([...t.map(t=>e.store.put(t)),e.done])}catch(e){x.error("Failed to save messages:",e)}}async getMessages(t=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-t)}catch(e){return x.error("Failed to get messages:",e),[]}}async getMessage(t){this.db||await this.init();try{return await this.db.get("messages",t)}catch(e){return void x.error("Failed to get message:",e)}}async deleteMessage(t){this.db||await this.init();try{await this.db.delete("messages",t)}catch(e){x.error("Failed to delete message:",e)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),x.info("Messages cleared from IndexedDB")}catch(t){x.error("Failed to clear messages:",t)}}async setMetadata(t){this.db||await this.init();try{await this.db.put("metadata",t,"chat-metadata")}catch(e){x.error("Failed to set metadata:",e)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(t){return x.error("Failed to get metadata:",t),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),x.info("All data cleared from IndexedDB")}catch(t){x.error("Failed to clear all data:",t)}}async migrateFromLocalStorage(t="default"){try{const e=`botuyo_chat_v1_${t}`,r=localStorage.getItem(e);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const t=o.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}));await this.saveMessages(t),x.info(`Migrated ${t.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(e),x.info("Migration from localStorage completed")}catch(e){x.error("Failed to migrate from localStorage:",e)}}}const ht=/* @__PURE__ */new Map,gt={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function mt(t,e){switch(e.type){case"TOGGLE_WINDOW":return{...t,isOpen:!t.isOpen};case"OPEN_WINDOW":return{...t,isOpen:!0};case"CLOSE_WINDOW":return{...t,isOpen:!1};case"SET_CONNECTED":return{...t,isConnected:e.payload};case"SET_TYPING":return{...t,isTyping:e.payload};case"ADD_MESSAGE":{if(t.messages.some(t=>t.id===e.payload.id))return t;const r=[...t.messages,e.payload],o="bot"===e.payload.sender;return{...t,messages:r,isTyping:!o&&t.isTyping}}case"SET_MESSAGES":return{...t,messages:[...e.payload]};case"SET_ERROR":return{...t,error:e.payload};case"SET_SESSION_ID":return{...t,sessionId:e.payload};case"CLEAR_CHAT":return{...gt,isOpen:t.isOpen};case"RESTORE_SESSION":return{...t,...e.payload,isConnected:!1,isTyping:!1,error:null};default:return t}}function ft(t,e,r){function o(r,o){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:o,constr:i,traits:/* @__PURE__ */new Set},enumerable:!1}),r._zod.traits.has(t))return;r._zod.traits.add(t),e(r,o);const n=i.prototype,a=Object.keys(n);for(let t=0;t<a.length;t++){const e=a[t];e in r||(r[e]=n[e].bind(r))}}const n=r?.Parent??Object;class a extends n{}function i(t){var e;const n=r?.Parent?new a:this;o(n,t),(e=n._zod).deferred??(e.deferred=[]);for(const r of n._zod.deferred)r();return n}return Object.defineProperty(a,"name",{value:t}),Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:e=>!!(r?.Parent&&e instanceof r.Parent)||e?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}class wt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class bt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const vt={};function yt(t){return vt}function xt(t){const e=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,r])=>-1===e.indexOf(+t)).map(([t,e])=>e)}function kt(t,e){return"bigint"==typeof e?e.toString():e}function _t(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function zt(t){return null==t}function Et(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}const St=/* @__PURE__ */Symbol("evaluating");function Ot(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==St)return void 0===o&&(o=St,o=r()),o},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function It(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ct(...t){const e={};for(const r of t){const t=Object.getOwnPropertyDescriptors(r);Object.assign(e,t)}return Object.defineProperties({},e)}function $t(t){return JSON.stringify(t)}const Nt="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Tt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}const Mt=_t(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(t){return!1}});function At(t){if(!1===Tt(t))return!1;const e=t.constructor;if(void 0===e)return!0;if("function"!=typeof e)return!0;const r=e.prototype;return!1!==Tt(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function jt(t){return At(t)?{...t}:Array.isArray(t)?[...t]:t}const Pt=/* @__PURE__ */new Set(["string","number","symbol"]);function Ft(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dt(t,e,r){const o=new t._zod.constr(e??t._zod.def);return e&&!r?.parent||(o._zod.parent=t),o}function Zt(t){const e=t;if(!e)return{};if("string"==typeof e)return{error:()=>e};if(void 0!==e?.message){if(void 0!==e?.error)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,"string"==typeof e.error?{...e,error:()=>e.error}:e}const Ut={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Lt(t,e=0){if(!0===t.aborted)return!0;for(let r=e;r<t.issues.length;r++)if(!0!==t.issues[r]?.continue)return!0;return!1}function Rt(t,e){return e.map(e=>{var r;return(r=e).path??(r.path=[]),e.path.unshift(t),e})}function Wt(t){return"string"==typeof t?t:t?.message}function Bt(t,e,r){const o={...t,path:t.path??[]};if(!t.message){const n=Wt(t.inst?._zod.def?.error?.(t))??Wt(e?.error?.(t))??Wt(r.customError?.(t))??Wt(r.localeError?.(t))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,e?.reportInput||delete o.input,o}function Jt(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function Vt(...t){const[e,r,o]=t;return"string"==typeof e?{message:e,code:"custom",input:r,inst:o}:{...e}}const qt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,kt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gt=ft("$ZodError",qt),Kt=ft("$ZodError",qt,{Parent:Error}),Ht=t=>(e,r,o,n)=>{const a=o?Object.assign(o,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new wt;if(i.issues.length){const e=new(n?.Err??t)(i.issues.map(t=>Bt(t,a,yt())));throw Nt(e,n?.callee),e}return i.value},Yt=t=>async(e,r,o,n)=>{const a=o?Object.assign(o,{async:!0}):{async:!0};let i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const e=new(n?.Err??t)(i.issues.map(t=>Bt(t,a,yt())));throw Nt(e,n?.callee),e}return i.value},Xt=t=>(e,r,o)=>{const n=o?{...o,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},n);if(a instanceof Promise)throw new wt;return a.issues.length?{success:!1,error:new(t??Gt)(a.issues.map(t=>Bt(t,n,yt())))}:{success:!0,data:a.value}},Qt=/* @__PURE__ */Xt(Kt),te=t=>async(e,r,o)=>{const n=o?Object.assign(o,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},n);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(t=>Bt(t,n,yt())))}:{success:!0,data:a.value}},ee=/* @__PURE__ */te(Kt),re=t=>(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ht(t)(e,r,n)},oe=t=>(e,r,o)=>Ht(t)(e,r,o),ne=t=>async(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Yt(t)(e,r,n)},ae=t=>async(e,r,o)=>Yt(t)(e,r,o),ie=t=>(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Xt(t)(e,r,n)},se=t=>(e,r,o)=>Xt(t)(e,r,o),ce=t=>async(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return te(t)(e,r,n)},le=t=>async(e,r,o)=>te(t)(e,r,o),de=/^[cC][^\s-]{8,}$/,ue=/^[0-9a-z]+$/,pe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,he=/^[0-9a-vA-V]{20}$/,ge=/^[A-Za-z0-9]{27}$/,me=/^[a-zA-Z0-9_-]{21}$/,fe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,we=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,be=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ve=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ye=/^(?:(?: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])$/,xe=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,ke=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,_e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ze=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ee=/^[A-Za-z0-9_-]*$/,Se=/^\+[1-9]\d{6,14}$/,Oe="(?:(?:\\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])))",Ie=/* @__PURE__ */new RegExp(`^${Oe}$`);function Ce(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof t.precision?-1===t.precision?`${e}`:0===t.precision?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}const $e=/^-?\d+$/,Ne=/^-?\d+(?:\.\d+)?$/,Te=/^[^A-Z]*$/,Me=/^[^a-z]*$/,Ae=/* @__PURE__ */ft("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),je={number:"number",bigint:"bigint",object:"date"},Pe=/* @__PURE__ */ft("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);const r=je[typeof e.value];t._zod.onattach.push(t=>{const r=t._zod.bag,o=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:r,code:"too_big",maximum:"object"==typeof e.value?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fe=/* @__PURE__ */ft("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);const r=je[typeof e.value];t._zod.onattach.push(t=>{const r=t._zod.bag,o=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:"object"==typeof e.value?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),De=/* @__PURE__ */ft("$ZodCheckMultipleOf",(t,e)=>{Ae.init(t,e),t._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%e.value===BigInt(0):0===function(t,e){const r=(t.toString().split(".")[1]||"").length,o=e.toString();let n=(o.split(".")[1]||"").length;if(0===n&&/\d?e-\d?/.test(o)){const t=o.match(/\d?e-(\d?)/);t?.[1]&&(n=Number.parseInt(t[1]))}const a=r>n?r:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(e.toFixed(a).replace(".",""))/10**a}(r.value,e.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ze=/* @__PURE__ */ft("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),o=r?"int":"number",[n,a]=Ut[e.format];t._zod.onattach.push(t=>{const o=t._zod.bag;o.format=e.format,o.minimum=n,o.maximum=a,r&&(o.pattern=$e)}),t._zod.check=i=>{const s=i.value;if(r){if(!Number.isInteger(s))return void i.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:s,inst:t});if(!Number.isSafeInteger(s))return void(s>0?i.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):i.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}))}s<n&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),s>a&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),Ue=/* @__PURE__ */ft("$ZodCheckMaxLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(t._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const o=r.value;if(o.length<=e.maximum)return;const n=Jt(o);r.issues.push({origin:n,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Le=/* @__PURE__ */ft("$ZodCheckMinLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(t._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const o=r.value;if(o.length>=e.minimum)return;const n=Jt(o);r.issues.push({origin:n,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Re=/* @__PURE__ */ft("$ZodCheckLengthEquals",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=r=>{const o=r.value,n=o.length;if(n===e.length)return;const a=Jt(o),i=n>e.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),We=/* @__PURE__ */ft("$ZodCheckStringFormat",(t,e)=>{var r,o;Ae.init(t,e),t._zod.onattach.push(t=>{const r=t._zod.bag;r.format=e.format,e.pattern&&(r.patterns??(r.patterns=/* @__PURE__ */new Set),r.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=r=>{e.pattern.lastIndex=0,e.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Be=/* @__PURE__ */ft("$ZodCheckRegex",(t,e)=>{We.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,e.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Je=/* @__PURE__ */ft("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Te),We.init(t,e)}),Ve=/* @__PURE__ */ft("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Me),We.init(t,e)}),qe=/* @__PURE__ */ft("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);const r=Ft(e.includes),o=new RegExp("number"==typeof e.position?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(o)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),Ge=/* @__PURE__ */ft("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);const r=new RegExp(`^${Ft(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(r)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Ke=/* @__PURE__ */ft("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);const r=new RegExp(`.*${Ft(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(r)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),He=/* @__PURE__ */ft("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=t=>{t.value=e.tx(t.value)}});class Ye{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if("function"==typeof t)return t(this,{execution:"sync"}),void t(this,{execution:"async"});const e=t.split("\n").filter(t=>t),r=Math.min(...e.map(t=>t.length-t.trimStart().length)),o=e.map(t=>t.slice(r)).map(t=>" ".repeat(2*this.indent)+t);for(const n of o)this.content.push(n)}compile(){const t=Function,e=this?.args;return new t(...e,[...(this?.content??[""]).map(t=>` ${t}`)].join("\n"))}}const Xe={major:4,minor:3,patch:6},Qe=/* @__PURE__ */ft("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xe;const o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(const n of o)for(const e of n._zod.onattach)e(t);if(0===o.length)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const e=(t,e,r)=>{let o,n=Lt(t);for(const a of e){if(a._zod.def.when){if(!a._zod.def.when(t))continue}else if(n)continue;const e=t.issues.length,i=a._zod.check(t);if(i instanceof Promise&&!1===r?.async)throw new wt;if(o||i instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await i,t.issues.length!==e&&(n||(n=Lt(t,e)))});else{if(t.issues.length===e)continue;n||(n=Lt(t,e))}}return o?o.then(()=>t):t},r=(r,n,a)=>{if(Lt(r))return r.aborted=!0,r;const i=e(n,o,a);if(i instanceof Promise){if(!1===a.async)throw new wt;return i.then(e=>t._zod.parse(e,a))}return t._zod.parse(i,a)};t._zod.run=(n,a)=>{if(a.skipChecks)return t._zod.parse(n,a);if("backward"===a.direction){const e=t._zod.parse({value:n.value,issues:[]},{...a,skipChecks:!0});return e instanceof Promise?e.then(t=>r(t,n,a)):r(e,n,a)}const i=t._zod.parse(n,a);if(i instanceof Promise){if(!1===a.async)throw new wt;return i.then(t=>e(t,o,a))}return e(i,o,a)}}Ot(t,"~standard",()=>({validate:e=>{try{const r=Qt(t,e);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return ee(t,e).then(t=>t.success?{value:t.data}:{issues:t.error?.issues})}},vendor:"zod",version:1}))}),tr=/* @__PURE__ */ft("$ZodString",(t,e)=>{var r;Qe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??(r=t._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),er=/* @__PURE__ */ft("$ZodStringFormat",(t,e)=>{We.init(t,e),tr.init(t,e)}),rr=/* @__PURE__ */ft("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=we),er.init(t,e)}),or=/* @__PURE__ */ft("$ZodUUID",(t,e)=>{if(e.version){const t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(void 0===t)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=be(t))}else e.pattern??(e.pattern=be());er.init(t,e)}),nr=/* @__PURE__ */ft("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ve),er.init(t,e)}),ar=/* @__PURE__ */ft("$ZodURL",(t,e)=>{er.init(t,e),t._zod.check=r=>{try{const o=r.value.trim(),n=new URL(o);return e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),void(e.normalize?r.value=n.href:r.value=o)}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ir=/* @__PURE__ */ft("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),er.init(t,e)}),sr=/* @__PURE__ */ft("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=me),er.init(t,e)}),cr=/* @__PURE__ */ft("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=de),er.init(t,e)}),lr=/* @__PURE__ */ft("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ue),er.init(t,e)}),dr=/* @__PURE__ */ft("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pe),er.init(t,e)}),ur=/* @__PURE__ */ft("$ZodXID",(t,e)=>{e.pattern??(e.pattern=he),er.init(t,e)}),pr=/* @__PURE__ */ft("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ge),er.init(t,e)}),hr=/* @__PURE__ */ft("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=function(t){const e=Ce({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${e}(?:${r.join("|")})`;return new RegExp(`^${Oe}T(?:${o})$`)}(e)),er.init(t,e)}),gr=/* @__PURE__ */ft("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ie),er.init(t,e)}),mr=/* @__PURE__ */ft("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=new RegExp(`^${Ce(e)}$`)),er.init(t,e)}),fr=/* @__PURE__ */ft("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=fe),er.init(t,e)}),wr=/* @__PURE__ */ft("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ye),er.init(t,e),t._zod.bag.format="ipv4"}),br=/* @__PURE__ */ft("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xe),er.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),vr=/* @__PURE__ */ft("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ke),er.init(t,e)}),yr=/* @__PURE__ */ft("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=_e),er.init(t,e),t._zod.check=r=>{const o=r.value.split("/");try{if(2!==o.length)throw new Error;const[t,e]=o;if(!e)throw new Error;const r=Number(e);if(`${r}`!==e)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function xr(t){if(""===t)return!0;if(t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}const kr=/* @__PURE__ */ft("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ze),er.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{xr(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}}),_r=/* @__PURE__ */ft("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ee),er.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{(function(t){if(!Ee.test(t))return!1;const e=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return xr(e.padEnd(4*Math.ceil(e.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),zr=/* @__PURE__ */ft("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Se),er.init(t,e)}),Er=/* @__PURE__ */ft("$ZodJWT",(t,e)=>{er.init(t,e),t._zod.check=r=>{(function(t,e=null){try{const r=t.split(".");if(3!==r.length)return!1;const[o]=r;if(!o)return!1;const n=JSON.parse(atob(o));return!("typ"in n&&"JWT"!==n?.typ||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}})(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Sr=/* @__PURE__ */ft("$ZodNumber",(t,e)=>{Qe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ne,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch(i){}const n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;const a="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...a?{received:a}:{}}),r}}),Or=/* @__PURE__ */ft("$ZodNumberFormat",(t,e)=>{Ze.init(t,e),Sr.init(t,e)}),Ir=/* @__PURE__ */ft("$ZodAny",(t,e)=>{Qe.init(t,e),t._zod.parse=t=>t}),Cr=/* @__PURE__ */ft("$ZodUnknown",(t,e)=>{Qe.init(t,e),t._zod.parse=t=>t}),$r=/* @__PURE__ */ft("$ZodNever",(t,e)=>{Qe.init(t,e),t._zod.parse=(e,r)=>(e.issues.push({expected:"never",code:"invalid_type",input:e.value,inst:t}),e)});function Nr(t,e,r){t.issues.length&&e.issues.push(...Rt(r,t.issues)),e.value[r]=t.value}const Tr=/* @__PURE__ */ft("$ZodArray",(t,e)=>{Qe.init(t,e),t._zod.parse=(r,o)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const a=[];for(let t=0;t<n.length;t++){const i=n[t],s=e.element._zod.run({value:i,issues:[]},o);s instanceof Promise?a.push(s.then(e=>Nr(e,r,t))):Nr(s,r,t)}return a.length?Promise.all(a).then(()=>r):r}});function Mr(t,e,r,o,n){if(t.issues.length){if(n&&!(r in o))return;e.issues.push(...Rt(r,t.issues))}void 0===t.value?r in o&&(e.value[r]=void 0):e.value[r]=t.value}function Ar(t){const e=Object.keys(t.shape);for(const n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=(o=t.shape,Object.keys(o).filter(t=>"optional"===o[t]._zod.optin&&"optional"===o[t]._zod.optout));var o;return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function jr(t,e,r,o,n,a){const i=[],s=n.keySet,c=n.catchall._zod,l=c.def.type,d="optional"===c.optout;for(const u in e){if(s.has(u))continue;if("never"===l){i.push(u);continue}const n=c.run({value:e[u],issues:[]},o);n instanceof Promise?t.push(n.then(t=>Mr(t,r,u,e,d))):Mr(n,r,u,e,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:a}),t.length?Promise.all(t).then(()=>r):r}const Pr=/* @__PURE__ */ft("$ZodObject",(t,e)=>{Qe.init(t,e);const r=Object.getOwnPropertyDescriptor(e,"shape");if(!r?.get){const t=e.shape;Object.defineProperty(e,"shape",{get:()=>{const r={...t};return Object.defineProperty(e,"shape",{value:r}),r}})}const o=_t(()=>Ar(e));Ot(t._zod,"propValues",()=>{const t=e.shape,r={};for(const e in t){const o=t[e]._zod;if(o.values){r[e]??(r[e]=/* @__PURE__ */new Set);for(const t of o.values)r[e].add(t)}}return r});const n=Tt,a=e.catchall;let i;t._zod.parse=(e,r)=>{i??(i=o.value);const s=e.value;if(!n(s))return e.issues.push({expected:"object",code:"invalid_type",input:s,inst:t}),e;e.value={};const c=[],l=i.shape;for(const t of i.keys){const o=l[t],n="optional"===o._zod.optout,a=o._zod.run({value:s[t],issues:[]},r);a instanceof Promise?c.push(a.then(r=>Mr(r,e,t,s,n))):Mr(a,e,t,s,n)}return a?jr(c,s,e,r,o.value,t):c.length?Promise.all(c).then(()=>e):e}}),Fr=/* @__PURE__ */ft("$ZodObjectJIT",(t,e)=>{Pr.init(t,e);const r=t._zod.parse,o=_t(()=>Ar(e));let n;const a=Tt,i=!vt.jitless,s=i&&Mt.value,c=e.catchall;let l;t._zod.parse=(d,u)=>{l??(l=o.value);const p=d.value;return a(p)?i&&s&&!1===u?.async&&!0!==u.jitless?(n||(n=(t=>{const e=new Ye(["shape","payload","ctx"]),r=o.value,n=t=>{const e=$t(t);return`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`};e.write("const input = payload.value;");const a=/* @__PURE__ */Object.create(null);let i=0;for(const o of r.keys)a[o]="key_"+i++;e.write("const newResult = {};");for(const o of r.keys){const r=a[o],i=$t(o),s=t[o],c="optional"===s?._zod?.optout;e.write(`const ${r} = ${n(o)};`),c?e.write(`\n if (${r}.issues.length) {\n if (${i} in input) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `):e.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `)}e.write("payload.value = newResult;"),e.write("return payload;");const s=e.compile();return(e,r)=>s(t,e,r)})(e.shape)),d=n(d,u),c?jr([],p,d,u,l,t):d):r(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d)}});function Dr(t,e,r,o){for(const a of t)if(0===a.issues.length)return e.value=a.value,e;const n=t.filter(t=>!Lt(t));return 1===n.length?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(t=>t.issues.map(t=>Bt(t,o,yt())))}),e)}const Zr=/* @__PURE__ */ft("$ZodUnion",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.options.some(t=>"optional"===t._zod.optin)?"optional":void 0),Ot(t._zod,"optout",()=>e.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),Ot(t._zod,"values",()=>{if(e.options.every(t=>t._zod.values))return new Set(e.options.flatMap(t=>Array.from(t._zod.values)))}),Ot(t._zod,"pattern",()=>{if(e.options.every(t=>t._zod.pattern)){const t=e.options.map(t=>t._zod.pattern);return new RegExp(`^(${t.map(t=>Et(t.source)).join("|")})$`)}});const r=1===e.options.length,o=e.options[0]._zod.run;t._zod.parse=(n,a)=>{if(r)return o(n,a);let i=!1;const s=[];for(const t of e.options){const e=t._zod.run({value:n.value,issues:[]},a);if(e instanceof Promise)s.push(e),i=!0;else{if(0===e.issues.length)return e;s.push(e)}}return i?Promise.all(s).then(e=>Dr(e,n,t,a)):Dr(s,n,t,a)}}),Ur=/* @__PURE__ */ft("$ZodIntersection",(t,e)=>{Qe.init(t,e),t._zod.parse=(t,r)=>{const o=t.value,n=e.left._zod.run({value:o,issues:[]},r),a=e.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||a instanceof Promise?Promise.all([n,a]).then(([e,r])=>Rr(t,e,r)):Rr(t,n,a)}});function Lr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t===+e)return{valid:!0,data:t};if(At(t)&&At(e)){const r=Object.keys(e),o=Object.keys(t).filter(t=>-1!==r.indexOf(t)),n={...t,...e};for(const a of o){const r=Lr(t[a],e[a]);if(!r.valid)return{valid:!1,mergeErrorPath:[a,...r.mergeErrorPath]};n[a]=r.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let o=0;o<t.length;o++){const n=Lr(t[o],e[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};r.push(n.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Rr(t,e,r){const o=/* @__PURE__ */new Map;let n;for(const s of e.issues)if("unrecognized_keys"===s.code){n??(n=s);for(const t of s.keys)o.has(t)||o.set(t,{}),o.get(t).l=!0}else t.issues.push(s);for(const s of r.issues)if("unrecognized_keys"===s.code)for(const t of s.keys)o.has(t)||o.set(t,{}),o.get(t).r=!0;else t.issues.push(s);const a=[...o].filter(([,t])=>t.l&&t.r).map(([t])=>t);if(a.length&&n&&t.issues.push({...n,keys:a}),Lt(t))return t;const i=Lr(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}const Wr=/* @__PURE__ */ft("$ZodEnum",(t,e)=>{Qe.init(t,e);const r=xt(e.entries),o=new Set(r);t._zod.values=o,t._zod.pattern=new RegExp(`^(${r.filter(t=>Pt.has(typeof t)).map(t=>"string"==typeof t?Ft(t):t.toString()).join("|")})$`),t._zod.parse=(e,n)=>{const a=e.value;return o.has(a)||e.issues.push({code:"invalid_value",values:r,input:a,inst:t}),e}}),Br=/* @__PURE__ */ft("$ZodTransform",(t,e)=>{Qe.init(t,e),t._zod.parse=(r,o)=>{if("backward"===o.direction)throw new bt(t.constructor.name);const n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(r.value=t,r));if(n instanceof Promise)throw new wt;return r.value=n,r}});function Jr(t,e){return t.issues.length&&void 0===e?{issues:[],value:void 0}:t}const Vr=/* @__PURE__ */ft("$ZodOptional",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ot(t._zod,"values",()=>e.innerType._zod.values?/* @__PURE__ */new Set([...e.innerType._zod.values,void 0]):void 0),Ot(t._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${Et(t.source)})?$`):void 0}),t._zod.parse=(t,r)=>{if("optional"===e.innerType._zod.optin){const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(e=>Jr(e,t.value)):Jr(o,t.value)}return void 0===t.value?t:e.innerType._zod.run(t,r)}}),qr=/* @__PURE__ */ft("$ZodExactOptional",(t,e)=>{Vr.init(t,e),Ot(t._zod,"values",()=>e.innerType._zod.values),Ot(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(t,r)=>e.innerType._zod.run(t,r)}),Gr=/* @__PURE__ */ft("$ZodNullable",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.innerType._zod.optin),Ot(t._zod,"optout",()=>e.innerType._zod.optout),Ot(t._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${Et(t.source)}|null)$`):void 0}),Ot(t._zod,"values",()=>e.innerType._zod.values?/* @__PURE__ */new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(t,r)=>null===t.value?t:e.innerType._zod.run(t,r)}),Kr=/* @__PURE__ */ft("$ZodDefault",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);if(void 0===t.value)return t.value=e.defaultValue,t;const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(t=>Hr(t,e)):Hr(o,e)}});function Hr(t,e){return void 0===t.value&&(t.value=e.defaultValue),t}const Yr=/* @__PURE__ */ft("$ZodPrefault",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>("backward"===r.direction||void 0===t.value&&(t.value=e.defaultValue),e.innerType._zod.run(t,r))}),Xr=/* @__PURE__ */ft("$ZodNonOptional",(t,e)=>{Qe.init(t,e),Ot(t._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(t=>void 0!==t)):void 0}),t._zod.parse=(r,o)=>{const n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(e=>Qr(e,t)):Qr(n,t)}});function Qr(t,e){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const to=/* @__PURE__ */ft("$ZodCatch",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.innerType._zod.optin),Ot(t._zod,"optout",()=>e.innerType._zod.optout),Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(o=>(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(t=>Bt(t,r,yt()))},input:t.value}),t.issues=[]),t)):(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(t=>Bt(t,r,yt()))},input:t.value}),t.issues=[]),t)}}),eo=/* @__PURE__ */ft("$ZodPipe",(t,e)=>{Qe.init(t,e),Ot(t._zod,"values",()=>e.in._zod.values),Ot(t._zod,"optin",()=>e.in._zod.optin),Ot(t._zod,"optout",()=>e.out._zod.optout),Ot(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(t,r)=>{if("backward"===r.direction){const o=e.out._zod.run(t,r);return o instanceof Promise?o.then(t=>ro(t,e.in,r)):ro(o,e.in,r)}const o=e.in._zod.run(t,r);return o instanceof Promise?o.then(t=>ro(t,e.out,r)):ro(o,e.out,r)}});function ro(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}const oo=/* @__PURE__ */ft("$ZodReadonly",(t,e)=>{Qe.init(t,e),Ot(t._zod,"propValues",()=>e.innerType._zod.propValues),Ot(t._zod,"values",()=>e.innerType._zod.values),Ot(t._zod,"optin",()=>e.innerType?._zod?.optin),Ot(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(no):no(o)}});function no(t){return t.value=Object.freeze(t.value),t}const ao=/* @__PURE__ */ft("$ZodCustom",(t,e)=>{Ae.init(t,e),Qe.init(t,e),t._zod.parse=(t,e)=>t,t._zod.check=r=>{const o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(e=>io(e,r,o,t));io(n,r,o,t)}});function io(t,e,r,o){if(!t){const t={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(t.params=o._zod.def.params),e.issues.push(Vt(t))}}var so;(so=globalThis).__zod_globalRegistry??(so.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(t,...e){const r=e[0];return this._map.set(t,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(t){const e=this._map.get(t);return e&&"object"==typeof e&&"id"in e&&this._idmap.delete(e.id),this._map.delete(t),this}get(t){const e=t._zod.parent;if(e){const r={...this.get(e)??{}};delete r.id;const o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});const co=globalThis.__zod_globalRegistry;function lo(t,e){return new t({type:"string",...Zt(e)})}function uo(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Zt(e)})}function po(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Zt(e)})}function ho(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Zt(e)})}function go(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Zt(e)})}function mo(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Zt(e)})}function fo(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Zt(e)})}function wo(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Zt(e)})}function bo(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Zt(e)})}function vo(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Zt(e)})}function yo(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Zt(e)})}function xo(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Zt(e)})}function ko(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Zt(e)})}function _o(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Zt(e)})}function zo(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Zt(e)})}function Eo(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Zt(e)})}function So(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Zt(e)})}function Oo(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Zt(e)})}function Io(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Zt(e)})}function Co(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Zt(e)})}function $o(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Zt(e)})}function No(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Zt(e)})}function To(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Zt(e)})}function Mo(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Zt(e)})}function Ao(t,e){return new t({type:"string",format:"date",check:"string_format",...Zt(e)})}function jo(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Zt(e)})}function Po(t,e){return new t({type:"string",format:"duration",check:"string_format",...Zt(e)})}function Fo(t,e){return new t({type:"number",checks:[],...Zt(e)})}function Do(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Zt(e)})}function Zo(t){return new t({type:"any"})}function Uo(t){return new t({type:"unknown"})}function Lo(t,e){return new t({type:"never",...Zt(e)})}function Ro(t,e){return new Pe({check:"less_than",...Zt(e),value:t,inclusive:!1})}function Wo(t,e){return new Pe({check:"less_than",...Zt(e),value:t,inclusive:!0})}function Bo(t,e){return new Fe({check:"greater_than",...Zt(e),value:t,inclusive:!1})}function Jo(t,e){return new Fe({check:"greater_than",...Zt(e),value:t,inclusive:!0})}function Vo(t,e){return new De({check:"multiple_of",...Zt(e),value:t})}function qo(t,e){return new Ue({check:"max_length",...Zt(e),maximum:t})}function Go(t,e){return new Le({check:"min_length",...Zt(e),minimum:t})}function Ko(t,e){return new Re({check:"length_equals",...Zt(e),length:t})}function Ho(t,e){return new Be({check:"string_format",format:"regex",...Zt(e),pattern:t})}function Yo(t){return new Je({check:"string_format",format:"lowercase",...Zt(t)})}function Xo(t){return new Ve({check:"string_format",format:"uppercase",...Zt(t)})}function Qo(t,e){return new qe({check:"string_format",format:"includes",...Zt(e),includes:t})}function tn(t,e){return new Ge({check:"string_format",format:"starts_with",...Zt(e),prefix:t})}function en(t,e){return new Ke({check:"string_format",format:"ends_with",...Zt(e),suffix:t})}function rn(t){return new He({check:"overwrite",tx:t})}function on(t){/* @__PURE__ */
|
|
15
|
+
/* @__PURE__ */$("button",{onClick:this.handleReset,className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 transition-opacity",children:"Intentar de nuevo"})]}):this.props.children}}const L={bubble:"rounded-2xl",image:"rounded-xl",button:"rounded-xl",card:"rounded-2xl"},R={bg:"bg-muted/50 dark:bg-muted/20",text:"text-foreground",border:"border-border/50"},W={text:"text-primary-foreground"};const B=(t,e)=>e.some(e=>t instanceof e);let J,V;const q=/* @__PURE__ */new WeakMap,G=/* @__PURE__ */new WeakMap,K=/* @__PURE__ */new WeakMap;let H={get(t,e,r){if(t instanceof IDBTransaction){if("done"===e)return q.get(t);if("store"===e)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Q(t[e])},set:(t,e,r)=>(t[e]=r,!0),has:(t,e)=>t instanceof IDBTransaction&&("done"===e||"store"===e)||e in t};function Y(t){H=t(H)}function X(t){return"function"==typeof t?(e=t,(V||(V=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(e)?function(...t){return e.apply(tt(this),t),Q(this.request)}:function(...t){return Q(e.apply(tt(this),t))}):(t instanceof IDBTransaction&&function(t){if(q.has(t))return;const e=new Promise((e,r)=>{const o=()=>{t.removeEventListener("complete",n),t.removeEventListener("error",a),t.removeEventListener("abort",a)},n=()=>{e(),o()},a=()=>{r(t.error||new DOMException("AbortError","AbortError")),o()};t.addEventListener("complete",n),t.addEventListener("error",a),t.addEventListener("abort",a)});q.set(t,e)}(t),B(t,J||(J=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(t,H):t);var e}function Q(t){if(t instanceof IDBRequest)return function(t){const e=new Promise((e,r)=>{const o=()=>{t.removeEventListener("success",n),t.removeEventListener("error",a)},n=()=>{e(Q(t.result)),o()},a=()=>{r(t.error),o()};t.addEventListener("success",n),t.addEventListener("error",a)});return K.set(e,t),e}(t);if(G.has(t))return G.get(t);const e=X(t);return e!==t&&(G.set(t,e),K.set(e,t)),e}const tt=t=>K.get(t),et=["get","getKey","getAll","getAllKeys","count"],rt=["put","add","delete","clear"],ot=/* @__PURE__ */new Map;function nt(t,e){if(!(t instanceof IDBDatabase)||e in t||"string"!=typeof e)return;if(ot.get(e))return ot.get(e);const r=e.replace(/FromIndex$/,""),o=e!==r,n=rt.includes(r);if(!(r in(o?IDBIndex:IDBObjectStore).prototype)||!n&&!et.includes(r))return;const a=async function(t,...e){const a=this.transaction(t,n?"readwrite":"readonly");let i=a.store;return o&&(i=i.index(e.shift())),(await Promise.all([i[r](...e),n&&a.done]))[0]};return ot.set(e,a),a}Y(t=>({...t,get:(e,r,o)=>nt(e,r)||t.get(e,r,o),has:(e,r)=>!!nt(e,r)||t.has(e,r)}));const at=["continue","continuePrimaryKey","advance"],it={},st=/* @__PURE__ */new WeakMap,ct=/* @__PURE__ */new WeakMap,lt={get(t,e){if(!at.includes(e))return t[e];let r=it[e];return r||(r=it[e]=function(...t){st.set(this,ct.get(this)[e](...t))}),r}};async function*dt(...t){let e=this;if(e instanceof IDBCursor||(e=await e.openCursor(...t)),!e)return;const r=new Proxy(e,lt);for(ct.set(r,e),K.set(r,tt(e));e;)yield r,e=await(st.get(r)||e.continue()),st.delete(r)}function ut(t,e){return e===Symbol.asyncIterator&&B(t,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===e&&B(t,[IDBIndex,IDBObjectStore])}Y(t=>({...t,get:(e,r,o)=>ut(e,r)?dt:t.get(e,r,o),has:(e,r)=>ut(e,r)||t.has(e,r)}));class pt{db=null;DB_NAME;DB_VERSION=1;constructor(t="default"){this.DB_NAME=`botuyo-chat-${t}`}async init(){try{this.db=await function(t,e,{blocked:r,upgrade:o,blocking:n,terminated:a}={}){const i=indexedDB.open(t,e),s=Q(i);return o&&i.addEventListener("upgradeneeded",t=>{o(Q(i.result),t.oldVersion,t.newVersion,Q(i.transaction),t)}),r&&i.addEventListener("blocked",t=>r(t.oldVersion,t.newVersion,t)),s.then(t=>{a&&t.addEventListener("close",()=>a()),n&&t.addEventListener("versionchange",t=>n(t.oldVersion,t.newVersion,t))}).catch(()=>{}),s}(this.DB_NAME,this.DB_VERSION,{upgrade(t){t.objectStoreNames.contains("messages")||t.createObjectStore("messages",{keyPath:"id"}).createIndex("by-timestamp","timestamp"),t.objectStoreNames.contains("metadata")||t.createObjectStore("metadata")}}),x.info("IndexedDB initialized")}catch(t){throw x.error("Failed to initialize IndexedDB:",t),t}}async saveMessage(t){this.db||await this.init();try{await this.db.put("messages",t)}catch(e){x.error("Failed to save message:",e)}}async saveMessages(t){this.db||await this.init();try{const e=this.db.transaction("messages","readwrite");await Promise.all([...t.map(t=>e.store.put(t)),e.done])}catch(e){x.error("Failed to save messages:",e)}}async getMessages(t=100){this.db||await this.init();try{return(await this.db.getAllFromIndex("messages","by-timestamp")).slice(-t)}catch(e){return x.error("Failed to get messages:",e),[]}}async getMessage(t){this.db||await this.init();try{return await this.db.get("messages",t)}catch(e){return void x.error("Failed to get message:",e)}}async deleteMessage(t){this.db||await this.init();try{await this.db.delete("messages",t)}catch(e){x.error("Failed to delete message:",e)}}async clearMessages(){this.db||await this.init();try{await this.db.clear("messages"),x.info("Messages cleared from IndexedDB")}catch(t){x.error("Failed to clear messages:",t)}}async setMetadata(t){this.db||await this.init();try{await this.db.put("metadata",t,"chat-metadata")}catch(e){x.error("Failed to set metadata:",e)}}async getMetadata(){this.db||await this.init();try{return await this.db.get("metadata","chat-metadata")}catch(t){return x.error("Failed to get metadata:",t),null}}async clearAll(){this.db||await this.init();try{await Promise.all([this.db.clear("messages"),this.db.clear("metadata")]),x.info("All data cleared from IndexedDB")}catch(t){x.error("Failed to clear all data:",t)}}async migrateFromLocalStorage(t="default"){try{const e=`botuyo_chat_v1_${t}`,r=localStorage.getItem(e);if(!r)return;const o=JSON.parse(r);if(o.messages&&Array.isArray(o.messages)){const t=o.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}));await this.saveMessages(t),x.info(`Migrated ${t.length} messages from localStorage`)}o.sessionId&&await this.setMetadata({sessionId:o.sessionId}),localStorage.removeItem(e),x.info("Migration from localStorage completed")}catch(e){x.error("Failed to migrate from localStorage:",e)}}}const ht=/* @__PURE__ */new Map,gt={isOpen:!1,isConnected:!1,isTyping:!1,messages:[],error:null,sessionId:null};function mt(t,e){switch(e.type){case"TOGGLE_WINDOW":return{...t,isOpen:!t.isOpen};case"OPEN_WINDOW":return{...t,isOpen:!0};case"CLOSE_WINDOW":return{...t,isOpen:!1};case"SET_CONNECTED":return{...t,isConnected:e.payload};case"SET_TYPING":return{...t,isTyping:e.payload};case"ADD_MESSAGE":{if(t.messages.some(t=>t.id===e.payload.id))return t;if(e.payload.id.startsWith("msg-")&&"text"===e.payload.type){const r=/* @__PURE__ */(new Date).getTime();if(t.messages.slice(-10).some(t=>"text"===t.type&&t.sender===e.payload.sender&&"content"in t&&"content"in e.payload&&t.content===e.payload.content&&Math.abs(r-new Date(t.timestamp).getTime())<3e4))return t}const r=[...t.messages,e.payload],o="bot"===e.payload.sender;return{...t,messages:r,isTyping:!o&&t.isTyping}}case"SET_MESSAGES":return{...t,messages:[...e.payload]};case"SET_ERROR":return{...t,error:e.payload};case"SET_SESSION_ID":return{...t,sessionId:e.payload};case"CLEAR_CHAT":return{...gt,isOpen:t.isOpen};case"RESTORE_SESSION":return{...t,...e.payload,isConnected:!1,isTyping:!1,error:null};default:return t}}function ft(t,e,r){function o(r,o){if(r._zod||Object.defineProperty(r,"_zod",{value:{def:o,constr:i,traits:/* @__PURE__ */new Set},enumerable:!1}),r._zod.traits.has(t))return;r._zod.traits.add(t),e(r,o);const n=i.prototype,a=Object.keys(n);for(let t=0;t<a.length;t++){const e=a[t];e in r||(r[e]=n[e].bind(r))}}const n=r?.Parent??Object;class a extends n{}function i(t){var e;const n=r?.Parent?new a:this;o(n,t),(e=n._zod).deferred??(e.deferred=[]);for(const r of n._zod.deferred)r();return n}return Object.defineProperty(a,"name",{value:t}),Object.defineProperty(i,"init",{value:o}),Object.defineProperty(i,Symbol.hasInstance,{value:e=>!!(r?.Parent&&e instanceof r.Parent)||e?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}class wt extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class bt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const vt={};function yt(t){return vt}function xt(t){const e=Object.values(t).filter(t=>"number"==typeof t);return Object.entries(t).filter(([t,r])=>-1===e.indexOf(+t)).map(([t,e])=>e)}function kt(t,e){return"bigint"==typeof e?e.toString():e}function _t(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function zt(t){return null==t}function Et(t){const e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}const St=/* @__PURE__ */Symbol("evaluating");function Ot(t,e,r){let o;Object.defineProperty(t,e,{get(){if(o!==St)return void 0===o&&(o=St,o=r()),o},set(r){Object.defineProperty(t,e,{value:r})},configurable:!0})}function It(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ct(...t){const e={};for(const r of t){const t=Object.getOwnPropertyDescriptors(r);Object.assign(e,t)}return Object.defineProperties({},e)}function $t(t){return JSON.stringify(t)}const Nt="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Tt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}const Mt=_t(()=>{if("undefined"!=typeof navigator&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(t){return!1}});function At(t){if(!1===Tt(t))return!1;const e=t.constructor;if(void 0===e)return!0;if("function"!=typeof e)return!0;const r=e.prototype;return!1!==Tt(r)&&!1!==Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")}function jt(t){return At(t)?{...t}:Array.isArray(t)?[...t]:t}const Pt=/* @__PURE__ */new Set(["string","number","symbol"]);function Ft(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dt(t,e,r){const o=new t._zod.constr(e??t._zod.def);return e&&!r?.parent||(o._zod.parent=t),o}function Zt(t){const e=t;if(!e)return{};if("string"==typeof e)return{error:()=>e};if(void 0!==e?.message){if(void 0!==e?.error)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,"string"==typeof e.error?{...e,error:()=>e.error}:e}const Ut={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Lt(t,e=0){if(!0===t.aborted)return!0;for(let r=e;r<t.issues.length;r++)if(!0!==t.issues[r]?.continue)return!0;return!1}function Rt(t,e){return e.map(e=>{var r;return(r=e).path??(r.path=[]),e.path.unshift(t),e})}function Wt(t){return"string"==typeof t?t:t?.message}function Bt(t,e,r){const o={...t,path:t.path??[]};if(!t.message){const n=Wt(t.inst?._zod.def?.error?.(t))??Wt(e?.error?.(t))??Wt(r.customError?.(t))??Wt(r.localeError?.(t))??"Invalid input";o.message=n}return delete o.inst,delete o.continue,e?.reportInput||delete o.input,o}function Jt(t){return Array.isArray(t)?"array":"string"==typeof t?"string":"unknown"}function Vt(...t){const[e,r,o]=t;return"string"==typeof e?{message:e,code:"custom",input:r,inst:o}:{...e}}const qt=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,kt,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gt=ft("$ZodError",qt),Kt=ft("$ZodError",qt,{Parent:Error}),Ht=t=>(e,r,o,n)=>{const a=o?Object.assign(o,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise)throw new wt;if(i.issues.length){const e=new(n?.Err??t)(i.issues.map(t=>Bt(t,a,yt())));throw Nt(e,n?.callee),e}return i.value},Yt=t=>async(e,r,o,n)=>{const a=o?Object.assign(o,{async:!0}):{async:!0};let i=e._zod.run({value:r,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const e=new(n?.Err??t)(i.issues.map(t=>Bt(t,a,yt())));throw Nt(e,n?.callee),e}return i.value},Xt=t=>(e,r,o)=>{const n=o?{...o,async:!1}:{async:!1},a=e._zod.run({value:r,issues:[]},n);if(a instanceof Promise)throw new wt;return a.issues.length?{success:!1,error:new(t??Gt)(a.issues.map(t=>Bt(t,n,yt())))}:{success:!0,data:a.value}},Qt=/* @__PURE__ */Xt(Kt),te=t=>async(e,r,o)=>{const n=o?Object.assign(o,{async:!0}):{async:!0};let a=e._zod.run({value:r,issues:[]},n);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new t(a.issues.map(t=>Bt(t,n,yt())))}:{success:!0,data:a.value}},ee=/* @__PURE__ */te(Kt),re=t=>(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Ht(t)(e,r,n)},oe=t=>(e,r,o)=>Ht(t)(e,r,o),ne=t=>async(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Yt(t)(e,r,n)},ae=t=>async(e,r,o)=>Yt(t)(e,r,o),ie=t=>(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return Xt(t)(e,r,n)},se=t=>(e,r,o)=>Xt(t)(e,r,o),ce=t=>async(e,r,o)=>{const n=o?Object.assign(o,{direction:"backward"}):{direction:"backward"};return te(t)(e,r,n)},le=t=>async(e,r,o)=>te(t)(e,r,o),de=/^[cC][^\s-]{8,}$/,ue=/^[0-9a-z]+$/,pe=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,he=/^[0-9a-vA-V]{20}$/,ge=/^[A-Za-z0-9]{27}$/,me=/^[a-zA-Z0-9_-]{21}$/,fe=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,we=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,be=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,ve=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ye=/^(?:(?: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])$/,xe=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,ke=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,_e=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ze=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ee=/^[A-Za-z0-9_-]*$/,Se=/^\+[1-9]\d{6,14}$/,Oe="(?:(?:\\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])))",Ie=/* @__PURE__ */new RegExp(`^${Oe}$`);function Ce(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return"number"==typeof t.precision?-1===t.precision?`${e}`:0===t.precision?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}const $e=/^-?\d+$/,Ne=/^-?\d+(?:\.\d+)?$/,Te=/^[^A-Z]*$/,Me=/^[^a-z]*$/,Ae=/* @__PURE__ */ft("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),je={number:"number",bigint:"bigint",object:"date"},Pe=/* @__PURE__ */ft("$ZodCheckLessThan",(t,e)=>{Ae.init(t,e);const r=je[typeof e.value];t._zod.onattach.push(t=>{const r=t._zod.bag,o=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value<=e.value:o.value<e.value)||o.issues.push({origin:r,code:"too_big",maximum:"object"==typeof e.value?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fe=/* @__PURE__ */ft("$ZodCheckGreaterThan",(t,e)=>{Ae.init(t,e);const r=je[typeof e.value];t._zod.onattach.push(t=>{const r=t._zod.bag,o=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),t._zod.check=o=>{(e.inclusive?o.value>=e.value:o.value>e.value)||o.issues.push({origin:r,code:"too_small",minimum:"object"==typeof e.value?e.value.getTime():e.value,input:o.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),De=/* @__PURE__ */ft("$ZodCheckMultipleOf",(t,e)=>{Ae.init(t,e),t._zod.onattach.push(t=>{var r;(r=t._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");("bigint"==typeof r.value?r.value%e.value===BigInt(0):0===function(t,e){const r=(t.toString().split(".")[1]||"").length,o=e.toString();let n=(o.split(".")[1]||"").length;if(0===n&&/\d?e-\d?/.test(o)){const t=o.match(/\d?e-(\d?)/);t?.[1]&&(n=Number.parseInt(t[1]))}const a=r>n?r:n;return Number.parseInt(t.toFixed(a).replace(".",""))%Number.parseInt(e.toFixed(a).replace(".",""))/10**a}(r.value,e.value))||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Ze=/* @__PURE__ */ft("$ZodCheckNumberFormat",(t,e)=>{Ae.init(t,e),e.format=e.format||"float64";const r=e.format?.includes("int"),o=r?"int":"number",[n,a]=Ut[e.format];t._zod.onattach.push(t=>{const o=t._zod.bag;o.format=e.format,o.minimum=n,o.maximum=a,r&&(o.pattern=$e)}),t._zod.check=i=>{const s=i.value;if(r){if(!Number.isInteger(s))return void i.issues.push({expected:o,format:e.format,code:"invalid_type",continue:!1,input:s,inst:t});if(!Number.isSafeInteger(s))return void(s>0?i.issues.push({input:s,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}):i.issues.push({input:s,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:o,inclusive:!0,continue:!e.abort}))}s<n&&i.issues.push({origin:"number",input:s,code:"too_small",minimum:n,inclusive:!0,inst:t,continue:!e.abort}),s>a&&i.issues.push({origin:"number",input:s,code:"too_big",maximum:a,inclusive:!0,inst:t,continue:!e.abort})}}),Ue=/* @__PURE__ */ft("$ZodCheckMaxLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(t._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const o=r.value;if(o.length<=e.maximum)return;const n=Jt(o);r.issues.push({origin:n,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Le=/* @__PURE__ */ft("$ZodCheckMinLength",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(t._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const o=r.value;if(o.length>=e.minimum)return;const n=Jt(o);r.issues.push({origin:n,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Re=/* @__PURE__ */ft("$ZodCheckLengthEquals",(t,e)=>{var r;Ae.init(t,e),(r=t._zod.def).when??(r.when=t=>{const e=t.value;return!zt(e)&&void 0!==e.length}),t._zod.onattach.push(t=>{const r=t._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),t._zod.check=r=>{const o=r.value,n=o.length;if(n===e.length)return;const a=Jt(o),i=n>e.length;r.issues.push({origin:a,...i?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),We=/* @__PURE__ */ft("$ZodCheckStringFormat",(t,e)=>{var r,o;Ae.init(t,e),t._zod.onattach.push(t=>{const r=t._zod.bag;r.format=e.format,e.pattern&&(r.patterns??(r.patterns=/* @__PURE__ */new Set),r.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=r=>{e.pattern.lastIndex=0,e.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(o=t._zod).check??(o.check=()=>{})}),Be=/* @__PURE__ */ft("$ZodCheckRegex",(t,e)=>{We.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,e.pattern.test(r.value)||r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Je=/* @__PURE__ */ft("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Te),We.init(t,e)}),Ve=/* @__PURE__ */ft("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Me),We.init(t,e)}),qe=/* @__PURE__ */ft("$ZodCheckIncludes",(t,e)=>{Ae.init(t,e);const r=Ft(e.includes),o=new RegExp("number"==typeof e.position?`^.{${e.position}}${r}`:r);e.pattern=o,t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(o)}),t._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:t,continue:!e.abort})}}),Ge=/* @__PURE__ */ft("$ZodCheckStartsWith",(t,e)=>{Ae.init(t,e);const r=new RegExp(`^${Ft(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(r)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),Ke=/* @__PURE__ */ft("$ZodCheckEndsWith",(t,e)=>{Ae.init(t,e);const r=new RegExp(`.*${Ft(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(t=>{const e=t._zod.bag;e.patterns??(e.patterns=/* @__PURE__ */new Set),e.patterns.add(r)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),He=/* @__PURE__ */ft("$ZodCheckOverwrite",(t,e)=>{Ae.init(t,e),t._zod.check=t=>{t.value=e.tx(t.value)}});class Ye{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if("function"==typeof t)return t(this,{execution:"sync"}),void t(this,{execution:"async"});const e=t.split("\n").filter(t=>t),r=Math.min(...e.map(t=>t.length-t.trimStart().length)),o=e.map(t=>t.slice(r)).map(t=>" ".repeat(2*this.indent)+t);for(const n of o)this.content.push(n)}compile(){const t=Function,e=this?.args;return new t(...e,[...(this?.content??[""]).map(t=>` ${t}`)].join("\n"))}}const Xe={major:4,minor:3,patch:6},Qe=/* @__PURE__ */ft("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Xe;const o=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&o.unshift(t);for(const n of o)for(const e of n._zod.onattach)e(t);if(0===o.length)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{const e=(t,e,r)=>{let o,n=Lt(t);for(const a of e){if(a._zod.def.when){if(!a._zod.def.when(t))continue}else if(n)continue;const e=t.issues.length,i=a._zod.check(t);if(i instanceof Promise&&!1===r?.async)throw new wt;if(o||i instanceof Promise)o=(o??Promise.resolve()).then(async()=>{await i,t.issues.length!==e&&(n||(n=Lt(t,e)))});else{if(t.issues.length===e)continue;n||(n=Lt(t,e))}}return o?o.then(()=>t):t},r=(r,n,a)=>{if(Lt(r))return r.aborted=!0,r;const i=e(n,o,a);if(i instanceof Promise){if(!1===a.async)throw new wt;return i.then(e=>t._zod.parse(e,a))}return t._zod.parse(i,a)};t._zod.run=(n,a)=>{if(a.skipChecks)return t._zod.parse(n,a);if("backward"===a.direction){const e=t._zod.parse({value:n.value,issues:[]},{...a,skipChecks:!0});return e instanceof Promise?e.then(t=>r(t,n,a)):r(e,n,a)}const i=t._zod.parse(n,a);if(i instanceof Promise){if(!1===a.async)throw new wt;return i.then(t=>e(t,o,a))}return e(i,o,a)}}Ot(t,"~standard",()=>({validate:e=>{try{const r=Qt(t,e);return r.success?{value:r.data}:{issues:r.error?.issues}}catch(r){return ee(t,e).then(t=>t.success?{value:t.data}:{issues:t.error?.issues})}},vendor:"zod",version:1}))}),tr=/* @__PURE__ */ft("$ZodString",(t,e)=>{var r;Qe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??(r=t._zod.bag,new RegExp(`^${r?`[\\s\\S]{${r?.minimum??0},${r?.maximum??""}}`:"[\\s\\S]*"}$`)),t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=String(r.value)}catch(n){}return"string"==typeof r.value||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),er=/* @__PURE__ */ft("$ZodStringFormat",(t,e)=>{We.init(t,e),tr.init(t,e)}),rr=/* @__PURE__ */ft("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=we),er.init(t,e)}),or=/* @__PURE__ */ft("$ZodUUID",(t,e)=>{if(e.version){const t={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(void 0===t)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=be(t))}else e.pattern??(e.pattern=be());er.init(t,e)}),nr=/* @__PURE__ */ft("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ve),er.init(t,e)}),ar=/* @__PURE__ */ft("$ZodURL",(t,e)=>{er.init(t,e),t._zod.check=r=>{try{const o=r.value.trim(),n=new URL(o);return e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),void(e.normalize?r.value=n.href:r.value=o)}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),ir=/* @__PURE__ */ft("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),er.init(t,e)}),sr=/* @__PURE__ */ft("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=me),er.init(t,e)}),cr=/* @__PURE__ */ft("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=de),er.init(t,e)}),lr=/* @__PURE__ */ft("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=ue),er.init(t,e)}),dr=/* @__PURE__ */ft("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pe),er.init(t,e)}),ur=/* @__PURE__ */ft("$ZodXID",(t,e)=>{e.pattern??(e.pattern=he),er.init(t,e)}),pr=/* @__PURE__ */ft("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=ge),er.init(t,e)}),hr=/* @__PURE__ */ft("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=function(t){const e=Ce({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const o=`${e}(?:${r.join("|")})`;return new RegExp(`^${Oe}T(?:${o})$`)}(e)),er.init(t,e)}),gr=/* @__PURE__ */ft("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Ie),er.init(t,e)}),mr=/* @__PURE__ */ft("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=new RegExp(`^${Ce(e)}$`)),er.init(t,e)}),fr=/* @__PURE__ */ft("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=fe),er.init(t,e)}),wr=/* @__PURE__ */ft("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ye),er.init(t,e),t._zod.bag.format="ipv4"}),br=/* @__PURE__ */ft("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xe),er.init(t,e),t._zod.bag.format="ipv6",t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),vr=/* @__PURE__ */ft("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=ke),er.init(t,e)}),yr=/* @__PURE__ */ft("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=_e),er.init(t,e),t._zod.check=r=>{const o=r.value.split("/");try{if(2!==o.length)throw new Error;const[t,e]=o;if(!e)throw new Error;const r=Number(e);if(`${r}`!==e)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function xr(t){if(""===t)return!0;if(t.length%4!=0)return!1;try{return atob(t),!0}catch{return!1}}const kr=/* @__PURE__ */ft("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=ze),er.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=r=>{xr(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}}),_r=/* @__PURE__ */ft("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ee),er.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=r=>{(function(t){if(!Ee.test(t))return!1;const e=t.replace(/[-_]/g,t=>"-"===t?"+":"/");return xr(e.padEnd(4*Math.ceil(e.length/4),"="))})(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),zr=/* @__PURE__ */ft("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Se),er.init(t,e)}),Er=/* @__PURE__ */ft("$ZodJWT",(t,e)=>{er.init(t,e),t._zod.check=r=>{(function(t,e=null){try{const r=t.split(".");if(3!==r.length)return!1;const[o]=r;if(!o)return!1;const n=JSON.parse(atob(o));return!("typ"in n&&"JWT"!==n?.typ||!n.alg||e&&(!("alg"in n)||n.alg!==e))}catch{return!1}})(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Sr=/* @__PURE__ */ft("$ZodNumber",(t,e)=>{Qe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ne,t._zod.parse=(r,o)=>{if(e.coerce)try{r.value=Number(r.value)}catch(i){}const n=r.value;if("number"==typeof n&&!Number.isNaN(n)&&Number.isFinite(n))return r;const a="number"==typeof n?Number.isNaN(n)?"NaN":Number.isFinite(n)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:n,inst:t,...a?{received:a}:{}}),r}}),Or=/* @__PURE__ */ft("$ZodNumberFormat",(t,e)=>{Ze.init(t,e),Sr.init(t,e)}),Ir=/* @__PURE__ */ft("$ZodAny",(t,e)=>{Qe.init(t,e),t._zod.parse=t=>t}),Cr=/* @__PURE__ */ft("$ZodUnknown",(t,e)=>{Qe.init(t,e),t._zod.parse=t=>t}),$r=/* @__PURE__ */ft("$ZodNever",(t,e)=>{Qe.init(t,e),t._zod.parse=(e,r)=>(e.issues.push({expected:"never",code:"invalid_type",input:e.value,inst:t}),e)});function Nr(t,e,r){t.issues.length&&e.issues.push(...Rt(r,t.issues)),e.value[r]=t.value}const Tr=/* @__PURE__ */ft("$ZodArray",(t,e)=>{Qe.init(t,e),t._zod.parse=(r,o)=>{const n=r.value;if(!Array.isArray(n))return r.issues.push({expected:"array",code:"invalid_type",input:n,inst:t}),r;r.value=Array(n.length);const a=[];for(let t=0;t<n.length;t++){const i=n[t],s=e.element._zod.run({value:i,issues:[]},o);s instanceof Promise?a.push(s.then(e=>Nr(e,r,t))):Nr(s,r,t)}return a.length?Promise.all(a).then(()=>r):r}});function Mr(t,e,r,o,n){if(t.issues.length){if(n&&!(r in o))return;e.issues.push(...Rt(r,t.issues))}void 0===t.value?r in o&&(e.value[r]=void 0):e.value[r]=t.value}function Ar(t){const e=Object.keys(t.shape);for(const n of e)if(!t.shape?.[n]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${n}": expected a Zod schema`);const r=(o=t.shape,Object.keys(o).filter(t=>"optional"===o[t]._zod.optin&&"optional"===o[t]._zod.optout));var o;return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(r)}}function jr(t,e,r,o,n,a){const i=[],s=n.keySet,c=n.catchall._zod,l=c.def.type,d="optional"===c.optout;for(const u in e){if(s.has(u))continue;if("never"===l){i.push(u);continue}const n=c.run({value:e[u],issues:[]},o);n instanceof Promise?t.push(n.then(t=>Mr(t,r,u,e,d))):Mr(n,r,u,e,d)}return i.length&&r.issues.push({code:"unrecognized_keys",keys:i,input:e,inst:a}),t.length?Promise.all(t).then(()=>r):r}const Pr=/* @__PURE__ */ft("$ZodObject",(t,e)=>{Qe.init(t,e);const r=Object.getOwnPropertyDescriptor(e,"shape");if(!r?.get){const t=e.shape;Object.defineProperty(e,"shape",{get:()=>{const r={...t};return Object.defineProperty(e,"shape",{value:r}),r}})}const o=_t(()=>Ar(e));Ot(t._zod,"propValues",()=>{const t=e.shape,r={};for(const e in t){const o=t[e]._zod;if(o.values){r[e]??(r[e]=/* @__PURE__ */new Set);for(const t of o.values)r[e].add(t)}}return r});const n=Tt,a=e.catchall;let i;t._zod.parse=(e,r)=>{i??(i=o.value);const s=e.value;if(!n(s))return e.issues.push({expected:"object",code:"invalid_type",input:s,inst:t}),e;e.value={};const c=[],l=i.shape;for(const t of i.keys){const o=l[t],n="optional"===o._zod.optout,a=o._zod.run({value:s[t],issues:[]},r);a instanceof Promise?c.push(a.then(r=>Mr(r,e,t,s,n))):Mr(a,e,t,s,n)}return a?jr(c,s,e,r,o.value,t):c.length?Promise.all(c).then(()=>e):e}}),Fr=/* @__PURE__ */ft("$ZodObjectJIT",(t,e)=>{Pr.init(t,e);const r=t._zod.parse,o=_t(()=>Ar(e));let n;const a=Tt,i=!vt.jitless,s=i&&Mt.value,c=e.catchall;let l;t._zod.parse=(d,u)=>{l??(l=o.value);const p=d.value;return a(p)?i&&s&&!1===u?.async&&!0!==u.jitless?(n||(n=(t=>{const e=new Ye(["shape","payload","ctx"]),r=o.value,n=t=>{const e=$t(t);return`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`};e.write("const input = payload.value;");const a=/* @__PURE__ */Object.create(null);let i=0;for(const o of r.keys)a[o]="key_"+i++;e.write("const newResult = {};");for(const o of r.keys){const r=a[o],i=$t(o),s=t[o],c="optional"===s?._zod?.optout;e.write(`const ${r} = ${n(o)};`),c?e.write(`\n if (${r}.issues.length) {\n if (${i} in input) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `):e.write(`\n if (${r}.issues.length) {\n payload.issues = payload.issues.concat(${r}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${i}, ...iss.path] : [${i}]\n })));\n }\n \n if (${r}.value === undefined) {\n if (${i} in input) {\n newResult[${i}] = undefined;\n }\n } else {\n newResult[${i}] = ${r}.value;\n }\n \n `)}e.write("payload.value = newResult;"),e.write("return payload;");const s=e.compile();return(e,r)=>s(t,e,r)})(e.shape)),d=n(d,u),c?jr([],p,d,u,l,t):d):r(d,u):(d.issues.push({expected:"object",code:"invalid_type",input:p,inst:t}),d)}});function Dr(t,e,r,o){for(const a of t)if(0===a.issues.length)return e.value=a.value,e;const n=t.filter(t=>!Lt(t));return 1===n.length?(e.value=n[0].value,n[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(t=>t.issues.map(t=>Bt(t,o,yt())))}),e)}const Zr=/* @__PURE__ */ft("$ZodUnion",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.options.some(t=>"optional"===t._zod.optin)?"optional":void 0),Ot(t._zod,"optout",()=>e.options.some(t=>"optional"===t._zod.optout)?"optional":void 0),Ot(t._zod,"values",()=>{if(e.options.every(t=>t._zod.values))return new Set(e.options.flatMap(t=>Array.from(t._zod.values)))}),Ot(t._zod,"pattern",()=>{if(e.options.every(t=>t._zod.pattern)){const t=e.options.map(t=>t._zod.pattern);return new RegExp(`^(${t.map(t=>Et(t.source)).join("|")})$`)}});const r=1===e.options.length,o=e.options[0]._zod.run;t._zod.parse=(n,a)=>{if(r)return o(n,a);let i=!1;const s=[];for(const t of e.options){const e=t._zod.run({value:n.value,issues:[]},a);if(e instanceof Promise)s.push(e),i=!0;else{if(0===e.issues.length)return e;s.push(e)}}return i?Promise.all(s).then(e=>Dr(e,n,t,a)):Dr(s,n,t,a)}}),Ur=/* @__PURE__ */ft("$ZodIntersection",(t,e)=>{Qe.init(t,e),t._zod.parse=(t,r)=>{const o=t.value,n=e.left._zod.run({value:o,issues:[]},r),a=e.right._zod.run({value:o,issues:[]},r);return n instanceof Promise||a instanceof Promise?Promise.all([n,a]).then(([e,r])=>Rr(t,e,r)):Rr(t,n,a)}});function Lr(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t===+e)return{valid:!0,data:t};if(At(t)&&At(e)){const r=Object.keys(e),o=Object.keys(t).filter(t=>-1!==r.indexOf(t)),n={...t,...e};for(const a of o){const r=Lr(t[a],e[a]);if(!r.valid)return{valid:!1,mergeErrorPath:[a,...r.mergeErrorPath]};n[a]=r.data}return{valid:!0,data:n}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let o=0;o<t.length;o++){const n=Lr(t[o],e[o]);if(!n.valid)return{valid:!1,mergeErrorPath:[o,...n.mergeErrorPath]};r.push(n.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Rr(t,e,r){const o=/* @__PURE__ */new Map;let n;for(const s of e.issues)if("unrecognized_keys"===s.code){n??(n=s);for(const t of s.keys)o.has(t)||o.set(t,{}),o.get(t).l=!0}else t.issues.push(s);for(const s of r.issues)if("unrecognized_keys"===s.code)for(const t of s.keys)o.has(t)||o.set(t,{}),o.get(t).r=!0;else t.issues.push(s);const a=[...o].filter(([,t])=>t.l&&t.r).map(([t])=>t);if(a.length&&n&&t.issues.push({...n,keys:a}),Lt(t))return t;const i=Lr(e.value,r.value);if(!i.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(i.mergeErrorPath)}`);return t.value=i.data,t}const Wr=/* @__PURE__ */ft("$ZodEnum",(t,e)=>{Qe.init(t,e);const r=xt(e.entries),o=new Set(r);t._zod.values=o,t._zod.pattern=new RegExp(`^(${r.filter(t=>Pt.has(typeof t)).map(t=>"string"==typeof t?Ft(t):t.toString()).join("|")})$`),t._zod.parse=(e,n)=>{const a=e.value;return o.has(a)||e.issues.push({code:"invalid_value",values:r,input:a,inst:t}),e}}),Br=/* @__PURE__ */ft("$ZodTransform",(t,e)=>{Qe.init(t,e),t._zod.parse=(r,o)=>{if("backward"===o.direction)throw new bt(t.constructor.name);const n=e.transform(r.value,r);if(o.async)return(n instanceof Promise?n:Promise.resolve(n)).then(t=>(r.value=t,r));if(n instanceof Promise)throw new wt;return r.value=n,r}});function Jr(t,e){return t.issues.length&&void 0===e?{issues:[],value:void 0}:t}const Vr=/* @__PURE__ */ft("$ZodOptional",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ot(t._zod,"values",()=>e.innerType._zod.values?/* @__PURE__ */new Set([...e.innerType._zod.values,void 0]):void 0),Ot(t._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${Et(t.source)})?$`):void 0}),t._zod.parse=(t,r)=>{if("optional"===e.innerType._zod.optin){const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(e=>Jr(e,t.value)):Jr(o,t.value)}return void 0===t.value?t:e.innerType._zod.run(t,r)}}),qr=/* @__PURE__ */ft("$ZodExactOptional",(t,e)=>{Vr.init(t,e),Ot(t._zod,"values",()=>e.innerType._zod.values),Ot(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(t,r)=>e.innerType._zod.run(t,r)}),Gr=/* @__PURE__ */ft("$ZodNullable",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.innerType._zod.optin),Ot(t._zod,"optout",()=>e.innerType._zod.optout),Ot(t._zod,"pattern",()=>{const t=e.innerType._zod.pattern;return t?new RegExp(`^(${Et(t.source)}|null)$`):void 0}),Ot(t._zod,"values",()=>e.innerType._zod.values?/* @__PURE__ */new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(t,r)=>null===t.value?t:e.innerType._zod.run(t,r)}),Kr=/* @__PURE__ */ft("$ZodDefault",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);if(void 0===t.value)return t.value=e.defaultValue,t;const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(t=>Hr(t,e)):Hr(o,e)}});function Hr(t,e){return void 0===t.value&&(t.value=e.defaultValue),t}const Yr=/* @__PURE__ */ft("$ZodPrefault",(t,e)=>{Qe.init(t,e),t._zod.optin="optional",Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>("backward"===r.direction||void 0===t.value&&(t.value=e.defaultValue),e.innerType._zod.run(t,r))}),Xr=/* @__PURE__ */ft("$ZodNonOptional",(t,e)=>{Qe.init(t,e),Ot(t._zod,"values",()=>{const t=e.innerType._zod.values;return t?new Set([...t].filter(t=>void 0!==t)):void 0}),t._zod.parse=(r,o)=>{const n=e.innerType._zod.run(r,o);return n instanceof Promise?n.then(e=>Qr(e,t)):Qr(n,t)}});function Qr(t,e){return t.issues.length||void 0!==t.value||t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const to=/* @__PURE__ */ft("$ZodCatch",(t,e)=>{Qe.init(t,e),Ot(t._zod,"optin",()=>e.innerType._zod.optin),Ot(t._zod,"optout",()=>e.innerType._zod.optout),Ot(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(o=>(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(t=>Bt(t,r,yt()))},input:t.value}),t.issues=[]),t)):(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(t=>Bt(t,r,yt()))},input:t.value}),t.issues=[]),t)}}),eo=/* @__PURE__ */ft("$ZodPipe",(t,e)=>{Qe.init(t,e),Ot(t._zod,"values",()=>e.in._zod.values),Ot(t._zod,"optin",()=>e.in._zod.optin),Ot(t._zod,"optout",()=>e.out._zod.optout),Ot(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(t,r)=>{if("backward"===r.direction){const o=e.out._zod.run(t,r);return o instanceof Promise?o.then(t=>ro(t,e.in,r)):ro(o,e.in,r)}const o=e.in._zod.run(t,r);return o instanceof Promise?o.then(t=>ro(t,e.out,r)):ro(o,e.out,r)}});function ro(t,e,r){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues},r)}const oo=/* @__PURE__ */ft("$ZodReadonly",(t,e)=>{Qe.init(t,e),Ot(t._zod,"propValues",()=>e.innerType._zod.propValues),Ot(t._zod,"values",()=>e.innerType._zod.values),Ot(t._zod,"optin",()=>e.innerType?._zod?.optin),Ot(t._zod,"optout",()=>e.innerType?._zod?.optout),t._zod.parse=(t,r)=>{if("backward"===r.direction)return e.innerType._zod.run(t,r);const o=e.innerType._zod.run(t,r);return o instanceof Promise?o.then(no):no(o)}});function no(t){return t.value=Object.freeze(t.value),t}const ao=/* @__PURE__ */ft("$ZodCustom",(t,e)=>{Ae.init(t,e),Qe.init(t,e),t._zod.parse=(t,e)=>t,t._zod.check=r=>{const o=r.value,n=e.fn(o);if(n instanceof Promise)return n.then(e=>io(e,r,o,t));io(n,r,o,t)}});function io(t,e,r,o){if(!t){const t={code:"custom",input:r,inst:o,path:[...o._zod.def.path??[]],continue:!o._zod.def.abort};o._zod.def.params&&(t.params=o._zod.def.params),e.issues.push(Vt(t))}}var so;(so=globalThis).__zod_globalRegistry??(so.__zod_globalRegistry=new class{constructor(){this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map}add(t,...e){const r=e[0];return this._map.set(t,r),r&&"object"==typeof r&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=/* @__PURE__ */new WeakMap,this._idmap=/* @__PURE__ */new Map,this}remove(t){const e=this._map.get(t);return e&&"object"==typeof e&&"id"in e&&this._idmap.delete(e.id),this._map.delete(t),this}get(t){const e=t._zod.parent;if(e){const r={...this.get(e)??{}};delete r.id;const o={...r,...this._map.get(t)};return Object.keys(o).length?o:void 0}return this._map.get(t)}has(t){return this._map.has(t)}});const co=globalThis.__zod_globalRegistry;function lo(t,e){return new t({type:"string",...Zt(e)})}function uo(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...Zt(e)})}function po(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...Zt(e)})}function ho(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...Zt(e)})}function go(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Zt(e)})}function mo(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Zt(e)})}function fo(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Zt(e)})}function wo(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...Zt(e)})}function bo(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...Zt(e)})}function vo(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...Zt(e)})}function yo(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...Zt(e)})}function xo(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...Zt(e)})}function ko(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...Zt(e)})}function _o(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...Zt(e)})}function zo(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...Zt(e)})}function Eo(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...Zt(e)})}function So(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...Zt(e)})}function Oo(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Zt(e)})}function Io(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Zt(e)})}function Co(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...Zt(e)})}function $o(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...Zt(e)})}function No(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...Zt(e)})}function To(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...Zt(e)})}function Mo(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Zt(e)})}function Ao(t,e){return new t({type:"string",format:"date",check:"string_format",...Zt(e)})}function jo(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...Zt(e)})}function Po(t,e){return new t({type:"string",format:"duration",check:"string_format",...Zt(e)})}function Fo(t,e){return new t({type:"number",checks:[],...Zt(e)})}function Do(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...Zt(e)})}function Zo(t){return new t({type:"any"})}function Uo(t){return new t({type:"unknown"})}function Lo(t,e){return new t({type:"never",...Zt(e)})}function Ro(t,e){return new Pe({check:"less_than",...Zt(e),value:t,inclusive:!1})}function Wo(t,e){return new Pe({check:"less_than",...Zt(e),value:t,inclusive:!0})}function Bo(t,e){return new Fe({check:"greater_than",...Zt(e),value:t,inclusive:!1})}function Jo(t,e){return new Fe({check:"greater_than",...Zt(e),value:t,inclusive:!0})}function Vo(t,e){return new De({check:"multiple_of",...Zt(e),value:t})}function qo(t,e){return new Ue({check:"max_length",...Zt(e),maximum:t})}function Go(t,e){return new Le({check:"min_length",...Zt(e),minimum:t})}function Ko(t,e){return new Re({check:"length_equals",...Zt(e),length:t})}function Ho(t,e){return new Be({check:"string_format",format:"regex",...Zt(e),pattern:t})}function Yo(t){return new Je({check:"string_format",format:"lowercase",...Zt(t)})}function Xo(t){return new Ve({check:"string_format",format:"uppercase",...Zt(t)})}function Qo(t,e){return new qe({check:"string_format",format:"includes",...Zt(e),includes:t})}function tn(t,e){return new Ge({check:"string_format",format:"starts_with",...Zt(e),prefix:t})}function en(t,e){return new Ke({check:"string_format",format:"ends_with",...Zt(e),suffix:t})}function rn(t){return new He({check:"overwrite",tx:t})}function on(t){/* @__PURE__ */
|
|
16
16
|
return rn(e=>e.normalize(t))}function nn(){/* @__PURE__ */
|
|
17
17
|
return rn(t=>t.trim())}function an(){/* @__PURE__ */
|
|
18
18
|
return rn(t=>t.toLowerCase())}function sn(){/* @__PURE__ */
|
|
@@ -28,7 +28,7 @@ return Fo(ca,t)}const da=/* @__PURE__ */ft("ZodNumberFormat",(t,e)=>{Or.init(t,e
|
|
|
28
28
|
return Do(da,t)}const pa=/* @__PURE__ */ft("ZodAny",(t,e)=>{Ir.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(t,e,r)=>{}}),ha=/* @__PURE__ */ft("ZodUnknown",(t,e)=>{Cr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(t,e,r)=>{}});function ga(){/* @__PURE__ */
|
|
29
29
|
return Uo(ha)}const ma=/* @__PURE__ */ft("ZodNever",(t,e)=>{$r.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e,r)=>{r.not={}})(0,0,e)}),fa=/* @__PURE__ */ft("ZodArray",(t,e)=>{Tr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=r,a=t._zod.def,{minimum:i,maximum:s}=t._zod.bag;"number"==typeof i&&(n.minItems=i),"number"==typeof s&&(n.maxItems=s),n.type="array",n.items=gn(a.element,e,{...o,path:[...o.path,"items"]})})(t,e,r,o),t.element=e.element,t.min=(e,r)=>t.check(/* @__PURE__ */Go(e,r)),t.nonempty=e=>t.check(/* @__PURE__ */Go(1,e)),t.max=(e,r)=>t.check(/* @__PURE__ */qo(e,r)),t.length=(e,r)=>t.check(/* @__PURE__ */Ko(e,r)),t.unwrap=()=>t.element}),wa=/* @__PURE__ */ft("ZodObject",(t,e)=>{Fr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=r,a=t._zod.def;n.type="object",n.properties={};const i=a.shape;for(const l in i)n.properties[l]=gn(i[l],e,{...o,path:[...o.path,"properties",l]});const s=new Set(Object.keys(i)),c=new Set([...s].filter(t=>{const r=a.shape[t]._zod;return"input"===e.io?void 0===r.optin:void 0===r.optout}));c.size>0&&(n.required=Array.from(c)),"never"===a.catchall?._zod.def.type?n.additionalProperties=!1:a.catchall?a.catchall&&(n.additionalProperties=gn(a.catchall,e,{...o,path:[...o.path,"additionalProperties"]})):"output"===e.io&&(n.additionalProperties=!1)})(t,e,r,o),Ot(t,"shape",()=>e.shape),t.keyof=()=>xa(Object.keys(t._zod.def.shape)),t.catchall=e=>t.clone({...t._zod.def,catchall:e}),t.passthrough=()=>t.clone({...t._zod.def,catchall:ga()}),t.loose=()=>t.clone({...t._zod.def,catchall:ga()}),t.strict=()=>t.clone({...t._zod.def,catchall:/* @__PURE__ */Lo(ma,void 0)}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=e=>function(t,e){if(!At(e))throw new Error("Invalid input to extend: expected a plain object");const r=t._zod.def.checks;if(r&&r.length>0){const r=t._zod.def.shape;for(const t in e)if(void 0!==Object.getOwnPropertyDescriptor(r,t))throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const o=Ct(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return It(this,"shape",r),r}});return Dt(t,o)}(t,e),t.safeExtend=e=>function(t,e){if(!At(e))throw new Error("Invalid input to safeExtend: expected a plain object");const r=Ct(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return It(this,"shape",r),r}});return Dt(t,r)}(t,e),t.merge=e=>function(t,e){const r=Ct(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e._zod.def.shape};return It(this,"shape",r),r},get catchall(){return e._zod.def.catchall},checks:[]});return Dt(t,r)}(t,e),t.pick=e=>function(t,e){const r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");return Dt(t,Ct(t._zod.def,{get shape(){const t={};for(const o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(t[o]=r.shape[o])}return It(this,"shape",t),t},checks:[]}))}(t,e),t.omit=e=>function(t,e){const r=t._zod.def,o=r.checks;if(o&&o.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const n=Ct(t._zod.def,{get shape(){const o={...t._zod.def.shape};for(const t in e){if(!(t in r.shape))throw new Error(`Unrecognized key: "${t}"`);e[t]&&delete o[t]}return It(this,"shape",o),o},checks:[]});return Dt(t,n)}(t,e),t.partial=(...e)=>function(t,e,r){const o=e._zod.def.checks;if(o&&o.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const n=Ct(e._zod.def,{get shape(){const o=e._zod.def.shape,n={...o};if(r)for(const e in r){if(!(e in o))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=t?new t({type:"optional",innerType:o[e]}):o[e])}else for(const e in o)n[e]=t?new t({type:"optional",innerType:o[e]}):o[e];return It(this,"shape",n),n},checks:[]});return Dt(e,n)}(_a,t,e[0]),t.required=(...e)=>function(t,e,r){const o=Ct(e._zod.def,{get shape(){const o=e._zod.def.shape,n={...o};if(r)for(const e in r){if(!(e in n))throw new Error(`Unrecognized key: "${e}"`);r[e]&&(n[e]=new t({type:"nonoptional",innerType:o[e]}))}else for(const e in o)n[e]=new t({type:"nonoptional",innerType:o[e]});return It(this,"shape",n),n}});return Dt(e,o)}($a,t,e[0])}),ba=/* @__PURE__ */ft("ZodUnion",(t,e)=>{Zr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def,a=!1===n.inclusive,i=n.options.map((t,r)=>gn(t,e,{...o,path:[...o.path,a?"oneOf":"anyOf",r]}));a?r.oneOf=i:r.anyOf=i})(t,e,r,o),t.options=e.options}),va=/* @__PURE__ */ft("ZodIntersection",(t,e)=>{Ur.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def,a=gn(n.left,e,{...o,path:[...o.path,"allOf",0]}),i=gn(n.right,e,{...o,path:[...o.path,"allOf",1]}),s=t=>"allOf"in t&&1===Object.keys(t).length,c=[...s(a)?a.allOf:[a],...s(i)?i.allOf:[i]];r.allOf=c})(t,e,r,o)}),ya=/* @__PURE__ */ft("ZodEnum",(t,e)=>{Wr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r)=>{const o=xt(t._zod.def.entries);o.every(t=>"number"==typeof t)&&(r.type="number"),o.every(t=>"string"==typeof t)&&(r.type="string"),r.enum=o})(t,0,r),t.enum=e.entries,t.options=Object.values(e.entries);const r=new Set(Object.keys(e.entries));t.extract=(t,o)=>{const n={};for(const a of t){if(!r.has(a))throw new Error(`Key ${a} not found in enum`);n[a]=e.entries[a]}return new ya({...e,checks:[],...Zt(o),entries:n})},t.exclude=(t,o)=>{const n={...e.entries};for(const e of t){if(!r.has(e))throw new Error(`Key ${e} not found in enum`);delete n[e]}return new ya({...e,checks:[],...Zt(o),entries:n})}});function xa(t,e){const r=Array.isArray(t)?Object.fromEntries(t.map(t=>[t,t])):t;return new ya({type:"enum",entries:r,...Zt(e)})}const ka=/* @__PURE__ */ft("ZodTransform",(t,e)=>{Br.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e)=>{if("throw"===e.unrepresentable)throw new Error("Transforms cannot be represented in JSON Schema")})(0,t),t._zod.parse=(r,o)=>{if("backward"===o.direction)throw new bt(t.constructor.name);r.addIssue=o=>{if("string"==typeof o)r.issues.push(Vt(o,r.value,e));else{const e=o;e.fatal&&(e.continue=!1),e.code??(e.code="custom"),e.input??(e.input=r.value),e.inst??(e.inst=t),r.issues.push(Vt(e))}};const n=e.transform(r.value,r);return n instanceof Promise?n.then(t=>(r.value=t,r)):(r.value=n,r)}}),_a=/* @__PURE__ */ft("ZodOptional",(t,e)=>{Vr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>yn(t,e,0,o),t.unwrap=()=>t._zod.def.innerType});function za(t){return new _a({type:"optional",innerType:t})}const Ea=/* @__PURE__ */ft("ZodExactOptional",(t,e)=>{qr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>yn(t,e,0,o),t.unwrap=()=>t._zod.def.innerType}),Sa=/* @__PURE__ */ft("ZodNullable",(t,e)=>{Gr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def,a=gn(n.innerType,e,o),i=e.seen.get(t);"openapi-3.0"===e.target?(i.ref=n.innerType,r.nullable=!0):r.anyOf=[a,{type:"null"}]})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType});function Oa(t){return new Sa({type:"nullable",innerType:t})}const Ia=/* @__PURE__ */ft("ZodDefault",(t,e)=>{Kr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def;gn(n.innerType,e,o),e.seen.get(t).ref=n.innerType,r.default=JSON.parse(JSON.stringify(n.defaultValue))})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap}),Ca=/* @__PURE__ */ft("ZodPrefault",(t,e)=>{Yr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def;gn(n.innerType,e,o),e.seen.get(t).ref=n.innerType,"input"===e.io&&(r._prefault=JSON.parse(JSON.stringify(n.defaultValue)))})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType}),$a=/* @__PURE__ */ft("ZodNonOptional",(t,e)=>{Xr.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def;gn(n.innerType,e,o),e.seen.get(t).ref=n.innerType})(t,e,0,o),t.unwrap=()=>t._zod.def.innerType}),Na=/* @__PURE__ */ft("ZodCatch",(t,e)=>{to.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def;let a;gn(n.innerType,e,o),e.seen.get(t).ref=n.innerType;try{a=n.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}r.default=a})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap}),Ta=/* @__PURE__ */ft("ZodPipe",(t,e)=>{eo.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def,a="input"===e.io?"transform"===n.in._zod.def.type?n.out:n.in:n.out;gn(a,e,o),e.seen.get(t).ref=a})(t,e,0,o),t.in=e.in,t.out=e.out});function Ma(t,e){return new Ta({type:"pipe",in:t,out:e})}const Aa=/* @__PURE__ */ft("ZodReadonly",(t,e)=>{oo.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(e,r,o)=>((t,e,r,o)=>{const n=t._zod.def;gn(n.innerType,e,o),e.seen.get(t).ref=n.innerType,r.readOnly=!0})(t,e,r,o),t.unwrap=()=>t._zod.def.innerType}),ja=/* @__PURE__ */ft("ZodCustom",(t,e)=>{ao.init(t,e),Dn.init(t,e),t._zod.processJSONSchema=(t,e,r)=>((t,e)=>{if("throw"===e.unrepresentable)throw new Error("Custom types cannot be represented in JSON Schema")})(0,t)}),Pa="chat_device_id";function Fa(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)})}const Da=function(){const t={type:"object",shape:{id:Ln().optional(),type:xa(["text","image","audio","location","system"]).default("text"),content:Ln().optional(),imageUrl:Ln().url().optional(),audioUrl:Ln().url().optional(),latitude:la().optional(),longitude:la().optional(),timestamp:Ln().optional(),sender:xa(["bot","user","system"]).optional(),emotion:/* @__PURE__ */Zo(pa).optional()}??{},...Zt(void 0)};return new wa(t)}();class Za{queue=[];endpoint;apiKey;flushInterval=null;isFlushing=!1;isDisabled=!1;MAX_QUEUE_SIZE=100;FLUSH_INTERVAL_MS=3e4;BATCH_SIZE=10;constructor(t,e){this.endpoint=t,this.apiKey=e,this.startAutoFlush()}startAutoFlush(){this.flushInterval=setInterval(()=>{!this.isDisabled&&this.queue.length>0&&this.flush()},this.FLUSH_INTERVAL_MS)}trackOpen(){this.track("chat_opened")}trackClose(){this.track("chat_closed")}trackMessageSent(t){this.track("message_sent",{type:t})}trackMessageReceived(t,e){this.track("message_received",{type:t,latency:e})}trackError(t,e){this.track("error",{error:t,context:e})}trackConnectionStatus(t){this.track("connection_status",{isConnected:t})}trackFeatureUsed(t){this.track("feature_used",{feature:t})}trackTypingStarted(){this.track("typing_started")}trackAttachmentSent(t,e){this.track("attachment_sent",{type:t,size:e})}track(t,e){this.isDisabled||(this.queue.push({event:t,properties:{...e,userAgent:"undefined"!=typeof navigator?navigator.userAgent:void 0,url:"undefined"!=typeof window?window.location.href:void 0},timestamp:Date.now()}),this.queue.length>=this.BATCH_SIZE&&this.flush(),this.queue.length>this.MAX_QUEUE_SIZE&&(this.queue=this.queue.slice(-this.MAX_QUEUE_SIZE),x.warn("Analytics queue overflow, dropping old events")))}async flush(){if(this.isDisabled||0===this.queue.length||this.isFlushing)return;this.isFlushing=!0;const t=[...this.queue];this.queue=[];try{const e=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({events:t}),keepalive:!0});e.ok?x.debug(`Analytics: Flushed ${t.length} events`):(this.isDisabled=!0,this.queue=[],x.debug(`Analytics disabled: endpoint returned ${e.status}`))}catch(e){this.isDisabled=!0,this.queue=[],x.debug("Analytics disabled due to network error")}finally{this.isFlushing=!1}}destroy(){this.flushInterval&&clearInterval(this.flushInterval),this.flush()}}let Ua=null,La=null;function Ra(t){Ua=t}function Wa(t){La=t}const Ba=l(null);function Ja({children:t,defaultLocale:e,initialState:r,onStateChange:n,...a}){const[i,c]=o(r?.isOpen??!1),[l,d]=o(0),u=s(()=>{c(!0),d(0),n?.(!0)},[n]),p=s(()=>{c(!1),n?.(!1)},[n]),h=s(()=>{c(t=>{const e=!t;return e&&d(0),n?.(e),e})},[n]),g=s(t=>{Ua?(Ua(t),x.debug("ChatWidgetProvider sendMessage:",t)):x.warn("sendMessage called but no handler registered")},[]),m=s(()=>{La?(La(),x.debug("ChatWidgetProvider clearMessages called")):x.warn("clearMessages called but no handler registered")},[]),f={isOpen:i,open:u,close:p,toggle:h,sendMessage:g,clearMessages:m,unreadCount:l},w=s((t,e)=>{"message:received"!==t||i||d(t=>t+1),a.onEvent?.(t,e)},[i,a]);/* @__PURE__ */
|
|
30
30
|
return $(E,{defaultLocale:e,children:/* @__PURE__ */N(Ba.Provider,{value:f,children:[t,
|
|
31
|
-
/* @__PURE__ */$(Ha,{...a,onStateChange:t=>{c(t),t&&d(0),n?.(t)},onEvent:w})]})})}function Va(){const t=d(Ba);if(!t)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return t}const qa=t=>new Promise((e,r)=>{const o=new FileReader;o.readAsDataURL(t),o.onload=()=>e(o.result),o.onerror=t=>r(t)});function Ga(t){const{apiKey:a,apiBaseUrl:l,agentId:d,pageContext:u,includeSEOMetadata:p=!1,theme:g,userContext:m,onLogin:f,onNavigate:b,onEvent:v,onStateChange:y,onThemeUpdate:k}=t,[E,S]=o(0),O=r(0),{t:I}=h(),C=function(t,e,o=!0){const a=r(null);return n(()=>{if(!o||!t||!e)return;const r=`${t}/analytics`;a.current=new Za(r,e);const n=()=>a.current?.flush(),i=()=>{"hidden"===document.visibilityState&&a.current?.flush()};return window.addEventListener("beforeunload",n),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",n),window.removeEventListener("visibilitychange",i),a.current?.destroy()}},[t,e,o]),{trackOpen:s(()=>{a.current?.trackOpen()},[]),trackClose:s(()=>{a.current?.trackClose()},[]),trackMessageSent:s(t=>{a.current?.trackMessageSent(t)},[]),trackMessageReceived:s((t,e)=>{a.current?.trackMessageReceived(t,e)},[]),trackError:s((t,e)=>{a.current?.trackError(t,e)},[]),trackConnectionStatus:s(t=>{a.current?.trackConnectionStatus(t)},[]),trackFeatureUsed:s(t=>{a.current?.trackFeatureUsed(t)},[])}}(l,a,!0),$=function({enabled:t=!0,soundEnabled:e=!0,desktopEnabled:a=!0,botName:i="BotUyo",logoUrl:c,notificationSoundUrl:l}={}){const[d,u]=o("default"),p=r(null),h=c||w,g=l||z;n(()=>{e&&"undefined"!=typeof window&&(p.current=new Audio(g),p.current.volume=.3)},[e,g]),n(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return x.warn("Notifications API not available"),!1;try{const t=await Notification.requestPermission();return u(t),x.info("Notification permission:",t),"granted"===t}catch(t){return x.error("Error requesting notification permission:",t),!1}},[]),f=s(e=>{if(t&&a&&"granted"===d&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${i}`;let r="Mensaje recibido";"text"===e.type&&"content"in e?r=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?r="📷 Imagen":"audio"===e.type?r="🎵 Audio":"location"===e.type&&(r="📍 Ubicación");const o=new Notification(t,{body:r,icon:h,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(r){x.error("Error showing notification:",r)}},[t,a,d,i,h]),b=s(()=>{if(t&&e&&("undefined"==typeof document||!document.hasFocus()))try{p.current?.play().catch(t=>{x.debug("Audio playback blocked:",t)})}catch(r){x.error("Error playing sound:",r)}},[t,e]),v=s(t=>{f(t),b()},[f,b]);return{permission:d,requestPermission:m,notify:f,playSound:b,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:g?.botName||"BotUyo",logoUrl:g?.logoUrl}),N=function(t=10,e=6e4){const o=r([]);return{isAllowed:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),!(o.current.length>=t||(o.current.push(r),0))},[t,e]),getRemainingAttempts:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),Math.max(0,t-o.current.length)},[t,e]),getTimeUntilReset:s(()=>{if(0===o.current.length)return 0;const t=Date.now(),r=o.current[0],n=e-(t-r);return Math.max(0,n)},[e]),reset:s(()=>{o.current=[]},[])}}(10,6e4),{state:M,actions:A}=function(t="default"){const[r,a]=c(mt,gt),[i,l]=o(!1),d=e.useMemo(()=>function(t="default"){return`botuyo_chat_v1_${t}`}(t),[t]),u=e.useMemo(()=>((t="default")=>(ht.has(t)||ht.set(t,new pt(t)),ht.get(t)))(t),[t]);n(()=>{"undefined"==typeof window||i||(async()=>{try{await u.migrateFromLocalStorage(t);const e=await u.getMessages(100),r=await u.getMetadata();if(e.length>0||r){const t={messages:e.map(t=>({...t,timestamp:new Date(t.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};a({type:"RESTORE_SESSION",payload:t})}}catch(e){x.warn("Chat: Error rehydrating from IndexedDB",e);try{const t=localStorage.getItem(d);if(t){const e=JSON.parse(t);e.messages&&(e.messages=e.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}))),a({type:"RESTORE_SESSION",payload:e})}}catch(r){x.error("Chat: Fallback rehydration failed",r)}}finally{l(!0)}})()},[i]),n(()=>{if(!i)return;const t=setTimeout(async()=>{try{await u.saveMessages(r.messages),await u.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(t){x.error("Chat Persistence Error:",t);try{const t={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(d,JSON.stringify(t))}catch(e){x.error("Chat: Fallback persistence failed",e)}}},500);return()=>clearTimeout(t)},[r.isOpen,r.messages,r.sessionId,i]);const p=s(t=>{a({type:"ADD_MESSAGE",payload:t})},[]),h=s(()=>a({type:"TOGGLE_WINDOW"}),[]),g=s(()=>a({type:"OPEN_WINDOW"}),[]),m=s(()=>a({type:"CLOSE_WINDOW"}),[]),f=s(t=>a({type:"SET_CONNECTED",payload:t}),[]),w=s(t=>a({type:"SET_TYPING",payload:t}),[]),b=s(t=>a({type:"SET_MESSAGES",payload:t}),[]),v=s(t=>a({type:"SET_ERROR",payload:t}),[]),y=s(t=>a({type:"SET_SESSION_ID",payload:t}),[]),k=s(()=>{localStorage.removeItem(d),a({type:"CLEAR_CHAT"})},[]),_=s(()=>{a({type:"SET_MESSAGES",payload:[]})},[]);return{state:r,isHydrated:i,actions:{toggleWindow:h,openWindow:g,closeWindow:m,setConnected:f,setTyping:w,addMessage:p,setMessages:b,setError:v,setSessionId:y,clearChat:k,clearMessages:_}}}(d),j=function(t=!1){const e="undefined"!=typeof window?window.location.pathname:"",r=i(()=>e,[e]),[a,s]=o({});return n(()=>{if(!t)return void s({});const e=setTimeout(()=>{const t=function(){if("undefined"==typeof window)return{};const t={};t.title=document.title,document.querySelectorAll("meta").forEach(e=>{const r=e.getAttribute("name"),o=e.getAttribute("property"),n=e.getAttribute("content");if(n){if(r)switch(r){case"description":t.description=n;break;case"keywords":t.keywords=n.split(",").map(t=>t.trim());break;case"author":t.author=n}if(o){if(o.startsWith("og:")){const e=o.replace("og:","og_");t[e]=n}if(o.startsWith("twitter:")){const e=o.replace("twitter:","twitter_");t[e]=n}}}});try{const e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length>0){const r=[];e.forEach(t=>{try{const e=JSON.parse(t.textContent||"");r.push(e)}catch{}}),r.length>0&&(t.structuredData=r)}}catch{}return t}();s(t)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(a).length>0?a:void 0}(p),P=function(t){const{apiKey:e,apiBaseUrl:a,agentId:c,pageContext:l,userContext:d}=t,u=r(t);n(()=>{u.current=t},[t]);const p=r(null),[h,g]=o(!1),[m,f]=o(!1),w=r(function(){try{const t=localStorage.getItem(Pa);if(t)return t;const e=Fa();return localStorage.setItem(Pa,e),e}catch{return x.warn("localStorage not available, using session-only device ID"),Fa()}}()),b=r(l);n(()=>{b.current=l},[l]);const v=s(t=>{const e=Da.safeParse(t),r=e.success&&e.data.id?e.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=e.success&&e.data.sender?e.data.sender:"bot",n=e.success&&e.data.timestamp?new Date(e.data.timestamp):/* @__PURE__ */new Date,a=e.success?e.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:n,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":return{id:r,type:"audio",sender:o,timestamp:n,content:a.audioUrl||a.content||""};case"location":return{id:r,type:"location",sender:o,timestamp:n,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:n,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:n,content:String(a.content||"Sin contenido"),emotion:a.emotion}}},[]),y=s(()=>{if(!e||!a)return;if(p.current?.connected)return;g(!0);const t=T(`${a}/webchat`,{auth:{apiKey:e,deviceId:w.current,agentId:c,token:d?.token,metadata:d?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});t.on("connect",()=>{g(!1),f(!0),u.current.onConnected(`temp-${Date.now()}`,void 0)}),t.on("disconnect",t=>{g(!1),f(!1),u.current.onDisconnected()}),t.on("connect_error",t=>{g(!1),u.current.onError(`Error de conexión: ${t.message}`)}),t.on("connection_ack",t=>{u.current.onConnected(t.sessionId,t.config)}),t.on("bot_message",t=>{try{u.current.onMessage(v(t))}catch(e){x.error("ChatSocket Error processing bot_message:",e)}}),t.on("chat_history",t=>{t.messages&&Array.isArray(t.messages)&&t.messages.forEach(t=>{try{u.current.onMessage(v(t))}catch(e){x.debug("Error processing history message:",e)}}),u.current.onEvent&&u.current.onEvent("history_loaded",t)}),t.on("bot_typing",t=>u.current.onTyping(t)),t.on("auth_success",t=>{u.current.onLogin&&u.current.onLogin(t),t.theme&&u.current.onThemeUpdate&&u.current.onThemeUpdate(t.theme)}),p.current=t},[e,a]),k=s(()=>{p.current&&(p.current.disconnect(),p.current=null,f(!1))},[]),z=r(y);z.current=y,n(()=>(z.current(),()=>{p.current&&(p.current.disconnect(),p.current=null)}),[]);const E=r([]),S=r([]),O=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),I=s(()=>{if(p.current?.connected)for(;E.current.length>0;){const t=E.current.shift();p.current.emit("user_message",t)}},[]);n(()=>{m&&I()},[m,I]),n(()=>{if(!m)return;const t=setInterval(()=>{const t=Date.now();S.current=S.current.filter(e=>t<e.nextRetryAt||(e.attempts>=e.maxAttempts?(u.current.onEvent?.("message_failed",{id:e.id,payload:e.payload}),x.error("Message failed after max retries:",e.id),!1):!p.current?.connected||(p.current.emit("user_message",e.payload,t=>{t?.success&&u.current.onEvent?.("message_sent",{id:e.id})}),e.attempts++,e.nextRetryAt=t+1e3*Math.pow(2,e.attempts),e.attempts<e.maxAttempts)))},500);return()=>clearInterval(t)},[m]);const C=s((t,e="text")=>{const r=O(),o={...b.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:w.current},n={id:r,content:t.trim(),type:e,metadata:o};return p.current?.connected?(p.current.emit("user_message",n,t=>{!1!==t?.success&&t?u.current.onEvent?.("message_sent",{id:r}):(S.current.push({id:r,payload:n,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),u.current.onEvent?.("message_retry_queued",{id:r}))}),r):(E.current.push(n),u.current.onEvent?.("queued_message",{id:r,payload:n}),r)},[O]),$=i(()=>_(t=>{p.current?.emit("typing",t)},250),[]);return{isConnected:m,isConnecting:h,sendMessage:C,sendTyping:$,getSocket:s(()=>p.current,[]),requestHistory:s(()=>{p.current?.emit("request_history")},[]),reconnect:y,disconnect:k}}({apiKey:a,apiBaseUrl:l,agentId:d,pageContext:i(()=>j?{...u||{},seo:{...j||{}}}:u,[u,j]),userContext:m,onMessage:s(t=>{const e=Date.now(),r=O.current>0?e-O.current:void 0;O.current=e,A.addMessage(t),C.trackMessageReceived(t.type,r),M.isOpen||"bot"!==t.sender||(S(t=>t+1),$.notifyWithSound(t))},[A,M.isOpen,C,$]),onConnected:s((t,e)=>{A.setConnected(!0),A.setSessionId(t),C.trackConnectionStatus(!0),e&&k&&k(e),e&&v&&v("backend_config",e)},[A,v,k,C]),onDisconnected:s(()=>{A.setConnected(!1),C.trackConnectionStatus(!1)},[A,C]),onTyping:s(t=>A.setTyping(t),[A]),onError:s(t=>{A.setError(t),C.trackError(t)},[A,C]),onLogin:f,onNavigate:b,onEvent:v,onThemeUpdate:k}),F=s(()=>{x.debug("ChatWidget handleToggle called, current isOpen:",M.isOpen),M.isOpen?(A.closeWindow(),C.trackClose(),y?.(!1),x.debug("ChatWidget Closing window")):(A.openWindow(),S(0),C.trackOpen(),y?.(!0),x.debug("ChatWidget Opening window"))},[M.isOpen,A,y,C]),D=s(t=>{if(!N.isAllowed()){const t=N.getTimeUntilReset(),e=Math.ceil(t/1e3);return void A.setError(I("rate_limit_exceeded")+` Espera ${e}s.`)}const e={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t};A.addMessage(e),C.trackMessageSent("text"),P.sendMessage(t,"text")},[A,P,N,C,I]),Z=s(async(t,e)=>{let r;r="audio"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(t)}:"image"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(t)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${t.name}`},A.addMessage(r);const o=await qa(t);P.sendMessage(o,e)},[A,P]),U=s(t=>{const e={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:t.latitude,longitude:t.longitude,name:"Mi ubicación"};A.addMessage(e),P.sendMessage(JSON.stringify(t),"location")},[A,P]);n(()=>{const t=()=>{M.isOpen||A.openWindow()},e=()=>{M.isOpen&&A.closeWindow()},r=()=>{M.isOpen?A.closeWindow():A.openWindow()},o=t=>{t.detail?.message&&D(t.detail.message)};return window.addEventListener("botuyo-chat:open",t),window.addEventListener("botuyo-chat:close",e),window.addEventListener("botuyo-chat:toggle",r),window.addEventListener("botuyo-chat:send-message",o),()=>{window.removeEventListener("botuyo-chat:open",t),window.removeEventListener("botuyo-chat:close",e),window.removeEventListener("botuyo-chat:toggle",r),window.removeEventListener("botuyo-chat:send-message",o)}},[M.isOpen,A,D]),n(()=>(Ra(D),()=>Ra(null)),[D]);const L=s(()=>{A.clearMessages(),x.info("Chat history cleared")},[A]);n(()=>(Wa(L),()=>Wa(null)),[L]);const R=i(()=>{if(M.isTyping)return"thinking";const t=[...M.messages].reverse().find(t=>"bot"===t.sender&&"text"===t.type);return"text"===t?.type&&t.emotion?t.emotion:"default"},[M.isTyping,M.messages]);return{state:M,actions:A,unreadCount:E,currentBotEmotion:R,isConnected:P.isConnected,getSocket:P.getSocket,handleToggle:F,handleSendText:D,handleSendAttachment:Z,handleSendLocation:U}}function Ka(t){const{apiKey:e,apiBaseUrl:a="https://api.botuyo.com",agentId:c,pageContext:l,includeSEOMetadata:d=!1,theme:u,mediaConfig:p,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w}=t,v=r(null),y=O();!function(t){const[e,r]=o(!1);n(()=>{let e=null;const o=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),o=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),n=document.getElementById("botuyo-chat-widget-root"),a=!!n?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),c="dark"===document.documentElement.getAttribute("data-theme"),l="dark"===document.body.getAttribute("data-theme"),d=!!t.current.parentElement?.closest('[data-theme="dark"]'),u=window.matchMedia("(prefers-color-scheme: dark)").matches,p=e||o||a||i||s||c||l||d||u;t.current&&(p?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(p)};o();const n=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>o();n.addEventListener("change",a);const i=new MutationObserver(()=>{o()}),s=document.getElementById("botuyo-chat-widget-root");s&&(i.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(i.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=s.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class","data-theme"]}),c=c.parentElement;const l=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),o())},100);return()=>{i.disconnect(),n.removeEventListener("change",a),clearInterval(l)}},[t])}(v);const[x,_]=o(),{mergedTheme:z,mergedStyles:E,getContainerStyle:S}=function(t,e){const r=function(){const[t,e]=o(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return n(()=>{const t=window.matchMedia("(prefers-contrast: high)"),r=window.matchMedia("(prefers-contrast: more)"),o=t=>{e(t.matches)};return t.addEventListener("change",o),r.addEventListener("change",o),()=>{t.removeEventListener("change",o),r.removeEventListener("change",o)}},[]),t}(),a=i(()=>{const o=k(t,e);return r?{...o,primaryColor:"#000000",cssVariables:{...o.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:o},[t,e,r]),s=i(()=>({radius:{...L,...t?.bubbleStyles?.radius},bot:{...R,...t?.bubbleStyles?.bot},user:{...W,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:a,mergedStyles:s,getContainerStyle:(t,e,r)=>({"--chat-primary":a.primaryColor,zIndex:t?2147483647:9999,position:"fixed",top:e&&t?0:"auto",left:e&&t?0:"bottom-left"===r?"24px":"auto",right:e&&t?0:"bottom-right"!==r&&r?"auto":"24px",bottom:e&&t?0:"24px",width:e&&t?"100%":"auto",height:e&&t?"100%":"auto"})}}(u,x);n(()=>{z.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[z.isHidden]);const{state:C,actions:T,unreadCount:M,currentBotEmotion:A,isConnected:j,handleToggle:P,handleSendText:F,handleSendAttachment:D,handleSendLocation:B,getSocket:J}=Ga({apiKey:e,apiBaseUrl:a,agentId:c,pageContext:l,includeSEOMetadata:d,theme:u,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w,onThemeUpdate:_}),V=s(t=>{T.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:t.sender,timestamp:/* @__PURE__ */new Date,content:t.content})},[T]),q=i(()=>{const t={...p||{}},e=x;return null!=e?.voiceEnabled&&(t.enableVoice=e.voiceEnabled),t},[p,x]),G=s(t=>{t.stopPropagation()},[]),K=S(C.isOpen,y,u?.position),H=i(()=>{if(!z.cssVariables)return{};const t={},e=z.cssVariables;return e.background&&(t["--background"]=e.background),e.foreground&&(t["--foreground"]=e.foreground),e.card&&(t["--card"]=e.card),e.cardForeground&&(t["--card-foreground"]=e.cardForeground),e.primary&&(t["--primary"]=e.primary),e.primaryForeground&&(t["--primary-foreground"]=e.primaryForeground),e.muted&&(t["--muted"]=e.muted),e.mutedForeground&&(t["--muted-foreground"]=e.mutedForeground),e.border&&(t["--border"]=e.border),e.destructive&&(t["--destructive"]=e.destructive),e.radius&&(t["--radius"]=e.radius),e.spacing1&&(t["--spacing-1"]=e.spacing1),e.spacing2&&(t["--spacing-2"]=e.spacing2),e.spacing3&&(t["--spacing-3"]=e.spacing3),e.spacing4&&(t["--spacing-4"]=e.spacing4),e.spacing5&&(t["--spacing-5"]=e.spacing5),e.spacing6&&(t["--spacing-6"]=e.spacing6),e.spacing8&&(t["--spacing-8"]=e.spacing8),t},[z.cssVariables]);return z.isHidden?null:/* @__PURE__ */N("div",{ref:v,id:"botuyo-chat-widget",className:b("botuyo-chat-widget flex flex-col",!y&&("bottom-left"===u?.position?"items-start":"items-end")),style:{...K,...H,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===u?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===u?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===u?.effects?.softShadows?"false":void 0,children:[
|
|
31
|
+
/* @__PURE__ */$(Ha,{...a,onStateChange:t=>{c(t),t&&d(0),n?.(t)},onEvent:w})]})})}function Va(){const t=d(Ba);if(!t)throw new Error("useChatWidget must be used within a ChatWidgetProvider. Wrap your app with <ChatWidgetProvider>...</ChatWidgetProvider>");return t}const qa=t=>new Promise((e,r)=>{const o=new FileReader;o.readAsDataURL(t),o.onload=()=>e(o.result),o.onerror=t=>r(t)});function Ga(t){const{apiKey:a,apiBaseUrl:l,agentId:d,pageContext:u,includeSEOMetadata:p=!1,theme:g,userContext:m,onLogin:f,onNavigate:b,onEvent:v,onStateChange:y,onThemeUpdate:k}=t,[E,S]=o(0),O=r(0),{t:I}=h(),C=function(t,e,o=!0){const a=r(null);return n(()=>{if(!o||!t||!e)return;const r=`${t}/analytics`;a.current=new Za(r,e);const n=()=>a.current?.flush(),i=()=>{"hidden"===document.visibilityState&&a.current?.flush()};return window.addEventListener("beforeunload",n),window.addEventListener("visibilitychange",i),()=>{window.removeEventListener("beforeunload",n),window.removeEventListener("visibilitychange",i),a.current?.destroy()}},[t,e,o]),{trackOpen:s(()=>{a.current?.trackOpen()},[]),trackClose:s(()=>{a.current?.trackClose()},[]),trackMessageSent:s(t=>{a.current?.trackMessageSent(t)},[]),trackMessageReceived:s((t,e)=>{a.current?.trackMessageReceived(t,e)},[]),trackError:s((t,e)=>{a.current?.trackError(t,e)},[]),trackConnectionStatus:s(t=>{a.current?.trackConnectionStatus(t)},[]),trackFeatureUsed:s(t=>{a.current?.trackFeatureUsed(t)},[])}}(l,a,!0),$=function({enabled:t=!0,soundEnabled:e=!0,desktopEnabled:a=!0,botName:i="BotUyo",logoUrl:c,notificationSoundUrl:l}={}){const[d,u]=o("default"),p=r(null),h=c||w,g=l||z;n(()=>{e&&"undefined"!=typeof window&&(p.current=new Audio(g),p.current.volume=.3)},[e,g]),n(()=>{"undefined"!=typeof window&&"Notification"in window&&u(Notification.permission)},[]);const m=s(async()=>{if("undefined"==typeof window||!("Notification"in window))return x.warn("Notifications API not available"),!1;try{const t=await Notification.requestPermission();return u(t),x.info("Notification permission:",t),"granted"===t}catch(t){return x.error("Error requesting notification permission:",t),!1}},[]),f=s(e=>{if(t&&a&&"granted"===d&&("undefined"==typeof document||!document.hasFocus()))try{const t=`Nuevo mensaje de ${i}`;let r="Mensaje recibido";"text"===e.type&&"content"in e?r=e.content?.slice(0,100)||"Mensaje recibido":"image"===e.type?r="📷 Imagen":"audio"===e.type?r="🎵 Audio":"location"===e.type&&(r="📍 Ubicación");const o=new Notification(t,{body:r,icon:h,tag:"chat-message",requireInteraction:!1,silent:!1});o.onclick=()=>{window.focus(),o.close()},setTimeout(()=>o.close(),5e3)}catch(r){x.error("Error showing notification:",r)}},[t,a,d,i,h]),b=s(()=>{if(t&&e&&("undefined"==typeof document||!document.hasFocus()))try{p.current?.play().catch(t=>{x.debug("Audio playback blocked:",t)})}catch(r){x.error("Error playing sound:",r)}},[t,e]),v=s(t=>{f(t),b()},[f,b]);return{permission:d,requestPermission:m,notify:f,playSound:b,notifyWithSound:v}}({enabled:!0,soundEnabled:!0,desktopEnabled:!0,botName:g?.botName||"BotUyo",logoUrl:g?.logoUrl}),N=function(t=10,e=6e4){const o=r([]);return{isAllowed:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),!(o.current.length>=t||(o.current.push(r),0))},[t,e]),getRemainingAttempts:s(()=>{const r=Date.now();return o.current=o.current.filter(t=>r-t<e),Math.max(0,t-o.current.length)},[t,e]),getTimeUntilReset:s(()=>{if(0===o.current.length)return 0;const t=Date.now(),r=o.current[0],n=e-(t-r);return Math.max(0,n)},[e]),reset:s(()=>{o.current=[]},[])}}(10,6e4),{state:M,actions:A}=function(t="default"){const[r,a]=c(mt,gt),[i,l]=o(!1),d=e.useMemo(()=>function(t="default"){return`botuyo_chat_v1_${t}`}(t),[t]),u=e.useMemo(()=>((t="default")=>(ht.has(t)||ht.set(t,new pt(t)),ht.get(t)))(t),[t]);n(()=>{"undefined"==typeof window||i||(async()=>{try{await u.migrateFromLocalStorage(t);const e=await u.getMessages(100),r=await u.getMetadata();if(e.length>0||r){const t={messages:e.map(t=>({...t,timestamp:new Date(t.timestamp)})),sessionId:r?.sessionId||null,isOpen:r?.isOpen||!1};a({type:"RESTORE_SESSION",payload:t})}}catch(e){x.warn("Chat: Error rehydrating from IndexedDB",e);try{const t=localStorage.getItem(d);if(t){const e=JSON.parse(t);e.messages&&(e.messages=e.messages.map(t=>({...t,timestamp:new Date(t.timestamp)}))),a({type:"RESTORE_SESSION",payload:e})}}catch(r){x.error("Chat: Fallback rehydration failed",r)}}finally{l(!0)}})()},[i]),n(()=>{if(!i)return;const t=setTimeout(async()=>{try{await u.saveMessages(r.messages),await u.setMetadata({isOpen:r.isOpen,sessionId:r.sessionId})}catch(t){x.error("Chat Persistence Error:",t);try{const t={isOpen:r.isOpen,messages:r.messages,sessionId:r.sessionId};localStorage.setItem(d,JSON.stringify(t))}catch(e){x.error("Chat: Fallback persistence failed",e)}}},500);return()=>clearTimeout(t)},[r.isOpen,r.messages,r.sessionId,i]);const p=s(t=>{a({type:"ADD_MESSAGE",payload:t})},[]),h=s(()=>a({type:"TOGGLE_WINDOW"}),[]),g=s(()=>a({type:"OPEN_WINDOW"}),[]),m=s(()=>a({type:"CLOSE_WINDOW"}),[]),f=s(t=>a({type:"SET_CONNECTED",payload:t}),[]),w=s(t=>a({type:"SET_TYPING",payload:t}),[]),b=s(t=>a({type:"SET_MESSAGES",payload:t}),[]),v=s(t=>a({type:"SET_ERROR",payload:t}),[]),y=s(t=>a({type:"SET_SESSION_ID",payload:t}),[]),k=s(()=>{localStorage.removeItem(d),a({type:"CLEAR_CHAT"})},[]),_=s(()=>{a({type:"SET_MESSAGES",payload:[]})},[]);return{state:r,isHydrated:i,actions:{toggleWindow:h,openWindow:g,closeWindow:m,setConnected:f,setTyping:w,addMessage:p,setMessages:b,setError:v,setSessionId:y,clearChat:k,clearMessages:_}}}(d),j=function(t=!1){const e="undefined"!=typeof window?window.location.pathname:"",r=i(()=>e,[e]),[a,s]=o({});return n(()=>{if(!t)return void s({});const e=setTimeout(()=>{const t=function(){if("undefined"==typeof window)return{};const t={};t.title=document.title,document.querySelectorAll("meta").forEach(e=>{const r=e.getAttribute("name"),o=e.getAttribute("property"),n=e.getAttribute("content");if(n){if(r)switch(r){case"description":t.description=n;break;case"keywords":t.keywords=n.split(",").map(t=>t.trim());break;case"author":t.author=n}if(o){if(o.startsWith("og:")){const e=o.replace("og:","og_");t[e]=n}if(o.startsWith("twitter:")){const e=o.replace("twitter:","twitter_");t[e]=n}}}});try{const e=document.querySelectorAll('script[type="application/ld+json"]');if(e.length>0){const r=[];e.forEach(t=>{try{const e=JSON.parse(t.textContent||"");r.push(e)}catch{}}),r.length>0&&(t.structuredData=r)}}catch{}return t}();s(t)},100);return()=>clearTimeout(e)},[r,t]),t&&Object.keys(a).length>0?a:void 0}(p),P=function(t){const{apiKey:e,apiBaseUrl:a,agentId:c,pageContext:l,userContext:d}=t,u=r(t);n(()=>{u.current=t},[t]);const p=r(null),[h,g]=o(!1),[m,f]=o(!1),w=r(function(){try{const t=localStorage.getItem(Pa);if(t)return t;const e=Fa();return localStorage.setItem(Pa,e),e}catch{return x.warn("localStorage not available, using session-only device ID"),Fa()}}()),b=r(l);n(()=>{b.current=l},[l]);const v=s(t=>{const e=Da.safeParse(t),r=e.success&&e.data.id?e.data.id:`msg-${Math.random().toString(36).slice(2,11)}`,o=e.success&&e.data.sender?e.data.sender:"bot",n=e.success&&e.data.timestamp?new Date(e.data.timestamp):/* @__PURE__ */new Date,a=e.success?e.data:{type:"text"};switch(a.type){case"image":return{id:r,type:"image",sender:o,timestamp:n,imageUrl:a.imageUrl||a.content||"",altText:"Imagen enviada"};case"audio":return{id:r,type:"audio",sender:o,timestamp:n,content:a.audioUrl||a.content||""};case"location":return{id:r,type:"location",sender:o,timestamp:n,latitude:Number(a.latitude||0),longitude:Number(a.longitude||0),name:a.content||"Ubicación compartida"};case"system":return{id:r,type:"system",sender:"system",timestamp:n,content:String(a.content||"")};default:return{id:r,type:"text",sender:o,timestamp:n,content:String(a.content||"Sin contenido"),emotion:a.emotion}}},[]),y=s(()=>{if(!e||!a)return;if(p.current?.connected)return;g(!0);const t=T(`${a}/webchat`,{auth:{apiKey:e,deviceId:w.current,agentId:c,token:d?.token,metadata:d?.metadata},transports:["websocket","polling"],reconnection:!0,reconnectionAttempts:5,reconnectionDelay:1e3,extraHeaders:{"bypass-tunnel-reminder":"true","X-Tunnel-Skip-Anti-Phishing-Page":"true"}});t.on("connect",()=>{g(!1),f(!0),u.current.onConnected(`temp-${Date.now()}`,void 0)}),t.on("disconnect",t=>{g(!1),f(!1),u.current.onDisconnected()}),t.on("connect_error",t=>{g(!1),u.current.onError(`Error de conexión: ${t.message}`)}),t.on("connection_ack",t=>{u.current.onConnected(t.sessionId,t.config)}),t.on("bot_message",t=>{try{u.current.onMessage(v(t))}catch(e){x.error("ChatSocket Error processing bot_message:",e)}}),t.on("chat_history",t=>{if(t.messages&&Array.isArray(t.messages))if(u.current.onHistoryLoaded){const e=t.messages.map(t=>{try{return v(t)}catch(e){return x.debug("Error processing history message:",e),null}}).filter(t=>null!==t);u.current.onHistoryLoaded(e)}else t.messages.forEach(t=>{try{u.current.onMessage(v(t))}catch(e){x.debug("Error processing history message:",e)}});u.current.onEvent&&u.current.onEvent("history_loaded",t)}),t.on("bot_typing",t=>u.current.onTyping(t)),t.on("auth_success",t=>{u.current.onLogin&&u.current.onLogin(t),t.theme&&u.current.onThemeUpdate&&u.current.onThemeUpdate(t.theme)}),p.current=t},[e,a]),k=s(()=>{p.current&&(p.current.disconnect(),p.current=null,f(!1))},[]),z=r(y);z.current=y,n(()=>(z.current(),()=>{p.current&&(p.current.disconnect(),p.current=null)}),[]);const E=r([]),S=r([]),O=s(()=>`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,[]),I=s(()=>{if(p.current?.connected)for(;E.current.length>0;){const t=E.current.shift();p.current.emit("user_message",t)}},[]);n(()=>{m&&I()},[m,I]),n(()=>{if(!m)return;const t=setInterval(()=>{const t=Date.now();S.current=S.current.filter(e=>t<e.nextRetryAt||(e.attempts>=e.maxAttempts?(u.current.onEvent?.("message_failed",{id:e.id,payload:e.payload}),x.error("Message failed after max retries:",e.id),!1):!p.current?.connected||(p.current.emit("user_message",e.payload,t=>{t?.success&&u.current.onEvent?.("message_sent",{id:e.id})}),e.attempts++,e.nextRetryAt=t+1e3*Math.pow(2,e.attempts),e.attempts<e.maxAttempts)))},500);return()=>clearInterval(t)},[m]);const C=s((t,e="text")=>{const r=O(),o={...b.current,currentUrl:"undefined"!=typeof window?window.location.href:void 0,sentAt:/* @__PURE__ */(new Date).toISOString(),deviceId:w.current},n={id:r,content:t.trim(),type:e,metadata:o};return p.current?.connected?(p.current.emit("user_message",n,t=>{!1!==t?.success&&t?u.current.onEvent?.("message_sent",{id:r}):(S.current.push({id:r,payload:n,attempts:0,maxAttempts:3,nextRetryAt:Date.now()+1e3}),u.current.onEvent?.("message_retry_queued",{id:r}))}),r):(E.current.push(n),u.current.onEvent?.("queued_message",{id:r,payload:n}),r)},[O]),$=i(()=>_(t=>{p.current?.emit("typing",t)},250),[]);return{isConnected:m,isConnecting:h,sendMessage:C,sendTyping:$,getSocket:s(()=>p.current,[]),requestHistory:s(()=>{p.current?.emit("request_history")},[]),reconnect:y,disconnect:k}}({apiKey:a,apiBaseUrl:l,agentId:d,pageContext:i(()=>j?{...u||{},seo:{...j||{}}}:u,[u,j]),userContext:m,onMessage:s(t=>{const e=Date.now(),r=O.current>0?e-O.current:void 0;O.current=e,A.addMessage(t),C.trackMessageReceived(t.type,r),M.isOpen||"bot"!==t.sender||(S(t=>t+1),$.notifyWithSound(t))},[A,M.isOpen,C,$]),onConnected:s((t,e)=>{A.setConnected(!0),A.setSessionId(t),C.trackConnectionStatus(!0),e&&k&&k(e),e&&v&&v("backend_config",e)},[A,v,k,C]),onDisconnected:s(()=>{A.setConnected(!1),C.trackConnectionStatus(!1)},[A,C]),onTyping:s(t=>A.setTyping(t),[A]),onError:s(t=>{A.setError(t),C.trackError(t)},[A,C]),onLogin:f,onNavigate:b,onEvent:v,onThemeUpdate:k,onHistoryLoaded:s(t=>{const e=new Set(M.messages.map(t=>t.id)),r=t.filter(t=>!e.has(t.id));r.length>0&&(0===M.messages.length?A.setMessages(t):r.forEach(t=>A.addMessage(t)))},[M.messages,A])}),F=s(()=>{x.debug("ChatWidget handleToggle called, current isOpen:",M.isOpen),M.isOpen?(A.closeWindow(),C.trackClose(),y?.(!1),x.debug("ChatWidget Closing window")):(A.openWindow(),S(0),C.trackOpen(),y?.(!0),x.debug("ChatWidget Opening window"))},[M.isOpen,A,y,C]),D=s(t=>{if(!N.isAllowed()){const t=N.getTimeUntilReset(),e=Math.ceil(t/1e3);return void A.setError(I("rate_limit_exceeded")+` Espera ${e}s.`)}const e={id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:t};A.addMessage(e),C.trackMessageSent("text"),P.sendMessage(t,"text")},[A,P,N,C,I]),Z=s(async(t,e)=>{let r;r="audio"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"audio",sender:"user",timestamp:/* @__PURE__ */new Date,content:URL.createObjectURL(t)}:"image"===e?{id:`temp-${Date.now()}-${Math.random()}`,type:"image",sender:"user",timestamp:/* @__PURE__ */new Date,imageUrl:URL.createObjectURL(t)}:{id:`temp-${Date.now()}-${Math.random()}`,type:"text",sender:"user",timestamp:/* @__PURE__ */new Date,content:`📎 ${t.name}`},A.addMessage(r);const o=await qa(t);P.sendMessage(o,e)},[A,P]),U=s(t=>{const e={id:`temp-${Date.now()}-${Math.random()}`,type:"location",sender:"user",timestamp:/* @__PURE__ */new Date,latitude:t.latitude,longitude:t.longitude,name:"Mi ubicación"};A.addMessage(e),P.sendMessage(JSON.stringify(t),"location")},[A,P]);n(()=>{const t=()=>{M.isOpen||A.openWindow()},e=()=>{M.isOpen&&A.closeWindow()},r=()=>{M.isOpen?A.closeWindow():A.openWindow()},o=t=>{t.detail?.message&&D(t.detail.message)};return window.addEventListener("botuyo-chat:open",t),window.addEventListener("botuyo-chat:close",e),window.addEventListener("botuyo-chat:toggle",r),window.addEventListener("botuyo-chat:send-message",o),()=>{window.removeEventListener("botuyo-chat:open",t),window.removeEventListener("botuyo-chat:close",e),window.removeEventListener("botuyo-chat:toggle",r),window.removeEventListener("botuyo-chat:send-message",o)}},[M.isOpen,A,D]),n(()=>(Ra(D),()=>Ra(null)),[D]);const L=s(()=>{A.clearMessages(),x.info("Chat history cleared")},[A]);n(()=>(Wa(L),()=>Wa(null)),[L]);const R=i(()=>{if(M.isTyping)return"thinking";const t=[...M.messages].reverse().find(t=>"bot"===t.sender&&"text"===t.type);return"text"===t?.type&&t.emotion?t.emotion:"default"},[M.isTyping,M.messages]);return{state:M,actions:A,unreadCount:E,currentBotEmotion:R,isConnected:P.isConnected,getSocket:P.getSocket,handleToggle:F,handleSendText:D,handleSendAttachment:Z,handleSendLocation:U}}function Ka(t){const{apiKey:e,apiBaseUrl:a="https://api.botuyo.com",agentId:c,pageContext:l,includeSEOMetadata:d=!1,theme:u,mediaConfig:p,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w}=t,v=r(null),y=O();!function(t){const[e,r]=o(!1);n(()=>{let e=null;const o=()=>{if(!t.current)return;const e=!!t.current.parentElement?.closest(".dark"),o=!!document.getElementById("botuyo-chat-widget-root")?.classList.contains("dark"),n=document.getElementById("botuyo-chat-widget-root"),a=!!n?.parentElement?.closest(".dark"),i=document.documentElement.classList.contains("dark"),s=document.body.classList.contains("dark"),c="dark"===document.documentElement.getAttribute("data-theme"),l="dark"===document.body.getAttribute("data-theme"),d=!!t.current.parentElement?.closest('[data-theme="dark"]'),u=window.matchMedia("(prefers-color-scheme: dark)").matches,p=e||o||a||i||s||c||l||d||u;t.current&&(p?t.current.classList.add("dark"):t.current.classList.remove("dark")),r(p)};o();const n=window.matchMedia("(prefers-color-scheme: dark)"),a=()=>o();n.addEventListener("change",a);const i=new MutationObserver(()=>{o()}),s=document.getElementById("botuyo-chat-widget-root");s&&(i.observe(s,{attributes:!0,attributeFilter:["class"]}),s.parentElement&&(i.observe(s.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=s.parentElement)),i.observe(document.documentElement,{attributes:!0,attributeFilter:["class","data-theme"]}),i.observe(document.body,{attributes:!0,attributeFilter:["class","data-theme"]});let c=t.current?.parentElement;for(;c;)i.observe(c,{attributes:!0,attributeFilter:["class","data-theme"]}),c=c.parentElement;const l=setInterval(()=>{const t=document.getElementById("botuyo-chat-widget-root");t&&t.parentElement!==e&&(e&&t.parentElement&&(i.observe(t.parentElement,{attributes:!0,attributeFilter:["class"],childList:!0}),e=t.parentElement),o())},100);return()=>{i.disconnect(),n.removeEventListener("change",a),clearInterval(l)}},[t])}(v);const[x,_]=o(),{mergedTheme:z,mergedStyles:E,getContainerStyle:S}=function(t,e){const r=function(){const[t,e]=o(()=>"undefined"!=typeof window&&(window.matchMedia("(prefers-contrast: high)").matches||window.matchMedia("(prefers-contrast: more)").matches));return n(()=>{const t=window.matchMedia("(prefers-contrast: high)"),r=window.matchMedia("(prefers-contrast: more)"),o=t=>{e(t.matches)};return t.addEventListener("change",o),r.addEventListener("change",o),()=>{t.removeEventListener("change",o),r.removeEventListener("change",o)}},[]),t}(),a=i(()=>{const o=k(t,e);return r?{...o,primaryColor:"#000000",cssVariables:{...o.cssVariables,background:"#FFFFFF",foreground:"#000000",card:"#FFFFFF",cardForeground:"#000000",primary:"#000000",primaryForeground:"#FFFFFF",muted:"#F5F5F5",mutedForeground:"#000000",border:"#000000"}}:o},[t,e,r]),s=i(()=>({radius:{...L,...t?.bubbleStyles?.radius},bot:{...R,...t?.bubbleStyles?.bot},user:{...W,...t?.bubbleStyles?.user},launcher:{...t?.bubbleStyles?.launcher},mapCard:{...t?.bubbleStyles?.mapCard}}),[t?.bubbleStyles]);return{mergedTheme:a,mergedStyles:s,getContainerStyle:(t,e,r)=>({"--chat-primary":a.primaryColor,zIndex:t?2147483647:9999,position:"fixed",top:e&&t?0:"auto",left:e&&t?0:"bottom-left"===r?"24px":"auto",right:e&&t?0:"bottom-right"!==r&&r?"auto":"24px",bottom:e&&t?0:"24px",width:e&&t?"100%":"auto",height:e&&t?"100%":"auto"})}}(u,x);n(()=>{z.isHidden&&console.warn('[BotUyo] ⚠️ El agente (o Flow) de IA asociado a esta API Key se encuentra pausado o en estado "boceto" (draft). El widget no se mostrará hasta que lo publiques dentro de la plataforma BotUyo.')},[z.isHidden]);const{state:C,actions:T,unreadCount:M,currentBotEmotion:A,isConnected:j,handleToggle:P,handleSendText:F,handleSendAttachment:D,handleSendLocation:B,getSocket:J}=Ga({apiKey:e,apiBaseUrl:a,agentId:c,pageContext:l,includeSEOMetadata:d,theme:u,userContext:h,onLogin:g,onNavigate:m,onEvent:f,onStateChange:w,onThemeUpdate:_}),V=s(t=>{T.addMessage({id:`voice-${Date.now()}-${Math.random().toString(36).slice(2,7)}`,type:"text",sender:t.sender,timestamp:/* @__PURE__ */new Date,content:t.content})},[T]),q=i(()=>{const t={...p||{}},e=x;return null!=e?.voiceEnabled&&(t.enableVoice=e.voiceEnabled),t},[p,x]),G=s(t=>{t.stopPropagation()},[]),K=S(C.isOpen,y,u?.position),H=i(()=>{if(!z.cssVariables)return{};const t={},e=z.cssVariables;return e.background&&(t["--background"]=e.background),e.foreground&&(t["--foreground"]=e.foreground),e.card&&(t["--card"]=e.card),e.cardForeground&&(t["--card-foreground"]=e.cardForeground),e.primary&&(t["--primary"]=e.primary),e.primaryForeground&&(t["--primary-foreground"]=e.primaryForeground),e.muted&&(t["--muted"]=e.muted),e.mutedForeground&&(t["--muted-foreground"]=e.mutedForeground),e.border&&(t["--border"]=e.border),e.destructive&&(t["--destructive"]=e.destructive),e.radius&&(t["--radius"]=e.radius),e.spacing1&&(t["--spacing-1"]=e.spacing1),e.spacing2&&(t["--spacing-2"]=e.spacing2),e.spacing3&&(t["--spacing-3"]=e.spacing3),e.spacing4&&(t["--spacing-4"]=e.spacing4),e.spacing5&&(t["--spacing-5"]=e.spacing5),e.spacing6&&(t["--spacing-6"]=e.spacing6),e.spacing8&&(t["--spacing-8"]=e.spacing8),t},[z.cssVariables]);return z.isHidden?null:/* @__PURE__ */N("div",{ref:v,id:"botuyo-chat-widget",className:b("botuyo-chat-widget flex flex-col",!y&&("bottom-left"===u?.position?"items-start":"items-end")),style:{...K,...H,pointerEvents:"auto",backgroundColor:"transparent"},"data-animations-disabled":!1===u?.animations?.enabled?"true":void 0,"data-effects-glassmorphism":!1===u?.effects?.glassmorphism?"false":void 0,"data-effects-shadows":!1===u?.effects?.softShadows?"false":void 0,children:[
|
|
32
32
|
/* @__PURE__ */$("div",{className:b("transition-all duration-400 ease-[cubic-bezier(0.34,1.56,0.64,1)]",y?"bottom-left"===u?.position?"origin-bottom-left":"origin-bottom-right":"origin-bottom",C.isOpen?"opacity-100 scale-100 h-full w-full translate-y-0 pointer-events-auto":"opacity-0 scale-[0.85] pointer-events-none translate-y-8 h-0 w-0"),style:{pointerEvents:C.isOpen?"auto":"none"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */$(U,{children:/* @__PURE__ */$(I,{isOpen:C.isOpen,isConnected:j,isTyping:C.isTyping,messages:C.messages,onClose:()=>T.closeWindow(),onSendMessage:F,onSendAttachment:D,onSendLocation:B,botName:z.botName,logoUrl:z.logoUrl,welcomeMessage:z.welcomeMessage,inputPlaceholder:u?.inputPlaceholder,primaryColor:z.primaryColor,position:u?.position,bubbleStyles:E,avatars:u?.avatars,mediaConfig:q,theme:z,avatar3dUrl:u?.avatar3dUrl,getSocket:J,onAddVoiceMessage:V})})}),
|
|
33
33
|
/* @__PURE__ */$("div",{className:b(C.isOpen?"hidden":"block",!y&&"mt-4"),style:{pointerEvents:"auto"},onMouseDown:G,onTouchStart:G,children:/* @__PURE__ */$(Z,{isOpen:C.isOpen,onClick:P,unreadCount:M,position:u?.position||"bottom-right",primaryColor:u?.primaryColor,logoUrl:u?.logoUrl,starterPrompt:u?.starterPrompt,avatars:u?.avatars,emotion:A,styles:E,promptPersistence:u?.promptPersistence,avatarScale:u?.avatarScale,showPromptAvatar:u?.showPromptAvatar})})]})}function Ha(t){/* @__PURE__ */
|
|
34
34
|
return $(E,{defaultLocale:t.theme?.defaultLocale,children:/* @__PURE__ */$(S,{animations:t.theme?.animations,effects:t.theme?.effects,children:/* @__PURE__ */$(Ka,{...t})})})}const Ya=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,ChatWidget:Ha,ChatWidgetInner:Ka},Symbol.toStringTag,{value:"Module"})),Xa="https://api.botuyo.com";class Qa extends a{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(){return{hasError:!0}}componentDidCatch(t,e){console.error("[BotUyoChat] Widget error:",t,e)}render(){return this.state.hasError?null:this.props.children}}const ti={"--background":"240 10% 3.9%","--foreground":"0 0% 98%","--card":"240 10% 3.9%","--cardForeground":"0 0% 98%","--primary":"160 84% 39%","--primaryForeground":"0 0% 100%","--muted":"240 3.7% 15.9%","--mutedForeground":"240 5% 64.9%","--border":"240 3.7% 15.9%"},ei=u(()=>Promise.resolve().then(()=>Ya).then(t=>({default:t.ChatWidget})));class ri{root=null;container=null;shadowRoot=null;mountPoint=null;darkModeObserver=null;darkModeMediaQuery=null;config=null;init(t){return this.config={...t,apiBaseUrl:t.apiBaseUrl||Xa},this.render(),this.setupDarkModeDetection(),this}render(){if(!this.config)return void console.error("[BotUyoChat] No configuration provided");if(!this.container){this.container=document.createElement("div"),this.container.id="botuyo-chat-widget-root",document.body.appendChild(this.container),this.shadowRoot=this.container.attachShadow({mode:"open"});const t=document.createElement("style");t.textContent=M.replace(/:root/g,":host"),this.shadowRoot.appendChild(t),this.mountPoint=document.createElement("div"),this.mountPoint.id="botuyo-chat-widget-root",this.shadowRoot.appendChild(this.mountPoint)}if(this.config.theme?.cssVariables&&this.mountPoint){const t=this.config.theme.cssVariables,e={background:t.background,foreground:t.foreground,card:t.card,cardForeground:t.cardForeground,primary:t.primary,primaryForeground:t.primaryForeground,muted:t.muted,mutedForeground:t.mutedForeground,border:t.border,destructive:t.destructive,radius:t.radius,spacing1:t.spacing1,spacing2:t.spacing2,spacing3:t.spacing3,spacing4:t.spacing4,spacing5:t.spacing5,spacing6:t.spacing6,spacing8:t.spacing8};Object.entries(e).forEach(([t,e])=>{void 0!==e&&this.mountPoint.style.setProperty(`--${t}`,e)})}this.mountPoint&&!this.config.theme?.cssVariables&&(!function(){const t=document.documentElement.getAttribute("data-theme");return"dark"===t||"light"!==t&&window.matchMedia("(prefers-color-scheme: dark)").matches}()?Object.keys(ti).forEach(t=>{this.mountPoint.style.removeProperty(t)}):Object.entries(ti).forEach(([t,e])=>{this.mountPoint.style.setProperty(t,e)})),!this.root&&this.mountPoint&&(this.root=t(this.mountPoint));const r={apiKey:this.config.apiKey,apiBaseUrl:this.config.apiBaseUrl||Xa,agentId:this.config.agentId,theme:{primaryColor:"#10b981",botName:"Asistente Virtual",position:"bottom-right",welcomeMessage:"¡Hola! 👋 ¿En qué puedo ayudarte?",inputPlaceholder:"Escribe tu mensaje...",borderRadius:"0.75rem",launcherBorderRadius:"50%",...this.config.theme},userContext:this.config.userContext,pageContext:this.config.pageContext,includeSEOMetadata:this.config.includeSEOMetadata??!1,mediaConfig:this.config.mediaConfig,onNavigate:this.config.onNavigate,onLogin:this.config.onLogin,onEvent:this.config.onEvent,onStateChange:this.config.onStateChange},o=e.createElement(p,{fallback:e.createElement("div",{style:{position:"fixed",bottom:"24px",right:"24px",width:"60px",height:"60px",borderRadius:"50%",backgroundColor:r.theme?.primaryColor||"#10b981",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 4px 12px rgba(0, 0, 0, 0.15)",cursor:"wait"}},e.createElement("div",{style:{width:"24px",height:"24px",border:"3px solid rgba(255, 255, 255, 0.3)",borderTopColor:"#fff",borderRadius:"50%",animation:"spin 1s linear infinite"}}))},e.createElement(ei,r));this.root.render(e.createElement(Qa,null,e.createElement(E,{defaultLocale:this.config.theme?.defaultLocale,children:o}))),console.log("[BotUyoChat] Widget initialized",r)}update(t){this.config?(this.config={...this.config,...t,theme:{...this.config.theme,...t.theme}},this.render()):console.error("[BotUyoChat] Widget not initialized")}destroy(){this.darkModeObserver&&(this.darkModeObserver.disconnect(),this.darkModeObserver=null),this.darkModeMediaQuery&&(this.darkModeMediaQuery.removeEventListener("change",this.handleDarkModeChange),this.darkModeMediaQuery=null),this.root&&(this.root.unmount(),this.root=null),this.container&&this.container.parentNode&&(this.container.parentNode.removeChild(this.container),this.container=null,this.shadowRoot=null,this.mountPoint=null),this.config=null,console.log("[BotUyoChat] Widget destroyed")}setupDarkModeDetection(){this.config?.theme?.cssVariables||(this.handleDarkModeChange=()=>this.render(),this.darkModeObserver=new MutationObserver(this.handleDarkModeChange),this.darkModeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),this.darkModeMediaQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.darkModeMediaQuery.addEventListener("change",this.handleDarkModeChange))}handleDarkModeChange=()=>{};open(){window.dispatchEvent(new CustomEvent("botuyo-chat:open"))}close(){window.dispatchEvent(new CustomEvent("botuyo-chat:close"))}sendMessage(t){window.dispatchEvent(new CustomEvent("botuyo-chat:send-message",{detail:{message:t}}))}getState(){return null}}const oi=new ri;window.BotUyoChat=oi;export{ri as BotUyoChatWidget,D as ChatWidget,Ja as ChatWidgetProvider,Ha as ChatWidgetUnstyled,E as LanguageProvider,oi as default,Va as useChatWidget,C as useLanguage};
|