@osvi-ai/chat 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1 -3
- package/dist/core.js +10 -0
- package/dist/core.js.map +1 -0
- package/dist/index-BsRyQwUM.js +1331 -0
- package/dist/index-BsRyQwUM.js.map +1 -0
- package/dist/types/core/client.d.ts +65 -0
- package/dist/types/core/connection.d.ts +78 -0
- package/dist/types/core/errors.d.ts +14 -0
- package/dist/types/core/http.d.ts +38 -0
- package/dist/types/core/index.d.ts +7 -0
- package/dist/types/core/interactions.d.ts +50 -0
- package/dist/types/core/protocol/envelope.d.ts +2 -0
- package/dist/types/core/protocol/readers.d.ts +14 -0
- package/dist/types/core/protocol/types.d.ts +118 -0
- package/dist/types/core/protocol/validators.d.ts +10 -0
- package/dist/types/core/state.d.ts +23 -0
- package/dist/types/core/storage.d.ts +10 -0
- package/dist/types/core/version.d.ts +1 -0
- package/dist/types/ui/define.d.ts +1 -0
- package/dist/types/ui/index.d.ts +9 -0
- package/dist/types/ui/osvi-chat.d.ts +69 -0
- package/dist/types/ui/panel/attrs.d.ts +6 -0
- package/dist/types/ui/panel/composer.d.ts +10 -0
- package/dist/types/ui/panel/linkify.d.ts +7 -0
- package/dist/types/ui/panel/transcript.d.ts +4 -0
- package/dist/types/ui/strings.d.ts +27 -0
- package/dist/types/ui/styles.d.ts +1 -0
- package/dist/types/ui/theme.d.ts +22 -0
- package/dist/types/ui/tools/base.d.ts +14 -0
- package/dist/types/ui/tools/osvi-buttons.d.ts +10 -0
- package/dist/types/ui/tools/osvi-carousel.d.ts +16 -0
- package/dist/types/ui/tools/osvi-date-picker.d.ts +17 -0
- package/dist/types/widget/config.d.ts +22 -0
- package/dist/types/widget/index.d.ts +1 -0
- package/dist/types/widget/launcher.d.ts +35 -0
- package/dist/types/widget/widget.d.ts +13 -0
- package/dist/ui.js +49 -0
- package/dist/ui.js.map +1 -0
- package/dist/ui.mjs +570 -0
- package/dist/ui.mjs.map +1 -0
- package/dist/widget.js +59 -0
- package/dist/widget.js.map +1 -0
- package/package.json +60 -4
package/dist/ui.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
var OsviChatUi=(function(A){"use strict";var E;const ft=globalThis,St=ft.ShadowRoot&&(ft.ShadyCSS===void 0||ft.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,At=Symbol(),Xt=new WeakMap;let Zt=class{constructor(t,e,s){if(this._$cssResult$=!0,s!==At)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const e=this.t;if(St&&t===void 0){const s=e!==void 0&&e.length===1;s&&(t=Xt.get(e)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&Xt.set(e,t))}return t}toString(){return this.cssText}};const M=i=>new Zt(typeof i=="string"?i:i+"",void 0,At),Qt=(i,...t)=>{const e=i.length===1?i[0]:t.reduce((s,n,r)=>s+(o=>{if(o._$cssResult$===!0)return o.cssText;if(typeof o=="number")return o;throw Error("Value passed to 'css' function must be a 'css' function result: "+o+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(n)+i[r+1],i[0]);return new Zt(e,i,At)},Ke=(i,t)=>{if(St)i.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const e of t){const s=document.createElement("style"),n=ft.litNonce;n!==void 0&&s.setAttribute("nonce",n),s.textContent=e.cssText,i.appendChild(s)}},te=St?i=>i:i=>i instanceof CSSStyleSheet?(t=>{let e="";for(const s of t.cssRules)e+=s.cssText;return M(e)})(i):i;const{is:Ye,defineProperty:Je,getOwnPropertyDescriptor:Xe,getOwnPropertyNames:Ze,getOwnPropertySymbols:Qe,getPrototypeOf:ts}=Object,x=globalThis,ee=x.trustedTypes,es=ee?ee.emptyScript:"",ss=x.reactiveElementPolyfillSupport,Z=(i,t)=>i,gt={toAttribute(i,t){switch(t){case Boolean:i=i?es:null;break;case Object:case Array:i=i==null?i:JSON.stringify(i)}return i},fromAttribute(i,t){let e=i;switch(t){case Boolean:e=i!==null;break;case Number:e=i===null?null:Number(i);break;case Object:case Array:try{e=JSON.parse(i)}catch{e=null}}return e}},kt=(i,t)=>!Ye(i,t),se={attribute:!0,type:String,converter:gt,reflect:!1,useDefault:!1,hasChanged:kt};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),x.litPropertyMetadata??(x.litPropertyMetadata=new WeakMap);let z=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??(this.l=[])).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,e=se){if(e.state&&(e.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((e=Object.create(e)).wrapped=!0),this.elementProperties.set(t,e),!e.noAccessor){const s=Symbol(),n=this.getPropertyDescriptor(t,s,e);n!==void 0&&Je(this.prototype,t,n)}}static getPropertyDescriptor(t,e,s){const{get:n,set:r}=Xe(this.prototype,t)??{get(){return this[e]},set(o){this[e]=o}};return{get:n,set(o){const a=n?.call(this);r?.call(this,o),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??se}static _$Ei(){if(this.hasOwnProperty(Z("elementProperties")))return;const t=ts(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(Z("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Z("properties"))){const e=this.properties,s=[...Ze(e),...Qe(e)];for(const n of s)this.createProperty(n,e[n])}const t=this[Symbol.metadata];if(t!==null){const e=litPropertyMetadata.get(t);if(e!==void 0)for(const[s,n]of e)this.elementProperties.set(s,n)}this._$Eh=new Map;for(const[e,s]of this.elementProperties){const n=this._$Eu(e,s);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const e=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const n of s)e.unshift(te(n))}else t!==void 0&&e.push(te(t));return e}static _$Eu(t,e){const s=e.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??(this._$EO=new Set)).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,e=this.constructor.elementProperties;for(const s of e.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Ke(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,e,s){this._$AK(t,s)}_$ET(t,e){const s=this.constructor.elementProperties.get(t),n=this.constructor._$Eu(t,s);if(n!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:gt).toAttribute(e,s.type);this._$Em=t,r==null?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(t,e){const s=this.constructor,n=s._$Eh.get(t);if(n!==void 0&&this._$Em!==n){const r=s.getPropertyOptions(n),o=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:gt;this._$Em=n;const a=o.fromAttribute(e,r.type);this[n]=a??this._$Ej?.get(n)??a,this._$Em=null}}requestUpdate(t,e,s,n=!1,r){if(t!==void 0){const o=this.constructor;if(n===!1&&(r=this[t]),s??(s=o.getPropertyOptions(t)),!((s.hasChanged??kt)(r,e)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(o._$Eu(t,s))))return;this.C(t,e,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,e,{useDefault:s,reflect:n,wrapped:r},o){s&&!(this._$Ej??(this._$Ej=new Map)).has(t)&&(this._$Ej.set(t,o??e??this[t]),r!==!0||o!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(e=void 0),this._$AL.set(t,e)),n===!0&&this._$Em!==t&&(this._$Eq??(this._$Eq=new Set)).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,r]of this._$Ep)this[n]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[n,r]of s){const{wrapped:o}=r,a=this[n];o!==!0||this._$AL.has(n)||a===void 0||this.C(n,void 0,r,a)}}let t=!1;const e=this._$AL;try{t=this.shouldUpdate(e),t?(this.willUpdate(e),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(e)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(e)}willUpdate(t){}_$AE(t){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&(this._$Eq=this._$Eq.forEach(e=>this._$ET(e,this[e]))),this._$EM()}updated(t){}firstUpdated(t){}};z.elementStyles=[],z.shadowRootOptions={mode:"open"},z[Z("elementProperties")]=new Map,z[Z("finalized")]=new Map,ss?.({ReactiveElement:z}),(x.reactiveElementVersions??(x.reactiveElementVersions=[])).push("2.1.2");const Q=globalThis,ie=i=>i,mt=Q.trustedTypes,ne=mt?mt.createPolicy("lit-html",{createHTML:i=>i}):void 0,re="$lit$",P=`lit$${Math.random().toFixed(9).slice(2)}$`,oe="?"+P,is=`<${oe}>`,N=document,tt=()=>N.createComment(""),et=i=>i===null||typeof i!="object"&&typeof i!="function",Ct=Array.isArray,ns=i=>Ct(i)||typeof i?.[Symbol.iterator]=="function",Tt=`[
|
|
2
|
+
\f\r]`,st=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ae=/-->/g,ce=/>/g,D=RegExp(`>|${Tt}(?:([^\\s"'>=/]+)(${Tt}*=${Tt}*(?:[^
|
|
3
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),he=/'/g,le=/"/g,de=/^(?:script|style|textarea|title)$/i,rs=i=>(t,...e)=>({_$litType$:i,strings:t,values:e}),u=rs(1),k=Symbol.for("lit-noChange"),m=Symbol.for("lit-nothing"),ue=new WeakMap,B=N.createTreeWalker(N,129);function pe(i,t){if(!Ct(i)||!i.hasOwnProperty("raw"))throw Error("invalid template strings array");return ne!==void 0?ne.createHTML(t):t}const os=(i,t)=>{const e=i.length-1,s=[];let n,r=t===2?"<svg>":t===3?"<math>":"",o=st;for(let a=0;a<e;a++){const c=i[a];let h,d,l=-1,p=0;for(;p<c.length&&(o.lastIndex=p,d=o.exec(c),d!==null);)p=o.lastIndex,o===st?d[1]==="!--"?o=ae:d[1]!==void 0?o=ce:d[2]!==void 0?(de.test(d[2])&&(n=RegExp("</"+d[2],"g")),o=D):d[3]!==void 0&&(o=D):o===D?d[0]===">"?(o=n??st,l=-1):d[1]===void 0?l=-2:(l=o.lastIndex-d[2].length,h=d[1],o=d[3]===void 0?D:d[3]==='"'?le:he):o===le||o===he?o=D:o===ae||o===ce?o=st:(o=D,n=void 0);const f=o===D&&i[a+1].startsWith("/>")?" ":"";r+=o===st?c+is:l>=0?(s.push(h),c.slice(0,l)+re+c.slice(l)+P+f):c+P+(l===-2?a:f)}return[pe(i,r+(i[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class it{constructor({strings:t,_$litType$:e},s){let n;this.parts=[];let r=0,o=0;const a=t.length-1,c=this.parts,[h,d]=os(t,e);if(this.el=it.createElement(h,s),B.currentNode=this.el.content,e===2||e===3){const l=this.el.content.firstChild;l.replaceWith(...l.childNodes)}for(;(n=B.nextNode())!==null&&c.length<a;){if(n.nodeType===1){if(n.hasAttributes())for(const l of n.getAttributeNames())if(l.endsWith(re)){const p=d[o++],f=n.getAttribute(l).split(P),g=/([.?@])?(.*)/.exec(p);c.push({type:1,index:r,name:g[2],strings:f,ctor:g[1]==="."?cs:g[1]==="?"?hs:g[1]==="@"?ls:_t}),n.removeAttribute(l)}else l.startsWith(P)&&(c.push({type:6,index:r}),n.removeAttribute(l));if(de.test(n.tagName)){const l=n.textContent.split(P),p=l.length-1;if(p>0){n.textContent=mt?mt.emptyScript:"";for(let f=0;f<p;f++)n.append(l[f],tt()),B.nextNode(),c.push({type:2,index:++r});n.append(l[p],tt())}}}else if(n.nodeType===8)if(n.data===oe)c.push({type:2,index:r});else{let l=-1;for(;(l=n.data.indexOf(P,l+1))!==-1;)c.push({type:7,index:r}),l+=P.length-1}r++}}static createElement(t,e){const s=N.createElement("template");return s.innerHTML=t,s}}function G(i,t,e=i,s){if(t===k)return t;let n=s!==void 0?e._$Co?.[s]:e._$Cl;const r=et(t)?void 0:t._$litDirective$;return n?.constructor!==r&&(n?._$AO?.(!1),r===void 0?n=void 0:(n=new r(i),n._$AT(i,e,s)),s!==void 0?(e._$Co??(e._$Co=[]))[s]=n:e._$Cl=n),n!==void 0&&(t=G(i,n._$AS(i,t.values),n,s)),t}class as{constructor(t,e){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=e}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:e},parts:s}=this._$AD,n=(t?.creationScope??N).importNode(e,!0);B.currentNode=n;let r=B.nextNode(),o=0,a=0,c=s[0];for(;c!==void 0;){if(o===c.index){let h;c.type===2?h=new K(r,r.nextSibling,this,t):c.type===1?h=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(h=new ds(r,this,t)),this._$AV.push(h),c=s[++a]}o!==c?.index&&(r=B.nextNode(),o++)}return B.currentNode=N,n}p(t){let e=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,e),e+=s.strings.length-2):s._$AI(t[e])),e++}}class K{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,e,s,n){this.type=2,this._$AH=m,this._$AN=void 0,this._$AA=t,this._$AB=e,this._$AM=s,this.options=n,this._$Cv=n?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const e=this._$AM;return e!==void 0&&t?.nodeType===11&&(t=e.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,e=this){t=G(this,t,e),et(t)?t===m||t==null||t===""?(this._$AH!==m&&this._$AR(),this._$AH=m):t!==this._$AH&&t!==k&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):ns(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==m&&et(this._$AH)?this._$AA.nextSibling.data=t:this.T(N.createTextNode(t)),this._$AH=t}$(t){const{values:e,_$litType$:s}=t,n=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=it.createElement(pe(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===n)this._$AH.p(e);else{const r=new as(n,this),o=r.u(this.options);r.p(e),this.T(o),this._$AH=r}}_$AC(t){let e=ue.get(t.strings);return e===void 0&&ue.set(t.strings,e=new it(t)),e}k(t){Ct(this._$AH)||(this._$AH=[],this._$AR());const e=this._$AH;let s,n=0;for(const r of t)n===e.length?e.push(s=new K(this.O(tt()),this.O(tt()),this,this.options)):s=e[n],s._$AI(r),n++;n<e.length&&(this._$AR(s&&s._$AB.nextSibling,n),e.length=n)}_$AR(t=this._$AA.nextSibling,e){for(this._$AP?.(!1,!0,e);t!==this._$AB;){const s=ie(t).nextSibling;ie(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}class _t{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,s,n,r){this.type=1,this._$AH=m,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=m}_$AI(t,e=this,s,n){const r=this.strings;let o=!1;if(r===void 0)t=G(this,t,e,0),o=!et(t)||t!==this._$AH&&t!==k,o&&(this._$AH=t);else{const a=t;let c,h;for(t=r[0],c=0;c<r.length-1;c++)h=G(this,a[s+c],e,c),h===k&&(h=this._$AH[c]),o||(o=!et(h)||h!==this._$AH[c]),h===m?t=m:t!==m&&(t+=(h??"")+r[c+1]),this._$AH[c]=h}o&&!n&&this.j(t)}j(t){t===m?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}}class cs extends _t{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===m?void 0:t}}class hs extends _t{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==m)}}class ls extends _t{constructor(t,e,s,n,r){super(t,e,s,n,r),this.type=5}_$AI(t,e=this){if((t=G(this,t,e,0)??m)===k)return;const s=this._$AH,n=t===m&&s!==m||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==m&&(s===m||n);n&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}}class ds{constructor(t,e,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=e,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){G(this,t)}}const us={I:K},ps=Q.litHtmlPolyfillSupport;ps?.(it,K),(Q.litHtmlVersions??(Q.litHtmlVersions=[])).push("3.3.3");const fs=(i,t,e)=>{const s=e?.renderBefore??t;let n=s._$litPart$;if(n===void 0){const r=e?.renderBefore??null;s._$litPart$=n=new K(t.insertBefore(tt(),r),r,void 0,e??{})}return n._$AI(i),n};const nt=globalThis;let Y=class extends z{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var e;const t=super.createRenderRoot();return(e=this.renderOptions).renderBefore??(e.renderBefore=t.firstChild),t}update(t){const e=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=fs(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return k}};Y._$litElement$=!0,Y.finalized=!0,nt.litElementHydrateSupport?.({LitElement:Y});const gs=nt.litElementPolyfillSupport;gs?.({LitElement:Y}),(nt.litElementVersions??(nt.litElementVersions=[])).push("4.2.2");const ms={attribute:!0,type:String,converter:gt,reflect:!1,hasChanged:kt},_s=(i=ms,t,e)=>{const{kind:s,metadata:n}=e;let r=globalThis.litPropertyMetadata.get(n);if(r===void 0&&globalThis.litPropertyMetadata.set(n,r=new Map),s==="setter"&&((i=Object.create(i)).wrapped=!0),r.set(e.name,i),s==="accessor"){const{name:o}=e;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(o,c,i,!0,a)},init(a){return a!==void 0&&this.C(o,void 0,i,a),a}}}if(s==="setter"){const{name:o}=e;return function(a){const c=this[o];t.call(this,a),this.requestUpdate(o,c,i,!0,a)}}throw Error("Unsupported decorator location: "+s)};function _(i){return(t,e)=>typeof e=="object"?_s(i,t,e):((s,n,r)=>{const o=n.hasOwnProperty(r);return n.constructor.createProperty(r,s),o?Object.getOwnPropertyDescriptor(n,r):void 0})(i,t,e)}function C(i){return _({...i,state:!0,attribute:!1})}const ys="0.1.0",bs=new Set(["origin_not_allowed","agent_inactive","agent_archived","agent_not_found","session_not_found","session_closed","invalid_customer_id","invalid_token","session_unavailable","stream_unavailable","token_failed","rate_limited","network","interaction_not_pending","interaction_suspended","invalid_interaction","unknown"]),vs=new Set(["rate_limited","network","session_unavailable","stream_unavailable","token_failed"]);function v(i,t){const e=i&&bs.has(i)?i:"unknown";return{code:e,message:t||e,retryable:vs.has(e)}}class S extends Error{constructor(t,e){super(t.message),this.error=t,this.status=e,this.name="ChatRequestError"}}const $s=3e5;function fe(i,t=Date.now()){return typeof i!="number"||!Number.isFinite(i)?t+$s:i<1e12?i*1e3:i}class ws{constructor(t,e=(...s)=>globalThis.fetch.bind(globalThis)(...s)){this.fetchImpl=e,this.base=t.replace(/\/+$/,"")}resolveUrl(t){return`${this.base}${t}`}bootstrap(t,e,s){const n=`?customer_id=${encodeURIComponent(e)}`;return this.request(`/public/chat/agents/${encodeURIComponent(t)}/bootstrap${n}`,{signal:s})}createSession(t,e){return this.request(`/public/chat/agents/${encodeURIComponent(t)}/session`,{method:"POST",body:JSON.stringify({customer_id:e})})}async mintPublicToken(t){const e=await this.request(`/public/chat/session/${encodeURIComponent(t)}/ws_token`,{method:"POST",body:"{}"});if(!e?.token||!e?.ws_url)throw new S(v("stream_unavailable"),200);return{token:e.token,wsUrl:e.ws_url,expiresAt:fe(e.expires_at)}}snapshot(t,e){return this.request(`/public/chat/session/${encodeURIComponent(t)}/snapshot`,{headers:{Authorization:`Bearer ${e}`}})}async request(t,e={}){let s;try{const r=this.fetchImpl,o={...e.headers};e.body!==void 0&&(o["Content-Type"]="application/json"),s=await r(this.resolveUrl(t),{...e,credentials:"omit",headers:o})}catch(r){throw r?.name==="AbortError"?r:new S(v("network","Network error"),0)}let n=null;try{n=await s.json()}catch{n=null}if(!s.ok||n?.success===!1){const r=v(typeof n?.error=="string"?n.error:void 0,typeof n?.message=="string"?n.message:void 0);if(typeof n?.origin=="string"&&(r.origin=n.origin),s.status===429){r.code="rate_limited",r.retryable=!0;const o=Number(s.headers.get("Retry-After")),a=Number(n?.retry_after),c=Number.isFinite(o)&&o>0?o:a;Number.isFinite(c)&&c>0&&(r.retryAfterSeconds=c)}throw new S(r,s.status)}return n?.data??n}}const It=[{tool_type:"ui_buttons",schema_version:1},{tool_type:"ui_buttons",schema_version:2},{tool_type:"ui_carousel",schema_version:1},{tool_type:"ui_date_picker",schema_version:1}],Ss=65536,As=2e3,ks=8192,ge=2048,Et=/^[A-Za-z0-9_-]{1,64}$/,T=i=>!!i&&typeof i=="object"&&!Array.isArray(i),O=(i,t)=>Object.keys(i).every(e=>t.includes(e)),Cs=i=>[...i].length,me=i=>new TextEncoder().encode(i).length,Ts=i=>[...i].some(t=>{const e=t.codePointAt(0)??0;return e===127||e<32&&e!==9&&e!==10&&e!==13}),Is=i=>[...i].some(t=>{const e=t.codePointAt(0)??0;return e<=32||e===127}),$=(i,t,e=!1)=>typeof i=="string"&&Cs(i)<=t&&!Ts(i)&&(!e||i.trim().length>0),xt=i=>Array.isArray(i)?i.map(xt):T(i)?Object.fromEntries(Object.keys(i).sort().map(t=>[t,xt(i[t])])):i,Pt=i=>{try{return me(JSON.stringify(xt(i)))<=Ss}catch{return!1}};function _e(i){return typeof i=="string"&&/^\/public\/chat\/images\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/(?:0|[1-9][0-9]*)$/i.test(i)}function Es(i){if(typeof i!="string"||i.length===0||i.length>ge||Is(i))return!1;try{const t=new URL(i),e=t.hostname.toLowerCase();return t.protocol!=="https:"||t.username||t.password||t.hash||t.port||!e||e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal")||e.startsWith("[")||/^\d{1,3}(?:\.\d{1,3}){3}$/.test(e)?!1:t.toString().length<=ge}catch{return!1}}function yt(i,t){if(!T(i)||!O(i,["label","description","options"])||!$(i.label,160,!0)||"description"in i&&i.description!==void 0&&!$(i.description,240)||!Array.isArray(i.options)||i.options.length===0||t!==void 0)return!1;const e=new Set;let s=0;for(const n of i.options){if(!T(n)||!O(n,["id","label","description","allow_input","input_placeholder"])||typeof n.id!="string"||!Et.test(n.id)||e.has(n.id)||!$(n.label,80,!0)||"description"in n&&n.description!==void 0&&!$(n.description,240))return!1;const r=n.allow_input===!0;if("allow_input"in n&&!r||"input_placeholder"in n&&(!r||!$(n.input_placeholder,160,!0))||(r&&(s+=1),s>1))return!1;e.add(n.id)}return Pt(i)}function ye(i,t){return yt(i,t)&&i.options.every(e=>!Object.prototype.hasOwnProperty.call(e,"allow_input")&&!Object.prototype.hasOwnProperty.call(e,"input_placeholder"))}function be(i,t,e=!1){if(!T(i)||!O(i,["label","description","items"])||!$(i.label,160,!0)||"description"in i&&i.description!==void 0&&!$(i.description,240)||!Array.isArray(i.items)||i.items.length===0||t!==void 0)return!1;const s=new Set;for(const n of i.items){if(!T(n)||!O(n,["id","title","description","image","action_label"])||typeof n.id!="string"||!Et.test(n.id)||s.has(n.id)||!$(n.title,120,!0)||"description"in n&&n.description!==void 0&&!$(n.description,500)||"action_label"in n&&n.action_label!==void 0&&!$(n.action_label,80,!0)||"image"in n&&n.image!==void 0&&(!T(n.image)||!O(n.image,["url","alt"])||!(Es(n.image.url)||e&&_e(n.image.url))||!$(n.image.alt,240,!0)))return!1;s.add(n.id)}return Pt(i)}function R(i){if(typeof i!="string"||!/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(i))return!1;const t=Number(i.slice(0,4)),e=Number(i.slice(5,7)),s=Number(i.slice(8,10));if(t<1||t>9999||e<1||e>12||s<1)return!1;const r=[31,t%4===0&&(t%100!==0||t%400===0)?29:28,31,30,31,30,31,31,30,31,30,31];return s<=r[e-1]}function Ot(i){return!T(i)||!O(i,["label","description","min_date","max_date","confirm_label","selection_mode"])||!$(i.label,160,!0)||!["single","range"].includes(String(i.selection_mode))||"description"in i&&i.description!==void 0&&!$(i.description,240)||"confirm_label"in i&&i.confirm_label!==void 0&&!$(i.confirm_label,80,!0)||"min_date"in i&&i.min_date!==void 0&&!R(i.min_date)||"max_date"in i&&i.max_date!==void 0&&!R(i.max_date)||typeof i.min_date=="string"&&typeof i.max_date=="string"&&i.min_date>i.max_date?!1:Pt(i)}function xs(i,t){return i.tool_type==="ui_buttons"&&i.schema_version===1?ye(t):i.tool_type==="ui_buttons"&&i.schema_version===2?yt(t):i.tool_type==="ui_carousel"&&i.schema_version===1?be(t,void 0,!0):i.tool_type==="ui_date_picker"&&i.schema_version===1?Ot(t):!1}function ve(i,t){return!T(t)||!O(t,["kind","value"])||Object.keys(t).length!==2?!1:t.kind==="date_range"?i.tool_type==="ui_date_picker"&&i.schema_version===1&&T(t.value)&&O(t.value,["start_date","end_date"])&&Object.keys(t.value).length===2&&R(t.value.start_date)&&R(t.value.end_date)&&t.value.start_date<t.value.end_date:typeof t.value!="string"?!1:t.kind==="selection"?(i.tool_type==="ui_buttons"||i.tool_type==="ui_carousel")&&Et.test(t.value):t.kind==="text"?i.tool_type==="ui_buttons"&&i.schema_version===2&&t.value===t.value.trim()&&$(t.value,As,!0)&&me(t.value)<=ks:t.kind==="date"?i.tool_type==="ui_date_picker"&&i.schema_version===1&&R(t.value):!1}const Rt=i=>i!==null&&typeof i=="object"&&!Array.isArray(i),Ps=new Set(["preparing","pending","accepted","resumed","cancelled","expired"]);function J(i){if(!Rt(i)||i.type!=="interaction"||typeof i.id!="string"||!i.id||i.role!=="assistant"||typeof i.content!="string"||typeof i.interaction_id!="string"||!i.interaction_id||typeof i.tool_type!="string"||!Number.isSafeInteger(i.schema_version)||Number(i.schema_version)<1||!Number.isSafeInteger(i.interaction_revision)||Number(i.interaction_revision)<1||!Ps.has(String(i.interaction_status))||!Rt(i.presentation))return null;const t={tool_type:i.tool_type,schema_version:Number(i.schema_version)},e=i.response_payload;return e!=null&&!ve(t,e)?null:{id:i.id,type:"interaction",role:"assistant",content:i.content,interaction_id:i.interaction_id,tool_type:i.tool_type,schema_version:Number(i.schema_version),presentation:i.presentation,interaction_status:i.interaction_status,interaction_revision:Number(i.interaction_revision),...typeof i.created_at=="string"?{created_at:i.created_at}:{},...typeof i.selected_option_id=="string"?{selected_option_id:i.selected_option_id}:{},...e!==void 0?{response_payload:e}:{}}}function I(i){if(!Rt(i)||typeof i.id!="string"&&typeof i.id!="number"||typeof i.content!="string"||!["assistant","user","operator","system"].includes(String(i.role)))return null;const t=J({...i,id:String(i.id)});return{id:String(i.id),content:i.content,type:i.type==="interaction"?"interaction":"message",ts:typeof i.created_at=="string"?i.created_at:typeof i.ts=="string"?i.ts:new Date().toISOString(),...t??{},role:i.role}}function Ut(i){return typeof i=="string"&&/^\d+$/.test(i)?i.replace(/^0+(?=\d)/,""):null}function X(i,t){return i.length===t.length?i===t?0:i>t?1:-1:i.length>t.length?1:-1}function Mt(i,t){const e=[...i];for(const s of t){const n=e.findIndex(r=>r.id===s.id||s.interaction_id&&r.interaction_id===s.interaction_id);if(n<0)e.push(s);else{const r=e[n],o=c=>c.interaction_status==="preparing"?0:c.interaction_status==="pending"?1:c.interaction_status==="accepted"?2:3;!(s.interaction_revision===r.interaction_revision&&o(s)<o(r))&&(!s.interaction_revision||!r.interaction_revision||s.interaction_revision>=r.interaction_revision)&&(e[n]={...r,...s})}}return e}const Os=new Set(["user","ai","assistant","operator","support","system"]);function Nt(i){if(!i||typeof i!="object")return null;const t=i,e=typeof t.id=="number"?String(t.id):t.id;if(typeof e!="string"||e===""||typeof t.content!="string"||typeof t.role!="string"||!Os.has(t.role))return null;const s={id:e,role:t.role,content:t.content};return typeof t.created_at=="string"&&(s.created_at=t.created_at),(t.type==="interaction"||t.type==="message")&&(s.type=t.type),s}const rt=i=>["pending","accepted"].includes(i.interaction_status);class Rs{constructor(t){this.host=t,this._active=null,this._cursor="0",this._pending=!1,this._error=null,this.operations=new Map,this.operation=null,this.generation=0,this.refreshInFlight=!1,this.recoveryCursor=null}get active(){return this._active}get cursor(){return this._cursor}get pending(){return this._pending}get error(){return this._error}setActive(t){this._active=t,this.host.onChange()}setCursor(t){this._cursor=t,this.host.onChange()}setSelectionPending(t){this._pending=t,this.host.onChange()}setInteractionError(t){this._error=t,this.host.onChange()}setRows(t){this.host.updateItems(e=>{let s=e.length;for(;s>0&&e[s-1].kind!=="divider";)s-=1;const n=e.slice(s);return[...e.slice(0,s),...Ms(t(Us(n)),n)]})}reset(){this.generation+=1,this.refreshInFlight=!1,this.recoveryCursor=null,this.setActive(null),this._cursor="0",this.setCursor("0"),this.operations.clear(),this.operation=null,this.setSelectionPending(!1),this.setInteractionError(null)}reject(t,e){this.operations.delete(t.interactionId),this.operations.size===0&&(this.recoveryCursor=null),this.operation===t&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(e);const s=this._active,n=s?.interaction_id===t.interactionId&&s.interaction_revision<=t.original.interaction_revision;n&&this.setActive(t.original),this.setRows(r=>r.filter(o=>o.id!==t.messageId).map(o=>n&&o.interaction_id===t.interactionId?I(t.original):o))}mergeProjection(t,e){const s=I(e),n=t&&this.operations.get(t.interaction_id);n&&s?.role==="user"&&(this.operations.delete(n.interactionId),this.operations.size===0&&(this.recoveryCursor=null),this.operation===n&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(null));const r=[t&&I(t),s?.role==="user"?s:null].filter(o=>o!==null);this.setRows(o=>{const a=n&&s?.role==="user"&&o.some(c=>c.id===n.messageId)?o.flatMap(c=>c.id===n.messageId?[s]:c.id===s.id?[]:[c]):o;return Mt(a,r)})}refreshMissingOutcome(t){if(this.operations.size===0){this.recoveryCursor=null;return}if((this.recoveryCursor===null||X(t,this.recoveryCursor)>0)&&(this.recoveryCursor=t),this.refreshInFlight)return;const e=this.recoveryCursor,s=[...this.operations.values()],n=a=>this.operations.get(a.interactionId)===a,r=this.generation,o=this.host.sessionId();this.refreshInFlight=!0,this.setSelectionPending(!0),this.host.refreshSnapshot().then(a=>{if(!a)throw new Error("Snapshot unavailable");if(r!==this.generation||o!==this.host.sessionId()||a.session!==null&&a.session.id!==o||!s.some(n))return;const c=Ut(a.interaction_cursor);if(c===null||X(c,this.recoveryCursor??e)<0||X(c,this._cursor)<0)return;const h=a.active_interaction===null?null:J(a.active_interaction);if(a.active_interaction!==null&&(!h||!rt(h)))return;const d=a.messages.map(I).filter(g=>g!==null),l=I(a.interaction_response_message);h&&d.push(I(h)),l?.role==="user"&&d.push(l);const p=s.filter(g=>n(g)&&(h?.interaction_id!==g.interactionId||h.interaction_status==="accepted"&&l?.role==="user")),f=new Set(p.map(g=>g.messageId));this.setRows(g=>Mt(g.filter(w=>!f.has(w.id)),d).sort((w,pt)=>Date.parse(w.ts)-Date.parse(pt.ts)||0)),p.forEach(g=>this.operations.delete(g.interactionId)),this.operation&&p.includes(this.operation)&&(this.operation=null),this._cursor=c,this.recoveryCursor=null,this.setCursor(c),this.setActive(h),this.setSelectionPending(this.operation!==null),this.setInteractionError(null)}).catch(()=>{r===this.generation&&s.some(n)&&this.setInteractionError({code:"network",message:"Reconnecting to confirm your selection…"})}).finally(()=>{if(r===this.generation){if(this.refreshInFlight=!1,this.operations.size===0){this.recoveryCursor=null;return}const a=this.recoveryCursor;a!==null&&X(a,e)>0&&this.refreshMissingOutcome(a)}})}hasMissingOutcome(t){return[...this.operations.values()].some(e=>!t||e.interactionId!==t.interaction_id)}applySnapshot(t){const e=Ut(t.interaction_cursor);if(e===null||!Object.prototype.hasOwnProperty.call(t,"active_interaction"))return;const s=X(e,this._cursor);if(s<0)return;const n=t.active_interaction===null?null:J(t.active_interaction);if(!(t.active_interaction!==null&&(!n||!rt(n)))){if(s>0&&this.hasMissingOutcome(n)){this.refreshMissingOutcome(e);return}s===0&&(this.operation||n&&this.operations.has(n.interaction_id)||n===null&&this._active)||(this._cursor=e,this.setCursor(e),this.setActive(n),this.mergeProjection(n,t.interaction_response_message),(!n||this.operation?.interactionId!==n.interaction_id)&&(this.operation=null,this.setSelectionPending(!1)))}}applyEvent(t){if(!["interaction_published","interaction_updated","interaction_closed"].includes(t.type))return!1;if(t.session_id&&t.session_id!==this.host.sessionId())return!0;const e=Ut(t.payload.interaction_cursor),s=J(t.payload);return!s||s.interaction_status==="preparing"||e===null||X(e,this._cursor)<=0?!0:this.hasMissingOutcome(s)||!rt(s)&&this.operations.has(s.interaction_id)&&!I(t.payload.interaction_response_message)?(this.refreshMissingOutcome(e),!0):(this._cursor=e,this.setCursor(e),this.mergeProjection(s,t.payload.interaction_response_message),rt(s)?this.setActive(s):this._active?.interaction_id===s.interaction_id&&this.setActive(null),this.operation&&(this.operation.interactionId!==s.interaction_id||!rt(s))&&(this.operation=null,this.setSelectionPending(!1)),!0)}handleWriteResult(t){const e=t,s=[...this.operations.values()].find(n=>n.messageId===e.message_id);if(!s)return!1;if(e.error||["refused","failed","error","busy"].includes(String(e.state))){const n=["interaction_not_pending","interaction_suspended","invalid_interaction","network"].includes(String(e.error))?e.error:"invalid_interaction";this.reject(s,{code:n,message:String(e.error||e.reason||"The selection was not accepted. Please try again.")})}else s.acknowledged=!0,this.operation===s&&(this.operation=null),this.setSelectionPending(!1),this.setInteractionError(null);return!0}respond(t,e){const s=this._active;if(!this.host.sessionId()||this.host.humanConnected()||this.operation||!s||s.interaction_id!==t||s.interaction_status!=="pending"||!It.some(h=>h.tool_type===s.tool_type&&h.schema_version===s.schema_version)||!ve(s,e))return!1;const n=s.tool_type==="ui_buttons"&&s.schema_version===1;let r=null;if(n&&e.kind==="selection"&&ye(s.presentation))r=s.presentation.options.find(h=>h.id===e.value)?.label??null;else if(!n&&e.kind==="text"&&s.tool_type==="ui_buttons"&&yt(s.presentation))r=e.value;else if(!n&&e.kind==="selection"&&s.tool_type==="ui_buttons"&&yt(s.presentation))r=s.presentation.options.find(h=>h.id===e.value)?.label??null;else if(e.kind==="selection"&&s.tool_type==="ui_carousel"&&be(s.presentation,void 0,!0))r=s.presentation.items.find(h=>h.id===e.value)?.title??null;else if(e.kind==="date"&&s.tool_type==="ui_date_picker"&&s.schema_version===1&&Ot(s.presentation)&&s.presentation.selection_mode==="single")(!s.presentation.min_date||e.value>=s.presentation.min_date)&&(!s.presentation.max_date||e.value<=s.presentation.max_date)&&(r=e.value);else if(e.kind==="date_range"&&s.tool_type==="ui_date_picker"&&s.schema_version===1&&Ot(s.presentation)&&s.presentation.selection_mode==="range"){const{start_date:h,end_date:d}=e.value;(!s.presentation.min_date||h>=s.presentation.min_date)&&(!s.presentation.max_date||d<=s.presentation.max_date)&&(r=`${h} to ${d}`)}if(!r)return!1;const o=this.host.newId(),a={interactionId:t,messageId:o,original:s,acknowledged:!1,sent:!1,frame:{type:"interaction_response",interaction_id:t,...n?{option_id:e.value}:{response:e},message_id:o,idempotency_key:this.host.newId(),supported_interactions:It}};this.operations.set(t,a),this.operation=a,this.setSelectionPending(!0),this.setInteractionError(null);const c={...s,interaction_status:"accepted",...n?{selected_option_id:e.value}:{response_payload:e}};return this.setActive(c),this.setRows(h=>Mt(h,[I(c),{id:o,type:"message",role:"user",content:r,ts:new Date().toISOString(),local:!0}])),a.sent=this.host.sendFrame(a.frame),!0}onConnectionOpen(){const t=this.operation;t&&!t.acknowledged&&!this.host.humanConnected()&&(t.sent=this.host.sendFrame(t.frame))}}function Us(i){const t=[];for(const e of i)e.kind==="interaction"?t.push(I(e.interaction)):e.kind==="message"&&t.push({id:e.serverId??e.id,type:"message",role:e.role==="human"?"operator":e.role,content:e.content,ts:e.createdAt});return t}function Ms(i,t){const e=new Map;for(const n of t)n.kind==="message"&&(e.set(n.id,n),n.serverId&&e.set(n.serverId,n));const s=[];for(const n of i){if(n.type==="interaction"&&n.interaction_id){const o=J(n);o&&s.push({kind:"interaction",id:n.interaction_id,interaction:o});continue}if(n.role==="system")continue;const r=e.get(n.id);if(r){s.push(r.content===n.content?r:{...r,content:n.content});continue}if(n.local){s.push({kind:"message",id:n.id,role:"user",content:n.content,createdAt:n.ts,status:"sending"});continue}s.push({kind:"message",id:`srv:${n.id}`,serverId:n.id,role:n.role==="operator"?"human":n.role,content:n.content,createdAt:n.ts,status:"sent"})}return s}function Ns(i){let t=i;if(typeof i=="string")try{t=JSON.parse(i)}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;const e=t;if(typeof e.type!="string")return null;const s=e.payload&&typeof e.payload=="object"&&!Array.isArray(e.payload)?e.payload:{};return{...e,type:e.type,payload:s}}const Ds=25e3,Bs=6e4,js=3e4,$e=6e4,ot=[1e3,2e3,4e3,8e3,16e3,3e4],Dt=1e4,Fs=4e3,Ls=2,we=new Set(["invalid_token","session_not_found","session_closed","origin_not_allowed","agent_archived","agent_not_found"]);function Se(){return{isVisible:()=>typeof document>"u"||document.visibilityState!=="hidden",onVisible:i=>{const t=()=>{document.visibilityState!=="hidden"&&i()};return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))},onOnline:i=>typeof window>"u"?()=>{}:(window.addEventListener("online",i),()=>window.removeEventListener("online",i))}}function at(i){i&&(i.onopen=null,i.onmessage=null,i.onclose=null,i.onerror=null)}class Hs{constructor(t){this.opts=t,this.socket=null,this.next=null,this.stopped=!1,this.started=!1,this.everOpened=!1,this.failures=0,this.authCloses=0,this.epoch=0,this.rotating=!1,this.pingSupported=!0,this.lastInbound=0,this.lastPingSentAt=0,this.expiresAt=0,this.timers=new Set,this.pingTimer=null,this.waitingForPage=new Set,this.page=t.page??Se(),this.WS=t.WebSocketImpl??WebSocket,this.random=t.random??Math.random}get isOpen(){return!this.stopped&&this.socket?.readyState===1}start(){this.started||this.stopped||(this.started=!0,this.opts.onStatus("connecting"),this.connect())}send(t){return this.isOpen?(this.socket.send(JSON.stringify(t)),!0):!1}stop(){this.stopped=!0,this.epoch+=1,this.clearTimers(),this.stopPings(),this.waitingForPage.forEach(t=>t()),this.waitingForPage.clear(),this.abandon(this.next),this.next=null,this.abandon(this.socket),this.socket=null}abandon(t){at(t);try{t?.close(1e3,"client-stop")}catch{}}recoveringStatus(){return this.everOpened?"recovering":"connecting"}urlFor(t){const e=t.wsUrl.includes("?")?"&":"?";return`${t.wsUrl}${e}token=${encodeURIComponent(t.token)}&sdk=${encodeURIComponent(this.opts.sdkVersion)}`}async connect(){if(this.stopped)return;const t=this.epoch;let e;try{e=await this.opts.mint()}catch(s){if(this.stopped||t!==this.epoch)return;this.handleMintFailure(s);return}if(!(this.stopped||t!==this.epoch))try{this.openSocket(e,!1)}catch(s){this.handleMintFailure(s)}}openSocket(t,e){const s=new this.WS(this.urlFor(t));e?this.next=s:(this.socket=s,this.expiresAt=t.expiresAt),s.onopen=()=>{this.stopped||(e?this.next===s&&this.swapIn(s,t.expiresAt):this.socket===s&&this.handleOpen())},s.onmessage=n=>{this.socket===s&&this.handleMessage(n.data)},s.onclose=n=>{if(!this.stopped){if(this.next===s){at(s),this.next=null,this.later(Dt,()=>this.whenVisible(()=>{this.rotate()}));return}this.socket===s&&this.handleClose(n.code,n.reason)}}}handleOpen(){const t=this.everOpened;this.everOpened=!0,this.failures=0,this.authCloses=0,this.pingSupported=!0,this.lastInbound=Date.now(),this.opts.onStatus("open"),!this.stopped&&(this.startPings(),this.scheduleRotation(),!this.stopped&&(this.opts.onOpen(),t&&!this.stopped&&this.opts.onReconnected()))}swapIn(t,e){const s=this.socket;this.next=null,this.socket=t,this.expiresAt=e,this.failures=0,this.authCloses=0,this.pingSupported=!0,at(s);try{s?.close(Fs,"token-refresh")}catch{}this.clearTimers(),this.lastInbound=Date.now(),this.startPings(),this.scheduleRotation(),this.opts.onOpen(),this.stopped||this.opts.onReconnected()}handleMessage(t){if(this.stopped)return;this.lastInbound=Date.now();const e=Ns(t);if(e){if(e.type==="ws_write_result"&&e.payload.error==="invalid_input_type"&&!e.payload.message_id){this.pingSupported=!1,this.stopPings();return}this.opts.onFrame(e)}}handleClose(t,e){if(!this.stopped){if(this.epoch+=1,at(this.socket),this.socket=null,this.abandon(this.next),this.next=null,this.rotating=!1,this.stopPings(),this.clearTimers(),this.clearPageListeners(),t===4401){if(this.authCloses+=1,this.authCloses>Ls){this.opts.onError(v("invalid_token")),this.scheduleBackoff();return}this.opts.onStatus(this.recoveringStatus()),this.whenVisible(()=>this.reconnectNow());return}if(t===1008&&e==="agent_inactive"){this.opts.onError(v("agent_inactive")),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later($e,()=>this.reconnectNow());return}if(t===1008){this.terminate(e||"policy");return}this.scheduleBackoff()}}handleMintFailure(t){const e=t instanceof S?t.error:v("network");if(e.code==="agent_inactive"){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later($e,()=>this.reconnectNow());return}if(we.has(e.code)){this.terminate(e.code);return}if(e.code==="rate_limited"&&e.retryAfterSeconds){this.opts.onError(e),this.stopped||this.opts.onStatus(this.recoveringStatus()),this.later(e.retryAfterSeconds*1e3,()=>this.reconnectNow());return}this.scheduleBackoff()}reconnectNow(){this.stopped||(this.opts.onStatus(this.recoveringStatus()),this.connect())}scheduleBackoff(){if(this.stopped)return;const t=Math.min(this.failures,ot.length-1);if(this.failures+=1,this.failures>ot.length){this.opts.onStatus("offline"),this.retryWhenReachable();return}this.opts.onStatus(this.recoveringStatus());const e=Math.round(ot[t]*(.8+.4*this.random()));this.later(e,()=>{this.connect()})}retryWhenReachable(){if(this.stopped)return;let t=!1;const e=()=>{clearTimeout(o),this.timers.delete(o),n(),r(),this.waitingForPage.delete(e)},s=()=>{t||this.stopped||(t=!0,e(),this.reconnectNow())},n=this.page.onVisible(s),r=this.page.onOnline(s),o=setTimeout(()=>{this.stopped||s()},ot[ot.length-1]);this.timers.add(o),this.waitingForPage.add(e)}whenVisible(t){if(this.stopped)return;if(this.page.isVisible()){t();return}let e=!1;const s=this.page.onVisible(()=>{e||this.stopped||!this.page.isVisible()||(e=!0,s(),this.waitingForPage.delete(s),t())});this.waitingForPage.add(s)}startPings(){this.stopPings(),this.lastPingSentAt=0,this.pingTimer=setInterval(()=>{if(this.stopped||!this.isOpen||!this.pingSupported)return;const t=Date.now(),e=this.lastPingSentAt>this.lastInbound;if(this.page.isVisible()&&e&&t-this.lastInbound>=Bs){this.declareDead();return}this.send({type:"ping"})&&(this.lastPingSentAt=t)},Ds)}declareDead(){const t=this.socket;if(t){at(t);try{t.close(4001,"silent")}catch{}this.handleClose(4001,"silent")}}stopPings(){this.pingTimer!==null&&clearInterval(this.pingTimer),this.pingTimer=null}scheduleRotation(){const t=Math.max(5e3,this.expiresAt-Date.now()-js);this.later(t,()=>this.whenVisible(()=>{this.rotate()}))}async rotate(){if(this.stopped||this.rotating||!this.isOpen||this.next)return;this.rotating=!0;const t=this.epoch;let e;try{e=await this.opts.mint()}catch(s){if(this.stopped||t!==this.epoch)return;this.rotating=!1;const n=s instanceof S?s.error:v("network");if(we.has(n.code)){this.terminate(n.code);return}const r=n.retryAfterSeconds?n.retryAfterSeconds*1e3:Dt;this.later(r,()=>this.whenVisible(()=>{this.rotate()}));return}if(!(this.stopped||t!==this.epoch)){this.rotating=!1;try{this.openSocket(e,!0)}catch{this.later(Dt,()=>this.whenVisible(()=>{this.rotate()}))}}}terminate(t){this.stop(),this.opts.onClosed(t)}later(t,e){if(this.stopped)return;const s=setTimeout(()=>{this.timers.delete(s),this.stopped||e()},t);this.timers.add(s)}clearPageListeners(){this.waitingForPage.forEach(t=>t()),this.waitingForPage.clear()}clearTimers(){this.timers.forEach(clearTimeout),this.timers.clear()}}const Bt="osvi.chat.visitor",Vs=/^web:[0-9a-f]{32}$/;function qs(){const i=new Map;return{get:t=>i.get(t)??null,set:(t,e)=>{i.set(t,e)},remove:t=>{i.delete(t)}}}function Ws(){const i=qs();let t=!1;const e=(s,n)=>{if(t)return n();try{return s()}catch{return t=!0,n()}};return{get:s=>e(()=>window.localStorage.getItem(s),()=>i.get(s)),set:(s,n)=>e(()=>window.localStorage.setItem(s,n),()=>i.set(s,n)),remove:s=>e(()=>window.localStorage.removeItem(s),()=>i.remove(s))}}const Ae=i=>`web:${Array.from(i,t=>t.toString(16).padStart(2,"0")).join("")}`;let jt=null;function ct(i,t){const e=i.get(Bt);if(e&&Vs.test(e))return e;e!==null&&i.remove(Bt);let s;try{s=globalThis.crypto?.getRandomValues?.(new Uint8Array(16))}catch{}if(s){const n=Ae(s);return i.set(Bt,n),n}if(!jt){const n=new Uint8Array(16);for(let r=0;r<n.length;r+=1)n[r]=Math.floor(Math.random()*256);jt=Ae(n)}return jt}function Ft(i){return`osvi.chat.session.${i}`}const zs="https://api.osvi.ai",Gs=12e4,Ks=15e3,ke=[1e3,2e3,4e3,8e3,16e3],Ys=2048,Js=new Set(["session_closed","session_dormant","new_session"]);function bt(){const i=globalThis.crypto;if(i?.randomUUID)return i.randomUUID();if(i?.getRandomValues){const t=i.getRandomValues(new Uint8Array(16));t[6]=t[6]&15|64,t[8]=t[8]&63|128;const e=Array.from(t,s=>s.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}return`${Date.now().toString(16)}-${Math.random().toString(16).slice(2)}`}const Ce=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Te={user:"user",ai:"assistant",assistant:"assistant",operator:"human",support:"human"};class Xs{constructor(t){this.opts=t,this.state=Ce(),this.listeners=new Set,this.conn=null,this.sessionId=null,this.latestToken=null,this.chain=Promise.resolve(),this.startP=null,this.ensureP=null,this.pending=new Map,this.openGen=0,this.sessionGeneration=0,this.seen=[],this.seenSet=new Set,this.timers=new Set,this.awaitingTimer=null,this.destroyed=!1,this.wantNewServerSession=!1,this.switchTo=null,this.http=new ws(t.baseUrl??zs,t.fetch),this.store=t.store??Ws(),this.page=t.page??Se(),this.interactions=new Rs({sessionId:()=>this.sessionId,humanConnected:()=>this.state.mode==="human",sendFrame:e=>this.conn?.send(e)??!1,updateItems:e=>this.patch({items:e(this.state.items)}),refreshSnapshot:()=>this.fetchSnapshot(),onChange:()=>this.patch({}),newId:bt})}get serverMode(){return this.opts.auth?.mode==="server"}serialize(t){const e=this.chain.then(t);return this.chain=e.catch(()=>{}),e}start(){return this.destroyed?Promise.resolve():(this.startP||(this.startP=this.serialize(()=>this.doStart()).finally(()=>{this.startP=null})),this.startP)}async doStart(){if(!(this.destroyed||this.sessionId&&this.conn)){if(this.serverMode){await this.openServerSession();return}try{const t=await this.http.bootstrap(this.opts.agentId,ct(this.store));if(this.destroyed)return;this.patch({agent:{agentId:this.opts.agentId,name:t.agent?.name??""}}),t.session?.id&&t.session.status==="active"?this.adopt(t.session.id,t,this.pending.size?"append":"replace"):this.store.remove(Ft(this.opts.agentId))}catch(t){this.fail(t,!1)}}}async send(t){if(this.destroyed)return{ok:!1,reason:"destroyed"};const e=t.trim();if(!e)return{ok:!1,reason:"empty"};if(this.state.mode==="ai"&&(this.interactions.pending||this.interactions.active?.interaction_status==="pending"))return{ok:!1,reason:"awaiting_interaction"};const s=bt(),n=bt(),r={kind:"message",id:s,role:"user",content:e,createdAt:new Date().toISOString(),status:"sending",idempotencyKey:n};return this.patch({items:[...this.state.items,r]}),this.pending.set(s,{frame:this.frameFor(r),attempts:0,gen:-1,ackTimer:null}),await this.ensureSession()?(this.transmit(s),{ok:!0,messageId:s}):(this.dropPending(s),this.setMessage(s,{status:"failed"}),{ok:!1,reason:"unavailable"})}async respond(t,e){return this.destroyed?!1:this.interactions.respond(t,e)}async retry(t){const e=this.state.items.find(s=>s.kind==="message"&&s.id===t);return!e||e.status!=="failed"||!e.idempotencyKey||this.destroyed?!1:(this.dropPending(t),this.pending.set(t,{frame:this.frameFor(e),attempts:0,gen:-1,ackTimer:null}),this.setMessage(t,{status:"sending"}),await this.ensureSession()?(this.transmit(t),!0):(this.dropPending(t),this.setMessage(t,{status:"failed"}),!1))}newSession(){return this.destroyed?Promise.resolve(!1):!this.sessionId&&this.ensureP?this.ensureP.then(t=>t!==null):this.serialize(async()=>{if(this.destroyed)return!1;if(this.sessionId&&this.endSession("new_session"),this.serverMode)return this.wantNewServerSession=!0,await this.openServerSession()!==null;try{const t=await this.http.createSession(this.opts.agentId,ct(this.store));return this.destroyed?!1:(this.adopt(t.id,null,"keep"),!0)}catch(t){return this.fail(t,!1),!1}})}subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}getState(){return this.state}resolveUrl(t){return this.http.resolveUrl(t)}destroy(){this.destroyed||(this.destroyed=!0,this.sessionGeneration+=1,this.conn?.stop(),this.conn=null,this.timers.forEach(clearTimeout),this.timers.clear(),this.pending.forEach(t=>{t.ackTimer&&clearTimeout(t.ackTimer)}),this.pending.clear(),this.awaitingTimer&&clearTimeout(this.awaitingTimer),this.interactions.reset(),this.sessionId=null,this.latestToken=null,this.switchTo=null,this.state=Ce(),this.listeners.clear())}ensureSession(){return this.ensureP?this.ensureP:(this.ensureP=this.serialize(async()=>this.destroyed?null:this.sessionId?this.sessionId:this.serverMode?this.openServerSession():this.openAnonymousSession()).finally(()=>{this.ensureP=null}),this.ensureP)}async openAnonymousSession(){try{const t=ct(this.store),e=await this.http.bootstrap(this.opts.agentId,t);if(this.destroyed)return null;if(this.patch({agent:{agentId:this.opts.agentId,name:e.agent?.name??""}}),e.session?.id&&e.session.status==="active")return this.adopt(e.session.id,e,"append"),this.sessionId;const s=await this.http.createSession(this.opts.agentId,t);return this.destroyed?null:(this.adopt(s.id,null,"keep"),this.sessionId)}catch(t){return this.fail(t,!1),null}}async openServerSession(t){const e=this.sessionGeneration;try{let s=t?this.accept(t):await this.serverToken(e);this.assertCurrent(e),this.latestToken=s.token;let n;try{n=await this.http.snapshot(s.sessionId,s.token)}catch(r){if(this.assertCurrent(e),!(r instanceof S)||r.error.code!=="invalid_token")throw r;s=await this.serverToken(e),this.assertCurrent(e),this.latestToken=s.token,n=await this.http.snapshot(s.sessionId,s.token)}return this.assertCurrent(e),this.adopt(s.sessionId,n,this.state.items.length?"append":"replace",s),this.sessionId}catch(s){return this.isCurrent(e)&&this.fail(s,!0),null}}async serverToken(t=this.sessionGeneration){if(this.assertCurrent(t),this.opts.auth?.mode!=="server")throw new Error("not server mode");let e;const s=this.wantNewServerSession;this.wantNewServerSession=!1;try{e=await(s?this.opts.auth.getToken({newSession:!0}):this.opts.auth.getToken())}catch{throw new S(v("token_failed","getToken failed"),0)}this.assertCurrent(t);try{return this.accept(e)}catch(n){throw this.isCurrent(t)&&this.fail(n,!1),n}}accept(t){return this.checkWsUrl(t.wsUrl),{...t,expiresAt:fe(t.expiresAt)}}checkWsUrl(t){let e=null;try{e=new URL(t)}catch{}const s=e?.hostname==="localhost"||e?.hostname==="127.0.0.1";if(e&&(e.protocol==="wss:"||e.protocol==="ws:"&&s))return;const n=v("token_failed","The chat stream URL must use wss://");throw new S(n,0)}isCurrent(t,e){return!this.destroyed&&this.sessionGeneration===t&&(e===void 0||this.sessionId===e)}assertCurrent(t,e){if(!this.isCurrent(t,e))throw new S(v("session_closed"),0)}adopt(t,e,s,n,r=!0){if(this.sessionId===t&&this.conn)return;this.conn?.stop(),this.conn=null,this.sessionId=t;const o=++this.sessionGeneration;this.serverMode||this.store.set(Ft(this.opts.agentId),t),e&&this.applySnapshot(e,s);let a=n??null;const c=this.serverMode?null:ct(this.store);let h=!0,d=!1;const l=async()=>{if(this.assertCurrent(o,t),a){const g=a;return a=null,this.latestToken=g.token,g}if(this.serverMode){const g=await this.serverToken(o);if(this.assertCurrent(o,t),g.sessionId!==t)throw this.switchTo=g,new S(v("session_closed"),0);return this.latestToken=g.token,g}const p=h;h=!1;let f;try{f=await this.http.mintPublicToken(t)}catch(g){throw d=p&&r&&this.isCurrent(o,t)&&g instanceof S&&g.status===404&&g.error.code==="session_not_found"&&[...this.pending.values()].every(w=>w.gen===-1),g}this.assertCurrent(o,t);try{this.checkWsUrl(f.wsUrl)}catch(g){throw this.fail(g,!1),g}return this.latestToken=f.token,f};this.conn=new Hs({mint:l,sdkVersion:ys,page:this.page,random:this.opts.random,WebSocketImpl:this.opts.WebSocketImpl,onFrame:p=>this.onFrame(p),onStatus:p=>this.patch({status:p,...p==="open"?{error:null}:{}}),onOpen:()=>this.onOpen(),onReconnected:()=>{this.recover()},onError:p=>this.patch({error:p}),onClosed:p=>{if(!this.isCurrent(o,t))return;if(d&&c&&p==="session_not_found"){d=!1,this.serialize(()=>this.replaceBeforeFirstWrite(o,t,c));return}const f=this.switchTo;this.switchTo=null,this.endSession(p),f&&this.serialize(()=>this.openServerSession(f))}}),this.conn.start()}async replaceBeforeFirstWrite(t,e,s){if(this.isCurrent(t,e))try{const n=await this.http.bootstrap(this.opts.agentId,s);if(!this.isCurrent(t,e))return;const r=n?.session,o=r,a=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;if(n?.agent?.agent_uuid!==this.opts.agentId||!Array.isArray(n.messages)||!r||typeof r.id!="string"||!a.test(r.id)||r.id===e||r.status!=="active"||r.mode!=="ai"&&r.mode!=="support"||o&&"customer_id"in o&&o.customer_id!==s||o&&"agent_uuid"in o&&o.agent_uuid!==this.opts.agentId||[...this.pending.values()].some(c=>c.gen!==-1)){this.endSession("session_not_found");return}this.adopt(r.id,n,"append",void 0,!1)}catch{this.isCurrent(t,e)&&this.endSession("session_not_found")}}onOpen(){this.openGen+=1,this.seen=[],this.seenSet.clear();for(const t of[...this.pending.keys()])this.write(t);this.interactions.onConnectionOpen()}async recover(){const t=this.sessionId,e=this.sessionGeneration,s=await this.fetchSnapshot();s&&t&&this.isCurrent(e,t)&&this.applySnapshot(s,"reconcile")}async fetchSnapshot(){if(this.destroyed)return null;const t=this.sessionId,e=this.sessionGeneration;if(!t)return null;try{try{const s=await this.http.snapshot(t,this.latestToken??await this.mintFresh(t));return this.isCurrent(e,t)?s:null}catch(s){if(this.assertCurrent(e,t),!(s instanceof S)||s.error.code!=="invalid_token")throw s;const n=await this.http.snapshot(t,await this.mintFresh(t));return this.isCurrent(e,t)?n:null}}catch(s){if(s instanceof S&&s.error.code==="session_not_found"){if(!this.isCurrent(e,t))return null;this.endSession("session_closed"),this.serverMode||this.readoptAfterReplacement()}return null}}async mintFresh(t){const e=this.sessionGeneration;if(this.assertCurrent(e,t),this.serverMode){const n=await this.serverToken(e);return this.assertCurrent(e,t),this.latestToken=n.token,n.token}const s=await this.http.mintPublicToken(t);return this.assertCurrent(e,t),this.checkWsUrl(s.wsUrl),this.latestToken=s.token,s.token}async readoptAfterReplacement(){try{const t=await this.http.bootstrap(this.opts.agentId,ct(this.store));!this.destroyed&&!this.sessionId&&t.session?.id&&t.session.status==="active"&&this.adopt(t.session.id,t,"append")}catch{}}endSession(t){if(this.destroyed)return;this.sessionGeneration+=1,this.conn?.stop(),this.conn=null,this.sessionId=null,this.latestToken=null,this.serverMode||this.store.remove(Ft(this.opts.agentId)),this.interactions.reset(),this.pending.forEach(r=>{r.ackTimer&&clearTimeout(r.ackTimer)}),this.pending.clear();const e=this.state.items.map(r=>r.kind==="message"&&r.status==="sending"?{...r,status:"failed"}:r),s=e[e.length-1],n={kind:"divider",id:bt(),reason:"session_ended"};this.setAwaiting(!1),this.patch({status:"closed",mode:"ai",items:e.length&&s?.kind!=="divider"?[...e,n]:e,...Js.has(t)?{}:{error:v(t)}})}onFrame(t){if(this.destroyed)return;if(t.event_id!==void 0){const s=String(t.event_id);if(this.seenSet.has(s))return;this.seenSet.add(s),this.seen.push(s),this.seen.length>Ys&&this.seenSet.delete(this.seen.shift())}const e=t.payload;switch(t.type){case"ws_write_result":this.interactions.handleWriteResult(e)||this.onWriteResult(e);return;case"message_received":{if(e.type==="interaction")return;const s=Nt(e);if(!s)return;s.role==="user"?this.onUserEcho(s.id,s.content,s.created_at,typeof e.message_id=="string"?e.message_id:void 0):this.appendRemote(s.id,s.role,s.content,s.created_at);return}case"operator_message":{const s=Nt({...e,role:"operator"});s&&this.appendRemote(s.id,"operator",s.content,s.created_at);return}case"mode_changed":e.to==="support"?this.setMode("human"):e.to==="ai"&&this.setMode("ai");return;case"takeover_started":this.setMode("human");return;case"takeover_ended":this.setMode("ai");return;case"interaction_published":case"interaction_updated":case"interaction_closed":this.interactions.applyEvent(t)&&t.type==="interaction_published"&&this.setAwaiting(!1),this.patch({});return;case"turn_result":(e.state==="failed"||e.state==="error")&&(this.setAwaiting(!1),this.patch({error:{code:"unknown",message:"The assistant could not reply",retryable:!0}}));return;case"session_closed":case"session_dormant":this.endSession(t.type);return;default:return}}onWriteResult(t){const e=t.message_id;if(!e)return;const s=this.pending.get(e);if(s){if(s.ackTimer&&(clearTimeout(s.ackTimer),s.ackTimer=null),t.state==="accepted"||t.state==="merged"||t.state==="done"){this.pending.delete(e),this.setMessage(e,{status:"sent"}),this.setAwaiting(!0);return}if(t.state==="busy"&&s.attempts<ke.length){const n=ke[s.attempts];s.attempts+=1,this.later(n,()=>{this.pending.get(e)===s&&(s.gen=-1,this.transmit(e))});return}this.pending.delete(e),this.setMessage(e,{status:"failed"}),this.patch({error:v(t.error,t.error)})}}onUserEcho(t,e,s,n){const r=this.state.items;if(r.some(a=>a.kind==="message"&&a.serverId===t))return;const o=n?r.findIndex(a=>a.kind==="message"&&a.role==="user"&&a.id===n):r.findIndex(a=>a.kind==="message"&&a.role==="user"&&!a.serverId&&a.status!=="failed"&&a.content===e);if(o>=0){const a=r.slice(),c=a[o];a[o]={...c,serverId:t,status:"sent"},this.dropPending(c.id),this.patch({items:a});return}this.appendRemote(t,"user",e,s)}appendRemote(t,e,s,n){const r=Te[e];if(!r||this.state.items.some(a=>a.kind==="message"&&a.serverId===t))return;const o={kind:"message",id:`srv:${t}`,serverId:t,role:r,content:s,createdAt:n??new Date().toISOString(),status:"sent"};this.patch({items:[...this.state.items,o]}),r!=="user"&&this.setAwaiting(!1)}applySnapshot(t,e){if(this.destroyed)return;const s=[],n=new Map;for(const c of t.messages??[]){const h=J(c);if(h){s.push({kind:"interaction",id:h.interaction_id,interaction:h});continue}const d=Nt(c),l=d?Te[d.role]:void 0;if(d&&l){s.push({kind:"message",id:`srv:${d.id}`,serverId:d.id,role:l,content:d.content,createdAt:d.created_at??new Date().toISOString(),status:"sent"});const p=c.message_id;typeof p=="string"&&n.set(d.id,p)}}let r=this.state.items;if(e==="replace")r=s;else if(e==="append"){let c=r.length;for(;c>0;){const h=r[c-1];if(h.kind==="message"&&h.role==="user"&&h.status==="sending"&&!h.serverId)c-=1;else break}r=[...r.slice(0,c),...s,...r.slice(c)]}else if(e==="reconcile"){const c=new Set(r.flatMap(h=>h.kind==="message"?[h.serverId]:h.kind==="interaction"?[h.id]:[]));for(const h of s){const d=h.kind==="message"?h.serverId:h.id;if(h.kind==="message"&&h.role==="user"&&!c.has(d)){const l=n.get(h.serverId),p=r.findIndex(f=>f.kind==="message"&&f.role==="user"&&!f.serverId&&(l?f.id===l:f.content===h.content));if(p>=0){const f=r[p];r=r.slice(),r[p]={...f,serverId:h.serverId,status:"sent"},this.dropPending(f.id),c.add(d);continue}}c.has(d)||(r=[...r,h],c.add(d))}}const o=t.session;this.patch({items:r,...o?{mode:o.mode==="support"?"human":"ai"}:{}}),this.interactions.applySnapshot(t);const a=r.filter(c=>c.kind!=="divider").at(-1);a&&!(a.kind==="message"&&a.role==="user")&&this.setAwaiting(!1),this.patch({})}frameFor(t){return{type:"message",content:t.content,message_id:t.id,idempotency_key:t.idempotencyKey,supported_interactions:It}}transmit(t){this.write(t)}write(t){const e=this.pending.get(t);!e||!this.conn?.isOpen||e.gen===this.openGen||this.conn.send(e.frame)&&(e.gen=this.openGen,e.ackTimer&&clearTimeout(e.ackTimer),e.ackTimer=setTimeout(()=>{this.onAckTimeout(t)},Ks))}async onAckTimeout(t){const e=this.pending.get(t);if(!e||this.destroyed||(e.ackTimer=null,!this.conn?.isOpen))return;const s=this.openGen;await this.recover(),!(this.destroyed||this.pending.get(t)!==e||!this.conn?.isOpen||s!==this.openGen)&&(this.dropPending(t),this.setMessage(t,{status:"failed"}),this.patch({error:v("network","The message could not be confirmed")}))}dropPending(t){const e=this.pending.get(t);e?.ackTimer&&clearTimeout(e.ackTimer),this.pending.delete(t)}setMode(t){this.setAwaiting(!1),this.patch({mode:t})}setAwaiting(t){this.awaitingTimer&&(clearTimeout(this.awaitingTimer),this.awaitingTimer=null),t&&(this.awaitingTimer=setTimeout(()=>{this.awaitingTimer=null,this.patch({awaitingReply:!1})},Gs)),this.state.awaitingReply!==t&&this.patch({awaitingReply:t})}setMessage(t,e){this.patch({items:this.state.items.map(s=>s.kind==="message"&&s.id===t?{...s,...e}:s)})}fail(t,e){const s=t instanceof S?t.error:v("network","Network error");this.patch({error:s,...e||!s.retryable?{status:"closed"}:{}})}later(t,e){const s=setTimeout(()=>{this.timers.delete(s),this.destroyed||e()},t);this.timers.add(s)}patch(t){if(this.destroyed)return;const e={...this.state,...t,activeInteraction:this.interactions.active,interactionPending:this.interactions.pending};Object.keys(e).some(n=>e[n]!==this.state[n])&&(this.state=e,this.listeners.forEach(n=>n(e)))}}function Zs(i){return new Xs(i)}const Ie={primary:"#4f46e5",background:"#ffffff",surface:"#f4f4f5",text:"#18181b",userBubble:"#4f46e5",assistantBubble:"#f4f4f5"},Qs={primary:"#6366f1",background:"#0a0a12",surface:"#1c1c27",text:"#f4f4f5",userBubble:"#6366f1",assistantBubble:"#1f1f2b"},ti={none:"0px",sm:"6px",md:"10px",lg:"16px",full:"9999px"},ht={primary:"--osvi-color-primary",background:"--osvi-color-background",surface:"--osvi-color-surface",text:"--osvi-color-text",userBubble:"--osvi-color-user-bubble",assistantBubble:"--osvi-color-assistant-bubble"},j=i=>`var(${ht[i]}, ${Ie[i]})`;function Lt(i){const t={...i?.mode==="dark"?Qs:Ie,...i?.colors},e={};for(const n of Object.keys(ht))e[ht[n]]=t[n];const s=i?.radius??"md";return e["--osvi-radius"]=typeof s=="number"?`${s}px`:ti[s],e}function Ee(i){if(!i)return{};if(i.mode)return Lt(i);const t=Lt(i),e={};for(const s of Object.keys(i.colors??{}))e[ht[s]]=t[ht[s]];return i.radius!==void 0&&(e["--osvi-radius"]=t["--osvi-radius"]),e}const xe=new WeakMap;function Ht(i,t){for(const s of xe.get(i)??[])i.style.removeProperty(s);const e=Ee(t);for(const[s,n]of Object.entries(e))i.style.setProperty(s,n);xe.set(i,Object.keys(e))}const Vt={placeholder:"Type your message…",send:"Send",typing:"Typing…",humanJoined:"A team member has joined",chooseOption:"Choose an option to continue.",typeAnswer:"Type your answer below, then press Send.",sending:"Sending your response…",pausedForHuman:"Choices are paused while a team member is connected.",sendFailed:"Message not sent.",retry:"Retry",sessionEnded:"Conversation ended",reconnecting:"Reconnecting…",offline:"You are offline. We will reconnect automatically.",unavailable:"This chat is unavailable.",originBlocked:"This chat is not enabled for this website.",rateLimited:"Too many requests. Please try again in a few minutes.",tryAgain:"Try again",closeChat:"Close chat",poweredBy:"Powered by OSVI",newChat:"New chat",emptyState:"Send a message to start chatting.",defaultTitle:"Chat"},Pe=new Set;function Oe(i,t){Pe.has(i)||(Pe.add(i),console.warn(`[osvi-chat] ${t}`))}function F(i,t){return i!=null&&t.includes(i)?i:void 0}function Re(i){if(i!=null)return F(i,["none","sm","md","lg","full"])??(/^\d{1,2}(?:px)?$/.test(i)?Number(i.replace(/px$/,"")):void 0)}function Ue(i){if(i){try{const t=new URL(i);if(!t.username&&!t.password&&(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1"].includes(t.hostname)))return i.replace(/\/+$/,"")}catch{}Oe("base-url","ignored an invalid base-url (https required, http only for localhost)")}}function ei(i){if(i){if(/^data:image\/(png|jpeg|gif|webp);base64,[a-z0-9+/]+={0,2}$/i.test(i))return i;try{const t=new URL(i);if(t.protocol==="https:"&&!t.username&&!t.password)return i}catch{}}}function Me(i,t){if(t){try{const e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}Oe(i,`ignored invalid JSON in the ${i} attribute`)}}const L={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4},Ne=i=>(...t)=>({_$litDirective$:i,values:t});let De=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,e,s){this._$Ct=t,this._$AM=e,this._$Ci=s}_$AS(t,e){return this.update(t,e)}update(t,e){return this.render(...e)}};const{I:si}=us,Be=i=>i,ii=i=>i.strings===void 0,je=()=>document.createComment(""),lt=(i,t,e)=>{const s=i._$AA.parentNode,n=t===void 0?i._$AB:t._$AA;if(e===void 0){const r=s.insertBefore(je(),n),o=s.insertBefore(je(),n);e=new si(r,o,i,i.options)}else{const r=e._$AB.nextSibling,o=e._$AM,a=o!==i;if(a){let c;e._$AQ?.(i),e._$AM=i,e._$AP!==void 0&&(c=i._$AU)!==o._$AU&&e._$AP(c)}if(r!==n||a){let c=e._$AA;for(;c!==r;){const h=Be(c).nextSibling;Be(s).insertBefore(c,n),c=h}}}return e},H=(i,t,e=i)=>(i._$AI(t,e),i),ni={},Fe=(i,t=ni)=>i._$AH=t,ri=i=>i._$AH,qt=i=>{i._$AR(),i._$AA.remove()};const Le=(i,t,e)=>{const s=new Map;for(let n=t;n<=e;n++)s.set(i[n],n);return s},oi=Ne(class extends De{constructor(i){if(super(i),i.type!==L.CHILD)throw Error("repeat() can only be used in text expressions")}dt(i,t,e){let s;e===void 0?e=t:t!==void 0&&(s=t);const n=[],r=[];let o=0;for(const a of i)n[o]=s?s(a,o):o,r[o]=e(a,o),o++;return{values:r,keys:n}}render(i,t,e){return this.dt(i,t,e).values}update(i,[t,e,s]){const n=ri(i),{values:r,keys:o}=this.dt(t,e,s);if(!Array.isArray(n))return this.ut=o,r;const a=this.ut??(this.ut=[]),c=[];let h,d,l=0,p=n.length-1,f=0,g=r.length-1;for(;l<=p&&f<=g;)if(n[l]===null)l++;else if(n[p]===null)p--;else if(a[l]===o[f])c[f]=H(n[l],r[f]),l++,f++;else if(a[p]===o[g])c[g]=H(n[p],r[g]),p--,g--;else if(a[l]===o[g])c[g]=H(n[l],r[g]),lt(i,c[g+1],n[l]),l++,g--;else if(a[p]===o[f])c[f]=H(n[p],r[f]),lt(i,n[l],n[p]),p--,f++;else if(h===void 0&&(h=Le(o,f,g),d=Le(a,l,p)),h.has(a[l]))if(h.has(a[p])){const w=d.get(o[f]),pt=w!==void 0?n[w]:null;if(pt===null){const Ge=lt(i,n[l]);H(Ge,r[f]),c[f]=Ge}else c[f]=H(pt,r[f]),lt(i,n[l],pt),n[w]=null;f++}else qt(n[p]),p--;else qt(n[l]),l++;for(;f<=g;){const w=lt(i,c[g+1]);H(w,r[f]),c[f++]=w}for(;l<=p;){const w=n[l++];w!==null&&qt(w)}return this.ut=o,Fe(i,c),k}}),ai=/https?:\/\/[^\s<>"']+/g,vt=(i,t)=>i.split(t).length-1;function ci(i){for(;;){const t=i[i.length-1];if(t&&".,!?;:".includes(t)||t===")"&&vt(i,")")>vt(i,"(")||t==="]"&&vt(i,"]")>vt(i,"[")){i=i.slice(0,-1);continue}return i}}function hi(i){const t=[];let e=0;for(const s of i.matchAll(ai)){const n=ci(s[0]),r=s.index;try{const o=new URL(n);if(!["http:","https:"].includes(o.protocol))continue}catch{continue}r>e&&t.push({text:i.slice(e,r)}),t.push({href:n,text:n}),e=r+n.length}return e<i.length&&t.push({text:i.slice(e)}),t.length?t:[{text:i}]}function li(i,t,e,s,n){return u`${i.items.length?oi(i.items,r=>r.id,r=>{if(r.kind==="divider")return u`<p class="divider">${t.sessionEnded}</p>`;if(r.kind==="message")return u`<article class=${`bubble ${r.role}`}>${r.role==="human"?u`<small>Team</small>`:m}<p>${hi(r.content).map(h=>"href"in h?u`<a href=${h.href} target="_blank" rel="noopener noreferrer">${h.text}</a>`:h.text)}</p>${r.role==="user"&&r.status==="failed"?u`<span>${t.sendFailed}</span><button type="button" @click=${()=>n(r.id)}>${t.retry}</button>`:m}</article>`;const o=r.interaction,a=o.interaction_id===i.activeInteraction?.interaction_id&&o.interaction_status==="pending",c=!a||i.interactionPending||i.mode==="human";switch(o.tool_type){case"ui_buttons":return u`<osvi-buttons data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.buttons??"chips"} base-url=${s}></osvi-buttons>`;case"ui_carousel":return u`<osvi-carousel data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} .variant=${e.carousel??"slider"} base-url=${s}></osvi-carousel>`;case"ui_date_picker":return u`<osvi-date-picker data-live=${a?"true":"false"} .interaction=${o} .disabled=${c} base-url=${s}></osvi-date-picker>`;default:return u`<p>${o.content}</p>`}}):u`<p>${t.emptyState}</p>`}${i.awaitingReply?u`<p aria-label=${t.typing}>${t.typing}<span aria-hidden="true"> •••</span></p>`:m}`}const di=Ne(class extends De{constructor(i){if(super(i),i.type!==L.PROPERTY&&i.type!==L.ATTRIBUTE&&i.type!==L.BOOLEAN_ATTRIBUTE)throw Error("The `live` directive is not allowed on child or event bindings");if(!ii(i))throw Error("`live` bindings can only contain a single expression")}render(i){return i}update(i,[t]){if(t===k||t===m)return t;const e=i.element,s=i.name;if(i.type===L.PROPERTY){if(t===e[s])return k}else if(i.type===L.BOOLEAN_ATTRIBUTE){if(!!t===e.hasAttribute(s))return k}else if(i.type===L.ATTRIBUTE&&e.getAttribute(s)===t+"")return k;return Fe(i),t}});function ui(i){return u`<div class="composer"><textarea aria-label="Message" placeholder=${i.placeholder} .value=${di(i.draft)} ?disabled=${i.disabled} @input=${i.input} @keydown=${t=>{t.key==="Enter"&&!t.shiftKey&&!t.isComposing&&!i.disabled&&(t.preventDefault(),i.send())}}></textarea><button type="button" aria-label=${i.strings.send} ?disabled=${i.disabled||!i.draft.trim()} @click=${i.send}>${i.strings.send}</button></div>`}var pi=Object.defineProperty,b=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&pi(t,e,n),n};const He=()=>({status:"idle",mode:"ai",awaitingReply:!1,items:[],activeInteraction:null,interactionPending:!1,agent:null,error:null}),Ve={fromAttribute:i=>i!=="false"},y=(E=class extends Y{constructor(){super(...arguments),this.agentId="",this.baseUrl="",this.client=null,this.theme={},this.variants={},this.strings={},this.poweredBy=!0,this.newChat=!0,this.header={},this.closable=!1,this.chatState=He(),this.draft="",this.busy=!1,this.typed=null,this.ownClient=null,this.boundClient=null,this.ownKey="",this.generation=0,this.followBottom=!0,this.focusedInteraction=null,this.send=()=>{if(this.blocked||!this.draft.trim()||!this.boundClient)return;const t=this.boundClient,e=this.draft.trim(),s=this.typed;this.draft="",s&&this.restoreDraft(),this.requestUpdate(),this.run(()=>s?t.respond(s.id,{kind:"text",value:e}):t.send(e))},this.respond=t=>{const e=t.detail,s=this.chatState;if(!e||this.busy||s.mode!=="ai"||s.interactionPending||s.activeInteraction?.interaction_status!=="pending"||e.interactionId!==s.activeInteraction.interaction_id)return;t.stopPropagation();const n=this.boundClient;n&&this.run(()=>n.respond(e.interactionId,e.response))},this.requestInput=t=>{const e=t.detail,s=this.chatState;!e||this.busy||s.mode!=="ai"||s.interactionPending||s.activeInteraction?.interaction_status!=="pending"||e.interactionId!==s.activeInteraction.interaction_id||(t.stopPropagation(),this.typed={id:e.interactionId,placeholder:typeof e.placeholder=="string"?e.placeholder:void 0,previousDraft:this.typed?.previousDraft??this.draft},this.draft="",this.requestUpdate(),this.updateComplete.then(()=>this.renderRoot.querySelector("textarea")?.focus()))}}connectedCallback(){super.connectedCallback(),this.syncClient()}disconnectedCallback(){super.disconnectedCallback(),this.releaseClient()}releaseClient(){++this.generation,this.unsubscribe?.(),this.unsubscribe=void 0,this.boundClient=null;const t=this.ownClient;this.ownClient=null,this.ownKey="",t?.destroy(),this.busy=!1,this.typed=null,this.focusedInteraction=null,this.requestUpdate()}syncClient(){if(!this.isConnected||!this.client&&!this.agentId&&!this.boundClient)return;const t=JSON.stringify([this.agentId,Ue(this.baseUrl)]);if((this.client?this.boundClient===this.client&&!this.ownClient:this.ownClient&&t===this.ownKey)||(this.releaseClient(),this.chatState=He(),!this.client&&!this.agentId))return;const e=!this.client,s=this.client??E.clientFactory({agentId:this.agentId,baseUrl:Ue(this.baseUrl)});this.boundClient=s,e&&(this.ownClient=s,this.ownKey=t);const n=this.generation;this.chatState=s.getState(),this.requestUpdate(),this.unsubscribe=s.subscribe(r=>{this.generation!==n||this.boundClient!==s||(this.chatState=r,this.requestUpdate(),this.typed&&(r.mode==="human"||r.activeInteraction?.interaction_id!==this.typed.id||r.activeInteraction.interaction_status!=="pending")&&this.restoreDraft())}),e&&this.run(()=>s.start())}willUpdate(){this.syncClient(),Ht(this,this.mergedTheme())}mergedTheme(){const t=Me("theme",this.themeAttribute),e={},s=t?.colors;if(s&&typeof s=="object"&&!Array.isArray(s))for(const o of["primary","background","surface","text","userBubble","assistantBubble"]){const a=s[o];typeof a=="string"&&(e[o]=a)}typeof this.primaryColor=="string"&&(e.primary=this.primaryColor);const n=Re(this.radius)??(typeof t?.radius=="number"&&Number.isInteger(t.radius)&&t.radius>=0&&t.radius<=99?t.radius:typeof t?.radius=="string"?Re(t.radius):void 0),r=F(this.mode,["light","dark"])??F(typeof t?.mode=="string"?t.mode:void 0,["light","dark"]);return{...this.theme,colors:{...this.theme?.colors,...e},...n===void 0?{}:{radius:n},...r===void 0?{}:{mode:r}}}get labels(){const t={...Vt};for(const e of[this.strings,Me("strings",this.stringsAttribute)])for(const s of Object.keys(Vt))typeof e?.[s]=="string"&&(t[s]=e[s]);return t}get blocked(){const t=this.chatState;return!this.boundClient||this.busy||t.status==="connecting"||t.status==="closed"&&!!t.error&&!t.error.retryable||t.mode==="ai"&&(t.interactionPending||t.activeInteraction?.interaction_status==="pending"&&!this.typed)}get sessionBusy(){return this.busy||this.chatState.status==="connecting"||this.chatState.interactionPending||this.chatState.items.some(t=>t.kind==="message"&&t.status==="sending")}async run(t){if(this.busy||!this.boundClient)return;const e=this.generation;this.busy=!0,this.requestUpdate();try{await t()}catch{}finally{this.generation===e&&(this.busy=!1,this.requestUpdate())}}restoreDraft(){this.typed&&(this.draft=this.typed.previousDraft,this.typed=null,this.requestUpdate())}async focusActiveInteraction(){if(await this.updateComplete,!this.isConnected||this.chatState.activeInteraction?.interaction_status!=="pending")return;const t=this.renderRoot.querySelector('[data-live="true"]');if(!t)return;const e=this.chatState.activeInteraction.interaction_id;await t.updateComplete,!(!this.isConnected||this.chatState.activeInteraction?.interaction_id!==e)&&t.shadowRoot?.querySelector('button:not(:disabled),input:not(:disabled),select:not(:disabled),textarea:not(:disabled),[tabindex="0"]')?.focus()}updated(){const t=this.renderRoot.querySelector(".transcript");t&&this.followBottom&&(t.scrollTop=t.scrollHeight);const e=this.chatState.activeInteraction?.interaction_status==="pending"?this.chatState.activeInteraction.interaction_id:null;e!==this.focusedInteraction&&(this.focusedInteraction=e,e&&this.isConnected&&!this.hidden&&document.visibilityState!=="hidden"&&this.focusActiveInteraction())}statusText(t){const e=this.chatState;return e.error?.code==="origin_not_allowed"?t.originBlocked:e.error&&["agent_inactive","agent_archived","agent_not_found"].includes(e.error.code)?t.unavailable:e.error?.code==="rate_limited"?t.rateLimited:e.error?.code==="token_failed"?e.error.message:e.status==="recovering"?t.reconnecting:e.status==="offline"?t.offline:e.interactionPending||this.busy&&this.typed?t.sending:e.activeInteraction?.interaction_status==="pending"?e.mode==="human"?t.pausedForHuman:this.typed?t.typeAnswer:t.chooseOption:e.status==="closed"?t.sessionEnded:""}render(){const t=this.labels,e=this.chatState,s=this.boundClient,n=ei(this.headerAvatar??this.header.avatarUrl),r={...this.variants,...F(this.buttons,["chips","list"])?{buttons:F(this.buttons,["chips","list"])}:{},...F(this.carousel,["slider","list"])?{carousel:F(this.carousel,["slider","list"])}:{}};return u`<header>${n?u`<img src=${n} alt="" referrerpolicy="no-referrer">`:m}<div class="heading"><h2>${this.headerTitle??this.header.title??e.agent?.name??t.defaultTitle}</h2>${this.headerSubtitle??this.header.subtitle?u`<p>${this.headerSubtitle??this.header.subtitle}</p>`:m}${e.mode==="human"?u`<small>${t.humanJoined}</small>`:m}</div>
|
|
4
|
+
${this.newChat?u`<button type="button" ?disabled=${!s||this.sessionBusy} @click=${()=>s&&!this.sessionBusy&&void this.run(()=>s.newSession())}>${t.newChat}</button>`:m}
|
|
5
|
+
${this.closable?u`<button type="button" aria-label=${t.closeChat} @click=${()=>this.dispatchEvent(new CustomEvent("osvi-close",{bubbles:!0,composed:!0}))}>×</button>`:m}</header>
|
|
6
|
+
<div class="transcript" role="log" aria-live="polite" aria-label="Conversation" @scroll=${o=>{const a=o.currentTarget;this.followBottom=a.scrollHeight-a.scrollTop-a.clientHeight<=80}} @osvi-respond=${this.respond} @osvi-request-input=${this.requestInput}>${li(e,t,r,s?.resolveUrl("")??"",o=>{s&&this.run(()=>s.retry(o))})}</div>
|
|
7
|
+
<div class="status" role="status">${this.statusText(t)}${e.error?.retryable&&(e.status==="idle"||e.status==="closed")?u`<button type="button" ?disabled=${this.busy||!s} @click=${()=>s&&void this.run(()=>s.start())}>${t.tryAgain}</button>`:m}</div>
|
|
8
|
+
${ui({strings:t,draft:this.draft,placeholder:this.typed?.placeholder??t.placeholder,disabled:this.blocked,input:o=>{this.draft=o.target.value,this.requestUpdate()},send:this.send})}
|
|
9
|
+
${this.poweredBy?u`<footer><a href="https://osvi.ai" target="_blank" rel="noopener noreferrer">${t.poweredBy}</a></footer>`:m}`}},E.clientFactory=Zs,E.properties={themeAttribute:{attribute:"theme"},stringsAttribute:{attribute:"strings"}},E.styles=Qt`
|
|
10
|
+
:host { display:flex; flex-direction:column; height:100%; min-height:260px; color:var(--osvi-color-text,#18181b); background:var(--osvi-color-background,#fff); font:14px/1.5 system-ui,sans-serif; border-radius:var(--osvi-radius,10px); overflow:hidden; }
|
|
11
|
+
header { display:flex; align-items:center; gap:10px; padding:14px; border-bottom:1px solid var(--osvi-color-surface,#f4f4f5); } header img { width:36px; height:36px; border-radius:50%; } .heading { flex:1; } h2,p { margin:0; } h2 { font-size:16px; } small { display:block; }
|
|
12
|
+
.transcript { flex:1; overflow:auto; padding:16px; min-height:0; } .bubble { width:fit-content; max-width:85%; padding:10px 14px; margin:8px 0; border-radius:var(--osvi-radius,10px); background:var(--osvi-color-assistant-bubble,#f4f4f5); overflow-wrap:anywhere; white-space:pre-wrap; } .user { margin-left:auto; color:#fff; background:var(--osvi-color-user-bubble,#4f46e5); } .bubble a { color:inherit; } .divider { text-align:center; } .status { padding:0 14px; } .composer { display:flex; gap:8px; padding:14px; } textarea { flex:1; resize:vertical; min-width:0; } button,textarea { font:inherit; } button { cursor:pointer; } button:disabled { cursor:default; } footer { padding:0 14px 10px; text-align:center; } footer a { color:inherit; } osvi-buttons,osvi-carousel,osvi-date-picker { display:block; margin:8px 0; }
|
|
13
|
+
`,E);b([_({attribute:"agent-id"})],y.prototype,"agentId"),b([_({attribute:"base-url"})],y.prototype,"baseUrl"),b([_({attribute:!1})],y.prototype,"client"),b([_({attribute:!1})],y.prototype,"theme"),b([_({attribute:!1})],y.prototype,"variants"),b([_({attribute:!1})],y.prototype,"strings"),b([_({attribute:"powered-by",converter:Ve})],y.prototype,"poweredBy"),b([_({attribute:"new-chat",converter:Ve})],y.prototype,"newChat"),b([_({attribute:!1})],y.prototype,"header"),b([_({type:Boolean})],y.prototype,"closable"),b([_({attribute:"header-title"})],y.prototype,"headerTitle"),b([_({attribute:"header-subtitle"})],y.prototype,"headerSubtitle"),b([_({attribute:"header-avatar"})],y.prototype,"headerAvatar"),b([_({attribute:"primary-color"})],y.prototype,"primaryColor"),b([_()],y.prototype,"radius"),b([_()],y.prototype,"mode"),b([_()],y.prototype,"buttons"),b([_()],y.prototype,"carousel"),b([C()],y.prototype,"chatState"),b([C()],y.prototype,"draft"),b([C()],y.prototype,"busy"),b([C()],y.prototype,"typed");let qe=y;function dt(i,t){typeof customElements>"u"||customElements.get(i)||customElements.define(i,t)}const Wt=Qt`
|
|
14
|
+
:host { display: block; font: inherit; color: ${M(j("text"))}; background: ${M(j("background"))}; }
|
|
15
|
+
* { box-sizing: border-box; }
|
|
16
|
+
button { font: inherit; color: inherit; background: ${M(j("surface"))}; border: 1px solid currentColor; border-radius: var(--osvi-radius, 10px); padding: 10px 14px; cursor: pointer; }
|
|
17
|
+
button:focus-visible { outline: 3px solid ${M(j("primary"))}; outline-offset: 3px; }
|
|
18
|
+
button:disabled { opacity: .5; cursor: default; }
|
|
19
|
+
button[aria-pressed="true"] { outline: 2px solid ${M(j("primary"))}; }
|
|
20
|
+
small { display: block; }
|
|
21
|
+
.chips { display: flex; flex-wrap: wrap; gap: 8px; }
|
|
22
|
+
.list { display: grid; gap: 6px; }
|
|
23
|
+
.list button { width: 100%; text-align: left; }
|
|
24
|
+
.card { background: ${M(j("surface"))}; border-radius: var(--osvi-radius, 10px); padding: 12px; }
|
|
25
|
+
.image { aspect-ratio: 16 / 9; display: grid; place-items: center; overflow: hidden; }
|
|
26
|
+
.image img { width: 100%; height: 100%; object-fit: cover; }
|
|
27
|
+
.navigation { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 10px 0; }
|
|
28
|
+
.days, .weekdays { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 4px; text-align: center; }
|
|
29
|
+
.days button { padding: 8px 0; }
|
|
30
|
+
`;var fi=Object.defineProperty,$t=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&fi(t,e,n),n};class V extends Y{constructor(){super(...arguments),this.interaction=null,this.disabled=!1,this.baseUrl=""}get live(){return!this.disabled&&this.interaction?.interaction_status==="pending"}get valid(){const t=this.interaction;return!!t&&t.tool_type===this.toolType&&xs(t,t.presentation)}respond(t){!this.interaction||!this.live||!this.valid||this.dispatchEvent(new CustomEvent("osvi-respond",{bubbles:!0,composed:!0,detail:{interactionId:this.interaction.interaction_id,response:t}}))}updated(t){t.has("theme")&&Ht(this,this.theme)}}$t([_({attribute:!1})],V.prototype,"interaction"),$t([_({type:Boolean})],V.prototype,"disabled"),$t([_({attribute:!1})],V.prototype,"theme"),$t([_({attribute:"base-url"})],V.prototype,"baseUrl");var gi=Object.defineProperty,mi=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&gi(t,e,n),n};const Kt=class Kt extends V{constructor(){super(...arguments),this.toolType="ui_buttons",this.variant="chips"}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return u`<p>${t.content}</p>`;const e=t.presentation,s=t.response_payload?.kind==="text"?t.response_payload.value:e.options.find(n=>n.id===(t.response_payload?.kind==="selection"?t.response_payload.value:t.selected_option_id))?.label;return u`<p>${e.label}</p>${e.description?u`<p>${e.description}</p>`:m}
|
|
31
|
+
${this.live?u`<div role="group" aria-label="Options" class=${this.variant} @keydown=${this.onKey}>
|
|
32
|
+
${e.options.map(n=>u`<button type="button" @click=${()=>this.pick(n.id,n.allow_input,n.input_placeholder)}><span>${n.label}</span>${n.description?u`<small>${n.description}</small>`:m}</button>`)}
|
|
33
|
+
</div>`:s?u`<p>${s}</p>`:m}`}pick(t,e,s){!this.live||!this.valid||!this.interaction||(this.interaction.schema_version===2&&e?this.dispatchEvent(new CustomEvent("osvi-request-input",{bubbles:!0,composed:!0,detail:{interactionId:this.interaction.interaction_id,placeholder:s}})):this.respond({kind:"selection",value:t}))}onKey(t){if(!["ArrowDown","ArrowUp","ArrowRight","ArrowLeft"].includes(t.key))return;const e=[...this.renderRoot.querySelectorAll("button")],s=e.indexOf(this.renderRoot.activeElement),n=t.key==="ArrowDown"||t.key==="ArrowRight"?1:-1;e[(s+n+e.length)%e.length]?.focus(),t.preventDefault()}};Kt.styles=Wt;let ut=Kt;mi([_()],ut.prototype,"variant");var _i=Object.defineProperty,zt=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&_i(t,e,n),n};const Yt=class Yt extends V{constructor(){super(...arguments),this.toolType="ui_carousel",this.variant="slider",this.index=0,this.imageFailed=new Set,this.suppressPointerClick=!1}willUpdate(t){t.has("interaction")&&(this.index=0,this.imageFailed=new Set,this.pointerStart=void 0,this.suppressPointerClick=!1)}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return u`<p>${t.content}</p>`;const e=t.presentation,s=e.items.find(n=>n.id===(t.response_payload?.kind==="selection"?t.response_payload.value:t.selected_option_id));return u`<p>${e.label}</p>${e.description?u`<p>${e.description}</p>`:m}
|
|
34
|
+
${this.live?this.variant==="list"?u`<div class="list">${e.items.map((n,r)=>this.card(n,r))}</div>`:u`<div @pointerdown=${n=>{this.pointerStart=n.clientX,this.suppressPointerClick=!1}} @pointerup=${n=>{this.pointerStart!==void 0&&Math.abs(n.clientX-this.pointerStart)>40&&(this.suppressPointerClick=!0,this.navigate(n.clientX<this.pointerStart?1:-1,e.items.length)),this.pointerStart=void 0}} @pointercancel=${()=>{this.pointerStart=void 0}}>${this.card(e.items[this.index],this.index)}</div>
|
|
35
|
+
<div class="navigation"><button type="button" aria-label="Previous card" ?disabled=${this.index===0} @click=${()=>this.navigate(-1,e.items.length)}>Previous</button>
|
|
36
|
+
<span aria-live="polite">${this.index+1} of ${e.items.length}</span>
|
|
37
|
+
<button type="button" aria-label="Next card" ?disabled=${this.index===e.items.length-1} @click=${()=>this.navigate(1,e.items.length)}>Next</button></div>`:s?u`<p>${s.title}</p>`:m}`}navigate(t,e){this.index=Math.max(0,Math.min(e-1,this.index+t))}select(t,e){if(this.suppressPointerClick&&t.detail!==0){this.suppressPointerClick=!1,t.preventDefault(),t.stopPropagation();return}this.respond({kind:"selection",value:e})}card(t,e){const s=t.image;return u`<article class="card">${s&&_e(s.url)?u`<div class="image">${this.imageFailed.has(e)?u`<span role="img" aria-label="Image unavailable">Image unavailable</span>`:u`<img src=${this.baseUrl.replace(/\/$/,"")+s.url} alt=${s.alt} referrerpolicy="no-referrer" loading="lazy" @error=${()=>{this.imageFailed=new Set([...this.imageFailed,e])}}>`}</div>`:m}
|
|
38
|
+
<h3>${t.title}</h3>${t.description?u`<p>${t.description}</p>`:m}
|
|
39
|
+
<button type="button" @click=${n=>this.select(n,t.id)}>${t.action_label??"Select"}</button></article>`}};Yt.styles=Wt;let q=Yt;zt([_()],q.prototype,"variant"),zt([C()],q.prototype,"index"),zt([C()],q.prototype,"imageFailed");var yi=Object.defineProperty,wt=(i,t,e,s)=>{for(var n=void 0,r=i.length-1,o;r>=0;r--)(o=i[r])&&(n=o(t,e,n)||n);return n&&yi(t,e,n),n};const We=i=>`${String(i.getFullYear()).padStart(4,"0")}-${String(i.getMonth()+1).padStart(2,"0")}-${String(i.getDate()).padStart(2,"0")}`,Gt=()=>We(new Date),ze=i=>{const t=new Date(0);return t.setHours(0,0,0,0),t.setFullYear(Number(i.slice(0,4)),Number(i.slice(5,7))-1,Number(i.slice(8,10))),t},W=i=>i.slice(0,7),Jt=class Jt extends V{constructor(){super(...arguments),this.toolType="ui_date_picker",this.variant="grid",this.month=W(Gt()),this.start="",this.end=""}earliest(t){return t.min_date&&t.min_date>Gt()?t.min_date:Gt()}willUpdate(t){t.has("interaction")&&(this.start="",this.end="",this.valid&&(this.month=W(this.earliest(this.interaction.presentation))))}render(){const t=this.interaction;if(!t)return m;if(!this.valid)return u`<p>${t.content}</p>`;const e=t.presentation,s=t.response_payload,n=s?.kind==="date_range"?`${s.value.start_date} – ${s.value.end_date}`:s?.kind==="date"||s?.kind==="text"?s.value:t.selected_option_id;if(!this.live)return u`<p>${e.label}</p>${e.description?u`<p>${e.description}</p>`:m}${n?u`<p>${n}</p>`:m}`;const r=ze(`${this.month}-01`),o=new Date(r);o.setMonth(o.getMonth()+1,0);const a=this.earliest(e),c=Array.from({length:o.getDate()},(d,l)=>`${this.month}-${String(l+1).padStart(2,"0")}`),h=e.selection_mode==="range"?this.start?this.end?`${this.start} – ${this.end}`:`Check-in: ${this.start}. Choose check-out.`:"Choose check-in, then check-out.":this.start;return u`<p>${e.label}</p>${e.description?u`<p>${e.description}</p>`:m}
|
|
40
|
+
<div class="navigation"><button type="button" aria-label="Previous month" ?disabled=${this.month<=W(a)} @click=${()=>this.moveMonth(-1,e)}>Previous</button>
|
|
41
|
+
<span aria-live="polite">${r.toLocaleDateString(void 0,{month:"long",year:"numeric"})}</span>
|
|
42
|
+
<button type="button" aria-label="Next month" ?disabled=${!!e.max_date&&this.month>=W(e.max_date)} @click=${()=>this.moveMonth(1,e)}>Next</button></div>
|
|
43
|
+
<div class="weekdays" aria-hidden="true">${["Su","Mo","Tu","We","Th","Fr","Sa"].map(d=>u`<span>${d}</span>`)}</div>
|
|
44
|
+
<div class="days" role="group" aria-label="Choose date" @keydown=${this.onKey}>
|
|
45
|
+
${Array.from({length:r.getDay()},()=>u`<span></span>`)}
|
|
46
|
+
${c.map((d,l)=>u`<button type="button" aria-label=${d} aria-pressed=${d===this.start||d===this.end} ?disabled=${d<a||!!e.max_date&&d>e.max_date} @click=${()=>this.pick(d,e)}>${l+1}</button>`)}
|
|
47
|
+
</div><p aria-live="polite">${h}</p>
|
|
48
|
+
<button type="button" ?disabled=${!this.start||e.selection_mode==="range"&&(!this.end||this.start>=this.end)} @click=${()=>this.confirm(e)}>${e.confirm_label??"Confirm date"}</button>`}moveMonth(t,e){const s=ze(`${this.month}-01`);s.setMonth(s.getMonth()+t);const n=W(We(s));n>=W(this.earliest(e))&&(!e.max_date||n<=W(e.max_date))&&(this.month=n)}pick(t,e){!this.live||!this.valid||!R(t)||t<this.earliest(e)||e.max_date&&t>e.max_date||(e.selection_mode==="single"||!this.start||this.end||t<=this.start?(this.start=t,this.end=""):this.end=t)}confirm(t){!R(this.start)||this.start<this.earliest(t)||t.max_date&&this.start>t.max_date||(t.selection_mode==="single"?this.respond({kind:"date",value:this.start}):R(this.end)&&this.start<this.end&&(!t.max_date||this.end<=t.max_date)&&this.respond({kind:"date_range",value:{start_date:this.start,end_date:this.end}}))}onKey(t){const s={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[t.key];if(s===void 0)return;const n=[...this.renderRoot.querySelectorAll(".days button")],r=n.indexOf(this.renderRoot.activeElement);if(r<0)return;let o=r+s;for(;o>=0&&o<n.length&&n[o]?.disabled;)o+=s>0?1:-1;n[o]?.focus(),t.preventDefault()}};Jt.styles=Wt;let U=Jt;return wt([_()],U.prototype,"variant"),wt([C()],U.prototype,"month"),wt([C()],U.prototype,"start"),wt([C()],U.prototype,"end"),dt("osvi-chat",qe),dt("osvi-buttons",ut),dt("osvi-carousel",q),dt("osvi-date-picker",U),A.DEFAULT_STRINGS=Vt,A.OsviButtons=ut,A.OsviCarousel=q,A.OsviChat=qe,A.OsviDatePicker=U,A.applyTheme=Ht,A.cssVar=j,A.defineOnce=dt,A.explicitThemeVariables=Ee,A.themeVariables=Lt,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),A})({});
|
|
49
|
+
//# sourceMappingURL=ui.js.map
|