@paramms/chat-widget 1.6.0 → 1.6.2

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