@paramms/chat-widget 1.7.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var RelayEmbedLite=function(ee){"use strict";var Dn=Object.defineProperty;var Nn=(ee,X,ce)=>X in ee?Dn(ee,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):ee[X]=ce;var c=(ee,X,ce)=>Nn(ee,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function ut(t,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function ft(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function We(){let t=null;try{t=localStorage.getItem(X)}catch{}t||(t=ce(X));const e=t??ft();try{localStorage.setItem(X,e)}catch{}return ut(X,e),e}function wt(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 gt(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 xt=new TextEncoder,yt=50;function mt(t,e,n){xt.encodeInto(t,e.subarray(n))}function bt(t,e,n){t.length>yt?mt(t,e,n):gt(t,e,n)}const vt=4096;function Ke(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 l=t[i++]&63;s.push((u&31)<<6|l)}else if((u&240)===224){const l=t[i++]&63,p=t[i++]&63;s.push((u&31)<<12|l<<6|p)}else if((u&248)===240){const l=t[i++]&63,p=t[i++]&63,g=t[i++]&63;let d=(u&7)<<18|l<<12|p<<6|g;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(u);s.length>=vt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const kt=new TextDecoder,St=200;function It(t,e,n){const i=t.subarray(e,e+n);return kt.decode(i)}function Ct(t,e,n){return n>St?It(t,e,n):Ke(t,e,n)}class me{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class V extends Error{constructor(e){super(e);const n=Object.create(V.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V.name})}}const he=4294967295;function Tt(t,e,n){const i=n/4294967296,o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ve(t,e,n){const i=Math.floor(n/4294967296),o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ye(t,e){const n=t.getInt32(e),i=t.getUint32(e+4);return n*4294967296+i}function Et(t,e){const n=t.getUint32(e),i=t.getUint32(e+4);return n*4294967296+i}const Ut=-1,Bt=4294967296-1,Lt=17179869184-1;function At({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Lt)if(e===0&&t<=Bt){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),Ve(i,4,t),n}}function zt(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 Mt(t){if(t instanceof Date){const e=zt(t);return At(e)}else return null}function $t(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=Ye(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Rt(t){const e=$t(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Pt={type:Ut,encode:Mt,decode:Rt},Ie=class Ie{constructor(){c(this,"__brand");c(this,"builtInEncoders",[]);c(this,"builtInDecoders",[]);c(this,"encoders",[]);c(this,"decoders",[]);this.register(Pt)}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 me(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 me(r,s)}}}return e instanceof me?e:null}decode(e,n,i){const o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(e,n,i):new me(n,e)}};c(Ie,"defaultCodec",new Ie);let be=Ie;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 Dt=100,Nt=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)??be.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)??Dt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Nt,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=wt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),bt(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),Tt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ve(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 qt(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const jt=16,Ot=16;class Ht{constructor(e=jt,n=Ot){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=Ke(e,n,i),r=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(r,s),s}}const ze="array",pe="map_key",Ge="map_value",Ft=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new V("The type of key must be string or number but "+typeof t)};class Wt{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=pe,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===pe||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 ue=-1,Me=new DataView(new ArrayBuffer(0)),Kt=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 Xe=new RangeError("Insufficient data"),Vt=new Ht;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",Kt);c(this,"headByte",ue);c(this,"stack",new Wt);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.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)??he,this.maxBinLength=(e==null?void 0:e.maxBinLength)??he,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??he,this.maxMapLength=(e==null?void 0:e.maxMapLength)??he,this.maxExtLength=(e==null?void 0:e.maxExtLength)??he,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Vt,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Ft}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=ue,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===ue&&!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(l){if(!(l instanceof RangeError))throw l}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 V(`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===pe){if(n==="__proto__")throw new V("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=pe;continue e}}return n}}readHeadByte(){return this.headByte===ue&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ue}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 V(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`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 V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Xe;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=Ct(this.bytes,i,e),this.pos+=n+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===pe:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Xe;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 V(`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=Et(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ye(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 Yt(t,e){return new $e(e).decode(t)}const Gt=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 Xt(t){return Gt.has(t.type)}function Re(t){return qt(t)}function Je(t){let e;try{e=Yt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Jt{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=Qe(n);let o=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Qe(r.status)>=i||(this.byId.set(s,{...r,status:n}),o=!0);o&&(this._sorted=null)}}function Qe(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Qt{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??tn)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Je(new Uint8Array(s.data));!r||Xt(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"&&Zt.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",en(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 Zt=new Set(["UNAUTHORIZED"]);function en(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function tn(t){return new WebSocket(t)}const Ze=200,nn=7*864e5;class on{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()-nn,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>Ze?n.slice(n.length-Ze):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 sn={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)"},rn={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)"},an="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function et(t,e){return Object.entries(e).map(([n,i])=>`--${t}-${n}:${i};`).join(" ")}function tt(t){return`${et(t,sn)} --${t}-fb:${an}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ve(t){return et(t,rn)}const cn=`
1
+ var RelayEmbedLite=function(te){"use strict";var Dn=Object.defineProperty;var Nn=(te,X,ce)=>X in te?Dn(te,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):te[X]=ce;var c=(te,X,ce)=>Nn(te,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(t){try{const e=document.cookie.match(new RegExp(`(?:^|; )${t}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function ft(t,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${t}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function wt(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function We(){let t=null;try{t=localStorage.getItem(X)}catch{}t||(t=ce(X));const e=t??wt();try{localStorage.setItem(X,e)}catch{}return ft(X,e),e}function gt(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 xt(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 p=t.charCodeAt(s);(p&64512)===56320&&(++s,r=((r&1023)<<10)+(p&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 yt=new TextEncoder,mt=50;function bt(t,e,n){yt.encodeInto(t,e.subarray(n))}function vt(t,e,n){t.length>mt?bt(t,e,n):xt(t,e,n)}const kt=4096;function Ke(t,e,n){let i=e;const o=i+n,s=[];let r="";for(;i<o;){const p=t[i++];if(!(p&128))s.push(p);else if((p&224)===192){const l=t[i++]&63;s.push((p&31)<<6|l)}else if((p&240)===224){const l=t[i++]&63,g=t[i++]&63;s.push((p&31)<<12|l<<6|g)}else if((p&248)===240){const l=t[i++]&63,g=t[i++]&63,w=t[i++]&63;let d=(p&7)<<18|l<<12|g<<6|w;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(p);s.length>=kt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const St=new TextDecoder,It=200;function Ct(t,e,n){const i=t.subarray(e,e+n);return St.decode(i)}function Tt(t,e,n){return n>It?Ct(t,e,n):Ke(t,e,n)}class me{constructor(e,n){c(this,"type");c(this,"data");this.type=e,this.data=n}}class V extends Error{constructor(e){super(e);const n=Object.create(V.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:V.name})}}const he=4294967295;function Et(t,e,n){const i=n/4294967296,o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ve(t,e,n){const i=Math.floor(n/4294967296),o=n;t.setUint32(e,i),t.setUint32(e+4,o)}function Ye(t,e){const n=t.getInt32(e),i=t.getUint32(e+4);return n*4294967296+i}function Ut(t,e){const n=t.getUint32(e),i=t.getUint32(e+4);return n*4294967296+i}const Bt=-1,Lt=4294967296-1,At=17179869184-1;function zt({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=At)if(e===0&&t<=Lt){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),Ve(i,4,t),n}}function Mt(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 $t(t){if(t instanceof Date){const e=Mt(t);return zt(e)}else return null}function Rt(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=Ye(e,4),i=e.getUint32(0);return{sec:n,nsec:i}}default:throw new V(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Pt(t){const e=Rt(t);return new Date(e.sec*1e3+e.nsec/1e6)}const _t={type:Bt,encode:$t,decode:Pt},Ie=class Ie{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 me(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 me(r,s)}}}return e instanceof me?e:null}decode(e,n,i){const o=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return o?o(e,n,i):new me(n,e)}};c(Ie,"defaultCodec",new Ie);let be=Ie;function Dt(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):Dt(t)?new Uint8Array(t):Uint8Array.from(t)}const Nt=100,qt=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)??be.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)??Nt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??qt,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=gt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),vt(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),Et(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ve(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 jt(t,e){return new Le(e).encodeSharedRef(t)}function Ae(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const Ot=16,Ht=16;class Ft{constructor(e=Ot,n=Ht){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 p=0;p<i;p++)if(r[p]!==e[n+p])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=Ke(e,n,i),r=Uint8Array.prototype.slice.call(e,n,n+i);return this.store(r,s),s}}const ze="array",pe="map_key",Ge="map_value",Wt=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new V("The type of key must be string or number but "+typeof t)};class Kt{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=pe,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===pe||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 ue=-1,Me=new DataView(new ArrayBuffer(0)),Vt=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 Xe=new RangeError("Insufficient data"),Yt=new Ft;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",Vt);c(this,"headByte",ue);c(this,"stack",new Kt);c(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??be.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)??he,this.maxBinLength=(e==null?void 0:e.maxBinLength)??he,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??he,this.maxMapLength=(e==null?void 0:e.maxMapLength)??he,this.maxExtLength=(e==null?void 0:e.maxExtLength)??he,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Yt,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Wt}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=ue,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===ue&&!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 p of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);try{i=this.doDecodeSync(),n=!0}catch(l){if(!(l instanceof RangeError))throw l}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 V(`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===pe){if(n==="__proto__")throw new V("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=pe;continue e}}return n}}readHeadByte(){return this.headByte===ue&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ue}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 V(`Unrecognized array type byte: ${Ae(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new V(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new V(`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 V(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Xe;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=Tt(this.bytes,i,e),this.pos+=n+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===pe:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new V(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Xe;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 V(`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=Ut(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ye(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 Gt(t,e){return new $e(e).decode(t)}const Xt=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 Jt(t){return Xt.has(t.type)}function Re(t){return jt(t)}function Je(t){let e;try{e=Gt(t)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Qt{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))}actionById(e){return this.actions.find(n=>n.id===e)}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=Qe(n);let o=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||Qe(r.status)>=i||(this.byId.set(s,{...r,status:n}),o=!0);o&&(this._sorted=null)}}function Qe(t){switch(t){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}class Zt{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??nn)(this.opts.url);n.binaryType="arraybuffer",this.socket=n,n.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},n.onmessage=s=>{const r=Je(new Uint8Array(s.data));!r||Jt(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"&&en.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 p;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(p=this.socket)==null||p.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",tn(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 en=new Set(["UNAUTHORIZED"]);function tn(t){switch(t){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function nn(t){return new WebSocket(t)}const Ze=200,on=7*864e5;class sn{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()-on,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>Ze?n.slice(n.length-Ze):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 rn={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)"},an={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)"},cn="'Nunito',-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif";function et(t,e){return Object.entries(e).map(([n,i])=>`--${t}-${n}:${i};`).join(" ")}function tt(t){return`${et(t,rn)} --${t}-fb:${cn}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function ve(t){return et(t,an)}const ln=`
2
2
  .ocw { ${tt("ocw")}
3
3
  position:relative;
4
4
  display:flex; flex-direction:column; height:100%; min-height:320px; background:var(--ocw-bg);
@@ -189,7 +189,7 @@ var RelayEmbedLite=function(ee){"use strict";var Dn=Object.defineProperty;var Nn
189
189
  .ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
190
190
  .ocw-translation { margin-top:6px; padding-top:6px; border-top:1px solid var(--ocw-line); font-size:13px; line-height:1.45; }
191
191
  .ocw-translation::before { content:'🌐 '; opacity:.75; }
192
- `,nt="objectchat-widget-styles",ln=["👍","❤️","😂","😮","😢","🙏"],dn=400,hn='<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 pn(){if(typeof document>"u"||document.getElementById(nt))return;const t=document.createElement("style");t.id=nt,t.textContent=cn,document.head.appendChild(t)}const ot="ocw-webfont";function un(){if(typeof document>"u"||document.getElementById(ot))return;const t=document.createElement("link");t.id=ot,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 fn(t,e){const n=/(https?:\/\/[^\s]+)/g;let i=0,o=null,s;for(;(s=n.exec(e))!==null;){if(s.index>i){const d=document.createTextNode(e.slice(i,s.index));t.append(d),o??(o=d)}let u=s[0],l="";const p=/[).,!?;:]+$/.exec(u);p&&(l=p[0],u=u.slice(0,-l.length));const g=document.createElement("a");g.href=u,g.target="_blank",g.rel="noopener noreferrer",g.textContent=u,g.style.cssText="color:inherit;text-decoration:underline;word-break:break-all",t.append(g),l&&t.append(document.createTextNode(l)),i=s.index+s[0].length}const r=document.createTextNode(e.slice(i));return t.append(r),o??(o=r),o}function wn(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 gn{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 R,O,B,J,f,h,E,m,k,C,$;this.root=e,this.me=n,this.h=i,this.cfg=o,pn(),o.webfont!==!1&&un(),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 b=a("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),r.append(b)}const u=((R=o.subject)==null?void 0:R.ownerLabel)??((O=o.subject)==null?void 0:O.title)??"",l=a("div","ocw-avatar");u.trim()&&(l.textContent=u.trim()[0].toUpperCase(),r.append(l));const p=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((B=o.subject)==null?void 0:B.ownerLabel)??((J=o.subject)==null?void 0:J.title)??""),p.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",p.append(this.headStatus),(f=o.subject)!=null&&f.subtitle&&p.append(a("div","ocw-head-meta",o.subject.subtitle)),r.append(p),this.statusBadge=a("span","ocw-badge",((h=o.subject)==null?void 0:h.status)??""),(E=o.subject)!=null&&E.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 g=a("div","ocw-typing-bubble");g.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(g),this.quick=a("div","ocw-quick");for(const b of o.quickReplies??[]){const S=a("button",void 0,b);S.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(S)}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=((m=o.i18n)==null?void 0:m.placeholder)??"Message…";const d=a("button","ocw-sendbtn");d.type="button";const x=(k=o.i18n)==null?void 0:k.send;x?(d.textContent=x,d.classList.add("ocw-sendbtn-label"),d.setAttribute("aria-label",x)):(d.innerHTML=hn,d.setAttribute("aria-label","Send message")),d.disabled=!0,this.sendBtn=d,d.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,S;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(j=>j.senderRole==="guest")?(S=(b=this.h).onDeflectQuery)==null||S.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const U=a("button","ocw-attach","📎");U.title="Attach image or file";const T=document.createElement("input");T.type="file",T.accept="image/*,.pdf,.txt,.doc,.docx",T.style.display="none",U.addEventListener("click",()=>T.click()),T.addEventListener("change",()=>{var b;(b=T.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(T.files[0]),T.value=""});const _=a("div","ocw-input");_.append(U,T,this.input,d);const z=a("div","ocw-footer");((C=o.i18n)==null?void 0:C.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",(($=this.cfg.i18n)==null?void 0:$.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const b=this.root.querySelector(".ocw-input textarea");b==null||b.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,_,this.reopenBtn,this.footer);const M=b=>{e.classList.toggle("ocw-compact",b>0&&b<dn)};M(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var j;const S=((j=b[0])==null?void 0:j.contentRect.width)??e.clientWidth;M(S)}),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)}setBotName(e){this.cfg.i18n={...this.cfg.i18n??{},aiAssistant:e}}render(e){var T,_,z,M,R,O,B,J;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 f=(T=this.cfg.subject)==null?void 0:T.ownerLabel;f&&(this.headerName.textContent=f)}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 f of n)this.chips.append(this.chipEl(f));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 f=a("div","ocw-load-more");f.textContent="↑ Loading earlier messages…",f.style.pointerEvents="none",this.scroll.append(f)}let s=0,r=null;const u=[...e.messages()];for(let f=0;f<u.length;f++){const h=u[f],E=h.senderRole!=="system"&&h.senderId!==this.me&&!h.internal&&h.senderId!==r;this.scroll.append(this.messageEl(h,e,E,f===u.length-1)),h.senderRole!=="system"&&(r=h.senderId),h.senderId!==this.me&&h.seq>s&&(s=h.seq)}o>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+o:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const l=[...e.typing];this.typing.classList.toggle("active",l.length>0);const p=this.typing.querySelector(".ocw-typing-bubble");p&&p.setAttribute("aria-label",l.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const g=e.messages().some(f=>f.senderRole==="guest");if(!!((_=e.preChat)!=null&&_.enabled)&&!this.preChatDone&&!g&&(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 f=this.awayNotice.lastChild;f.textContent=e.offlineMessage||((M=this.cfg.i18n)==null?void 0:M.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";(R=this.root.querySelector(".ocw-input"))==null||R.style.removeProperty("display")}const x=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&x.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const U=x.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((O=this.cfg.i18n)==null?void 0:O.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((B=this.cfg.i18n)==null?void 0:B.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",U&&e.messages().length>0){const f=a("div","ocw-resolved-note",`— ${((J=this.cfg.i18n)==null?void 0:J.resolved)??"Marked as resolved"} —`);this.scroll.append(f),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 l;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((l=e.topics)!=null&&l.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 d=document.createElement("option");d.value=g,d.textContent=g,o.append(d)}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 x,U,T,_,z,M,R;const p=(x=i.email)==null?void 0:x.value.trim();if(i.email&&(!p||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p))){i.email.focus();return}const g=!!(s!=null&&s.checked),d=(((U=i.phone)==null?void 0:U.value)??(r==null?void 0:r.value)??"").trim();if(g&&!d){(T=i.phone??r)==null||T.focus();return}if(o&&((_=e.topics)!=null&&_.length)&&!o.value){o.focus();return}u.disabled=!0,this.completePreChat(),(R=(M=this.h).onPreChat)==null||R.call(M,{...(z=i.name)!=null&&z.value.trim()?{name:i.name.value.trim()}:{},...p?{email:p}:{},...d?{phone:d}:{},...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,l]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${u}: ${l}`));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"),l=p=>{i.remove(),n(p)};r.addEventListener("click",()=>l(!1)),u.addEventListener("click",()=>l(!0)),i.addEventListener("click",p=>{p.target===i&&l(!1)}),s.append(r,u),o.append(s),i.append(o),this.root.append(i),u.focus()})}openForm(e){var u,l;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 d=a("select","ocw-form-input");p.required||d.append(a("option",void 0,"— select —"));for(const x of p.options){const U=a("option");U.value=x,U.textContent=x,d.append(U)}p.required&&(d.required=!0),g.append(d),i.set(p.name,d)}else{const d=a("input","ocw-form-input");d.type=p.type==="number"?"number":p.type==="date"?"datetime-local":"text",p.required&&(d.required=!0),g.append(d),i.set(p.name,d)}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,d]of i){if(d.required&&!d.value){d.style.borderColor="#e5484d";return}p[g]=d.type==="number"?Number(d.value):d.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,p)}),o.append(s,r),n.append(o),this.formHost.append(n),(l=i.values().next().value)==null||l.focus()}messageEl(e,n,i=!1,o=!1){var U,T,_,z,M,R,O,B,J;if(e.senderRole==="system"){const f=a("div","ocw-sys");return f.textContent=e.deletedAt?"message deleted":Pe(e.content),f}const s=e.senderId===this.me,r=!!e.internal,u=a("div",`ocw-row ${r?"ocw-note mine":s?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`),l=a("div");if(i){const f=e.senderRole==="bot"?((U=this.cfg.i18n)==null?void 0:U.aiAssistant)??"AI Assistant":((T=this.cfg.subject)==null?void 0:T.ownerLabel)??((_=this.cfg.subject)==null?void 0:_.title)??"Support";l.append(a("div","ocw-msg-sender",f))}const p=a("div","ocw-bubble-wrap");if(e.replyToId){const f=a("div","ocw-reply-to","↩ replying to a message");f.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",l.append(f)}const g=a("div","ocw-bubble");let d=null;if(e.deletedAt)g.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const f=e.content;if((z=f.mime)!=null&&z.startsWith("image/")){const h=document.createElement("img");h.src=f.url,h.alt=f.name??"image",h.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",h.addEventListener("click",()=>window.open(f.url,"_blank")),g.append(h)}else if((M=f.mime)!=null&&M.startsWith("video/")){const h=document.createElement("video");h.src=f.url,h.controls=!0,h.style.cssText="max-width:240px;max-height:180px;border-radius:10px;display:block",g.append(h)}else{const h=document.createElement("a");h.href=f.url,h.target="_blank",h.rel="noopener",h.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",h.append(a("span",void 0,"📄"),a("span",void 0,f.name??"file")),g.append(h)}}else if(e.content.kind==="appointment"){const f=e.content,h=a("div","ocw-appt");h.append(a("div","ocw-appt-title",`📅 ${f.title}`)),h.append(a("div","ocw-appt-time",new Date(f.startIso).toLocaleString()+" – "+new Date(f.endIso).toLocaleTimeString())),f.location&&h.append(a("div","ocw-appt-loc",`📍 ${f.location}`)),f.description&&h.append(a("div","ocw-appt-desc",f.description));const E=a("div","ocw-appt-links"),m=document.createElement("a");m.href=f.googleUrl,m.target="_blank",m.rel="noopener",m.className="ocw-appt-btn",m.textContent="📅 Add to Google Calendar";const k=document.createElement("a");k.href=f.icalUrl,k.download=`${f.title}.ics`,k.className="ocw-appt-btn ocw-appt-btn-sec",k.textContent="🍎 Apple / iCal",E.append(m,k),h.append(E),g.append(h)}else d=fn(g,Pe(e.content)),e.editedAt&&g.append(a("span","ocw-edited","(edited)"));if(p.append(g),o&&!e.deletedAt&&e.content.kind==="text"&&((R=e.content.quickReplies)!=null&&R.length)){const f=a("div","ocw-flow-choices");f.style.cssText="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px";for(const h of e.content.quickReplies){const E=a("button","ocw-flow-choice",h);E.type="button",E.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:var(--ocw-bg,#fff);color:inherit;border-radius:14px;padding:5px 12px;font:inherit;font-size:13px;cursor:pointer",E.addEventListener("click",()=>{f.querySelectorAll("button").forEach(m=>m.disabled=!0),f.style.opacity="0.5",this.h.onSend(h)}),f.append(E)}p.append(f)}if(!s&&!r&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&d){const f=e.content.text;if(f.trim()){const h=a("button","ocw-translate-btn","🌐");h.type="button",h.title="Translate";const E=a("div","ocw-translation");E.style.display="none",g.append(E);const m=$=>{E.textContent=$,E.style.display="",this.showingTranslation.add(e.id),h.textContent="↩",h.title="Show original"},k=()=>{E.style.display="none",this.showingTranslation.delete(e.id),h.textContent="🌐",h.title="Translate"};h.addEventListener("click",$=>{if($.stopPropagation(),this.showingTranslation.has(e.id)){k();return}const b=this.translationCache.get(e.id);if(b!==void 0){m(b);return}h.textContent="⏳",this.h.onTranslate(f).then(S=>{if(S===null){h.textContent="⚠️",h.title="Translation unavailable",setTimeout(()=>{h.textContent="🌐",h.title="Translate"},1500);return}this.translationCache.set(e.id,S),m(S)})}),p.append(h);const C=this.translationCache.get(e.id);this.showingTranslation.has(e.id)&&C!==void 0&&m(C)}}if(s&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const f=a("div","ocw-msg-menu");if(this.h.onEdit){const h=a("button",void 0,"✏️");h.title="Edit",h.addEventListener("click",E=>{E.stopPropagation();const m=Pe(e.content),k=document.createElement("textarea");k.value=m,k.rows=Math.min(4,Math.ceil(m.length/40)+1),k.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 C=a("button","ocw-form-submit","Save");C.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const $=a("button","ocw-form-cancel","Cancel");$.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const b=a("div");b.style.cssText="display:flex;gap:6px;justify-content:flex-end",b.append($,C);const S=a("div");S.append(k,b),g.replaceChildren(S),k.focus(),k.select();const j=()=>g.replaceChildren(d??document.createTextNode(m));$.addEventListener("click",j),C.addEventListener("click",()=>{const H=k.value.trim();H&&H!==m&&this.h.onEdit(e.id,H),j()}),k.addEventListener("keydown",H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),C.click()),H.key==="Escape"&&j()})}),f.append(h)}if(this.h.onDelete){const h=a("button","del","🗑");h.title="Delete",h.addEventListener("click",E=>{E.stopPropagation(),this.h.onDelete(e.id)}),f.append(h)}p.append(f)}if(l.append(p),e.senderRole==="bot"&&!e.deletedAt&&e.seq>0&&e.content.kind==="text"){const f=e.content.citations;if(f!=null&&f.length){const h=a("div","ocw-cites");h.style.cssText="margin-top:4px;font-size:11px;color:var(--ocw-mut,#667)",h.textContent=`${((O=this.cfg.i18n)==null?void 0:O.sources)??"Sources"}: ${f.map(E=>E.source).join(", ")}`,l.append(h)}if(this.h.onReact){const h=a("div","ocw-bot-feedback");h.style.cssText="display:flex;gap:6px;margin-top:4px";const E=(m,k)=>{const C=a("button","ocw-fb-btn",m);C.type="button",C.title=k,C.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:transparent;border-radius:12px;padding:1px 8px;font-size:12px;cursor:pointer;opacity:.7";const $=()=>{var b,S;return!!((S=(b=e.reactions)==null?void 0:b[m])!=null&&S.includes(this.me))};return $()&&(C.style.opacity="1"),C.addEventListener("click",()=>{var b,S;(S=(b=this.h).onReact)==null||S.call(b,e.id,m,$()),C.style.opacity="1"}),C};h.append(E("👍",((B=this.cfg.i18n)==null?void 0:B.helpful)??"Helpful"),E("👎",((J=this.cfg.i18n)==null?void 0:J.notHelpful)??"Not helpful")),l.append(h)}}if(this.h.onReact&&!e.deletedAt&&e.seq>0){const f=a("div","ocw-react-wrap"),h=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[k,C]of Object.entries(e.reactions)){const $=a("button",`ocw-react-pill${C.includes(this.me)?" mine":""}`,`${k} ${C.length}`);$.addEventListener("click",()=>{var b,S;return(S=(b=this.h).onReact)==null?void 0:S.call(b,e.id,k,C.includes(this.me))}),h.append($)}const E=a("button","ocw-react-btn","+"),m=a("div","ocw-react-picker");for(const k of ln){const C=a("button",void 0,k);C.addEventListener("click",$=>{var S,j,H,Q;$.stopPropagation();const b=(j=(S=e.reactions)==null?void 0:S[k])==null?void 0:j.includes(this.me);(Q=(H=this.h).onReact)==null||Q.call(H,e.id,k,!!b),m.style.display="none"}),m.append(C)}m.style.display="none",E.addEventListener("click",k=>{k.stopPropagation();const C=m.style.display==="none";m.style.display=C?"flex":"none",C&&document.addEventListener("click",()=>{m.style.display="none"},{once:!0})}),h.append(E),f.append(h,m),l.append(f)}else e.reactions&&Object.keys(e.reactions).length&&l.append(a("div","ocw-react",Object.entries(e.reactions).map(([f,h])=>`${f}${h.length}`).join(" ")));const x=a("div","ocw-time ocw-meta",wn(e.ts));if(s&&e.status){const f=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,xn(e.status));x.append(f)}return s&&e.seq>0&&n.lastReadByOthers>=e.seq&&x.append(a("span","ocw-seen"," · Seen")),l.append(x),u.append(l),u}}function xn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const yn=20;function _e(t,e){var l;const n=t.trim().replace(/\/+$/,""),i=(l=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:l[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 mn(t){return _e(t).httpBase}function bn(t,e,n,i){const o=`beforeSeq=${n}&limit=${i}`;return[`${t}/conversations/${e}/messages?${o}`,`${t}/conversations/${e}/history?${o}`]}async function it(t,e,n,i,o=yn){let s,r=!1;for(const u of bn(t,e,i,o))try{const l=await fetch(u,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!l.ok)continue;const p=await l.json();return{messages:p.messages??[],hasMore:p.hasMore??!1}}catch(l){s=l}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 vn(t,e,n,i,o,s){const r=s?s.replace(/\/+$/,""):mn(t),u=await it(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 l=!1;const p=async()=>{if(l||!i.hasMoreHistory)return;l=!0;const U=i.messages()[0];if(!U){l=!1;return}const T=await it(r,n,e,U.seq);T&&(i.apply({type:"history",conversationId:n,messages:T.messages,hasMore:T.hasMore}),o.render(i)),l=!1},g=o.getScrollEl();if(!g)return;let d=!1;setTimeout(()=>{d=!0},300);const x=()=>{d&&g.scrollTop<80&&i.hasMoreHistory&&!l&&p()};g.addEventListener("scroll",x,{passive:!0}),o.setScrollCleanup(()=>g.removeEventListener("scroll",x))}const kn=`
192
+ `,nt="objectchat-widget-styles",dn=["👍","❤️","😂","😮","😢","🙏"],hn=400,pn='<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 un(){if(typeof document>"u"||document.getElementById(nt))return;const t=document.createElement("style");t.id=nt,t.textContent=ln,document.head.appendChild(t)}const ot="ocw-webfont";function fn(){if(typeof document>"u"||document.getElementById(ot))return;const t=document.createElement("link");t.id=ot,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 wn(t,e){const n=/(https?:\/\/[^\s]+)/g;let i=0,o=null,s;for(;(s=n.exec(e))!==null;){if(s.index>i){const d=document.createTextNode(e.slice(i,s.index));t.append(d),o??(o=d)}let p=s[0],l="";const g=/[).,!?;:]+$/.exec(p);g&&(l=g[0],p=p.slice(0,-l.length));const w=document.createElement("a");w.href=p,w.target="_blank",w.rel="noopener noreferrer",w.textContent=p,w.style.cssText="color:inherit;text-decoration:underline;word-break:break-all",t.append(w),l&&t.append(document.createTextNode(l)),i=s.index+s[0].length}const r=document.createTextNode(e.slice(i));return t.append(r),o??(o=r),o}function gn(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 xn{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,B,J,L,f,h,y,v,T,U;this.root=e,this.me=n,this.h=i,this.cfg=o,un(),o.webfont!==!1&&fn(),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 k=a("button","ocw-back","‹");k.type="button",k.setAttribute("aria-label","Back"),k.addEventListener("click",()=>this.h.onBack()),r.append(k)}const p=((_=o.subject)==null?void 0:_.ownerLabel)??((F=o.subject)==null?void 0:F.title)??"",l=a("div","ocw-avatar");p.trim()&&(l.textContent=p.trim()[0].toUpperCase(),r.append(l));const g=a("div","ocw-head-main");this.headerName=a("div","ocw-head-name",((B=o.subject)==null?void 0:B.ownerLabel)??((J=o.subject)==null?void 0:J.title)??""),g.append(this.headerName),this.headStatus=a("div","ocw-head-status"),this.headStatus.style.display="none",g.append(this.headStatus),(L=o.subject)!=null&&L.subtitle&&g.append(a("div","ocw-head-meta",o.subject.subtitle)),r.append(g),this.statusBadge=a("span","ocw-badge",((f=o.subject)==null?void 0:f.status)??""),(h=o.subject)!=null&&h.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 w=a("div","ocw-typing-bubble");w.append(a("div","ocw-typing-dot"),a("div","ocw-typing-dot"),a("div","ocw-typing-dot")),this.typing.append(w),this.quick=a("div","ocw-quick");for(const k of o.quickReplies??[]){const S=a("button",void 0,k);S.addEventListener("click",()=>{this.h.onSend(k),this.quick.style.display="none"}),this.quick.append(S)}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=((y=o.i18n)==null?void 0:y.placeholder)??"Message…";const d=a("button","ocw-sendbtn");d.type="button";const x=(v=o.i18n)==null?void 0:v.send;x?(d.textContent=x,d.classList.add("ocw-sendbtn-label"),d.setAttribute("aria-label",x)):(d.innerHTML=pn,d.setAttribute("aria-label","Send message")),d.disabled=!0,this.sendBtn=d,d.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var k,S;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(A=>A.senderRole==="guest")?(S=(k=this.h).onDeflectQuery)==null||S.call(k,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",k=>{k.isComposing||k.keyCode===229||(k.key==="Enter"&&!k.shiftKey?(k.preventDefault(),this.flushSend()):this.signalTyping())});const I=a("button","ocw-attach","📎");I.title="Attach image or file";const C=document.createElement("input");C.type="file",C.accept="image/*,.pdf,.txt,.doc,.docx",C.style.display="none",I.addEventListener("click",()=>C.click()),C.addEventListener("change",()=>{var k;(k=C.files)!=null&&k[0]&&this.h.onAttach&&this.h.onAttach(C.files[0]),C.value=""});const M=a("div","ocw-input");M.append(I,C,this.input,d);const R=a("div","ocw-footer");((T=o.i18n)==null?void 0:T.poweredBy)!==void 0?R.textContent=o.i18n.poweredBy:R.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=R,this.reopenBtn=a("button","ocw-reopen",((U=this.cfg.i18n)==null?void 0:U.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const k=this.root.querySelector(".ocw-input textarea");k==null||k.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,M,this.reopenBtn,this.footer);const P=k=>{e.classList.toggle("ocw-compact",k>0&&k<hn)};P(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(k=>{var A;const S=((A=k[0])==null?void 0:A.contentRect.width)??e.clientWidth;P(S)}),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)}setBotName(e){this.cfg.i18n={...this.cfg.i18n??{},aiAssistant:e}}render(e){var C,M,R,P,_,F,B,J;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 L=(C=this.cfg.subject)==null?void 0:C.ownerLabel;L&&(this.headerName.textContent=L)}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 L of n)this.chips.append(this.chipEl(L));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 L=a("div","ocw-load-more");L.textContent="↑ Loading earlier messages…",L.style.pointerEvents="none",this.scroll.append(L)}let s=0,r=null;const p=[...e.messages()];for(let L=0;L<p.length;L++){const f=p[L],h=f.senderRole!=="system"&&f.senderId!==this.me&&!f.internal&&f.senderId!==r;this.scroll.append(this.messageEl(f,e,h,L===p.length-1)),f.senderRole!=="system"&&(r=f.senderId),f.senderId!==this.me&&f.seq>s&&(s=f.seq)}o>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+o:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const l=[...e.typing];this.typing.classList.toggle("active",l.length>0);const g=this.typing.querySelector(".ocw-typing-bubble");g&&g.setAttribute("aria-label",l.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const w=e.messages().some(L=>L.senderRole==="guest");if(!!((M=e.preChat)!=null&&M.enabled)&&!this.preChatDone&&!w&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(R=this.root.querySelector(".ocw-input"))==null||R.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 L=this.awayNotice.lastChild;L.textContent=e.offlineMessage||((P=this.cfg.i18n)==null?void 0:P.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";(_=this.root.querySelector(".ocw-input"))==null||_.style.removeProperty("display")}const x=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&x.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const I=x.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((F=this.cfg.i18n)==null?void 0:F.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((B=this.cfg.i18n)==null?void 0:B.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",I&&e.messages().length>0){const L=a("div","ocw-resolved-note",`— ${((J=this.cfg.i18n)==null?void 0:J.resolved)??"Marked as resolved"} —`);this.scroll.append(L),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 l;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 g of e.fields??["name","email"]){const w=a("input","ocw-offline-input");w.type=g==="email"?"email":g==="phone"?"tel":"text",w.placeholder=g==="name"?"Your name":g==="email"?"Your email":"Your phone number",i[g]=w,n.append(w)}let o=null;if((l=e.topics)!=null&&l.length){o=a("select",void 0);const g=document.createElement("option");g.value="",g.textContent="What is this about?",o.append(g);for(const w of e.topics){const d=document.createElement("option");d.value=w,d.textContent=w,o.append(d)}n.append(o)}let s=null,r=null;if(e.callbackOption){const g=a("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",g.append(s,document.createTextNode("📞 Request a call back")),n.append(g),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 p=a("button","ocw-offline-submit","Start chat");p.type="button",p.addEventListener("click",()=>{var x,I,C,M,R,P,_;const g=(x=i.email)==null?void 0:x.value.trim();if(i.email&&(!g||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(g))){i.email.focus();return}const w=!!(s!=null&&s.checked),d=(((I=i.phone)==null?void 0:I.value)??(r==null?void 0:r.value)??"").trim();if(w&&!d){(C=i.phone??r)==null||C.focus();return}if(o&&((M=e.topics)!=null&&M.length)&&!o.value){o.focus();return}p.disabled=!0,this.completePreChat(),(_=(P=this.h).onPreChat)==null||_.call(P,{...(R=i.name)!=null&&R.value.trim()?{name:i.name.value.trim()}:{},...g?{email:g}:{},...d?{phone:d}:{},...o!=null&&o.value?{topic:o.value}:{},...w?{callback:!0}:{}})}),n.append(p),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[p,l]of Object.entries(n.fields))s.append(a("span","ocw-tag",`${p}: ${l}`));else for(const p of(i==null?void 0:i.tags)??[])s.append(a("span","ocw-tag",p));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"),p=a("button","ocw-modal-ok","Confirm"),l=g=>{i.remove(),n(g)};r.addEventListener("click",()=>l(!1)),p.addEventListener("click",()=>l(!0)),i.addEventListener("click",g=>{g.target===i&&l(!1)}),s.append(r,p),o.append(s),i.append(o),this.root.append(i),p.focus()})}openForm(e,n){var l,g;this.formHost.replaceChildren();const i=a("div","ocw-form");i.append(a("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const o=new Map;for(const w of e.input??[]){const d=n==null?void 0:n[w.name],x=a("label","ocw-form-row");if(x.append(a("span","ocw-form-lbl",w.label)),w.type==="select"&&((l=w.options)!=null&&l.length)){const I=a("select","ocw-form-input");w.required||I.append(a("option",void 0,"— select —"));for(const C of w.options){const M=a("option");M.value=C,M.textContent=C,I.append(M)}w.required&&(I.required=!0),d!=null&&w.options.includes(d)&&(I.value=d),x.append(I),o.set(w.name,I)}else{const I=a("input","ocw-form-input");I.type=w.type==="number"?"number":w.type==="date"?"datetime-local":"text",w.required&&(I.required=!0),d!=null&&d!==""&&(I.value=d),x.append(I),o.set(w.name,I)}i.append(x)}const s=a("div","ocw-form-actions"),r=a("button","ocw-form-cancel","Cancel"),p=a("button","ocw-form-submit","Send");r.addEventListener("click",()=>this.formHost.replaceChildren()),p.addEventListener("click",()=>{const w={};for(const[d,x]of o){if(x.required&&!x.value){x.style.borderColor="#e5484d";return}w[d]=x.type==="number"?Number(x.value):x.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,w)}),s.append(r,p),i.append(s),this.formHost.append(i),(g=o.values().next().value)==null||g.focus()}messageEl(e,n,i=!1,o=!1){var I,C,M,R,P,_,F,B,J,L;if(e.senderRole==="system"){const f=a("div","ocw-sys");return f.textContent=e.deletedAt?"message deleted":Pe(e.content),f}const s=e.senderId===this.me,r=!!e.internal,p=a("div",`ocw-row ${r?"ocw-note mine":s?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`),l=a("div");if(i){const f=e.senderRole==="bot"?((I=this.cfg.i18n)==null?void 0:I.aiAssistant)??"AI Assistant":((C=this.cfg.subject)==null?void 0:C.ownerLabel)??((M=this.cfg.subject)==null?void 0:M.title)??"Support";l.append(a("div","ocw-msg-sender",f))}const g=a("div","ocw-bubble-wrap");if(e.replyToId){const f=a("div","ocw-reply-to","↩ replying to a message");f.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",l.append(f)}const w=a("div","ocw-bubble");let d=null;if(e.deletedAt)w.append(a("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const f=e.content;if((R=f.mime)!=null&&R.startsWith("image/")){const h=document.createElement("img");h.src=f.url,h.alt=f.name??"image",h.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",h.addEventListener("click",()=>window.open(f.url,"_blank")),w.append(h)}else if((P=f.mime)!=null&&P.startsWith("video/")){const h=document.createElement("video");h.src=f.url,h.controls=!0,h.style.cssText="max-width:240px;max-height:180px;border-radius:10px;display:block",w.append(h)}else{const h=document.createElement("a");h.href=f.url,h.target="_blank",h.rel="noopener",h.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",h.append(a("span",void 0,"📄"),a("span",void 0,f.name??"file")),w.append(h)}}else if(e.content.kind==="appointment"){const f=e.content,h=a("div","ocw-appt");h.append(a("div","ocw-appt-title",`📅 ${f.title}`)),h.append(a("div","ocw-appt-time",new Date(f.startIso).toLocaleString()+" – "+new Date(f.endIso).toLocaleTimeString())),f.location&&h.append(a("div","ocw-appt-loc",`📍 ${f.location}`)),f.description&&h.append(a("div","ocw-appt-desc",f.description));const y=a("div","ocw-appt-links"),v=document.createElement("a");v.href=f.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.textContent="📅 Add to Google Calendar";const T=document.createElement("a");T.href=f.icalUrl,T.download=`${f.title}.ics`,T.className="ocw-appt-btn ocw-appt-btn-sec",T.textContent="🍎 Apple / iCal",y.append(v,T),h.append(y),w.append(h)}else d=wn(w,Pe(e.content)),e.editedAt&&w.append(a("span","ocw-edited","(edited)"));if(g.append(w),o&&!e.deletedAt&&e.content.kind==="text"&&((_=e.content.quickReplies)!=null&&_.length)){const f=a("div","ocw-flow-choices");f.style.cssText="display:flex;flex-wrap:wrap;gap:6px;margin-top:6px";for(const h of e.content.quickReplies){const y=a("button","ocw-flow-choice",h);y.type="button",y.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:var(--ocw-bg,#fff);color:inherit;border-radius:14px;padding:5px 12px;font:inherit;font-size:13px;cursor:pointer",y.addEventListener("click",()=>{f.querySelectorAll("button").forEach(v=>v.disabled=!0),f.style.opacity="0.5",this.h.onSend(h)}),f.append(y)}g.append(f)}if(o&&!e.deletedAt&&e.content.kind==="form"){const f=e.content,h=n.actionById(f.actionId);if((F=h==null?void 0:h.input)!=null&&F.length){const y=a("button","ocw-chip",h.icon?`${h.icon} ${h.label}`:h.label);y.type="button",y.style.cssText="margin-top:6px",y.addEventListener("click",async()=>{h.confirm&&!await this.confirm(h.label)||this.openForm(h,f.prefill)}),g.append(y)}}if(!s&&!r&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&d){const f=e.content.text;if(f.trim()){const h=a("button","ocw-translate-btn","🌐");h.type="button",h.title="Translate";const y=a("div","ocw-translation");y.style.display="none",w.append(y);const v=k=>{y.textContent=k,y.style.display="",this.showingTranslation.add(e.id),h.textContent="↩",h.title="Show original"},T=()=>{y.style.display="none",this.showingTranslation.delete(e.id),h.textContent="🌐",h.title="Translate"};h.addEventListener("click",k=>{if(k.stopPropagation(),this.showingTranslation.has(e.id)){T();return}const S=this.translationCache.get(e.id);if(S!==void 0){v(S);return}h.textContent="⏳",this.h.onTranslate(f).then(A=>{if(A===null){h.textContent="⚠️",h.title="Translation unavailable",setTimeout(()=>{h.textContent="🌐",h.title="Translate"},1500);return}this.translationCache.set(e.id,A),v(A)})}),g.append(h);const U=this.translationCache.get(e.id);this.showingTranslation.has(e.id)&&U!==void 0&&v(U)}}if(s&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const f=a("div","ocw-msg-menu");if(this.h.onEdit){const h=a("button",void 0,"✏️");h.title="Edit",h.addEventListener("click",y=>{y.stopPropagation();const v=Pe(e.content),T=document.createElement("textarea");T.value=v,T.rows=Math.min(4,Math.ceil(v.length/40)+1),T.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 U=a("button","ocw-form-submit","Save");U.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const k=a("button","ocw-form-cancel","Cancel");k.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const S=a("div");S.style.cssText="display:flex;gap:6px;justify-content:flex-end",S.append(k,U);const A=a("div");A.append(T,S),w.replaceChildren(A),T.focus(),T.select();const Q=()=>w.replaceChildren(d??document.createTextNode(v));k.addEventListener("click",Q),U.addEventListener("click",()=>{const q=T.value.trim();q&&q!==v&&this.h.onEdit(e.id,q),Q()}),T.addEventListener("keydown",q=>{q.key==="Enter"&&!q.shiftKey&&(q.preventDefault(),U.click()),q.key==="Escape"&&Q()})}),f.append(h)}if(this.h.onDelete){const h=a("button","del","🗑");h.title="Delete",h.addEventListener("click",y=>{y.stopPropagation(),this.h.onDelete(e.id)}),f.append(h)}g.append(f)}if(l.append(g),e.senderRole==="bot"&&!e.deletedAt&&e.seq>0&&e.content.kind==="text"){const f=e.content.citations;if(f!=null&&f.length){const h=a("div","ocw-cites");h.style.cssText="margin-top:4px;font-size:11px;color:var(--ocw-mut,#667)",h.textContent=`${((B=this.cfg.i18n)==null?void 0:B.sources)??"Sources"}: ${f.map(y=>y.source).join(", ")}`,l.append(h)}if(this.h.onReact){const h=a("div","ocw-bot-feedback");h.style.cssText="display:flex;gap:6px;margin-top:4px";const y=(v,T)=>{const U=a("button","ocw-fb-btn",v);U.type="button",U.title=T,U.style.cssText="border:1px solid var(--ocw-bd,rgba(0,0,0,.12));background:transparent;border-radius:12px;padding:1px 8px;font-size:12px;cursor:pointer;opacity:.7";const k=()=>{var S,A;return!!((A=(S=e.reactions)==null?void 0:S[v])!=null&&A.includes(this.me))};return k()&&(U.style.opacity="1"),U.addEventListener("click",()=>{var S,A;(A=(S=this.h).onReact)==null||A.call(S,e.id,v,k()),U.style.opacity="1"}),U};h.append(y("👍",((J=this.cfg.i18n)==null?void 0:J.helpful)??"Helpful"),y("👎",((L=this.cfg.i18n)==null?void 0:L.notHelpful)??"Not helpful")),l.append(h)}}if(this.h.onReact&&!e.deletedAt&&e.seq>0){const f=a("div","ocw-react-wrap"),h=a("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[T,U]of Object.entries(e.reactions)){const k=a("button",`ocw-react-pill${U.includes(this.me)?" mine":""}`,`${T} ${U.length}`);k.addEventListener("click",()=>{var S,A;return(A=(S=this.h).onReact)==null?void 0:A.call(S,e.id,T,U.includes(this.me))}),h.append(k)}const y=a("button","ocw-react-btn","+"),v=a("div","ocw-react-picker");for(const T of dn){const U=a("button",void 0,T);U.addEventListener("click",k=>{var A,Q,q,b;k.stopPropagation();const S=(Q=(A=e.reactions)==null?void 0:A[T])==null?void 0:Q.includes(this.me);(b=(q=this.h).onReact)==null||b.call(q,e.id,T,!!S),v.style.display="none"}),v.append(U)}v.style.display="none",y.addEventListener("click",T=>{T.stopPropagation();const U=v.style.display==="none";v.style.display=U?"flex":"none",U&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),h.append(y),f.append(h,v),l.append(f)}else e.reactions&&Object.keys(e.reactions).length&&l.append(a("div","ocw-react",Object.entries(e.reactions).map(([f,h])=>`${f}${h.length}`).join(" ")));const x=a("div","ocw-time ocw-meta",gn(e.ts));if(s&&e.status){const f=a("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,yn(e.status));x.append(f)}return s&&e.seq>0&&n.lastReadByOthers>=e.seq&&x.append(a("span","ocw-seen"," · Seen")),l.append(x),p.append(l),p}}function yn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const mn=20;function _e(t,e){var l;const n=t.trim().replace(/\/+$/,""),i=(l=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:l[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 bn(t){return _e(t).httpBase}function vn(t,e,n,i){const o=`beforeSeq=${n}&limit=${i}`;return[`${t}/conversations/${e}/messages?${o}`,`${t}/conversations/${e}/history?${o}`]}async function it(t,e,n,i,o=mn){let s,r=!1;for(const p of vn(t,e,i,o))try{const l=await fetch(p,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!l.ok)continue;const g=await l.json();return{messages:g.messages??[],hasMore:g.hasMore??!1}}catch(l){s=l}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 kn(t,e,n,i,o,s){const r=s?s.replace(/\/+$/,""):bn(t),p=await it(r,n,e,Number.MAX_SAFE_INTEGER);if(!p||(p.messages.length?(i.apply({type:"sync",conversationId:n,messages:p.messages}),i.apply({type:"history",conversationId:n,messages:[],hasMore:p.hasMore}),o.render(i)):i.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!p.hasMore))return;let l=!1;const g=async()=>{if(l||!i.hasMoreHistory)return;l=!0;const I=i.messages()[0];if(!I){l=!1;return}const C=await it(r,n,e,I.seq);C&&(i.apply({type:"history",conversationId:n,messages:C.messages,hasMore:C.hasMore}),o.render(i)),l=!1},w=o.getScrollEl();if(!w)return;let d=!1;setTimeout(()=>{d=!0},300);const x=()=>{d&&w.scrollTop<80&&i.hasMoreHistory&&!l&&g()};w.addEventListener("scroll",x,{passive:!0}),o.setScrollCleanup(()=>w.removeEventListener("scroll",x))}const Sn=`
193
193
  .ocl { ${tt("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; }
@@ -237,5 +237,5 @@ var RelayEmbedLite=function(ee){"use strict";var Dn=Object.defineProperty;var Nn
237
237
  .ocl-compact .ocl-search { font-size:16px; }
238
238
  .ocl-compact .ocl-compose { width:36px; height:36px; }
239
239
  .ocl-row:focus-visible, .ocl button:focus-visible, .ocl input:focus-visible { outline:2px solid var(--ocl-accent); outline-offset:2px; border-radius:12px; }
240
- `,Sn={en:{placeholder:"Message…",offline:"We're offline right now",online:"Online",away:"Away",aiAssistant:"AI Assistant",resolved:"Marked as resolved",reopen:"Reopen conversation",sources:"Sources",helpful:"Helpful",notHelpful:"Not helpful",title:"Your conversations",newChat:"New conversation",startChat:"Start a conversation",all:"All conversations",empty:"No conversations yet.",error:"Could not load conversations.",retry:"Retry",search:"🔍 Search",unread:"Unread",close:"Close"},ko:{placeholder:"메시지…",offline:"지금은 오프라인입니다",online:"온라인",away:"자리 비움",aiAssistant:"AI 어시스턴트",resolved:"해결됨으로 표시됨",reopen:"대화 다시 열기",sources:"출처",helpful:"도움돼요",notHelpful:"도움 안돼요",title:"내 대화",newChat:"새 대화",startChat:"대화 시작하기",all:"전체 대화",empty:"아직 대화가 없습니다.",error:"대화를 불러오지 못했습니다.",retry:"다시 시도",search:"🔍 검색",unread:"읽지 않음",close:"닫기"}};function In(t){const e=(t??(typeof navigator<"u"?navigator.language:"")??"").toLowerCase();return e.startsWith("ko")||e.includes("korean")||e.includes("한국")?"ko":"en"}function st(t,e){const n=Sn[In(t)],i={};for(const[o,s]of Object.entries(e??{}))typeof s=="string"&&s!==""&&(i[o]=s);return{...n,...i}}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`}}function A(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function rt(t){const e=t.token??t.userId??We(),{httpBase:n,wsUrl:i}=_e(t.url,t.apiUrl),o=st(t.locale,t.i18n),s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const v=document.createElement("style");v.id="ocl-styles",v.textContent=kn,document.head.append(v)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const v=document.createElement("link");v.id="ocw-webfont",v.rel="stylesheet",v.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(v)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const u=A("div","ocl-head"),l=o.title??"Your conversations",p=A("span","ocl-title",l);if(p.setAttribute("aria-label",l),u.append(p),t.onNewChat){const v=A("button","ocl-compose","✎");v.title=o.newChat??"New conversation",v.addEventListener("click",()=>t.onNewChat()),u.append(v)}const g=A("div","ocl-search-wrap"),d=A("input","ocl-search");d.placeholder=o.search??"🔍 Search",d.type="search",g.append(d);const x=A("div","ocl-body");x.append(A("div","ocl-spinner","Loading…")),r.append(u,g,x),t.el.replaceChildren(r);const U=v=>{r.classList.toggle("ocl-compact",v>0&&v<400)};U(r.clientWidth);let T=null;if(typeof ResizeObserver<"u"&&(T=new ResizeObserver(v=>{var P;return U(((P=v[0])==null?void 0:P.contentRect.width)??r.clientWidth)}),T.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let _;const z=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let M={};try{M=JSON.parse(localStorage.getItem(z)??"{}")}catch{}const R=()=>{try{localStorage.setItem(z,JSON.stringify(M))}catch{}};let O=[],B=!1;const J=async()=>{const v=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,P=`${n}/conversations/mine?${v}`,F={authorization:`Bearer ${e}`};let Y;try{Y=await fetch(P,{headers:F})}catch{Y=await fetch(P,{headers:F})}if(!Y.ok)return[];const K=await Y.json();return K.defaultProfileId&&(_=K.defaultProfileId),(K.conversations??[]).sort((Z,L)=>L.updatedAt-Z.updatedAt)},f=(v,P)=>{if(B)return;const F=P?v.filter(L=>h(L).toLowerCase().includes(P)||(L.lastMessage??"").toLowerCase().includes(P)):v;if(x.replaceChildren(),!F.length){const L=A("div","ocl-empty",P?"No results.":o.empty??"No conversations yet.");if(!P&&t.onNewChat){L.append(A("br"));const ae=A("button","ocl-start",o.startChat??"Start a conversation");ae.addEventListener("click",()=>t.onNewChat()),L.append(ae)}x.append(L);return}const Y=L=>(L.lastSeq??0)>(M[L.id]??0),K=F.filter(Y),Z=F.filter(L=>!Y(L));if(K.length){x.append(A("div","ocl-section",`${o.unread??"Unread"} (${K.length})`));for(const L of K)x.append(E(L,Y(L)))}if(Z.length){x.append(A("div","ocl-section",K.length?o.all??"All conversations":""));for(const L of Z)x.append(E(L,!1))}},h=v=>v.subjectTitle??(v.kind==="direct"?v.peerId??"Direct message":"General enquiry"),E=(v,P)=>{var W;const F=h(v),Y=(((W=F.match(new RegExp("\\p{L}","u")))==null?void 0:W[0])??F.trim()[0]??"?").toUpperCase(),K=v.lastSeq??0,Z=P?Math.max(1,K-(M[v.id]??0)):0,L=A("button",`ocl-row${P?" unread":""}`),ae=A("div","ocl-av",Y);L.append(ae);const le=A("div","ocl-info");le.append(A("div","ocl-name",F));const w={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};le.append(A("div","ocl-preview",v.lastMessage??w[v.state]??v.state)),L.append(le);const y=A("div","ocl-right");y.append(A("div","ocl-time",Tn(v.updatedAt)));const I=Cn(v.state);return I&&y.append(A("div",`ocl-status ${I.cls}`,I.label)),Z>0&&y.append(A("div","ocl-badge",String(Z>99?"99+":Z))),L.append(y),L.addEventListener("click",()=>{var re;K>0&&(M[v.id]=K,R()),L.classList.remove("unread"),(re=y.querySelector(".ocl-badge"))==null||re.remove(),t.onSelect(v)}),L},m=()=>{B||J().then(v=>{B||(O=v,f(v,d.value.trim().toLowerCase()))}).catch(v=>{if(B)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,v);const P=A("div","ocl-empty",o.error??"Could not load conversations.");P.append(A("br"));const F=A("button","ocl-retry",o.retry??"Retry");F.addEventListener("click",()=>{x.replaceChildren(A("div","ocl-spinner","Loading…")),m()}),P.append(F),x.replaceChildren(P)})};d.addEventListener("input",()=>f(O,d.value.trim().toLowerCase())),m();let k=null,C,$,b=0,S=!1;const j=()=>{$||($=setTimeout(()=>{$=void 0,m()},300))},H=()=>{if(!B){try{k=new WebSocket(i)}catch{Q();return}k.binaryType="arraybuffer",k.onopen=()=>{b=0,k.send(Re({type:"auth",token:e})),k.send(Re({type:"subscribe_inbox"})),S&&j(),S=!0},k.onmessage=v=>{const P=Je(new Uint8Array(v.data));P&&P.type==="inbox_event"&&j()},k.onclose=()=>{k=null,Q()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Q=()=>{if(B||C)return;const v=Math.min(15e3,500*2**b++)+Math.random()*250;C=setTimeout(()=>{C=void 0,H()},v)};return H(),{refresh:m,close(){B=!0,C&&clearTimeout(C),$&&clearTimeout($),T==null||T.disconnect(),T=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??_}}}const En=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:rt},Symbol.toStringTag,{value:"Module"})),fe=new WeakMap,ke=new Map;function at(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let we=null;function Un(){if(we&&we.state!=="closed")return we;try{return we=new AudioContext,we}catch{return null}}function Bn(t){const e=t.el;let n=null,i=null,o=!1;const s=()=>{n==null||n.close(),n=null,i==null||i.close(),i=null,e.innerHTML=""};function r(){o||(s(),i=rt({el:e,url:t.url,...t.apiUrl?{apiUrl:t.apiUrl}:{},...t.profileId?{profileId:t.profileId}:{},scope:t.inboxScope??"tenant",...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.locale?{locale:t.locale}:{},...t.i18n?{i18n:t.i18n}:{},onSelect:l=>u(l)}))}function u(l){if(o)return;s();const{subjectId:p,kind:g,peerId:d,...x}=t;n=De({...x,inbox:!1,launcher:!1,el:e,...l.profileId?{profileId:l.profileId}:{},...l.subjectId?{subjectId:l.subjectId}:{},...l.kind==="direct"&&l.peerId?{kind:"direct",peerId:l.peerId}:{},onBack:r})}return r(),{close(){o=!0,s()}}}function De(t){var P,F,Y,K,Z,L,ae,le;if(t.inbox)return Bn(t);fe.has(t.el)&&(fe.get(t.el).close(),fe.delete(t.el)),t.launcher&&((P=ke.get(at(t)))==null||P.close());const e=We();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 l=new Jt(o);const p=t.subjectId?`${o}::${t.subjectId}`:o,g=new on(p);let d,x=!1,U=null,T=null,_=null,z=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 w of g.load())l.addOptimistic(w.clientMsgId,w.content);let M=null,R=null,O=0,B=!t.launcher;if(t.launcher){const y=(t.position??"bottom-right").includes("right");M=document.createElement("div"),M.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 I=document.createElement("div"),W=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,re=N=>{t.el.classList.toggle("ocw-fs",N),I.style.cssText=N?["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(";")};re((W==null?void 0:W.matches)??!1);const ye=N=>re(N.matches);W==null||W.addEventListener("change",ye),U=W,T=ye,t.el.style.cssText="width:100%;height:100%;overflow:hidden",I.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)"},R=document.createElement("span"),R.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=B?Te:Ce,G.setAttribute("aria-label",B?"Close chat":"Open chat"),G.setAttribute("aria-expanded",String(B)),G.append(R)};Ee(),M.append(I,G),document.body.append(M);const je=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let D=null;const Pn=()=>{try{return sessionStorage.getItem(je)==="1"}catch{return!1}},_n='<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>',dt=()=>{const N=Ue!=null&&Ue.title?Ue:l.launcherMessage??void 0;if(!(!!(N!=null&&N.title)&&!B&&!Pn())){D&&(D.remove(),D=null);return}if(D)return;D=document.createElement("div"),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.setAttribute("aria-label",N.title),D.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 He=document.createElement("div");if(He.textContent=N.title,He.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",D.append(He),N.subtitle){const oe=document.createElement("div");oe.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Fe=document.createElement("span");Fe.innerHTML=_n,Fe.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const pt=document.createElement("span");pt.textContent=N.subtitle,oe.append(Fe,pt),D.append(oe)}const de=document.createElement("button");de.type="button",de.setAttribute("aria-label","Dismiss"),de.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>',de.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",de.addEventListener("click",oe=>{oe.stopPropagation();try{sessionStorage.setItem(je,"1")}catch{}D&&(D.remove(),D=null)}),D.append(de);const ht=()=>{B||(B=!0,Oe(!0),Ee(),O=0,R&&(R.style.display="none"),D&&(D.remove(),D=null))};D.addEventListener("click",ht),D.addEventListener("keydown",oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),ht())}),M.insertBefore(D,G)};if(!document.getElementById("ocw-teaser-style")){const N=document.createElement("style");N.id="ocw-teaser-style",N.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(N)}z=dt,dt();const Oe=N=>{N?(I.style.display="flex",requestAnimationFrame(()=>{I.style.opacity="1",I.style.transform="scale(1)"})):(I.style.opacity="0",I.style.transform="scale(.95)",setTimeout(()=>{B||(I.style.display="none")},180))};G.addEventListener("click",()=>{if(B=!B,Oe(B),Ee(),B){O=0,R&&(R.style.display="none");try{sessionStorage.setItem(je,"1")}catch{}}z==null||z()}),_=N=>{N.key==="Escape"&&B&&(B=!1,Oe(!1),Ee())},document.addEventListener("keydown",_)}const J=()=>{B||(O++,R&&(R.textContent=String(O),R.style.display="flex"))},f=()=>{try{const w=Un();if(!w)return;w.state==="suspended"&&w.resume().catch(()=>{});const y=w.createOscillator(),I=w.createGain();y.connect(I),I.connect(w.destination),y.frequency.setValueAtTime(880,w.currentTime),y.frequency.exponentialRampToValueAtTime(440,w.currentTime+.15),I.gain.setValueAtTime(.3,w.currentTime),I.gain.exponentialRampToValueAtTime(.001,w.currentTime+.3),y.start(),y.stop(w.currentTime+.3)}catch{}},h=[],E=w=>{for(;h.length;){const y=h.shift();g.add({clientMsgId:y.clientMsgId,content:y.content,ts:Date.now()}),m.send({type:"send",conversationId:w,clientMsgId:y.clientMsgId,content:y.content})}};let m;const k=st(t.locale,t.i18n),C=["ar","he","fa","ur"],$=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";C.includes($)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const b=`oc_prechat_${t.profileId}_${o.slice(-8)}`,S=new gn(t.el,o,{onSend(w){const y=`cm_${Math.random().toString(36).slice(2)}`,I={kind:"text",text:w};if(l.addOptimistic(y,I),S.render(l),l.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else d?(g.add({clientMsgId:y,content:I,ts:Date.now()}),m.send({type:"send",conversationId:d,clientMsgId:y,content:I})):h.push({clientMsgId:y,content:I})},async onAttach(w){if(!d)return;const y=`${u}/upload?name=${encodeURIComponent(w.name)}`,I=`cm_${Math.random().toString(36).slice(2)}`;l.addOptimistic(I,{kind:"text",text:`📎 Uploading ${w.name}…`}),S.render(l);try{const W=await fetch(y,{method:"POST",headers:{"content-type":w.type,authorization:`Bearer ${o}`},body:w});if(!W.ok)throw new Error(`Upload failed: ${W.status}`);const{url:re,name:ye,mime:Ce,size:Te}=await W.json();l.addOptimistic(I,{kind:"attachment",url:re,name:ye,mime:Ce,size:Te}),S.render(l),m.send({type:"send",conversationId:d,clientMsgId:I,content:{kind:"attachment",url:re,name:ye,mime:Ce,size:Te}})}catch(W){l.addOptimistic(I,{kind:"text",text:`⚠️ Upload failed: ${W.message}`}),S.render(l)}},onInvoke(w,y){d&&m.send({type:"invoke",conversationId:d,actionId:w,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...y?{inputs:y}:{}})},onTyping(w,y){d&&m.send({type:"typing",conversationId:d,isTyping:w,...y?{preview:y}:{}})},onPreChat(w){try{localStorage.setItem(b,"1")}catch{}m.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...w.name?{name:w.name}:{},...w.email?{email:w.email}:{},...w.phone||w.topic?{meta:{...w.phone?{phone:w.phone}:{},...w.topic?{topic:w.topic}:{}}}:{}}});const y=w.callback?`📞 Call-back requested${w.phone?`: ${w.phone}`:""}${w.topic?` — ${w.topic}`:""}`:w.topic?`Topic: ${w.topic}`:"";y&&d&&!l.e2e&&m.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:y}})},...((F=t.features)==null?void 0:F.deflection)!==!1?{onDeflectQuery(w){if(i)return;clearTimeout(n);const y=w.trim();if(y.length<3){S.hideDeflection();return}n=setTimeout(()=>{fetch(`${u}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(y.slice(0,200))}`).then(I=>I.ok?I.json():{articles:[]}).then(I=>S.showDeflection(I.articles??[])).catch(()=>S.hideDeflection())},350)}}:{},onReadUpTo(w){d&&m.send({type:"read",conversationId:d,seq:w})},onLoadMore(){if(!d||!l.e2e)return;const w=l.messages()[0];w&&m.send({type:"history",conversationId:d,beforeSeq:w.seq,limit:20})},onEdit(w,y){d&&m.send({type:"edit",conversationId:d,messageId:w,content:{kind:"text",text:y}})},onDelete(w){d&&m.send({type:"delete",conversationId:d,messageId:w})},...((Y=t.features)==null?void 0:Y.reactions)!==!1?{onReact(w,y,I){d&&m.send({type:"react",conversationId:d,messageId:w,emoji:y,remove:I})}}:{},...((K=t.features)==null?void 0:K.csat)!==!1?{onCsat(w){d&&fetch(`${u}/conversations/${d}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({score:w})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(w){try{const y=await fetch(`${u}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({text:w,targetLang:t.translateLang})});if(!y.ok)return null;const{translated:I}=await y.json();return I}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}:{},...(Z=t.user)!=null&&Z.name||(L=t.user)!=null&&L.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:k});try{localStorage.getItem(b)&&S.completePreChat()}catch{}const j=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,H={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...j?{userInfo:j}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(ae=t.subject)!=null&&ae.title?{subjectTitle:t.subject.title}:{},...(le=t.subject)!=null&&le.subtitle?{subjectMeta:t.subject.subtitle}:{}};m=new Qt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:o,open:H,getCursor:()=>l.highestSeq(),onStatusChange:(w,y)=>S.setConnStatus(w,y),onFrame(w){if(w.type==="opened"){if(d=w.conversation.id,!x){x=!0;for(const y of g.load())m.send({type:"send",conversationId:d,clientMsgId:y.clientMsgId,content:y.content})}vn(r,o,d,l,S,u),h.length&&E(d)}w.type==="ack"&&g.remove(w.clientMsgId),(async()=>{if(l.apply(w),w.type==="manifest"){z==null||z();const y=w.botName;y&&S.setBotName(y)}w.type==="message"&&w.message.senderId!==o&&!w.message.internal&&(J(),f()),S.render(l)})()}}),m.connect(),S.render(l);const Q=t.launcher?at(t):null,v={close:()=>{i=!0,clearTimeout(n),m.close(),M==null||M.remove(),S.destroy(),U&&T&&U.removeEventListener("change",T),_&&(document.removeEventListener("keydown",_),_=null),fe.delete(t.el),Q&&ke.get(Q)===v&&ke.delete(Q)}};return fe.set(t.el,v),Q&&ke.set(Q,v),v}const Ne="wss://api.paramms.com/ws";function Ln(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,l=t.listingPrice??t.subjectPrice,p=s?{title:s,...r?{subtitle:r}:{},...l!=null?{tags:[`$${l.toLocaleString()}`]}:{},...u?{status:u}:{}}:void 0,g=t.subject??p,d=t.userName??t.name,x=t.userEmail??t.email,U=t.userAvatar??t.avatar,T=d||x||U?{...d?{name:d}:{},...x?{email:x}:{},...U?{avatar:U}:{}}:void 0,_=t.user??T,z=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??Ne,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}:{},..._?{user:_}:{},...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.locale?{locale:t.locale}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...z?{launcherMessage:z}:{},...ct(t)&&!o?{onBack:()=>{ge=!0,xe=!1,Se(se)}}:{},launcher:o,position:t.position??"bottom-right"}}let te=null,q=null,ie=!1,se={},ge=!1,xe=!1;function ct(t){return!!(t.inbox||t.inboxStart)}let ne=null;function An(t,e){const n=!e&&!!t.el;if(ie&&!n&&(q.innerHTML="",q=null,ie=!1),n){const i=typeof t.el=="string"?document.querySelector(t.el):t.el;i instanceof HTMLElement?(q&&q!==i&&!ie&&q.remove(),q=i,ie=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!q||!ie&&!q.isConnected)&&(q=document.createElement("div"),q.id="relay-widget-root",document.body.appendChild(q),ie=!1),!e&&t.height&&(q.style.height=t.height,q.style.width||(q.style.width="100%")),q}function Se(t){try{const e=t.launcher??!0;ne==null||ne(),ne=null,te==null||te.close(),te=null;const n=An(t,e);if(ct(t)&&!e&&ge){zn(t,n);return}te=De(Ln(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function zn(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=()=>{ge=!1,Se(se)},i.append(o,s);const u=!xe&&!!n;u&&i.append(r),e.appendChild(i);let l=null,p=null;ne=()=>{p==null||p.close(),l==null||l.close(),e.innerHTML=""};let g;try{({mountChatList:g}=await Promise.resolve().then(()=>En))}catch(x){console.error("[Relay] could not load the conversation list module.",x),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 d=x=>{const U=x.profileId??n;if(!U){console.error("[Relay] conversation row has no chatroom; cannot open it.",x);return}r.style.display="none",p==null||p.close(),p=De({el:s,url:t.url??Ne,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:U,...x.kind==="direct"&&x.peerId?{kind:"direct",peerId:x.peerId}:x.subjectId?{subjectId:x.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}:{}}}:{},...x.subjectTitle?{subject:{title:x.subjectTitle,...x.subjectMeta?{subtitle:x.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="",l==null||l.refresh()}}),o.style.display="none",s.style.display=""};l=g({el:o,url:t.url??Ne,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...u?{reserveCloseSpace:!0}:{},onSelect:d,onNewChat:()=>{const x=n??(l==null?void 0:l.defaultProfileId());x&&d({id:"__new__",profileId:x,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function lt(t){xe=!!(t.inboxStart&&!(t.launcher??!0)),ge=xe,se={...t},Se(se)}function Mn(t){se={...se,...t},Se(se)}function $n(){ne==null||ne(),ne=null,te==null||te.close(),te=null,q&&!ie&&q.remove(),q=null,ie=!1,ge=!1,xe=!1,se={}}function qe(t,e){switch(t){case"boot":lt(e??{});break;case"update":case"identify":Mn(e??{});break;case"shutdown":$n();break;default:console.warn("[Relay] unknown command:",t)}}function Rn(){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.relayLocale&&(o.locale=e.relayLocale),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??Rn();i&&lt(i)}}return ee.Relay=qe,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"}),ee}({});
240
+ `,In={en:{placeholder:"Message…",offline:"We're offline right now",online:"Online",away:"Away",aiAssistant:"AI Assistant",resolved:"Marked as resolved",reopen:"Reopen conversation",sources:"Sources",helpful:"Helpful",notHelpful:"Not helpful",title:"Your conversations",newChat:"New conversation",startChat:"Start a conversation",all:"All conversations",empty:"No conversations yet.",error:"Could not load conversations.",retry:"Retry",search:"🔍 Search",unread:"Unread",close:"Close"},ko:{placeholder:"메시지…",offline:"지금은 오프라인입니다",online:"온라인",away:"자리 비움",aiAssistant:"AI 어시스턴트",resolved:"해결됨으로 표시됨",reopen:"대화 다시 열기",sources:"출처",helpful:"도움돼요",notHelpful:"도움 안돼요",title:"내 대화",newChat:"새 대화",startChat:"대화 시작하기",all:"전체 대화",empty:"아직 대화가 없습니다.",error:"대화를 불러오지 못했습니다.",retry:"다시 시도",search:"🔍 검색",unread:"읽지 않음",close:"닫기"}};function st(t){const e=(t??(typeof navigator<"u"?navigator.language:"")??"").toLowerCase();return e.startsWith("ko")||e.includes("korean")||e.includes("한국")?"ko":"en"}function rt(t,e){const n=In[st(t)],i={};for(const[o,s]of Object.entries(e??{}))typeof s=="string"&&s!==""&&(i[o]=s);return{...n,...i}}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`}}function $(t,e,n){const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i}function at(t){const e=t.token??t.userId??We(),{httpBase:n,wsUrl:i}=_e(t.url,t.apiUrl),o=rt(t.locale,t.i18n),s=t.accent??"#6c5ce7";if(!document.getElementById("ocl-styles")){const b=document.createElement("style");b.id="ocl-styles",b.textContent=Sn,document.head.append(b)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const b=document.createElement("link");b.id="ocw-webfont",b.rel="stylesheet",b.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(b)}const r=$("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const p=$("div","ocl-head"),l=o.title??"Your conversations",g=$("span","ocl-title",l);if(g.setAttribute("aria-label",l),p.append(g),t.onNewChat){const b=$("button","ocl-compose","✎");b.title=o.newChat??"New conversation",b.addEventListener("click",()=>t.onNewChat()),p.append(b)}const w=$("div","ocl-search-wrap"),d=$("input","ocl-search");d.placeholder=o.search??"🔍 Search",d.type="search",w.append(d);const x=$("div","ocl-body");x.append($("div","ocl-spinner","Loading…")),r.append(p,w,x),t.el.replaceChildren(r);const I=b=>{r.classList.toggle("ocl-compact",b>0&&b<400)};I(r.clientWidth);let C=null;if(typeof ResizeObserver<"u"&&(C=new ResizeObserver(b=>{var D;return I(((D=b[0])==null?void 0:D.contentRect.width)??r.clientWidth)}),C.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let M;const R=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let P={};try{P=JSON.parse(localStorage.getItem(R)??"{}")}catch{}const _=()=>{try{localStorage.setItem(R,JSON.stringify(P))}catch{}};let F=[],B=!1;const J=async()=>{const b=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,D=`${n}/conversations/mine?${b}`,W={authorization:`Bearer ${e}`};let Y;try{Y=await fetch(D,{headers:W})}catch{Y=await fetch(D,{headers:W})}if(!Y.ok)return[];const K=await Y.json();return K.defaultProfileId&&(M=K.defaultProfileId),(K.conversations??[]).sort((Z,z)=>z.updatedAt-Z.updatedAt)},L=(b,D)=>{if(B)return;const W=D?b.filter(z=>f(z).toLowerCase().includes(D)||(z.lastMessage??"").toLowerCase().includes(D)):b;if(x.replaceChildren(),!W.length){const z=$("div","ocl-empty",D?"No results.":o.empty??"No conversations yet.");if(!D&&t.onNewChat){z.append($("br"));const ae=$("button","ocl-start",o.startChat??"Start a conversation");ae.addEventListener("click",()=>t.onNewChat()),z.append(ae)}x.append(z);return}const Y=z=>(z.lastSeq??0)>(P[z.id]??0),K=W.filter(Y),Z=W.filter(z=>!Y(z));if(K.length){x.append($("div","ocl-section",`${o.unread??"Unread"} (${K.length})`));for(const z of K)x.append(h(z,Y(z)))}if(Z.length){x.append($("div","ocl-section",K.length?o.all??"All conversations":""));for(const z of Z)x.append(h(z,!1))}},f=b=>b.subjectTitle??(b.kind==="direct"?b.peerId??"Direct message":"General enquiry"),h=(b,D)=>{var O;const W=f(b),Y=(((O=W.match(new RegExp("\\p{L}","u")))==null?void 0:O[0])??W.trim()[0]??"?").toUpperCase(),K=b.lastSeq??0,Z=D?Math.max(1,K-(P[b.id]??0)):0,z=$("button",`ocl-row${D?" unread":""}`),ae=$("div","ocl-av",Y);z.append(ae);const le=$("div","ocl-info");le.append($("div","ocl-name",W));const u={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};le.append($("div","ocl-preview",b.lastMessage??u[b.state]??b.state)),z.append(le);const m=$("div","ocl-right");m.append($("div","ocl-time",Tn(b.updatedAt)));const E=Cn(b.state);return E&&m.append($("div",`ocl-status ${E.cls}`,E.label)),Z>0&&m.append($("div","ocl-badge",String(Z>99?"99+":Z))),z.append(m),z.addEventListener("click",()=>{var ee;K>0&&(P[b.id]=K,_()),z.classList.remove("unread"),(ee=m.querySelector(".ocl-badge"))==null||ee.remove(),t.onSelect(b)}),z},y=()=>{B||J().then(b=>{B||(F=b,L(b,d.value.trim().toLowerCase()))}).catch(b=>{if(B)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,b);const D=$("div","ocl-empty",o.error??"Could not load conversations.");D.append($("br"));const W=$("button","ocl-retry",o.retry??"Retry");W.addEventListener("click",()=>{x.replaceChildren($("div","ocl-spinner","Loading…")),y()}),D.append(W),x.replaceChildren(D)})};d.addEventListener("input",()=>L(F,d.value.trim().toLowerCase())),y();let v=null,T,U,k=0,S=!1;const A=()=>{U||(U=setTimeout(()=>{U=void 0,y()},300))},Q=()=>{if(!B){try{v=new WebSocket(i)}catch{q();return}v.binaryType="arraybuffer",v.onopen=()=>{k=0,v.send(Re({type:"auth",token:e})),v.send(Re({type:"subscribe_inbox"})),S&&A(),S=!0},v.onmessage=b=>{const D=Je(new Uint8Array(b.data));D&&D.type==="inbox_event"&&A()},v.onclose=()=>{v=null,q()},v.onerror=()=>{try{v==null||v.close()}catch{}}}},q=()=>{if(B||T)return;const b=Math.min(15e3,500*2**k++)+Math.random()*250;T=setTimeout(()=>{T=void 0,Q()},b)};return Q(),{refresh:y,close(){B=!0,T&&clearTimeout(T),U&&clearTimeout(U),C==null||C.disconnect(),C=null;try{v==null||v.close()}catch{}v=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??M}}}const En=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:at},Symbol.toStringTag,{value:"Module"})),fe=new WeakMap,ke=new Map;function ct(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let we=null;function Un(){if(we&&we.state!=="closed")return we;try{return we=new AudioContext,we}catch{return null}}function Bn(t){const e=t.el;let n=null,i=null,o=!1;const s=()=>{n==null||n.close(),n=null,i==null||i.close(),i=null,e.innerHTML=""};function r(){o||(s(),i=at({el:e,url:t.url,...t.apiUrl?{apiUrl:t.apiUrl}:{},...t.profileId?{profileId:t.profileId}:{},scope:t.inboxScope??"tenant",...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.locale?{locale:t.locale}:{},...t.i18n?{i18n:t.i18n}:{},onSelect:l=>p(l)}))}function p(l){if(o)return;s();const{subjectId:g,kind:w,peerId:d,...x}=t;n=De({...x,inbox:!1,launcher:!1,el:e,...l.profileId?{profileId:l.profileId}:{},...l.subjectId?{subjectId:l.subjectId}:{},...l.kind==="direct"&&l.peerId?{kind:"direct",peerId:l.peerId}:{},onBack:r})}return r(),{close(){o=!0,s()}}}function De(t){var D,W,Y,K,Z,z,ae,le;if(t.inbox)return Bn(t);fe.has(t.el)&&(fe.get(t.el).close(),fe.delete(t.el)),t.launcher&&((D=ke.get(ct(t)))==null||D.close());const e=We();let n,i=!1;const o=t.token??t.userId??e,s=o!==e?e:void 0,{wsUrl:r,httpBase:p}=_e(t.url,t.apiUrl);let l=new Qt(o);const g=t.subjectId?`${o}::${t.subjectId}`:o,w=new sn(g);let d,x=!1,I=null,C=null,M=null,R=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 u of w.load())l.addOptimistic(u.clientMsgId,u.content);let P=null,_=null,F=0,B=!t.launcher;if(t.launcher){const m=(t.position??"bottom-right").includes("right");P=document.createElement("div"),P.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 E=document.createElement("div"),O=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,ee=j=>{t.el.classList.toggle("ocw-fs",j),E.style.cssText=j?["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(";")};ee((O==null?void 0:O.matches)??!1);const ye=j=>ee(j.matches);O==null||O.addEventListener("change",ye),I=O,C=ye,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>',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)"},_=document.createElement("span"),_.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=B?Te:Ce,G.setAttribute("aria-label",B?"Close chat":"Open chat"),G.setAttribute("aria-expanded",String(B)),G.append(_)};Ee(),P.append(E,G),document.body.append(P);const je=`ocw-teaser-dismissed::${t.profileId}`,Ue=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let N=null;const Pn=()=>{try{return sessionStorage.getItem(je)==="1"}catch{return!1}},_n='<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>',ht=()=>{const j=Ue!=null&&Ue.title?Ue:l.launcherMessage??void 0;if(!(!!(j!=null&&j.title)&&!B&&!Pn())){N&&(N.remove(),N=null);return}if(N)return;N=document.createElement("div"),N.setAttribute("role","button"),N.setAttribute("tabindex","0"),N.setAttribute("aria-label",j.title),N.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 He=document.createElement("div");if(He.textContent=j.title,He.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",N.append(He),j.subtitle){const ie=document.createElement("div");ie.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Fe=document.createElement("span");Fe.innerHTML=_n,Fe.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const ut=document.createElement("span");ut.textContent=j.subtitle,ie.append(Fe,ut),N.append(ie)}const de=document.createElement("button");de.type="button",de.setAttribute("aria-label","Dismiss"),de.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>',de.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",de.addEventListener("click",ie=>{ie.stopPropagation();try{sessionStorage.setItem(je,"1")}catch{}N&&(N.remove(),N=null)}),N.append(de);const pt=()=>{B||(B=!0,Oe(!0),Ee(),F=0,_&&(_.style.display="none"),N&&(N.remove(),N=null))};N.addEventListener("click",pt),N.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),pt())}),P.insertBefore(N,G)};if(!document.getElementById("ocw-teaser-style")){const j=document.createElement("style");j.id="ocw-teaser-style",j.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(j)}R=ht,ht();const Oe=j=>{j?(E.style.display="flex",requestAnimationFrame(()=>{E.style.opacity="1",E.style.transform="scale(1)"})):(E.style.opacity="0",E.style.transform="scale(.95)",setTimeout(()=>{B||(E.style.display="none")},180))};G.addEventListener("click",()=>{if(B=!B,Oe(B),Ee(),B){F=0,_&&(_.style.display="none");try{sessionStorage.setItem(je,"1")}catch{}}R==null||R()}),M=j=>{j.key==="Escape"&&B&&(B=!1,Oe(!1),Ee())},document.addEventListener("keydown",M)}const J=()=>{B||(F++,_&&(_.textContent=String(F),_.style.display="flex"))},L=()=>{try{const u=Un();if(!u)return;u.state==="suspended"&&u.resume().catch(()=>{});const m=u.createOscillator(),E=u.createGain();m.connect(E),E.connect(u.destination),m.frequency.setValueAtTime(880,u.currentTime),m.frequency.exponentialRampToValueAtTime(440,u.currentTime+.15),E.gain.setValueAtTime(.3,u.currentTime),E.gain.exponentialRampToValueAtTime(.001,u.currentTime+.3),m.start(),m.stop(u.currentTime+.3)}catch{}},f=[],h=u=>{for(;f.length;){const m=f.shift();w.add({clientMsgId:m.clientMsgId,content:m.content,ts:Date.now()}),y.send({type:"send",conversationId:u,clientMsgId:m.clientMsgId,content:m.content})}};let y;const v=rt(t.locale,t.i18n),T=["ar","he","fa","ur"],U=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";T.includes(U)&&!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)}`,S=new xn(t.el,o,{onSend(u){const m=`cm_${Math.random().toString(36).slice(2)}`,E={kind:"text",text:u};if(l.addOptimistic(m,E),S.render(l),l.e2e){console.error("[relay] this chat is end-to-end encrypted — use the full widget build");return}else d?(w.add({clientMsgId:m,content:E,ts:Date.now()}),y.send({type:"send",conversationId:d,clientMsgId:m,content:E})):f.push({clientMsgId:m,content:E})},async onAttach(u){if(!d)return;const m=`${p}/upload?name=${encodeURIComponent(u.name)}`,E=`cm_${Math.random().toString(36).slice(2)}`;l.addOptimistic(E,{kind:"text",text:`📎 Uploading ${u.name}…`}),S.render(l);try{const O=await fetch(m,{method:"POST",headers:{"content-type":u.type,authorization:`Bearer ${o}`},body:u});if(!O.ok)throw new Error(`Upload failed: ${O.status}`);const{url:ee,name:ye,mime:Ce,size:Te}=await O.json();l.addOptimistic(E,{kind:"attachment",url:ee,name:ye,mime:Ce,size:Te}),S.render(l),y.send({type:"send",conversationId:d,clientMsgId:E,content:{kind:"attachment",url:ee,name:ye,mime:Ce,size:Te}})}catch(O){l.addOptimistic(E,{kind:"text",text:`⚠️ Upload failed: ${O.message}`}),S.render(l)}},onInvoke(u,m){d&&y.send({type:"invoke",conversationId:d,actionId:u,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...m?{inputs:m}:{}})},onTyping(u,m){d&&y.send({type:"typing",conversationId:d,isTyping:u,...m?{preview:m}:{}})},onPreChat(u){try{localStorage.setItem(k,"1")}catch{}y.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...u.name?{name:u.name}:{},...u.email?{email:u.email}:{},...u.phone||u.topic?{meta:{...u.phone?{phone:u.phone}:{},...u.topic?{topic:u.topic}:{}}}:{}}});const m=u.callback?`📞 Call-back requested${u.phone?`: ${u.phone}`:""}${u.topic?` — ${u.topic}`:""}`:u.topic?`Topic: ${u.topic}`:"";m&&d&&!l.e2e&&y.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:m}})},...((W=t.features)==null?void 0:W.deflection)!==!1?{onDeflectQuery(u){if(i)return;clearTimeout(n);const m=u.trim();if(m.length<3){S.hideDeflection();return}n=setTimeout(()=>{fetch(`${p}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(m.slice(0,200))}`).then(E=>E.ok?E.json():{articles:[]}).then(E=>S.showDeflection(E.articles??[])).catch(()=>S.hideDeflection())},350)}}:{},onReadUpTo(u){d&&y.send({type:"read",conversationId:d,seq:u})},onLoadMore(){if(!d||!l.e2e)return;const u=l.messages()[0];u&&y.send({type:"history",conversationId:d,beforeSeq:u.seq,limit:20})},onEdit(u,m){d&&y.send({type:"edit",conversationId:d,messageId:u,content:{kind:"text",text:m}})},onDelete(u){d&&y.send({type:"delete",conversationId:d,messageId:u})},...((Y=t.features)==null?void 0:Y.reactions)!==!1?{onReact(u,m,E){d&&y.send({type:"react",conversationId:d,messageId:u,emoji:m,remove:E})}}:{},...((K=t.features)==null?void 0:K.csat)!==!1?{onCsat(u){d&&fetch(`${p}/conversations/${d}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({score:u})}).catch(()=>{})}}:{},...(()=>{const u=t.locale??(typeof navigator<"u"?navigator.language:""),m=t.translateLang!==void 0?t.translateLang:u?u.split("-")[0]:st();return m?{async onTranslate(E){try{const O=await fetch(`${p}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({text:E,targetLang:m})});if(!O.ok)return null;const{translated:ee}=await O.json();return ee}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}:{},...(Z=t.user)!=null&&Z.name||(z=t.user)!=null&&z.avatar?{userInfo:{...t.user.name?{name:t.user.name}:{},...t.user.avatar?{avatar:t.user.avatar}:{}}}:{},i18n:v});try{localStorage.getItem(k)&&S.completePreChat()}catch{}const A=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,Q={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...A?{userInfo:A}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(ae=t.subject)!=null&&ae.title?{subjectTitle:t.subject.title}:{},...(le=t.subject)!=null&&le.subtitle?{subjectMeta:t.subject.subtitle}:{}};y=new Zt({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:o,open:Q,getCursor:()=>l.highestSeq(),onStatusChange:(u,m)=>S.setConnStatus(u,m),onFrame(u){if(u.type==="opened"){if(d=u.conversation.id,!x){x=!0;for(const m of w.load())y.send({type:"send",conversationId:d,clientMsgId:m.clientMsgId,content:m.content})}kn(r,o,d,l,S,p),f.length&&h(d)}u.type==="ack"&&w.remove(u.clientMsgId),(async()=>{if(l.apply(u),u.type==="manifest"){R==null||R();const m=u.botName;m&&S.setBotName(m)}u.type==="message"&&u.message.senderId!==o&&!u.message.internal&&(J(),L()),S.render(l)})()}}),y.connect(),S.render(l);const q=t.launcher?ct(t):null,b={close:()=>{i=!0,clearTimeout(n),y.close(),P==null||P.remove(),S.destroy(),I&&C&&I.removeEventListener("change",C),M&&(document.removeEventListener("keydown",M),M=null),fe.delete(t.el),q&&ke.get(q)===b&&ke.delete(q)}};return fe.set(t.el,b),q&&ke.set(q,b),b}const Ne="wss://api.paramms.com/ws";function Ln(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,p=t.contextStatus??t.listingStatus??t.subjectStatus,l=t.listingPrice??t.subjectPrice,g=s?{title:s,...r?{subtitle:r}:{},...l!=null?{tags:[`$${l.toLocaleString()}`]}:{},...p?{status:p}:{}}:void 0,w=t.subject??g,d=t.userName??t.name,x=t.userEmail??t.email,I=t.userAvatar??t.avatar,C=d||x||I?{...d?{name:d}:{},...x?{email:x}:{},...I?{avatar:I}:{}}:void 0,M=t.user??C,R=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??Ne,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}:{},...w?{subject:w}:{},...M?{user:M}:{},...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.locale?{locale:t.locale}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...R?{launcherMessage:R}:{},...lt(t)&&!o?{onBack:()=>{ge=!0,xe=!1,Se(re)}}:{},launcher:o,position:t.position??"bottom-right"}}let ne=null,H=null,se=!1,re={},ge=!1,xe=!1;function lt(t){return!!(t.inbox||t.inboxStart)}let oe=null;function An(t,e){const n=!e&&!!t.el;if(se&&!n&&(H.innerHTML="",H=null,se=!1),n){const i=typeof t.el=="string"?document.querySelector(t.el):t.el;i instanceof HTMLElement?(H&&H!==i&&!se&&H.remove(),H=i,se=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!H||!se&&!H.isConnected)&&(H=document.createElement("div"),H.id="relay-widget-root",document.body.appendChild(H),se=!1),!e&&t.height&&(H.style.height=t.height,H.style.width||(H.style.width="100%")),H}function Se(t){try{const e=t.launcher??!0;oe==null||oe(),oe=null,ne==null||ne.close(),ne=null;const n=An(t,e);if(lt(t)&&!e&&ge){zn(t,n);return}ne=De(Ln(t,n))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function zn(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=()=>{ge=!1,Se(re)},i.append(o,s);const p=!xe&&!!n;p&&i.append(r),e.appendChild(i);let l=null,g=null;oe=()=>{g==null||g.close(),l==null||l.close(),e.innerHTML=""};let w;try{({mountChatList:w}=await Promise.resolve().then(()=>En))}catch(x){console.error("[Relay] could not load the conversation list module.",x),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 d=x=>{const I=x.profileId??n;if(!I){console.error("[Relay] conversation row has no chatroom; cannot open it.",x);return}r.style.display="none",g==null||g.close(),g=De({el:s,url:t.url??Ne,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:I,...x.kind==="direct"&&x.peerId?{kind:"direct",peerId:x.peerId}:x.subjectId?{subjectId:x.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}:{}}}:{},...x.subjectTitle?{subject:{title:x.subjectTitle,...x.subjectMeta?{subtitle:x.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{g==null||g.close(),g=null,s.style.display="none",o.style.display="",r.style.display="",l==null||l.refresh()}}),o.style.display="none",s.style.display=""};l=w({el:o,url:t.url??Ne,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...p?{reserveCloseSpace:!0}:{},onSelect:d,onNewChat:()=>{const x=n??(l==null?void 0:l.defaultProfileId());x&&d({id:"__new__",profileId:x,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function dt(t){xe=!!(t.inboxStart&&!(t.launcher??!0)),ge=xe,re={...t},Se(re)}function Mn(t){re={...re,...t},Se(re)}function $n(){oe==null||oe(),oe=null,ne==null||ne.close(),ne=null,H&&!se&&H.remove(),H=null,se=!1,ge=!1,xe=!1,re={}}function qe(t,e){switch(t){case"boot":dt(e??{});break;case"update":case"identify":Mn(e??{});break;case"shutdown":$n();break;default:console.warn("[Relay] unknown command:",t)}}function Rn(){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.relayLocale&&(o.locale=e.relayLocale),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??Rn();i&&dt(i)}}return te.Relay=qe,Object.defineProperty(te,Symbol.toStringTag,{value:"Module"}),te}({});
241
241
  //# sourceMappingURL=embed-lite.js.map