@paramms/chat-widget 1.0.45 → 1.0.47

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
- var RelayEmbedLite=function(J){"use strict";var zn=Object.defineProperty;var Mn=(J,Y,oe)=>Y in J?zn(J,Y,{enumerable:!0,configurable:!0,writable:!0,value:oe}):J[Y]=oe;var c=(J,Y,oe)=>Mn(J,typeof Y!="symbol"?Y+"":Y,oe);const Y="oc_uid";function oe(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function dt(t,e){try{const o=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${o}`}catch{}}function ht(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function He(){let t=null;try{t=localStorage.getItem(Y)}catch{}t||(t=oe(Y));const e=t??ht();try{localStorage.setItem(Y,e)}catch{}return dt(Y,e),e}function pt(t){const e=t.length;let n=0,o=0;for(;o<e;){let i=t.charCodeAt(o++);if(i&4294967168)if(!(i&4294965248))n+=2;else{if(i>=55296&&i<=56319&&o<e){const s=t.charCodeAt(o);(s&64512)===56320&&(++o,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?n+=4:n+=3}else{n++;continue}}return n}function ut(t,e,n){const o=t.length;let i=n,s=0;for(;s<o;){let r=t.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[i++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<o){const u=t.charCodeAt(s);(u&64512)===56320&&(++s,r=((r&1023)<<10)+(u&1023)+65536)}r&4294901760?(e[i++]=r>>18&7|240,e[i++]=r>>12&63|128,e[i++]=r>>6&63|128):(e[i++]=r>>12&15|224,e[i++]=r>>6&63|128)}else{e[i++]=r;continue}e[i++]=r&63|128}}const ft=new TextEncoder,wt=50;function gt(t,e,n){ft.encodeInto(t,e.subarray(n))}function xt(t,e,n){t.length>wt?gt(t,e,n):ut(t,e,n)}const mt=4096;function We(t,e,n){let o=e;const i=o+n,s=[];let r="";for(;o<i;){const u=t[o++];if(!(u&128))s.push(u);else if((u&224)===192){const d=t[o++]&63;s.push((u&31)<<6|d)}else if((u&240)===224){const d=t[o++]&63,p=t[o++]&63;s.push((u&31)<<12|d<<6|p)}else if((u&248)===240){const d=t[o++]&63,p=t[o++]&63,g=t[o++]&63;let l=(u&7)<<18|d<<12|p<<6|g;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(u);s.length>=mt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const yt=new TextDecoder,bt=200;function vt(t,e,n){const o=t.subarray(e,e+n);return yt.decode(o)}function kt(t,e,n){return n>bt?vt(t,e,n):We(t,e,n)}class xe{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class H extends Error{constructor(e){super(e);const n=Object.create(H.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:H.name})}}const ae=4294967295;function St(t,e,n){const o=n/4294967296,i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function Ke(t,e,n){const o=Math.floor(n/4294967296),i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function Ve(t,e){const n=t.getInt32(e),o=t.getUint32(e+4);return n*4294967296+o}function It(t,e){const n=t.getUint32(e),o=t.getUint32(e+4);return n*4294967296+o}const Ct=-1,Tt=4294967296-1,Et=17179869184-1;function Ut({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Et)if(e===0&&t<=Tt){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,o=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,o),i}else{const n=new Uint8Array(12),o=new DataView(n.buffer);return o.setUint32(0,e),Ke(o,4,t),n}}function Bt(t){const e=t.getTime(),n=Math.floor(e/1e3),o=(e-n*1e3)*1e6,i=Math.floor(o/1e9);return{sec:n+i,nsec:o-i*1e9}}function Lt(t){if(t instanceof Date){const e=Bt(t);return Ut(e)}else return null}function At(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),o=e.getUint32(4),i=(n&3)*4294967296+o,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=Ve(e,4),o=e.getUint32(0);return{sec:n,nsec:o}}default:throw new H(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function zt(t){const e=At(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Mt={type:Ct,encode:Lt,decode:zt},ke=class ke{constructor(){c(this,"__brand");c(this,"builtInEncoders",[]);c(this,"builtInDecoders",[]);c(this,"encoders",[]);c(this,"decoders",[]);this.register(Mt)}register({type:e,encode:n,decode:o}){if(e>=0)this.encoders[e]=n,this.decoders[e]=o;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=o}}tryToEncode(e,n){for(let o=0;o<this.builtInEncoders.length;o++){const i=this.builtInEncoders[o];if(i!=null){const s=i(e,n);if(s!=null){const r=-1-o;return new xe(r,s)}}}for(let o=0;o<this.encoders.length;o++){const i=this.encoders[o];if(i!=null){const s=i(e,n);if(s!=null){const r=o;return new xe(r,s)}}}return e instanceof xe?e:null}decode(e,n,o){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,o):new xe(n,e)}};c(ke,"defaultCodec",new ke);let me=ke;function $t(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Be(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):$t(t)?new Uint8Array(t):Uint8Array.from(t)}const Rt=100,Pt=2048;class Le{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"maxDepth");c(this,"initialBufferSize");c(this,"sortKeys");c(this,"forceFloat32");c(this,"ignoreUndefined");c(this,"forceIntegerToFloat");c(this,"pos");c(this,"view");c(this,"bytes");c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??me.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Rt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Pt,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Le({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),o=new Uint8Array(n),i=new DataView(n);o.set(this.bytes),this.view=i,this.bytes=o}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const o=pt(e);this.ensureBufferSizeToWrite(5+o),this.writeStringHeader(o),xt(e,this.bytes,this.pos),this.pos+=o}encodeObject(e,n){const o=this.extensionCodec.tryToEncode(e,this.context);if(o!=null)this.encodeExtension(o);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const o=Be(e);this.writeU8a(o)}encodeArray(e,n){const o=e.length;if(o<16)this.writeU8(144+o);else if(o<65536)this.writeU8(220),this.writeU16(o);else if(o<4294967296)this.writeU8(221),this.writeU32(o);else throw new Error(`Too large array: ${o}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let o=0;for(const i of n)e[i]!==void 0&&o++;return o}encodeMap(e,n){const o=Object.keys(e);this.sortKeys&&o.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,o):o.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of o){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const o=e.data(this.pos+6),i=o.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(o);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),St(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ke(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function _t(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const Dt=16,qt=16;class jt{constructor(e=Dt,n=qt){c(this,"hit",0);c(this,"miss",0);c(this,"caches");c(this,"maxKeyLength");c(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let o=0;o<this.maxKeyLength;o++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,o){const i=this.caches[o-1];e:for(const s of i){const r=s.bytes;for(let u=0;u<o;u++)if(r[u]!==e[n+u])continue e;return s.str}return null}store(e,n){const o=this.caches[e.length-1],i={bytes:e,str:n};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=i:o.push(i)}decode(e,n,o){const i=this.find(e,n,o);if(i!=null)return this.hit++,i;this.miss++;const s=We(e,n,o),r=Uint8Array.prototype.slice.call(e,n,n+o);return this.store(r,s),s}}const ze="array",ce="map_key",Ge="map_value",Nt=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new H("The type of key must be string or number but "+typeof t)};class Ot{constructor(){c(this,"stack",[]);c(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=ze,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ce,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===ze){const o=e;o.size=0,o.array=void 0,o.position=0,o.type=void 0}if(e.type===ce||e.type===Ge){const o=e;o.size=0,o.map=void 0,o.readCount=0,o.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const le=-1,Me=new DataView(new ArrayBuffer(0)),Ft=new Uint8Array(Me.buffer);try{Me.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Ye=new RangeError("Insufficient data"),Ht=new jt;class $e{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"rawStrings");c(this,"maxStrLength");c(this,"maxBinLength");c(this,"maxArrayLength");c(this,"maxMapLength");c(this,"maxExtLength");c(this,"keyDecoder");c(this,"mapKeyConverter");c(this,"totalPos",0);c(this,"pos",0);c(this,"view",Me);c(this,"bytes",Ft);c(this,"headByte",le);c(this,"stack",new Ot);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??me.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??ae,this.maxBinLength=(e==null?void 0:e.maxBinLength)??ae,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??ae,this.maxMapLength=(e==null?void 0:e.maxMapLength)??ae,this.maxExtLength=(e==null?void 0:e.maxExtLength)??ae,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Ht,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Nt}clone(){return new $e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=le,this.stack.reset()}setBuffer(e){const n=Be(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===le&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),o=Be(e),i=new Uint8Array(n.length+o.length);i.set(n),i.set(o,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:o}=this;return new RangeError(`Extra ${n.byteLength-o} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,o;for await(const u of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(u);try{o=this.doDecodeSync(),n=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return o}const{headByte:i,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${Ae(i)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let o=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),o&&(i=this.readArraySize(),o=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new H(`Unrecognized type byte: ${Ae(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===ze)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,o.release(i);else continue e;else if(i.type===ce){if(n==="__proto__")throw new H("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Ge;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,o.release(i);else{i.key=null,i.type=ce;continue e}}return n}}readHeadByte(){return this.headByte===le&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=le}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new H(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new H(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new H(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var s;if(e>this.maxStrLength)throw new H(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Ye;const o=this.pos+n;let i;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?i=this.keyDecoder.decode(this.bytes,o,e):i=kt(this.bytes,o,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ce:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new H(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Ye;const o=this.pos+n,i=this.bytes.subarray(o,o+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new H(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const o=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,o,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=It(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ve(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Wt(t,e){return new $e(e).decode(t)}const Kt=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Vt(t){return Kt.has(t.type)}function Re(t){return _t(t)}function Xe(t){let e;try{e=Wt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Gt{constructor(e){c(this,"conversationId");c(this,"state","");c(this,"version",0);c(this,"hasMoreHistory",!1);c(this,"lastReadByOthers",0);c(this,"assignedAgentId");c(this,"accent");c(this,"subject");c(this,"name");c(this,"e2e",!1);c(this,"offline",!1);c(this,"offlineMessage","");c(this,"launcherMessage",null);c(this,"preChat",null);c(this,"whiteLabel",!1);c(this,"typing",new Set);c(this,"online",new Set);c(this,"sentiment");c(this,"sentimentScore");c(this,"actions",[]);c(this,"byId",new Map);c(this,"keyByClient",new Map);c(this,"_maxSeq",0);c(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,n)=>{const o=e.status==="pending",i=n.status==="pending";return o!==i?o?1:-1:o&&i?e.ts-n.ts:e.seq-n.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,n){const o={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:n,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,o),this.keyByClient.set(e,e),this._sorted=null,o}apply(e){var n;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(n=e.theme)!=null&&n.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const o=this.keyByClient.get(e.clientMsgId),i=o?this.byId.get(o):void 0;if(i&&o){this.byId.delete(o);const s={...i,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const o of e.messages)this.upsert({...o});return;case"history":for(const o of e.messages)this.upsert({...o});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const o=this.byId.get(e.messageId);if(!o)return;const i={...o.reactions??{}},s=(i[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?i[e.emoji]=s:delete i[e.emoji],this.byId.set(e.messageId,{...o,reactions:i}),this._sorted=null;return}case"edited":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const o=this.byId.get(e.messageId);o&&(this.byId.set(e.messageId,{...o,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const n=this.byId.get(e.id);this.byId.set(e.id,n?{...n,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,n){const o=Je(n);let i=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Je(r.status)>=o||(this.byId.set(s,{...r,status:n}),i=!0);i&&(this._sorted=null)}}function Je(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Yt{constructor(e){c(this,"socket",null);c(this,"state","idle");c(this,"authed",!1);c(this,"everAuthed",!1);c(this,"attempt",0);c(this,"outbox",[]);c(this,"stopped",!1);c(this,"timer",null);c(this,"refreshing",!1);this.opts=e}connect(){var o,i;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(i=(o=this.opts).onStatusChange)==null||i.call(o,this.attempt>0?"reconnecting":"connecting");const n=(this.opts.socketFactory??Qt)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Xe(new Uint8Array(s.data));!r||Vt(r)||this.handle(r)},n.onclose=()=>this.onClosed(),n.onerror=()=>{try{n.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var n,o,i,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(o=(n=this.opts).onStatusChange)==null||o.call(n,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&Xt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var u;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(u=this.socket)==null||u.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,o,i;this.stopped=!0;try{(n=this.socket)==null||n.close()}catch{}this.state="closed",(i=(o=this.opts).onStatusChange)==null||i.call(o,"error",Jt(e.code)),this.opts.onFrame(e)}flush(e){const n=this.outbox;this.outbox=[];for(const o of n)this.raw(e&&o.type==="send"&&o.conversationId!==e?{...o,conversationId:e}:o)}queue(e){const n=this.opts.maxOutbox??1e3;this.outbox.length>=n&&(this.outbox=this.outbox.slice(this.outbox.length-(n>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(Re(e))}catch{this.queue(e)}}onClosed(){var i,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,n=this.opts.backoffMaxMs??15e3,o=Math.min(n,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),o)}}const Xt=new Set(["UNAUTHORIZED"]);function Jt(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function Qt(t){return new WebSocket(t)}const Qe=200,Zt=7*864e5;class en{constructor(e){c(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const n=JSON.parse(e),o=Date.now()-Zt,i=n.filter(s=>s.ts>=o);return i.length!==n.length&&this.save(i),i}catch{return[]}}add(e){try{const n=this.load();n.push(e),this.save(n.length>Qe?n.slice(n.length-Qe):n)}catch{}}remove(e){try{const n=this.load().filter(o=>o.clientMsgId!==e);this.save(n)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const tn={accent:"#6c5ce7",accent2:"#4c6fff",bg:"#f4f3fb",card:"#fff",tint:"#eeecfb",line:"#e6e2f5",ink:"#221d3a",mut:"#8f8aa8",onaccent:"#fff",rowhover:"#e7e3f8",shadow:"0 12px 32px rgba(108,92,231,.14)"},nn={accent:"#a99cf2",accent2:"#6f8cff",bg:"#221d3a",card:"#2b2550",tint:"#2f2853",line:"#3a3363",ink:"#eceafc",mut:"#9b93c9",onaccent:"#221d3a",rowhover:"#39325e",shadow:"0 12px 32px rgba(0,0,0,.4)"},on="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function Ze(t,e){return Object.entries(e).map(([n,o])=>`--${t}-${n}:${o};`).join(" ")}function et(t){return`${Ze(t,tn)} --${t}-fb:${on}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ye(t){return Ze(t,nn)}const sn=`
1
+ var RelayEmbedLite=function(J){"use strict";var $n=Object.defineProperty;var Rn=(J,Y,ie)=>Y in J?$n(J,Y,{enumerable:!0,configurable:!0,writable:!0,value:ie}):J[Y]=ie;var c=(J,Y,ie)=>Rn(J,typeof Y!="symbol"?Y+"":Y,ie);const Y="oc_uid";function ie(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function ht(t,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function pt(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function He(){let t=null;try{t=localStorage.getItem(Y)}catch{}t||(t=ie(Y));const e=t??pt();try{localStorage.setItem(Y,e)}catch{}return ht(Y,e),e}function ut(t){const e=t.length;let n=0,i=0;for(;i<e;){let o=t.charCodeAt(i++);if(o&4294967168)if(!(o&4294965248))n+=2;else{if(o>=55296&&o<=56319&&i<e){const s=t.charCodeAt(i);(s&64512)===56320&&(++i,o=((o&1023)<<10)+(s&1023)+65536)}o&4294901760?n+=4:n+=3}else{n++;continue}}return n}function ft(t,e,n){const i=t.length;let o=n,s=0;for(;s<i;){let r=t.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[o++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<i){const u=t.charCodeAt(s);(u&64512)===56320&&(++s,r=((r&1023)<<10)+(u&1023)+65536)}r&4294901760?(e[o++]=r>>18&7|240,e[o++]=r>>12&63|128,e[o++]=r>>6&63|128):(e[o++]=r>>12&15|224,e[o++]=r>>6&63|128)}else{e[o++]=r;continue}e[o++]=r&63|128}}const wt=new TextEncoder,gt=50;function xt(t,e,n){wt.encodeInto(t,e.subarray(n))}function mt(t,e,n){t.length>gt?xt(t,e,n):ft(t,e,n)}const yt=4096;function We(t,e,n){let i=e;const o=i+n,s=[];let r="";for(;i<o;){const u=t[i++];if(!(u&128))s.push(u);else if((u&224)===192){const d=t[i++]&63;s.push((u&31)<<6|d)}else if((u&240)===224){const d=t[i++]&63,p=t[i++]&63;s.push((u&31)<<12|d<<6|p)}else if((u&248)===240){const d=t[i++]&63,p=t[i++]&63,g=t[i++]&63;let l=(u&7)<<18|d<<12|p<<6|g;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(u);s.length>=yt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const bt=new TextDecoder,vt=200;function kt(t,e,n){const i=t.subarray(e,e+n);return bt.decode(i)}function St(t,e,n){return n>vt?kt(t,e,n):We(t,e,n)}class xe{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class H extends Error{constructor(e){super(e);const n=Object.create(H.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:H.name})}}const ae=4294967295;function It(t,e,n){const i=n/4294967296,o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ke(t,e,n){const i=Math.floor(n/4294967296),o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ve(t,e){const n=t.getInt32(e),i=t.getUint32(e+4);return n*4294967296+i}function Ct(t,e){const n=t.getUint32(e),i=t.getUint32(e+4);return n*4294967296+i}const Et=-1,Tt=4294967296-1,Ut=17179869184-1;function Bt({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Ut)if(e===0&&t<=Tt){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,i=t&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,i),o}else{const n=new Uint8Array(12),i=new DataView(n.buffer);return i.setUint32(0,e),Ke(i,4,t),n}}function Lt(t){const e=t.getTime(),n=Math.floor(e/1e3),i=(e-n*1e3)*1e6,o=Math.floor(i/1e9);return{sec:n+o,nsec:i-o*1e9}}function At(t){if(t instanceof Date){const e=Lt(t);return Bt(e)}else return null}function zt(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),i=e.getUint32(4),o=(n&3)*4294967296+i,s=n>>>2;return{sec:o,nsec:s}}case 12:{const n=Ve(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new H(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Mt(t){const e=zt(t);return new Date(e.sec*1e3+e.nsec/1e6)}const $t={type:Et,encode:At,decode:Mt},ke=class ke{constructor(){c(this,"__brand");c(this,"builtInEncoders",[]);c(this,"builtInDecoders",[]);c(this,"encoders",[]);c(this,"decoders",[]);this.register($t)}register({type:e,encode:n,decode:i}){if(e>=0)this.encoders[e]=n,this.decoders[e]=i;else{const o=-1-e;this.builtInEncoders[o]=n,this.builtInDecoders[o]=i}}tryToEncode(e,n){for(let i=0;i<this.builtInEncoders.length;i++){const o=this.builtInEncoders[i];if(o!=null){const s=o(e,n);if(s!=null){const r=-1-i;return new xe(r,s)}}}for(let i=0;i<this.encoders.length;i++){const o=this.encoders[i];if(o!=null){const s=o(e,n);if(s!=null){const r=i;return new xe(r,s)}}}return e instanceof xe?e:null}decode(e,n,i){const o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(e,n,i):new xe(n,e)}};c(ke,"defaultCodec",new ke);let me=ke;function Rt(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Be(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Rt(t)?new Uint8Array(t):Uint8Array.from(t)}const Pt=100,_t=2048;class Le{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"maxDepth");c(this,"initialBufferSize");c(this,"sortKeys");c(this,"forceFloat32");c(this,"ignoreUndefined");c(this,"forceIntegerToFloat");c(this,"pos");c(this,"view");c(this,"bytes");c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??me.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Pt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??_t,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Le({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),i=new Uint8Array(n),o=new DataView(n);i.set(this.bytes),this.view=o,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=ut(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),mt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,n){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const i=Be(e);this.writeU8a(i)}encodeArray(e,n){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const o of e)this.doEncode(o,n+1)}countWithoutUndefined(e,n){let i=0;for(const o of n)e[o]!==void 0&&i++;return i}encodeMap(e,n){const i=Object.keys(e);this.sortKeys&&i.sort();const o=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(const s of i){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),o=i.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(e.type),this.writeU8a(i);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),It(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ke(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function Dt(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const qt=16,jt=16;class Nt{constructor(e=qt,n=jt){c(this,"hit",0);c(this,"miss",0);c(this,"caches");c(this,"maxKeyLength");c(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,i){const o=this.caches[i-1];e:for(const s of o){const r=s.bytes;for(let u=0;u<i;u++)if(r[u]!==e[n+u])continue e;return s.str}return null}store(e,n){const i=this.caches[e.length-1],o={bytes:e,str:n};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=o:i.push(o)}decode(e,n,i){const o=this.find(e,n,i);if(o!=null)return this.hit++,o;this.miss++;const s=We(e,n,i),r=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(r,s),s}}const ze="array",ce="map_key",Ge="map_value",Ot=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new H("The type of key must be string or number but "+typeof t)};class Ft{constructor(){c(this,"stack",[]);c(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=ze,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ce,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===ze){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===ce||e.type===Ge){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const le=-1,Me=new DataView(new ArrayBuffer(0)),Ht=new Uint8Array(Me.buffer);try{Me.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Ye=new RangeError("Insufficient data"),Wt=new Nt;class $e{constructor(e){c(this,"extensionCodec");c(this,"context");c(this,"useBigInt64");c(this,"rawStrings");c(this,"maxStrLength");c(this,"maxBinLength");c(this,"maxArrayLength");c(this,"maxMapLength");c(this,"maxExtLength");c(this,"keyDecoder");c(this,"mapKeyConverter");c(this,"totalPos",0);c(this,"pos",0);c(this,"view",Me);c(this,"bytes",Ht);c(this,"headByte",le);c(this,"stack",new Ft);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??me.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??ae,this.maxBinLength=(e==null?void 0:e.maxBinLength)??ae,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??ae,this.maxMapLength=(e==null?void 0:e.maxMapLength)??ae,this.maxExtLength=(e==null?void 0:e.maxExtLength)??ae,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Wt,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Ot}clone(){return new $e({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=le,this.stack.reset()}setBuffer(e){const n=Be(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===le&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),i=Be(e),o=new Uint8Array(n.length+i.length);o.set(n),o.set(i,n.length),this.setBuffer(o)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:i}=this;return new RangeError(`Extra ${n.byteLength-i} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,i;for await(const u of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(u);try{i=this.doDecodeSync(),n=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:o,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${Ae(o)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let i=n,o=-1;for await(const s of e){if(n&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(o=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const o=e-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e<160){const o=e-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else{const o=e-160;n=this.decodeString(o,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const o=this.lookU8();n=this.decodeString(o,1)}else if(e===218){const o=this.lookU16();n=this.decodeString(o,2)}else if(e===219){const o=this.lookU32();n=this.decodeString(o,4)}else if(e===220){const o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else if(e===221){const o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else n=[]}else if(e===222){const o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e===223){const o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else n={}}else if(e===196){const o=this.lookU8();n=this.decodeBinary(o,1)}else if(e===197){const o=this.lookU16();n=this.decodeBinary(o,2)}else if(e===198){const o=this.lookU32();n=this.decodeBinary(o,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const o=this.lookU8();n=this.decodeExtension(o,1)}else if(e===200){const o=this.lookU16();n=this.decodeExtension(o,2)}else if(e===201){const o=this.lookU32();n=this.decodeExtension(o,4)}else throw new H(`Unrecognized type byte: ${Ae(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const o=i.top();if(o.type===ze)if(o.array[o.position]=n,o.position++,o.position===o.size)n=o.array,i.release(o);else continue e;else if(o.type===ce){if(n==="__proto__")throw new H("The key __proto__ is not allowed");o.key=this.mapKeyConverter(n),o.type=Ge;continue e}else if(o.map[o.key]=n,o.readCount++,o.readCount===o.size)n=o.map,i.release(o);else{o.key=null,o.type=ce;continue e}}return n}}readHeadByte(){return this.headByte===le&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=le}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new H(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new H(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new H(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){var s;if(e>this.maxStrLength)throw new H(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Ye;const i=this.pos+n;let o;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,i,e):o=St(this.bytes,i,e),this.pos+=n+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ce:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new H(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Ye;const i=this.pos+n,o=this.bytes.subarray(i,i+e);return this.pos+=n+e,o}decodeExtension(e,n){if(e>this.maxExtLength)throw new H(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+n),o=this.decodeBinary(e,n+1);return this.extensionCodec.decode(o,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Ct(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ve(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function Kt(t,e){return new $e(e).decode(t)}const Vt=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Gt(t){return Vt.has(t.type)}function Re(t){return Dt(t)}function Xe(t){let e;try{e=Kt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Yt{constructor(e){c(this,"conversationId");c(this,"state","");c(this,"version",0);c(this,"hasMoreHistory",!1);c(this,"lastReadByOthers",0);c(this,"assignedAgentId");c(this,"accent");c(this,"subject");c(this,"name");c(this,"e2e",!1);c(this,"offline",!1);c(this,"offlineMessage","");c(this,"launcherMessage",null);c(this,"preChat",null);c(this,"whiteLabel",!1);c(this,"typing",new Set);c(this,"online",new Set);c(this,"sentiment");c(this,"sentimentScore");c(this,"actions",[]);c(this,"byId",new Map);c(this,"keyByClient",new Map);c(this,"_maxSeq",0);c(this,"_sorted",null);this.me=e}messages(){return this._sorted||(this._sorted=[...this.byId.values()].sort((e,n)=>{const i=e.status==="pending",o=n.status==="pending";return i!==o?i?1:-1:i&&o?e.ts-n.ts:e.seq-n.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,n){const i={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:n,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,i),this.keyByClient.set(e,e),this._sorted=null,i}apply(e){var n;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(n=e.theme)!=null&&n.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const i=this.keyByClient.get(e.clientMsgId),o=i?this.byId.get(i):void 0;if(o&&i){this.byId.delete(i);const s={...o,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const i of e.messages)this.upsert({...i});return;case"history":for(const i of e.messages)this.upsert({...i});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const i=this.byId.get(e.messageId);if(!i)return;const o={...i.reactions??{}},s=(o[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?o[e.emoji]=s:delete o[e.emoji],this.byId.set(e.messageId,{...i,reactions:o}),this._sorted=null;return}case"edited":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const n=this.byId.get(e.id);this.byId.set(e.id,n?{...n,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,n){const i=Je(n);let o=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Je(r.status)>=i||(this.byId.set(s,{...r,status:n}),o=!0);o&&(this._sorted=null)}}function Je(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Xt{constructor(e){c(this,"socket",null);c(this,"state","idle");c(this,"authed",!1);c(this,"everAuthed",!1);c(this,"attempt",0);c(this,"outbox",[]);c(this,"stopped",!1);c(this,"timer",null);c(this,"refreshing",!1);this.opts=e}connect(){var i,o;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(o=(i=this.opts).onStatusChange)==null||o.call(i,this.attempt>0?"reconnecting":"connecting");const n=(this.opts.socketFactory??Zt)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Xe(new Uint8Array(s.data));!r||Gt(r)||this.handle(r)},n.onclose=()=>this.onClosed(),n.onerror=()=>{try{n.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}this.queue(e)}pendingCount(){return this.outbox.length}close(){var e;this.stopped=!0,this.timer&&clearTimeout(this.timer),this.state="closed";try{(e=this.socket)==null||e.close()}catch{}}handle(e){var n,i,o,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(i=(n=this.opts).onStatusChange)==null||i.call(n,"open"),this.raw(this.opts.open),this.opts.open.type!=="open"&&this.flush()),e.type==="opened"&&(this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),this.flush(e.conversation.id)),e.type==="error"&&Jt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var u;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(u=this.socket)==null||u.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,i,o;this.stopped=!0;try{(n=this.socket)==null||n.close()}catch{}this.state="closed",(o=(i=this.opts).onStatusChange)==null||o.call(i,"error",Qt(e.code)),this.opts.onFrame(e)}flush(e){const n=this.outbox;this.outbox=[];for(const i of n)this.raw(e&&i.type==="send"&&i.conversationId!==e?{...i,conversationId:e}:i)}queue(e){const n=this.opts.maxOutbox??1e3;this.outbox.length>=n&&(this.outbox=this.outbox.slice(this.outbox.length-(n>>1))),this.outbox.push(e)}raw(e){if(!this.socket){this.queue(e);return}try{this.socket.send(Re(e))}catch{this.queue(e)}}onClosed(){var o,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,n=this.opts.backoffMaxMs??15e3,i=Math.min(n,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),i)}}const Jt=new Set(["UNAUTHORIZED"]);function Qt(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function Zt(t){return new WebSocket(t)}const Qe=200,en=7*864e5;class tn{constructor(e){c(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const n=JSON.parse(e),i=Date.now()-en,o=n.filter(s=>s.ts>=i);return o.length!==n.length&&this.save(o),o}catch{return[]}}add(e){try{const n=this.load();n.push(e),this.save(n.length>Qe?n.slice(n.length-Qe):n)}catch{}}remove(e){try{const n=this.load().filter(i=>i.clientMsgId!==e);this.save(n)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const nn={accent:"#6c5ce7",accent2:"#4c6fff",bg:"#f4f3fb",card:"#fff",tint:"#eeecfb",line:"#e6e2f5",ink:"#221d3a",mut:"#8f8aa8",onaccent:"#fff",rowhover:"#e7e3f8",shadow:"0 12px 32px rgba(108,92,231,.14)"},on={accent:"#a99cf2",accent2:"#6f8cff",bg:"#221d3a",card:"#2b2550",tint:"#2f2853",line:"#3a3363",ink:"#eceafc",mut:"#9b93c9",onaccent:"#221d3a",rowhover:"#39325e",shadow:"0 12px 32px rgba(0,0,0,.4)"},sn="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function Ze(t,e){return Object.entries(e).map(([n,i])=>`--${t}-${n}:${i};`).join(" ")}function et(t){return`${Ze(t,nn)} --${t}-fb:${sn}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ye(t){return Ze(t,on)}const rn=`
2
2
  .ocw { ${et("ocw")}
3
3
  position:relative;
4
4
  display:flex; flex-direction:column; height:100%; min-height:320px; background:var(--ocw-bg);
5
5
  font-family:var(--ocw-fb); color:var(--ocw-ink); overflow:hidden; }
6
- @media (prefers-color-scheme: dark) { .ocw:not([data-theme="light"]) { ${ye("ocw")} } }
6
+ @media (prefers-color-scheme: dark) { .ocw[data-theme="auto"] { ${ye("ocw")} } }
7
7
  .ocw[data-theme="dark"] { ${ye("ocw")} }
8
8
  /* ── Responsive sizing ──────────────────────────────────────────────────────
9
9
  * Sizing is driven by the WIDGET'S OWN width (ResizeObserver toggles
@@ -110,7 +110,7 @@ var RelayEmbedLite=function(J){"use strict";var zn=Object.defineProperty;var Mn=
110
110
  .ocw button:focus-visible, .ocw textarea:focus-visible, .ocw a:focus-visible, .ocw [tabindex]:focus-visible { outline:2px solid var(--ocw-accent); outline-offset:2px; border-radius:8px; }
111
111
  .ocw-sendbtn:active { transform:scale(.92); }
112
112
  .ocw-quick button:active, .ocw-chip:active { transform:scale(.97); }
113
- @media (prefers-color-scheme: dark) { .ocw:not([data-theme="light"]) .ocw-away { background:#3a3018; border-color:#5a4a1f; color:#e8d9a8; } .ocw:not([data-theme="light"]) .ocw-note .ocw-bubble { background:#332b12; border-color:#7a5c17; color:#f0e2bd; } .ocw:not([data-theme="light"]) .ocw-note .ocw-bubble::before { color:#e0c060; } }
113
+ @media (prefers-color-scheme: dark) { .ocw[data-theme="auto"] .ocw-away { background:#3a3018; border-color:#5a4a1f; color:#e8d9a8; } .ocw[data-theme="auto"] .ocw-note .ocw-bubble { background:#332b12; border-color:#7a5c17; color:#f0e2bd; } .ocw[data-theme="auto"] .ocw-note .ocw-bubble::before { color:#e0c060; } }
114
114
  .ocw[data-theme="dark"] .ocw-away { background:#3a3018; border-color:#5a4a1f; color:#e8d9a8; }
115
115
  .ocw[data-theme="dark"] .ocw-note .ocw-bubble { background:#332b12; border-color:#7a5c17; color:#f0e2bd; }
116
116
  .ocw[data-theme="dark"] .ocw-note .ocw-bubble::before { color:#e0c060; }
@@ -189,11 +189,11 @@ var RelayEmbedLite=function(J){"use strict";var zn=Object.defineProperty;var Mn=
189
189
  .ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
190
190
  .ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
191
191
  .ocw-translated-tag { font-size:10px; color:var(--ocw-mut); margin-top:2px; }
192
- `,tt="objectchat-widget-styles",rn=["👍","❤️","😂","😮","😢","🙏"],an=400,cn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function ln(){if(typeof document>"u"||document.getElementById(tt))return;const t=document.createElement("style");t.id=tt,t.textContent=sn,document.head.appendChild(t)}function a(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function dn(t){try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Pe(t){var e;switch(t.kind){case"text":return t.text;case"system":return typeof((e=t.data)==null?void 0:e.message)=="string"?String(t.data.message):t.event;case"card":return[t.title,t.body].filter(Boolean).join(" — ");case"attachment":return t.name??t.url;case"form":return t.prompt;case"appointment":return`📅 ${t.title} — ${new Date(t.startIso).toLocaleString()}`}}class hn{constructor(e,n,o,i={}){c(this,"scroll");c(this,"chips");c(this,"typing");c(this,"quick");c(this,"formHost");c(this,"csatPanel");c(this,"awayNotice");c(this,"headStatus");c(this,"reopenBtn");c(this,"preChatPanel");c(this,"deflectPanel");c(this,"preChatBuilt",!1);c(this,"preChatDone",!1);c(this,"footer");c(this,"input");c(this,"subjectCard");c(this,"e2eBadge");c(this,"statusBadge");c(this,"headerName");c(this,"connStatus");c(this,"typingTimer",null);c(this,"csatSubmitted",!1);c(this,"sendBtn");c(this,"compactObserver",null);c(this,"storeRef",null);c(this,"cfgAccent2");c(this,"scrollCleanup",null);c(this,"translationCache",new Map);c(this,"showingTranslation",new Set);c(this,"subjectBuilt",!1);var f,E,I,x,y,q,_,j,k,M,W;this.root=e,this.me=n,this.h=o,this.cfg=i,ln(),e.replaceChildren(),e.classList.add("ocw"),i.accent&&e.style.setProperty("--ocw-accent",i.accent);const s=i.accent2??i.accent;s&&e.style.setProperty("--ocw-accent2",s),this.cfgAccent2=i.accent2,i.theme&&i.theme!=="auto"&&(e.dataset.theme=i.theme);const r=a("div","ocw-head");if(this.h.onBack){const C=a("button","ocw-back","‹");C.type="button",C.setAttribute("aria-label","Back"),C.addEventListener("click",()=>this.h.onBack()),r.append(C)}const u=a("div","ocw-avatar");if((f=i.userInfo)!=null&&f.avatar){const C=document.createElement("img");C.src=i.userInfo.avatar,C.alt=i.userInfo.name??"You",C.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",u.append(C)}else u.textContent=(E=i.userInfo)!=null&&E.name?i.userInfo.name[0].toUpperCase():"🧑";r.append(u);const d=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((I=i.subject)==null?void 0:I.ownerLabel)??((x=i.subject)==null?void 0:x.title)??""),d.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",d.append(this.headStatus),(y=i.subject)!=null&&y.subtitle&&d.append(a("div","ocw-head-meta",i.subject.subtitle)),r.append(d),this.statusBadge=a("span","ocw-badge",((q=i.subject)==null?void 0:q.status)??""),(_=i.subject)!=null&&_.status||(this.statusBadge.style.display="none"),r.append(this.statusBadge),this.e2eBadge=a("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",r.append(this.e2eBadge),this.connStatus=a("span","ocw-conn-status"),this.connStatus.style.display="none",r.append(this.connStatus),r.append(a("button","ocw-menu","⋯")),this.chips=a("div","ocw-chiprow"),this.scroll=a("div","ocw-scroll"),this.subjectCard=a("div","ocw-subject"),this.typing=a("div","ocw-typing");const p=a("div","ocw-typing-bubble");p.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(a("div","ocw-dot","🧑"),p),this.quick=a("div","ocw-quick");for(const C of i.quickReplies??[]){const K=a("button",void 0,C);K.addEventListener("click",()=>{this.h.onSend(C),this.quick.style.display="none"}),this.quick.append(K)}this.formHost=a("div","ocw-form-host"),this.csatPanel=a("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=a("div","ocw-away"),this.awayNotice.style.display="none",this.preChatPanel=a("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=a("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=a("textarea",void 0),this.input.rows=1,this.input.placeholder=((j=i.i18n)==null?void 0:j.placeholder)??"Message…";const g=a("button","ocw-sendbtn");g.type="button";const l=(k=i.i18n)==null?void 0:k.send;l?(g.textContent=l,g.classList.add("ocw-sendbtn-label"),g.setAttribute("aria-label",l)):(g.innerHTML=cn,g.setAttribute("aria-label","Send message")),g.disabled=!0,this.sendBtn=g,g.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var C,K;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some($=>$.senderRole==="guest")?(K=(C=this.h).onDeflectQuery)==null||K.call(C,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",C=>{C.isComposing||C.keyCode===229||(C.key==="Enter"&&!C.shiftKey?(C.preventDefault(),this.flushSend()):this.signalTyping())});const v=a("button","ocw-attach","📎");v.title="Attach image or file";const S=document.createElement("input");S.type="file",S.accept="image/*,.pdf,.txt,.doc,.docx",S.style.display="none",v.addEventListener("click",()=>S.click()),S.addEventListener("change",()=>{var C;(C=S.files)!=null&&C[0]&&this.h.onAttach&&this.h.onAttach(S.files[0]),S.value=""});const A=a("div","ocw-input");A.append(v,S,this.input,g);const z=a("div","ocw-footer");((M=i.i18n)==null?void 0:M.poweredBy)!==void 0?z.textContent=i.i18n.poweredBy:z.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=z,this.reopenBtn=a("button","ocw-reopen",((W=this.cfg.i18n)==null?void 0:W.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const C=this.root.querySelector(".ocw-input textarea");C==null||C.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,A,this.reopenBtn,this.footer);const w=C=>{e.classList.toggle("ocw-compact",C>0&&C<an)};w(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(C=>{var $;const K=(($=C[0])==null?void 0:$.contentRect.width)??e.clientWidth;w(K)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var S,A,z,w,f,E,I,x;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const y=(S=this.cfg.subject)==null?void 0:S.ownerLabel;y&&(this.headerName.textContent=y)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const y of n)this.chips.append(this.chipEl(y));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const y=a("div","ocw-load-more");y.textContent="↑ Loading earlier messages…",y.style.pointerEvents="none",this.scroll.append(y)}let s=0,r=null;for(const y of e.messages()){const q=y.senderRole!=="system"&&y.senderId!==this.me&&!y.internal&&y.senderId!==r;this.scroll.append(this.messageEl(y,e,q)),y.senderRole!=="system"&&(r=y.senderId),y.senderId!==this.me&&y.seq>s&&(s=y.seq)}i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const u=[...e.typing];this.typing.classList.toggle("active",u.length>0);const d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",u.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const p=e.messages().some(y=>y.senderRole==="guest");if(!!((A=e.preChat)!=null&&A.enabled)&&!this.preChatDone&&!p&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(z=this.root.querySelector(".ocw-input"))==null||z.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(a("span","ocw-away-icon","🌙"),a("span","",""));const y=this.awayNotice.lastChild;y.textContent=e.offlineMessage||((w=this.cfg.i18n)==null?void 0:w.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(f=this.root.querySelector(".ocw-input"))==null||f.style.removeProperty("display")}const l=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&l.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const v=l.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((E=this.cfg.i18n)==null?void 0:E.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((I=this.cfg.i18n)==null?void 0:I.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",v&&e.messages().length>0){const y=a("div","ocw-resolved-note",`— ${((x=this.cfg.i18n)==null?void 0:x.resolved)??"Marked as resolved"} —`);this.scroll.append(y),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const o=e==="error";this.connStatus.className=`ocw-conn-status${o?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=o?`⚠ ${n??"Chat unavailable"}`:e==="reconnecting"?n??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var d;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(a("div","ocw-prechat-title",e.title??"Before we start…"));const n=a("div","ocw-offline-form"),o={};for(const p of e.fields??["name","email"]){const g=a("input","ocw-offline-input");g.type=p==="email"?"email":p==="phone"?"tel":"text",g.placeholder=p==="name"?"Your name":p==="email"?"Your email":"Your phone number",o[p]=g,n.append(g)}let i=null;if((d=e.topics)!=null&&d.length){i=a("select",void 0);const p=document.createElement("option");p.value="",p.textContent="What is this about?",i.append(p);for(const g of e.topics){const l=document.createElement("option");l.value=g,l.textContent=g,i.append(l)}n.append(i)}let s=null,r=null;if(e.callbackOption){const p=a("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",p.append(s,document.createTextNode("📞 Request a call back")),n.append(p),o.phone||(r=a("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),n.append(r))}const u=a("button","ocw-offline-submit","Start chat");u.type="button",u.addEventListener("click",()=>{var v,S,A,z,w,f,E;const p=(v=o.email)==null?void 0:v.value.trim();if(o.email&&(!p||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p))){o.email.focus();return}const g=!!(s!=null&&s.checked),l=(((S=o.phone)==null?void 0:S.value)??(r==null?void 0:r.value)??"").trim();if(g&&!l){(A=o.phone??r)==null||A.focus();return}if(i&&((z=e.topics)!=null&&z.length)&&!i.value){i.focus();return}u.disabled=!0,this.completePreChat(),(E=(f=this.h).onPreChat)==null||E.call(f,{...(w=o.name)!=null&&w.value.trim()?{name:o.name.value.trim()}:{},...p?{email:p}:{},...l?{phone:l}:{},...i!=null&&i.value?{topic:i.value}:{},...g?{callback:!0}:{}})}),n.append(u),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(a("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const n of e.slice(0,3)){const o=a("button","ocw-deflect-card");o.append(a("div","ocw-deflect-q",n.title),a("div","ocw-deflect-a",n.answer)),o.addEventListener("click",()=>o.classList.toggle("open")),this.deflectPanel.append(o)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(a("div","ocw-csat-title","How did we do?"));const e=a("div","ocw-csat-stars"),n=[];for(let o=1;o<=5;o++){const i=a("button","ocw-csat-star","★");i.dataset.score=String(o),i.addEventListener("mouseenter",()=>n.forEach((s,r)=>s.classList.toggle("lit",r<o))),i.addEventListener("mouseleave",()=>n.forEach(s=>s.classList.remove("lit"))),i.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(a("div","ocw-csat-done",`Thanks for your ${o}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,o)}),n.push(i),e.append(i)}this.csatPanel.append(e)}buildSubjectCard(e){if(this.subjectBuilt)return;const n=e.subject,o=this.cfg.subject,i=(n==null?void 0:n.title)??(o==null?void 0:o.title);if(!i)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(a("div","ocw-subject-title",i)),o!=null&&o.subtitle&&this.subjectCard.append(a("div","ocw-subject-sub",o.subtitle));const s=a("div","ocw-tags");if(n)for(const[u,d]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${u}: ${d}`));else for(const u of(o==null?void 0:o.tags)??[])s.append(a("span","ocw-tag",u));s.childNodes.length&&this.subjectCard.append(s);const r=(n==null?void 0:n.state)??(o==null?void 0:o.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const n=a("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return n.dataset.actionId=e.id,n.addEventListener("click",async()=>{var o;e.confirm&&!await this.confirm(e.label)||((o=e.input)!=null&&o.length?this.openForm(e):this.h.onInvoke(e.id))}),n}confirm(e){return new Promise(n=>{const o=a("div","ocw-modal"),i=a("div","ocw-modal-card");i.append(a("div","ocw-modal-title",e)),i.append(a("div","ocw-modal-body",`Confirm “${e}”?`));const s=a("div","ocw-modal-actions"),r=a("button","ocw-modal-cancel","Cancel"),u=a("button","ocw-modal-ok","Confirm"),d=p=>{o.remove(),n(p)};r.addEventListener("click",()=>d(!1)),u.addEventListener("click",()=>d(!0)),o.addEventListener("click",p=>{p.target===o&&d(!1)}),s.append(r,u),i.append(s),o.append(i),this.root.append(o),u.focus()})}openForm(e){var u,d;this.formHost.replaceChildren();const n=a("div","ocw-form");n.append(a("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const o=new Map;for(const p of e.input??[]){const g=a("label","ocw-form-row");if(g.append(a("span","ocw-form-lbl",p.label)),p.type==="select"&&((u=p.options)!=null&&u.length)){const l=a("select","ocw-form-input");p.required||l.append(a("option",void 0,"— select —"));for(const v of p.options){const S=a("option");S.value=v,S.textContent=v,l.append(S)}p.required&&(l.required=!0),g.append(l),o.set(p.name,l)}else{const l=a("input","ocw-form-input");l.type=p.type==="number"?"number":p.type==="date"?"datetime-local":"text",p.required&&(l.required=!0),g.append(l),o.set(p.name,l)}n.append(g)}const i=a("div","ocw-form-actions"),s=a("button","ocw-form-cancel","Cancel"),r=a("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const p={};for(const[g,l]of o){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}p[g]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,p)}),i.append(s,r),n.append(i),this.formHost.append(n),(d=o.values().next().value)==null||d.focus()}messageEl(e,n,o=!1){var v,S,A,z;if(e.senderRole==="system"){const w=a("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":Pe(e.content),w}const i=e.senderId===this.me,s=!!e.internal,r=a("div",`ocw-row ${s?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!i&&!s&&r.append(a("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const u=a("div");if(o){const w=e.senderRole==="bot"?((v=this.cfg.i18n)==null?void 0:v.aiAssistant)??"AI Assistant":((S=this.cfg.subject)==null?void 0:S.ownerLabel)??((A=this.cfg.subject)==null?void 0:A.title)??"Support";u.append(a("div","ocw-msg-sender",w))}const d=a("div","ocw-bubble-wrap");if(e.replyToId){const w=a("div","ocw-reply-to","↩ replying to a message");w.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",u.append(w)}const p=a("div","ocw-bubble");let g=null;if(e.deletedAt)p.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((z=w.mime)!=null&&z.startsWith("image/")){const f=document.createElement("img");f.src=w.url,f.alt=w.name??"image",f.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",f.addEventListener("click",()=>window.open(w.url,"_blank")),p.append(f)}else{const f=document.createElement("a");f.href=w.url,f.target="_blank",f.rel="noopener",f.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",f.append(a("span",void 0,"📄"),a("span",void 0,w.name??"file")),p.append(f)}}else if(e.content.kind==="appointment"){const w=e.content,f=a("div","ocw-appt");f.append(a("div","ocw-appt-title",`📅 ${w.title}`)),f.append(a("div","ocw-appt-time",new Date(w.startIso).toLocaleString()+" – "+new Date(w.endIso).toLocaleTimeString())),w.location&&f.append(a("div","ocw-appt-loc",`📍 ${w.location}`)),w.description&&f.append(a("div","ocw-appt-desc",w.description));const E=a("div","ocw-appt-links"),I=document.createElement("a");I.href=w.googleUrl,I.target="_blank",I.rel="noopener",I.className="ocw-appt-btn",I.textContent="📅 Add to Google Calendar";const x=document.createElement("a");x.href=w.icalUrl,x.download=`${w.title}.ics`,x.className="ocw-appt-btn ocw-appt-btn-sec",x.textContent="🍎 Apple / iCal",E.append(I,x),f.append(E),p.append(f)}else g=document.createTextNode(Pe(e.content)),p.append(g),e.editedAt&&p.append(a("span","ocw-edited","(edited)"));if(d.append(p),!i&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&g){const w=e.content.text;if(w.trim()){const f=a("button","ocw-translate-btn","🌐");f.type="button",f.title="Translate",f.addEventListener("click",E=>{if(E.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),g.textContent=w,f.textContent="🌐",f.title="Translate";return}const I=this.translationCache.get(e.id);if(I!==void 0){this.showingTranslation.add(e.id),g.textContent=I,f.textContent="↩",f.title="Show original";return}f.textContent="⏳",this.h.onTranslate(w).then(x=>{if(x===null){f.textContent="⚠️",f.title="Translation unavailable",setTimeout(()=>{f.textContent="🌐",f.title="Translate"},1500);return}this.translationCache.set(e.id,x),this.showingTranslation.add(e.id),g.textContent=x,f.textContent="↩",f.title="Show original"})}),d.append(f)}}if(i&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const w=a("div","ocw-msg-menu");if(this.h.onEdit){const f=a("button",void 0,"✏️");f.title="Edit",f.addEventListener("click",E=>{E.stopPropagation();const I=Pe(e.content),x=document.createElement("textarea");x.value=I,x.rows=Math.min(4,Math.ceil(I.length/40)+1),x.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:var(--ocw-card);color:#1c1b1a;box-sizing:border-box";const y=a("button","ocw-form-submit","Save");y.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const q=a("button","ocw-form-cancel","Cancel");q.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const _=a("div");_.style.cssText="display:flex;gap:6px;justify-content:flex-end",_.append(q,y);const j=a("div");j.append(x,_),p.replaceChildren(j),x.focus(),x.select();const k=()=>p.replaceChildren(g??document.createTextNode(I));q.addEventListener("click",k),y.addEventListener("click",()=>{const M=x.value.trim();M&&M!==I&&this.h.onEdit(e.id,M),k()}),x.addEventListener("keydown",M=>{M.key==="Enter"&&!M.shiftKey&&(M.preventDefault(),y.click()),M.key==="Escape"&&k()})}),w.append(f)}if(this.h.onDelete){const f=a("button","del","🗑");f.title="Delete",f.addEventListener("click",E=>{E.stopPropagation(),this.h.onDelete(e.id)}),w.append(f)}d.append(w)}if(u.append(d),this.h.onReact&&!e.deletedAt&&e.seq>0){const w=a("div","ocw-react-wrap"),f=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[x,y]of Object.entries(e.reactions)){const q=a("button",`ocw-react-pill${y.includes(this.me)?" mine":""}`,`${x} ${y.length}`);q.addEventListener("click",()=>{var _,j;return(j=(_=this.h).onReact)==null?void 0:j.call(_,e.id,x,y.includes(this.me))}),f.append(q)}const E=a("button","ocw-react-btn","+"),I=a("div","ocw-react-picker");for(const x of rn){const y=a("button",void 0,x);y.addEventListener("click",q=>{var j,k,M,W;q.stopPropagation();const _=(k=(j=e.reactions)==null?void 0:j[x])==null?void 0:k.includes(this.me);(W=(M=this.h).onReact)==null||W.call(M,e.id,x,!!_),I.style.display="none"}),I.append(y)}I.style.display="none",E.addEventListener("click",x=>{x.stopPropagation();const y=I.style.display==="none";I.style.display=y?"flex":"none",y&&document.addEventListener("click",()=>{I.style.display="none"},{once:!0})}),f.append(E),w.append(f,I),u.append(w)}else e.reactions&&Object.keys(e.reactions).length&&u.append(a("div","ocw-react",Object.entries(e.reactions).map(([w,f])=>`${w}${f.length}`).join(" ")));const l=a("div","ocw-time ocw-meta",dn(e.ts));if(i&&e.status){const w=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,pn(e.status));l.append(w)}return i&&e.seq>0&&n.lastReadByOthers>=e.seq&&l.append(a("span","ocw-seen"," · Seen")),u.append(l),r.append(u),r}}function pn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const un=20;function _e(t,e){var d;const n=t.trim().replace(/\/+$/,""),o=(d=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:d[1],i=o?o==="https"||o==="wss":!0,s=(o?n.slice(o.length+3):n).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${i?"https":"http"}://${s}`;return{wsUrl:`${i?"wss":"ws"}://${s}/ws`,httpBase:r}}function fn(t){return _e(t).httpBase}function wn(t,e,n,o){const i=`beforeSeq=${n}&limit=${o}`;return[`${t}/conversations/${e}/messages?${i}`,`${t}/conversations/${e}/history?${i}`]}async function nt(t,e,n,o,i=un){let s,r=!1;for(const u of wn(t,e,o,i))try{const d=await fetch(u,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!d.ok)continue;const p=await d.json();return{messages:p.messages??[],hasMore:p.hasMore??!1}}catch(d){s=d}return r?console.error(`[chat-widget] history request to ${t} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${t} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function gn(t,e,n,o,i,s){const r=s?s.replace(/\/+$/,""):fn(t),u=await nt(r,n,e,Number.MAX_SAFE_INTEGER);if(!u||(u.messages.length?(o.apply({type:"sync",conversationId:n,messages:u.messages}),o.apply({type:"history",conversationId:n,messages:[],hasMore:u.hasMore}),i.render(o)):o.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!u.hasMore))return;let d=!1;const p=async()=>{if(d||!o.hasMoreHistory)return;d=!0;const S=o.messages()[0];if(!S){d=!1;return}const A=await nt(r,n,e,S.seq);A&&(o.apply({type:"history",conversationId:n,messages:A.messages,hasMore:A.hasMore}),i.render(o)),d=!1},g=i.getScrollEl();if(!g)return;let l=!1;setTimeout(()=>{l=!0},300);const v=()=>{l&&g.scrollTop<80&&o.hasMoreHistory&&!d&&p()};g.addEventListener("scroll",v,{passive:!0}),i.setScrollCleanup(()=>g.removeEventListener("scroll",v))}const de=new WeakMap,be=new Map;function it(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let he=null;function xn(){if(he&&he.state!=="closed")return he;try{return he=new AudioContext,he}catch{return null}}function ot(t){var N,V,F,X,U,ie,se,Ie;de.has(t.el)&&(de.get(t.el).close(),de.delete(t.el)),t.launcher&&((N=be.get(it(t)))==null||N.close());const e=He();let n,o=!1;const i=t.token??t.userId??e,s=i!==e?e:void 0,{wsUrl:r,httpBase:u}=_e(t.url,t.apiUrl);let d=new Gt(i);const p=t.subjectId?`${i}::${t.subjectId}`:i,g=new en(p);let l,v=!1,S=null,A=null,z=null,w=null;!t.launcher&&!t.el.style.height&&t.el.clientHeight===0&&(t.el.style.width=t.el.style.width||"100%",t.el.style.height="600px");for(const h of g.load())d.addOptimistic(h.clientMsgId,h.content);let f=null,E=null,I=0,x=!t.launcher;if(t.launcher){const m=(t.position??"bottom-right").includes("right");f=document.createElement("div"),f.style.cssText=`position:fixed;${m?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${m?"flex-end":"flex-start"};gap:12px`;const T=document.createElement("div"),O=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,we=P=>{t.el.classList.toggle("ocw-fs",P),T.style.cssText=P?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(m?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};we((O==null?void 0:O.matches)??!1);const ge=P=>we(P.matches);O==null||O.addEventListener("change",ge),S=O,A=ge,t.el.style.cssText="width:100%;height:100%;overflow:hidden",T.append(t.el);const Ce='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Te='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',G=document.createElement("button");G.type="button",G.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${t.accent??"#6c5ce7"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 12px 32px rgba(108,92,231,.14)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),G.onmouseenter=()=>{G.style.transform="scale(1.08)"},G.onmouseleave=()=>{G.style.transform="scale(1)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#4c6fff;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const Ee=()=>{G.innerHTML=x?Te:Ce,G.setAttribute("aria-label",x?"Close chat":"Open chat"),G.setAttribute("aria-expanded",String(x)),G.append(E)};Ee(),f.append(T,G),document.body.append(f);const je=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let R=null;const Ln=()=>{try{return sessionStorage.getItem(je)==="1"}catch{return!1}},An='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',at=()=>{const P=Ue!=null&&Ue.title?Ue:d.launcherMessage??void 0;if(!(!!(P!=null&&P.title)&&!x&&!Ln())){R&&(R.remove(),R=null);return}if(R)return;R=document.createElement("div"),R.setAttribute("role","button"),R.setAttribute("tabindex","0"),R.setAttribute("aria-label",P.title),R.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${m?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Oe=document.createElement("div");if(Oe.textContent=P.title,Oe.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",R.append(Oe),P.subtitle){const ee=document.createElement("div");ee.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Fe=document.createElement("span");Fe.innerHTML=An,Fe.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const lt=document.createElement("span");lt.textContent=P.subtitle,ee.append(Fe,lt),R.append(ee)}const re=document.createElement("button");re.type="button",re.setAttribute("aria-label","Dismiss"),re.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',re.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",re.addEventListener("click",ee=>{ee.stopPropagation();try{sessionStorage.setItem(je,"1")}catch{}R&&(R.remove(),R=null)}),R.append(re);const ct=()=>{x||(x=!0,Ne(!0),Ee(),I=0,E&&(E.style.display="none"),R&&(R.remove(),R=null))};R.addEventListener("click",ct),R.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),ct())}),f.insertBefore(R,G)};if(!document.getElementById("ocw-teaser-style")){const P=document.createElement("style");P.id="ocw-teaser-style",P.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(P)}w=at,at();const Ne=P=>{P?(T.style.display="flex",requestAnimationFrame(()=>{T.style.opacity="1",T.style.transform="scale(1)"})):(T.style.opacity="0",T.style.transform="scale(.95)",setTimeout(()=>{x||(T.style.display="none")},180))};G.addEventListener("click",()=>{if(x=!x,Ne(x),Ee(),x){I=0,E&&(E.style.display="none");try{sessionStorage.setItem(je,"1")}catch{}}w==null||w()}),z=P=>{P.key==="Escape"&&x&&(x=!1,Ne(!1),Ee())},document.addEventListener("keydown",z)}const y=()=>{x||(I++,E&&(E.textContent=String(I),E.style.display="flex"))},q=()=>{try{const h=xn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const m=h.createOscillator(),T=h.createGain();m.connect(T),T.connect(h.destination),m.frequency.setValueAtTime(880,h.currentTime),m.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),T.gain.setValueAtTime(.3,h.currentTime),T.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),m.start(),m.stop(h.currentTime+.3)}catch{}},_=[],j=h=>{for(;_.length;){const m=_.shift();g.add({clientMsgId:m.clientMsgId,content:m.content,ts:Date.now()}),k.send({type:"send",conversationId:h,clientMsgId:m.clientMsgId,content:m.content})}};let k;const M=t.i18n??{},W=["ar","he","fa","ur"],C=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";W.includes(C)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const K=`oc_prechat_${t.profileId}_${i.slice(-8)}`,$=new hn(t.el,i,{onSend(h){const m=`cm_${Math.random().toString(36).slice(2)}`,T={kind:"text",text:h};if(d.addOptimistic(m,T),$.render(d),d.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else l?(g.add({clientMsgId:m,content:T,ts:Date.now()}),k.send({type:"send",conversationId:l,clientMsgId:m,content:T})):_.push({clientMsgId:m,content:T})},async onAttach(h){if(!l)return;const m=`${u}/upload?name=${encodeURIComponent(h.name)}`,T=`cm_${Math.random().toString(36).slice(2)}`;d.addOptimistic(T,{kind:"text",text:`📎 Uploading ${h.name}…`}),$.render(d);try{const O=await fetch(m,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${i}`},body:h});if(!O.ok)throw new Error(`Upload failed: ${O.status}`);const{url:we,name:ge,mime:Ce,size:Te}=await O.json();d.addOptimistic(T,{kind:"attachment",url:we,name:ge,mime:Ce,size:Te}),$.render(d),k.send({type:"send",conversationId:l,clientMsgId:T,content:{kind:"attachment",url:we,name:ge,mime:Ce,size:Te}})}catch(O){d.addOptimistic(T,{kind:"text",text:`⚠️ Upload failed: ${O.message}`}),$.render(d)}},onInvoke(h,m){l&&k.send({type:"invoke",conversationId:l,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...m?{inputs:m}:{}})},onTyping(h,m){l&&k.send({type:"typing",conversationId:l,isTyping:h,...m?{preview:m}:{}})},onPreChat(h){try{localStorage.setItem(K,"1")}catch{}k.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const m=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";m&&l&&!d.e2e&&k.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:m}})},...((V=t.features)==null?void 0:V.deflection)!==!1?{onDeflectQuery(h){if(o)return;clearTimeout(n);const m=h.trim();if(m.length<3){$.hideDeflection();return}n=setTimeout(()=>{fetch(`${u}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(m.slice(0,200))}`).then(T=>T.ok?T.json():{articles:[]}).then(T=>$.showDeflection(T.articles??[])).catch(()=>$.hideDeflection())},350)}}:{},onReadUpTo(h){l&&k.send({type:"read",conversationId:l,seq:h})},onLoadMore(){if(!l||!d.e2e)return;const h=d.messages()[0];h&&k.send({type:"history",conversationId:l,beforeSeq:h.seq,limit:20})},onEdit(h,m){l&&k.send({type:"edit",conversationId:l,messageId:h,content:{kind:"text",text:m}})},onDelete(h){l&&k.send({type:"delete",conversationId:l,messageId:h})},...((F=t.features)==null?void 0:F.reactions)!==!1?{onReact(h,m,T){l&&k.send({type:"react",conversationId:l,messageId:h,emoji:m,remove:T})}}:{},...((X=t.features)==null?void 0:X.csat)!==!1?{onCsat(h){l&&fetch(`${u}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({score:h})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(h){try{const m=await fetch(`${u}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:h,targetLang:t.translateLang})});if(!m.ok)return null;const{translated:T}=await m.json();return T}catch{return null}}}:{},...t.onBack?{onBack:t.onBack}:{}},{...t.subject?{subject:t.subject}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...(U=t.user)!=null&&U.name||(ie=t.user)!=null&&ie.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:M});try{localStorage.getItem(K)&&$.completePreChat()}catch{}const fe=t.user&&(t.user.name||t.user.email||t.user.avatar||t.user.meta)?{...t.user.name?{name:t.user.name}:{},...t.user.email?{email:t.user.email}:{},...t.user.avatar?{avatar:t.user.avatar}:{},...t.user.meta?{meta:t.user.meta}:{}}:void 0,Se={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...fe?{userInfo:fe}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(se=t.subject)!=null&&se.title?{subjectTitle:t.subject.title}:{},...(Ie=t.subject)!=null&&Ie.subtitle?{subjectMeta:t.subject.subtitle}:{}};k=new Yt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:i,open:Se,getCursor:()=>d.highestSeq(),onStatusChange:(h,m)=>$.setConnStatus(h,m),onFrame(h){if(h.type==="opened"){if(l=h.conversation.id,!v){v=!0;for(const m of g.load())k.send({type:"send",conversationId:l,clientMsgId:m.clientMsgId,content:m.content})}gn(r,i,l,d,$,u),_.length&&j(l)}h.type==="ack"&&g.remove(h.clientMsgId),(async()=>(d.apply(h),h.type==="manifest"&&(w==null||w()),h.type==="message"&&h.message.senderId!==i&&!h.message.internal&&(y(),q()),$.render(d)))()}}),k.connect(),$.render(d);const b=t.launcher?it(t):null,L={close:()=>{o=!0,clearTimeout(n),k.close(),f==null||f.remove(),$.destroy(),S&&A&&S.removeEventListener("change",A),z&&(document.removeEventListener("keydown",z),z=null),de.delete(t.el),b&&be.get(b)===L&&be.delete(b)}};return de.set(t.el,L),b&&be.set(b,L),L}const De="wss://api.paramms.com/ws";function mn(t,e){const n=t.profileId??t.appId;if(!n)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const o=t.subjectId??(t.listingId?`listing_${t.listingId}`:void 0),i=t.launcher??!0,s=t.contextTitle??t.listingTitle??t.subjectTitle,r=t.contextSubtitle??t.listingMeta??t.subjectMeta,u=t.contextStatus??t.listingStatus??t.subjectStatus,d=t.listingPrice??t.subjectPrice,p=s?{title:s,...r?{subtitle:r}:{},...d!=null?{tags:[`$${d.toLocaleString()}`]}:{},...u?{status:u}:{}}:void 0,g=t.subject??p,l=t.userName??t.name,v=t.userEmail??t.email,S=t.userAvatar??t.avatar,A=l||v||S?{...l?{name:l}:{},...v?{email:v}:{},...S?{avatar:S}:{}}:void 0,z=t.user??A,w=t.launcherMessage&&typeof t.launcherMessage=="object"?t.launcherMessage:t.launcherMessage?t.launcherSubtitle?{title:t.launcherMessage,subtitle:t.launcherSubtitle}:t.launcherMessage:void 0;return{el:e,url:t.url??De,profileId:n,...t.apiUrl?{apiUrl:t.apiUrl}:{},...o?{subjectId:o}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...g?{subject:g}:{},...z?{user:z}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.translateLang?{translateLang:t.translateLang}:{},...w?{launcherMessage:w}:{},...st(t)&&!i?{onBack:()=>{pe=!0,ue=!1,ve(ne)}}:{},launcher:i,position:t.position??"bottom-right"}}let Q=null,D=null,te=!1,ne={},pe=!1,ue=!1;function st(t){return!!(t.inbox||t.inboxStart)}let Z=null;function yn(t,e){const n=!e&&!!t.el;if(te&&!n&&(D.innerHTML="",D=null,te=!1),n){const o=typeof t.el=="string"?document.querySelector(t.el):t.el;o instanceof HTMLElement?(D&&D!==o&&!te&&D.remove(),D=o,te=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!D||!te&&!D.isConnected)&&(D=document.createElement("div"),D.id="relay-widget-root",document.body.appendChild(D),te=!1),!e&&t.height&&(D.style.height=t.height,D.style.width||(D.style.width="100%")),D}function ve(t){try{const e=t.launcher??!0;Z==null||Z(),Z=null,Q==null||Q.close(),Q=null;const n=yn(t,e);if(st(t)&&!e&&pe){bn(t,n);return}Q=ot(mn(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function bn(t,e){const n=t.profileId??t.appId;if(!n&&!t.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const o=document.createElement("div");o.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const i=document.createElement("div");i.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{pe=!1,ve(ne)},o.append(i,s);const u=!ue&&!!n;u&&o.append(r),e.appendChild(o);let d=null,p=null;Z=()=>{p==null||p.close(),d==null||d.close(),e.innerHTML=""};let g;try{({mountChatList:g}=await Promise.resolve().then(()=>Bn))}catch(v){console.error("[Relay] could not load the conversation list module.",v),i.isConnected&&(i.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",i.textContent="Could not load conversations.");return}if(!i.isConnected)return;const l=v=>{const S=v.profileId??n;if(!S){console.error("[Relay] conversation row has no chatroom; cannot open it.",v);return}r.style.display="none",p==null||p.close(),p=ot({el:s,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:S,...v.kind==="direct"&&v.peerId?{kind:"direct",peerId:v.peerId}:v.subjectId?{subjectId:v.subjectId}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...t.userId||t.userName||t.userEmail||t.userAvatar?{user:{...t.userName?{name:t.userName}:{},...t.userEmail?{email:t.userEmail}:{},...t.userAvatar?{avatar:t.userAvatar}:{}}}:{},...v.subjectTitle?{subject:{title:v.subjectTitle,...v.subjectMeta?{subtitle:v.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{p==null||p.close(),p=null,s.style.display="none",i.style.display="",r.style.display="",d==null||d.refresh()}}),i.style.display="none",s.style.display=""};d=g({el:i,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...u?{reserveCloseSpace:!0}:{},onSelect:l,onNewChat:()=>{const v=n??(d==null?void 0:d.defaultProfileId());v&&l({id:"__new__",profileId:v,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function rt(t){ue=!!(t.inboxStart&&!(t.launcher??!0)),pe=ue,ne={...t},ve(ne)}function vn(t){ne={...ne,...t},ve(ne)}function kn(){Z==null||Z(),Z=null,Q==null||Q.close(),Q=null,D&&!te&&D.remove(),D=null,te=!1,pe=!1,ue=!1,ne={}}function qe(t,e){switch(t){case"boot":rt(e??{});break;case"update":case"identify":vn(e??{});break;case"shutdown":kn();break;default:console.warn("[Relay] unknown command:",t)}}function Sn(){if(typeof document>"u")return null;const t=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=t==null?void 0:t.dataset,n=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),o=e==null?void 0:e.relayTenantId;if(!n&&!o)return null;const i=n?{profileId:n}:{};o&&(i.tenantId=o),e.relayUser&&(i.userId=e.relayUser),e.relayToken&&(i.token=e.relayToken),e.relayListing&&(i.listingId=e.relayListing),e.relayAccent&&(i.accent=e.relayAccent),e.relayAccent2&&(i.accent2=e.relayAccent2),e.relayTheme&&(i.theme=e.relayTheme),e.relayUrl&&(i.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(i.position=s),e.relayLauncherMessage&&(i.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(i.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(i.launcher=!1),e.relayUserName&&(i.userName=e.relayUserName),e.relayUserEmail&&(i.userEmail=e.relayUserEmail),e.relayUserAvatar&&(i.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(i.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(i.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(i.contextStatus=e.relayContextStatus),e.relayListingTitle&&(i.listingTitle=e.relayListingTitle),e.relayListingMeta&&(i.listingMeta=e.relayListingMeta),e.relayListingPrice&&(i.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(i.listingStatus=e.relayListingStatus),e.relayTarget&&(i.el=e.relayTarget),e.relayHeight&&(i.height=e.relayHeight),e.relayInbox==="true"&&(i.inbox=!0),e.relayInbox==="false"&&(i.inbox=!1),e.relayInboxStart==="true"&&(i.inboxStart=!0),e.relayInboxStart==="false"&&(i.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(i.inboxScope=r),e.relayTranslateLang&&(i.translateLang=e.relayTranslateLang),i}if(typeof window<"u"){const t=window,e=t.Relay&&t.Relay.q?t.Relay.q:[];t.Relay=qe;let n=!1;for(const o of e){const[i,s]=o;i==="boot"&&(n=!0),qe(i,s)}if(!n){const o=t.relaySettings??Sn();o&&rt(o)}}const In=`
192
+ `,tt="objectchat-widget-styles",an=["👍","❤️","😂","😮","😢","🙏"],cn=400,ln='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function dn(){if(typeof document>"u"||document.getElementById(tt))return;const t=document.createElement("style");t.id=tt,t.textContent=rn,document.head.appendChild(t)}const nt="ocw-webfont";function hn(){if(typeof document>"u"||document.getElementById(nt))return;const t=document.createElement("link");t.id=nt,t.rel="stylesheet",t.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.appendChild(t)}function a(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function pn(t){try{return new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Pe(t){var e;switch(t.kind){case"text":return t.text;case"system":return typeof((e=t.data)==null?void 0:e.message)=="string"?String(t.data.message):t.event;case"card":return[t.title,t.body].filter(Boolean).join(" — ");case"attachment":return t.name??t.url;case"form":return t.prompt;case"appointment":return`📅 ${t.title} — ${new Date(t.startIso).toLocaleString()}`}}class un{constructor(e,n,i,o={}){c(this,"scroll");c(this,"chips");c(this,"typing");c(this,"quick");c(this,"formHost");c(this,"csatPanel");c(this,"awayNotice");c(this,"headStatus");c(this,"reopenBtn");c(this,"preChatPanel");c(this,"deflectPanel");c(this,"preChatBuilt",!1);c(this,"preChatDone",!1);c(this,"footer");c(this,"input");c(this,"subjectCard");c(this,"e2eBadge");c(this,"statusBadge");c(this,"headerName");c(this,"connStatus");c(this,"typingTimer",null);c(this,"csatSubmitted",!1);c(this,"sendBtn");c(this,"compactObserver",null);c(this,"storeRef",null);c(this,"cfgAccent2");c(this,"scrollCleanup",null);c(this,"translationCache",new Map);c(this,"showingTranslation",new Set);c(this,"subjectBuilt",!1);var f,T,I,m,b,q,_,j,k,M,W;this.root=e,this.me=n,this.h=i,this.cfg=o,dn(),o.webfont!==!1&&hn(),e.replaceChildren(),e.classList.add("ocw"),o.accent&&e.style.setProperty("--ocw-accent",o.accent);const s=o.accent2??o.accent;s&&e.style.setProperty("--ocw-accent2",s),this.cfgAccent2=o.accent2,e.dataset.theme=o.theme??"light";const r=a("div","ocw-head");if(this.h.onBack){const C=a("button","ocw-back","‹");C.type="button",C.setAttribute("aria-label","Back"),C.addEventListener("click",()=>this.h.onBack()),r.append(C)}const u=a("div","ocw-avatar");if((f=o.userInfo)!=null&&f.avatar){const C=document.createElement("img");C.src=o.userInfo.avatar,C.alt=o.userInfo.name??"You",C.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",u.append(C)}else u.textContent=(T=o.userInfo)!=null&&T.name?o.userInfo.name[0].toUpperCase():"🧑";r.append(u);const d=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((I=o.subject)==null?void 0:I.ownerLabel)??((m=o.subject)==null?void 0:m.title)??""),d.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",d.append(this.headStatus),(b=o.subject)!=null&&b.subtitle&&d.append(a("div","ocw-head-meta",o.subject.subtitle)),r.append(d),this.statusBadge=a("span","ocw-badge",((q=o.subject)==null?void 0:q.status)??""),(_=o.subject)!=null&&_.status||(this.statusBadge.style.display="none"),r.append(this.statusBadge),this.e2eBadge=a("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",r.append(this.e2eBadge),this.connStatus=a("span","ocw-conn-status"),this.connStatus.style.display="none",r.append(this.connStatus),r.append(a("button","ocw-menu","⋯")),this.chips=a("div","ocw-chiprow"),this.scroll=a("div","ocw-scroll"),this.subjectCard=a("div","ocw-subject"),this.typing=a("div","ocw-typing");const p=a("div","ocw-typing-bubble");p.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(a("div","ocw-dot","🧑"),p),this.quick=a("div","ocw-quick");for(const C of o.quickReplies??[]){const K=a("button",void 0,C);K.addEventListener("click",()=>{this.h.onSend(C),this.quick.style.display="none"}),this.quick.append(K)}this.formHost=a("div","ocw-form-host"),this.csatPanel=a("div","ocw-csat"),this.csatPanel.style.display="none",this.awayNotice=a("div","ocw-away"),this.awayNotice.style.display="none",this.preChatPanel=a("div","ocw-prechat"),this.preChatPanel.style.display="none",this.deflectPanel=a("div","ocw-deflect"),this.deflectPanel.style.display="none",this.input=a("textarea",void 0),this.input.rows=1,this.input.placeholder=((j=o.i18n)==null?void 0:j.placeholder)??"Message…";const g=a("button","ocw-sendbtn");g.type="button";const l=(k=o.i18n)==null?void 0:k.send;l?(g.textContent=l,g.classList.add("ocw-sendbtn-label"),g.setAttribute("aria-label",l)):(g.innerHTML=ln,g.setAttribute("aria-label","Send message")),g.disabled=!0,this.sendBtn=g,g.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var C,K;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some($=>$.senderRole==="guest")?(K=(C=this.h).onDeflectQuery)==null||K.call(C,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",C=>{C.isComposing||C.keyCode===229||(C.key==="Enter"&&!C.shiftKey?(C.preventDefault(),this.flushSend()):this.signalTyping())});const v=a("button","ocw-attach","📎");v.title="Attach image or file";const S=document.createElement("input");S.type="file",S.accept="image/*,.pdf,.txt,.doc,.docx",S.style.display="none",v.addEventListener("click",()=>S.click()),S.addEventListener("change",()=>{var C;(C=S.files)!=null&&C[0]&&this.h.onAttach&&this.h.onAttach(S.files[0]),S.value=""});const A=a("div","ocw-input");A.append(v,S,this.input,g);const z=a("div","ocw-footer");((M=o.i18n)==null?void 0:M.poweredBy)!==void 0?z.textContent=o.i18n.poweredBy:z.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=z,this.reopenBtn=a("button","ocw-reopen",((W=this.cfg.i18n)==null?void 0:W.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const C=this.root.querySelector(".ocw-input textarea");C==null||C.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,A,this.reopenBtn,this.footer);const w=C=>{e.classList.toggle("ocw-compact",C>0&&C<cn)};w(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(C=>{var $;const K=(($=C[0])==null?void 0:$.contentRect.width)??e.clientWidth;w(K)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var S,A,z,w,f,T,I,m;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const b=(S=this.cfg.subject)==null?void 0:S.ownerLabel;b&&(this.headerName.textContent=b)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const b of n)this.chips.append(this.chipEl(b));const i=this.scroll.scrollHeight,o=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const b=a("div","ocw-load-more");b.textContent="↑ Loading earlier messages…",b.style.pointerEvents="none",this.scroll.append(b)}let s=0,r=null;for(const b of e.messages()){const q=b.senderRole!=="system"&&b.senderId!==this.me&&!b.internal&&b.senderId!==r;this.scroll.append(this.messageEl(b,e,q)),b.senderRole!=="system"&&(r=b.senderId),b.senderId!==this.me&&b.seq>s&&(s=b.seq)}o>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+o:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const u=[...e.typing];this.typing.classList.toggle("active",u.length>0);const d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",u.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const p=e.messages().some(b=>b.senderRole==="guest");if(!!((A=e.preChat)!=null&&A.enabled)&&!this.preChatDone&&!p&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(z=this.root.querySelector(".ocw-input"))==null||z.style.setProperty("display","none");else{if(this.preChatPanel.style.display="none",e.offline){this.awayNotice.firstChild||this.awayNotice.append(a("span","ocw-away-icon","🌙"),a("span","",""));const b=this.awayNotice.lastChild;b.textContent=e.offlineMessage||((w=this.cfg.i18n)==null?void 0:w.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(f=this.root.querySelector(".ocw-input"))==null||f.style.removeProperty("display")}const l=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&l.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const v=l.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((T=this.cfg.i18n)==null?void 0:T.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((I=this.cfg.i18n)==null?void 0:I.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",v&&e.messages().length>0){const b=a("div","ocw-resolved-note",`— ${((m=this.cfg.i18n)==null?void 0:m.resolved)??"Marked as resolved"} —`);this.scroll.append(b),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const i=e==="error";this.connStatus.className=`ocw-conn-status${i?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=i?`⚠ ${n??"Chat unavailable"}`:e==="reconnecting"?n??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var d;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(a("div","ocw-prechat-title",e.title??"Before we start…"));const n=a("div","ocw-offline-form"),i={};for(const p of e.fields??["name","email"]){const g=a("input","ocw-offline-input");g.type=p==="email"?"email":p==="phone"?"tel":"text",g.placeholder=p==="name"?"Your name":p==="email"?"Your email":"Your phone number",i[p]=g,n.append(g)}let o=null;if((d=e.topics)!=null&&d.length){o=a("select",void 0);const p=document.createElement("option");p.value="",p.textContent="What is this about?",o.append(p);for(const g of e.topics){const l=document.createElement("option");l.value=g,l.textContent=g,o.append(l)}n.append(o)}let s=null,r=null;if(e.callbackOption){const p=a("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",p.append(s,document.createTextNode("📞 Request a call back")),n.append(p),i.phone||(r=a("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",s.addEventListener("change",()=>r.style.setProperty("display",s.checked?"block":"none")),n.append(r))}const u=a("button","ocw-offline-submit","Start chat");u.type="button",u.addEventListener("click",()=>{var v,S,A,z,w,f,T;const p=(v=i.email)==null?void 0:v.value.trim();if(i.email&&(!p||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p))){i.email.focus();return}const g=!!(s!=null&&s.checked),l=(((S=i.phone)==null?void 0:S.value)??(r==null?void 0:r.value)??"").trim();if(g&&!l){(A=i.phone??r)==null||A.focus();return}if(o&&((z=e.topics)!=null&&z.length)&&!o.value){o.focus();return}u.disabled=!0,this.completePreChat(),(T=(f=this.h).onPreChat)==null||T.call(f,{...(w=i.name)!=null&&w.value.trim()?{name:i.name.value.trim()}:{},...p?{email:p}:{},...l?{phone:l}:{},...o!=null&&o.value?{topic:o.value}:{},...g?{callback:!0}:{}})}),n.append(u),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(a("div","ocw-deflect-hint","Instant answers — tap to expand"));for(const n of e.slice(0,3)){const i=a("button","ocw-deflect-card");i.append(a("div","ocw-deflect-q",n.title),a("div","ocw-deflect-a",n.answer)),i.addEventListener("click",()=>i.classList.toggle("open")),this.deflectPanel.append(i)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(a("div","ocw-csat-title","How did we do?"));const e=a("div","ocw-csat-stars"),n=[];for(let i=1;i<=5;i++){const o=a("button","ocw-csat-star","★");o.dataset.score=String(i),o.addEventListener("mouseenter",()=>n.forEach((s,r)=>s.classList.toggle("lit",r<i))),o.addEventListener("mouseleave",()=>n.forEach(s=>s.classList.remove("lit"))),o.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(a("div","ocw-csat-done",`Thanks for your ${i}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,i)}),n.push(o),e.append(o)}this.csatPanel.append(e)}buildSubjectCard(e){if(this.subjectBuilt)return;const n=e.subject,i=this.cfg.subject,o=(n==null?void 0:n.title)??(i==null?void 0:i.title);if(!o)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(a("div","ocw-subject-title",o)),i!=null&&i.subtitle&&this.subjectCard.append(a("div","ocw-subject-sub",i.subtitle));const s=a("div","ocw-tags");if(n)for(const[u,d]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${u}: ${d}`));else for(const u of(i==null?void 0:i.tags)??[])s.append(a("span","ocw-tag",u));s.childNodes.length&&this.subjectCard.append(s);const r=(n==null?void 0:n.state)??(i==null?void 0:i.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const n=a("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return n.dataset.actionId=e.id,n.addEventListener("click",async()=>{var i;e.confirm&&!await this.confirm(e.label)||((i=e.input)!=null&&i.length?this.openForm(e):this.h.onInvoke(e.id))}),n}confirm(e){return new Promise(n=>{const i=a("div","ocw-modal"),o=a("div","ocw-modal-card");o.append(a("div","ocw-modal-title",e)),o.append(a("div","ocw-modal-body",`Confirm “${e}”?`));const s=a("div","ocw-modal-actions"),r=a("button","ocw-modal-cancel","Cancel"),u=a("button","ocw-modal-ok","Confirm"),d=p=>{i.remove(),n(p)};r.addEventListener("click",()=>d(!1)),u.addEventListener("click",()=>d(!0)),i.addEventListener("click",p=>{p.target===i&&d(!1)}),s.append(r,u),o.append(s),i.append(o),this.root.append(i),u.focus()})}openForm(e){var u,d;this.formHost.replaceChildren();const n=a("div","ocw-form");n.append(a("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const i=new Map;for(const p of e.input??[]){const g=a("label","ocw-form-row");if(g.append(a("span","ocw-form-lbl",p.label)),p.type==="select"&&((u=p.options)!=null&&u.length)){const l=a("select","ocw-form-input");p.required||l.append(a("option",void 0,"— select —"));for(const v of p.options){const S=a("option");S.value=v,S.textContent=v,l.append(S)}p.required&&(l.required=!0),g.append(l),i.set(p.name,l)}else{const l=a("input","ocw-form-input");l.type=p.type==="number"?"number":p.type==="date"?"datetime-local":"text",p.required&&(l.required=!0),g.append(l),i.set(p.name,l)}n.append(g)}const o=a("div","ocw-form-actions"),s=a("button","ocw-form-cancel","Cancel"),r=a("button","ocw-form-submit","Send");s.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const p={};for(const[g,l]of i){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}p[g]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,p)}),o.append(s,r),n.append(o),this.formHost.append(n),(d=i.values().next().value)==null||d.focus()}messageEl(e,n,i=!1){var v,S,A,z;if(e.senderRole==="system"){const w=a("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":Pe(e.content),w}const o=e.senderId===this.me,s=!!e.internal,r=a("div",`ocw-row ${s?"ocw-note mine":o?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!o&&!s&&r.append(a("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const u=a("div");if(i){const w=e.senderRole==="bot"?((v=this.cfg.i18n)==null?void 0:v.aiAssistant)??"AI Assistant":((S=this.cfg.subject)==null?void 0:S.ownerLabel)??((A=this.cfg.subject)==null?void 0:A.title)??"Support";u.append(a("div","ocw-msg-sender",w))}const d=a("div","ocw-bubble-wrap");if(e.replyToId){const w=a("div","ocw-reply-to","↩ replying to a message");w.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",u.append(w)}const p=a("div","ocw-bubble");let g=null;if(e.deletedAt)p.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((z=w.mime)!=null&&z.startsWith("image/")){const f=document.createElement("img");f.src=w.url,f.alt=w.name??"image",f.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",f.addEventListener("click",()=>window.open(w.url,"_blank")),p.append(f)}else{const f=document.createElement("a");f.href=w.url,f.target="_blank",f.rel="noopener",f.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",f.append(a("span",void 0,"📄"),a("span",void 0,w.name??"file")),p.append(f)}}else if(e.content.kind==="appointment"){const w=e.content,f=a("div","ocw-appt");f.append(a("div","ocw-appt-title",`📅 ${w.title}`)),f.append(a("div","ocw-appt-time",new Date(w.startIso).toLocaleString()+" – "+new Date(w.endIso).toLocaleTimeString())),w.location&&f.append(a("div","ocw-appt-loc",`📍 ${w.location}`)),w.description&&f.append(a("div","ocw-appt-desc",w.description));const T=a("div","ocw-appt-links"),I=document.createElement("a");I.href=w.googleUrl,I.target="_blank",I.rel="noopener",I.className="ocw-appt-btn",I.textContent="📅 Add to Google Calendar";const m=document.createElement("a");m.href=w.icalUrl,m.download=`${w.title}.ics`,m.className="ocw-appt-btn ocw-appt-btn-sec",m.textContent="🍎 Apple / iCal",T.append(I,m),f.append(T),p.append(f)}else g=document.createTextNode(Pe(e.content)),p.append(g),e.editedAt&&p.append(a("span","ocw-edited","(edited)"));if(d.append(p),!o&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&g){const w=e.content.text;if(w.trim()){const f=a("button","ocw-translate-btn","🌐");f.type="button",f.title="Translate",f.addEventListener("click",T=>{if(T.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),g.textContent=w,f.textContent="🌐",f.title="Translate";return}const I=this.translationCache.get(e.id);if(I!==void 0){this.showingTranslation.add(e.id),g.textContent=I,f.textContent="↩",f.title="Show original";return}f.textContent="⏳",this.h.onTranslate(w).then(m=>{if(m===null){f.textContent="⚠️",f.title="Translation unavailable",setTimeout(()=>{f.textContent="🌐",f.title="Translate"},1500);return}this.translationCache.set(e.id,m),this.showingTranslation.add(e.id),g.textContent=m,f.textContent="↩",f.title="Show original"})}),d.append(f)}}if(o&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const w=a("div","ocw-msg-menu");if(this.h.onEdit){const f=a("button",void 0,"✏️");f.title="Edit",f.addEventListener("click",T=>{T.stopPropagation();const I=Pe(e.content),m=document.createElement("textarea");m.value=I,m.rows=Math.min(4,Math.ceil(I.length/40)+1),m.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:var(--ocw-card);color:#1c1b1a;box-sizing:border-box";const b=a("button","ocw-form-submit","Save");b.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const q=a("button","ocw-form-cancel","Cancel");q.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const _=a("div");_.style.cssText="display:flex;gap:6px;justify-content:flex-end",_.append(q,b);const j=a("div");j.append(m,_),p.replaceChildren(j),m.focus(),m.select();const k=()=>p.replaceChildren(g??document.createTextNode(I));q.addEventListener("click",k),b.addEventListener("click",()=>{const M=m.value.trim();M&&M!==I&&this.h.onEdit(e.id,M),k()}),m.addEventListener("keydown",M=>{M.key==="Enter"&&!M.shiftKey&&(M.preventDefault(),b.click()),M.key==="Escape"&&k()})}),w.append(f)}if(this.h.onDelete){const f=a("button","del","🗑");f.title="Delete",f.addEventListener("click",T=>{T.stopPropagation(),this.h.onDelete(e.id)}),w.append(f)}d.append(w)}if(u.append(d),this.h.onReact&&!e.deletedAt&&e.seq>0){const w=a("div","ocw-react-wrap"),f=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[m,b]of Object.entries(e.reactions)){const q=a("button",`ocw-react-pill${b.includes(this.me)?" mine":""}`,`${m} ${b.length}`);q.addEventListener("click",()=>{var _,j;return(j=(_=this.h).onReact)==null?void 0:j.call(_,e.id,m,b.includes(this.me))}),f.append(q)}const T=a("button","ocw-react-btn","+"),I=a("div","ocw-react-picker");for(const m of an){const b=a("button",void 0,m);b.addEventListener("click",q=>{var j,k,M,W;q.stopPropagation();const _=(k=(j=e.reactions)==null?void 0:j[m])==null?void 0:k.includes(this.me);(W=(M=this.h).onReact)==null||W.call(M,e.id,m,!!_),I.style.display="none"}),I.append(b)}I.style.display="none",T.addEventListener("click",m=>{m.stopPropagation();const b=I.style.display==="none";I.style.display=b?"flex":"none",b&&document.addEventListener("click",()=>{I.style.display="none"},{once:!0})}),f.append(T),w.append(f,I),u.append(w)}else e.reactions&&Object.keys(e.reactions).length&&u.append(a("div","ocw-react",Object.entries(e.reactions).map(([w,f])=>`${w}${f.length}`).join(" ")));const l=a("div","ocw-time ocw-meta",pn(e.ts));if(o&&e.status){const w=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,fn(e.status));l.append(w)}return o&&e.seq>0&&n.lastReadByOthers>=e.seq&&l.append(a("span","ocw-seen"," · Seen")),u.append(l),r.append(u),r}}function fn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const wn=20;function _e(t,e){var d;const n=t.trim().replace(/\/+$/,""),i=(d=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:d[1],o=i?i==="https"||i==="wss":!0,s=(i?n.slice(i.length+3):n).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${o?"https":"http"}://${s}`;return{wsUrl:`${o?"wss":"ws"}://${s}/ws`,httpBase:r}}function gn(t){return _e(t).httpBase}function xn(t,e,n,i){const o=`beforeSeq=${n}&limit=${i}`;return[`${t}/conversations/${e}/messages?${o}`,`${t}/conversations/${e}/history?${o}`]}async function ot(t,e,n,i,o=wn){let s,r=!1;for(const u of xn(t,e,i,o))try{const d=await fetch(u,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!d.ok)continue;const p=await d.json();return{messages:p.messages??[],hasMore:p.hasMore??!1}}catch(d){s=d}return r?console.error(`[chat-widget] history request to ${t} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${t} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function mn(t,e,n,i,o,s){const r=s?s.replace(/\/+$/,""):gn(t),u=await ot(r,n,e,Number.MAX_SAFE_INTEGER);if(!u||(u.messages.length?(i.apply({type:"sync",conversationId:n,messages:u.messages}),i.apply({type:"history",conversationId:n,messages:[],hasMore:u.hasMore}),o.render(i)):i.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!u.hasMore))return;let d=!1;const p=async()=>{if(d||!i.hasMoreHistory)return;d=!0;const S=i.messages()[0];if(!S){d=!1;return}const A=await ot(r,n,e,S.seq);A&&(i.apply({type:"history",conversationId:n,messages:A.messages,hasMore:A.hasMore}),o.render(i)),d=!1},g=o.getScrollEl();if(!g)return;let l=!1;setTimeout(()=>{l=!0},300);const v=()=>{l&&g.scrollTop<80&&i.hasMoreHistory&&!d&&p()};g.addEventListener("scroll",v,{passive:!0}),o.setScrollCleanup(()=>g.removeEventListener("scroll",v))}const de=new WeakMap,be=new Map;function it(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let he=null;function yn(){if(he&&he.state!=="closed")return he;try{return he=new AudioContext,he}catch{return null}}function st(t){var N,V,F,X,U,oe,se,Ie;de.has(t.el)&&(de.get(t.el).close(),de.delete(t.el)),t.launcher&&((N=be.get(it(t)))==null||N.close());const e=He();let n,i=!1;const o=t.token??t.userId??e,s=o!==e?e:void 0,{wsUrl:r,httpBase:u}=_e(t.url,t.apiUrl);let d=new Yt(o);const p=t.subjectId?`${o}::${t.subjectId}`:o,g=new tn(p);let l,v=!1,S=null,A=null,z=null,w=null;!t.launcher&&!t.el.style.height&&t.el.clientHeight===0&&(t.el.style.width=t.el.style.width||"100%",t.el.style.height="600px");for(const h of g.load())d.addOptimistic(h.clientMsgId,h.content);let f=null,T=null,I=0,m=!t.launcher;if(t.launcher){const y=(t.position??"bottom-right").includes("right");f=document.createElement("div"),f.style.cssText=`position:fixed;${y?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${y?"flex-end":"flex-start"};gap:12px`;const E=document.createElement("div"),O=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,we=P=>{t.el.classList.toggle("ocw-fs",P),E.style.cssText=P?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(y?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};we((O==null?void 0:O.matches)??!1);const ge=P=>we(P.matches);O==null||O.addEventListener("change",ge),S=O,A=ge,t.el.style.cssText="width:100%;height:100%;overflow:hidden",E.append(t.el);const Ce='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ee='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',G=document.createElement("button");G.type="button",G.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${t.accent??"#6c5ce7"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 12px 32px rgba(108,92,231,.14)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),G.onmouseenter=()=>{G.style.transform="scale(1.08)"},G.onmouseleave=()=>{G.style.transform="scale(1)"},T=document.createElement("span"),T.style.cssText="position:absolute;top:-4px;right:-4px;background:#4c6fff;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const Te=()=>{G.innerHTML=m?Ee:Ce,G.setAttribute("aria-label",m?"Close chat":"Open chat"),G.setAttribute("aria-expanded",String(m)),G.append(T)};Te(),f.append(E,G),document.body.append(f);const je=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let R=null;const zn=()=>{try{return sessionStorage.getItem(je)==="1"}catch{return!1}},Mn='<svg viewBox="0 0 24 24" width="15" height="15" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',ct=()=>{const P=Ue!=null&&Ue.title?Ue:d.launcherMessage??void 0;if(!(!!(P!=null&&P.title)&&!m&&!zn())){R&&(R.remove(),R=null);return}if(R)return;R=document.createElement("div"),R.setAttribute("role","button"),R.setAttribute("tabindex","0"),R.setAttribute("aria-label",P.title),R.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${y?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Oe=document.createElement("div");if(Oe.textContent=P.title,Oe.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",R.append(Oe),P.subtitle){const ee=document.createElement("div");ee.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Fe=document.createElement("span");Fe.innerHTML=Mn,Fe.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const dt=document.createElement("span");dt.textContent=P.subtitle,ee.append(Fe,dt),R.append(ee)}const re=document.createElement("button");re.type="button",re.setAttribute("aria-label","Dismiss"),re.innerHTML='<svg viewBox="0 0 24 24" width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',re.style.cssText="position:absolute;top:8px;right:8px;width:24px;height:24px;border:none;border-radius:50%;background:#f3f4f6;color:#6b7280;cursor:pointer;display:flex;align-items:center;justify-content:center;padding:0",re.addEventListener("click",ee=>{ee.stopPropagation();try{sessionStorage.setItem(je,"1")}catch{}R&&(R.remove(),R=null)}),R.append(re);const lt=()=>{m||(m=!0,Ne(!0),Te(),I=0,T&&(T.style.display="none"),R&&(R.remove(),R=null))};R.addEventListener("click",lt),R.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),lt())}),f.insertBefore(R,G)};if(!document.getElementById("ocw-teaser-style")){const P=document.createElement("style");P.id="ocw-teaser-style",P.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(P)}w=ct,ct();const Ne=P=>{P?(E.style.display="flex",requestAnimationFrame(()=>{E.style.opacity="1",E.style.transform="scale(1)"})):(E.style.opacity="0",E.style.transform="scale(.95)",setTimeout(()=>{m||(E.style.display="none")},180))};G.addEventListener("click",()=>{if(m=!m,Ne(m),Te(),m){I=0,T&&(T.style.display="none");try{sessionStorage.setItem(je,"1")}catch{}}w==null||w()}),z=P=>{P.key==="Escape"&&m&&(m=!1,Ne(!1),Te())},document.addEventListener("keydown",z)}const b=()=>{m||(I++,T&&(T.textContent=String(I),T.style.display="flex"))},q=()=>{try{const h=yn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const y=h.createOscillator(),E=h.createGain();y.connect(E),E.connect(h.destination),y.frequency.setValueAtTime(880,h.currentTime),y.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),E.gain.setValueAtTime(.3,h.currentTime),E.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),y.start(),y.stop(h.currentTime+.3)}catch{}},_=[],j=h=>{for(;_.length;){const y=_.shift();g.add({clientMsgId:y.clientMsgId,content:y.content,ts:Date.now()}),k.send({type:"send",conversationId:h,clientMsgId:y.clientMsgId,content:y.content})}};let k;const M=t.i18n??{},W=["ar","he","fa","ur"],C=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";W.includes(C)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const K=`oc_prechat_${t.profileId}_${o.slice(-8)}`,$=new un(t.el,o,{onSend(h){const y=`cm_${Math.random().toString(36).slice(2)}`,E={kind:"text",text:h};if(d.addOptimistic(y,E),$.render(d),d.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else l?(g.add({clientMsgId:y,content:E,ts:Date.now()}),k.send({type:"send",conversationId:l,clientMsgId:y,content:E})):_.push({clientMsgId:y,content:E})},async onAttach(h){if(!l)return;const y=`${u}/upload?name=${encodeURIComponent(h.name)}`,E=`cm_${Math.random().toString(36).slice(2)}`;d.addOptimistic(E,{kind:"text",text:`📎 Uploading ${h.name}…`}),$.render(d);try{const O=await fetch(y,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${o}`},body:h});if(!O.ok)throw new Error(`Upload failed: ${O.status}`);const{url:we,name:ge,mime:Ce,size:Ee}=await O.json();d.addOptimistic(E,{kind:"attachment",url:we,name:ge,mime:Ce,size:Ee}),$.render(d),k.send({type:"send",conversationId:l,clientMsgId:E,content:{kind:"attachment",url:we,name:ge,mime:Ce,size:Ee}})}catch(O){d.addOptimistic(E,{kind:"text",text:`⚠️ Upload failed: ${O.message}`}),$.render(d)}},onInvoke(h,y){l&&k.send({type:"invoke",conversationId:l,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...y?{inputs:y}:{}})},onTyping(h,y){l&&k.send({type:"typing",conversationId:l,isTyping:h,...y?{preview:y}:{}})},onPreChat(h){try{localStorage.setItem(K,"1")}catch{}k.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const y=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";y&&l&&!d.e2e&&k.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:y}})},...((V=t.features)==null?void 0:V.deflection)!==!1?{onDeflectQuery(h){if(i)return;clearTimeout(n);const y=h.trim();if(y.length<3){$.hideDeflection();return}n=setTimeout(()=>{fetch(`${u}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(y.slice(0,200))}`).then(E=>E.ok?E.json():{articles:[]}).then(E=>$.showDeflection(E.articles??[])).catch(()=>$.hideDeflection())},350)}}:{},onReadUpTo(h){l&&k.send({type:"read",conversationId:l,seq:h})},onLoadMore(){if(!l||!d.e2e)return;const h=d.messages()[0];h&&k.send({type:"history",conversationId:l,beforeSeq:h.seq,limit:20})},onEdit(h,y){l&&k.send({type:"edit",conversationId:l,messageId:h,content:{kind:"text",text:y}})},onDelete(h){l&&k.send({type:"delete",conversationId:l,messageId:h})},...((F=t.features)==null?void 0:F.reactions)!==!1?{onReact(h,y,E){l&&k.send({type:"react",conversationId:l,messageId:h,emoji:y,remove:E})}}:{},...((X=t.features)==null?void 0:X.csat)!==!1?{onCsat(h){l&&fetch(`${u}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({score:h})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(h){try{const y=await fetch(`${u}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({text:h,targetLang:t.translateLang})});if(!y.ok)return null;const{translated:E}=await y.json();return E}catch{return null}}}:{},...t.onBack?{onBack:t.onBack}:{}},{...t.subject?{subject:t.subject}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...(U=t.user)!=null&&U.name||(oe=t.user)!=null&&oe.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:M});try{localStorage.getItem(K)&&$.completePreChat()}catch{}const fe=t.user&&(t.user.name||t.user.email||t.user.avatar||t.user.meta)?{...t.user.name?{name:t.user.name}:{},...t.user.email?{email:t.user.email}:{},...t.user.avatar?{avatar:t.user.avatar}:{},...t.user.meta?{meta:t.user.meta}:{}}:void 0,Se={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...fe?{userInfo:fe}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(se=t.subject)!=null&&se.title?{subjectTitle:t.subject.title}:{},...(Ie=t.subject)!=null&&Ie.subtitle?{subjectMeta:t.subject.subtitle}:{}};k=new Xt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:o,open:Se,getCursor:()=>d.highestSeq(),onStatusChange:(h,y)=>$.setConnStatus(h,y),onFrame(h){if(h.type==="opened"){if(l=h.conversation.id,!v){v=!0;for(const y of g.load())k.send({type:"send",conversationId:l,clientMsgId:y.clientMsgId,content:y.content})}mn(r,o,l,d,$,u),_.length&&j(l)}h.type==="ack"&&g.remove(h.clientMsgId),(async()=>(d.apply(h),h.type==="manifest"&&(w==null||w()),h.type==="message"&&h.message.senderId!==o&&!h.message.internal&&(b(),q()),$.render(d)))()}}),k.connect(),$.render(d);const x=t.launcher?it(t):null,L={close:()=>{i=!0,clearTimeout(n),k.close(),f==null||f.remove(),$.destroy(),S&&A&&S.removeEventListener("change",A),z&&(document.removeEventListener("keydown",z),z=null),de.delete(t.el),x&&be.get(x)===L&&be.delete(x)}};return de.set(t.el,L),x&&be.set(x,L),L}const De="wss://api.paramms.com/ws";function bn(t,e){const n=t.profileId??t.appId;if(!n)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const i=t.subjectId??(t.listingId?`listing_${t.listingId}`:void 0),o=t.launcher??!0,s=t.contextTitle??t.listingTitle??t.subjectTitle,r=t.contextSubtitle??t.listingMeta??t.subjectMeta,u=t.contextStatus??t.listingStatus??t.subjectStatus,d=t.listingPrice??t.subjectPrice,p=s?{title:s,...r?{subtitle:r}:{},...d!=null?{tags:[`$${d.toLocaleString()}`]}:{},...u?{status:u}:{}}:void 0,g=t.subject??p,l=t.userName??t.name,v=t.userEmail??t.email,S=t.userAvatar??t.avatar,A=l||v||S?{...l?{name:l}:{},...v?{email:v}:{},...S?{avatar:S}:{}}:void 0,z=t.user??A,w=t.launcherMessage&&typeof t.launcherMessage=="object"?t.launcherMessage:t.launcherMessage?t.launcherSubtitle?{title:t.launcherMessage,subtitle:t.launcherSubtitle}:t.launcherMessage:void 0;return{el:e,url:t.url??De,profileId:n,...t.apiUrl?{apiUrl:t.apiUrl}:{},...i?{subjectId:i}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...g?{subject:g}:{},...z?{user:z}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...w?{launcherMessage:w}:{},...rt(t)&&!o?{onBack:()=>{pe=!0,ue=!1,ve(ne)}}:{},launcher:o,position:t.position??"bottom-right"}}let Q=null,D=null,te=!1,ne={},pe=!1,ue=!1;function rt(t){return!!(t.inbox||t.inboxStart)}let Z=null;function vn(t,e){const n=!e&&!!t.el;if(te&&!n&&(D.innerHTML="",D=null,te=!1),n){const i=typeof t.el=="string"?document.querySelector(t.el):t.el;i instanceof HTMLElement?(D&&D!==i&&!te&&D.remove(),D=i,te=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!D||!te&&!D.isConnected)&&(D=document.createElement("div"),D.id="relay-widget-root",document.body.appendChild(D),te=!1),!e&&t.height&&(D.style.height=t.height,D.style.width||(D.style.width="100%")),D}function ve(t){try{const e=t.launcher??!0;Z==null||Z(),Z=null,Q==null||Q.close(),Q=null;const n=vn(t,e);if(rt(t)&&!e&&pe){kn(t,n);return}Q=st(bn(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function kn(t,e){const n=t.profileId??t.appId;if(!n&&!t.tenantId){console.error("[Relay] `inbox` requires `profileId` or `tenantId`.");return}e.innerHTML="";const i=document.createElement("div");i.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const o=document.createElement("div");o.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{pe=!1,ve(ne)},i.append(o,s);const u=!ue&&!!n;u&&i.append(r),e.appendChild(i);let d=null,p=null;Z=()=>{p==null||p.close(),d==null||d.close(),e.innerHTML=""};let g;try{({mountChatList:g}=await Promise.resolve().then(()=>An))}catch(v){console.error("[Relay] could not load the conversation list module.",v),o.isConnected&&(o.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",o.textContent="Could not load conversations.");return}if(!o.isConnected)return;const l=v=>{const S=v.profileId??n;if(!S){console.error("[Relay] conversation row has no chatroom; cannot open it.",v);return}r.style.display="none",p==null||p.close(),p=st({el:s,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:S,...v.kind==="direct"&&v.peerId?{kind:"direct",peerId:v.peerId}:v.subjectId?{subjectId:v.subjectId}:{},...t.token?{token:t.token}:{},...t.refreshToken?{refreshToken:t.refreshToken}:{},...t.userId?{userId:t.userId}:{},...t.userId||t.userName||t.userEmail||t.userAvatar?{user:{...t.userName?{name:t.userName}:{},...t.userEmail?{email:t.userEmail}:{},...t.userAvatar?{avatar:t.userAvatar}:{}}}:{},...v.subjectTitle?{subject:{title:v.subjectTitle,...v.subjectMeta?{subtitle:v.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{p==null||p.close(),p=null,s.style.display="none",o.style.display="",r.style.display="",d==null||d.refresh()}}),o.style.display="none",s.style.display=""};d=g({el:o,url:t.url??De,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...u?{reserveCloseSpace:!0}:{},onSelect:l,onNewChat:()=>{const v=n??(d==null?void 0:d.defaultProfileId());v&&l({id:"__new__",profileId:v,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function at(t){ue=!!(t.inboxStart&&!(t.launcher??!0)),pe=ue,ne={...t},ve(ne)}function Sn(t){ne={...ne,...t},ve(ne)}function In(){Z==null||Z(),Z=null,Q==null||Q.close(),Q=null,D&&!te&&D.remove(),D=null,te=!1,pe=!1,ue=!1,ne={}}function qe(t,e){switch(t){case"boot":at(e??{});break;case"update":case"identify":Sn(e??{});break;case"shutdown":In();break;default:console.warn("[Relay] unknown command:",t)}}function Cn(){if(typeof document>"u")return null;const t=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]")??document.querySelector("script[data-relay-tenant-id]"),e=t==null?void 0:t.dataset,n=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId),i=e==null?void 0:e.relayTenantId;if(!n&&!i)return null;const o=n?{profileId:n}:{};i&&(o.tenantId=i),e.relayUser&&(o.userId=e.relayUser),e.relayToken&&(o.token=e.relayToken),e.relayListing&&(o.listingId=e.relayListing),e.relayAccent&&(o.accent=e.relayAccent),e.relayAccent2&&(o.accent2=e.relayAccent2),e.relayTheme&&(o.theme=e.relayTheme),e.relayWebfont==="false"&&(o.webfont=!1),e.relayUrl&&(o.url=e.relayUrl);const s=e.relayPosition;(s==="bottom-left"||s==="bottom-right")&&(o.position=s),e.relayLauncherMessage&&(o.launcherMessage=e.relayLauncherMessage),e.relayLauncherSubtitle&&(o.launcherSubtitle=e.relayLauncherSubtitle),e.relayLauncher==="false"&&(o.launcher=!1),e.relayUserName&&(o.userName=e.relayUserName),e.relayUserEmail&&(o.userEmail=e.relayUserEmail),e.relayUserAvatar&&(o.userAvatar=e.relayUserAvatar),e.relayContextTitle&&(o.contextTitle=e.relayContextTitle),e.relayContextSubtitle&&(o.contextSubtitle=e.relayContextSubtitle),e.relayContextStatus&&(o.contextStatus=e.relayContextStatus),e.relayListingTitle&&(o.listingTitle=e.relayListingTitle),e.relayListingMeta&&(o.listingMeta=e.relayListingMeta),e.relayListingPrice&&(o.listingPrice=Number(e.relayListingPrice)),e.relayListingStatus&&(o.listingStatus=e.relayListingStatus),e.relayTarget&&(o.el=e.relayTarget),e.relayHeight&&(o.height=e.relayHeight),e.relayInbox==="true"&&(o.inbox=!0),e.relayInbox==="false"&&(o.inbox=!1),e.relayInboxStart==="true"&&(o.inboxStart=!0),e.relayInboxStart==="false"&&(o.inboxStart=!1);const r=e.relayInboxScope;return(r==="tenant"||r==="profile")&&(o.inboxScope=r),e.relayTranslateLang&&(o.translateLang=e.relayTranslateLang),o}if(typeof window<"u"){const t=window,e=t.Relay&&t.Relay.q?t.Relay.q:[];t.Relay=qe;let n=!1;for(const i of e){const[o,s]=i;o==="boot"&&(n=!0),qe(o,s)}if(!n){const i=t.relaySettings??Cn();i&&at(i)}}const En=`
193
193
  .ocl { ${et("ocl")}
194
194
  display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
195
195
  font-family:var(--ocl-fb); color:var(--ocl-ink); overflow:hidden; }
196
- @media (prefers-color-scheme: dark) { .ocl:not([data-theme="light"]) { ${ye("ocl")} } }
196
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] { ${ye("ocl")} } }
197
197
  .ocl[data-theme="dark"] { ${ye("ocl")} }
198
198
  .ocl-head { display:flex; align-items:center; padding:16px 16px 10px; background:var(--ocl-bg); }
199
199
  .ocl-title { flex:1; display:flex; align-items:center; color:var(--ocl-accent); }
@@ -222,7 +222,7 @@ var RelayEmbedLite=function(J){"use strict";var zn=Object.defineProperty;var Mn=
222
222
  .ocl-status.waiting { background:var(--ocl-tint); color:var(--ocl-accent); border:1px solid var(--ocl-accent); }
223
223
  .ocl-status.done { background:#eee; color:#777; }
224
224
  .ocl[data-theme="dark"] .ocl-status.done { background:#39325e; color:#b3abd6; }
225
- @media (prefers-color-scheme: dark) { .ocl:not([data-theme="light"]) .ocl-status.done { background:#39325e; color:#b3abd6; } }
225
+ @media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] .ocl-status.done { background:#39325e; color:#b3abd6; } }
226
226
  .ocl-spinner { padding:24px; text-align:center; color:var(--ocl-mut); font-size:13px; }
227
227
  .ocl-compose { border:none; background:var(--ocl-accent); color:var(--ocl-onaccent); width:32px; height:32px; border-radius:50%; font-size:18px; line-height:1; cursor:pointer; box-shadow:var(--ocl-shadow); }
228
228
  .ocl-compose:hover { filter:brightness(1.08); }
@@ -238,5 +238,5 @@ var RelayEmbedLite=function(J){"use strict";var zn=Object.defineProperty;var Mn=
238
238
  .ocl-compact .ocl-search { font-size:16px; }
239
239
  .ocl-compact .ocl-compose { width:36px; height:36px; }
240
240
  .ocl-row:focus-visible, .ocl button:focus-visible, .ocl input:focus-visible { outline:2px solid var(--ocl-accent); outline-offset:2px; border-radius:12px; }
241
- `;function Cn(t){switch(t){case"open":return{label:"Open",cls:"open"};case"awaiting_staff":return{label:"Waiting on you",cls:"waiting"};case"resolved":return{label:"Resolved",cls:"done"};case"closed":return{label:"Closed",cls:"done"};default:return null}}function Tn(t){const e=Math.floor((Date.now()-t)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const n=Math.floor(e/86400);if(n<=7)return`${n}d`;try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${n}d`}}const En='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" fill-opacity="0.12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function B(t,e,n){const o=document.createElement(t);return e&&(o.className=e),n!==void 0&&(o.textContent=n),o}function Un(t){const e=t.token??t.userId??He(),{httpBase:n,wsUrl:o}=_e(t.url,t.apiUrl),i=t.i18n??{},s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const b=document.createElement("style");b.id="ocl-styles",b.textContent=In,document.head.append(b)}const r=B("div","ocl");r.style.setProperty("--ocl-accent",s),t.theme&&t.theme!=="auto"&&(r.dataset.theme=t.theme),t.reserveCloseSpace&&r.classList.add("ocl-has-close");const u=B("div","ocl-head"),d=B("span","ocl-title");if(d.setAttribute("role","img"),d.setAttribute("aria-label",i.title??"Messages"),d.innerHTML=En,u.append(d),t.onNewChat){const b=B("button","ocl-compose","✎");b.title=i.newChat??"New conversation",b.addEventListener("click",()=>t.onNewChat()),u.append(b)}const p=B("div","ocl-search-wrap"),g=B("input","ocl-search");g.placeholder=i.search??"🔍 Search",g.type="search",p.append(g);const l=B("div","ocl-body");l.append(B("div","ocl-spinner","Loading…")),r.append(u,p,l),t.el.replaceChildren(r);const v=b=>{r.classList.toggle("ocl-compact",b>0&&b<400)};v(r.clientWidth);let S=null;if(typeof ResizeObserver<"u"&&(S=new ResizeObserver(b=>{var L;return v(((L=b[0])==null?void 0:L.contentRect.width)??r.clientWidth)}),S.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let A;const z=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let w={};try{w=JSON.parse(localStorage.getItem(z)??"{}")}catch{}const f=()=>{try{localStorage.setItem(z,JSON.stringify(w))}catch{}};let E=[],I=!1;const x=async()=>{const b=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,L=`${n}/conversations/mine?${b}`,N={authorization:`Bearer ${e}`};let V;try{V=await fetch(L,{headers:N})}catch{V=await fetch(L,{headers:N})}if(!V.ok)return[];const F=await V.json();return F.defaultProfileId&&(A=F.defaultProfileId),(F.conversations??[]).sort((X,U)=>U.updatedAt-X.updatedAt)},y=(b,L)=>{if(I)return;const N=L?b.filter(U=>q(U).toLowerCase().includes(L)||(U.lastMessage??"").toLowerCase().includes(L)):b;if(l.replaceChildren(),!N.length){const U=B("div","ocl-empty",L?"No results.":i.empty??"No conversations yet.");if(!L&&t.onNewChat){U.append(B("br"));const ie=B("button","ocl-start",i.newChat??"Start a conversation");ie.addEventListener("click",()=>t.onNewChat()),U.append(ie)}l.append(U);return}const V=U=>(U.lastSeq??0)>(w[U.id]??0),F=N.filter(V),X=N.filter(U=>!V(U));if(F.length){l.append(B("div","ocl-section",`${i.unread??"Unread"} (${F.length})`));for(const U of F)l.append(_(U,V(U)))}if(X.length){l.append(B("div","ocl-section",F.length?i.all??"All conversations":""));for(const U of X)l.append(_(U,!1))}},q=b=>b.subjectTitle??(b.kind==="direct"?b.peerId??"Direct message":"General enquiry"),_=(b,L)=>{var T;const N=q(b),V=(((T=N.match(new RegExp("\\p{L}","u")))==null?void 0:T[0])??N.trim()[0]??"?").toUpperCase(),F=b.lastSeq??0,X=L?Math.max(1,F-(w[b.id]??0)):0,U=B("button",`ocl-row${L?" unread":""}`),ie=B("div","ocl-av",V);U.append(ie);const se=B("div","ocl-info");se.append(B("div","ocl-name",N));const Ie={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};se.append(B("div","ocl-preview",b.lastMessage??Ie[b.state]??b.state)),U.append(se);const h=B("div","ocl-right");h.append(B("div","ocl-time",Tn(b.updatedAt)));const m=Cn(b.state);return m&&h.append(B("div",`ocl-status ${m.cls}`,m.label)),X>0&&h.append(B("div","ocl-badge",String(X>99?"99+":X))),U.append(h),U.addEventListener("click",()=>{var O;F>0&&(w[b.id]=F,f()),U.classList.remove("unread"),(O=h.querySelector(".ocl-badge"))==null||O.remove(),t.onSelect(b)}),U},j=()=>{I||x().then(b=>{I||(E=b,y(b,g.value.trim().toLowerCase()))}).catch(b=>{if(I)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,b);const L=B("div","ocl-empty",i.error??"Could not load conversations.");L.append(B("br"));const N=B("button","ocl-retry",i.retry??"Retry");N.addEventListener("click",()=>{l.replaceChildren(B("div","ocl-spinner","Loading…")),j()}),L.append(N),l.replaceChildren(L)})};g.addEventListener("input",()=>y(E,g.value.trim().toLowerCase())),j();let k=null,M,W,C=0,K=!1;const $=()=>{W||(W=setTimeout(()=>{W=void 0,j()},300))},fe=()=>{if(!I){try{k=new WebSocket(o)}catch{Se();return}k.binaryType="arraybuffer",k.onopen=()=>{C=0,k.send(Re({type:"auth",token:e})),k.send(Re({type:"subscribe_inbox"})),K&&$(),K=!0},k.onmessage=b=>{const L=Xe(new Uint8Array(b.data));L&&L.type==="inbox_event"&&$()},k.onclose=()=>{k=null,Se()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Se=()=>{if(I||M)return;const b=Math.min(15e3,500*2**C++)+Math.random()*250;M=setTimeout(()=>{M=void 0,fe()},b)};return fe(),{refresh:j,close(){I=!0,M&&clearTimeout(M),W&&clearTimeout(W),S==null||S.disconnect(),S=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??A}}}const Bn=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:Un},Symbol.toStringTag,{value:"Module"}));return J.Relay=qe,Object.defineProperty(J,Symbol.toStringTag,{value:"Module"}),J}({});
241
+ `;function Tn(t){switch(t){case"open":return{label:"Open",cls:"open"};case"awaiting_staff":return{label:"Waiting on you",cls:"waiting"};case"resolved":return{label:"Resolved",cls:"done"};case"closed":return{label:"Closed",cls:"done"};default:return null}}function Un(t){const e=Math.floor((Date.now()-t)/1e3);if(e<60)return"just now";if(e<3600)return`${Math.floor(e/60)}m`;if(e<86400)return`${Math.floor(e/3600)}h`;const n=Math.floor(e/86400);if(n<=7)return`${n}d`;try{return new Date(t).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${n}d`}}const Bn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" fill-opacity="0.12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function B(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function Ln(t){const e=t.token??t.userId??He(),{httpBase:n,wsUrl:i}=_e(t.url,t.apiUrl),o=t.i18n??{},s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const x=document.createElement("style");x.id="ocl-styles",x.textContent=En,document.head.append(x)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const x=document.createElement("link");x.id="ocw-webfont",x.rel="stylesheet",x.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.append(x)}const r=B("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const u=B("div","ocl-head"),d=B("span","ocl-title");if(d.setAttribute("role","img"),d.setAttribute("aria-label",o.title??"Messages"),d.innerHTML=Bn,u.append(d),t.onNewChat){const x=B("button","ocl-compose","✎");x.title=o.newChat??"New conversation",x.addEventListener("click",()=>t.onNewChat()),u.append(x)}const p=B("div","ocl-search-wrap"),g=B("input","ocl-search");g.placeholder=o.search??"🔍 Search",g.type="search",p.append(g);const l=B("div","ocl-body");l.append(B("div","ocl-spinner","Loading…")),r.append(u,p,l),t.el.replaceChildren(r);const v=x=>{r.classList.toggle("ocl-compact",x>0&&x<400)};v(r.clientWidth);let S=null;if(typeof ResizeObserver<"u"&&(S=new ResizeObserver(x=>{var L;return v(((L=x[0])==null?void 0:L.contentRect.width)??r.clientWidth)}),S.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let A;const z=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let w={};try{w=JSON.parse(localStorage.getItem(z)??"{}")}catch{}const f=()=>{try{localStorage.setItem(z,JSON.stringify(w))}catch{}};let T=[],I=!1;const m=async()=>{const x=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,L=`${n}/conversations/mine?${x}`,N={authorization:`Bearer ${e}`};let V;try{V=await fetch(L,{headers:N})}catch{V=await fetch(L,{headers:N})}if(!V.ok)return[];const F=await V.json();return F.defaultProfileId&&(A=F.defaultProfileId),(F.conversations??[]).sort((X,U)=>U.updatedAt-X.updatedAt)},b=(x,L)=>{if(I)return;const N=L?x.filter(U=>q(U).toLowerCase().includes(L)||(U.lastMessage??"").toLowerCase().includes(L)):x;if(l.replaceChildren(),!N.length){const U=B("div","ocl-empty",L?"No results.":o.empty??"No conversations yet.");if(!L&&t.onNewChat){U.append(B("br"));const oe=B("button","ocl-start",o.newChat??"Start a conversation");oe.addEventListener("click",()=>t.onNewChat()),U.append(oe)}l.append(U);return}const V=U=>(U.lastSeq??0)>(w[U.id]??0),F=N.filter(V),X=N.filter(U=>!V(U));if(F.length){l.append(B("div","ocl-section",`${o.unread??"Unread"} (${F.length})`));for(const U of F)l.append(_(U,V(U)))}if(X.length){l.append(B("div","ocl-section",F.length?o.all??"All conversations":""));for(const U of X)l.append(_(U,!1))}},q=x=>x.subjectTitle??(x.kind==="direct"?x.peerId??"Direct message":"General enquiry"),_=(x,L)=>{var E;const N=q(x),V=(((E=N.match(new RegExp("\\p{L}","u")))==null?void 0:E[0])??N.trim()[0]??"?").toUpperCase(),F=x.lastSeq??0,X=L?Math.max(1,F-(w[x.id]??0)):0,U=B("button",`ocl-row${L?" unread":""}`),oe=B("div","ocl-av",V);U.append(oe);const se=B("div","ocl-info");se.append(B("div","ocl-name",N));const Ie={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};se.append(B("div","ocl-preview",x.lastMessage??Ie[x.state]??x.state)),U.append(se);const h=B("div","ocl-right");h.append(B("div","ocl-time",Un(x.updatedAt)));const y=Tn(x.state);return y&&h.append(B("div",`ocl-status ${y.cls}`,y.label)),X>0&&h.append(B("div","ocl-badge",String(X>99?"99+":X))),U.append(h),U.addEventListener("click",()=>{var O;F>0&&(w[x.id]=F,f()),U.classList.remove("unread"),(O=h.querySelector(".ocl-badge"))==null||O.remove(),t.onSelect(x)}),U},j=()=>{I||m().then(x=>{I||(T=x,b(x,g.value.trim().toLowerCase()))}).catch(x=>{if(I)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,x);const L=B("div","ocl-empty",o.error??"Could not load conversations.");L.append(B("br"));const N=B("button","ocl-retry",o.retry??"Retry");N.addEventListener("click",()=>{l.replaceChildren(B("div","ocl-spinner","Loading…")),j()}),L.append(N),l.replaceChildren(L)})};g.addEventListener("input",()=>b(T,g.value.trim().toLowerCase())),j();let k=null,M,W,C=0,K=!1;const $=()=>{W||(W=setTimeout(()=>{W=void 0,j()},300))},fe=()=>{if(!I){try{k=new WebSocket(i)}catch{Se();return}k.binaryType="arraybuffer",k.onopen=()=>{C=0,k.send(Re({type:"auth",token:e})),k.send(Re({type:"subscribe_inbox"})),K&&$(),K=!0},k.onmessage=x=>{const L=Xe(new Uint8Array(x.data));L&&L.type==="inbox_event"&&$()},k.onclose=()=>{k=null,Se()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Se=()=>{if(I||M)return;const x=Math.min(15e3,500*2**C++)+Math.random()*250;M=setTimeout(()=>{M=void 0,fe()},x)};return fe(),{refresh:j,close(){I=!0,M&&clearTimeout(M),W&&clearTimeout(W),S==null||S.disconnect(),S=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??A}}}const An=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:Ln},Symbol.toStringTag,{value:"Module"}));return J.Relay=qe,Object.defineProperty(J,Symbol.toStringTag,{value:"Module"}),J}({});
242
242
  //# sourceMappingURL=embed-lite.js.map