@paramms/chat-widget 1.0.47 → 1.0.48
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/chatlist.js +62 -64
- package/dist/chatlist.js.map +1 -1
- package/dist/embed-lite.js +10 -11
- package/dist/embed-lite.js.map +1 -1
- package/dist/embed.js +8 -9
- package/dist/embed.js.map +1 -1
- package/dist/index.js +356 -353
- package/dist/index.js.map +1 -1
- package/dist/react.js +125 -130
- package/dist/react.js.map +1 -1
- package/package.json +1 -1
package/dist/embed.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var RelayEmbed=function(Q){"use strict";var di=Object.defineProperty;var hi=(Q,X,le)=>X in Q?di(Q,X,{enumerable:!0,configurable:!0,writable:!0,value:le}):Q[X]=le;var a=(Q,X,le)=>hi(Q,typeof X!="symbol"?X+"":X,le);const X="oc_uid";function le(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 tt(){let t=null;try{t=localStorage.getItem(X)}catch{}t||(t=le(X));const e=t??At();try{localStorage.setItem(X,e)}catch{}return Bt(X,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 p=t.charCodeAt(s);(p&64512)===56320&&(++s,r=((r&1023)<<10)+(p&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 nt(t,e,n){let o=e;const i=o+n,s=[];let r="";for(;o<i;){const p=t[o++];if(!(p&128))s.push(p);else if((p&224)===192){const l=t[o++]&63;s.push((p&31)<<6|l)}else if((p&240)===224){const l=t[o++]&63,u=t[o++]&63;s.push((p&31)<<12|l<<6|u)}else if((p&248)===240){const l=t[o++]&63,u=t[o++]&63,f=t[o++]&63;let d=(p&7)<<18|l<<12|u<<6|f;d>65535&&(d-=65536,s.push(d>>>10&1023|55296),d=56320|d&1023),s.push(d)}else s.push(p);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):nt(t,e,n)}class Te{constructor(e,n){a(this,"type");a(this,"data");this.type=e,this.data=n}}class W extends Error{constructor(e){super(e);const n=Object.create(W.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:W.name})}}const fe=4294967295;function Ot(t,e,n){const o=n/4294967296,i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function it(t,e,n){const o=Math.floor(n/4294967296),i=n;t.setUint32(e,o),t.setUint32(e+4,i)}function ot(t,e){const n=t.getInt32(e),o=t.getUint32(e+4);return n*4294967296+o}function Ht(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),it(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=ot(e,4),o=e.getUint32(0);return{sec:n,nsec:o}}default:throw new W(`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},ze=class ze{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 Te(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 Te(r,s)}}}return e instanceof Te?e:null}decode(e,n,o){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,o):new Te(n,e)}};a(ze,"defaultCodec",new ze);let Ue=ze;function en(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function _e(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 je{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)??Ue.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 je({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=_e(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),Ot(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),it(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 je(e).encodeSharedRef(t)}function Ne(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 p=0;p<o;p++)if(r[p]!==e[n+p])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=nt(e,n,o),r=Uint8Array.prototype.slice.call(e,n,n+o);return this.store(r,s),s}}const qe="array",we="map_key",st="map_value",cn=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new W("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=qe,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=we,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===qe){const o=e;o.size=0,o.array=void 0,o.position=0,o.type=void 0}if(e.type===we||e.type===st){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 ge=-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 rt=new RangeError("Insufficient data"),hn=new an;class He{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",ge);a(this,"stack",new ln);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ue.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)??fe,this.maxBinLength=(e==null?void 0:e.maxBinLength)??fe,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??fe,this.maxMapLength=(e==null?void 0:e.maxMapLength)??fe,this.maxExtLength=(e==null?void 0:e.maxExtLength)??fe,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 He({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=ge,this.stack.reset()}setBuffer(e){const n=_e(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ge&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),o=_e(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 p of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(p);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 ${Ne(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 W(`Unrecognized type byte: ${Ne(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===qe)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===we){if(n==="__proto__")throw new W("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=st;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=we;continue e}}return n}}readHeadByte(){return this.headByte===ge&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ge}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 W(`Unrecognized array type byte: ${Ne(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new W(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new W(`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 W(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw rt;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===we:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new W(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw rt;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 W(`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=Ht(this.view,this.pos);return this.pos+=8,e}readI64(){const e=ot(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 He(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 Fe(t){return on(t)}function at(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=ct(n);let i=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||ct(r.status)>=o||(this.byId.set(s,{...r,status:n}),i=!0);i&&(this._sorted=null)}}function ct(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=at(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 p;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(p=this.socket)==null||p.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,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(Fe(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 lt=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>lt?n.slice(n.length-lt):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 A=()=>globalThis.crypto.subtle;function Pe(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 We(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 ye(){const t=await A().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:t.publicKey,privateKey:t.privateKey}}async function ie(t){return Pe(await A().exportKey("raw",t))}async function de(t){return A().importKey("raw",We(t),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function kn(t,e){const n=await de(e);return A().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 A().encrypt({name:"AES-GCM",iv:n},t,o);return{ct:Pe(i),iv:Pe(n)}}async function In(t,e,n){const o=await A().decrypt({name:"AES-GCM",iv:We(n)},t,We(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),p=await A().importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!0,[]),l=await A().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:p,privateKey:l}}}catch{}const e=await ye();try{const i=await A().exportKey("jwk",e.publicKey),s=await A().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 A().exportKey("raw",e),o=await A().sign({name:"ECDSA",hash:"SHA-256"},t,n);return Pe(o)}async function Tn(){const t=await ye(),e=await A().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:t,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await ie(t.publicKey),sigPublicKeyB64:await ie(e.publicKey)}}async function dt(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 A().importKey("jwk",s.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),p=await A().importKey("jwk",s.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),l=await A().importKey("jwk",s.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),u=await A().importKey("jwk",s.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:p},ecdsaKP:{publicKey:l,privateKey:u},publicKeyB64:await ie(r),sigPublicKeyB64:await ie(l)}}}catch{}const e=await Tn();try{const i=await A().exportKey("jwk",e.ecdhKP.publicKey),s=await A().exportKey("jwk",e.ecdhKP.privateKey),r=await A().exportKey("jwk",e.ecdsaKP.publicKey),p=await A().exportKey("jwk",e.ecdsaKP.privateKey);(o=globalThis.localStorage)==null||o.setItem(`${t}-identity`,JSON.stringify({ecdhPub:i,ecdhPriv:s,ecdsaPub:r,ecdsaPriv:p}))}catch{}return e}async function Un(t,e){const n=await ye(),o=await ie(n.publicKey),i=await de(e.identityKey),s=await de(e.signedPrekey),r=e.oneTimePrekey?await de(e.oneTimePrekey):null,p=await oe(t.privateKey,s),l=await oe(n.privateKey,i),u=await oe(n.privateKey,s),f=r?await oe(n.privateKey,r):null,d=ht(p,l,u,...f?[f]:[]);return{sharedKey:await pt(d),ephemeralPublicKey:o}}async function Pn(t,e,n,o,i){const s=await de(n),r=await de(o),p=await oe(e.privateKey,s),l=await oe(t.privateKey,r),u=await oe(e.privateKey,r),f=i?await oe(i.privateKey,r):null,d=ht(p,l,u,...f?[f]:[]);return pt(d)}async function oe(t,e){return A().deriveBits({name:"ECDH",public:e},t,256)}function ht(...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 pt(t){const e=await A().importKey("raw",t,"HKDF",!1,["deriveKey"]);return A().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),ie(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await kn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await dt(this.storageKey),this.signedPreKP=await ye(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let i=0;i<Bn;i++)this.otpKeys.push(await ye());const e=await ie(this.signedPreKP.publicKey),n=await En(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),o=await Promise.all(this.otpKeys.map(i=>ie(i.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:n,oneTimePrekeys:o}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await dt(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 ut(t,e){return Object.entries(e).map(([n,o])=>`--${t}-${n}:${o};`).join(" ")}function ft(t){return`${ut(t,zn)} --${t}-fb:${Kn}; --${t}-fh:'Baloo 2',var(--${t}-fb);`}function Be(t){return ut(t,Mn)}const $n=`
|
|
2
|
-
.ocw { ${
|
|
1
|
+
var RelayEmbed=function(Q){"use strict";var li=Object.defineProperty;var di=(Q,Y,le)=>Y in Q?li(Q,Y,{enumerable:!0,configurable:!0,writable:!0,value:le}):Q[Y]=le;var a=(Q,Y,le)=>di(Q,typeof Y!="symbol"?Y+"":Y,le);const Y="oc_uid";function le(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(Y)}catch{}t||(t=le(Y));const e=t??At();try{localStorage.setItem(Y,e)}catch{}return Bt(Y,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 u=t.charCodeAt(s);(u&64512)===56320&&(++s,r=((r&1023)<<10)+(u&1023)+65536)}r&4294901760?(e[i++]=r>>18&7|240,e[i++]=r>>12&63|128,e[i++]=r>>6&63|128):(e[i++]=r>>12&15|224,e[i++]=r>>6&63|128)}else{e[i++]=r;continue}e[i++]=r&63|128}}const 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 u=t[o++];if(!(u&128))s.push(u);else if((u&224)===192){const d=t[o++]&63;s.push((u&31)<<6|d)}else if((u&240)===224){const d=t[o++]&63,p=t[o++]&63;s.push((u&31)<<12|d<<6|p)}else if((u&248)===240){const d=t[o++]&63,p=t[o++]&63,g=t[o++]&63;let l=(u&7)<<18|d<<12|p<<6|g;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(u);s.length>=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 Te{constructor(e,n){a(this,"type");a(this,"data");this.type=e,this.data=n}}class W extends Error{constructor(e){super(e);const n=Object.create(W.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:W.name})}}const we=4294967295;function Ot(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 Ht(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 W(`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},ze=class ze{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 Te(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 Te(r,s)}}}return e instanceof Te?e:null}decode(e,n,o){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,o):new Te(n,e)}};a(ze,"defaultCodec",new ze);let Ue=ze;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)??Ue.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),Ot(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 u=0;u<o;u++)if(r[u]!==e[n+u])continue e;return s.str}return null}store(e,n){const o=this.caches[e.length-1],i={bytes:e,str:n};o.length>=this.maxLengthPerKey?o[Math.random()*o.length|0]=i:o.push(i)}decode(e,n,o){const i=this.find(e,n,o);if(i!=null)return this.hit++,i;this.miss++;const s=it(e,n,o),r=Uint8Array.prototype.slice.call(e,n,n+o);return this.store(r,s),s}}const Oe="array",ye="map_key",rt="map_value",cn=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new W("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=Oe,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===Oe){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 ge=-1,He=new DataView(new ArrayBuffer(0)),dn=new Uint8Array(He.buffer);try{He.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",He);a(this,"bytes",dn);a(this,"headByte",ge);a(this,"stack",new ln);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ue.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)??we,this.maxBinLength=(e==null?void 0:e.maxBinLength)??we,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??we,this.maxMapLength=(e==null?void 0:e.maxMapLength)??we,this.maxExtLength=(e==null?void 0:e.maxExtLength)??we,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=ge,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===ge&&!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 u of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(u);try{o=this.doDecodeSync(),n=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return o}const{headByte:i,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${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 W(`Unrecognized type byte: ${qe(e)}`);this.complete();const o=this.stack;for(;o.length>0;){const i=o.top();if(i.type===Oe)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 W("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===ge&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ge}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 W(`Unrecognized array type byte: ${qe(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new W(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new W(`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 W(`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 W(`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 W(`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=Ht(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 yn{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"&&gn.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(i=this.opts).onStatusChange)==null||s.call(i,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var u;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(u=this.socket)==null||u.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var n,o,i;this.stopped=!0;try{(n=this.socket)==null||n.close()}catch{}this.state="closed",(i=(o=this.opts).onStatusChange)==null||i.call(o,"error",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 gn=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 z=()=>globalThis.crypto.subtle;function Pe(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 xe(){const t=await z().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:t.publicKey,privateKey:t.privateKey}}async function oe(t){return Pe(await z().exportKey("raw",t))}async function de(t){return z().importKey("raw",Ve(t),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function kn(t,e){const n=await de(e);return z().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 z().encrypt({name:"AES-GCM",iv:n},t,o);return{ct:Pe(i),iv:Pe(n)}}async function In(t,e,n){const o=await z().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),u=await z().importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!0,[]),d=await z().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:u,privateKey:d}}}catch{}const e=await xe();try{const i=await z().exportKey("jwk",e.publicKey),s=await z().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 z().exportKey("raw",e),o=await z().sign({name:"ECDSA",hash:"SHA-256"},t,n);return Pe(o)}async function Tn(){const t=await xe(),e=await z().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 z().importKey("jwk",s.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),u=await z().importKey("jwk",s.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),d=await z().importKey("jwk",s.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),p=await z().importKey("jwk",s.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:u},ecdsaKP:{publicKey:d,privateKey:p},publicKeyB64:await oe(r),sigPublicKeyB64:await oe(d)}}}catch{}const e=await Tn();try{const i=await z().exportKey("jwk",e.ecdhKP.publicKey),s=await z().exportKey("jwk",e.ecdhKP.privateKey),r=await z().exportKey("jwk",e.ecdsaKP.publicKey),u=await z().exportKey("jwk",e.ecdsaKP.privateKey);(o=globalThis.localStorage)==null||o.setItem(`${t}-identity`,JSON.stringify({ecdhPub:i,ecdhPriv:s,ecdsaPub:r,ecdsaPriv:u}))}catch{}return e}async function Un(t,e){const n=await xe(),o=await oe(n.publicKey),i=await de(e.identityKey),s=await de(e.signedPrekey),r=e.oneTimePrekey?await de(e.oneTimePrekey):null,u=await se(t.privateKey,s),d=await se(n.privateKey,i),p=await se(n.privateKey,s),g=r?await se(n.privateKey,r):null,l=pt(u,d,p,...g?[g]:[]);return{sharedKey:await ut(l),ephemeralPublicKey:o}}async function Pn(t,e,n,o,i){const s=await de(n),r=await de(o),u=await se(e.privateKey,s),d=await se(t.privateKey,r),p=await se(e.privateKey,r),g=i?await se(i.privateKey,r):null,l=pt(u,d,p,...g?[g]:[]);return ut(l)}async function se(t,e){return z().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 z().importKey("raw",t,"HKDF",!1,["deriveKey"]);return z().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 xe(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let i=0;i<Bn;i++)this.otpKeys.push(await xe());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 Be(t){return ft(t,Mn)}const $n=`
|
|
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; }
|
|
@@ -59,7 +59,6 @@ var RelayEmbed=function(Q){"use strict";var di=Object.defineProperty;var hi=(Q,X
|
|
|
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-dot { width:26px; height:26px; border-radius:50%; background:var(--ocw-tint); color:var(--ocw-accent); font-size:12px; font-weight:700; display:flex; align-items:center; justify-content:center; flex:none; }
|
|
63
62
|
.ocw-bubble { padding:10px 14px; border-radius:18px; font-size:13.5px; line-height:1.45; word-wrap:break-word; max-width:80%; }
|
|
64
63
|
.theirs .ocw-bubble { background:var(--ocw-tint); border-bottom-left-radius:4px; }
|
|
65
64
|
.mine .ocw-bubble { background:var(--ocw-accent2); color:#fff; border-bottom-right-radius:4px; }
|
|
@@ -188,16 +187,16 @@ var RelayEmbed=function(Q){"use strict";var di=Object.defineProperty;var hi=(Q,X
|
|
|
188
187
|
.ocw-translate-btn { position:absolute; bottom:2px; right:-26px; background:var(--ocw-card); border:1px solid var(--ocw-line); border-radius:50%; width:22px; height:22px; font-size:11px; cursor:pointer; color:var(--ocw-mut); display:flex; align-items:center; justify-content:center; opacity:0; transition:opacity .15s; padding:0; }
|
|
189
188
|
.ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
|
|
190
189
|
.ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
|
|
191
|
-
.ocw-
|
|
192
|
-
`,wt="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(wt))return;const t=document.createElement("style");t.id=wt,t.textContent=$n,document.head.appendChild(t)}const gt="ocw-webfont";function Nn(){if(typeof document>"u"||document.getElementById(gt))return;const t=document.createElement("link");t.id=gt,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 Ve(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 On{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 w,U,C,x,b,_,R,j,m,P,H;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 E=c("button","ocw-back","‹");E.type="button",E.setAttribute("aria-label","Back"),E.addEventListener("click",()=>this.h.onBack()),r.append(E)}const p=c("div","ocw-avatar");if((w=i.userInfo)!=null&&w.avatar){const E=document.createElement("img");E.src=i.userInfo.avatar,E.alt=i.userInfo.name??"You",E.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",p.append(E)}else p.textContent=(U=i.userInfo)!=null&&U.name?i.userInfo.name[0].toUpperCase():"🧑";r.append(p);const l=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((C=i.subject)==null?void 0:C.ownerLabel)??((x=i.subject)==null?void 0:x.title)??""),l.append(this.headerName),this.headStatus=c("div","ocw-head-status"),this.headStatus.style.display="none",l.append(this.headStatus),(b=i.subject)!=null&&b.subtitle&&l.append(c("div","ocw-head-meta",i.subject.subtitle)),r.append(l),this.statusBadge=c("span","ocw-badge",((_=i.subject)==null?void 0:_.status)??""),(R=i.subject)!=null&&R.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 u=c("div","ocw-typing-bubble");u.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),u),this.quick=c("div","ocw-quick");for(const E of i.quickReplies??[]){const q=c("button",void 0,E);q.addEventListener("click",()=>{this.h.onSend(E),this.quick.style.display="none"}),this.quick.append(q)}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=((j=i.i18n)==null?void 0:j.placeholder)??"Message…";const f=c("button","ocw-sendbtn");f.type="button";const d=(m=i.i18n)==null?void 0:m.send;d?(f.textContent=d,f.classList.add("ocw-sendbtn-label"),f.setAttribute("aria-label",d)):(f.innerHTML=_n,f.setAttribute("aria-label","Send message")),f.disabled=!0,this.sendBtn=f,f.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var E,q;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(J=>J.senderRole==="guest")?(q=(E=this.h).onDeflectQuery)==null||q.call(E,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",E=>{E.isComposing||E.keyCode===229||(E.key==="Enter"&&!E.shiftKey?(E.preventDefault(),this.flushSend()):this.signalTyping())});const k=c("button","ocw-attach","📎");k.title="Attach image or file";const S=document.createElement("input");S.type="file",S.accept="image/*,.pdf,.txt,.doc,.docx",S.style.display="none",k.addEventListener("click",()=>S.click()),S.addEventListener("change",()=>{var E;(E=S.files)!=null&&E[0]&&this.h.onAttach&&this.h.onAttach(S.files[0]),S.value=""});const L=c("div","ocw-input");L.append(k,S,this.input,f);const z=c("div","ocw-footer");((P=i.i18n)==null?void 0:P.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",((H=this.cfg.i18n)==null?void 0:H.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const E=this.root.querySelector(".ocw-input textarea");E==null||E.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,L,this.reopenBtn,this.footer);const g=E=>{e.classList.toggle("ocw-compact",E>0&&E<Dn)};g(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(E=>{var J;const q=((J=E[0])==null?void 0:J.contentRect.width)??e.clientWidth;g(q)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var S,L,z,g,w,U,C,x;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const b=(S=this.cfg.subject)==null?void 0:S.ownerLabel;b&&(this.headerName.textContent=b)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const b of n)this.chips.append(this.chipEl(b));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const b=c("div","ocw-load-more");b.textContent="↑ Loading earlier messages…",b.style.pointerEvents="none",this.scroll.append(b)}let s=0,r=null;for(const b of e.messages()){const _=b.senderRole!=="system"&&b.senderId!==this.me&&!b.internal&&b.senderId!==r;this.scroll.append(this.messageEl(b,e,_)),b.senderRole!=="system"&&(r=b.senderId),b.senderId!==this.me&&b.seq>s&&(s=b.seq)}i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const p=[...e.typing];this.typing.classList.toggle("active",p.length>0);const l=this.typing.querySelector(".ocw-typing-bubble");l&&l.setAttribute("aria-label",p.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const u=e.messages().some(b=>b.senderRole==="guest");if(!!((L=e.preChat)!=null&&L.enabled)&&!this.preChatDone&&!u&&(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 b=this.awayNotice.lastChild;b.textContent=e.offlineMessage||((g=this.cfg.i18n)==null?void 0:g.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";(w=this.root.querySelector(".ocw-input"))==null||w.style.removeProperty("display")}const d=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&d.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const k=d.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((U=this.cfg.i18n)==null?void 0:U.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((C=this.cfg.i18n)==null?void 0:C.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",k&&e.messages().length>0){const b=c("div","ocw-resolved-note",`— ${((x=this.cfg.i18n)==null?void 0:x.resolved)??"Marked as resolved"} —`);this.scroll.append(b),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const 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 f=c("input","ocw-offline-input");f.type=u==="email"?"email":u==="phone"?"tel":"text",f.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",o[u]=f,n.append(f)}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 f of e.topics){const d=document.createElement("option");d.value=f,d.textContent=f,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 p=c("button","ocw-offline-submit","Start chat");p.type="button",p.addEventListener("click",()=>{var k,S,L,z,g,w,U;const u=(k=o.email)==null?void 0:k.value.trim();if(o.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){o.email.focus();return}const f=!!(s!=null&&s.checked),d=(((S=o.phone)==null?void 0:S.value)??(r==null?void 0:r.value)??"").trim();if(f&&!d){(L=o.phone??r)==null||L.focus();return}if(i&&((z=e.topics)!=null&&z.length)&&!i.value){i.focus();return}p.disabled=!0,this.completePreChat(),(U=(w=this.h).onPreChat)==null||U.call(w,{...(g=o.name)!=null&&g.value.trim()?{name:o.name.value.trim()}:{},...u?{email:u}:{},...d?{phone:d}:{},...i!=null&&i.value?{topic:i.value}:{},...f?{callback:!0}:{}})}),n.append(p),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(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[p,l]of Object.entries(n.fields))s.append(c("span","ocw-tag",`${p}: ${l}`));else for(const p of(o==null?void 0:o.tags)??[])s.append(c("span","ocw-tag",p));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"),p=c("button","ocw-modal-ok","Confirm"),l=u=>{o.remove(),n(u)};r.addEventListener("click",()=>l(!1)),p.addEventListener("click",()=>l(!0)),o.addEventListener("click",u=>{u.target===o&&l(!1)}),s.append(r,p),i.append(s),o.append(i),this.root.append(o),p.focus()})}openForm(e){var p,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 f=c("label","ocw-form-row");if(f.append(c("span","ocw-form-lbl",u.label)),u.type==="select"&&((p=u.options)!=null&&p.length)){const d=c("select","ocw-form-input");u.required||d.append(c("option",void 0,"— select —"));for(const k of u.options){const S=c("option");S.value=k,S.textContent=k,d.append(S)}u.required&&(d.required=!0),f.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),f.append(d),o.set(u.name,d)}n.append(f)}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[f,d]of o){if(d.required&&!d.value){d.style.borderColor="#e5484d";return}u[f]=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){var k,S,L,z;if(e.senderRole==="system"){const g=c("div","ocw-sys");return g.textContent=e.deletedAt?"message deleted":Ve(e.content),g}const i=e.senderId===this.me,s=!!e.internal,r=c("div",`ocw-row ${s?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!i&&!s&&r.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const p=c("div");if(o){const g=e.senderRole==="bot"?((k=this.cfg.i18n)==null?void 0:k.aiAssistant)??"AI Assistant":((S=this.cfg.subject)==null?void 0:S.ownerLabel)??((L=this.cfg.subject)==null?void 0:L.title)??"Support";p.append(c("div","ocw-msg-sender",g))}const l=c("div","ocw-bubble-wrap");if(e.replyToId){const g=c("div","ocw-reply-to","↩ replying to a message");g.style.cssText="font-size:11px;color:var(--ocw-mut);margin-bottom:2px;font-style:italic",p.append(g)}const u=c("div","ocw-bubble");let f=null;if(e.deletedAt)u.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const g=e.content;if((z=g.mime)!=null&&z.startsWith("image/")){const w=document.createElement("img");w.src=g.url,w.alt=g.name??"image",w.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",w.addEventListener("click",()=>window.open(g.url,"_blank")),u.append(w)}else{const w=document.createElement("a");w.href=g.url,w.target="_blank",w.rel="noopener",w.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",w.append(c("span",void 0,"📄"),c("span",void 0,g.name??"file")),u.append(w)}}else if(e.content.kind==="appointment"){const g=e.content,w=c("div","ocw-appt");w.append(c("div","ocw-appt-title",`📅 ${g.title}`)),w.append(c("div","ocw-appt-time",new Date(g.startIso).toLocaleString()+" – "+new Date(g.endIso).toLocaleTimeString())),g.location&&w.append(c("div","ocw-appt-loc",`📍 ${g.location}`)),g.description&&w.append(c("div","ocw-appt-desc",g.description));const U=c("div","ocw-appt-links"),C=document.createElement("a");C.href=g.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=g.icalUrl,x.download=`${g.title}.ics`,x.className="ocw-appt-btn ocw-appt-btn-sec",x.textContent="🍎 Apple / iCal",U.append(C,x),w.append(U),u.append(w)}else f=document.createTextNode(Ve(e.content)),u.append(f),e.editedAt&&u.append(c("span","ocw-edited","(edited)"));if(l.append(u),!i&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&f){const g=e.content.text;if(g.trim()){const w=c("button","ocw-translate-btn","🌐");w.type="button",w.title="Translate",w.addEventListener("click",U=>{if(U.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),f.textContent=g,w.textContent="🌐",w.title="Translate";return}const C=this.translationCache.get(e.id);if(C!==void 0){this.showingTranslation.add(e.id),f.textContent=C,w.textContent="↩",w.title="Show original";return}w.textContent="⏳",this.h.onTranslate(g).then(x=>{if(x===null){w.textContent="⚠️",w.title="Translation unavailable",setTimeout(()=>{w.textContent="🌐",w.title="Translate"},1500);return}this.translationCache.set(e.id,x),this.showingTranslation.add(e.id),f.textContent=x,w.textContent="↩",w.title="Show original"})}),l.append(w)}}if(i&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const g=c("div","ocw-msg-menu");if(this.h.onEdit){const w=c("button",void 0,"✏️");w.title="Edit",w.addEventListener("click",U=>{U.stopPropagation();const C=Ve(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 b=c("button","ocw-form-submit","Save");b.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const _=c("button","ocw-form-cancel","Cancel");_.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const R=c("div");R.style.cssText="display:flex;gap:6px;justify-content:flex-end",R.append(_,b);const j=c("div");j.append(x,R),u.replaceChildren(j),x.focus(),x.select();const m=()=>u.replaceChildren(f??document.createTextNode(C));_.addEventListener("click",m),b.addEventListener("click",()=>{const P=x.value.trim();P&&P!==C&&this.h.onEdit(e.id,P),m()}),x.addEventListener("keydown",P=>{P.key==="Enter"&&!P.shiftKey&&(P.preventDefault(),b.click()),P.key==="Escape"&&m()})}),g.append(w)}if(this.h.onDelete){const w=c("button","del","🗑");w.title="Delete",w.addEventListener("click",U=>{U.stopPropagation(),this.h.onDelete(e.id)}),g.append(w)}l.append(g)}if(p.append(l),this.h.onReact&&!e.deletedAt&&e.seq>0){const g=c("div","ocw-react-wrap"),w=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[x,b]of Object.entries(e.reactions)){const _=c("button",`ocw-react-pill${b.includes(this.me)?" mine":""}`,`${x} ${b.length}`);_.addEventListener("click",()=>{var R,j;return(j=(R=this.h).onReact)==null?void 0:j.call(R,e.id,x,b.includes(this.me))}),w.append(_)}const U=c("button","ocw-react-btn","+"),C=c("div","ocw-react-picker");for(const x of Rn){const b=c("button",void 0,x);b.addEventListener("click",_=>{var j,m,P,H;_.stopPropagation();const R=(m=(j=e.reactions)==null?void 0:j[x])==null?void 0:m.includes(this.me);(H=(P=this.h).onReact)==null||H.call(P,e.id,x,!!R),C.style.display="none"}),C.append(b)}C.style.display="none",U.addEventListener("click",x=>{x.stopPropagation();const b=C.style.display==="none";C.style.display=b?"flex":"none",b&&document.addEventListener("click",()=>{C.style.display="none"},{once:!0})}),w.append(U),g.append(w,C),p.append(g)}else e.reactions&&Object.keys(e.reactions).length&&p.append(c("div","ocw-react",Object.entries(e.reactions).map(([g,w])=>`${g}${w.length}`).join(" ")));const d=c("div","ocw-time ocw-meta",qn(e.ts));if(i&&e.status){const g=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,Hn(e.status));d.append(g)}return i&&e.seq>0&&n.lastReadByOthers>=e.seq&&d.append(c("span","ocw-seen"," · Seen")),p.append(d),r.append(p),r}}function Hn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Fn=20;function Xe(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 Xe(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 yt(t,e,n,o,i=Fn){let s,r=!1;for(const p of Vn(t,e,o,i))try{const l=await fetch(p,{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),p=await yt(r,n,e,Number.MAX_SAFE_INTEGER);if(!p||(p.messages.length?(o.apply({type:"sync",conversationId:n,messages:p.messages}),o.apply({type:"history",conversationId:n,messages:[],hasMore:p.hasMore}),i.render(o)):o.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!p.hasMore))return;let l=!1;const u=async()=>{if(l||!o.hasMoreHistory)return;l=!0;const S=o.messages()[0];if(!S){l=!1;return}const L=await yt(r,n,e,S.seq);L&&(o.apply({type:"history",conversationId:n,messages:L.messages,hasMore:L.hasMore}),i.render(o)),l=!1},f=i.getScrollEl();if(!f)return;let d=!1;setTimeout(()=>{d=!0},300);const k=()=>{d&&f.scrollTop<80&&o.hasMoreHistory&&!l&&u()};f.addEventListener("scroll",k,{passive:!0}),i.setScrollCleanup(()=>f.removeEventListener("scroll",k))}const xe=new WeakMap,Ae=new Map;function xt(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let me=null;function Gn(){if(me&&me.state!=="closed")return me;try{return me=new AudioContext,me}catch{return null}}function mt(t){var pe,Se,Ie,kt,St,It,Ct,Et;xe.has(t.el)&&(xe.get(t.el).close(),xe.delete(t.el)),t.launcher&&((pe=Ae.get(xt(t)))==null||pe.close());const e=tt();let n,o=!1;const i=t.token??t.userId??e,s=i!==e?e:void 0,{wsUrl:r,httpBase:p}=Xe(t.url,t.apiUrl);let l=new wn(i);const u=t.subjectId?`${i}::${t.subjectId}`:i,f=new vn(u);let d,k=!1,S=null,L=null,z=null,g=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 f.load())l.addOptimistic(h.clientMsgId,h.content);let w=null,U=null,C=0,x=!t.launcher;if(t.launcher){const y=(t.position??"bottom-right").includes("right");w=document.createElement("div"),w.style.cssText=`position:fixed;${y?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${y?"flex-end":"flex-start"};gap:12px`;const T=document.createElement("div"),N=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,Ce=$=>{t.el.classList.toggle("ocw-fs",$),T.style.cssText=$?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(y?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};Ce((N==null?void 0:N.matches)??!1);const Ee=$=>Ce($.matches);N==null||N.addEventListener("change",Ee),S=N,L=Ee,t.el.style.cssText="width:100%;height:100%;overflow:hidden",T.append(t.el);const Ke='<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>',$e='<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>',V=document.createElement("button");V.type="button",V.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(";"),V.onmouseenter=()=>{V.style.transform="scale(1.08)"},V.onmouseleave=()=>{V.style.transform="scale(1)"},U=document.createElement("span"),U.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 Re=()=>{V.innerHTML=x?$e:Ke,V.setAttribute("aria-label",x?"Close chat":"Open chat"),V.setAttribute("aria-expanded",String(x)),V.append(U)};Re(),w.append(T,V),document.body.append(w);const Je=`ocw-teaser-dismissed::${t.profileId}`,De=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let K=null;const ci=()=>{try{return sessionStorage.getItem(Je)==="1"}catch{return!1}},li='<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 $=De!=null&&De.title?De:l.launcherMessage??void 0;if(!(!!($!=null&&$.title)&&!x&&!ci())){K&&(K.remove(),K=null);return}if(K)return;K=document.createElement("div"),K.setAttribute("role","button"),K.setAttribute("tabindex","0"),K.setAttribute("aria-label",$.title),K.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${y?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Qe=document.createElement("div");if(Qe.textContent=$.title,Qe.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",K.append(Qe),$.subtitle){const ne=document.createElement("div");ne.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const et=document.createElement("span");et.innerHTML=li,et.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const Pt=document.createElement("span");Pt.textContent=$.subtitle,ne.append(et,Pt),K.append(ne)}const ue=document.createElement("button");ue.type="button",ue.setAttribute("aria-label","Dismiss"),ue.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>',ue.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",ue.addEventListener("click",ne=>{ne.stopPropagation();try{sessionStorage.setItem(Je,"1")}catch{}K&&(K.remove(),K=null)}),K.append(ue);const Ut=()=>{x||(x=!0,Ze(!0),Re(),C=0,U&&(U.style.display="none"),K&&(K.remove(),K=null))};K.addEventListener("click",Ut),K.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),Ut())}),w.insertBefore(K,V)};if(!document.getElementById("ocw-teaser-style")){const $=document.createElement("style");$.id="ocw-teaser-style",$.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append($)}g=Tt,Tt();const Ze=$=>{$?(T.style.display="flex",requestAnimationFrame(()=>{T.style.opacity="1",T.style.transform="scale(1)"})):(T.style.opacity="0",T.style.transform="scale(.95)",setTimeout(()=>{x||(T.style.display="none")},180))};V.addEventListener("click",()=>{if(x=!x,Ze(x),Re(),x){C=0,U&&(U.style.display="none");try{sessionStorage.setItem(Je,"1")}catch{}}g==null||g()}),z=$=>{$.key==="Escape"&&x&&(x=!1,Ze(!1),Re())},document.addEventListener("keydown",z)}const b=()=>{x||(C++,U&&(U.textContent=String(C),U.style.display="flex"))},_=()=>{try{const h=Gn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const y=h.createOscillator(),T=h.createGain();y.connect(T),T.connect(h.destination),y.frequency.setValueAtTime(880,h.currentTime),y.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),T.gain.setValueAtTime(.3,h.currentTime),T.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),y.start(),y.stop(h.currentTime+.3)}catch{}},R=[],j=h=>{for(;R.length;){const y=R.shift();f.add({clientMsgId:y.clientMsgId,content:y.content,ts:Date.now()}),m.send({type:"send",conversationId:h,clientMsgId:y.clientMsgId,content:y.content})}};let m;const P=new An(`ocw-e2e-${t.profileId}`);let H=!1;const E=[],q=[];let J=!1;const he=(h,y)=>{P.sealText(y).then(T=>{d&&m.send({type:"send",conversationId:d,clientMsgId:h,content:T})})},Me=(h,y,T)=>{P.sealText(y,T).then(N=>{d&&m.send({type:"send",conversationId:d,clientMsgId:h,content:N})})},v=()=>{for(;E.length;){const h=E.shift();he(h.clientMsgId,h.text)}for(;q.length;){const h=q.shift();he(h.clientMsgId,h.text)}},M=h=>{m.send({type:"fetchPrekey",targetUserId:h})},O=t.i18n??{},G=["ar","he","fa","ur"],F=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";G.includes(F)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Y=`oc_prechat_${t.profileId}_${i.slice(-8)}`,I=new On(t.el,i,{onSend(h){const y=`cm_${Math.random().toString(36).slice(2)}`,T={kind:"text",text:h};l.addOptimistic(y,T),I.render(l),l.e2e?P.ready?he(y,h):J?q.push({clientMsgId:y,text:h}):(E.push({clientMsgId:y,text:h}),l.assignedAgentId&&M(l.assignedAgentId)):d?(f.add({clientMsgId:y,content:T,ts:Date.now()}),m.send({type:"send",conversationId:d,clientMsgId:y,content:T})):R.push({clientMsgId:y,content:T})},async onAttach(h){if(!d)return;const y=`${p}/upload?name=${encodeURIComponent(h.name)}`,T=`cm_${Math.random().toString(36).slice(2)}`;l.addOptimistic(T,{kind:"text",text:`📎 Uploading ${h.name}…`}),I.render(l);try{const N=await fetch(y,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${i}`},body:h});if(!N.ok)throw new Error(`Upload failed: ${N.status}`);const{url:Ce,name:Ee,mime:Ke,size:$e}=await N.json();l.addOptimistic(T,{kind:"attachment",url:Ce,name:Ee,mime:Ke,size:$e}),I.render(l),m.send({type:"send",conversationId:d,clientMsgId:T,content:{kind:"attachment",url:Ce,name:Ee,mime:Ke,size:$e}})}catch(N){l.addOptimistic(T,{kind:"text",text:`⚠️ Upload failed: ${N.message}`}),I.render(l)}},onInvoke(h,y){d&&m.send({type:"invoke",conversationId:d,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...y?{inputs:y}:{}})},onTyping(h,y){d&&m.send({type:"typing",conversationId:d,isTyping:h,...y?{preview:y}:{}})},onPreChat(h){try{localStorage.setItem(Y,"1")}catch{}m.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const y=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";y&&d&&!l.e2e&&m.send({type:"send",conversationId:d,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:y}})},...((Se=t.features)==null?void 0:Se.deflection)!==!1?{onDeflectQuery(h){if(o)return;clearTimeout(n);const y=h.trim();if(y.length<3){I.hideDeflection();return}n=setTimeout(()=>{fetch(`${p}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(y.slice(0,200))}`).then(T=>T.ok?T.json():{articles:[]}).then(T=>I.showDeflection(T.articles??[])).catch(()=>I.hideDeflection())},350)}}:{},onReadUpTo(h){d&&m.send({type:"read",conversationId:d,seq:h})},onLoadMore(){if(!d||!l.e2e)return;const h=l.messages()[0];h&&m.send({type:"history",conversationId:d,beforeSeq:h.seq,limit:20})},onEdit(h,y){d&&m.send({type:"edit",conversationId:d,messageId:h,content:{kind:"text",text:y}})},onDelete(h){d&&m.send({type:"delete",conversationId:d,messageId:h})},...((Ie=t.features)==null?void 0:Ie.reactions)!==!1?{onReact(h,y,T){d&&m.send({type:"react",conversationId:d,messageId:h,emoji:y,remove:T})}}:{},...((kt=t.features)==null?void 0:kt.csat)!==!1?{onCsat(h){d&&fetch(`${p}/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 y=await fetch(`${p}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:h,targetLang:t.translateLang})});if(!y.ok)return null;const{translated:T}=await y.json();return T}catch{return null}}}:{},...t.onBack?{onBack:t.onBack}:{}},{...t.subject?{subject:t.subject}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...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:O});try{localStorage.getItem(Y)&&I.completePreChat()}catch{}const ae=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,ke={type:"open",profileId:t.profileId,...t.kind==="direct"&&t.peerId?{kind:"direct",peerId:t.peerId}:t.subjectId?{subjectId:t.subjectId}:{},...s?{linkFrom:s}:{},...ae?{userInfo:ae}:{},...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}:{}};m=new gn({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:i,open:ke,getCursor:()=>l.highestSeq(),onStatusChange:(h,y)=>I.setConnStatus(h,y),onFrame(h){if(h.type==="opened"){if(d=h.conversation.id,!k){k=!0;for(const y of f.load())m.send({type:"send",conversationId:d,clientMsgId:y.clientMsgId,content:y.content})}Xn(r,i,d,l,I,p),R.length&&j(d)}if(h.type==="ack"&&f.remove(h.clientMsgId),h.type==="prekeyBundle"){h.bundle&&(J=!0,P.x3dhSendTo(h.bundle).then(y=>{const T=[...E.splice(0),...q.splice(0)];for(const N of T)Me(N.clientMsgId,N.text,y);I.render(l)}));return}if(h.type==="message"&&l.e2e){const y=Ln(h.message.content);if(y&&!P.ready){P.x3dhReceiveFrom(y.x3dhIK,y.x3dhEK,y.x3dhSPK,y.x3dhOTP).then(async()=>{await P.openFrame(h),l.apply(h),I.render(l)});return}}if(h.type==="peerkey"){P.onPeerKey(h.key).then(()=>{v(),I.render(l)});return}(async()=>{if(l.e2e&&await P.openFrame(h),l.apply(h),h.type==="manifest"&&(g==null||g()),h.type==="message"&&h.message.senderId!==i&&!h.message.internal&&(b(),_()),l.e2e&&d&&!H){H=!0;const y=await P.initX3DH();m.send({type:"uploadPrekeys",...y});const T=await P.begin();m.send({type:"pubkey",conversationId:d,key:T})}I.render(l)})()}}),m.connect(),I.render(l);const ce=t.launcher?xt(t):null,Z={close:()=>{o=!0,clearTimeout(n),m.close(),w==null||w.remove(),I.destroy(),S&&L&&S.removeEventListener("change",L),z&&(document.removeEventListener("keydown",z),z=null),xe.delete(t.el),ce&&Ae.get(ce)===Z&&Ae.delete(ce)}};return xe.set(t.el,Z),ce&&Ae.set(ce,Z),Z}const Ge="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,p=t.contextStatus??t.listingStatus??t.subjectStatus,l=t.listingPrice??t.subjectPrice,u=s?{title:s,...r?{subtitle:r}:{},...l!=null?{tags:[`$${l.toLocaleString()}`]}:{},...p?{status:p}:{}}:void 0,f=t.subject??u,d=t.userName??t.name,k=t.userEmail??t.email,S=t.userAvatar??t.avatar,L=d||k||S?{...d?{name:d}:{},...k?{email:k}:{},...S?{avatar:S}:{}}:void 0,z=t.user??L,g=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??Ge,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}:{},...f?{subject:f}:{},...z?{user:z}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...g?{launcherMessage:g}:{},...bt(t)&&!i?{onBack:()=>{be=!0,ve=!1,Le(re)}}:{},launcher:i,position:t.position??"bottom-right"}}let ee=null,D=null,se=!1,re={},be=!1,ve=!1;function bt(t){return!!(t.inbox||t.inboxStart)}let te=null;function Jn(t,e){const n=!e&&!!t.el;if(se&&!n&&(D.innerHTML="",D=null,se=!1),n){const o=typeof t.el=="string"?document.querySelector(t.el):t.el;o instanceof HTMLElement?(D&&D!==o&&!se&&D.remove(),D=o,se=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!D||!se&&!D.isConnected)&&(D=document.createElement("div"),D.id="relay-widget-root",document.body.appendChild(D),se=!1),!e&&t.height&&(D.style.height=t.height,D.style.width||(D.style.width="100%")),D}function Le(t){try{const e=t.launcher??!0;te==null||te(),te=null,ee==null||ee.close(),ee=null;const n=Jn(t,e);if(bt(t)&&!e&&be){Zn(t,n);return}ee=mt(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=()=>{be=!1,Le(re)},o.append(i,s);const p=!ve&&!!n;p&&o.append(r),e.appendChild(o);let l=null,u=null;te=()=>{u==null||u.close(),l==null||l.close(),e.innerHTML=""};let f;try{({mountChatList:f}=await Promise.resolve().then(()=>ai))}catch(k){console.error("[Relay] could not load the conversation list module.",k),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=k=>{const S=k.profileId??n;if(!S){console.error("[Relay] conversation row has no chatroom; cannot open it.",k);return}r.style.display="none",u==null||u.close(),u=mt({el:s,url:t.url??Ge,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:S,...k.kind==="direct"&&k.peerId?{kind:"direct",peerId:k.peerId}:k.subjectId?{subjectId:k.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}:{}}}:{},...k.subjectTitle?{subject:{title:k.subjectTitle,...k.subjectMeta?{subtitle:k.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=f({el:i,url:t.url??Ge,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...p?{reserveCloseSpace:!0}:{},onSelect:d,onNewChat:()=>{const k=n??(l==null?void 0:l.defaultProfileId());k&&d({id:"__new__",profileId:k,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function vt(t){ve=!!(t.inboxStart&&!(t.launcher??!0)),be=ve,re={...t},Le(re)}function Qn(t){re={...re,...t},Le(re)}function ei(){te==null||te(),te=null,ee==null||ee.close(),ee=null,D&&!se&&D.remove(),D=null,se=!1,be=!1,ve=!1,re={}}function Ye(t,e){switch(t){case"boot":vt(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=Ye;let n=!1;for(const o of e){const[i,s]=o;i==="boot"&&(n=!0),Ye(i,s)}if(!n){const o=t.relaySettings??ti();o&&vt(o)}}const ni=`
|
|
193
|
-
.ocl { ${ft("ocl")}
|
|
190
|
+
.ocw-translation { margin-top:6px; padding-top:6px; border-top:1px solid var(--ocw-line); font-size:13px; line-height:1.45; }
|
|
191
|
+
.ocw-translation::before { content:'🌐 '; opacity:.75; }
|
|
192
|
+
`,yt="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(yt))return;const t=document.createElement("style");t.id=yt,t.textContent=$n,document.head.appendChild(t)}const gt="ocw-webfont";function Nn(){if(typeof document>"u"||document.getElementById(gt))return;const t=document.createElement("link");t.id=gt,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 On{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 I,C,x,b,$,R,_,E,k,F,V;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 T=c("button","ocw-back","‹");T.type="button",T.setAttribute("aria-label","Back"),T.addEventListener("click",()=>this.h.onBack()),r.append(T)}const u=((I=i.subject)==null?void 0:I.ownerLabel)??((C=i.subject)==null?void 0:C.title)??"",d=c("div","ocw-avatar");u.trim()&&(d.textContent=u.trim()[0].toUpperCase(),r.append(d));const p=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((x=i.subject)==null?void 0:x.ownerLabel)??((b=i.subject)==null?void 0:b.title)??""),p.append(this.headerName),this.headStatus=c("div","ocw-head-status"),this.headStatus.style.display="none",p.append(this.headStatus),($=i.subject)!=null&&$.subtitle&&p.append(c("div","ocw-head-meta",i.subject.subtitle)),r.append(p),this.statusBadge=c("span","ocw-badge",((R=i.subject)==null?void 0:R.status)??""),(_=i.subject)!=null&&_.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 T of i.quickReplies??[]){const X=c("button",void 0,T);X.addEventListener("click",()=>{this.h.onSend(T),this.quick.style.display="none"}),this.quick.append(X)}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=((E=i.i18n)==null?void 0:E.placeholder)??"Message…";const l=c("button","ocw-sendbtn");l.type="button";const m=(k=i.i18n)==null?void 0:k.send;m?(l.textContent=m,l.classList.add("ocw-sendbtn-label"),l.setAttribute("aria-label",m)):(l.innerHTML=_n,l.setAttribute("aria-label","Send message")),l.disabled=!0,this.sendBtn=l,l.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var T,X;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(Z=>Z.senderRole==="guest")?(X=(T=this.h).onDeflectQuery)==null||X.call(T,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",T=>{T.isComposing||T.keyCode===229||(T.key==="Enter"&&!T.shiftKey?(T.preventDefault(),this.flushSend()):this.signalTyping())});const P=c("button","ocw-attach","📎");P.title="Attach image or file";const U=document.createElement("input");U.type="file",U.accept="image/*,.pdf,.txt,.doc,.docx",U.style.display="none",P.addEventListener("click",()=>U.click()),U.addEventListener("change",()=>{var T;(T=U.files)!=null&&T[0]&&this.h.onAttach&&this.h.onAttach(U.files[0]),U.value=""});const M=c("div","ocw-input");M.append(P,U,this.input,l);const w=c("div","ocw-footer");((F=i.i18n)==null?void 0:F.poweredBy)!==void 0?w.textContent=i.i18n.poweredBy:w.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=w,this.reopenBtn=c("button","ocw-reopen",((V=this.cfg.i18n)==null?void 0:V.reopen)??"Reopen conversation"),this.reopenBtn.type="button",this.reopenBtn.addEventListener("click",()=>{this.reopenBtn.style.display="none";const T=this.root.querySelector(".ocw-input textarea");T==null||T.focus()}),e.append(r,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,M,this.reopenBtn,this.footer);const f=T=>{e.classList.toggle("ocw-compact",T>0&&T<Dn)};f(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(T=>{var Z;const X=((Z=T[0])==null?void 0:Z.contentRect.width)??e.clientWidth;f(X)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var n;(n=this.scrollCleanup)==null||n.call(this),this.scrollCleanup=e}destroy(){var e,n;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(n=this.compactObserver)==null||n.disconnect(),this.compactObserver=null}flushSend(){this.hideDeflection();const e=this.input.value.trim();e&&(this.input.value="",this.sendBtn.disabled=!0,this.autoGrowInput(),this.h.onTyping(!1),this.h.onSend(e))}autoGrowInput(){this.input.style.height="auto";const e=this.input.scrollHeight;e>0?this.input.style.height=`${Math.min(e,120)}px`:this.input.style.removeProperty("height")}signalTyping(){const e=this.input.value.trim().slice(0,100)||void 0;this.h.onTyping(!0,e),this.typingTimer&&clearTimeout(this.typingTimer),this.typingTimer=setTimeout(()=>this.h.onTyping(!1),2e3)}render(e){var P,U,M,w,f,I,C,x;if(this.storeRef=e,e.accent&&(this.root.style.setProperty("--ocw-accent",e.accent),this.root.style.setProperty("--ocw-accent2",this.cfgAccent2??e.accent)),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const b=(P=this.cfg.subject)==null?void 0:P.ownerLabel;b&&(this.headerName.textContent=b)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const n=e.visibleActions();this.chips.style.display=n.length?"flex":"none";for(const b of n)this.chips.append(this.chipEl(b));const o=this.scroll.scrollHeight,i=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const b=c("div","ocw-load-more");b.textContent="↑ Loading earlier messages…",b.style.pointerEvents="none",this.scroll.append(b)}let s=0,r=null;for(const b of e.messages()){const $=b.senderRole!=="system"&&b.senderId!==this.me&&!b.internal&&b.senderId!==r;this.scroll.append(this.messageEl(b,e,$)),b.senderRole!=="system"&&(r=b.senderId),b.senderId!==this.me&&b.seq>s&&(s=b.seq)}i>20?this.scroll.scrollTop=this.scroll.scrollHeight-o+i:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const u=[...e.typing];this.typing.classList.toggle("active",u.length>0);const d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",u.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const p=e.messages().some(b=>b.senderRole==="guest");if(!!((U=e.preChat)!=null&&U.enabled)&&!this.preChatDone&&!p&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(M=this.root.querySelector(".ocw-input"))==null||M.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 b=this.awayNotice.lastChild;b.textContent=e.offlineMessage||((w=this.cfg.i18n)==null?void 0:w.offline)||"We're away right now — send your message and we'll reply as soon as we're back.",this.awayNotice.style.display="flex"}else this.awayNotice.style.display="none";(f=this.root.querySelector(".ocw-input"))==null||f.style.removeProperty("display")}const l=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&l.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block");const m=l.includes(e.state);if(e.offline?(this.headStatus.textContent=`● ${e.offlineMessage||((I=this.cfg.i18n)==null?void 0:I.away)||"Away"}`,this.headStatus.className="ocw-head-status away",this.headStatus.style.display=""):e.conversationId?(this.headStatus.textContent=`● ${((C=this.cfg.i18n)==null?void 0:C.online)??"Online"}`,this.headStatus.className="ocw-head-status online",this.headStatus.style.display=""):this.headStatus.style.display="none",m&&e.messages().length>0){const b=c("div","ocw-resolved-note",`— ${((x=this.cfg.i18n)==null?void 0:x.resolved)??"Marked as resolved"} —`);this.scroll.append(b),this.reopenBtn.style.display="block"}else this.reopenBtn.style.display="none"}setConnStatus(e,n){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const o=e==="error";this.connStatus.className=`ocw-conn-status${o?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=o?`⚠ ${n??"Chat unavailable"}`:e==="reconnecting"?n??"↻ reconnecting…":"● connecting…"}buildPreChatPanel(e){var d;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(c("div","ocw-prechat-title",e.title??"Before we start…"));const n=c("div","ocw-offline-form"),o={};for(const p of e.fields??["name","email"]){const g=c("input","ocw-offline-input");g.type=p==="email"?"email":p==="phone"?"tel":"text",g.placeholder=p==="name"?"Your name":p==="email"?"Your email":"Your phone number",o[p]=g,n.append(g)}let i=null;if((d=e.topics)!=null&&d.length){i=c("select",void 0);const p=document.createElement("option");p.value="",p.textContent="What is this about?",i.append(p);for(const g of e.topics){const l=document.createElement("option");l.value=g,l.textContent=g,i.append(l)}n.append(i)}let s=null,r=null;if(e.callbackOption){const p=c("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",p.append(s,document.createTextNode("📞 Request a call back")),n.append(p),o.phone||(r=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 u=c("button","ocw-offline-submit","Start chat");u.type="button",u.addEventListener("click",()=>{var m,P,U,M,w,f,I;const p=(m=o.email)==null?void 0:m.value.trim();if(o.email&&(!p||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(p))){o.email.focus();return}const g=!!(s!=null&&s.checked),l=(((P=o.phone)==null?void 0:P.value)??(r==null?void 0:r.value)??"").trim();if(g&&!l){(U=o.phone??r)==null||U.focus();return}if(i&&((M=e.topics)!=null&&M.length)&&!i.value){i.focus();return}u.disabled=!0,this.completePreChat(),(I=(f=this.h).onPreChat)==null||I.call(f,{...(w=o.name)!=null&&w.value.trim()?{name:o.name.value.trim()}:{},...p?{email:p}:{},...l?{phone:l}:{},...i!=null&&i.value?{topic:i.value}:{},...g?{callback:!0}:{}})}),n.append(u),this.preChatPanel.append(n)}completePreChat(){this.preChatDone=!0,this.preChatPanel.style.display="none",this.storeRef&&this.render(this.storeRef)}showDeflection(e){if(!e.length)return this.hideDeflection();this.deflectPanel.replaceChildren(),this.deflectPanel.append(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[u,d]of Object.entries(n.fields))s.append(c("span","ocw-tag",`${u}: ${d}`));else for(const u of(o==null?void 0:o.tags)??[])s.append(c("span","ocw-tag",u));s.childNodes.length&&this.subjectCard.append(s);const r=(n==null?void 0:n.state)??(o==null?void 0:o.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const n=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"),u=c("button","ocw-modal-ok","Confirm"),d=p=>{o.remove(),n(p)};r.addEventListener("click",()=>d(!1)),u.addEventListener("click",()=>d(!0)),o.addEventListener("click",p=>{p.target===o&&d(!1)}),s.append(r,u),i.append(s),o.append(i),this.root.append(o),u.focus()})}openForm(e){var u,d;this.formHost.replaceChildren();const n=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 p of e.input??[]){const g=c("label","ocw-form-row");if(g.append(c("span","ocw-form-lbl",p.label)),p.type==="select"&&((u=p.options)!=null&&u.length)){const l=c("select","ocw-form-input");p.required||l.append(c("option",void 0,"— select —"));for(const m of p.options){const P=c("option");P.value=m,P.textContent=m,l.append(P)}p.required&&(l.required=!0),g.append(l),o.set(p.name,l)}else{const l=c("input","ocw-form-input");l.type=p.type==="number"?"number":p.type==="date"?"datetime-local":"text",p.required&&(l.required=!0),g.append(l),o.set(p.name,l)}n.append(g)}const i=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 p={};for(const[g,l]of o){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}p[g]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,p)}),i.append(s,r),n.append(i),this.formHost.append(n),(d=o.values().next().value)==null||d.focus()}messageEl(e,n,o=!1){var m,P,U,M;if(e.senderRole==="system"){const w=c("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":Xe(e.content),w}const i=e.senderId===this.me,s=!!e.internal,r=c("div",`ocw-row ${s?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`),u=c("div");if(o){const w=e.senderRole==="bot"?((m=this.cfg.i18n)==null?void 0:m.aiAssistant)??"AI Assistant":((P=this.cfg.subject)==null?void 0:P.ownerLabel)??((U=this.cfg.subject)==null?void 0:U.title)??"Support";u.append(c("div","ocw-msg-sender",w))}const d=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",u.append(w)}const p=c("div","ocw-bubble");let g=null;if(e.deletedAt)p.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((M=w.mime)!=null&&M.startsWith("image/")){const f=document.createElement("img");f.src=w.url,f.alt=w.name??"image",f.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",f.addEventListener("click",()=>window.open(w.url,"_blank")),p.append(f)}else{const f=document.createElement("a");f.href=w.url,f.target="_blank",f.rel="noopener",f.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",f.append(c("span",void 0,"📄"),c("span",void 0,w.name??"file")),p.append(f)}}else if(e.content.kind==="appointment"){const w=e.content,f=c("div","ocw-appt");f.append(c("div","ocw-appt-title",`📅 ${w.title}`)),f.append(c("div","ocw-appt-time",new Date(w.startIso).toLocaleString()+" – "+new Date(w.endIso).toLocaleTimeString())),w.location&&f.append(c("div","ocw-appt-loc",`📍 ${w.location}`)),w.description&&f.append(c("div","ocw-appt-desc",w.description));const I=c("div","ocw-appt-links"),C=document.createElement("a");C.href=w.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=w.icalUrl,x.download=`${w.title}.ics`,x.className="ocw-appt-btn ocw-appt-btn-sec",x.textContent="🍎 Apple / iCal",I.append(C,x),f.append(I),p.append(f)}else g=document.createTextNode(Xe(e.content)),p.append(g),e.editedAt&&p.append(c("span","ocw-edited","(edited)"));if(d.append(p),!i&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&g){const w=e.content.text;if(w.trim()){const f=c("button","ocw-translate-btn","🌐");f.type="button",f.title="Translate";const I=c("div","ocw-translation");I.style.display="none",p.append(I);const C=$=>{I.textContent=$,I.style.display="",this.showingTranslation.add(e.id),f.textContent="↩",f.title="Show original"},x=()=>{I.style.display="none",this.showingTranslation.delete(e.id),f.textContent="🌐",f.title="Translate"};f.addEventListener("click",$=>{if($.stopPropagation(),this.showingTranslation.has(e.id)){x();return}const R=this.translationCache.get(e.id);if(R!==void 0){C(R);return}f.textContent="⏳",this.h.onTranslate(w).then(_=>{if(_===null){f.textContent="⚠️",f.title="Translation unavailable",setTimeout(()=>{f.textContent="🌐",f.title="Translate"},1500);return}this.translationCache.set(e.id,_),C(_)})}),d.append(f);const b=this.translationCache.get(e.id);this.showingTranslation.has(e.id)&&b!==void 0&&C(b)}}if(i&&!e.deletedAt&&e.seq>0&&(this.h.onEdit??this.h.onDelete)){const w=c("div","ocw-msg-menu");if(this.h.onEdit){const f=c("button",void 0,"✏️");f.title="Edit",f.addEventListener("click",I=>{I.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 b=c("button","ocw-form-submit","Save");b.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const $=c("button","ocw-form-cancel","Cancel");$.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const R=c("div");R.style.cssText="display:flex;gap:6px;justify-content:flex-end",R.append($,b);const _=c("div");_.append(x,R),p.replaceChildren(_),x.focus(),x.select();const E=()=>p.replaceChildren(g??document.createTextNode(C));$.addEventListener("click",E),b.addEventListener("click",()=>{const k=x.value.trim();k&&k!==C&&this.h.onEdit(e.id,k),E()}),x.addEventListener("keydown",k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),b.click()),k.key==="Escape"&&E()})}),w.append(f)}if(this.h.onDelete){const f=c("button","del","🗑");f.title="Delete",f.addEventListener("click",I=>{I.stopPropagation(),this.h.onDelete(e.id)}),w.append(f)}d.append(w)}if(u.append(d),this.h.onReact&&!e.deletedAt&&e.seq>0){const w=c("div","ocw-react-wrap"),f=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[x,b]of Object.entries(e.reactions)){const $=c("button",`ocw-react-pill${b.includes(this.me)?" mine":""}`,`${x} ${b.length}`);$.addEventListener("click",()=>{var R,_;return(_=(R=this.h).onReact)==null?void 0:_.call(R,e.id,x,b.includes(this.me))}),f.append($)}const I=c("button","ocw-react-btn","+"),C=c("div","ocw-react-picker");for(const x of Rn){const b=c("button",void 0,x);b.addEventListener("click",$=>{var _,E,k,F;$.stopPropagation();const R=(E=(_=e.reactions)==null?void 0:_[x])==null?void 0:E.includes(this.me);(F=(k=this.h).onReact)==null||F.call(k,e.id,x,!!R),C.style.display="none"}),C.append(b)}C.style.display="none",I.addEventListener("click",x=>{x.stopPropagation();const b=C.style.display==="none";C.style.display=b?"flex":"none",b&&document.addEventListener("click",()=>{C.style.display="none"},{once:!0})}),f.append(I),w.append(f,C),u.append(w)}else e.reactions&&Object.keys(e.reactions).length&&u.append(c("div","ocw-react",Object.entries(e.reactions).map(([w,f])=>`${w}${f.length}`).join(" ")));const l=c("div","ocw-time ocw-meta",qn(e.ts));if(i&&e.status){const w=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,Hn(e.status));l.append(w)}return i&&e.seq>0&&n.lastReadByOthers>=e.seq&&l.append(c("span","ocw-seen"," · Seen")),u.append(l),r.append(u),r}}function Hn(t){switch(t){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Fn=20;function Ge(t,e){var d;const n=t.trim().replace(/\/+$/,""),o=(d=n.match(/^(https|http|wss|ws):\/\//))==null?void 0:d[1],i=o?o==="https"||o==="wss":!0,s=(o?n.slice(o.length+3):n).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${i?"https":"http"}://${s}`;return{wsUrl:`${i?"wss":"ws"}://${s}/ws`,httpBase:r}}function 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 u of Vn(t,e,o,i))try{const d=await fetch(u,{headers:{authorization:`Bearer ${n}`}});if(r=!0,!d.ok)continue;const p=await d.json();return{messages:p.messages??[],hasMore:p.hasMore??!1}}catch(d){s=d}return r?console.error(`[chat-widget] history request to ${t} was rejected for conversation ${e}.`):console.error(`[chat-widget] could not load history from ${t} — the request never reached the server. This is almost always CORS: add this site's origin to the chatroom's allowed origins (dashboard → chatroom → allowed origins) or to the server's CORS_ORIGINS.`,s),null}async function Xn(t,e,n,o,i,s){const r=s?s.replace(/\/+$/,""):Wn(t),u=await xt(r,n,e,Number.MAX_SAFE_INTEGER);if(!u||(u.messages.length?(o.apply({type:"sync",conversationId:n,messages:u.messages}),o.apply({type:"history",conversationId:n,messages:[],hasMore:u.hasMore}),i.render(o)):o.apply({type:"history",conversationId:n,messages:[],hasMore:!1}),!u.hasMore))return;let d=!1;const p=async()=>{if(d||!o.hasMoreHistory)return;d=!0;const P=o.messages()[0];if(!P){d=!1;return}const U=await xt(r,n,e,P.seq);U&&(o.apply({type:"history",conversationId:n,messages:U.messages,hasMore:U.hasMore}),i.render(o)),d=!1},g=i.getScrollEl();if(!g)return;let l=!1;setTimeout(()=>{l=!0},300);const m=()=>{l&&g.scrollTop<80&&o.hasMoreHistory&&!d&&p()};g.addEventListener("scroll",m,{passive:!0}),i.setScrollCleanup(()=>g.removeEventListener("scroll",m))}const me=new WeakMap,Ae=new Map;function mt(t){return`relay-launcher::${t.profileId}::${t.subjectId??""}`}let be=null;function Gn(){if(be&&be.state!=="closed")return be;try{return be=new AudioContext,be}catch{return null}}function bt(t){var ce,ue,Se,Ie,St,It,Ct,Et;me.has(t.el)&&(me.get(t.el).close(),me.delete(t.el)),t.launcher&&((ce=Ae.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:u}=Ge(t.url,t.apiUrl);let d=new wn(i);const p=t.subjectId?`${i}::${t.subjectId}`:i,g=new vn(p);let l,m=!1,P=null,U=null,M=null,w=null;!t.launcher&&!t.el.style.height&&t.el.clientHeight===0&&(t.el.style.width=t.el.style.width||"100%",t.el.style.height="600px");for(const h of g.load())d.addOptimistic(h.clientMsgId,h.content);let f=null,I=null,C=0,x=!t.launcher;if(t.launcher){const y=(t.position??"bottom-right").includes("right");f=document.createElement("div"),f.style.cssText=`position:fixed;${y?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${y?"flex-end":"flex-start"};gap:12px`;const S=document.createElement("div"),q=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,Ce=j=>{t.el.classList.toggle("ocw-fs",j),S.style.cssText=j?["position:fixed","inset:0","width:100%","height:100dvh","border-radius:0","overflow:hidden","box-shadow:none","display:none","flex-direction:column","background:#fff","transition:opacity .18s","opacity:0","z-index:9998"].join(";"):["width:min(380px, calc(100vw - 40px))","height:min(600px, calc(100dvh - 108px))","border-radius:28px","overflow:hidden","box-shadow:0 12px 32px rgba(108,92,231,.14)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(y?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};Ce((q==null?void 0:q.matches)??!1);const Ee=j=>Ce(j.matches);q==null||q.addEventListener("change",Ee),P=q,U=Ee,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>',G=document.createElement("button");G.type="button",G.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${t.accent??"#6c5ce7"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 12px 32px rgba(108,92,231,.14)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),G.onmouseenter=()=>{G.style.transform="scale(1.08)"},G.onmouseleave=()=>{G.style.transform="scale(1)"},I=document.createElement("span"),I.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=()=>{G.innerHTML=x?Re:$e,G.setAttribute("aria-label",x?"Close chat":"Open chat"),G.setAttribute("aria-expanded",String(x)),G.append(I)};De(),f.append(S,G),document.body.append(f);const Ze=`ocw-teaser-dismissed::${t.profileId}`,_e=typeof t.launcherMessage=="string"?{title:t.launcherMessage}:t.launcherMessage;let D=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 j=_e!=null&&_e.title?_e:d.launcherMessage??void 0;if(!(!!(j!=null&&j.title)&&!x&&!ai())){D&&(D.remove(),D=null);return}if(D)return;D=document.createElement("div"),D.setAttribute("role","button"),D.setAttribute("tabindex","0"),D.setAttribute("aria-label",j.title),D.style.cssText=["max-width:280px","background:#fff","border-radius:16px","box-shadow:0 12px 32px rgba(108,92,231,.14)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${y?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const et=document.createElement("div");if(et.textContent=j.title,et.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",D.append(et),j.subtitle){const ie=document.createElement("div");ie.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const tt=document.createElement("span");tt.innerHTML=ci,tt.style.cssText=`color:${t.accent??"#6c5ce7"};display:inline-flex`;const Pt=document.createElement("span");Pt.textContent=j.subtitle,ie.append(tt,Pt),D.append(ie)}const fe=document.createElement("button");fe.type="button",fe.setAttribute("aria-label","Dismiss"),fe.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>',fe.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",fe.addEventListener("click",ie=>{ie.stopPropagation();try{sessionStorage.setItem(Ze,"1")}catch{}D&&(D.remove(),D=null)}),D.append(fe);const Ut=()=>{x||(x=!0,Qe(!0),De(),C=0,I&&(I.style.display="none"),D&&(D.remove(),D=null))};D.addEventListener("click",Ut),D.addEventListener("keydown",ie=>{(ie.key==="Enter"||ie.key===" ")&&(ie.preventDefault(),Ut())}),f.insertBefore(D,G)};if(!document.getElementById("ocw-teaser-style")){const j=document.createElement("style");j.id="ocw-teaser-style",j.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(j)}w=Tt,Tt();const Qe=j=>{j?(S.style.display="flex",requestAnimationFrame(()=>{S.style.opacity="1",S.style.transform="scale(1)"})):(S.style.opacity="0",S.style.transform="scale(.95)",setTimeout(()=>{x||(S.style.display="none")},180))};G.addEventListener("click",()=>{if(x=!x,Qe(x),De(),x){C=0,I&&(I.style.display="none");try{sessionStorage.setItem(Ze,"1")}catch{}}w==null||w()}),M=j=>{j.key==="Escape"&&x&&(x=!1,Qe(!1),De())},document.addEventListener("keydown",M)}const b=()=>{x||(C++,I&&(I.textContent=String(C),I.style.display="flex"))},$=()=>{try{const h=Gn();if(!h)return;h.state==="suspended"&&h.resume().catch(()=>{});const y=h.createOscillator(),S=h.createGain();y.connect(S),S.connect(h.destination),y.frequency.setValueAtTime(880,h.currentTime),y.frequency.exponentialRampToValueAtTime(440,h.currentTime+.15),S.gain.setValueAtTime(.3,h.currentTime),S.gain.exponentialRampToValueAtTime(.001,h.currentTime+.3),y.start(),y.stop(h.currentTime+.3)}catch{}},R=[],_=h=>{for(;R.length;){const y=R.shift();g.add({clientMsgId:y.clientMsgId,content:y.content,ts:Date.now()}),E.send({type:"send",conversationId:h,clientMsgId:y.clientMsgId,content:y.content})}};let E;const k=new An(`ocw-e2e-${t.profileId}`);let F=!1;const V=[],T=[];let X=!1;const Z=(h,y)=>{k.sealText(y).then(S=>{l&&E.send({type:"send",conversationId:l,clientMsgId:h,content:S})})},Me=(h,y,S)=>{k.sealText(y,S).then(q=>{l&&E.send({type:"send",conversationId:l,clientMsgId:h,content:q})})},Ke=()=>{for(;V.length;){const h=V.shift();Z(h.clientMsgId,h.text)}for(;T.length;){const h=T.shift();Z(h.clientMsgId,h.text)}},v=h=>{E.send({type:"fetchPrekey",targetUserId:h})},K=t.i18n??{},O=["ar","he","fa","ur"],J=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";O.includes(J)&&!t.el.dir&&(t.el.dir="rtl",t.el.style.fontFamily=t.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const H=`oc_prechat_${t.profileId}_${i.slice(-8)}`,L=new On(t.el,i,{onSend(h){const y=`cm_${Math.random().toString(36).slice(2)}`,S={kind:"text",text:h};d.addOptimistic(y,S),L.render(d),d.e2e?k.ready?Z(y,h):X?T.push({clientMsgId:y,text:h}):(V.push({clientMsgId:y,text:h}),d.assignedAgentId&&v(d.assignedAgentId)):l?(g.add({clientMsgId:y,content:S,ts:Date.now()}),E.send({type:"send",conversationId:l,clientMsgId:y,content:S})):R.push({clientMsgId:y,content:S})},async onAttach(h){if(!l)return;const y=`${u}/upload?name=${encodeURIComponent(h.name)}`,S=`cm_${Math.random().toString(36).slice(2)}`;d.addOptimistic(S,{kind:"text",text:`📎 Uploading ${h.name}…`}),L.render(d);try{const q=await fetch(y,{method:"POST",headers:{"content-type":h.type,authorization:`Bearer ${i}`},body:h});if(!q.ok)throw new Error(`Upload failed: ${q.status}`);const{url:Ce,name:Ee,mime:$e,size:Re}=await q.json();d.addOptimistic(S,{kind:"attachment",url:Ce,name:Ee,mime:$e,size:Re}),L.render(d),E.send({type:"send",conversationId:l,clientMsgId:S,content:{kind:"attachment",url:Ce,name:Ee,mime:$e,size:Re}})}catch(q){d.addOptimistic(S,{kind:"text",text:`⚠️ Upload failed: ${q.message}`}),L.render(d)}},onInvoke(h,y){l&&E.send({type:"invoke",conversationId:l,actionId:h,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...y?{inputs:y}:{}})},onTyping(h,y){l&&E.send({type:"typing",conversationId:l,isTyping:h,...y?{preview:y}:{}})},onPreChat(h){try{localStorage.setItem(H,"1")}catch{}E.send({type:"open",profileId:t.profileId,...t.subjectId?{subjectId:t.subjectId}:{},userInfo:{...h.name?{name:h.name}:{},...h.email?{email:h.email}:{},...h.phone||h.topic?{meta:{...h.phone?{phone:h.phone}:{},...h.topic?{topic:h.topic}:{}}}:{}}});const y=h.callback?`📞 Call-back requested${h.phone?`: ${h.phone}`:""}${h.topic?` — ${h.topic}`:""}`:h.topic?`Topic: ${h.topic}`:"";y&&l&&!d.e2e&&E.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:y}})},...((ue=t.features)==null?void 0:ue.deflection)!==!1?{onDeflectQuery(h){if(o)return;clearTimeout(n);const y=h.trim();if(y.length<3){L.hideDeflection();return}n=setTimeout(()=>{fetch(`${u}/kb/search?profileId=${encodeURIComponent(t.profileId)}&q=${encodeURIComponent(y.slice(0,200))}`).then(S=>S.ok?S.json():{articles:[]}).then(S=>L.showDeflection(S.articles??[])).catch(()=>L.hideDeflection())},350)}}:{},onReadUpTo(h){l&&E.send({type:"read",conversationId:l,seq:h})},onLoadMore(){if(!l||!d.e2e)return;const h=d.messages()[0];h&&E.send({type:"history",conversationId:l,beforeSeq:h.seq,limit:20})},onEdit(h,y){l&&E.send({type:"edit",conversationId:l,messageId:h,content:{kind:"text",text:y}})},onDelete(h){l&&E.send({type:"delete",conversationId:l,messageId:h})},...((Se=t.features)==null?void 0:Se.reactions)!==!1?{onReact(h,y,S){l&&E.send({type:"react",conversationId:l,messageId:h,emoji:y,remove:S})}}:{},...((Ie=t.features)==null?void 0:Ie.csat)!==!1?{onCsat(h){l&&fetch(`${u}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({score:h})}).catch(()=>{})}}:{},...t.translateLang?{async onTranslate(h){try{const y=await fetch(`${u}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${i}`},body:JSON.stringify({text:h,targetLang:t.translateLang})});if(!y.ok)return null;const{translated:S}=await y.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:K});try{localStorage.getItem(H)&&L.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,he={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}:{}};E=new yn({...t.refreshToken?{refreshToken:t.refreshToken}:{},url:r,token:i,open:he,getCursor:()=>d.highestSeq(),onStatusChange:(h,y)=>L.setConnStatus(h,y),onFrame(h){if(h.type==="opened"){if(l=h.conversation.id,!m){m=!0;for(const y of g.load())E.send({type:"send",conversationId:l,clientMsgId:y.clientMsgId,content:y.content})}Xn(r,i,l,d,L,u),R.length&&_(l)}if(h.type==="ack"&&g.remove(h.clientMsgId),h.type==="prekeyBundle"){h.bundle&&(X=!0,k.x3dhSendTo(h.bundle).then(y=>{const S=[...V.splice(0),...T.splice(0)];for(const q of S)Me(q.clientMsgId,q.text,y);L.render(d)}));return}if(h.type==="message"&&d.e2e){const y=Ln(h.message.content);if(y&&!k.ready){k.x3dhReceiveFrom(y.x3dhIK,y.x3dhEK,y.x3dhSPK,y.x3dhOTP).then(async()=>{await k.openFrame(h),d.apply(h),L.render(d)});return}}if(h.type==="peerkey"){k.onPeerKey(h.key).then(()=>{Ke(),L.render(d)});return}(async()=>{if(d.e2e&&await k.openFrame(h),d.apply(h),h.type==="manifest"&&(w==null||w()),h.type==="message"&&h.message.senderId!==i&&!h.message.internal&&(b(),$()),d.e2e&&l&&!F){F=!0;const y=await k.initX3DH();E.send({type:"uploadPrekeys",...y});const S=await k.begin();E.send({type:"pubkey",conversationId:l,key:S})}L.render(d)})()}}),E.connect(),L.render(d);const ne=t.launcher?mt(t):null,pe={close:()=>{o=!0,clearTimeout(n),E.close(),f==null||f.remove(),L.destroy(),P&&U&&P.removeEventListener("change",U),M&&(document.removeEventListener("keydown",M),M=null),me.delete(t.el),ne&&Ae.get(ne)===pe&&Ae.delete(ne)}};return me.set(t.el,pe),ne&&Ae.set(ne,pe),pe}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,u=t.contextStatus??t.listingStatus??t.subjectStatus,d=t.listingPrice??t.subjectPrice,p=s?{title:s,...r?{subtitle:r}:{},...d!=null?{tags:[`$${d.toLocaleString()}`]}:{},...u?{status:u}:{}}:void 0,g=t.subject??p,l=t.userName??t.name,m=t.userEmail??t.email,P=t.userAvatar??t.avatar,U=l||m||P?{...l?{name:l}:{},...m?{email:m}:{},...P?{avatar:P}:{}}:void 0,M=t.user??U,w=t.launcherMessage&&typeof t.launcherMessage=="object"?t.launcherMessage:t.launcherMessage?t.launcherSubtitle?{title:t.launcherMessage,subtitle:t.launcherSubtitle}:t.launcherMessage:void 0;return{el:e,url:t.url??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}:{},...M?{user:M}:{},...t.quickReplies?{quickReplies:t.quickReplies}:{},...t.i18n?{i18n:t.i18n}:{},...t.features?{features:t.features}:{},...t.accent?{accent:t.accent}:{},...t.accent2?{accent2:t.accent2}:{},...t.theme?{theme:t.theme}:{},...t.webfont===!1?{webfont:!1}:{},...t.translateLang?{translateLang:t.translateLang}:{},...w?{launcherMessage:w}:{},...vt(t)&&!i?{onBack:()=>{ve=!0,ke=!1,Le(ae)}}:{},launcher:i,position:t.position??"bottom-right"}}let ee=null,N=null,re=!1,ae={},ve=!1,ke=!1;function vt(t){return!!(t.inbox||t.inboxStart)}let te=null;function Jn(t,e){const n=!e&&!!t.el;if(re&&!n&&(N.innerHTML="",N=null,re=!1),n){const o=typeof t.el=="string"?document.querySelector(t.el):t.el;o instanceof HTMLElement?(N&&N!==o&&!re&&N.remove(),N=o,re=!0):console.error(`[Relay] \`el\` ("${String(t.el)}") did not match any element — falling back to an auto-created host.`)}return(!N||!re&&!N.isConnected)&&(N=document.createElement("div"),N.id="relay-widget-root",document.body.appendChild(N),re=!1),!e&&t.height&&(N.style.height=t.height,N.style.width||(N.style.width="100%")),N}function Le(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&&ve){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=()=>{ve=!1,Le(ae)},o.append(i,s);const u=!ke&&!!n;u&&o.append(r),e.appendChild(o);let d=null,p=null;te=()=>{p==null||p.close(),d==null||d.close(),e.innerHTML=""};let g;try{({mountChatList:g}=await Promise.resolve().then(()=>ri))}catch(m){console.error("[Relay] could not load the conversation list module.",m),i.isConnected&&(i.style.cssText+=";display:flex;align-items:center;justify-content:center;padding:16px;font:13px system-ui;color:#b91c1c;text-align:center",i.textContent="Could not load conversations.");return}if(!i.isConnected)return;const l=m=>{const P=m.profileId??n;if(!P){console.error("[Relay] conversation row has no chatroom; cannot open it.",m);return}r.style.display="none",p==null||p.close(),p=bt({el:s,url:t.url??Ye,...t.apiUrl?{apiUrl:t.apiUrl}:{},profileId:P,...m.kind==="direct"&&m.peerId?{kind:"direct",peerId:m.peerId}:m.subjectId?{subjectId:m.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}:{}}}:{},...m.subjectTitle?{subject:{title:m.subjectTitle,...m.subjectMeta?{subtitle:m.subjectMeta}:{}}}:{},...t.accent?{accent:t.accent}:{},launcher:!1,onBack:()=>{p==null||p.close(),p=null,s.style.display="none",i.style.display="",r.style.display="",d==null||d.refresh()}}),i.style.display="none",s.style.display=""};d=g({el:i,url:t.url??Ye,...t.apiUrl?{apiUrl:t.apiUrl}:{},...n?{profileId:n}:{},...t.tenantId?{tenantId:t.tenantId}:{},scope:t.inboxScope??"tenant",...u?{reserveCloseSpace:!0}:{},onSelect:l,onNewChat:()=>{const m=n??(d==null?void 0:d.defaultProfileId());m&&l({id:"__new__",profileId:m,state:"open",updatedAt:Date.now()})},...t.token?{token:t.token}:{},...t.userId?{userId:t.userId}:{},...t.accent?{accent:t.accent}:{}})}function kt(t){ke=!!(t.inboxStart&&!(t.launcher??!0)),ve=ke,ae={...t},Le(ae)}function Qn(t){ae={...ae,...t},Le(ae)}function ei(){te==null||te(),te=null,ee==null||ee.close(),ee=null,N&&!re&&N.remove(),N=null,re=!1,ve=!1,ke=!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=`
|
|
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
196
|
@media (prefers-color-scheme: dark) { .ocl[data-theme="auto"] { ${Be("ocl")} } }
|
|
197
197
|
.ocl[data-theme="dark"] { ${Be("ocl")} }
|
|
198
198
|
.ocl-head { display:flex; align-items:center; padding:16px 16px 10px; background:var(--ocl-bg); }
|
|
199
|
-
.ocl-title { flex:1; display:flex; align-items:center; color:var(--ocl-
|
|
200
|
-
.ocl-title svg { width:24px; height:24px; display:block; }
|
|
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); }
|
|
201
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; }
|
|
202
201
|
.ocl-search-wrap { padding:4px 12px 8px; background:var(--ocl-bg); }
|
|
203
202
|
.ocl-search { width:100%; box-sizing:border-box; border:none; background:var(--ocl-tint); border-radius:20px; padding:9px 14px; font:inherit; font-size:14px; outline:none; }
|
|
@@ -238,5 +237,5 @@ var RelayEmbed=function(Q){"use strict";var di=Object.defineProperty;var hi=(Q,X
|
|
|
238
237
|
.ocl-compact .ocl-search { font-size:16px; }
|
|
239
238
|
.ocl-compact .ocl-compose { width:36px; height:36px; }
|
|
240
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; }
|
|
241
|
-
`;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`}}
|
|
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 A(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 v=document.createElement("style");v.id="ocl-styles",v.textContent=ni,document.head.append(v)}if(t.webfont!==!1&&typeof document<"u"&&!document.getElementById("ocw-webfont")){const v=document.createElement("link");v.id="ocw-webfont",v.rel="stylesheet",v.href="https://fonts.googleapis.com/css2?family=Baloo+2:wght@500;600;700&family=Nunito:wght@400;500;600;700&display=swap",document.head.append(v)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s),r.dataset.theme=t.theme??"light",t.reserveCloseSpace&&r.classList.add("ocl-has-close");const u=A("div","ocl-head"),d=i.title??"Your conversations",p=A("span","ocl-title",d);if(p.setAttribute("aria-label",d),u.append(p),t.onNewChat){const v=A("button","ocl-compose","✎");v.title=i.newChat??"New conversation",v.addEventListener("click",()=>t.onNewChat()),u.append(v)}const g=A("div","ocl-search-wrap"),l=A("input","ocl-search");l.placeholder=i.search??"🔍 Search",l.type="search",g.append(l);const m=A("div","ocl-body");m.append(A("div","ocl-spinner","Loading…")),r.append(u,g,m),t.el.replaceChildren(r);const P=v=>{r.classList.toggle("ocl-compact",v>0&&v<400)};P(r.clientWidth);let U=null;if(typeof ResizeObserver<"u"&&(U=new ResizeObserver(v=>{var K;return P(((K=v[0])==null?void 0:K.contentRect.width)??r.clientWidth)}),U.observe(r)),!t.profileId&&!t.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let M;const w=`ocl_seen_${t.profileId??`t_${t.tenantId}`}_${(t.userId??e).slice(-8)}`;let f={};try{f=JSON.parse(localStorage.getItem(w)??"{}")}catch{}const I=()=>{try{localStorage.setItem(w,JSON.stringify(f))}catch{}};let C=[],x=!1;const b=async()=>{const v=t.profileId?`profileId=${encodeURIComponent(t.profileId)}${t.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(t.tenantId)}`,K=`${n}/conversations/mine?${v}`,O={authorization:`Bearer ${e}`};let J;try{J=await fetch(K,{headers:O})}catch{J=await fetch(K,{headers:O})}if(!J.ok)return[];const H=await J.json();return H.defaultProfileId&&(M=H.defaultProfileId),(H.conversations??[]).sort((L,B)=>B.updatedAt-L.updatedAt)},$=(v,K)=>{if(x)return;const O=K?v.filter(B=>R(B).toLowerCase().includes(K)||(B.lastMessage??"").toLowerCase().includes(K)):v;if(m.replaceChildren(),!O.length){const B=A("div","ocl-empty",K?"No results.":i.empty??"No conversations yet.");if(!K&&t.onNewChat){B.append(A("br"));const he=A("button","ocl-start",i.newChat??"Start a conversation");he.addEventListener("click",()=>t.onNewChat()),B.append(he)}m.append(B);return}const J=B=>(B.lastSeq??0)>(f[B.id]??0),H=O.filter(J),L=O.filter(B=>!J(B));if(H.length){m.append(A("div","ocl-section",`${i.unread??"Unread"} (${H.length})`));for(const B of H)m.append(_(B,J(B)))}if(L.length){m.append(A("div","ocl-section",H.length?i.all??"All conversations":""));for(const B of L)m.append(_(B,!1))}},R=v=>v.subjectTitle??(v.kind==="direct"?v.peerId??"Direct message":"General enquiry"),_=(v,K)=>{var Se;const O=R(v),J=(((Se=O.match(new RegExp("\\p{L}","u")))==null?void 0:Se[0])??O.trim()[0]??"?").toUpperCase(),H=v.lastSeq??0,L=K?Math.max(1,H-(f[v.id]??0)):0,B=A("button",`ocl-row${K?" unread":""}`),he=A("div","ocl-av",J);B.append(he);const ne=A("div","ocl-info");ne.append(A("div","ocl-name",O));const pe={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};ne.append(A("div","ocl-preview",v.lastMessage??pe[v.state]??v.state)),B.append(ne);const ce=A("div","ocl-right");ce.append(A("div","ocl-time",oi(v.updatedAt)));const ue=ii(v.state);return ue&&ce.append(A("div",`ocl-status ${ue.cls}`,ue.label)),L>0&&ce.append(A("div","ocl-badge",String(L>99?"99+":L))),B.append(ce),B.addEventListener("click",()=>{var Ie;H>0&&(f[v.id]=H,I()),B.classList.remove("unread"),(Ie=ce.querySelector(".ocl-badge"))==null||Ie.remove(),t.onSelect(v)}),B},E=()=>{x||b().then(v=>{x||(C=v,$(v,l.value.trim().toLowerCase()))}).catch(v=>{if(x)return;console.error(`[chat-widget] failed to load conversations from ${n}/conversations/mine — check the apiUrl/CORS config.`,v);const K=A("div","ocl-empty",i.error??"Could not load conversations.");K.append(A("br"));const O=A("button","ocl-retry",i.retry??"Retry");O.addEventListener("click",()=>{m.replaceChildren(A("div","ocl-spinner","Loading…")),E()}),K.append(O),m.replaceChildren(K)})};l.addEventListener("input",()=>$(C,l.value.trim().toLowerCase())),E();let k=null,F,V,T=0,X=!1;const Z=()=>{V||(V=setTimeout(()=>{V=void 0,E()},300))},Me=()=>{if(!x){try{k=new WebSocket(o)}catch{Ke();return}k.binaryType="arraybuffer",k.onopen=()=>{T=0,k.send(We({type:"auth",token:e})),k.send(We({type:"subscribe_inbox"})),X&&Z(),X=!0},k.onmessage=v=>{const K=ct(new Uint8Array(v.data));K&&K.type==="inbox_event"&&Z()},k.onclose=()=>{k=null,Ke()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Ke=()=>{if(x||F)return;const v=Math.min(15e3,500*2**T++)+Math.random()*250;F=setTimeout(()=>{F=void 0,Me()},v)};return Me(),{refresh:E,close(){x=!0,F&&clearTimeout(F),V&&clearTimeout(V),U==null||U.disconnect(),U=null;try{k==null||k.close()}catch{}k=null,t.el.replaceChildren()},defaultProfileId(){return t.profileId??M}}}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}({});
|
|
242
241
|
//# sourceMappingURL=embed.js.map
|