@applica-software-guru/persona-sdk 0.1.43 → 0.1.44-preview1

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.
@@ -1,15 +1,6 @@
1
- "use strict";var ie=Object.defineProperty;var ce=(r,t,e)=>t in r?ie(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var i=(r,t,e)=>ce(r,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const y=require("react"),te=require("@assistant-ui/react");var ne={exports:{}},O={},se;function le(){if(se)return O;se=1;/**
2
- * @license React
3
- * react-jsx-runtime.development.js
4
- *
5
- * Copyright (c) Meta Platforms, Inc. and affiliates.
6
- *
7
- * This source code is licensed under the MIT license found in the
8
- * LICENSE file in the root directory of this source tree.
9
- */return function(){function r(s){if(s==null)return null;if(typeof s=="function")return s.$$typeof===j?null:s.displayName||s.name||null;if(typeof s=="string")return s;switch(s){case k:return"Fragment";case W:return"Profiler";case $:return"StrictMode";case S:return"Suspense";case C:return"SuspenseList";case v:return"Activity"}if(typeof s=="object")switch(typeof s.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),s.$$typeof){case I:return"Portal";case z:return(s.displayName||"Context")+".Provider";case D:return(s._context.displayName||"Context")+".Consumer";case u:var a=s.render;return s=s.displayName,s||(s=a.displayName||a.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case x:return a=s.displayName||null,a!==null?a:r(s.type)||"Memo";case p:a=s._payload,s=s._init;try{return r(s(a))}catch{}}return null}function t(s){return""+s}function e(s){try{t(s);var a=!1}catch{a=!0}if(a){a=console;var l=a.error,m=typeof Symbol=="function"&&Symbol.toStringTag&&s[Symbol.toStringTag]||s.constructor.name||"Object";return l.call(a,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",m),t(s)}}function n(s){if(s===k)return"<>";if(typeof s=="object"&&s!==null&&s.$$typeof===p)return"<...>";try{var a=r(s);return a?"<"+a+">":"<...>"}catch{return"<...>"}}function o(){var s=A.A;return s===null?null:s.getOwner()}function c(){return Error("react-stack-top-frame")}function d(s){if(G.call(s,"key")){var a=Object.getOwnPropertyDescriptor(s,"key").get;if(a&&a.isReactWarning)return!1}return s.key!==void 0}function b(s,a){function l(){X||(X=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",a))}l.isReactWarning=!0,Object.defineProperty(s,"key",{get:l,configurable:!0})}function h(){var s=r(this.type);return H[s]||(H[s]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),s=this.props.ref,s!==void 0?s:null}function f(s,a,l,m,E,P,F,U){return l=P.ref,s={$$typeof:_,type:s,key:a,props:P,_owner:E},(l!==void 0?l:null)!==null?Object.defineProperty(s,"ref",{enumerable:!1,get:h}):Object.defineProperty(s,"ref",{enumerable:!1,value:null}),s._store={},Object.defineProperty(s._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(s,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(s,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:F}),Object.defineProperty(s,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.freeze&&(Object.freeze(s.props),Object.freeze(s)),s}function w(s,a,l,m,E,P,F,U){var g=a.children;if(g!==void 0)if(m)if(ae(g)){for(m=0;m<g.length;m++)N(g[m]);Object.freeze&&Object.freeze(g)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else N(g);if(G.call(a,"key")){g=r(s);var T=Object.keys(a).filter(function(oe){return oe!=="key"});m=0<T.length?"{key: someKey, "+T.join(": ..., ")+": ...}":"{key: someKey}",ee[g+m]||(T=0<T.length?"{"+T.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
10
- let props = %s;
11
- <%s {...props} />
12
- React keys must be passed directly to JSX without using spread:
13
- let props = %s;
14
- <%s key={someKey} {...props} />`,m,g,T,g),ee[g+m]=!0)}if(g=null,l!==void 0&&(e(l),g=""+l),d(a)&&(e(a.key),g=""+a.key),"key"in a){l={};for(var Y in a)Y!=="key"&&(l[Y]=a[Y])}else l=a;return g&&b(l,typeof s=="function"?s.displayName||s.name||"Unknown":s),f(s,g,P,E,o(),l,F,U)}function N(s){typeof s=="object"&&s!==null&&s.$$typeof===_&&s._store&&(s._store.validated=1)}var R=y,_=Symbol.for("react.transitional.element"),I=Symbol.for("react.portal"),k=Symbol.for("react.fragment"),$=Symbol.for("react.strict_mode"),W=Symbol.for("react.profiler"),D=Symbol.for("react.consumer"),z=Symbol.for("react.context"),u=Symbol.for("react.forward_ref"),S=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),x=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),v=Symbol.for("react.activity"),j=Symbol.for("react.client.reference"),A=R.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,G=Object.prototype.hasOwnProperty,ae=Array.isArray,L=console.createTask?console.createTask:function(){return null};R={"react-stack-bottom-frame":function(s){return s()}};var X,H={},Z=R["react-stack-bottom-frame"].bind(R,c)(),Q=L(n(c)),ee={};O.Fragment=k,O.jsx=function(s,a,l,m,E){var P=1e4>A.recentlyCreatedOwnerStacks++;return w(s,a,l,!1,m,E,P?Error("react-stack-top-frame"):Z,P?L(n(s)):Q)},O.jsxs=function(s,a,l,m,E){var P=1e4>A.recentlyCreatedOwnerStacks++;return w(s,a,l,!0,m,E,P?Error("react-stack-top-frame"):Z,P?L(n(s)):Q)}}(),O}ne.exports=le();var K=ne.exports;function ue(r){return r.filter(t=>{var e;return t.finishReason==="stop"?t.text!==null&&((e=t.text)==null?void 0:e.trim())!=="":!0})}function de(r){const t=[];let e=null;for(const n of r)n.type==="reasoning"?(e!=null&&(t.push(e),e=null),t.push(n)):n.functionCalls?(e&&t.push(e),t.push(n),e=null):n.functionResponse?t[t.length-1]={...t[t.length-1],functionResponse:n.functionResponse}:e&&n.protocol===e.protocol&&(e.role===n.role||n.finishReason==="stop")?e.text+=n.text:(e&&t.push(e),e={...n});return e&&t.push(e),ue(t)}function he(r){var t;return r.role==="function"?{id:r.id,role:"assistant",status:(r==null?void 0:r.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((t=r.functionCalls)==null?void 0:t.map(e=>{var n;return{type:"tool-call",toolName:e.name,toolCallId:e.id,args:e.args,result:(n=r.functionResponse)==null?void 0:n.result}}))??[]}:{id:r.id,role:r.role,content:r.type==="reasoning"?[{type:"reasoning",text:r.text}]:[{type:"text",text:r.text}]}}class M{constructor(){i(this,"statusChangeCallbacks",[]);i(this,"messageCallbacks",[])}addStatusChangeListener(t){this.statusChangeCallbacks.push(t)}addMessageListener(t){this.messageCallbacks.push(t)}async syncSession(t){this.session=t}async notifyMessage(t){this.messageCallbacks.forEach(e=>e(t))}async notifyMessages(t){t.forEach(e=>{this.messageCallbacks.forEach(n=>n(e))})}async setSession(t){this.session=t}async setStatus(t){const e=this.status!==t;this.status=t,e&&this.statusChangeCallbacks.forEach(n=>n(t))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class q extends M{constructor(e){super();i(this,"status");i(this,"autostart");i(this,"session");i(this,"config");i(this,"notify",!0);this.config=e,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(e){return this.setStatus("connected"),e}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(e){this.session=e}async send(e){const{apiUrl:n,apiKey:o,agentId:c}=this.config,d=this.session??"new",b=e,f=await(await fetch(`${n}/agents/${c}/sessions/${d}/messages`,{body:JSON.stringify({userMessage:b}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":o,"x-persona-apikey":o}})).json();this.notifyMessages(f.response.messages)}}class J extends M{constructor(e){super();i(this,"status");i(this,"autostart");i(this,"session");i(this,"config");i(this,"webSocket");this.config=e,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(e){var n;(n=this.config.logger)==null||n.debug("Syncing session with WebSocket protocol:",e),this.session=e,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(e))}connect(e){var b;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const n=e||this.session||"new";(b=this.config.logger)==null||b.debug("Connecting to WebSocket with sessionId:",n);const o=encodeURIComponent(this.config.apiKey),c=this.config.agentId,d=`${this.config.webSocketUrl}?sessionCode=${n}&agentId=${c}&apiKey=${o}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(d),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",h=>{const f=JSON.parse(h.data);if(f.type!=="message")return;const w=f.payload;this.notifyMessage(w!=null&&w.thought?{role:"assistant",type:"reasoning",text:w.thought}:w)}),this.webSocket.addEventListener("close",()=>{var h;this.setStatus("disconnected"),this.webSocket=null,(h=this.config.logger)==null||h.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",h=>{var f;this.setStatus("disconnected"),this.webSocket=null,(f=this.config.logger)==null||f.error("WebSocket error",h)}),Promise.resolve(n)}disconnect(){var e;return(e=this.config.logger)==null||e.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(e){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:e})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class fe{constructor(t){i(this,"config");i(this,"pc",null);i(this,"ws",null);i(this,"localStream",null);i(this,"remoteStream",new MediaStream);i(this,"audioCtx",null);i(this,"localAnalyser",null);i(this,"remoteAnalyser",null);i(this,"analyzerFrame",null);i(this,"dataChannel",null);i(this,"isConnected",!1);i(this,"visualizerCallbacks",[]);i(this,"messageCallbacks",[]);this.config=t}async connect(t){var e;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){(e=this.config.logger)==null||e.error("Error accessing microphone:",n);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(n=>{this.pc.addTrack(n,this.localStream)}),this.pc.ontrack=n=>{n.streams[0].getTracks().forEach(c=>{this.remoteStream.addTrack(c)}),this.audioCtx||this._startAnalyzers();const o=new Audio;o.srcObject=this.remoteStream,o.play().catch(c=>{var d;(d=this.config.logger)==null||d.error("Error playing remote audio:",c)})},this.pc.onicecandidate=n=>{var o;n.candidate&&((o=this.ws)==null?void 0:o.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:n.candidate}}))},this.pc.ondatachannel=n=>{const o=n.channel;o.onmessage=c=>{this.messageCallbacks.forEach(d=>{d(c)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var d,b;const n=await this.pc.createOffer();await this.pc.setLocalDescription(n);const o={agentId:this.config.agentId,sessionCode:t};(d=this.config.logger)==null||d.debug("Opening connection to WebRTC server: ",o);const c={type:"OFFER",src:((b=crypto.randomUUID)==null?void 0:b.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:n.sdp,type:n.type},connectionId:(Date.now()%1e6).toString(),metadata:o}};this.ws.send(JSON.stringify(c))},this.ws.onmessage=async n=>{var c;const o=JSON.parse(n.data);if(o.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(o.payload.sdp));else if(o.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(o.payload.candidate))}catch(d){(c=this.config.logger)==null||c.error("Error adding ICE candidate:",d)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var t;this.isConnected&&(this.isConnected=!1,((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(e=>e.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(t){this.visualizerCallbacks.push(t)}addMessageCallback(t){this.messageCallbacks.push(t)}createDataChannel(t="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(t),this.dataChannel.onopen=()=>{var e;return(e=this.config.logger)==null?void 0:e.info("Data channel opened")},this.dataChannel.onmessage=e=>{this.messageCallbacks.forEach(n=>{n(e)})})}sendMessage(t){var e,n;if(!this.dataChannel){(e=this.config.logger)==null||e.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(t),(n=this.config.logger)==null||n.info("Sent message:",t)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const t=this.audioCtx.createMediaStreamSource(this.localStream),e=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,t.connect(this.localAnalyser),e.connect(this.remoteAnalyser);const n=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const o=new Uint8Array(this.localAnalyser.frequencyBinCount),c=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(o),this.remoteAnalyser.getByteFrequencyData(c);const d=o.reduce((h,f)=>h+f,0)/o.length,b=c.reduce((h,f)=>h+f,0)/c.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(h=>{h({localAmplitude:d,remoteAmplitude:b})}),this.analyzerFrame=requestAnimationFrame(n)};this.analyzerFrame=requestAnimationFrame(n)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class B extends M{constructor(e){super();i(this,"status");i(this,"session");i(this,"autostart");i(this,"config");i(this,"webRTCClient");this.config=e,this.status="disconnected",this.session=null,this.autostart=(e==null?void 0:e.autostart)??!1,this.webRTCClient=new fe(e),this.webRTCClient.addMessageCallback(n=>{var c;(c=e.logger)==null||c.debug("Received data message:",n.data);const o=JSON.parse(n.data);o.type==="message"&&this.notifyMessage(o.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(e){super.syncSession(e),this.status==="connected"&&(await this.disconnect(),await this.connect(e))}async connect(e){var n;return this.status==="connected"?Promise.resolve(this.session):(this.session=e||this.session||"new",this.setStatus("connecting"),(n=this.config.logger)==null||n.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var e,n,o;if(this.status==="disconnected")return(e=this.config.logger)==null||e.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(o=(n=this.config)==null?void 0:n.logger)==null||o.debug("Disconnected from WebRTC")}send(e){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(e),Promise.resolve())}}const V=y.createContext(void 0);function me({dev:r=!1,protocols:t,logger:e,children:n,session:o="new",...c}){const[d,b]=y.useState(!1),[h,f]=y.useState([]),[w,N]=y.useState(o),[R,_]=y.useState(new Map),I=y.useRef(!1),k=y.useMemo(()=>{if(Array.isArray(t))return t;if(typeof t=="object"&&t!==null){const u=r?"localhost:8000":"persona.applica.guru/api",S=r?"http":"https",C=r?"ws":"wss";return Object.keys(t).map(p=>{switch(p){case"rest":const v=t[p];return v===!0?new q({apiUrl:`${S}://${u}`,apiKey:c.apiKey,agentId:c.agentId,logger:e}):new q(v);case"webrtc":const j=t[p];return j===!0?new B({webrtcUrl:`${C}://${u}/webrtc`,apiKey:c.apiKey,agentId:c.agentId,logger:e}):new B(j);case"websocket":const A=t[p];return A===!0?new J({webSocketUrl:`${C}://${u}/websocket`,apiKey:c.apiKey,agentId:c.agentId,logger:e}):new J(A);default:throw new Error(`Unknown protocol: ${p}`)}})}throw new Error("Invalid protocols configuration")},[]);y.useEffect(()=>{I.current||(I.current=!0,e==null||e.debug("Initializing protocols: ",k.map(u=>u.getName())),k.forEach(u=>{u.setSession(w),u.clearListeners(),u.addStatusChangeListener(S=>{e==null||e.debug(`${u.getName()} has notified new status: ${S}`),R.set(u.getName(),S),_(new Map(R))}),u.addMessageListener(S=>{f(C=>de([...C,{...S,protocol:u.getName()}]))}),u.autostart&&u.status==="disconnected"&&(e==null||e.debug(`Connecting to protocol: ${u.getName()}`),u.connect(w))}))},[w,k,e,R]);const $=async u=>{var x;if(((x=u.content[0])==null?void 0:x.type)!=="text")throw new Error("Only text messages are supported");const S=u.content[0].text;f(p=>[...p,{role:"user",type:"text",text:S}]),b(!0);const C=k.sort((p,v)=>v.getPriority()-p.getPriority()).find(p=>p.status==="connected");await(C==null?void 0:C.send(S)),b(!1)},W=y.useCallback(()=>(b(!1),f([]),N("new"),Promise.resolve()),[]),D=y.useCallback(()=>Promise.resolve(),[]),z=te.useExternalStoreRuntime({isRunning:d,messages:h,convertMessage:he,onNew:$,onCancel:W,onReload:D});return K.jsx(V.Provider,{value:{protocols:k,protocolsStatus:R},children:K.jsx(te.AssistantRuntimeProvider,{runtime:z,children:n})})}function ge({children:r,...t}){return K.jsx(me,{...t,children:r})}function be(){const r=y.useContext(V);if(!r)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return r}function re(r){const t=y.useContext(V);if(!t)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const e=t.protocols.find(o=>o.getName()===r);if(!e)return null;const n=t.protocolsStatus.get(e.getName());return{...e,connect:e.connect.bind(e),disconnect:e.disconnect.bind(e),send:e.send.bind(e),setSession:e.setSession.bind(e),addStatusChangeListener:e.addStatusChangeListener.bind(e),addMessageListener:e.addMessageListener.bind(e),getName:e.getName.bind(e),getPriority:e.getPriority.bind(e),status:n||e.status}}function pe(){return re("webrtc")}class ye{constructor(){i(this,"prefix","[Persona]")}log(t,...e){console.log(`${this.prefix} - ${t}`,...e)}info(t,...e){console.info(`${this.prefix} - ${t}`,...e)}warn(t,...e){console.warn(`${this.prefix} - ${t}`,...e)}error(t,...e){console.error(`${this.prefix} - ${t}`,...e)}debug(t,...e){console.debug(`${this.prefix} - ${t}`,...e)}}exports.PersonaConsoleLogger=ye;exports.PersonaProtocolBase=M;exports.PersonaRESTProtocol=q;exports.PersonaRuntimeProvider=ge;exports.PersonaWebRTCProtocol=B;exports.PersonaWebSocketProtocol=J;exports.usePersonaRuntime=be;exports.usePersonaRuntimeProtocol=re;exports.usePersonaRuntimeWebRTCProtocol=pe;
1
+ "use strict";var es=Object.defineProperty;var ts=(t,e,s)=>e in t?es(t,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[e]=s;var h=(t,e,s)=>ts(t,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P=require("react/jsx-runtime"),v=require("react");var S;(function(t){t.assertEqual=n=>n;function e(n){}t.assertIs=e;function s(n){throw new Error}t.assertNever=s,t.arrayToEnum=n=>{const i={};for(const a of n)i[a]=a;return i},t.getValidEnumValues=n=>{const i=t.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(const o of i)a[o]=n[o];return t.objectValues(a)},t.objectValues=n=>t.objectKeys(n).map(function(i){return n[i]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const i=[];for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&i.push(a);return i},t.find=(n,i)=>{for(const a of n)if(i(a))return a},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function r(n,i=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(n,i)=>typeof i=="bigint"?i.toString():i})(S||(S={}));var Qe;(function(t){t.mergeShapes=(e,s)=>({...e,...s})})(Qe||(Qe={}));const g=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),U=t=>{switch(typeof t){case"undefined":return g.undefined;case"string":return g.string;case"number":return isNaN(t)?g.nan:g.number;case"boolean":return g.boolean;case"function":return g.function;case"bigint":return g.bigint;case"symbol":return g.symbol;case"object":return Array.isArray(t)?g.array:t===null?g.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?g.promise:typeof Map<"u"&&t instanceof Map?g.map:typeof Set<"u"&&t instanceof Set?g.set:typeof Date<"u"&&t instanceof Date?g.date:g.object;default:return g.unknown}},l=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ss=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class R extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const s=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,s):this.__proto__=s,this.name="ZodError",this.issues=e}format(e){const s=e||function(i){return i.message},r={_errors:[]},n=i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)r._errors.push(s(a));else{let o=r,d=0;for(;d<a.path.length;){const c=a.path[d];d===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(s(a))):o[c]=o[c]||{_errors:[]},o=o[c],d++}}};return n(this),r}static assert(e){if(!(e instanceof R))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=s=>s.message){const s={},r=[];for(const n of this.issues)n.path.length>0?(s[n.path[0]]=s[n.path[0]]||[],s[n.path[0]].push(e(n))):r.push(e(n));return{formErrors:r,fieldErrors:s}}get formErrors(){return this.flatten()}}R.create=t=>new R(t);const ae=(t,e)=>{let s;switch(t.code){case l.invalid_type:t.received===g.undefined?s="Required":s=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:s=`Invalid literal value, expected ${JSON.stringify(t.expected,S.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:s=`Unrecognized key(s) in object: ${S.joinValues(t.keys,", ")}`;break;case l.invalid_union:s="Invalid input";break;case l.invalid_union_discriminator:s=`Invalid discriminator value. Expected ${S.joinValues(t.options)}`;break;case l.invalid_enum_value:s=`Invalid enum value. Expected ${S.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:s="Invalid function arguments";break;case l.invalid_return_type:s="Invalid function return type";break;case l.invalid_date:s="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(s=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(s=`${s} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?s=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?s=`Invalid input: must end with "${t.validation.endsWith}"`:S.assertNever(t.validation):t.validation!=="regex"?s=`Invalid ${t.validation}`:s="Invalid";break;case l.too_small:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:s="Invalid input";break;case l.too_big:t.type==="array"?s=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?s=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?s=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?s=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?s=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:s="Invalid input";break;case l.custom:s="Invalid input";break;case l.invalid_intersection_types:s="Intersection results could not be merged";break;case l.not_multiple_of:s=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:s="Number must be finite";break;default:s=e.defaultError,S.assertNever(t)}return{message:s}};let Tt=ae;function rs(t){Tt=t}function De(){return Tt}const Le=t=>{const{data:e,path:s,errorMaps:r,issueData:n}=t,i=[...s,...n.path||[]],a={...n,path:i};if(n.message!==void 0)return{...n,path:i,message:n.message};let o="";const d=r.filter(c=>!!c).slice().reverse();for(const c of d)o=c(a,{data:e,defaultError:o}).message;return{...n,path:i,message:o}},ns=[];function f(t,e){const s=De(),r=Le({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,s,s===ae?void 0:ae].filter(n=>!!n)});t.common.issues.push(r)}class E{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,s){const r=[];for(const n of s){if(n.status==="aborted")return b;n.status==="dirty"&&e.dirty(),r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,s){const r=[];for(const n of s){const i=await n.key,a=await n.value;r.push({key:i,value:a})}return E.mergeObjectSync(e,r)}static mergeObjectSync(e,s){const r={};for(const n of s){const{key:i,value:a}=n;if(i.status==="aborted"||a.status==="aborted")return b;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}}const b=Object.freeze({status:"aborted"}),re=t=>({status:"dirty",value:t}),I=t=>({status:"valid",value:t}),et=t=>t.status==="aborted",tt=t=>t.status==="dirty",Q=t=>t.status==="valid",fe=t=>typeof Promise<"u"&&t instanceof Promise;function $e(t,e,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function kt(t,e,s,r,n){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,s),s}var m;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(m||(m={}));var he,le;class L{constructor(e,s,r,n){this._cachedPath=[],this.parent=e,this.data=s,this._path=r,this._key=n}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const lt=(t,e)=>{if(Q(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const s=new R(t.common.issues);return this._error=s,this._error}}};function y(t){if(!t)return{};const{errorMap:e,invalid_type_error:s,required_error:r,description:n}=t;if(e&&(s||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(a,o)=>{var d,c;const{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:(d=u??r)!==null&&d!==void 0?d:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(c=u??s)!==null&&c!==void 0?c:o.defaultError}},description:n}}class w{get description(){return this._def.description}_getType(e){return U(e.data)}_getOrReturnCtx(e,s){return s||{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new E,ctx:{common:e.parent.common,data:e.data,parsedType:U(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const s=this._parse(e);if(fe(s))throw new Error("Synchronous parse encountered promise.");return s}_parseAsync(e){const s=this._parse(e);return Promise.resolve(s)}parse(e,s){const r=this.safeParse(e,s);if(r.success)return r.data;throw r.error}safeParse(e,s){var r;const n={common:{issues:[],async:(r=s==null?void 0:s.async)!==null&&r!==void 0?r:!1,contextualErrorMap:s==null?void 0:s.errorMap},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},i=this._parseSync({data:e,path:n.path,parent:n});return lt(n,i)}"~validate"(e){var s,r;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:n});return Q(i)?{value:i.value}:{issues:n.common.issues}}catch(i){!((r=(s=i==null?void 0:i.message)===null||s===void 0?void 0:s.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(i=>Q(i)?{value:i.value}:{issues:n.common.issues})}async parseAsync(e,s){const r=await this.safeParseAsync(e,s);if(r.success)return r.data;throw r.error}async safeParseAsync(e,s){const r={common:{issues:[],contextualErrorMap:s==null?void 0:s.errorMap,async:!0},path:(s==null?void 0:s.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:U(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(fe(n)?n:Promise.resolve(n));return lt(r,i)}refine(e,s){const r=n=>typeof s=="string"||typeof s>"u"?{message:s}:typeof s=="function"?s(n):s;return this._refinement((n,i)=>{const a=e(n),o=()=>i.addIssue({code:l.custom,...r(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(d=>d?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,s){return this._refinement((r,n)=>e(r)?!0:(n.addIssue(typeof s=="function"?s(r,n):s),!1))}_refinement(e){return new j({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s=>this["~validate"](s)}}optional(){return D.create(this,this._def)}nullable(){return K.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return B.create(this)}promise(){return ce.create(this,this._def)}or(e){return _e.create([this,e],this._def)}and(e){return be.create(this,e,this._def)}transform(e){return new j({...y(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const s=typeof e=="function"?e:()=>e;return new xe({...y(this._def),innerType:this,defaultValue:s,typeName:_.ZodDefault})}brand(){return new at({typeName:_.ZodBranded,type:this,...y(this._def)})}catch(e){const s=typeof e=="function"?e:()=>e;return new Te({...y(this._def),innerType:this,catchValue:s,typeName:_.ZodCatch})}describe(e){const s=this.constructor;return new s({...this._def,description:e})}pipe(e){return Ae.create(this,e)}readonly(){return ke.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const is=/^c[^\s-]{8,}$/i,as=/^[0-9a-z]+$/,os=/^[0-9A-HJKMNP-TV-Z]{26}$/i,cs=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ds=/^[a-z0-9_-]{21}$/i,us=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hs=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,ls=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fs="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xe;const ps=/^(?:(?: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])$/,gs=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ms=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,_s=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bs=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ys=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ct="((\\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])))",vs=new RegExp(`^${Ct}$`);function Et(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function ws(t){return new RegExp(`^${Et(t)}$`)}function It(t){let e=`${Ct}T${Et(t)}`;const s=[];return s.push(t.local?"Z?":"Z"),t.offset&&s.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${s.join("|")})`,new RegExp(`^${e}$`)}function Ss(t,e){return!!((e==="v4"||!e)&&ps.test(t)||(e==="v6"||!e)&&ms.test(t))}function xs(t,e){if(!us.test(t))return!1;try{const[s]=t.split("."),r=s.replace(/-/g,"+").replace(/_/g,"/").padEnd(s.length+(4-s.length%4)%4,"="),n=JSON.parse(atob(r));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Ts(t,e){return!!((e==="v4"||!e)&&gs.test(t)||(e==="v6"||!e)&&_s.test(t))}class O extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==g.string){const i=this._getOrReturnCtx(e);return f(i,{code:l.invalid_type,expected:g.string,received:i.parsedType}),b}const r=new E;let n;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(n=this._getOrReturnCtx(e,n),a?f(n,{code:l.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&f(n,{code:l.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")ls.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"email",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Xe||(Xe=new RegExp(fs,"u")),Xe.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"emoji",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")cs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"uuid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")ds.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"nanoid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")is.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")as.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cuid2",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")os.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ulid",code:l.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),f(n,{validation:"url",code:l.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"regex",code:l.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?It(i).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?vs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?ws(i).test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?hs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"duration",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?Ss(e.data,i.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"ip",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?xs(e.data,i.alg)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"jwt",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?Ts(e.data,i.version)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"cidr",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?bs.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64",code:l.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?ys.test(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{validation:"base64url",code:l.invalid_string,message:i.message}),r.dirty()):S.assertNever(i);return{status:r.value,value:e.data}}_regex(e,s,r){return this.refinement(n=>e.test(n),{validation:s,code:l.invalid_string,...m.errToObj(r)})}_addCheck(e){return new O({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){var s,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(s=e==null?void 0:e.offset)!==null&&s!==void 0?s:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...m.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...m.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,s){return this._addCheck({kind:"regex",regex:e,...m.errToObj(s)})}includes(e,s){return this._addCheck({kind:"includes",value:e,position:s==null?void 0:s.position,...m.errToObj(s==null?void 0:s.message)})}startsWith(e,s){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(s)})}endsWith(e,s){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(s)})}min(e,s){return this._addCheck({kind:"min",value:e,...m.errToObj(s)})}max(e,s){return this._addCheck({kind:"max",value:e,...m.errToObj(s)})}length(e,s){return this._addCheck({kind:"length",value:e,...m.errToObj(s)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new O({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new O({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new O({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxLength(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}O.create=t=>{var e;return new O({checks:[],typeName:_.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...y(t)})};function ks(t,e){const s=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,n=s>r?s:r,i=parseInt(t.toFixed(n).replace(".","")),a=parseInt(e.toFixed(n).replace(".",""));return i%a/Math.pow(10,n)}class Y extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==g.number){const i=this._getOrReturnCtx(e);return f(i,{code:l.invalid_type,expected:g.number,received:i.parsedType}),b}let r;const n=new E;for(const i of this._def.checks)i.kind==="int"?S.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:l.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()):i.kind==="multipleOf"?ks(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),f(r,{code:l.not_finite,message:i.message}),n.dirty()):S.assertNever(i);return{status:n.value,value:e.data}}gte(e,s){return this.setLimit("min",e,!0,m.toString(s))}gt(e,s){return this.setLimit("min",e,!1,m.toString(s))}lte(e,s){return this.setLimit("max",e,!0,m.toString(s))}lt(e,s){return this.setLimit("max",e,!1,m.toString(s))}setLimit(e,s,r,n){return new Y({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new Y({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(s)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,s=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(s===null||r.value>s)&&(s=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(s)&&Number.isFinite(e)}}Y.create=t=>new Y({checks:[],typeName:_.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...y(t)});class q extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==g.bigint)return this._getInvalidInput(e);let r;const n=new E;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),f(r,{code:l.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()):S.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:g.bigint,received:s.parsedType}),b}gte(e,s){return this.setLimit("min",e,!0,m.toString(s))}gt(e,s){return this.setLimit("min",e,!1,m.toString(s))}lte(e,s){return this.setLimit("max",e,!0,m.toString(s))}lt(e,s){return this.setLimit("max",e,!1,m.toString(s))}setLimit(e,s,r,n){return new q({...this._def,checks:[...this._def.checks,{kind:e,value:s,inclusive:r,message:m.toString(n)}]})}_addCheck(e){return new q({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,s){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(s)})}get minValue(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e}get maxValue(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e}}q.create=t=>{var e;return new q({checks:[],typeName:_.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...y(t)})};class pe extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==g.boolean){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.boolean,received:r.parsedType}),b}return I(e.data)}}pe.create=t=>new pe({typeName:_.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...y(t)});class ee extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==g.date){const i=this._getOrReturnCtx(e);return f(i,{code:l.invalid_type,expected:g.date,received:i.parsedType}),b}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return f(i,{code:l.invalid_date}),b}const r=new E;let n;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):S.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ee({...this._def,checks:[...this._def.checks,e]})}min(e,s){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(s)})}max(e,s){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(s)})}get minDate(){let e=null;for(const s of this._def.checks)s.kind==="min"&&(e===null||s.value>e)&&(e=s.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const s of this._def.checks)s.kind==="max"&&(e===null||s.value<e)&&(e=s.value);return e!=null?new Date(e):null}}ee.create=t=>new ee({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:_.ZodDate,...y(t)});class ze extends w{_parse(e){if(this._getType(e)!==g.symbol){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.symbol,received:r.parsedType}),b}return I(e.data)}}ze.create=t=>new ze({typeName:_.ZodSymbol,...y(t)});class ge extends w{_parse(e){if(this._getType(e)!==g.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.undefined,received:r.parsedType}),b}return I(e.data)}}ge.create=t=>new ge({typeName:_.ZodUndefined,...y(t)});class me extends w{_parse(e){if(this._getType(e)!==g.null){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.null,received:r.parsedType}),b}return I(e.data)}}me.create=t=>new me({typeName:_.ZodNull,...y(t)});class oe extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return I(e.data)}}oe.create=t=>new oe({typeName:_.ZodAny,...y(t)});class X extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return I(e.data)}}X.create=t=>new X({typeName:_.ZodUnknown,...y(t)});class V extends w{_parse(e){const s=this._getOrReturnCtx(e);return f(s,{code:l.invalid_type,expected:g.never,received:s.parsedType}),b}}V.create=t=>new V({typeName:_.ZodNever,...y(t)});class Fe extends w{_parse(e){if(this._getType(e)!==g.undefined){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.void,received:r.parsedType}),b}return I(e.data)}}Fe.create=t=>new Fe({typeName:_.ZodVoid,...y(t)});class B extends w{_parse(e){const{ctx:s,status:r}=this._processInputParams(e),n=this._def;if(s.parsedType!==g.array)return f(s,{code:l.invalid_type,expected:g.array,received:s.parsedType}),b;if(n.exactLength!==null){const a=s.data.length>n.exactLength.value,o=s.data.length<n.exactLength.value;(a||o)&&(f(s,{code:a?l.too_big:l.too_small,minimum:o?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty())}if(n.minLength!==null&&s.data.length<n.minLength.value&&(f(s,{code:l.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()),n.maxLength!==null&&s.data.length>n.maxLength.value&&(f(s,{code:l.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()),s.common.async)return Promise.all([...s.data].map((a,o)=>n.type._parseAsync(new L(s,a,s.path,o)))).then(a=>E.mergeArray(r,a));const i=[...s.data].map((a,o)=>n.type._parseSync(new L(s,a,s.path,o)));return E.mergeArray(r,i)}get element(){return this._def.type}min(e,s){return new B({...this._def,minLength:{value:e,message:m.toString(s)}})}max(e,s){return new B({...this._def,maxLength:{value:e,message:m.toString(s)}})}length(e,s){return new B({...this._def,exactLength:{value:e,message:m.toString(s)}})}nonempty(e){return this.min(1,e)}}B.create=(t,e)=>new B({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...y(e)});function se(t){if(t instanceof T){const e={};for(const s in t.shape){const r=t.shape[s];e[s]=D.create(se(r))}return new T({...t._def,shape:()=>e})}else return t instanceof B?new B({...t._def,type:se(t.element)}):t instanceof D?D.create(se(t.unwrap())):t instanceof K?K.create(se(t.unwrap())):t instanceof $?$.create(t.items.map(e=>se(e))):t}class T extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),s=S.objectKeys(e);return this._cached={shape:e,keys:s}}_parse(e){if(this._getType(e)!==g.object){const c=this._getOrReturnCtx(e);return f(c,{code:l.invalid_type,expected:g.object,received:c.parsedType}),b}const{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof V&&this._def.unknownKeys==="strip"))for(const c in n.data)a.includes(c)||o.push(c);const d=[];for(const c of a){const u=i[c],p=n.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new L(n,p,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof V){const c=this._def.unknownKeys;if(c==="passthrough")for(const u of o)d.push({key:{status:"valid",value:u},value:{status:"valid",value:n.data[u]}});else if(c==="strict")o.length>0&&(f(n,{code:l.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const u of o){const p=n.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new L(n,p,n.path,u)),alwaysSet:u in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const u of d){const p=await u.key,x=await u.value;c.push({key:p,value:x,alwaysSet:u.alwaysSet})}return c}).then(c=>E.mergeObjectSync(r,c)):E.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new T({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(s,r)=>{var n,i,a,o;const d=(a=(i=(n=this._def).errorMap)===null||i===void 0?void 0:i.call(n,s,r).message)!==null&&a!==void 0?a:r.defaultError;return s.code==="unrecognized_keys"?{message:(o=m.errToObj(e).message)!==null&&o!==void 0?o:d}:{message:d}}}:{}})}strip(){return new T({...this._def,unknownKeys:"strip"})}passthrough(){return new T({...this._def,unknownKeys:"passthrough"})}extend(e){return new T({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new T({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,s){return this.augment({[e]:s})}catchall(e){return new T({...this._def,catchall:e})}pick(e){const s={};return S.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(s[r]=this.shape[r])}),new T({...this._def,shape:()=>s})}omit(e){const s={};return S.objectKeys(this.shape).forEach(r=>{e[r]||(s[r]=this.shape[r])}),new T({...this._def,shape:()=>s})}deepPartial(){return se(this)}partial(e){const s={};return S.objectKeys(this.shape).forEach(r=>{const n=this.shape[r];e&&!e[r]?s[r]=n:s[r]=n.optional()}),new T({...this._def,shape:()=>s})}required(e){const s={};return S.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])s[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof D;)i=i._def.innerType;s[r]=i}}),new T({...this._def,shape:()=>s})}keyof(){return At(S.objectKeys(this.shape))}}T.create=(t,e)=>new T({shape:()=>t,unknownKeys:"strip",catchall:V.create(),typeName:_.ZodObject,...y(e)});T.strictCreate=(t,e)=>new T({shape:()=>t,unknownKeys:"strict",catchall:V.create(),typeName:_.ZodObject,...y(e)});T.lazycreate=(t,e)=>new T({shape:t,unknownKeys:"strip",catchall:V.create(),typeName:_.ZodObject,...y(e)});class _e extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r=this._def.options;function n(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return s.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new R(o.ctx.common.issues));return f(s,{code:l.invalid_union,unionErrors:a}),b}if(s.common.async)return Promise.all(r.map(async i=>{const a={...s,common:{...s.common,issues:[]},parent:null};return{result:await i._parseAsync({data:s.data,path:s.path,parent:a}),ctx:a}})).then(n);{let i;const a=[];for(const d of r){const c={...s,common:{...s.common,issues:[]},parent:null},u=d._parseSync({data:s.data,path:s.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!i&&(i={result:u,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(i)return s.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(d=>new R(d));return f(s,{code:l.invalid_union,unionErrors:o}),b}}get options(){return this._def.options}}_e.create=(t,e)=>new _e({options:t,typeName:_.ZodUnion,...y(e)});const F=t=>t instanceof ve?F(t.schema):t instanceof j?F(t.innerType()):t instanceof we?[t.value]:t instanceof H?t.options:t instanceof Se?S.objectValues(t.enum):t instanceof xe?F(t._def.innerType):t instanceof ge?[void 0]:t instanceof me?[null]:t instanceof D?[void 0,...F(t.unwrap())]:t instanceof K?[null,...F(t.unwrap())]:t instanceof at||t instanceof ke?F(t.unwrap()):t instanceof Te?F(t._def.innerType):[];class We extends w{_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==g.object)return f(s,{code:l.invalid_type,expected:g.object,received:s.parsedType}),b;const r=this.discriminator,n=s.data[r],i=this.optionsMap.get(n);return i?s.common.async?i._parseAsync({data:s.data,path:s.path,parent:s}):i._parseSync({data:s.data,path:s.path,parent:s}):(f(s,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,s,r){const n=new Map;for(const i of s){const a=F(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,i)}}return new We({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:s,optionsMap:n,...y(r)})}}function st(t,e){const s=U(t),r=U(e);if(t===e)return{valid:!0,data:t};if(s===g.object&&r===g.object){const n=S.objectKeys(e),i=S.objectKeys(t).filter(o=>n.indexOf(o)!==-1),a={...t,...e};for(const o of i){const d=st(t[o],e[o]);if(!d.valid)return{valid:!1};a[o]=d.data}return{valid:!0,data:a}}else if(s===g.array&&r===g.array){if(t.length!==e.length)return{valid:!1};const n=[];for(let i=0;i<t.length;i++){const a=t[i],o=e[i],d=st(a,o);if(!d.valid)return{valid:!1};n.push(d.data)}return{valid:!0,data:n}}else return s===g.date&&r===g.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}class be extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=(i,a)=>{if(et(i)||et(a))return b;const o=st(i.value,a.value);return o.valid?((tt(i)||tt(a))&&s.dirty(),{status:s.value,value:o.data}):(f(r,{code:l.invalid_intersection_types}),b)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>n(i,a)):n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}be.create=(t,e,s)=>new be({left:t,right:e,typeName:_.ZodIntersection,...y(s)});class $ extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.array)return f(r,{code:l.invalid_type,expected:g.array,received:r.parsedType}),b;if(r.data.length<this._def.items.length)return f(r,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),b;!this._def.rest&&r.data.length>this._def.items.length&&(f(r,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),s.dirty());const i=[...r.data].map((a,o)=>{const d=this._def.items[o]||this._def.rest;return d?d._parse(new L(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>E.mergeArray(s,a)):E.mergeArray(s,i)}get items(){return this._def.items}rest(e){return new $({...this._def,rest:e})}}$.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new $({items:t,typeName:_.ZodTuple,rest:null,...y(e)})};class ye extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.object)return f(r,{code:l.invalid_type,expected:g.object,received:r.parsedType}),b;const n=[],i=this._def.keyType,a=this._def.valueType;for(const o in r.data)n.push({key:i._parse(new L(r,o,r.path,o)),value:a._parse(new L(r,r.data[o],r.path,o)),alwaysSet:o in r.data});return r.common.async?E.mergeObjectAsync(s,n):E.mergeObjectSync(s,n)}get element(){return this._def.valueType}static create(e,s,r){return s instanceof w?new ye({keyType:e,valueType:s,typeName:_.ZodRecord,...y(r)}):new ye({keyType:O.create(),valueType:e,typeName:_.ZodRecord,...y(s)})}}class Ue extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.map)return f(r,{code:l.invalid_type,expected:g.map,received:r.parsedType}),b;const n=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([o,d],c)=>({key:n._parse(new L(r,o,r.path,[c,"key"])),value:i._parse(new L(r,d,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const d of a){const c=await d.key,u=await d.value;if(c.status==="aborted"||u.status==="aborted")return b;(c.status==="dirty"||u.status==="dirty")&&s.dirty(),o.set(c.value,u.value)}return{status:s.value,value:o}})}else{const o=new Map;for(const d of a){const c=d.key,u=d.value;if(c.status==="aborted"||u.status==="aborted")return b;(c.status==="dirty"||u.status==="dirty")&&s.dirty(),o.set(c.value,u.value)}return{status:s.value,value:o}}}}Ue.create=(t,e,s)=>new Ue({valueType:e,keyType:t,typeName:_.ZodMap,...y(s)});class te extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.parsedType!==g.set)return f(r,{code:l.invalid_type,expected:g.set,received:r.parsedType}),b;const n=this._def;n.minSize!==null&&r.data.size<n.minSize.value&&(f(r,{code:l.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),s.dirty()),n.maxSize!==null&&r.data.size>n.maxSize.value&&(f(r,{code:l.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),s.dirty());const i=this._def.valueType;function a(d){const c=new Set;for(const u of d){if(u.status==="aborted")return b;u.status==="dirty"&&s.dirty(),c.add(u.value)}return{status:s.value,value:c}}const o=[...r.data.values()].map((d,c)=>i._parse(new L(r,d,r.path,c)));return r.common.async?Promise.all(o).then(d=>a(d)):a(o)}min(e,s){return new te({...this._def,minSize:{value:e,message:m.toString(s)}})}max(e,s){return new te({...this._def,maxSize:{value:e,message:m.toString(s)}})}size(e,s){return this.min(e,s).max(e,s)}nonempty(e){return this.min(1,e)}}te.create=(t,e)=>new te({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...y(e)});class ie extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==g.function)return f(s,{code:l.invalid_type,expected:g.function,received:s.parsedType}),b;function r(o,d){return Le({data:o,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,De(),ae].filter(c=>!!c),issueData:{code:l.invalid_arguments,argumentsError:d}})}function n(o,d){return Le({data:o,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,De(),ae].filter(c=>!!c),issueData:{code:l.invalid_return_type,returnTypeError:d}})}const i={errorMap:s.common.contextualErrorMap},a=s.data;if(this._def.returns instanceof ce){const o=this;return I(async function(...d){const c=new R([]),u=await o._def.args.parseAsync(d,i).catch(C=>{throw c.addIssue(r(d,C)),c}),p=await Reflect.apply(a,this,u);return await o._def.returns._def.type.parseAsync(p,i).catch(C=>{throw c.addIssue(n(p,C)),c})})}else{const o=this;return I(function(...d){const c=o._def.args.safeParse(d,i);if(!c.success)throw new R([r(d,c.error)]);const u=Reflect.apply(a,this,c.data),p=o._def.returns.safeParse(u,i);if(!p.success)throw new R([n(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new ie({...this._def,args:$.create(e).rest(X.create())})}returns(e){return new ie({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,s,r){return new ie({args:e||$.create([]).rest(X.create()),returns:s||X.create(),typeName:_.ZodFunction,...y(r)})}}class ve extends w{get schema(){return this._def.getter()}_parse(e){const{ctx:s}=this._processInputParams(e);return this._def.getter()._parse({data:s.data,path:s.path,parent:s})}}ve.create=(t,e)=>new ve({getter:t,typeName:_.ZodLazy,...y(e)});class we extends w{_parse(e){if(e.data!==this._def.value){const s=this._getOrReturnCtx(e);return f(s,{received:s.data,code:l.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}}we.create=(t,e)=>new we({value:t,typeName:_.ZodLiteral,...y(e)});function At(t,e){return new H({values:t,typeName:_.ZodEnum,...y(e)})}class H extends w{constructor(){super(...arguments),he.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const s=this._getOrReturnCtx(e),r=this._def.values;return f(s,{expected:S.joinValues(r),received:s.parsedType,code:l.invalid_type}),b}if($e(this,he)||kt(this,he,new Set(this._def.values)),!$e(this,he).has(e.data)){const s=this._getOrReturnCtx(e),r=this._def.values;return f(s,{received:s.data,code:l.invalid_enum_value,options:r}),b}return I(e.data)}get options(){return this._def.values}get enum(){const e={};for(const s of this._def.values)e[s]=s;return e}get Values(){const e={};for(const s of this._def.values)e[s]=s;return e}get Enum(){const e={};for(const s of this._def.values)e[s]=s;return e}extract(e,s=this._def){return H.create(e,{...this._def,...s})}exclude(e,s=this._def){return H.create(this.options.filter(r=>!e.includes(r)),{...this._def,...s})}}he=new WeakMap;H.create=At;class Se extends w{constructor(){super(...arguments),le.set(this,void 0)}_parse(e){const s=S.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==g.string&&r.parsedType!==g.number){const n=S.objectValues(s);return f(r,{expected:S.joinValues(n),received:r.parsedType,code:l.invalid_type}),b}if($e(this,le)||kt(this,le,new Set(S.getValidEnumValues(this._def.values))),!$e(this,le).has(e.data)){const n=S.objectValues(s);return f(r,{received:r.data,code:l.invalid_enum_value,options:n}),b}return I(e.data)}get enum(){return this._def.values}}le=new WeakMap;Se.create=(t,e)=>new Se({values:t,typeName:_.ZodNativeEnum,...y(e)});class ce extends w{unwrap(){return this._def.type}_parse(e){const{ctx:s}=this._processInputParams(e);if(s.parsedType!==g.promise&&s.common.async===!1)return f(s,{code:l.invalid_type,expected:g.promise,received:s.parsedType}),b;const r=s.parsedType===g.promise?s.data:Promise.resolve(s.data);return I(r.then(n=>this._def.type.parseAsync(n,{path:s.path,errorMap:s.common.contextualErrorMap})))}}ce.create=(t,e)=>new ce({type:t,typeName:_.ZodPromise,...y(e)});class j extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:s,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:a=>{f(r,a),a.fatal?s.abort():s.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){const a=n.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async o=>{if(s.value==="aborted")return b;const d=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return d.status==="aborted"?b:d.status==="dirty"||s.value==="dirty"?re(d.value):d});{if(s.value==="aborted")return b;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?b:o.status==="dirty"||s.value==="dirty"?re(o.value):o}}if(n.type==="refinement"){const a=o=>{const d=n.refinement(o,i);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?b:(o.status==="dirty"&&s.dirty(),a(o.value),{status:s.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?b:(o.status==="dirty"&&s.dirty(),a(o.value).then(()=>({status:s.value,value:o.value}))))}if(n.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Q(a))return a;const o=n.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:s.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>Q(a)?Promise.resolve(n.transform(a.value,i)).then(o=>({status:s.value,value:o})):a);S.assertNever(n)}}j.create=(t,e,s)=>new j({schema:t,typeName:_.ZodEffects,effect:e,...y(s)});j.createWithPreprocess=(t,e,s)=>new j({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...y(s)});class D extends w{_parse(e){return this._getType(e)===g.undefined?I(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}D.create=(t,e)=>new D({innerType:t,typeName:_.ZodOptional,...y(e)});class K extends w{_parse(e){return this._getType(e)===g.null?I(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}K.create=(t,e)=>new K({innerType:t,typeName:_.ZodNullable,...y(e)});class xe extends w{_parse(e){const{ctx:s}=this._processInputParams(e);let r=s.data;return s.parsedType===g.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:s.path,parent:s})}removeDefault(){return this._def.innerType}}xe.create=(t,e)=>new xe({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...y(e)});class Te extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r={...s,common:{...s.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return fe(n)?n.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new R(r.common.issues)},input:r.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new R(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Te.create=(t,e)=>new Te({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...y(e)});class Ve extends w{_parse(e){if(this._getType(e)!==g.nan){const r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:g.nan,received:r.parsedType}),b}return{status:"valid",value:e.data}}}Ve.create=t=>new Ve({typeName:_.ZodNaN,...y(t)});const Cs=Symbol("zod_brand");class at extends w{_parse(e){const{ctx:s}=this._processInputParams(e),r=s.data;return this._def.type._parse({data:r,path:s.path,parent:s})}unwrap(){return this._def.type}}class Ae extends w{_parse(e){const{status:s,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?b:i.status==="dirty"?(s.dirty(),re(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return n.status==="aborted"?b:n.status==="dirty"?(s.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,s){return new Ae({in:e,out:s,typeName:_.ZodPipeline})}}class ke extends w{_parse(e){const s=this._def.innerType._parse(e),r=n=>(Q(n)&&(n.value=Object.freeze(n.value)),n);return fe(s)?s.then(n=>r(n)):r(s)}unwrap(){return this._def.innerType}}ke.create=(t,e)=>new ke({innerType:t,typeName:_.ZodReadonly,...y(e)});function ft(t,e){const s=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof s=="string"?{message:s}:s}function Rt(t,e={},s){return t?oe.create().superRefine((r,n)=>{var i,a;const o=t(r);if(o instanceof Promise)return o.then(d=>{var c,u;if(!d){const p=ft(e,r),x=(u=(c=p.fatal)!==null&&c!==void 0?c:s)!==null&&u!==void 0?u:!0;n.addIssue({code:"custom",...p,fatal:x})}});if(!o){const d=ft(e,r),c=(a=(i=d.fatal)!==null&&i!==void 0?i:s)!==null&&a!==void 0?a:!0;n.addIssue({code:"custom",...d,fatal:c})}}):oe.create()}const Es={object:T.lazycreate};var _;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));const Is=(t,e={message:`Input not instance of ${t.name}`})=>Rt(s=>s instanceof t,e),Mt=O.create,Ot=Y.create,As=Ve.create,Rs=q.create,Nt=pe.create,Ms=ee.create,Os=ze.create,Ns=ge.create,Ps=me.create,Bs=oe.create,js=X.create,Zs=V.create,Ds=Fe.create,Ls=B.create,$s=T.create,zs=T.strictCreate,Fs=_e.create,Us=We.create,Vs=be.create,Js=$.create,Ws=ye.create,Ys=Ue.create,qs=te.create,Hs=ie.create,Ks=ve.create,Gs=we.create,Xs=H.create,Qs=Se.create,er=ce.create,pt=j.create,tr=D.create,sr=K.create,rr=j.createWithPreprocess,nr=Ae.create,ir=()=>Mt().optional(),ar=()=>Ot().optional(),or=()=>Nt().optional(),cr={string:t=>O.create({...t,coerce:!0}),number:t=>Y.create({...t,coerce:!0}),boolean:t=>pe.create({...t,coerce:!0}),bigint:t=>q.create({...t,coerce:!0}),date:t=>ee.create({...t,coerce:!0})},dr=b;var A=Object.freeze({__proto__:null,defaultErrorMap:ae,setErrorMap:rs,getErrorMap:De,makeIssue:Le,EMPTY_PATH:ns,addIssueToContext:f,ParseStatus:E,INVALID:b,DIRTY:re,OK:I,isAborted:et,isDirty:tt,isValid:Q,isAsync:fe,get util(){return S},get objectUtil(){return Qe},ZodParsedType:g,getParsedType:U,ZodType:w,datetimeRegex:It,ZodString:O,ZodNumber:Y,ZodBigInt:q,ZodBoolean:pe,ZodDate:ee,ZodSymbol:ze,ZodUndefined:ge,ZodNull:me,ZodAny:oe,ZodUnknown:X,ZodNever:V,ZodVoid:Fe,ZodArray:B,ZodObject:T,ZodUnion:_e,ZodDiscriminatedUnion:We,ZodIntersection:be,ZodTuple:$,ZodRecord:ye,ZodMap:Ue,ZodSet:te,ZodFunction:ie,ZodLazy:ve,ZodLiteral:we,ZodEnum:H,ZodNativeEnum:Se,ZodPromise:ce,ZodEffects:j,ZodTransformer:j,ZodOptional:D,ZodNullable:K,ZodDefault:xe,ZodCatch:Te,ZodNaN:Ve,BRAND:Cs,ZodBranded:at,ZodPipeline:Ae,ZodReadonly:ke,custom:Rt,Schema:w,ZodSchema:w,late:Es,get ZodFirstPartyTypeKind(){return _},coerce:cr,any:Bs,array:Ls,bigint:Rs,boolean:Nt,date:Ms,discriminatedUnion:Us,effect:pt,enum:Xs,function:Hs,instanceof:Is,intersection:Vs,lazy:Ks,literal:Gs,map:Ys,nan:As,nativeEnum:Qs,never:Zs,null:Ps,nullable:sr,number:Ot,object:$s,oboolean:or,onumber:ar,optional:tr,ostring:ir,pipeline:nr,preprocess:rr,promise:er,record:Ws,set:qs,strictObject:zs,string:Mt,symbol:Os,transformer:pt,tuple:Js,undefined:Ns,union:Fs,unknown:js,void:Ds,NEVER:dr,ZodIssueCode:l,quotelessJson:ss,ZodError:R});A.object({maxTokens:A.number().int().positive().optional(),temperature:A.number().optional(),topP:A.number().optional(),presencePenalty:A.number().optional(),frequencyPenalty:A.number().optional(),seed:A.number().int().optional(),headers:A.record(A.string().optional()).optional()});A.object({apiKey:A.string().optional(),baseUrl:A.string().optional(),modelName:A.string().optional()});var ur=t=>Array.from(t).map(s=>s.getModelContext()).sort((s,r)=>(r.priority??0)-(s.priority??0)).reduce((s,r)=>{var n;if(r.system&&(s.system?s.system+=`
2
+
3
+ ${r.system}`:s.system=r.system),r.tools)for(const[i,a]of Object.entries(r.tools)){const o=(n=s.tools)==null?void 0:n[i];if(o&&o!==a)throw new Error(`You tried to define a tool with the name ${i}, but it already exists.`);s.tools||(s.tools={}),s.tools[i]=a}return r.config&&(s.config={...s.config,...r.config}),r.callSettings&&(s.callSettings={...s.callSettings,...r.callSettings}),s},{}),hr=class{constructor(){h(this,"_providers",new Set);h(this,"_subscribers",new Set)}getModelContext(){return ur(this._providers)}registerModelContextProvider(t){var s;this._providers.add(t);const e=(s=t.subscribe)==null?void 0:s.call(t,()=>{this.notifySubscribers()});return this.notifySubscribers(),()=>{this._providers.delete(t),e==null||e(),this.notifySubscribers()}}notifySubscribers(){for(const t of this._subscribers)t()}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}},lr=class{constructor(){h(this,"_contextProvider",new hr)}registerModelContextProvider(t){return this._contextProvider.registerModelContextProvider(t)}},fr=class{constructor(){h(this,"_subscribers",new Set)}subscribe(t){return this._subscribers.add(t),()=>this._subscribers.delete(t)}waitForUpdate(){return new Promise(t=>{const e=this.subscribe(()=>{e(),t()})})}_notifySubscribers(){const t=[];for(const e of this._subscribers)try{e()}catch(s){t.push(s)}if(t.length>0)throw t.length===1?t[0]:new AggregateError(t)}},pr=t=>t.status.type==="complete",Pt=class extends fr{constructor(){super(...arguments);h(this,"isEditing",!0);h(this,"_attachments",[]);h(this,"_text","");h(this,"_role","user");h(this,"_runConfig",{});h(this,"_eventSubscribers",new Map)}getAttachmentAccept(){var e;return((e=this.getAttachmentAdapter())==null?void 0:e.accept)??"*"}get attachments(){return this._attachments}setAttachments(e){this._attachments=e,this._notifySubscribers()}get isEmpty(){return!this.text.trim()&&!this.attachments.length}get text(){return this._text}get role(){return this._role}get runConfig(){return this._runConfig}setText(e){this._text!==e&&(this._text=e,this._notifySubscribers())}setRole(e){this._role!==e&&(this._role=e,this._notifySubscribers())}setRunConfig(e){this._runConfig!==e&&(this._runConfig=e,this._notifySubscribers())}_emptyTextAndAttachments(){this._attachments=[],this._text="",this._notifySubscribers()}async _onClearAttachments(){const e=this.getAttachmentAdapter();e&&await Promise.all(this._attachments.map(s=>e.remove(s)))}async reset(){if(this._attachments.length===0&&this._text===""&&this._role==="user"&&Object.keys(this._runConfig).length===0)return;this._role="user",this._runConfig={};const e=this._onClearAttachments();this._emptyTextAndAttachments(),await e}async clearAttachments(){const e=this._onClearAttachments();this.setAttachments([]),await e}async send(){const e=this.getAttachmentAdapter(),s=e&&this.attachments.length>0?await Promise.all(this.attachments.map(async n=>pr(n)?n:await e.send(n))):[],r={role:this.role,content:this.text?[{type:"text",text:this.text}]:[],attachments:s,runConfig:this.runConfig};this._emptyTextAndAttachments(),this.handleSend(r),this._notifyEventSubscribers("send")}cancel(){this.handleCancel()}async addAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=i=>{const a=this._attachments.findIndex(o=>o.id===i.id);a!==-1?this._attachments=[...this._attachments.slice(0,a),i,...this._attachments.slice(a+1)]:(this._attachments=[...this._attachments,i],this._notifyEventSubscribers("attachment_add")),this._notifySubscribers()},n=s.add({file:e});if(Symbol.asyncIterator in n)for await(const i of n)r(i);else r(await n);this._notifyEventSubscribers("attachment_add"),this._notifySubscribers()}async removeAttachment(e){const s=this.getAttachmentAdapter();if(!s)throw new Error("Attachments are not supported");const r=this._attachments.findIndex(i=>i.id===e);if(r===-1)throw new Error("Attachment not found");const n=this._attachments[r];await s.remove(n),this._attachments=[...this._attachments.slice(0,r),...this._attachments.slice(r+1)],this._notifySubscribers()}_notifyEventSubscribers(e){const s=this._eventSubscribers.get(e);if(s)for(const r of s)r()}unstable_on(e,s){const r=this._eventSubscribers.get(e);return r?r.add(s):this._eventSubscribers.set(e,new Set([s])),()=>{const n=this._eventSubscribers.get(e);n&&n.delete(s)}}},gr=class extends Pt{constructor(e){super();h(this,"_canCancel",!1);this.runtime=e,this.connect()}get canCancel(){return this._canCancel}get attachments(){return super.attachments}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}connect(){return this.runtime.subscribe(()=>{this.canCancel!==this.runtime.capabilities.cancel&&(this._canCancel=this.runtime.capabilities.cancel,this._notifySubscribers())})}async handleSend(e){var s;this.runtime.append({...e,parentId:((s=this.runtime.messages.at(-1))==null?void 0:s.id)??null,sourceId:null})}async handleCancel(){this.runtime.cancelRun()}};let mr=(t,e=21)=>(s=e)=>{let r="",n=s|0;for(;n--;)r+=t[Math.random()*t.length|0];return r};var Ce=mr("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7),_r="__optimistic__",br=()=>`${_r}${Ce()}`,yr=(t,{id:e=Ce(),status:s={type:"complete",reason:"unknown"},attachments:r=[]}={})=>{const n={id:e,createdAt:new Date},i=t.role;switch(i){case"assistant":return{...n,role:i,content:t.content.map(a=>a.type==="tool-call"?{...a,argsText:JSON.stringify(a.args)}:a),status:s,metadata:{unstable_annotations:[],unstable_data:[],steps:[],custom:{}}};case"user":return{...n,role:i,content:t.content,attachments:r,metadata:{custom:{}}};case"system":return{...n,role:i,content:t.content,metadata:{custom:{}}};default:{const a=i;throw new Error(`Unknown message role: ${a}`)}}},Bt=Object.freeze({type:"running"}),jt=Object.freeze({type:"complete",reason:"unknown"}),vr=t=>t===Bt||t===jt,Zt=(t,e)=>t&&e?Bt:jt;function wr(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ue={exports:{}};const Sr=typeof Buffer<"u",gt=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,mt=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function Dt(t,e,s){s==null&&e!==null&&typeof e=="object"&&(s=e,e=void 0),Sr&&Buffer.isBuffer(t)&&(t=t.toString()),t&&t.charCodeAt(0)===65279&&(t=t.slice(1));const r=JSON.parse(t,e);if(r===null||typeof r!="object")return r;const n=s&&s.protoAction||"error",i=s&&s.constructorAction||"error";if(n==="ignore"&&i==="ignore")return r;if(n!=="ignore"&&i!=="ignore"){if(gt.test(t)===!1&&mt.test(t)===!1)return r}else if(n!=="ignore"&&i==="ignore"){if(gt.test(t)===!1)return r}else if(mt.test(t)===!1)return r;return Lt(r,{protoAction:n,constructorAction:i,safe:s&&s.safe})}function Lt(t,{protoAction:e="error",constructorAction:s="error",safe:r}={}){let n=[t];for(;n.length;){const i=n;n=[];for(const a of i){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"__proto__")){if(r===!0)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.__proto__}if(s!=="ignore"&&Object.prototype.hasOwnProperty.call(a,"constructor")&&Object.prototype.hasOwnProperty.call(a.constructor,"prototype")){if(r===!0)return null;if(s==="error")throw new SyntaxError("Object contains forbidden prototype property");delete a.constructor}for(const o in a){const d=a[o];d&&typeof d=="object"&&n.push(d)}}}return t}function ot(t,e,s){const{stackTraceLimit:r}=Error;Error.stackTraceLimit=0;try{return Dt(t,e,s)}finally{Error.stackTraceLimit=r}}function xr(t,e){const{stackTraceLimit:s}=Error;Error.stackTraceLimit=0;try{return Dt(t,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=s}}ue.exports=ot;ue.exports.default=ot;ue.exports.parse=ot;ue.exports.safeParse=xr;ue.exports.scan=Lt;var Tr=ue.exports;const _t=wr(Tr);function kr(t){const e=["ROOT"];let s=-1,r=null;function n(c,u,p){switch(c){case'"':{s=u,e.pop(),e.push(p),e.push("INSIDE_STRING");break}case"f":case"t":case"n":{s=u,r=u,e.pop(),e.push(p),e.push("INSIDE_LITERAL");break}case"-":{e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=u,e.pop(),e.push(p),e.push("INSIDE_NUMBER");break}case"{":{s=u,e.pop(),e.push(p),e.push("INSIDE_OBJECT_START");break}case"[":{s=u,e.pop(),e.push(p),e.push("INSIDE_ARRAY_START");break}}}function i(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_OBJECT_AFTER_COMMA");break}case"}":{s=u,e.pop();break}}}function a(c,u){switch(c){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=u,e.pop();break}}}for(let c=0;c<t.length;c++){const u=t[c];switch(e[e.length-1]){case"ROOT":n(u,c,"FINISH");break;case"INSIDE_OBJECT_START":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}case"}":{s=c,e.pop();break}}break}case"INSIDE_OBJECT_AFTER_COMMA":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_KEY");break}}break}case"INSIDE_OBJECT_KEY":{switch(u){case'"':{e.pop(),e.push("INSIDE_OBJECT_AFTER_KEY");break}}break}case"INSIDE_OBJECT_AFTER_KEY":{switch(u){case":":{e.pop(),e.push("INSIDE_OBJECT_BEFORE_VALUE");break}}break}case"INSIDE_OBJECT_BEFORE_VALUE":{n(u,c,"INSIDE_OBJECT_AFTER_VALUE");break}case"INSIDE_OBJECT_AFTER_VALUE":{i(u,c);break}case"INSIDE_STRING":{switch(u){case'"':{e.pop(),s=c;break}case"\\":{e.push("INSIDE_STRING_ESCAPE");break}default:s=c}break}case"INSIDE_ARRAY_START":{switch(u){case"]":{s=c,e.pop();break}default:{s=c,n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}}break}case"INSIDE_ARRAY_AFTER_VALUE":{switch(u){case",":{e.pop(),e.push("INSIDE_ARRAY_AFTER_COMMA");break}case"]":{s=c,e.pop();break}default:{s=c;break}}break}case"INSIDE_ARRAY_AFTER_COMMA":{n(u,c,"INSIDE_ARRAY_AFTER_VALUE");break}case"INSIDE_STRING_ESCAPE":{e.pop(),s=c;break}case"INSIDE_NUMBER":{switch(u){case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":{s=c;break}case"e":case"E":case"-":case".":break;case",":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"}":{e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"&&i(u,c);break}case"]":{e.pop(),e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c);break}default:{e.pop();break}}break}case"INSIDE_LITERAL":{const x=t.substring(r,c+1);!"false".startsWith(x)&&!"true".startsWith(x)&&!"null".startsWith(x)?(e.pop(),e[e.length-1]==="INSIDE_OBJECT_AFTER_VALUE"?i(u,c):e[e.length-1]==="INSIDE_ARRAY_AFTER_VALUE"&&a(u,c)):s=c;break}}}let o=t.slice(0,s+1),d=0;for(let c=e.length-1;c>=0;c--)switch(e[c]){case"INSIDE_STRING":{o+='"',d++;break}case"INSIDE_OBJECT_KEY":case"INSIDE_OBJECT_AFTER_KEY":case"INSIDE_OBJECT_AFTER_COMMA":case"INSIDE_OBJECT_START":case"INSIDE_OBJECT_BEFORE_VALUE":case"INSIDE_OBJECT_AFTER_VALUE":{o+="}",d++;break}case"INSIDE_ARRAY_START":case"INSIDE_ARRAY_AFTER_COMMA":case"INSIDE_ARRAY_AFTER_VALUE":{o+="]",d++;break}case"INSIDE_LITERAL":{const p=t.substring(r,t.length);"true".startsWith(p)?o+="true".slice(p.length):"false".startsWith(p)?o+="false".slice(p.length):"null".startsWith(p)&&(o+="null".slice(p.length))}}return[o,d]}function $t(t,e){function s(r){const n=v.useContext(t);if(!(r!=null&&r.optional)&&!n)throw new Error(`This component must be used within ${e}.`);return n}return s}function zt(t,e){function s(n){const i=t(n);return i?i[e]:null}function r(n){let i=!1,a;typeof n=="function"?a=n:n&&typeof n=="object"&&(i=!!n.optional,a=n.selector);const o=s({optional:i});return o?a?o(a):o():null}return{[e]:r,[`${e}Store`]:s}}var Ee=t=>{var s;const e=t;e.__isBound||((s=e.__internal_bindMethods)==null||s.call(e),e.__isBound=!0)},Ft=v.createContext(null),Cr=$t(Ft,"AssistantRuntimeProvider"),{useToolUIs:zn,useToolUIsStore:Fn}=zt(Cr,"useToolUIs");const bt=t=>{let e;const s=new Set,r=(c,u)=>{const p=typeof c=="function"?c(e):c;if(!Object.is(p,e)){const x=e;e=u??(typeof p!="object"||p===null)?p:Object.assign({},e,p),s.forEach(C=>C(e,x))}},n=()=>e,o={setState:r,getState:n,getInitialState:()=>d,subscribe:c=>(s.add(c),()=>s.delete(c))},d=e=t(r,n,o);return o},Er=t=>t?bt(t):bt,Ir=t=>t;function Ar(t,e=Ir){const s=v.useSyncExternalStore(t.subscribe,()=>e(t.getState()),()=>e(t.getInitialState()));return v.useDebugValue(s),s}const yt=t=>{const e=Er(t),s=r=>Ar(e,r);return Object.assign(s,e),s},Re=t=>t?yt(t):yt;var Rr=()=>Re(t=>{const e=new Map;return Object.freeze({getToolUI:s=>{const r=e.get(s),n=r==null?void 0:r.at(-1);return n||null},setToolUI:(s,r)=>{let n=e.get(s);return n||(n=[],e.set(s,n)),n.push(r),t({}),()=>{const i=n.indexOf(r);i!==-1&&n.splice(i,1),i===n.length&&t({})}}})}),Mr=v.createContext(null),Ye=t=>t,Or=v.createContext(null),Nr=t=>{const[e]=v.useState(()=>Re(()=>t));return v.useEffect(()=>{Ee(t),Ye(e).setState(t,!0)},[t,e]),e},Pr=({runtime:t,children:e})=>{const s=Nr(t),[r]=v.useState(()=>({useThreadListItemRuntime:s}));return P.jsx(Or.Provider,{value:r,children:e})},Br=()=>{const t=new Set;return Re(()=>({isAtBottom:!0,scrollToBottom:()=>{for(const e of t)e()},onScrollToBottom:e=>(t.add(e),()=>{t.delete(e)})}))},Ut=v.createContext(null),jr=$t(Ut,"ThreadPrimitive.Viewport"),{useThreadViewport:Un,useThreadViewportStore:Zr}=zt(jr,"useThreadViewport"),Dr=()=>{const t=Zr({optional:!0}),[e]=v.useState(()=>Br());return v.useEffect(()=>t==null?void 0:t.getState().onScrollToBottom(()=>{e.getState().scrollToBottom()}),[t,e]),v.useEffect(()=>{if(t)return e.subscribe(s=>{t.getState().isAtBottom!==s.isAtBottom&&Ye(t).setState({isAtBottom:s.isAtBottom})})},[e,t]),e},Lr=({children:t})=>{const e=Dr(),[s]=v.useState(()=>({useThreadViewport:e}));return P.jsx(Ut.Provider,{value:s,children:t})},$r=t=>{const[e]=v.useState(()=>Re(()=>t));return v.useEffect(()=>{Ee(t),Ee(t.composer),Ye(e).setState(t,!0)},[t,e]),e},zr=({children:t,listItemRuntime:e,runtime:s})=>{const r=$r(s),[n]=v.useState(()=>({useThreadRuntime:r}));return P.jsx(Pr,{runtime:e,children:P.jsx(Mr.Provider,{value:n,children:P.jsx(Lr,{children:t})})})},Fr=t=>{const[e]=v.useState(()=>Re(()=>t));return v.useEffect(()=>{Ee(t),Ee(t.threads),Ye(e).setState(t,!0)},[t,e]),e},Ur=()=>v.useMemo(()=>Rr(),[]),Vr=t=>{var e;return(e=t._core)==null?void 0:e.RenderComponent},Jr=({children:t,runtime:e})=>{const s=Fr(e),r=Ur(),[n]=v.useState(()=>({useToolUIs:r,useAssistantRuntime:s})),i=Vr(e);return P.jsxs(Ft.Provider,{value:n,children:[i&&P.jsx(i,{}),P.jsx(zr,{runtime:e.thread,listItemRuntime:e.threads.mainItem,children:t})]})},Wr=v.memo(Jr),vt=class{constructor(t,e,s){this.contentBinding=t,this.messageApi=e,this.threadApi=s}get path(){return this.contentBinding.path}__internal_bindMethods(){this.addToolResult=this.addToolResult.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this.contentBinding.getState()}addToolResult(t){const e=this.contentBinding.getState();if(!e)throw new Error("Content part is not available");if(e.type!=="tool-call")throw new Error("Tried to add tool result to non-tool content part");if(!this.messageApi)throw new Error("Message API is not available. This is likely a bug in assistant-ui.");if(!this.threadApi)throw new Error("Thread API is not available");const s=this.messageApi.getState();if(!s)throw new Error("Message is not available");const r=e.toolName,n=e.toolCallId;this.threadApi.getState().addToolResult({messageId:s.id,toolName:r,toolCallId:n,result:t})}subscribe(t){return this.contentBinding.subscribe(t)}},Yr=Symbol("partial-json-count"),qr=t=>{try{return _t.parse(t)}catch{try{const[e,s]=kr(t),r=_t.parse(e);return r[Yr]=s,r}catch{return}}},Vt=(t,e,s)=>{const{role:r,id:n,createdAt:i,attachments:a,status:o,metadata:d}=t,c={id:n??e,createdAt:i??new Date},u=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;if(r!=="user"&&a)throw new Error("attachments are only supported for user messages");if(r!=="assistant"&&o)throw new Error("status is only supported for assistant messages");if(r!=="assistant"&&(d!=null&&d.steps))throw new Error("metadata.steps is only supported for assistant messages");switch(r){case"assistant":return{...c,role:r,content:u.map(p=>{const x=p.type;switch(x){case"text":case"reasoning":return p.text.trim().length===0?null:p;case"file":case"source":return p;case"tool-call":return p.args?{...p,toolCallId:p.toolCallId??"tool-"+Ce(),args:p.args,argsText:JSON.stringify(p.args)}:{...p,toolCallId:p.toolCallId??"tool-"+Ce(),args:p.args??qr(p.argsText??"{}"),argsText:p.argsText??""};default:{const C=x;throw new Error(`Unsupported assistant content part type: ${C}`)}}}).filter(p=>!!p),status:o??s,metadata:{unstable_annotations:(d==null?void 0:d.unstable_annotations)??[],unstable_data:(d==null?void 0:d.unstable_data)??[],custom:(d==null?void 0:d.custom)??{},steps:(d==null?void 0:d.steps)??[]}};case"user":return{...c,role:r,content:u.map(p=>{const x=p.type;switch(x){case"text":case"image":case"audio":case"file":return p;default:{const C=x;throw new Error(`Unsupported user content part type: ${C}`)}}}),attachments:a??[],metadata:{custom:(d==null?void 0:d.custom)??{}}};case"system":if(u.length!==1||u[0].type!=="text")throw new Error("System messages must have exactly one text content part.");return{...c,role:r,content:u,metadata:{custom:(d==null?void 0:d.custom)??{}}};default:{const p=r;throw new Error(`Unknown message role: ${p}`)}}},Hr={fromArray:t=>{const e=t.map(s=>Vt(s,Ce(),Zt(!1,!1)));return{messages:e.map((s,r)=>({parentId:r>0?e[r-1].id:null,message:s}))}}},Ze=t=>t.next?Ze(t.next):"current"in t?t:null,Kr=class{constructor(t){h(this,"_value",null);this.func=t}get value(){return this._value===null&&(this._value=this.func()),this._value}dirty(){this._value=null}},Gr=class{constructor(){h(this,"messages",new Map);h(this,"head",null);h(this,"root",{children:[],next:null});h(this,"_messages",new Kr(()=>{var e;const t=new Array(((e=this.head)==null?void 0:e.level)??0);for(let s=this.head;s;s=s.prev)t[s.level]=s.current;return t}))}performOp(t,e,s){const r=e.prev??this.root,n=t??this.root;if(!(s==="relink"&&r===n)){if(s!=="link"&&(r.children=r.children.filter(i=>i!==e.current.id),r.next===e)){const i=r.children.at(-1),a=i?this.messages.get(i):null;if(a===void 0)throw new Error("MessageRepository(performOp/cut): Fallback sibling message not found. This is likely an internal bug in assistant-ui.");r.next=a}if(s!=="cut"){for(let i=t;i;i=i.prev)if(i.current.id===e.current.id)throw new Error("MessageRepository(performOp/link): A message with the same id already exists in the parent tree. This error occurs if the same message id is found multiple times. This is likely an internal bug in assistant-ui.");n.children=[...n.children,e.current.id],(Ze(e)===this.head||n.next===null)&&(n.next=e),e.prev=t}}}get headId(){var t;return((t=this.head)==null?void 0:t.current.id)??null}getMessages(){return this._messages.value}addOrUpdateMessage(t,e){const s=this.messages.get(e.id),r=t?this.messages.get(t):null;if(r===void 0)throw new Error("MessageRepository(addOrUpdateMessage): Parent message not found. This is likely an internal bug in assistant-ui.");if(s){s.current=e,this.performOp(r,s,"relink"),this._messages.dirty();return}const n={prev:r,current:e,next:null,children:[],level:r?r.level+1:0};this.messages.set(e.id,n),this.performOp(r,n,"link"),this.head===r&&(this.head=n),this._messages.dirty()}getMessage(t){var s;const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(updateMessage): Message not found. This is likely an internal bug in assistant-ui.");return{parentId:((s=e.prev)==null?void 0:s.current.id)??null,message:e.current}}appendOptimisticMessage(t,e){let s;do s=br();while(this.messages.has(s));return this.addOrUpdateMessage(t,yr(e,{id:s,status:{type:"running"}})),s}deleteMessage(t,e){const s=this.messages.get(t);if(!s)throw new Error("MessageRepository(deleteMessage): Optimistic message not found. This is likely an internal bug in assistant-ui.");const r=e===void 0?s.prev:e===null?null:this.messages.get(e);if(r===void 0)throw new Error("MessageRepository(deleteMessage): Replacement not found. This is likely an internal bug in assistant-ui.");for(const n of s.children){const i=this.messages.get(n);if(!i)throw new Error("MessageRepository(deleteMessage): Child message not found. This is likely an internal bug in assistant-ui.");this.performOp(r,i,"relink")}this.performOp(null,s,"cut"),this.messages.delete(t),this.head===s&&(this.head=Ze(r??this.root)),this._messages.dirty()}getBranches(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(getBranches): Message not found. This is likely an internal bug in assistant-ui.");const{children:s}=e.prev??this.root;return s}switchToBranch(t){const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(switchToBranch): Branch not found. This is likely an internal bug in assistant-ui.");const s=e.prev??this.root;s.next=e,this.head=Ze(e),this._messages.dirty()}resetHead(t){if(t===null){this.head=null,this._messages.dirty();return}const e=this.messages.get(t);if(!e)throw new Error("MessageRepository(resetHead): Branch not found. This is likely an internal bug in assistant-ui.");this.head=e;for(let s=e;s;s=s.prev)s.prev&&(s.prev.next=s);this._messages.dirty()}clear(){this.messages.clear(),this.head=null,this.root={children:[],next:null},this._messages.dirty()}export(){var e,s;const t=[];for(const[,r]of this.messages)t.push({message:r.current,parentId:((e=r.prev)==null?void 0:e.current.id)??null});return{headId:((s=this.head)==null?void 0:s.current.id)??null,messages:t}}import({headId:t,messages:e}){var s;for(const{message:r,parentId:n}of e)this.addOrUpdateMessage(n,r);this.resetHead(t??((s=e.at(-1))==null?void 0:s.message.id)??null)}},qe=class{constructor(){h(this,"_subscriptions",new Set);h(this,"_connection")}get isConnected(){return!!this._connection}notifySubscribers(){for(const t of this._subscriptions)t()}_updateConnection(){var t;if(this._subscriptions.size>0){if(this._connection)return;this._connection=this._connect()}else(t=this._connection)==null||t.call(this),this._connection=void 0}subscribe(t){return this._subscriptions.add(t),this._updateConnection(),()=>{this._subscriptions.delete(t),this._updateConnection()}}},Z=Symbol("skip-update"),ct=class extends qe{constructor(e){super();h(this,"_previousStateDirty",!0);h(this,"_previousState");h(this,"getState",()=>{if(!this.isConnected||this._previousStateDirty){const e=this.binding.getState();e!==Z&&(this._previousState=e),this._previousStateDirty=!1}if(this._previousState===void 0)throw new Error("Entry not available in the store");return this._previousState});this.binding=e}get path(){return this.binding.path}_connect(){const e=()=>{this._previousStateDirty=!0,this.notifySubscribers()};return this.binding.subscribe(e)}},Pe=class{constructor(t,e){this._core=t,this._threadListBinding=e}get path(){return this._core.path}__internal_bindMethods(){this.switchTo=this.switchTo.bind(this),this.rename=this.rename.bind(this),this.archive=this.archive.bind(this),this.unarchive=this.unarchive.bind(this),this.delete=this.delete.bind(this),this.initialize=this.initialize.bind(this),this.generateTitle=this.generateTitle.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getState=this.getState.bind(this)}getState(){return this._core.getState()}switchTo(){const t=this._core.getState();return this._threadListBinding.switchToThread(t.id)}rename(t){const e=this._core.getState();return this._threadListBinding.rename(e.id,t)}archive(){const t=this._core.getState();return this._threadListBinding.archive(t.id)}unarchive(){const t=this._core.getState();return this._threadListBinding.unarchive(t.id)}delete(){const t=this._core.getState();return this._threadListBinding.delete(t.id)}initialize(){const t=this._core.getState();return this._threadListBinding.initialize(t.id)}generateTitle(){const t=this._core.getState();return this._threadListBinding.generateTitle(t.id)}unstable_on(t,e){let s=this._core.getState().isMain;return this.subscribe(()=>{const r=this._core.getState().isMain;s!==r&&(s=r,!(t==="switched-to"&&!r)&&(t==="switched-away"&&r||e()))})}subscribe(t){return this._core.subscribe(t)}};function Xr(t,e){if(t===void 0&&e===void 0)return!0;if(t===void 0||e===void 0)return!1;for(const s of Object.keys(t)){const r=t[s],n=e[s];if(!Object.is(r,n))return!1}return!0}var N=class extends qe{constructor(e){super();h(this,"_previousState");h(this,"getState",()=>(this.isConnected||this._syncState(),this._previousState));this.binding=e;const s=e.getState();if(s===Z)throw new Error("Entry not available in the store");this._previousState=s}get path(){return this.binding.path}_syncState(){const e=this.binding.getState();return e===Z||Xr(e,this._previousState)?!1:(this._previousState=e,!0)}_connect(){const e=()=>{this._syncState()&&this.notifySubscribers()};return this.binding.subscribe(e)}},de=Symbol("innerMessage"),Qr=t=>t[de],Ie=t=>t.content.filter(s=>s.type==="text").map(s=>s.text).join(`
4
+
5
+ `),Jt=class{constructor(t){this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.getState=this.getState.bind(this),this.remove=this.remove.bind(this),this.subscribe=this.subscribe.bind(this)}getState(){return this._core.getState()}subscribe(t){return this._core.subscribe(t)}},Wt=class extends Jt{constructor(t,e){super(t),this._composerApi=e}remove(){const t=this._composerApi.getState();if(!t)throw new Error("Composer is not available");return t.removeAttachment(this.getState().id)}},en=class extends Wt{get source(){return"thread-composer"}},tn=class extends Wt{get source(){return"edit-composer"}},sn=class extends Jt{get source(){return"message"}constructor(t){super(t)}remove(){throw new Error("Message attachments cannot be removed")}},Yt=class extends qe{constructor(t){super(),this.config=t}getState(){return this.config.binding.getState()}outerSubscribe(t){return this.config.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.config.binding.getState(),s=e==null?void 0:e.unstable_on(this.config.event,t);const r=()=>{var a;const i=this.config.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.config.binding.getState())==null?void 0:a.unstable_on(this.config.event,t))},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},qt=Object.freeze([]),Ht=Object.freeze({}),rn=t=>Object.freeze({type:"thread",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,attachments:(t==null?void 0:t.attachments)??qt,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",runConfig:(t==null?void 0:t.runConfig)??Ht,value:(t==null?void 0:t.text)??""}),nn=t=>Object.freeze({type:"edit",isEditing:(t==null?void 0:t.isEditing)??!1,canCancel:(t==null?void 0:t.canCancel)??!1,isEmpty:(t==null?void 0:t.isEmpty)??!0,text:(t==null?void 0:t.text)??"",role:(t==null?void 0:t.role)??"user",attachments:(t==null?void 0:t.attachments)??qt,runConfig:(t==null?void 0:t.runConfig)??Ht,value:(t==null?void 0:t.text)??""}),Kt=class{constructor(t){h(this,"_eventSubscriptionSubjects",new Map);this._core=t}get path(){return this._core.path}__internal_bindMethods(){this.setText=this.setText.bind(this),this.setRunConfig=this.setRunConfig.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.addAttachment=this.addAttachment.bind(this),this.reset=this.reset.bind(this),this.clearAttachments=this.clearAttachments.bind(this),this.send=this.send.bind(this),this.cancel=this.cancel.bind(this),this.setRole=this.setRole.bind(this),this.getAttachmentAccept=this.getAttachmentAccept.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_on=this.unstable_on.bind(this)}setText(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setText(t)}setRunConfig(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRunConfig(t)}addAttachment(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");return e.addAttachment(t)}reset(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.reset()}clearAttachments(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.clearAttachments()}send(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.send()}cancel(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");t.cancel()}setRole(t){const e=this._core.getState();if(!e)throw new Error("Composer is not available");e.setRole(t)}subscribe(t){return this._core.subscribe(t)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Yt({event:t,binding:this._core}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}getAttachmentAccept(){const t=this._core.getState();if(!t)throw new Error("Composer is not available");return t.getAttachmentAccept()}},an=class extends Kt{constructor(e){const s=new ct({path:e.path,getState:()=>rn(e.getState()),subscribe:r=>e.subscribe(r)});super({path:e.path,getState:()=>e.getState(),subscribe:r=>s.subscribe(r)});h(this,"_getState");this._getState=s.getState.bind(s)}get path(){return this._core.path}get type(){return"thread"}getState(){return this._getState()}getAttachmentByIndex(e){return new en(new N({path:{...this.path,attachmentSource:"thread-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"thread-composer"}:Z},subscribe:s=>this._core.subscribe(s)}),this._core)}},on=class extends Kt{constructor(e,s){const r=new ct({path:e.path,getState:()=>nn(e.getState()),subscribe:n=>e.subscribe(n)});super({path:e.path,getState:()=>e.getState(),subscribe:n=>r.subscribe(n)});h(this,"_getState");this._beginEdit=s,this._getState=r.getState.bind(r)}get path(){return this._core.path}get type(){return"edit"}__internal_bindMethods(){super.__internal_bindMethods(),this.beginEdit=this.beginEdit.bind(this)}getState(){return this._getState()}beginEdit(){this._beginEdit()}getAttachmentByIndex(e){return new tn(new N({path:{...this.path,attachmentSource:"edit-composer",attachmentSelector:{type:"index",index:e},ref:this.path.ref+`${this.path.ref}.attachments[${e}]`},getState:()=>{const r=this.getState().attachments[e];return r?{...r,source:"edit-composer"}:Z},subscribe:s=>this._core.subscribe(s)}),this._core)}},Je=class extends qe{constructor(t){super(),this.binding=t}get path(){return this.binding.path}getState(){return this.binding.getState()}outerSubscribe(t){return this.binding.subscribe(t)}_connect(){const t=()=>{this.notifySubscribers()};let e=this.binding.getState(),s=e==null?void 0:e.subscribe(t);const r=()=>{var a;const i=this.binding.getState();i!==e&&(e=i,s==null||s(),s=(a=this.binding.getState())==null?void 0:a.subscribe(t),t())},n=this.outerSubscribe(r);return()=>{n==null||n(),s==null||s()}}},Be=Object.freeze({type:"complete"}),cn=(t,e,s)=>{if(t.role!=="assistant")return Be;if(s.type==="tool-call")return s.result?Be:t.status;const r=e===Math.max(0,t.content.length-1);return t.status.type==="requires-action"?Be:r?t.status:Be},wt=(t,e)=>{const s=t.content[e];if(!s)return Z;const r=cn(t,e,s);return Object.freeze({...s,[de]:s[de],status:r})},dn=class{constructor(t,e){h(this,"composer");h(this,"_getEditComposerRuntimeCore",()=>this._threadBinding.getState().getEditComposer(this._core.getState().id));this._core=t,this._threadBinding=e,this.composer=new on(new Je({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"edit"},getState:this._getEditComposerRuntimeCore,subscribe:s=>this._threadBinding.subscribe(s)}),()=>this._threadBinding.getState().beginEdit(this._core.getState().id))}get path(){return this._core.path}__internal_bindMethods(){this.reload=this.reload.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getContentPartByIndex=this.getContentPartByIndex.bind(this),this.getContentPartByToolCallId=this.getContentPartByToolCallId.bind(this),this.getAttachmentByIndex=this.getAttachmentByIndex.bind(this),this.unstable_getCopyText=this.unstable_getCopyText.bind(this),this.speak=this.speak.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.submitFeedback=this.submitFeedback.bind(this),this.switchToBranch=this.switchToBranch.bind(this)}getState(){return this._core.getState()}reload(t={}){const e=this._getEditComposerRuntimeCore(),s=e??this._threadBinding.getState().composer,r=e??s,{runConfig:n=r.runConfig}=t,i=this._core.getState();if(i.role!=="assistant")throw new Error("Can only reload assistant messages");this._threadBinding.getState().startRun({parentId:i.parentId,sourceId:i.id,runConfig:n})}speak(){const t=this._core.getState();return this._threadBinding.getState().speak(t.id)}stopSpeaking(){var s;const t=this._core.getState();if(((s=this._threadBinding.getState().speech)==null?void 0:s.messageId)===t.id)this._threadBinding.getState().stopSpeaking();else throw new Error("Message is not being spoken")}submitFeedback({type:t}){const e=this._core.getState();this._threadBinding.getState().submitFeedback({messageId:e.id,type:t})}switchToBranch({position:t,branchId:e}){const s=this._core.getState();if(e&&t)throw new Error("May not specify both branchId and position");if(!e&&!t)throw new Error("Must specify either branchId or position");const n=this._threadBinding.getState().getBranches(s.id);let i=e;if(t==="previous"?i=n[s.branchNumber-2]:t==="next"&&(i=n[s.branchNumber]),!i)throw new Error("Branch not found");this._threadBinding.getState().switchToBranch(i)}unstable_getCopyText(){return Ie(this.getState())}subscribe(t){return this._core.subscribe(t)}getContentPartByIndex(t){if(t<0)throw new Error("Content part index must be >= 0");return new vt(new N({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[${t}]`,contentPartSelector:{type:"index",index:t}},getState:()=>wt(this.getState(),t),subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getContentPartByToolCallId(t){return new vt(new N({path:{...this.path,ref:this.path.ref+`${this.path.ref}.content[toolCallId=${JSON.stringify(t)}]`,contentPartSelector:{type:"toolCallId",toolCallId:t}},getState:()=>{const e=this._core.getState(),s=e.content.findIndex(r=>r.type==="tool-call"&&r.toolCallId===t);return s===-1?Z:wt(e,s)},subscribe:e=>this._core.subscribe(e)}),this._core,this._threadBinding)}getAttachmentByIndex(t){return new sn(new N({path:{...this.path,ref:this.path.ref+`${this.path.ref}.attachments[${t}]`,attachmentSource:"message",attachmentSelector:{type:"index",index:t}},getState:()=>{const e=this.getState().attachments,s=e==null?void 0:e[t];return s?{...s,source:"message"}:Z},subscribe:e=>this._core.subscribe(e)}))}},un=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{},stream:t.stream}),hn=t=>({parentId:t.parentId??null,sourceId:t.sourceId??null,runConfig:t.runConfig??{}}),ln=(t,e)=>{var s,r;return typeof e=="string"?{parentId:((s=t.at(-1))==null?void 0:s.id)??null,sourceId:null,runConfig:{},role:"user",content:[{type:"text",text:e}],attachments:[]}:e.role&&e.parentId&&e.attachments?e:{...e,parentId:e.parentId??((r=t.at(-1))==null?void 0:r.id)??null,sourceId:e.sourceId??null,role:e.role??"user",attachments:e.attachments??[]}},fn=(t,e)=>{const s=t.messages.at(-1);return Object.freeze({threadId:e.id,metadata:e,capabilities:t.capabilities,isDisabled:t.isDisabled,isRunning:(s==null?void 0:s.role)!=="assistant"?!1:s.status.type==="running",messages:t.messages,suggestions:t.suggestions,extras:t.extras,speech:t.speech})},pn=class{constructor(t,e){h(this,"_threadBinding");h(this,"composer");h(this,"_eventSubscriptionSubjects",new Map);const s=new N({path:t.path,getState:()=>fn(t.getState(),e.getState()),subscribe:r=>{const n=t.subscribe(r),i=e.subscribe(r);return()=>{n(),i()}}});this._threadBinding={path:t.path,getState:()=>t.getState(),getStateState:()=>s.getState(),outerSubscribe:r=>t.outerSubscribe(r),subscribe:r=>t.subscribe(r)},this.composer=new an(new Je({path:{...this.path,ref:this.path.ref+`${this.path.ref}.composer`,composerSource:"thread"},getState:()=>this._threadBinding.getState().composer,subscribe:r=>this._threadBinding.subscribe(r)}))}get path(){return this._threadBinding.path}get __internal_threadBinding(){return this._threadBinding}__internal_bindMethods(){this.append=this.append.bind(this),this.startRun=this.startRun.bind(this),this.cancelRun=this.cancelRun.bind(this),this.stopSpeaking=this.stopSpeaking.bind(this),this.export=this.export.bind(this),this.import=this.import.bind(this),this.getMesssageByIndex=this.getMesssageByIndex.bind(this),this.getMesssageById=this.getMesssageById.bind(this),this.subscribe=this.subscribe.bind(this),this.unstable_on=this.unstable_on.bind(this),this.getModelContext=this.getModelContext.bind(this),this.getModelConfig=this.getModelConfig.bind(this),this.getState=this.getState.bind(this)}getState(){return this._threadBinding.getStateState()}append(t){this._threadBinding.getState().append(ln(this._threadBinding.getState().messages,t))}subscribe(t){return this._threadBinding.subscribe(t)}getModelContext(){return this._threadBinding.getState().getModelContext()}getModelConfig(){return this.getModelContext()}startRun(t){const e=t===null||typeof t=="string"?{parentId:t}:t;return this._threadBinding.getState().startRun(hn(e))}unstable_resumeRun(t){return this._threadBinding.getState().resumeRun(un(t))}cancelRun(){this._threadBinding.getState().cancelRun()}stopSpeaking(){return this._threadBinding.getState().stopSpeaking()}export(){return this._threadBinding.getState().export()}import(t){this._threadBinding.getState().import(t)}getMesssageByIndex(t){if(t<0)throw new Error("Message index must be >= 0");return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[${t}]`,messageSelector:{type:"index",index:t}},()=>{var r;const e=this._threadBinding.getState().messages,s=e[t];if(s)return{message:s,parentId:((r=e[t-1])==null?void 0:r.id)??null}})}getMesssageById(t){return this._getMessageRuntime({...this.path,ref:this.path.ref+`${this.path.ref}.messages[messageId=${JSON.stringify(t)}]`,messageSelector:{type:"messageId",messageId:t}},()=>this._threadBinding.getState().getMessageById(t))}_getMessageRuntime(t,e){return new dn(new N({path:t,getState:()=>{var c;const{message:s,parentId:r}=e()??{},{messages:n,speech:i}=this._threadBinding.getState();if(!s||r===void 0)return Z;const a=this._threadBinding.getState(),o=a.getBranches(s.id),d=a.getSubmittedFeedback(s.id);return{...s,[de]:s[de],isLast:((c=n.at(-1))==null?void 0:c.id)===s.id,parentId:r,branchNumber:o.indexOf(s.id)+1,branchCount:o.length,speech:(i==null?void 0:i.messageId)===s.id?i:void 0,submittedFeedback:d}},subscribe:s=>this._threadBinding.subscribe(s)}),this._threadBinding)}unstable_on(t,e){let s=this._eventSubscriptionSubjects.get(t);return s||(s=new Yt({event:t,binding:this._threadBinding}),this._eventSubscriptionSubjects.set(t,s)),s.subscribe(e)}},gn=t=>({mainThreadId:t.mainThreadId,newThread:t.newThreadId,threads:t.threadIds,archivedThreads:t.archivedThreadIds}),je=(t,e)=>{if(e===void 0)return Z;const s=t.getItemById(e);return s?{id:s.threadId,threadId:s.threadId,remoteId:s.remoteId,externalId:s.externalId,title:s.title,status:s.status,isMain:s.threadId===t.mainThreadId}:Z},mn=class{constructor(t,e=pn){h(this,"_getState");h(this,"_mainThreadListItemRuntime");h(this,"main");this._core=t,this._runtimeFactory=e;const s=new ct({path:{},getState:()=>gn(t),subscribe:r=>t.subscribe(r)});this._getState=s.getState.bind(s),this._mainThreadListItemRuntime=new Pe(new N({path:{ref:"threadItems[main]",threadSelector:{type:"main"}},getState:()=>je(this._core,this._core.mainThreadId),subscribe:r=>this._core.subscribe(r)}),this._core),this.main=new e(new Je({path:{ref:"threads.main",threadSelector:{type:"main"}},getState:()=>t.getMainThreadRuntimeCore(),subscribe:r=>t.subscribe(r)}),this._mainThreadListItemRuntime)}__internal_bindMethods(){this.switchToThread=this.switchToThread.bind(this),this.switchToNewThread=this.switchToNewThread.bind(this),this.getState=this.getState.bind(this),this.subscribe=this.subscribe.bind(this),this.getById=this.getById.bind(this),this.getItemById=this.getItemById.bind(this),this.getItemByIndex=this.getItemByIndex.bind(this),this.getArchivedItemByIndex=this.getArchivedItemByIndex.bind(this)}switchToThread(t){return this._core.switchToThread(t)}switchToNewThread(){return this._core.switchToNewThread()}getState(){return this._getState()}subscribe(t){return this._core.subscribe(t)}get mainItem(){return this._mainThreadListItemRuntime}getById(t){return new this._runtimeFactory(new Je({path:{ref:"threads[threadId="+JSON.stringify(t)+"]",threadSelector:{type:"threadId",threadId:t}},getState:()=>this._core.getThreadRuntimeCore(t),subscribe:e=>this._core.subscribe(e)}),this.mainItem)}getItemByIndex(t){return new Pe(new N({path:{ref:`threadItems[${t}]`,threadSelector:{type:"index",index:t}},getState:()=>je(this._core,this._core.threadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getArchivedItemByIndex(t){return new Pe(new N({path:{ref:`archivedThreadItems[${t}]`,threadSelector:{type:"archiveIndex",index:t}},getState:()=>je(this._core,this._core.archivedThreadIds[t]),subscribe:e=>this._core.subscribe(e)}),this._core)}getItemById(t){return new Pe(new N({path:{ref:`threadItems[threadId=${t}]`,threadSelector:{type:"threadId",threadId:t}},getState:()=>je(this._core,t),subscribe:e=>this._core.subscribe(e)}),this._core)}},G=Object.freeze([]),ne="DEFAULT_THREAD_ID",_n=Object.freeze([ne]),bn=Object.freeze({threadId:ne,status:"regular"}),yn=Promise.resolve(),vn=class{constructor(t={},e){h(this,"_mainThreadId",ne);h(this,"_threads",_n);h(this,"_archivedThreads",G);h(this,"_mainThread");h(this,"_subscriptions",new Set);this.adapter=t,this.threadFactory=e,this._mainThread=this.threadFactory()}get newThreadId(){}get threadIds(){return this._threads}get archivedThreadIds(){return this._archivedThreads}getLoadThreadsPromise(){return yn}get mainThreadId(){return this._mainThreadId}getMainThreadRuntimeCore(){return this._mainThread}getThreadRuntimeCore(){throw new Error("Method not implemented.")}getItemById(t){for(const e of this.adapter.threads??[])if(e.threadId===t)return e;for(const e of this.adapter.archivedThreads??[])if(e.threadId===t)return e;if(t===ne)return bn}__internal_setAdapter(t){var d,c;const e=this.adapter;this.adapter=t;const s=t.threadId??ne,r=t.threads??G,n=t.archivedThreads??G,i=e.threadId??ne,a=e.threads??G,o=e.archivedThreads??G;i===s&&a===r&&o===n||(a!==r&&(this._threads=((d=this.adapter.threads)==null?void 0:d.map(u=>u.threadId))??G),o!==n&&(this._archivedThreads=((c=this.adapter.archivedThreads)==null?void 0:c.map(u=>u.threadId))??G),i!==s&&(this._mainThreadId=s,this._mainThread=this.threadFactory()),this._notifySubscribers())}async switchToThread(t){if(this._mainThreadId===t)return;const e=this.adapter.onSwitchToThread;if(!e)throw new Error("External store adapter does not support switching to thread");e(t)}async switchToNewThread(){const t=this.adapter.onSwitchToNewThread;if(!t)throw new Error("External store adapter does not support switching to new thread");t()}async rename(t,e){const s=this.adapter.onRename;if(!s)throw new Error("External store adapter does not support renaming");s(t,e)}async archive(t){const e=this.adapter.onArchive;if(!e)throw new Error("External store adapter does not support archiving");e(t)}async unarchive(t){const e=this.adapter.onUnarchive;if(!e)throw new Error("External store adapter does not support unarchiving");e(t)}async delete(t){const e=this.adapter.onDelete;if(!e)throw new Error("External store adapter does not support deleting");e(t)}initialize(){throw new Error("Method not implemented.")}generateTitle(){throw new Error("Method not implemented.")}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}_notifySubscribers(){for(const t of this._subscriptions)t()}},St=class{constructor(){h(this,"cache",new WeakMap)}convertMessages(t,e){return t.map((s,r)=>{const n=this.cache.get(s),i=e(n,s,r);return this.cache.set(s,i),i})}},wn=class extends Pt{constructor(e,s,{parentId:r,message:n}){super();h(this,"_nonTextParts");h(this,"_previousText");h(this,"_parentId");h(this,"_sourceId");this.runtime=e,this.endEditCallback=s,this._parentId=r,this._sourceId=n.id,this._previousText=Ie(n),this.setText(this._previousText),this.setRole(n.role),this.setAttachments(n.attachments??[]),this._nonTextParts=n.content.filter(i=>i.type!=="text"),this.setRunConfig({...e.composer.runConfig})}get canCancel(){return!0}getAttachmentAdapter(){var e;return(e=this.runtime.adapters)==null?void 0:e.attachments}async handleSend(e){Ie(e)!==this._previousText&&this.runtime.append({...e,content:[...e.content,...this._nonTextParts],parentId:this._parentId,sourceId:this._sourceId}),this.handleCancel()}handleCancel(){this.endEditCallback(),this._notifySubscribers()}},Sn=class{constructor(t){h(this,"_subscriptions",new Set);h(this,"_isInitialized",!1);h(this,"repository",new Gr);h(this,"composer",new gr(this));h(this,"_editComposers",new Map);h(this,"_submittedFeedback",{});h(this,"_stopSpeaking");h(this,"speech");h(this,"_eventSubscribers",new Map);this._contextProvider=t}get messages(){return this.repository.getMessages()}getModelContext(){return this._contextProvider.getModelContext()}getEditComposer(t){return this._editComposers.get(t)}beginEdit(t){if(this._editComposers.has(t))throw new Error("Edit already in progress");this._editComposers.set(t,new wn(this,()=>this._editComposers.delete(t),this.repository.getMessage(t))),this._notifySubscribers()}getMessageById(t){return this.repository.getMessage(t)}getBranches(t){return this.repository.getBranches(t)}switchToBranch(t){this.repository.switchToBranch(t),this._notifySubscribers()}_notifySubscribers(){for(const t of this._subscriptions)t()}_notifyEventSubscribers(t){const e=this._eventSubscribers.get(t);if(e)for(const s of e)s()}subscribe(t){return this._subscriptions.add(t),()=>this._subscriptions.delete(t)}getSubmittedFeedback(t){return this._submittedFeedback[t]}submitFeedback({messageId:t,type:e}){var n;const s=(n=this.adapters)==null?void 0:n.feedback;if(!s)throw new Error("Feedback adapter not configured");const{message:r}=this.repository.getMessage(t);s.submit({message:r,type:e}),this._submittedFeedback[t]={type:e},this._notifySubscribers()}speak(t){var i,a;const e=(i=this.adapters)==null?void 0:i.speech;if(!e)throw new Error("Speech adapter not configured");const{message:s}=this.repository.getMessage(t);(a=this._stopSpeaking)==null||a.call(this);const r=e.speak(Ie(s)),n=r.subscribe(()=>{r.status.type==="ended"?(this._stopSpeaking=void 0,this.speech=void 0):this.speech={messageId:t,status:r.status},this._notifySubscribers()});this.speech={messageId:t,status:r.status},this._notifySubscribers(),this._stopSpeaking=()=>{r.cancel(),n(),this.speech=void 0,this._stopSpeaking=void 0}}stopSpeaking(){if(!this._stopSpeaking)throw new Error("No message is being spoken");this._stopSpeaking(),this._notifySubscribers()}ensureInitialized(){this._isInitialized||(this._isInitialized=!0,this._notifyEventSubscribers("initialize"))}export(){return this.repository.export()}import(t){this.ensureInitialized(),this.repository.clear(),this.repository.import(t),this._notifySubscribers()}unstable_on(t,e){var r,n;if(t==="model-context-update")return((n=(r=this._contextProvider).subscribe)==null?void 0:n.call(r,e))??(()=>{});const s=this._eventSubscribers.get(t);return s?s.add(e):this._eventSubscribers.set(t,new Set([e])),()=>{this._eventSubscribers.get(t).delete(e)}}},xn=Object.freeze([]),Tn=(t,e)=>{var s;return t&&((s=e[e.length-1])==null?void 0:s.role)!=="assistant"},kn=class extends Sn{constructor(e,s){super(e);h(this,"assistantOptimisticId",null);h(this,"_capabilities",{switchToBranch:!1,edit:!1,reload:!1,cancel:!1,unstable_copy:!1,speech:!1,attachments:!1,feedback:!1});h(this,"_messages");h(this,"isDisabled");h(this,"suggestions",[]);h(this,"extras");h(this,"_converter",new St);h(this,"_store");h(this,"updateMessages",e=>{var r,n,i,a;this._store.convertMessage!==void 0?(n=(r=this._store).setMessages)==null||n.call(r,e.flatMap(Qr).filter(o=>o!=null)):(a=(i=this._store).setMessages)==null||a.call(i,e)});this.__internal_setAdapter(s)}get capabilities(){return this._capabilities}get messages(){return this._messages}get adapters(){return this._store.adapters}beginEdit(e){if(!this._store.onEdit)throw new Error("Runtime does not support editing.");super.beginEdit(e)}__internal_setAdapter(e){var i,a,o,d,c,u;if(this._store===e)return;const s=e.isRunning??!1;this.isDisabled=e.isDisabled??!1;const r=this._store;if(this._store=e,this.extras=e.extras,this.suggestions=e.suggestions??xn,this._capabilities={switchToBranch:this._store.setMessages!==void 0,edit:this._store.onEdit!==void 0,reload:this._store.onReload!==void 0,cancel:this._store.onCancel!==void 0,speech:((i=this._store.adapters)==null?void 0:i.speech)!==void 0,unstable_copy:((a=this._store.unstable_capabilities)==null?void 0:a.copy)!==!1,attachments:!!((o=this._store.adapters)!=null&&o.attachments),feedback:!!((d=this._store.adapters)!=null&&d.feedback)},r){if(r.convertMessage!==e.convertMessage)this._converter=new St;else if(r.isRunning===e.isRunning&&r.messages===e.messages){this._notifySubscribers();return}}const n=e.convertMessage?this._converter.convertMessages(e.messages,(p,x,C)=>{if(!e.convertMessage)return x;const Me=C===e.messages.length-1,J=Zt(Me,s);if(p&&(p.role!=="assistant"||!vr(p.status)||p.status===J))return p;const Ke=e.convertMessage(x,C),Oe=Vt(Ke,C.toString(),J);return Oe[de]=x,Oe}):e.messages;n.length>0&&this.ensureInitialized(),((r==null?void 0:r.isRunning)??e.isRunning!==!1??!1)&&(e.isRunning?this._notifyEventSubscribers("run-start"):this._notifyEventSubscribers("run-end"));for(let p=0;p<n.length;p++){const x=n[p],C=n[p-1];this.repository.addOrUpdateMessage((C==null?void 0:C.id)??null,x)}this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null),Tn(s,n)&&(this.assistantOptimisticId=this.repository.appendOptimisticMessage(((c=n.at(-1))==null?void 0:c.id)??null,{role:"assistant",content:[]})),this.repository.resetHead(this.assistantOptimisticId??((u=n.at(-1))==null?void 0:u.id)??null),this._messages=this.repository.getMessages(),this._notifySubscribers()}switchToBranch(e){if(!this._store.setMessages)throw new Error("Runtime does not support switching branches.");this.repository.switchToBranch(e),this.updateMessages(this.repository.getMessages())}async append(e){var s;if(e.parentId!==(((s=this.messages.at(-1))==null?void 0:s.id)??null)){if(!this._store.onEdit)throw new Error("Runtime does not support editing messages.");await this._store.onEdit(e)}else await this._store.onNew(e)}async startRun(e){if(!this._store.onReload)throw new Error("Runtime does not support reloading messages.");await this._store.onReload(e.parentId,e)}async resumeRun(){throw new Error("Runtime does not support resuming runs.")}cancelRun(){var r;if(!this._store.onCancel)throw new Error("Runtime does not support cancelling runs.");this._store.onCancel(),this.assistantOptimisticId&&(this.repository.deleteMessage(this.assistantOptimisticId),this.assistantOptimisticId=null);let e=this.repository.getMessages();const s=e[e.length-1];(s==null?void 0:s.role)==="user"&&s.id===((r=e.at(-1))==null?void 0:r.id)?(this.repository.deleteMessage(s.id),this.composer.text.trim()||this.composer.setText(Ie(s)),e=this.repository.getMessages()):this._notifySubscribers(),setTimeout(()=>{this.updateMessages(e)},0)}addToolResult(e){if(!this._store.onAddToolResult)throw new Error("Runtime does not support tool results.");this._store.onAddToolResult(e)}},xt=t=>{var e;return((e=t.adapters)==null?void 0:e.threadList)??{}},Cn=class extends lr{constructor(e){super();h(this,"threads");this.threads=new vn(xt(e),()=>new kn(this._contextProvider,e))}setAdapter(e){this.threads.__internal_setAdapter(xt(e)),this.threads.getMainThreadRuntimeCore().__internal_setAdapter(e)}},En=v.createContext(null),In=()=>v.useContext(En),An=t=>{const[e]=v.useState(()=>new Cn(t));v.useEffect(()=>{e.setAdapter(t)});const{modelContext:s}=In()??{};return v.useEffect(()=>{if(s)return e.registerModelContextProvider(s)},[s,e]),v.useMemo(()=>new Rn(e),[e])},Rn=class{constructor(t){h(this,"threads");h(this,"_thread");this._core=t,this.threads=new mn(t.threads),this._thread=this.threads.main}get threadList(){return this.threads}__internal_bindMethods(){this.switchToNewThread=this.switchToNewThread.bind(this),this.switchToThread=this.switchToThread.bind(this),this.registerModelContextProvider=this.registerModelContextProvider.bind(this),this.registerModelConfigProvider=this.registerModelConfigProvider.bind(this),this.reset=this.reset.bind(this)}get thread(){return this._thread}switchToNewThread(){return this._core.threads.switchToNewThread()}switchToThread(t){return this._core.threads.switchToThread(t)}registerModelContextProvider(t){return this._core.registerModelContextProvider(t)}registerModelConfigProvider(t){return this.registerModelContextProvider(t)}reset({initialMessages:t}={}){return this._core.threads.getMainThreadRuntimeCore().import(Hr.fromArray(t??[]))}};function Mn(t){return t.filter(e=>{var s;return e.finishReason==="stop"?e.text!==null&&((s=e.text)==null?void 0:s.trim())!=="":!0})}function On(t){const e=[];let s=null;for(const r of t)r.type==="reasoning"?(s!=null&&(e.push(s),s=null),e.push(r)):r.functionCalls?(s&&e.push(s),e.push(r),s=null):r.functionResponse?e[e.length-1]={...e[e.length-1],functionResponse:r.functionResponse}:s&&r.protocol===s.protocol&&(s.role===r.role||r.finishReason==="stop")?s.text+=r.text:(s&&e.push(s),s={...r});return s&&e.push(s),Mn(e)}function Nn(t){var e;return t.role==="function"?{id:t.id,role:"assistant",status:(t==null?void 0:t.functionResponse)===null?{type:"running"}:{type:"complete",reason:"stop"},content:((e=t.functionCalls)==null?void 0:e.map(s=>{var r;return{type:"tool-call",toolName:s.name,toolCallId:s.id,args:s.args,result:(r=t.functionResponse)==null?void 0:r.result}}))??[]}:{id:t.id,role:t.role,content:t.type==="reasoning"?[{type:"reasoning",text:t.text}]:[{type:"text",text:t.text}]}}class He{constructor(){h(this,"statusChangeCallbacks",[]);h(this,"messageCallbacks",[])}addStatusChangeListener(e){this.statusChangeCallbacks.push(e)}addMessageListener(e){this.messageCallbacks.push(e)}async syncSession(e){this.session=e}async notifyMessage(e){this.messageCallbacks.forEach(s=>s(e))}async notifyMessages(e){e.forEach(s=>{this.messageCallbacks.forEach(r=>r(s))})}async setSession(e){this.session=e}async setStatus(e){const s=this.status!==e;this.status=e,s&&this.statusChangeCallbacks.forEach(r=>r(e))}clearListeners(){this.statusChangeCallbacks=[],this.messageCallbacks=[]}}class rt extends He{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"notify",!0);this.config=s,this.status="disconnected",this.autostart=!0}getName(){return"rest"}getPriority(){return 0}async connect(s){return this.setStatus("connected"),s}async disconnect(){this.setStatus("disconnected"),this.session=null}async syncSession(s){this.session=s}async send(s){const{apiUrl:r,apiKey:n,agentId:i}=this.config,a=this.session??"new",o=s,c=await(await fetch(`${r}/agents/${i}/sessions/${a}/messages`,{body:JSON.stringify({userMessage:o}),method:"POST",headers:{"Content-Type":"application/json","x-fox-apikey":n,"x-persona-apikey":n}})).json();this.notifyMessages(c.response.messages)}}class nt extends He{constructor(s){super();h(this,"status");h(this,"autostart");h(this,"session");h(this,"config");h(this,"webSocket");this.config=s,this.status="disconnected",this.autostart=!0,this.session=null,this.webSocket=null}getName(){return"websocket"}getPriority(){return 1}async syncSession(s){var r;(r=this.config.logger)==null||r.debug("Syncing session with WebSocket protocol:",s),this.session=s,this.webSocket&&this.status==="connected"&&(this.disconnect(),this.connect(s))}connect(s){var o;if(this.webSocket!==null&&this.status==="connected")return Promise.resolve(this.session);const r=s||this.session||"new";(o=this.config.logger)==null||o.debug("Connecting to WebSocket with sessionId:",r);const n=encodeURIComponent(this.config.apiKey),i=this.config.agentId,a=`${this.config.webSocketUrl}?sessionCode=${r}&agentId=${i}&apiKey=${n}`;return this.setStatus("connecting"),this.webSocket=new WebSocket(a),this.webSocket.addEventListener("open",()=>{this.setStatus("connected")}),this.webSocket.addEventListener("message",d=>{const c=JSON.parse(d.data);if(c.type!=="message")return;const u=c.payload;this.notifyMessage(u!=null&&u.thought?{role:"assistant",type:"reasoning",text:u.thought}:u)}),this.webSocket.addEventListener("close",()=>{var d;this.setStatus("disconnected"),this.webSocket=null,(d=this.config.logger)==null||d.warn("WebSocket connection closed")}),this.webSocket.addEventListener("error",d=>{var c;this.setStatus("disconnected"),this.webSocket=null,(c=this.config.logger)==null||c.error("WebSocket error",d)}),Promise.resolve(r)}disconnect(){var s;return(s=this.config.logger)==null||s.debug("Disconnecting WebSocket"),this.webSocket&&this.status==="connected"&&(this.webSocket.close(),this.setStatus("disconnected"),this.webSocket=null),Promise.resolve()}send(s){return this.webSocket&&this.status==="connected"?(this.webSocket.send(JSON.stringify({type:"request",payload:s})),Promise.resolve()):Promise.reject(new Error("WebSocket is not connected"))}}class Pn{constructor(e){h(this,"config");h(this,"pc",null);h(this,"ws",null);h(this,"localStream",null);h(this,"remoteStream",new MediaStream);h(this,"audioCtx",null);h(this,"localAnalyser",null);h(this,"remoteAnalyser",null);h(this,"analyzerFrame",null);h(this,"dataChannel",null);h(this,"isConnected",!1);h(this,"visualizerCallbacks",[]);h(this,"messageCallbacks",[]);this.config=e}async connect(e){var s;if(!this.isConnected){this.isConnected=!0;try{this.localStream=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(r){(s=this.config.logger)==null||s.error("Error accessing microphone:",r);return}this.pc=new RTCPeerConnection({iceServers:this.config.iceServers||[{urls:"stun:34.38.108.251:3478"},{urls:"turn:34.38.108.251:3478",username:"webrtc",credential:"webrtc"}]}),this.localStream.getTracks().forEach(r=>{this.pc.addTrack(r,this.localStream)}),this.pc.ontrack=r=>{r.streams[0].getTracks().forEach(i=>{this.remoteStream.addTrack(i)}),this.audioCtx||this._startAnalyzers();const n=new Audio;n.srcObject=this.remoteStream,n.play().catch(i=>{var a;(a=this.config.logger)==null||a.error("Error playing remote audio:",i)})},this.pc.onicecandidate=r=>{var n;r.candidate&&((n=this.ws)==null?void 0:n.readyState)===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"CANDIDATE",src:"client",payload:{candidate:r.candidate}}))},this.pc.ondatachannel=r=>{const n=r.channel;n.onmessage=i=>{this.messageCallbacks.forEach(a=>{a(i)})}},this.ws=new WebSocket(this.config.webrtcUrl||"wss://persona.applica.guru/api/webrtc"),this.ws.onopen=async()=>{var a,o;const r=await this.pc.createOffer();await this.pc.setLocalDescription(r);const n={agentId:this.config.agentId,sessionCode:e};(a=this.config.logger)==null||a.debug("Opening connection to WebRTC server: ",n);const i={type:"OFFER",src:((o=crypto.randomUUID)==null?void 0:o.call(crypto))||"client_"+Date.now(),payload:{sdp:{sdp:r.sdp,type:r.type},connectionId:(Date.now()%1e6).toString(),metadata:n}};this.ws.send(JSON.stringify(i))},this.ws.onmessage=async r=>{var i;const n=JSON.parse(r.data);if(n.type==="ANSWER")await this.pc.setRemoteDescription(new RTCSessionDescription(n.payload.sdp));else if(n.type==="CANDIDATE")try{await this.pc.addIceCandidate(new RTCIceCandidate(n.payload.candidate))}catch(a){(i=this.config.logger)==null||i.error("Error adding ICE candidate:",a)}},this.ws.onclose=()=>{this._stopAnalyzers()}}}async disconnect(){var e;this.isConnected&&(this.isConnected=!1,((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN&&this.ws.close(),this.pc&&this.pc.close(),this.localStream&&this.localStream.getTracks().forEach(s=>s.stop()),this.remoteStream=new MediaStream,this.audioCtx&&(await this.audioCtx.close(),this.audioCtx=null),this._stopAnalyzers())}addVisualizerCallback(e){this.visualizerCallbacks.push(e)}addMessageCallback(e){this.messageCallbacks.push(e)}createDataChannel(e="messages"){this.pc&&(this.dataChannel=this.pc.createDataChannel(e),this.dataChannel.onopen=()=>{var s;return(s=this.config.logger)==null?void 0:s.info("Data channel opened")},this.dataChannel.onmessage=s=>{this.messageCallbacks.forEach(r=>{r(s)})})}sendMessage(e){var s,r;if(!this.dataChannel){(s=this.config.logger)==null||s.warn("Data channel is not open, cannot send message");return}this.dataChannel.send(e),(r=this.config.logger)==null||r.info("Sent message:",e)}_startAnalyzers(){if(!this.localStream||!this.remoteStream||this.visualizerCallbacks.length===0)return;this.audioCtx=new(window.AudioContext||window.webkitAudioContext);const e=this.audioCtx.createMediaStreamSource(this.localStream),s=this.audioCtx.createMediaStreamSource(this.remoteStream);this.localAnalyser=this.audioCtx.createAnalyser(),this.remoteAnalyser=this.audioCtx.createAnalyser(),this.localAnalyser.fftSize=256,this.remoteAnalyser.fftSize=256,e.connect(this.localAnalyser),s.connect(this.remoteAnalyser);const r=()=>{if(!this.localAnalyser||!this.remoteAnalyser||this.visualizerCallbacks.length===0)return;const n=new Uint8Array(this.localAnalyser.frequencyBinCount),i=new Uint8Array(this.remoteAnalyser.frequencyBinCount);this.localAnalyser.getByteFrequencyData(n),this.remoteAnalyser.getByteFrequencyData(i);const a=n.reduce((d,c)=>d+c,0)/n.length,o=i.reduce((d,c)=>d+c,0)/i.length;this.visualizerCallbacks.length>0&&this.visualizerCallbacks.forEach(d=>{d({localAmplitude:a,remoteAmplitude:o})}),this.analyzerFrame=requestAnimationFrame(r)};this.analyzerFrame=requestAnimationFrame(r)}_stopAnalyzers(){this.analyzerFrame&&(cancelAnimationFrame(this.analyzerFrame),this.analyzerFrame=null),this.localAnalyser=null,this.remoteAnalyser=null}}class it extends He{constructor(s){super();h(this,"status");h(this,"session");h(this,"autostart");h(this,"config");h(this,"webRTCClient");this.config=s,this.status="disconnected",this.session=null,this.autostart=(s==null?void 0:s.autostart)??!1,this.webRTCClient=new Pn(s),this.webRTCClient.addMessageCallback(r=>{var i;(i=s.logger)==null||i.debug("Received data message:",r.data);const n=JSON.parse(r.data);n.type==="message"&&this.notifyMessage(n.payload)})}getName(){return"webrtc"}getPriority(){return 10}async syncSession(s){super.syncSession(s),this.status==="connected"&&(await this.disconnect(),await this.connect(s))}async connect(s){var r;return this.status==="connected"?Promise.resolve(this.session):(this.session=s||this.session||"new",this.setStatus("connecting"),(r=this.config.logger)==null||r.debug("Connecting to WebRTC with sessionId:",this.session),await this.webRTCClient.connect(this.session),this.setStatus("connected"),await this.webRTCClient.createDataChannel(),this.session)}async disconnect(){var s,r,n;if(this.status==="disconnected")return(s=this.config.logger)==null||s.warn("Already disconnected"),Promise.resolve();await this.webRTCClient.disconnect(),this.setStatus("disconnected"),(n=(r=this.config)==null?void 0:r.logger)==null||n.debug("Disconnected from WebRTC")}send(s){return this.status!=="connected"?Promise.reject(new Error("Not connected")):(this.webRTCClient.sendMessage(s),Promise.resolve())}}const dt=v.createContext(void 0);function Bn({dev:t=!1,protocols:e,logger:s,children:r,session:n="new",...i}){const[a,o]=v.useState(!1),[d,c]=v.useState([]),[u,p]=v.useState(n),[x,C]=v.useState(new Map),Me=v.useRef(!1),J=v.useMemo(()=>{if(Array.isArray(e))return e;if(typeof e=="object"&&e!==null){const k=t?"localhost:8000":"persona.applica.guru/api",z=t?"http":"https",W=t?"ws":"wss";return Object.keys(e).map(M=>{switch(M){case"rest":const Ne=e[M];return Ne===!0?new rt({apiUrl:`${z}://${k}`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new rt(Ne);case"webrtc":const ut=e[M];return ut===!0?new it({webrtcUrl:`${W}://${k}/webrtc`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new it(ut);case"websocket":const ht=e[M];return ht===!0?new nt({webSocketUrl:`${W}://${k}/websocket`,apiKey:i.apiKey,agentId:i.agentId,logger:s}):new nt(ht);default:throw new Error(`Unknown protocol: ${M}`)}})}throw new Error("Invalid protocols configuration")},[]);v.useEffect(()=>{Me.current||(Me.current=!0,s==null||s.debug("Initializing protocols: ",J.map(k=>k.getName())),J.forEach(k=>{k.setSession(u),k.clearListeners(),k.addStatusChangeListener(z=>{s==null||s.debug(`${k.getName()} has notified new status: ${z}`),x.set(k.getName(),z),C(new Map(x))}),k.addMessageListener(z=>{c(W=>On([...W,{...z,protocol:k.getName()}]))}),k.autostart&&k.status==="disconnected"&&(s==null||s.debug(`Connecting to protocol: ${k.getName()}`),k.connect(u))}))},[u,J,s,x]);const Ke=async k=>{var Ge;if(((Ge=k.content[0])==null?void 0:Ge.type)!=="text")throw new Error("Only text messages are supported");const z=k.content[0].text;c(M=>[...M,{role:"user",type:"text",text:z}]),o(!0);const W=J.sort((M,Ne)=>Ne.getPriority()-M.getPriority()).find(M=>M.status==="connected");await(W==null?void 0:W.send(z)),o(!1)},Oe=v.useCallback(()=>(o(!1),c([]),p("new"),Promise.resolve()),[]),Xt=v.useCallback(()=>Promise.resolve(),[]),Qt=An({isRunning:a,messages:d,convertMessage:Nn,onNew:Ke,onCancel:Oe,onReload:Xt});return P.jsx(dt.Provider,{value:{protocols:J,protocolsStatus:x},children:P.jsx(Wr,{runtime:Qt,children:r})})}function jn({children:t,...e}){return P.jsx(Bn,{...e,children:t})}function Zn(){const t=v.useContext(dt);if(!t)throw new Error("usePersonaRuntime must be used within a PersonaRuntimeProvider");return t}function Gt(t){const e=v.useContext(dt);if(!e)throw new Error("usePersonaRuntimeProtocol must be used within a PersonaRuntimeProvider");const s=e.protocols.find(n=>n.getName()===t);if(!s)return null;const r=e.protocolsStatus.get(s.getName());return{...s,connect:s.connect.bind(s),disconnect:s.disconnect.bind(s),send:s.send.bind(s),setSession:s.setSession.bind(s),addStatusChangeListener:s.addStatusChangeListener.bind(s),addMessageListener:s.addMessageListener.bind(s),getName:s.getName.bind(s),getPriority:s.getPriority.bind(s),status:r||s.status}}function Dn(){return Gt("webrtc")}class Ln{constructor(){h(this,"prefix","[Persona]")}log(e,...s){console.log(`${this.prefix} - ${e}`,...s)}info(e,...s){console.info(`${this.prefix} - ${e}`,...s)}warn(e,...s){console.warn(`${this.prefix} - ${e}`,...s)}error(e,...s){console.error(`${this.prefix} - ${e}`,...s)}debug(e,...s){console.debug(`${this.prefix} - ${e}`,...s)}}exports.PersonaConsoleLogger=Ln;exports.PersonaProtocolBase=He;exports.PersonaRESTProtocol=rt;exports.PersonaRuntimeProvider=jn;exports.PersonaWebRTCProtocol=it;exports.PersonaWebSocketProtocol=nt;exports.usePersonaRuntime=Zn;exports.usePersonaRuntimeProtocol=Gt;exports.usePersonaRuntimeWebRTCProtocol=Dn;
15
6
  //# sourceMappingURL=bundle.cjs.js.map