@paramms/chat-widget 1.0.40 → 1.0.41
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/README.md +139 -12
- package/dist/embed.d.ts +110 -10
- package/dist/embed.js +44 -10
- package/dist/embed.js.map +1 -1
- package/dist/index.js +314 -323
- package/dist/index.js.map +1 -1
- package/dist/outbox.js +5 -5
- package/dist/outbox.js.map +1 -1
- package/dist/renderer.d.ts +1 -2
- package/package.json +1 -1
package/dist/embed.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var RelayEmbed=function(q){"use strict";var On=Object.defineProperty;var Nn=(q,R,X)=>R in q?On(q,R,{enumerable:!0,configurable:!0,writable:!0,value:X}):q[R]=X;var a=(q,R,X)=>Nn(q,typeof R!="symbol"?R+"":R,X);const R="oc_uid";function X(n){try{const e=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function at(n,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function ct(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function lt(){let n=null;try{n=localStorage.getItem(R)}catch{}n||(n=X(R));const e=n??ct();try{localStorage.setItem(R,e)}catch{}return at(R,e),e}function dt(n){const e=n.length;let t=0,i=0;for(;i<e;){let s=n.charCodeAt(i++);if(s&4294967168)if(!(s&4294965248))t+=2;else{if(s>=55296&&s<=56319&&i<e){const o=n.charCodeAt(i);(o&64512)===56320&&(++i,s=((s&1023)<<10)+(o&1023)+65536)}s&4294901760?t+=4:t+=3}else{t++;continue}}return t}function ht(n,e,t){const i=n.length;let s=t,o=0;for(;o<i;){let r=n.charCodeAt(o++);if(r&4294967168)if(!(r&4294965248))e[s++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&o<i){const d=n.charCodeAt(o);(d&64512)===56320&&(++o,r=((r&1023)<<10)+(d&1023)+65536)}r&4294901760?(e[s++]=r>>18&7|240,e[s++]=r>>12&63|128,e[s++]=r>>6&63|128):(e[s++]=r>>12&15|224,e[s++]=r>>6&63|128)}else{e[s++]=r;continue}e[s++]=r&63|128}}const pt=new TextEncoder,ut=50;function ft(n,e,t){pt.encodeInto(n,e.subarray(t))}function wt(n,e,t){n.length>ut?ft(n,e,t):ht(n,e,t)}const gt=4096;function Ke(n,e,t){let i=e;const s=i+t,o=[];let r="";for(;i<s;){const d=n[i++];if(!(d&128))o.push(d);else if((d&224)===192){const h=n[i++]&63;o.push((d&31)<<6|h)}else if((d&240)===224){const h=n[i++]&63,u=n[i++]&63;o.push((d&31)<<12|h<<6|u)}else if((d&248)===240){const h=n[i++]&63,u=n[i++]&63,x=n[i++]&63;let p=(d&7)<<18|h<<12|u<<6|x;p>65535&&(p-=65536,o.push(p>>>10&1023|55296),p=56320|p&1023),o.push(p)}else o.push(d);o.length>=gt&&(r+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(r+=String.fromCharCode(...o)),r}const yt=new TextDecoder,xt=200;function bt(n,e,t){const i=n.subarray(e,e+t);return yt.decode(i)}function mt(n,e,t){return t>xt?bt(n,e,t):Ke(n,e,t)}class oe{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class D extends Error{constructor(e){super(e);const t=Object.create(D.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:D.name})}}const Z=4294967295;function vt(n,e,t){const i=t/4294967296,s=t;n.setUint32(e,i),n.setUint32(e+4,s)}function Le(n,e,t){const i=Math.floor(t/4294967296),s=t;n.setUint32(e,i),n.setUint32(e+4,s)}function Me(n,e){const t=n.getInt32(e),i=n.getUint32(e+4);return t*4294967296+i}function kt(n,e){const t=n.getUint32(e),i=n.getUint32(e+4);return t*4294967296+i}const St=-1,Ct=4294967296-1,It=17179869184-1;function Et({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=It)if(e===0&&n<=Ct){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{const t=n/4294967296,i=n&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|t&3),o.setUint32(4,i),s}else{const t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),Le(i,4,n),t}}function Tt(n){const e=n.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,s=Math.floor(i/1e9);return{sec:t+s,nsec:i-s*1e9}}function Pt(n){if(n instanceof Date){const e=Tt(n);return Et(e)}else return null}function Ut(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),i=e.getUint32(4),s=(t&3)*4294967296+i,o=t>>>2;return{sec:s,nsec:o}}case 12:{const t=Me(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new D(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function At(n){const e=Ut(n);return new Date(e.sec*1e3+e.nsec/1e6)}const Bt={type:St,encode:Pt,decode:At},le=class le{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(Bt)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(s!=null){const o=s(e,t);if(o!=null){const r=-1-i;return new oe(r,o)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(s!=null){const o=s(e,t);if(o!=null){const r=i;return new oe(r,o)}}}return e instanceof oe?e:null}decode(e,t,i){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,i):new oe(t,e)}};a(le,"defaultCodec",new le);let re=le;function Kt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function ge(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Kt(n)?new Uint8Array(n):Uint8Array.from(n)}const Lt=100,Mt=2048;class ye{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)??re.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)??Lt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Mt,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 ye({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,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);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,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),s=new DataView(t);i.set(this.bytes),this.view=s,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=dt(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),wt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const i=ge(e);this.writeU8a(i)}encodeArray(e,t){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let i=0;for(const s of t)e[s]!==void 0&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const o of i){const r=e[o];this.ignoreUndefined&&r===void 0||(this.encodeString(o),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),s=i.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(i);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}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),vt(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Le(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 zt(n,e){return new ye(e).encodeSharedRef(n)}function xe(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}const Dt=16,$t=16;class Rt{constructor(e=Dt,t=$t){a(this,"hit",0);a(this,"miss",0);a(this,"caches");a(this,"maxKeyLength");a(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const s=this.caches[i-1];e:for(const o of s){const r=o.bytes;for(let d=0;d<i;d++)if(r[d]!==e[t+d])continue e;return o.str}return null}store(e,t){const i=this.caches[e.length-1],s={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,t,i){const s=this.find(e,t,i);if(s!=null)return this.hit++,s;this.miss++;const o=Ke(e,t,i),r=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(r,o),o}}const be="array",Q="map_key",ze="map_value",_t=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new D("The type of key must be string or number but "+typeof n)};class Ht{constructor(){a(this,"stack",[]);a(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=be,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Q,t.readCount=0,t.size=e,t.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===be){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===Q||e.type===ze){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const ee=-1,me=new DataView(new ArrayBuffer(0)),jt=new Uint8Array(me.buffer);try{me.getInt8(0)}catch(n){if(!(n 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 De=new RangeError("Insufficient data"),Ft=new Rt;class ve{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",me);a(this,"bytes",jt);a(this,"headByte",ee);a(this,"stack",new Ht);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??re.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)??Z,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Z,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Z,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Z,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Z,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Ft,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??_t}clone(){return new ve({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=ee,this.stack.reset()}setBuffer(e){const t=ge(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ee&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),i=ge(e),s=new Uint8Array(t.length+i.length);s.set(t),s.set(i,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.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 t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}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 t=!1,i;for await(const d of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(d);try{i=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:s,pos:o,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${xe(s)} at ${r} (${o} 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,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let i=t,s=-1;for await(const o of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==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 t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new D(`Unrecognized type byte: ${xe(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const s=i.top();if(s.type===be)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,i.release(s);else continue e;else if(s.type===Q){if(t==="__proto__")throw new D("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=ze;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,i.release(s);else{s.key=null,s.type=Q;continue e}}return t}}readHeadByte(){return this.headByte===ee&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ee}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 D(`Unrecognized array type byte: ${xe(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new D(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new D(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var o;if(e>this.maxStrLength)throw new D(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw De;const i=this.pos+t;let s;return this.stateIsMapKey()&&((o=this.keyDecoder)!=null&&o.canBeCached(e))?s=this.keyDecoder.decode(this.bytes,i,e):s=mt(this.bytes,i,e),this.pos+=t+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Q:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new D(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw De;const i=this.pos+t,s=this.bytes.subarray(i,i+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new D(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=kt(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Me(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 qt(n,e){return new ve(e).decode(n)}const Ot=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","annotate","annotate_clear","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function Nt(n){return Ot.has(n.type)}function Wt(n){return zt(n)}function Vt(n){let e;try{e=qt(n)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class Xt{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,"annotations",[]);a(this,"annotationVersion",0);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,t)=>{const i=e.status==="pending",s=t.status==="pending";return i!==s?i?1:-1:i&&s?e.ts-t.ts:e.seq-t.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,t){const i={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:t,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,i),this.keyByClient.set(e,e),this._sorted=null,i}apply(e){var t;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject),e.annotations&&(this.annotations=e.annotations,this.annotationVersion++);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(t=e.theme)!=null&&t.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),e.offline&&(this.offline=!0),e.offlineMessage&&(this.offlineMessage=e.offlineMessage),e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const i=this.keyByClient.get(e.clientMsgId),s=i?this.byId.get(i):void 0;if(s&&i){this.byId.delete(i);const o={...s,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,o),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const i of e.messages)this.upsert({...i});return;case"history":for(const i of e.messages)this.upsert({...i});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const i=this.byId.get(e.messageId);if(!i)return;const s={...i.reactions??{}},o=(s[e.emoji]??[]).filter(r=>r!==e.by);e.removed||o.push(e.by),o.length?s[e.emoji]=o:delete s[e.emoji],this.byId.set(e.messageId,{...i,reactions:s}),this._sorted=null;return}case"edited":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"annotation":this.annotations=[...this.annotations,e.stroke],this.annotationVersion++;return;case"annotation_clear":this.annotations=[],this.annotationVersion++;return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const t=this.byId.get(e.id);this.byId.set(e.id,t?{...t,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,t){const i=$e(t);let s=!1;for(const[o,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||$e(r.status)>=i||(this.byId.set(o,{...r,status:t}),s=!0);s&&(this._sorted=null)}}function $e(n){switch(n){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const Re="http://www.w3.org/2000/svg",Yt=8e3;class Gt{constructor(){a(this,"svg",null);a(this,"timers",new Set)}apply(e){var t;if(e.type==="annotation")this.draw(e.stroke);else if(e.type==="annotation_clear")this.clear();else if(e.type==="opened"&&((t=e.annotations)!=null&&t.length))for(const i of e.annotations)this.draw(i)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(Re,"svg");return e.setAttribute("data-relay-annotations",""),e.setAttribute("aria-hidden","true"),e.setAttribute("style","position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000;"),document.body.append(e),this.svg=e,e}draw(e){var d;if(typeof document>"u"||!((d=e.points)!=null&&d.length))return;const t=this.ensureSvg(),i=window.innerWidth,s=window.innerHeight,o=document.createElementNS(Re,"polyline");o.setAttribute("points",e.points.map(h=>`${(h.x*i).toFixed(1)},${(h.y*s).toFixed(1)}`).join(" ")),o.setAttribute("fill","none"),o.setAttribute("stroke",e.color||"#ff3b30"),o.setAttribute("stroke-width",String(e.width||3)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("data-stroke-id",e.id),t.append(o);const r=setTimeout(()=>{o.style.transition="opacity 600ms",o.style.opacity="0";const h=setTimeout(()=>{o.remove(),this.timers.delete(h)},650);this.timers.add(h),this.timers.delete(r)},Yt);this.timers.add(r)}clear(){var e;(e=this.svg)==null||e.replaceChildren()}destroy(){var e;for(const t of this.timers)clearTimeout(t);this.timers.clear(),(e=this.svg)==null||e.remove(),this.svg=null}}class Jt{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 i,s;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(s=(i=this.opts).onStatusChange)==null||s.call(i,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??en)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=o=>{const r=Vt(new Uint8Array(o.data));!r||Nt(r)||this.handle(r)},t.onclose=()=>this.onClosed(),t.onerror=()=>{try{t.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}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 t,i,s,o;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(i=(t=this.opts).onStatusChange)==null||i.call(t,"open"),this.raw(this.opts.open),this.flush()),e.type==="opened"&&this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),e.type==="error"&&Zt.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var d;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(d=this.socket)==null||d.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,i,s;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(s=(i=this.opts).onStatusChange)==null||s.call(i,"error",Qt(e.code)),this.opts.onFrame(e)}flush(){const e=this.outbox;this.outbox=[];for(const t of e)this.raw(t)}raw(e){var t;try{(t=this.socket)==null||t.send(Wt(e))}catch{this.outbox.push(e)}}onClosed(){var s,o;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,i=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((o=(s=this.opts).onStatusChange)==null||o.call(s,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),i)}}const Zt=new Set(["UNAUTHORIZED"]);function Qt(n){switch(n){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function en(n){return new WebSocket(n)}const _e=200,tn=7*864e5;class nn{constructor(e){a(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const t=JSON.parse(e),i=Date.now()-tn,s=t.filter(o=>o.ts>=i);return s.length!==t.length&&this.save(s),s}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>_e?t.slice(t.length-_e):t)}catch{}}remove(e){try{const t=this.load().filter(i=>i.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const T=()=>globalThis.crypto.subtle;function ae(n){const e=n instanceof Uint8Array?n:new Uint8Array(n);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}function ke(n){const e=atob(n),t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return i}async function te(){const n=await T().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:n.publicKey,privateKey:n.privateKey}}async function N(n){return ae(await T().exportKey("raw",n))}async function Y(n){return T().importKey("raw",ke(n),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function sn(n,e){const t=await Y(e);return T().deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function on(n,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),s=await T().encrypt({name:"AES-GCM",iv:t},n,i);return{ct:ae(s),iv:ae(t)}}async function rn(n,e,t){const i=await T().decrypt({name:"AES-GCM",iv:ke(t)},n,ke(e));return new TextDecoder().decode(i)}async function an(n){var t,i;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(n);if(s){const{pub:o,priv:r}=JSON.parse(s),d=await T().importKey("jwk",o,{name:"ECDH",namedCurve:"P-256"},!0,[]),h=await T().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:d,privateKey:h}}}catch{}const e=await te();try{const s=await T().exportKey("jwk",e.publicKey),o=await T().exportKey("jwk",e.privateKey);(i=globalThis.localStorage)==null||i.setItem(n,JSON.stringify({pub:s,priv:o}))}catch{}return e}async function cn(n,e){const t=await T().exportKey("raw",e),i=await T().sign({name:"ECDSA",hash:"SHA-256"},n,t);return ae(i)}async function ln(){const n=await te(),e=await T().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:n,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await N(n.publicKey),sigPublicKeyB64:await N(e.publicKey)}}async function He(n){var t,i;try{const s=(t=globalThis.localStorage)==null?void 0:t.getItem(`${n}-identity`);if(s){const o=JSON.parse(s),r=await T().importKey("jwk",o.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),d=await T().importKey("jwk",o.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),h=await T().importKey("jwk",o.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),u=await T().importKey("jwk",o.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:d},ecdsaKP:{publicKey:h,privateKey:u},publicKeyB64:await N(r),sigPublicKeyB64:await N(h)}}}catch{}const e=await ln();try{const s=await T().exportKey("jwk",e.ecdhKP.publicKey),o=await T().exportKey("jwk",e.ecdhKP.privateKey),r=await T().exportKey("jwk",e.ecdsaKP.publicKey),d=await T().exportKey("jwk",e.ecdsaKP.privateKey);(i=globalThis.localStorage)==null||i.setItem(`${n}-identity`,JSON.stringify({ecdhPub:s,ecdhPriv:o,ecdsaPub:r,ecdsaPriv:d}))}catch{}return e}async function dn(n,e){const t=await te(),i=await N(t.publicKey),s=await Y(e.identityKey),o=await Y(e.signedPrekey),r=e.oneTimePrekey?await Y(e.oneTimePrekey):null,d=await W(n.privateKey,o),h=await W(t.privateKey,s),u=await W(t.privateKey,o),x=r?await W(t.privateKey,r):null,p=je(d,h,u,...x?[x]:[]);return{sharedKey:await Fe(p),ephemeralPublicKey:i}}async function hn(n,e,t,i,s){const o=await Y(t),r=await Y(i),d=await W(e.privateKey,o),h=await W(n.privateKey,r),u=await W(e.privateKey,r),x=s?await W(s.privateKey,r):null,p=je(d,h,u,...x?[x]:[]);return Fe(p)}async function W(n,e){return T().deriveBits({name:"ECDH",public:e},n,256)}function je(...n){const e=n.reduce((s,o)=>s+o.byteLength,0),t=new Uint8Array(e);let i=0;for(const s of n)t.set(new Uint8Array(s),i),i+=s.byteLength;return t.buffer}async function Fe(n){const e=await T().importKey("raw",n,"HKDF",!1,["deriveKey"]);return T().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 pn=20;class un{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 an(this.storageKey),N(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await sn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await He(this.storageKey),this.signedPreKP=await te(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let s=0;s<pn;s++)this.otpKeys.push(await te());const e=await N(this.signedPreKP.publicKey),t=await cn(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),i=await Promise.all(this.otpKeys.map(s=>N(s.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:i}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await He(this.storageKey));const{sharedKey:t,ephemeralPublicKey:i}=await dn(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:i,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,i){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:i};return}const s=this.otpKeys.shift();this.x3dhShared=await hn(this.identityKP.ecdhKP,this.signedPreKP,e,t,s)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:i}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,i)}async sealText(e,t){const i=this.x3dhShared??this.shared;if(!i)throw new Error("secure channel not ready");const{ct:s,iv:o}=await on(i,e);return{kind:"text",text:s,enc:!0,iv:o,...t?{x3dhEK:t.ephemeralKey,x3dhSPK:t.spkId,x3dhIK:t.senderIK}:{}}}async openContent(e){if(e.kind!=="text"||!e.enc||!e.iv)return e;const t=this.x3dhShared??this.shared;if(!t)return{kind:"text",text:"🔒 encrypted"};try{return{kind:"text",text:await rn(t,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 t of e.messages)t.content=await this.openContent(t.content)}}function fn(n){if(n.kind!=="text"||!n.enc)return null;const e=n;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const qe="objectchat-widget-styles",wn=["👍","❤️","😂","😮","😢","🙏"],gn=400,yn='<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>',xn=`
|
|
1
|
+
var RelayEmbed=function(J){"use strict";var ei=Object.defineProperty;var ti=(J,X,ce)=>X in J?ei(J,X,{enumerable:!0,configurable:!0,writable:!0,value:ce}):J[X]=ce;var a=(J,X,ce)=>ti(J,typeof X!="symbol"?X+"":X,ce);const X="oc_uid";function ce(n){try{const e=document.cookie.match(new RegExp(`(?:^|; )${n}=([^;]*)`));return e?decodeURIComponent(e[1]):null}catch{return null}}function St(n,e){try{const i=location.protocol==="https:"?"; Secure":"";document.cookie=`${n}=${encodeURIComponent(e)}; Max-Age=31536000; Path=/; SameSite=Lax${i}`}catch{}}function Ct(){return`g_${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`}function Qe(){let n=null;try{n=localStorage.getItem(X)}catch{}n||(n=ce(X));const e=n??Ct();try{localStorage.setItem(X,e)}catch{}return St(X,e),e}function It(n){const e=n.length;let t=0,i=0;for(;i<e;){let o=n.charCodeAt(i++);if(o&4294967168)if(!(o&4294965248))t+=2;else{if(o>=55296&&o<=56319&&i<e){const s=n.charCodeAt(i);(s&64512)===56320&&(++i,o=((o&1023)<<10)+(s&1023)+65536)}o&4294901760?t+=4:t+=3}else{t++;continue}}return t}function Et(n,e,t){const i=n.length;let o=t,s=0;for(;s<i;){let r=n.charCodeAt(s++);if(r&4294967168)if(!(r&4294965248))e[o++]=r>>6&31|192;else{if(r>=55296&&r<=56319&&s<i){const h=n.charCodeAt(s);(h&64512)===56320&&(++s,r=((r&1023)<<10)+(h&1023)+65536)}r&4294901760?(e[o++]=r>>18&7|240,e[o++]=r>>12&63|128,e[o++]=r>>6&63|128):(e[o++]=r>>12&15|224,e[o++]=r>>6&63|128)}else{e[o++]=r;continue}e[o++]=r&63|128}}const Tt=new TextEncoder,Ut=50;function At(n,e,t){Tt.encodeInto(n,e.subarray(t))}function Pt(n,e,t){n.length>Ut?At(n,e,t):Et(n,e,t)}const Bt=4096;function et(n,e,t){let i=e;const o=i+t,s=[];let r="";for(;i<o;){const h=n[i++];if(!(h&128))s.push(h);else if((h&224)===192){const d=n[i++]&63;s.push((h&31)<<6|d)}else if((h&240)===224){const d=n[i++]&63,f=n[i++]&63;s.push((h&31)<<12|d<<6|f)}else if((h&248)===240){const d=n[i++]&63,f=n[i++]&63,y=n[i++]&63;let l=(h&7)<<18|d<<12|f<<6|y;l>65535&&(l-=65536,s.push(l>>>10&1023|55296),l=56320|l&1023),s.push(l)}else s.push(h);s.length>=Bt&&(r+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(r+=String.fromCharCode(...s)),r}const Lt=new TextDecoder,Mt=200;function zt(n,e,t){const i=n.subarray(e,e+t);return Lt.decode(i)}function Kt(n,e,t){return t>Mt?zt(n,e,t):et(n,e,t)}class Ce{constructor(e,t){a(this,"type");a(this,"data");this.type=e,this.data=t}}class O extends Error{constructor(e){super(e);const t=Object.create(O.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:O.name})}}const ue=4294967295;function $t(n,e,t){const i=t/4294967296,o=t;n.setUint32(e,i),n.setUint32(e+4,o)}function tt(n,e,t){const i=Math.floor(t/4294967296),o=t;n.setUint32(e,i),n.setUint32(e+4,o)}function nt(n,e){const t=n.getInt32(e),i=n.getUint32(e+4);return t*4294967296+i}function Dt(n,e){const t=n.getUint32(e),i=n.getUint32(e+4);return t*4294967296+i}const Rt=-1,_t=4294967296-1,jt=17179869184-1;function Ht({sec:n,nsec:e}){if(n>=0&&e>=0&&n<=jt)if(e===0&&n<=_t){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,n),t}else{const t=n/4294967296,i=n&4294967295,o=new Uint8Array(8),s=new DataView(o.buffer);return s.setUint32(0,e<<2|t&3),s.setUint32(4,i),o}else{const t=new Uint8Array(12),i=new DataView(t.buffer);return i.setUint32(0,e),tt(i,4,n),t}}function Nt(n){const e=n.getTime(),t=Math.floor(e/1e3),i=(e-t*1e3)*1e6,o=Math.floor(i/1e9);return{sec:t+o,nsec:i-o*1e9}}function qt(n){if(n instanceof Date){const e=Nt(n);return Ht(e)}else return null}function Ft(n){const e=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),i=e.getUint32(4),o=(t&3)*4294967296+i,s=t>>>2;return{sec:o,nsec:s}}case 12:{const t=nt(e,4),i=e.getUint32(0);return{sec:t,nsec:i}}default:throw new O(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${n.length}`)}}function Ot(n){const e=Ft(n);return new Date(e.sec*1e3+e.nsec/1e6)}const Wt={type:Rt,encode:qt,decode:Ot},Ae=class Ae{constructor(){a(this,"__brand");a(this,"builtInEncoders",[]);a(this,"builtInDecoders",[]);a(this,"encoders",[]);a(this,"decoders",[]);this.register(Wt)}register({type:e,encode:t,decode:i}){if(e>=0)this.encoders[e]=t,this.decoders[e]=i;else{const o=-1-e;this.builtInEncoders[o]=t,this.builtInDecoders[o]=i}}tryToEncode(e,t){for(let i=0;i<this.builtInEncoders.length;i++){const o=this.builtInEncoders[i];if(o!=null){const s=o(e,t);if(s!=null){const r=-1-i;return new Ce(r,s)}}}for(let i=0;i<this.encoders.length;i++){const o=this.encoders[i];if(o!=null){const s=o(e,t);if(s!=null){const r=i;return new Ce(r,s)}}}return e instanceof Ce?e:null}decode(e,t,i){const o=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return o?o(e,t,i):new Ce(t,e)}};a(Ae,"defaultCodec",new Ae);let Ie=Ae;function Vt(n){return n instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&n instanceof SharedArrayBuffer}function Ke(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):Vt(n)?new Uint8Array(n):Uint8Array.from(n)}const Xt=100,Gt=2048;class $e{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)??Ie.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)??Xt,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Gt,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 $e({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,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);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,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),i=new Uint8Array(t),o=new DataView(t);i.set(this.bytes),this.view=o,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=It(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Pt(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,t){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const i=Ke(e);this.writeU8a(i)}encodeArray(e,t){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const o of e)this.doEncode(o,t+1)}countWithoutUndefined(e,t){let i=0;for(const o of t)e[o]!==void 0&&i++;return i}encodeMap(e,t){const i=Object.keys(e);this.sortKeys&&i.sort();const o=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error(`Too large map object: ${o}`);for(const s of i){const r=e[s];this.ignoreUndefined&&r===void 0||(this.encodeString(s),this.doEncode(r,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),o=i.length;if(o>=4294967296)throw new Error(`Too large extension object: ${o}`);this.writeU8(201),this.writeU32(o),this.writeI8(e.type),this.writeU8a(i);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}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),$t(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),tt(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 Yt(n,e){return new $e(e).encodeSharedRef(n)}function De(n){return`${n<0?"-":""}0x${Math.abs(n).toString(16).padStart(2,"0")}`}const Jt=16,Zt=16;class Qt{constructor(e=Jt,t=Zt){a(this,"hit",0);a(this,"miss",0);a(this,"caches");a(this,"maxKeyLength");a(this,"maxLengthPerKey");this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,i){const o=this.caches[i-1];e:for(const s of o){const r=s.bytes;for(let h=0;h<i;h++)if(r[h]!==e[t+h])continue e;return s.str}return null}store(e,t){const i=this.caches[e.length-1],o={bytes:e,str:t};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=o:i.push(o)}decode(e,t,i){const o=this.find(e,t,i);if(o!=null)return this.hit++,o;this.miss++;const s=et(e,t,i),r=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(r,s),s}}const Re="array",fe="map_key",it="map_value",en=n=>{if(typeof n=="string"||typeof n=="number")return n;throw new O("The type of key must be string or number but "+typeof n)};class tn{constructor(){a(this,"stack",[]);a(this,"stackHeadPosition",-1)}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=Re,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=fe,t.readCount=0,t.size=e,t.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===Re){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===fe||e.type===it){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const we=-1,_e=new DataView(new ArrayBuffer(0)),nn=new Uint8Array(_e.buffer);try{_e.getInt8(0)}catch(n){if(!(n 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 ot=new RangeError("Insufficient data"),on=new Qt;class je{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",_e);a(this,"bytes",nn);a(this,"headByte",we);a(this,"stack",new tn);a(this,"entered",!1);this.extensionCodec=(e==null?void 0:e.extensionCodec)??Ie.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)??ue,this.maxBinLength=(e==null?void 0:e.maxBinLength)??ue,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??ue,this.maxMapLength=(e==null?void 0:e.maxMapLength)??ue,this.maxExtLength=(e==null?void 0:e.maxExtLength)??ue,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:on,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??en}clone(){return new je({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=we,this.stack.reset()}setBuffer(e){const t=Ke(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===we&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),i=Ke(e),o=new Uint8Array(t.length+i.length);o.set(t),o.set(i,t.length),this.setBuffer(o)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:i}=this;return new RangeError(`Extra ${t.byteLength-i} of ${t.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 t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}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 t=!1,i;for await(const h of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(h);try{i=this.doDecodeSync(),t=!0}catch(d){if(!(d instanceof RangeError))throw d}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:o,pos:s,totalPos:r}=this;throw new RangeError(`Insufficient data in parsing ${De(o)} at ${r} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let i=t,o=-1;for await(const s of e){if(t&&o===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(o=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--o!==0;);}catch(r){if(!(r instanceof RangeError))throw r}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const o=e-128;if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e<160){const o=e-144;if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else{const o=e-160;t=this.decodeString(o,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const o=this.lookU8();t=this.decodeString(o,1)}else if(e===218){const o=this.lookU16();t=this.decodeString(o,2)}else if(e===219){const o=this.lookU32();t=this.decodeString(o,4)}else if(e===220){const o=this.readU16();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===221){const o=this.readU32();if(o!==0){this.pushArrayState(o),this.complete();continue e}else t=[]}else if(e===222){const o=this.readU16();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===223){const o=this.readU32();if(o!==0){this.pushMapState(o),this.complete();continue e}else t={}}else if(e===196){const o=this.lookU8();t=this.decodeBinary(o,1)}else if(e===197){const o=this.lookU16();t=this.decodeBinary(o,2)}else if(e===198){const o=this.lookU32();t=this.decodeBinary(o,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const o=this.lookU8();t=this.decodeExtension(o,1)}else if(e===200){const o=this.lookU16();t=this.decodeExtension(o,2)}else if(e===201){const o=this.lookU32();t=this.decodeExtension(o,4)}else throw new O(`Unrecognized type byte: ${De(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const o=i.top();if(o.type===Re)if(o.array[o.position]=t,o.position++,o.position===o.size)t=o.array,i.release(o);else continue e;else if(o.type===fe){if(t==="__proto__")throw new O("The key __proto__ is not allowed");o.key=this.mapKeyConverter(t),o.type=it;continue e}else if(o.map[o.key]=t,o.readCount++,o.readCount===o.size)t=o.map,i.release(o);else{o.key=null,o.type=fe;continue e}}return t}}readHeadByte(){return this.headByte===we&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=we}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 O(`Unrecognized array type byte: ${De(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new O(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new O(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var s;if(e>this.maxStrLength)throw new O(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw ot;const i=this.pos+t;let o;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?o=this.keyDecoder.decode(this.bytes,i,e):o=Kt(this.bytes,i,e),this.pos+=t+e,o}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===fe:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new O(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw ot;const i=this.pos+t,o=this.bytes.subarray(i,i+e);return this.pos+=t+e,o}decodeExtension(e,t){if(e>this.maxExtLength)throw new O(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+t),o=this.decodeBinary(e,t+1);return this.extensionCodec.decode(o,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Dt(this.view,this.pos);return this.pos+=8,e}readI64(){const e=nt(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 sn(n,e){return new je(e).decode(n)}const rn=new Set(["auth","open","send","sync","history","read","typing","react","edit","delete","invoke","pubkey","ping","annotate","annotate_clear","uploadPrekeys","fetchPrekey","assign","tag","note","agent_status","subscribe_inbox","unsubscribe_inbox"]);function an(n){return rn.has(n.type)}function He(n){return Yt(n)}function st(n){let e;try{e=sn(n)}catch{return null}return typeof e!="object"||e===null||typeof e.type!="string"?null:e}class cn{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,"annotations",[]);a(this,"annotationVersion",0);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,t)=>{const i=e.status==="pending",o=t.status==="pending";return i!==o?i?1:-1:i&&o?e.ts-t.ts:e.seq-t.seq})),this._sorted}visibleActions(){return this.actions.filter(e=>!e.availableInStates||e.availableInStates.includes(this.state))}highestSeq(){return this._maxSeq}addOptimistic(e,t){const i={id:e,conversationId:this.conversationId,seq:0,senderId:this.me,senderRole:"guest",content:t,ts:Date.now(),clientMsgId:e,status:"pending"};return this.byId.set(e,i),this.keyByClient.set(e,e),this._sorted=null,i}apply(e){var t;switch(e.type){case"opened":this.conversationId=e.conversation.id,this.state=e.conversation.state,e.subject&&(this.subject=e.subject),e.annotations&&(this.annotations=e.annotations,this.annotationVersion++);return;case"manifest":this.actions=e.actions,this.version=e.version,e.name&&(this.name=e.name),(t=e.theme)!=null&&t.accent&&(this.accent=e.theme.accent),e.e2e&&(this.e2e=!0),this.offline=e.offline===!0,this.offlineMessage=e.offlineMessage??"",e.launcherMessage&&(this.launcherMessage=e.launcherMessage),e.whiteLabel&&(this.whiteLabel=!0),e.preChat&&(this.preChat=e.preChat);return;case"message":this.upsert({...e.message});return;case"ack":{const i=this.keyByClient.get(e.clientMsgId),o=i?this.byId.get(i):void 0;if(o&&i){this.byId.delete(i);const s={...o,id:e.messageId,seq:e.seq,ts:e.ts,status:"sent"};this.byId.set(e.messageId,s),this.keyByClient.set(e.clientMsgId,e.messageId),e.seq>this._maxSeq&&(this._maxSeq=e.seq)}this._sorted=null;return}case"delivered":this.markOwnStatus(e.seq,"delivered");return;case"read":e.by!==this.me&&(this.lastReadByOthers=Math.max(this.lastReadByOthers,e.seq),this.markOwnStatus(e.seq,"read"));return;case"sync":for(const i of e.messages)this.upsert({...i});return;case"history":for(const i of e.messages)this.upsert({...i});this.hasMoreHistory=e.hasMore;return;case"typing":e.userId!==this.me&&(e.isTyping?this.typing.add(e.userId):this.typing.delete(e.userId));return;case"reaction":{const i=this.byId.get(e.messageId);if(!i)return;const o={...i.reactions??{}},s=(o[e.emoji]??[]).filter(r=>r!==e.by);e.removed||s.push(e.by),s.length?o[e.emoji]=s:delete o[e.emoji],this.byId.set(e.messageId,{...i,reactions:o}),this._sorted=null;return}case"edited":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,content:e.content,editedAt:e.editedAt}),this._sorted=null);return}case"deleted":{const i=this.byId.get(e.messageId);i&&(this.byId.set(e.messageId,{...i,deletedAt:e.ts}),this._sorted=null);return}case"state":this.state=e.state;return;case"assigned":this.assignedAgentId=e.agentId??void 0;return;case"presence":e.status==="online"?this.online.add(e.userId):this.online.delete(e.userId);return;case"subjectState":case"invoked":case"authed":case"error":case"pong":return;case"annotation":this.annotations=[...this.annotations,e.stroke],this.annotationVersion++;return;case"annotation_clear":this.annotations=[],this.annotationVersion++;return;case"sentiment":this.sentiment=e.label,this.sentimentScore=e.score;return;default:return}}upsert(e){const t=this.byId.get(e.id);this.byId.set(e.id,t?{...t,...e}:e),e.seq>this._maxSeq&&(this._maxSeq=e.seq),this._sorted=null}markOwnStatus(e,t){const i=rt(t);let o=!1;for(const[s,r]of this.byId)r.senderId!==this.me||r.seq<=0||r.seq>e||rt(r.status)>=i||(this.byId.set(s,{...r,status:t}),o=!0);o&&(this._sorted=null)}}function rt(n){switch(n){case"read":return 3;case"delivered":return 2;case"sent":return 1;default:return 0}}const at="http://www.w3.org/2000/svg",ln=8e3;class dn{constructor(){a(this,"svg",null);a(this,"timers",new Set)}apply(e){var t;if(e.type==="annotation")this.draw(e.stroke);else if(e.type==="annotation_clear")this.clear();else if(e.type==="opened"&&((t=e.annotations)!=null&&t.length))for(const i of e.annotations)this.draw(i)}ensureSvg(){var t;if((t=this.svg)!=null&&t.isConnected)return this.svg;const e=document.createElementNS(at,"svg");return e.setAttribute("data-relay-annotations",""),e.setAttribute("aria-hidden","true"),e.setAttribute("style","position:fixed;inset:0;width:100vw;height:100vh;pointer-events:none;z-index:2147483000;"),document.body.append(e),this.svg=e,e}draw(e){var h;if(typeof document>"u"||!((h=e.points)!=null&&h.length))return;const t=this.ensureSvg(),i=window.innerWidth,o=window.innerHeight,s=document.createElementNS(at,"polyline");s.setAttribute("points",e.points.map(d=>`${(d.x*i).toFixed(1)},${(d.y*o).toFixed(1)}`).join(" ")),s.setAttribute("fill","none"),s.setAttribute("stroke",e.color||"#ff3b30"),s.setAttribute("stroke-width",String(e.width||3)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("data-stroke-id",e.id),t.append(s);const r=setTimeout(()=>{s.style.transition="opacity 600ms",s.style.opacity="0";const d=setTimeout(()=>{s.remove(),this.timers.delete(d)},650);this.timers.add(d),this.timers.delete(r)},ln);this.timers.add(r)}clear(){var e;(e=this.svg)==null||e.replaceChildren()}destroy(){var e;for(const t of this.timers)clearTimeout(t);this.timers.clear(),(e=this.svg)==null||e.remove(),this.svg=null}}class hn{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 i,o;if(this.state==="connecting"||this.state==="open")return;this.stopped=!1,this.state="connecting",this.authed=!1,(o=(i=this.opts).onStatusChange)==null||o.call(i,this.attempt>0?"reconnecting":"connecting");const t=(this.opts.socketFactory??fn)(this.opts.url);t.binaryType="arraybuffer",this.socket=t,t.onopen=()=>{this.raw({type:"auth",token:this.opts.token})},t.onmessage=s=>{const r=st(new Uint8Array(s.data));!r||an(r)||this.handle(r)},t.onclose=()=>this.onClosed(),t.onerror=()=>{try{t.close()}catch{}}}send(e){if(this.state==="open"&&this.authed){this.raw(e);return}const t=this.opts.maxOutbox??1e3;this.outbox.length>=t&&(this.outbox=this.outbox.slice(this.outbox.length-(t>>1))),this.outbox.push(e)}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 t,i,o,s;if(e.type==="authed"&&(this.attempt=0,this.state="open",this.authed=!0,this.everAuthed=!0,(i=(t=this.opts).onStatusChange)==null||i.call(t,"open"),this.raw(this.opts.open),this.flush()),e.type==="opened"&&this.raw({type:"sync",conversationId:e.conversation.id,sinceSeq:this.opts.getCursor()}),e.type==="error"&&pn.has(e.code)){if(e.code==="UNAUTHORIZED"&&this.opts.refreshToken&&!this.refreshing){this.refreshing=!0,(s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Renewing session…"),this.opts.refreshToken().then(r=>{var h;if(this.refreshing=!1,!r){this.fatal(e);return}this.opts.token=r;try{(h=this.socket)==null||h.close()}catch{}}).catch(()=>{this.refreshing=!1,this.fatal(e)});return}this.fatal(e);return}this.opts.onFrame(e)}fatal(e){var t,i,o;this.stopped=!0;try{(t=this.socket)==null||t.close()}catch{}this.state="closed",(o=(i=this.opts).onStatusChange)==null||o.call(i,"error",un(e.code)),this.opts.onFrame(e)}flush(){const e=this.outbox;this.outbox=[];for(const t of e)this.raw(t)}raw(e){var t;try{(t=this.socket)==null||t.send(He(e))}catch{this.outbox.push(e)}}onClosed(){var o,s;if(this.authed=!1,this.socket=null,this.stopped){this.state="closed";return}this.state="idle";const e=this.opts.backoffBaseMs??500,t=this.opts.backoffMaxMs??15e3,i=Math.min(t,e*2**this.attempt)*(.5+Math.random()*.5);this.attempt++,this.attempt>=3&&!this.everAuthed&&((s=(o=this.opts).onStatusChange)==null||s.call(o,"reconnecting","Can't reach chat — retrying…")),this.timer=setTimeout(()=>this.connect(),i)}}const pn=new Set(["UNAUTHORIZED"]);function un(n){switch(n){case"UNAUTHORIZED":return"Chat unavailable — sign-in/token was rejected";default:return"Chat unavailable"}}function fn(n){return new WebSocket(n)}const ct=200,wn=7*864e5;class gn{constructor(e){a(this,"key");this.key=`ocw_outbox_${e}`}load(){try{const e=localStorage.getItem(this.key);if(!e)return[];const t=JSON.parse(e),i=Date.now()-wn,o=t.filter(s=>s.ts>=i);return o.length!==t.length&&this.save(o),o}catch{return[]}}add(e){try{const t=this.load();t.push(e),this.save(t.length>ct?t.slice(t.length-ct):t)}catch{}}remove(e){try{const t=this.load().filter(i=>i.clientMsgId!==e);this.save(t)}catch{}}save(e){try{localStorage.setItem(this.key,JSON.stringify(e))}catch{}}}const B=()=>globalThis.crypto.subtle;function Ee(n){const e=n instanceof Uint8Array?n:new Uint8Array(n);let t="";for(const i of e)t+=String.fromCharCode(i);return btoa(t)}function Ne(n){const e=atob(n),t=new ArrayBuffer(e.length),i=new Uint8Array(t);for(let o=0;o<e.length;o++)i[o]=e.charCodeAt(o);return i}async function ge(){const n=await B().generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:n.publicKey,privateKey:n.privateKey}}async function ie(n){return Ee(await B().exportKey("raw",n))}async function le(n){return B().importKey("raw",Ne(n),{name:"ECDH",namedCurve:"P-256"},!1,[])}async function xn(n,e){const t=await le(e);return B().deriveKey({name:"ECDH",public:t},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function yn(n,e){const t=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(e),o=await B().encrypt({name:"AES-GCM",iv:t},n,i);return{ct:Ee(o),iv:Ee(t)}}async function bn(n,e,t){const i=await B().decrypt({name:"AES-GCM",iv:Ne(t)},n,Ne(e));return new TextDecoder().decode(i)}async function mn(n){var t,i;try{const o=(t=globalThis.localStorage)==null?void 0:t.getItem(n);if(o){const{pub:s,priv:r}=JSON.parse(o),h=await B().importKey("jwk",s,{name:"ECDH",namedCurve:"P-256"},!0,[]),d=await B().importKey("jwk",r,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]);return{publicKey:h,privateKey:d}}}catch{}const e=await ge();try{const o=await B().exportKey("jwk",e.publicKey),s=await B().exportKey("jwk",e.privateKey);(i=globalThis.localStorage)==null||i.setItem(n,JSON.stringify({pub:o,priv:s}))}catch{}return e}async function vn(n,e){const t=await B().exportKey("raw",e),i=await B().sign({name:"ECDSA",hash:"SHA-256"},n,t);return Ee(i)}async function kn(){const n=await ge(),e=await B().generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]);return{ecdhKP:n,ecdsaKP:{publicKey:e.publicKey,privateKey:e.privateKey},publicKeyB64:await ie(n.publicKey),sigPublicKeyB64:await ie(e.publicKey)}}async function lt(n){var t,i;try{const o=(t=globalThis.localStorage)==null?void 0:t.getItem(`${n}-identity`);if(o){const s=JSON.parse(o),r=await B().importKey("jwk",s.ecdhPub,{name:"ECDH",namedCurve:"P-256"},!0,[]),h=await B().importKey("jwk",s.ecdhPriv,{name:"ECDH",namedCurve:"P-256"},!0,["deriveKey","deriveBits"]),d=await B().importKey("jwk",s.ecdsaPub,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),f=await B().importKey("jwk",s.ecdsaPriv,{name:"ECDSA",namedCurve:"P-256"},!0,["sign"]);return{ecdhKP:{publicKey:r,privateKey:h},ecdsaKP:{publicKey:d,privateKey:f},publicKeyB64:await ie(r),sigPublicKeyB64:await ie(d)}}}catch{}const e=await kn();try{const o=await B().exportKey("jwk",e.ecdhKP.publicKey),s=await B().exportKey("jwk",e.ecdhKP.privateKey),r=await B().exportKey("jwk",e.ecdsaKP.publicKey),h=await B().exportKey("jwk",e.ecdsaKP.privateKey);(i=globalThis.localStorage)==null||i.setItem(`${n}-identity`,JSON.stringify({ecdhPub:o,ecdhPriv:s,ecdsaPub:r,ecdsaPriv:h}))}catch{}return e}async function Sn(n,e){const t=await ge(),i=await ie(t.publicKey),o=await le(e.identityKey),s=await le(e.signedPrekey),r=e.oneTimePrekey?await le(e.oneTimePrekey):null,h=await oe(n.privateKey,s),d=await oe(t.privateKey,o),f=await oe(t.privateKey,s),y=r?await oe(t.privateKey,r):null,l=dt(h,d,f,...y?[y]:[]);return{sharedKey:await ht(l),ephemeralPublicKey:i}}async function Cn(n,e,t,i,o){const s=await le(t),r=await le(i),h=await oe(e.privateKey,s),d=await oe(n.privateKey,r),f=await oe(e.privateKey,r),y=o?await oe(o.privateKey,r):null,l=dt(h,d,f,...y?[y]:[]);return ht(l)}async function oe(n,e){return B().deriveBits({name:"ECDH",public:e},n,256)}function dt(...n){const e=n.reduce((o,s)=>o+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const o of n)t.set(new Uint8Array(o),i),i+=o.byteLength;return t.buffer}async function ht(n){const e=await B().importKey("raw",n,"HKDF",!1,["deriveKey"]);return B().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 In=20;class En{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 mn(this.storageKey),ie(this.kp.publicKey)}async onPeerKey(e){this.kp&&(this.shared=await xn(this.kp.privateKey,e))}async initX3DH(){this.identityKP=await lt(this.storageKey),this.signedPreKP=await ge(),this.signedPrekeyId=`spk-${Date.now()}-${Math.random().toString(36).slice(2)}`;for(let o=0;o<In;o++)this.otpKeys.push(await ge());const e=await ie(this.signedPreKP.publicKey),t=await vn(this.identityKP.ecdsaKP.privateKey,this.signedPreKP.publicKey),i=await Promise.all(this.otpKeys.map(o=>ie(o.publicKey)));return{identityKey:this.identityKP.publicKeyB64,signedPrekey:e,signedPrekeyId:this.signedPrekeyId,signature:t,oneTimePrekeys:i}}async x3dhSendTo(e){this.identityKP||(this.identityKP=await lt(this.storageKey));const{sharedKey:t,ephemeralPublicKey:i}=await Sn(this.identityKP.ecdhKP,e);return this.x3dhShared=t,{ephemeralKey:i,spkId:e.signedPrekeyId,usedOTP:!!e.oneTimePrekey,senderIK:this.identityKP.publicKeyB64}}async x3dhReceiveFrom(e,t,i){if(!this.identityKP||!this.signedPreKP){this.pendingX3DH={senderIK:e,ephemeralKey:t,spkId:i};return}const o=this.otpKeys.shift();this.x3dhShared=await Cn(this.identityKP.ecdhKP,this.signedPreKP,e,t,o)}async flushPendingX3DH(){if(!this.pendingX3DH)return;const{senderIK:e,ephemeralKey:t,spkId:i}=this.pendingX3DH;this.pendingX3DH=void 0,await this.x3dhReceiveFrom(e,t,i)}async sealText(e,t){const i=this.x3dhShared??this.shared;if(!i)throw new Error("secure channel not ready");const{ct:o,iv:s}=await yn(i,e);return{kind:"text",text:o,enc:!0,iv:s,...t?{x3dhEK:t.ephemeralKey,x3dhSPK:t.spkId,x3dhIK:t.senderIK}:{}}}async openContent(e){if(e.kind!=="text"||!e.enc||!e.iv)return e;const t=this.x3dhShared??this.shared;if(!t)return{kind:"text",text:"🔒 encrypted"};try{return{kind:"text",text:await bn(t,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 t of e.messages)t.content=await this.openContent(t.content)}}function Tn(n){if(n.kind!=="text"||!n.enc)return null;const e=n;return!e.x3dhEK||!e.x3dhSPK||!e.x3dhIK?null:{x3dhEK:e.x3dhEK,x3dhSPK:e.x3dhSPK,x3dhIK:e.x3dhIK}}const pt="objectchat-widget-styles",Un=["👍","❤️","😂","😮","😢","🙏"],An=400,Pn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M22 2 11 13M22 2l-7 20-4-9-9-4 20-7z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Bn=`
|
|
2
2
|
.ocw { --ocw-accent:#4F63F5; --ocw-bg:#f3efe9; --ocw-card:#fff; --ocw-line:#ececec; --ocw-ink:#1c1b1a; --ocw-mut:#9b9690;
|
|
3
3
|
position:relative;
|
|
4
4
|
display:flex; flex-direction:column; height:100%; min-height:320px; background:var(--ocw-bg);
|
|
@@ -97,15 +97,13 @@ var RelayEmbed=function(q){"use strict";var On=Object.defineProperty;var Nn=(q,R
|
|
|
97
97
|
.ocw-conn-status.err { color:#c0392b; font-weight:600; }
|
|
98
98
|
.ocw-load-more { display:block; width:100%; background:none; border:1px solid #e3ded7; border-radius:10px; padding:6px 0; font-size:12px; color:var(--ocw-mut); cursor:pointer; margin-bottom:8px; }
|
|
99
99
|
.ocw-load-more:hover { border-color:var(--ocw-accent); color:var(--ocw-accent); }
|
|
100
|
-
.ocw-
|
|
101
|
-
.ocw-
|
|
102
|
-
|
|
103
|
-
.ocw-offline-msg { font-size:13px; color:var(--ocw-mut); margin-bottom:16px; }
|
|
100
|
+
.ocw-away { margin:0 14px 8px; padding:9px 12px; background:#fff8e6; border:1px solid #f0e2bd; border-radius:10px; font-size:12px; color:#7a5c17; display:flex; gap:7px; align-items:flex-start; line-height:1.45; }
|
|
101
|
+
.ocw-away-icon { flex:none; }
|
|
102
|
+
/* Shared form styles (used by the pre-chat panel; named for the retired offline form). */
|
|
104
103
|
.ocw-offline-form { display:flex; flex-direction:column; gap:8px; text-align:left; }
|
|
105
104
|
.ocw-offline-input { border:1px solid #e3ded7; border-radius:10px; padding:10px 12px; font-size:13px; font-family:inherit; }
|
|
106
105
|
.ocw-offline-input:focus { outline:none; border-color:var(--ocw-accent); }
|
|
107
106
|
.ocw-offline-submit { background:var(--ocw-accent); color:#fff; border:none; border-radius:10px; padding:11px; font-size:14px; font-weight:600; cursor:pointer; }
|
|
108
|
-
.ocw-offline-thanks { font-size:14px; color:#15803d; font-weight:600; }
|
|
109
107
|
.ocw-prechat { margin:20px 14px; padding:20px; background:#fff; border:1px solid #e3ded7; border-radius:16px; }
|
|
110
108
|
.ocw-prechat-title { font-weight:700; font-size:15px; margin-bottom:12px; }
|
|
111
109
|
.ocw-prechat select { border:1px solid #e3ded7; border-radius:10px; padding:10px 12px; font:inherit; font-size:13px; background:#fff; }
|
|
@@ -188,8 +186,44 @@ var RelayEmbed=function(q){"use strict";var On=Object.defineProperty;var Nn=(q,R
|
|
|
188
186
|
.ocw-row.theirs .ocw-translate-btn { right:auto; left:-26px; }
|
|
189
187
|
.ocw-bubble-wrap:hover .ocw-translate-btn { opacity:1; }
|
|
190
188
|
.ocw-translated-tag { font-size:10px; color:var(--ocw-mut); margin-top:2px; }
|
|
191
|
-
`;function bn(){if(typeof document>"u"||document.getElementById(qe))return;const n=document.createElement("style");n.id=qe,n.textContent=xn,document.head.appendChild(n)}function c(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function mn(n){try{return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function Se(n){var e;switch(n.kind){case"text":return n.text;case"system":return typeof((e=n.data)==null?void 0:e.message)=="string"?String(n.data.message):n.event;case"card":return[n.title,n.body].filter(Boolean).join(" — ");case"attachment":return n.name??n.url;case"form":return n.prompt;case"appointment":return`📅 ${n.title} — ${new Date(n.startIso).toLocaleString()}`}}class vn{constructor(e,t,i,s={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"offlinePanel");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,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var S,E,K,C,_,L,F,de,I,z;this.root=e,this.me=t,this.h=i,this.cfg=s,bn(),e.replaceChildren(),e.classList.add("ocw"),s.accent&&e.style.setProperty("--ocw-accent",s.accent);const o=c("div","ocw-head");if(this.h.onBack){const m=c("button","ocw-back","‹");m.type="button",m.setAttribute("aria-label","Back"),m.addEventListener("click",()=>this.h.onBack()),o.append(m)}const r=c("div","ocw-avatar");if((S=s.userInfo)!=null&&S.avatar){const m=document.createElement("img");m.src=s.userInfo.avatar,m.alt=s.userInfo.name??"You",m.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(m)}else r.textContent=(E=s.userInfo)!=null&&E.name?s.userInfo.name[0].toUpperCase():"🧑";o.append(r);const d=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((K=s.subject)==null?void 0:K.ownerLabel)??((C=s.subject)==null?void 0:C.title)??""),d.append(this.headerName),(_=s.subject)!=null&&_.subtitle&&d.append(c("div","ocw-head-meta",s.subject.subtitle)),o.append(d),this.statusBadge=c("span","ocw-badge",((L=s.subject)==null?void 0:L.status)??""),(F=s.subject)!=null&&F.status||(this.statusBadge.style.display="none"),o.append(this.statusBadge),this.e2eBadge=c("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",o.append(this.e2eBadge),this.connStatus=c("span","ocw-conn-status"),this.connStatus.style.display="none",o.append(this.connStatus),this.cobrowseBtn=c("button","ocw-menu ocw-cobrowse-btn","🖍"),this.cobrowseBtn.title="Shared whiteboard — draw to point things out together",this.cobrowseBtn.addEventListener("click",()=>{this.cobrowseActive=!this.cobrowseActive,this.updateCobrowseUI()}),o.append(this.cobrowseBtn),o.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 h=c("div","ocw-typing-bubble");h.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),h),this.quick=c("div","ocw-quick");for(const m of s.quickReplies??[]){const P=c("button",void 0,m);P.addEventListener("click",()=>{this.h.onSend(m),this.quick.style.display="none"}),this.quick.append(P)}this.formHost=c("div","ocw-form-host"),this.csatPanel=c("div","ocw-csat"),this.csatPanel.style.display="none",this.offlinePanel=c("div","ocw-offline"),this.offlinePanel.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=((de=s.i18n)==null?void 0:de.placeholder)??"Message…";const u=c("button","ocw-sendbtn");u.type="button";const x=(I=s.i18n)==null?void 0:I.send;x?(u.textContent=x,u.classList.add("ocw-sendbtn-label"),u.setAttribute("aria-label",x)):(u.innerHTML=yn,u.setAttribute("aria-label","Send message")),u.disabled=!0,this.sendBtn=u,u.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var m,P;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(H=>H.senderRole==="guest")?(P=(m=this.h).onDeflectQuery)==null||P.call(m,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",m=>{m.isComposing||m.keyCode===229||(m.key==="Enter"&&!m.shiftKey?(m.preventDefault(),this.flushSend()):this.signalTyping())});const p=c("button","ocw-attach","📎");p.title="Attach image or file";const w=document.createElement("input");w.type="file",w.accept="image/*,.pdf,.txt,.doc,.docx",w.style.display="none",p.addEventListener("click",()=>w.click()),w.addEventListener("change",()=>{var m;(m=w.files)!=null&&m[0]&&this.h.onAttach&&this.h.onAttach(w.files[0]),w.value=""});const f=c("div","ocw-input");f.append(p,w,this.input,u);const k=c("div","ocw-footer");((z=s.i18n)==null?void 0:z.poweredBy)!==void 0?k.textContent=s.i18n.poweredBy:k.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=k,e.append(o,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.offlinePanel,this.preChatPanel,this.deflectPanel,f,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const m of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const P=c("button","ocw-cobrowse-swatch");P.style.background=m,P.type="button",m===this.cobrowseColor&&P.classList.add("sel"),P.addEventListener("click",()=>{this.cobrowseColor=m;for(const H of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))H.classList.remove("sel");P.classList.add("sel")}),this.cobrowseToolbar.append(P)}const v=c("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var m,P;return(P=(m=this.h).onAnnotateClear)==null?void 0:P.call(m)}),this.cobrowseToolbar.append(v),this.cobrowseHint=c("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents();const y=m=>{e.classList.toggle("ocw-compact",m>0&&m<gn)};y(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(m=>{var H;const P=((H=m[0])==null?void 0:H.contentRect.width)??e.clientWidth;y(P)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e,t;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(t=this.compactObserver)==null||t.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,w,f,k,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const y=(p=this.cfg.subject)==null?void 0:p.ownerLabel;y&&(this.headerName.textContent=y)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const t=e.visibleActions();this.chips.style.display=t.length?"flex":"none";for(const y of t)this.chips.append(this.chipEl(y));const i=this.scroll.scrollHeight,s=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const y=c("div","ocw-load-more");y.textContent="↑ Loading earlier messages…",y.style.pointerEvents="none",this.scroll.append(y)}let o=0;for(const y of e.messages())this.scroll.append(this.messageEl(y,e)),y.senderId!==this.me&&y.seq>o&&(o=y.seq);s>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+s:this.scroll.scrollTop=this.scroll.scrollHeight,o>0&&this.h.onReadUpTo(o);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const d=this.typing.querySelector(".ocw-typing-bubble");d&&d.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const h=e.messages().some(y=>y.senderRole==="guest");!!((w=e.preChat)!=null&&w.enabled)&&!this.preChatDone&&!h&&(e.preChat.showWhen!=="offline"||e.offline)?(this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.offlinePanel.style.display="none",(f=this.root.querySelector(".ocw-input"))==null||f.style.setProperty("display","none")):(this.preChatPanel.style.display="none",e.offline?(this.offlinePanel.style.display==="none"&&this.buildOfflinePanel(e.offlineMessage),this.offlinePanel.style.display="block",(k=this.root.querySelector(".ocw-input"))==null||k.style.setProperty("display","none")):(this.offlinePanel.style.display="none",(v=this.root.querySelector(".ocw-input"))==null||v.style.removeProperty("display")));const x=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&x.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block")}setConnStatus(e,t){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const i=e==="error";this.connStatus.className=`ocw-conn-status${i?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=i?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ reconnecting…":"● connecting…"}buildOfflinePanel(e){var d;this.offlinePanel.replaceChildren(),this.offlinePanel.append(c("div","ocw-offline-icon","🌙")),this.offlinePanel.append(c("div","ocw-offline-title",((d=this.cfg.i18n)==null?void 0:d.offline)??"We're offline right now")),this.offlinePanel.append(c("div","ocw-offline-msg",e||"Leave your details and we'll get back to you soon."));const t=c("div","ocw-offline-form"),i=c("input","ocw-offline-input");i.placeholder="Your name",i.type="text";const s=c("input","ocw-offline-input");s.placeholder="Your email",s.type="email";const o=c("textarea","ocw-offline-input");o.placeholder="Your message",o.rows=3;const r=c("button","ocw-offline-submit","Send message");r.type="button",r.addEventListener("click",()=>{!s.value.trim()||!o.value.trim()||(r.disabled=!0,this.h.onSend(`[Offline form]
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
Message: ${o.value}`),this.offlinePanel.replaceChildren(c("div","ocw-offline-thanks","✓ Message sent! We'll reply to your email.")))}),t.append(i,s,o,r),this.offlinePanel.append(t)}buildPreChatPanel(e){var h;this.preChatBuilt=!0,this.preChatPanel.replaceChildren(),this.preChatPanel.append(c("div","ocw-prechat-title",e.title??"Before we start…"));const t=c("div","ocw-offline-form"),i={};for(const u of e.fields??["name","email"]){const x=c("input","ocw-offline-input");x.type=u==="email"?"email":u==="phone"?"tel":"text",x.placeholder=u==="name"?"Your name":u==="email"?"Your email":"Your phone number",i[u]=x,t.append(x)}let s=null;if((h=e.topics)!=null&&h.length){s=c("select",void 0);const u=document.createElement("option");u.value="",u.textContent="What is this about?",s.append(u);for(const x of e.topics){const p=document.createElement("option");p.value=x,p.textContent=x,s.append(p)}t.append(s)}let o=null,r=null;if(e.callbackOption){const u=c("label","ocw-prechat-cb");o=document.createElement("input"),o.type="checkbox",u.append(o,document.createTextNode("📞 Request a call back")),t.append(u),i.phone||(r=c("input","ocw-offline-input"),r.type="tel",r.placeholder="Phone number for the call",r.style.display="none",o.addEventListener("change",()=>r.style.setProperty("display",o.checked?"block":"none")),t.append(r))}const d=c("button","ocw-offline-submit","Start chat");d.type="button",d.addEventListener("click",()=>{var w,f,k,v,y,S,E;const u=(w=i.email)==null?void 0:w.value.trim();if(i.email&&(!u||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(u))){i.email.focus();return}const x=!!(o!=null&&o.checked),p=(((f=i.phone)==null?void 0:f.value)??(r==null?void 0:r.value)??"").trim();if(x&&!p){(k=i.phone??r)==null||k.focus();return}if(s&&((v=e.topics)!=null&&v.length)&&!s.value){s.focus();return}d.disabled=!0,this.completePreChat(),(E=(S=this.h).onPreChat)==null||E.call(S,{...(y=i.name)!=null&&y.value.trim()?{name:i.name.value.trim()}:{},...u?{email:u}:{},...p?{phone:p}:{},...s!=null&&s.value?{topic:s.value}:{},...x?{callback:!0}:{}})}),t.append(d),this.preChatPanel.append(t)}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 t of e.slice(0,3)){const i=c("button","ocw-deflect-card");i.append(c("div","ocw-deflect-q",t.title),c("div","ocw-deflect-a",t.answer)),i.addEventListener("click",()=>i.classList.toggle("open")),this.deflectPanel.append(i)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(c("div","ocw-csat-title","How did we do?"));const e=c("div","ocw-csat-stars"),t=[];for(let i=1;i<=5;i++){const s=c("button","ocw-csat-star","★");s.dataset.score=String(i),s.addEventListener("mouseenter",()=>t.forEach((o,r)=>o.classList.toggle("lit",r<i))),s.addEventListener("mouseleave",()=>t.forEach(o=>o.classList.remove("lit"))),s.addEventListener("click",()=>{var o,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(c("div","ocw-csat-done",`Thanks for your ${i}★ rating!`)),(r=(o=this.h).onCsat)==null||r.call(o,i)}),t.push(s),e.append(s)}this.csatPanel.append(e)}updateCobrowseUI(){this.cobrowseCanvas.classList.toggle("active",this.cobrowseActive),this.cobrowseToolbar.classList.toggle("active",this.cobrowseActive),this.cobrowseHint.classList.toggle("active",this.cobrowseActive),this.cobrowseBtn.classList.toggle("on",this.cobrowseActive),this.cobrowseActive&&(this.resizeCobrowseCanvas(),this.redrawCobrowse())}resizeCobrowseCanvas(){this.cobrowseCanvas.width=this.root.clientWidth||1,this.cobrowseCanvas.height=this.root.clientHeight||1}drawStroke(e){const t=this.cobrowseCanvas.getContext("2d");if(!t||e.points.length<2)return;const i=this.cobrowseCanvas.width,s=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(i,s)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*i,e.points[0].y*s);for(const o of e.points.slice(1))t.lineTo(o.x*i,o.y*s);t.stroke()}redrawCobrowse(){var t;const e=this.cobrowseCanvas.getContext("2d");if(e){e.clearRect(0,0,this.cobrowseCanvas.width,this.cobrowseCanvas.height);for(const i of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(i)}}bindCobrowsePointerEvents(){let e=!1,t=[];const i=r=>{const d=this.cobrowseCanvas.getBoundingClientRect(),h=d.width>0?(r.clientX-d.left)/d.width:0,u=d.height>0?(r.clientY-d.top)/d.height:0;return{x:Math.min(1,Math.max(0,h)),y:Math.min(1,Math.max(0,u))}},s=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[i(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(i(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:s}))});const o=r=>{var d,h;if(e){e=!1,t.length>1&&((h=(d=this.h).onAnnotate)==null||h.call(d,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:s})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",o),this.cobrowseCanvas.addEventListener("pointercancel",o)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,i=this.cfg.subject,s=(t==null?void 0:t.title)??(i==null?void 0:i.title);if(!s)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(c("div","ocw-subject-title",s)),i!=null&&i.subtitle&&this.subjectCard.append(c("div","ocw-subject-sub",i.subtitle));const o=c("div","ocw-tags");if(t)for(const[d,h]of Object.entries(t.fields))o.append(c("span","ocw-tag",`${d}: ${h}`));else for(const d of(i==null?void 0:i.tags)??[])o.append(c("span","ocw-tag",d));o.childNodes.length&&this.subjectCard.append(o);const r=(t==null?void 0:t.state)??(i==null?void 0:i.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const t=c("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return t.dataset.actionId=e.id,t.addEventListener("click",async()=>{var i;e.confirm&&!await this.confirm(e.label)||((i=e.input)!=null&&i.length?this.openForm(e):this.h.onInvoke(e.id))}),t}confirm(e){return new Promise(t=>{const i=c("div","ocw-modal"),s=c("div","ocw-modal-card");s.append(c("div","ocw-modal-title",e)),s.append(c("div","ocw-modal-body",`Confirm “${e}”?`));const o=c("div","ocw-modal-actions"),r=c("button","ocw-modal-cancel","Cancel"),d=c("button","ocw-modal-ok","Confirm"),h=u=>{i.remove(),t(u)};r.addEventListener("click",()=>h(!1)),d.addEventListener("click",()=>h(!0)),i.addEventListener("click",u=>{u.target===i&&h(!1)}),o.append(r,d),s.append(o),i.append(s),this.root.append(i),d.focus()})}openForm(e){var d,h;this.formHost.replaceChildren();const t=c("div","ocw-form");t.append(c("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const i=new Map;for(const u of e.input??[]){const x=c("label","ocw-form-row");if(x.append(c("span","ocw-form-lbl",u.label)),u.type==="select"&&((d=u.options)!=null&&d.length)){const p=c("select","ocw-form-input");u.required||p.append(c("option",void 0,"— select —"));for(const w of u.options){const f=c("option");f.value=w,f.textContent=w,p.append(f)}u.required&&(p.required=!0),x.append(p),i.set(u.name,p)}else{const p=c("input","ocw-form-input");p.type=u.type==="number"?"number":u.type==="date"?"datetime-local":"text",u.required&&(p.required=!0),x.append(p),i.set(u.name,p)}t.append(x)}const s=c("div","ocw-form-actions"),o=c("button","ocw-form-cancel","Cancel"),r=c("button","ocw-form-submit","Send");o.addEventListener("click",()=>this.formHost.replaceChildren()),r.addEventListener("click",()=>{const u={};for(const[x,p]of i){if(p.required&&!p.value){p.style.borderColor="#e5484d";return}u[x]=p.type==="number"?Number(p.value):p.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,u)}),s.append(o,r),t.append(s),this.formHost.append(t),(h=i.values().next().value)==null||h.focus()}messageEl(e,t){var p;if(e.senderRole==="system"){const w=c("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":Se(e.content),w}const i=e.senderId===this.me,s=!!e.internal,o=c("div",`ocw-row ${s?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!i&&!s&&o.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=c("div"),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",r.append(w)}const h=c("div","ocw-bubble");let u=null;if(e.deletedAt)h.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((p=w.mime)!=null&&p.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")),h.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")),h.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 k=c("div","ocw-appt-links"),v=document.createElement("a");v.href=w.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.textContent="📅 Add to Google Calendar";const y=document.createElement("a");y.href=w.icalUrl,y.download=`${w.title}.ics`,y.className="ocw-appt-btn ocw-appt-btn-sec",y.textContent="🍎 Apple / iCal",k.append(v,y),f.append(k),h.append(f)}else u=document.createTextNode(Se(e.content)),h.append(u),e.editedAt&&h.append(c("span","ocw-edited","(edited)"));if(d.append(h),!i&&!s&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&u){const w=e.content.text;if(w.trim()){const f=c("button","ocw-translate-btn","🌐");f.type="button",f.title="Translate",f.addEventListener("click",k=>{if(k.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),u.textContent=w,f.textContent="🌐",f.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),u.textContent=v,f.textContent="↩",f.title="Show original";return}f.textContent="⏳",this.h.onTranslate(w).then(y=>{if(y===null){f.textContent="⚠️",f.title="Translation unavailable",setTimeout(()=>{f.textContent="🌐",f.title="Translate"},1500);return}this.translationCache.set(e.id,y),this.showingTranslation.add(e.id),u.textContent=y,f.textContent="↩",f.title="Show original"})}),d.append(f)}}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",k=>{k.stopPropagation();const v=Se(e.content),y=document.createElement("textarea");y.value=v,y.rows=Math.min(4,Math.ceil(v.length/40)+1),y.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:#fff;color:#1c1b1a;box-sizing:border-box";const S=c("button","ocw-form-submit","Save");S.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const E=c("button","ocw-form-cancel","Cancel");E.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const K=c("div");K.style.cssText="display:flex;gap:6px;justify-content:flex-end",K.append(E,S);const C=c("div");C.append(y,K),h.replaceChildren(C),y.focus(),y.select();const _=()=>h.replaceChildren(u??document.createTextNode(v));E.addEventListener("click",_),S.addEventListener("click",()=>{const L=y.value.trim();L&&L!==v&&this.h.onEdit(e.id,L),_()}),y.addEventListener("keydown",L=>{L.key==="Enter"&&!L.shiftKey&&(L.preventDefault(),S.click()),L.key==="Escape"&&_()})}),w.append(f)}if(this.h.onDelete){const f=c("button","del","🗑");f.title="Delete",f.addEventListener("click",k=>{k.stopPropagation(),this.h.onDelete(e.id)}),w.append(f)}d.append(w)}if(r.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[y,S]of Object.entries(e.reactions)){const E=c("button",`ocw-react-pill${S.includes(this.me)?" mine":""}`,`${y} ${S.length}`);E.addEventListener("click",()=>{var K,C;return(C=(K=this.h).onReact)==null?void 0:C.call(K,e.id,y,S.includes(this.me))}),f.append(E)}const k=c("button","ocw-react-btn","+"),v=c("div","ocw-react-picker");for(const y of wn){const S=c("button",void 0,y);S.addEventListener("click",E=>{var C,_,L,F;E.stopPropagation();const K=(_=(C=e.reactions)==null?void 0:C[y])==null?void 0:_.includes(this.me);(F=(L=this.h).onReact)==null||F.call(L,e.id,y,!!K),v.style.display="none"}),v.append(S)}v.style.display="none",k.addEventListener("click",y=>{y.stopPropagation();const S=v.style.display==="none";v.style.display=S?"flex":"none",S&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),f.append(k),w.append(f,v),r.append(w)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([w,f])=>`${w}${f.length}`).join(" ")));const x=c("div","ocw-time ocw-meta",mn(e.ts));if(i&&e.status){const w=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,kn(e.status));x.append(w)}return i&&e.seq>0&&t.lastReadByOthers>=e.seq&&x.append(c("span","ocw-seen"," · Seen")),r.append(x),o.append(r),o}}function kn(n){switch(n){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const Sn=20;function Oe(n,e){var h;const t=n.trim().replace(/\/+$/,""),i=(h=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:h[1],s=i?i==="https"||i==="wss":!0,o=(i?t.slice(i.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${s?"https":"http"}://${o}`;return{wsUrl:`${s?"wss":"ws"}://${o}/ws`,httpBase:r}}function Cn(n){return Oe(n).httpBase}function In(n,e,t,i){const s=`beforeSeq=${t}&limit=${i}`;return[`${n}/conversations/${e}/messages?${s}`,`${n}/conversations/${e}/history?${s}`]}async function Ne(n,e,t,i,s=Sn){for(const o of In(n,e,i,s))try{const r=await fetch(o,{headers:{authorization:`Bearer ${t}`}});if(!r.ok)continue;const d=await r.json();return{messages:d.messages??[],hasMore:d.hasMore??!1}}catch{}return null}async function En(n,e,t,i,s,o){const r=o?o.replace(/\/+$/,""):Cn(n),d=await Ne(r,t,e,Number.MAX_SAFE_INTEGER);if(!d||(d.messages.length?(i.apply({type:"sync",conversationId:t,messages:d.messages}),i.apply({type:"history",conversationId:t,messages:[],hasMore:d.hasMore}),s.render(i)):i.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!d.hasMore))return;let h=!1;const u=async()=>{if(h||!i.hasMoreHistory)return;h=!0;const f=i.messages()[0];if(!f){h=!1;return}const k=await Ne(r,t,e,f.seq);k&&(i.apply({type:"history",conversationId:t,messages:k.messages,hasMore:k.hasMore}),s.render(i)),h=!1},x=s.getScrollEl();if(!x)return;let p=!1;setTimeout(()=>{p=!0},300);const w=()=>{p&&x.scrollTop<80&&i.hasMoreHistory&&!h&&u()};x.addEventListener("scroll",w,{passive:!0}),s.setScrollCleanup(()=>x.removeEventListener("scroll",w))}const ne=new WeakMap,ce=new Map;function We(n){return`relay-launcher::${n.profileId}::${n.subjectId??""}`}let ie=null;function Tn(){if(ie&&ie.state!=="closed")return ie;try{return ie=new AudioContext,ie}catch{return null}}function Pn(n){var Qe,et,tt,nt,it;ne.has(n.el)&&(ne.get(n.el).close(),ne.delete(n.el)),n.launcher&&((Qe=ce.get(We(n)))==null||Qe.close());const e=lt();let t,i=!1;const s=n.token??n.userId??e,o=s!==e?e:void 0,{wsUrl:r,httpBase:d}=Oe(n.url,n.apiUrl);let h=new Xt(s);const u=n.subjectId?`${s}::${n.subjectId}`:s,x=new nn(u);let p,w=!1,f=null,k=null,v=null,y=null;!n.launcher&&!n.el.style.height&&n.el.clientHeight===0&&(n.el.style.width=n.el.style.width||"100%",n.el.style.height="600px");for(const l of x.load())h.addOptimistic(l.clientMsgId,l.content);let S=null,E=null,K=0,C=!n.launcher;if(n.launcher){const g=(n.position??"bottom-right").includes("right");S=document.createElement("div"),S.style.cssText=`position:fixed;${g?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${g?"flex-end":"flex-start"};gap:12px`;const b=document.createElement("div"),B=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,pe=A=>{n.el.classList.toggle("ocw-fs",A),b.style.cssText=A?["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:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(g?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};pe((B==null?void 0:B.matches)??!1);const ue=A=>pe(A.matches);B==null||B.addEventListener("change",ue),f=B,k=ue,n.el.style.cssText="width:100%;height:100%;overflow:hidden",b.append(n.el);const Ee='<svg viewBox="0 0 24 24" width="26" height="26" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',Te='<svg viewBox="0 0 24 24" width="22" height="22" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"/></svg>',$=document.createElement("button");$.type="button",$.style.cssText=["width:56px;height:56px;border-radius:50%",`background:${n.accent??"#4F63F5"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","position:relative;flex:none","display:flex;align-items:center;justify-content:center","transition:transform .15s"].join(";"),$.onmouseenter=()=>{$.style.transform="scale(1.08)"},$.onmouseleave=()=>{$.style.transform="scale(1)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const fe=()=>{$.innerHTML=C?Te:Ee,$.setAttribute("aria-label",C?"Close chat":"Open chat"),$.setAttribute("aria-expanded",String(C)),$.append(E)};fe(),S.append(b,$),document.body.append(S);const Pe=`ocw-teaser-dismissed::${n.profileId}`,we=typeof n.launcherMessage=="string"?{title:n.launcherMessage}:n.launcherMessage;let U=null;const Fn=()=>{try{return sessionStorage.getItem(Pe)==="1"}catch{return!1}},qn='<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>',st=()=>{const A=we!=null&&we.title?we:h.launcherMessage??void 0;if(!(!!(A!=null&&A.title)&&!C&&!Fn())){U&&(U.remove(),U=null);return}if(U)return;U=document.createElement("div"),U.setAttribute("role","button"),U.setAttribute("tabindex","0"),U.setAttribute("aria-label",A.title),U.style.cssText=["max-width:280px","background:#fff","border-radius:14px","box-shadow:0 6px 28px rgba(0,0,0,.16)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${g?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Ae=document.createElement("div");if(Ae.textContent=A.title,Ae.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",U.append(Ae),A.subtitle){const O=document.createElement("div");O.style.cssText="display:flex;align-items:center;gap:6px;margin-top:6px;font-size:13px;color:#6b7280";const Be=document.createElement("span");Be.innerHTML=qn,Be.style.cssText=`color:${n.accent??"#4F63F5"};display:inline-flex`;const rt=document.createElement("span");rt.textContent=A.subtitle,O.append(Be,rt),U.append(O)}const J=document.createElement("button");J.type="button",J.setAttribute("aria-label","Dismiss"),J.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>',J.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",J.addEventListener("click",O=>{O.stopPropagation();try{sessionStorage.setItem(Pe,"1")}catch{}U&&(U.remove(),U=null)}),U.append(J);const ot=()=>{C||(C=!0,Ue(!0),fe(),K=0,E&&(E.style.display="none"),U&&(U.remove(),U=null))};U.addEventListener("click",ot),U.addEventListener("keydown",O=>{(O.key==="Enter"||O.key===" ")&&(O.preventDefault(),ot())}),S.insertBefore(U,$)};if(!document.getElementById("ocw-teaser-style")){const A=document.createElement("style");A.id="ocw-teaser-style",A.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(A)}y=st,st();const Ue=A=>{A?(b.style.display="flex",requestAnimationFrame(()=>{b.style.opacity="1",b.style.transform="scale(1)"})):(b.style.opacity="0",b.style.transform="scale(.95)",setTimeout(()=>{C||(b.style.display="none")},180))};$.addEventListener("click",()=>{if(C=!C,Ue(C),fe(),C){K=0,E&&(E.style.display="none");try{sessionStorage.setItem(Pe,"1")}catch{}}y==null||y()}),v=A=>{A.key==="Escape"&&C&&(C=!1,Ue(!1),fe())},document.addEventListener("keydown",v)}const _=()=>{C||(K++,E&&(E.textContent=String(K),E.style.display="flex"))},L=()=>{try{const l=Tn();if(!l)return;l.state==="suspended"&&l.resume().catch(()=>{});const g=l.createOscillator(),b=l.createGain();g.connect(b),b.connect(l.destination),g.frequency.setValueAtTime(880,l.currentTime),g.frequency.exponentialRampToValueAtTime(440,l.currentTime+.15),b.gain.setValueAtTime(.3,l.currentTime),b.gain.exponentialRampToValueAtTime(.001,l.currentTime+.3),g.start(),g.stop(l.currentTime+.3)}catch{}},F=[],de=l=>{for(;F.length;){const g=F.shift();x.add({clientMsgId:g.clientMsgId,content:g.content,ts:Date.now()}),I.send({type:"send",conversationId:l,clientMsgId:g.clientMsgId,content:g.content})}};let I;const z=new un(`ocw-e2e-${n.profileId}`);let m=!1;const P=[],H=[];let Ye=!1;const Ie=(l,g)=>{z.sealText(g).then(b=>{p&&I.send({type:"send",conversationId:p,clientMsgId:l,content:b})})},zn=(l,g,b)=>{z.sealText(g,b).then(B=>{p&&I.send({type:"send",conversationId:p,clientMsgId:l,content:B})})},Dn=()=>{for(;P.length;){const l=P.shift();Ie(l.clientMsgId,l.text)}for(;H.length;){const l=H.shift();Ie(l.clientMsgId,l.text)}},$n=l=>{I.send({type:"fetchPrekey",targetUserId:l})},Rn=n.i18n??{},_n=["ar","he","fa","ur"],Hn=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";_n.includes(Hn)&&!n.el.dir&&(n.el.dir="rtl",n.el.style.fontFamily=n.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Ge=new Gt,Je=`oc_prechat_${n.profileId}_${s.slice(-8)}`,M=new vn(n.el,s,{onSend(l){const g=`cm_${Math.random().toString(36).slice(2)}`,b={kind:"text",text:l};h.addOptimistic(g,b),M.render(h),h.e2e?z.ready?Ie(g,l):Ye?H.push({clientMsgId:g,text:l}):(P.push({clientMsgId:g,text:l}),h.assignedAgentId&&$n(h.assignedAgentId)):p?(x.add({clientMsgId:g,content:b,ts:Date.now()}),I.send({type:"send",conversationId:p,clientMsgId:g,content:b})):F.push({clientMsgId:g,content:b})},async onAttach(l){if(!p)return;const g=`${d}/upload?name=${encodeURIComponent(l.name)}`,b=`cm_${Math.random().toString(36).slice(2)}`;h.addOptimistic(b,{kind:"text",text:`📎 Uploading ${l.name}…`}),M.render(h);try{const B=await fetch(g,{method:"POST",headers:{"content-type":l.type,authorization:`Bearer ${s}`},body:l});if(!B.ok)throw new Error(`Upload failed: ${B.status}`);const{url:pe,name:ue,mime:Ee,size:Te}=await B.json();I.send({type:"send",conversationId:p,clientMsgId:b,content:{kind:"attachment",url:pe,name:ue,mime:Ee,size:Te}})}catch(B){h.addOptimistic(b,{kind:"text",text:`⚠️ Upload failed: ${B.message}`}),M.render(h)}},onInvoke(l,g){p&&I.send({type:"invoke",conversationId:p,actionId:l,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...g?{inputs:g}:{}})},onTyping(l,g){p&&I.send({type:"typing",conversationId:p,isTyping:l,...g?{preview:g}:{}})},onPreChat(l){try{localStorage.setItem(Je,"1")}catch{}I.send({type:"open",profileId:n.profileId,...n.subjectId?{subjectId:n.subjectId}:{},userInfo:{...l.name?{name:l.name}:{},...l.email?{email:l.email}:{},...l.phone||l.topic?{meta:{...l.phone?{phone:l.phone}:{},...l.topic?{topic:l.topic}:{}}}:{}}});const g=l.callback?`📞 Call-back requested${l.phone?`: ${l.phone}`:""}${l.topic?` — ${l.topic}`:""}`:l.topic?`Topic: ${l.topic}`:"";g&&p&&!h.e2e&&I.send({type:"send",conversationId:p,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:g}})},onDeflectQuery(l){if(i)return;clearTimeout(t);const g=l.trim();if(g.length<3){M.hideDeflection();return}t=setTimeout(()=>{fetch(`${d}/kb/search?profileId=${encodeURIComponent(n.profileId)}&q=${encodeURIComponent(g.slice(0,200))}`).then(b=>b.ok?b.json():{articles:[]}).then(b=>M.showDeflection(b.articles??[])).catch(()=>M.hideDeflection())},350)},onReadUpTo(l){p&&I.send({type:"read",conversationId:p,seq:l})},onLoadMore(){if(!p||!h.e2e)return;const l=h.messages()[0];l&&I.send({type:"history",conversationId:p,beforeSeq:l.seq,limit:20})},onEdit(l,g){p&&I.send({type:"edit",conversationId:p,messageId:l,content:{kind:"text",text:g}})},onDelete(l){p&&I.send({type:"delete",conversationId:p,messageId:l})},onReact(l,g,b){p&&I.send({type:"react",conversationId:p,messageId:l,emoji:g,remove:b})},onCsat(l){p&&fetch(`${d}/conversations/${p}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify({score:l})}).catch(()=>{})},onAnnotate(l){p&&I.send({type:"annotate",conversationId:p,stroke:l})},onAnnotateClear(){p&&I.send({type:"annotate_clear",conversationId:p})},...n.translateLang?{async onTranslate(l){try{const g=await fetch(`${d}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${s}`},body:JSON.stringify({text:l,targetLang:n.translateLang})});if(!g.ok)return null;const{translated:b}=await g.json();return b}catch{return null}}}:{},...n.onBack?{onBack:n.onBack}:{}},{...n.subject?{subject:n.subject}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.accent?{accent:n.accent}:{},...(et=n.user)!=null&&et.name||(tt=n.user)!=null&&tt.avatar?{userInfo:{...n.user.name?{name:n.user.name}:{},...n.user.avatar?{avatar:n.user.avatar}:{}}}:{},i18n:Rn});try{localStorage.getItem(Je)&&M.completePreChat()}catch{}const Ze=n.user&&(n.user.name||n.user.email||n.user.avatar||n.user.meta)?{...n.user.name?{name:n.user.name}:{},...n.user.email?{email:n.user.email}:{},...n.user.avatar?{avatar:n.user.avatar}:{},...n.user.meta?{meta:n.user.meta}:{}}:void 0,jn={type:"open",profileId:n.profileId,...n.kind==="direct"&&n.peerId?{kind:"direct",peerId:n.peerId}:n.subjectId?{subjectId:n.subjectId}:{},...o?{linkFrom:o}:{},...Ze?{userInfo:Ze}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(nt=n.subject)!=null&&nt.title?{subjectTitle:n.subject.title}:{},...(it=n.subject)!=null&&it.subtitle?{subjectMeta:n.subject.subtitle}:{}};I=new Jt({...n.refreshToken?{refreshToken:n.refreshToken}:{},url:r,token:s,open:jn,getCursor:()=>h.highestSeq(),onStatusChange:(l,g)=>M.setConnStatus(l,g),onFrame(l){if(Ge.apply(l),l.type==="opened"){if(p=l.conversation.id,!w){w=!0;for(const g of x.load())I.send({type:"send",conversationId:p,clientMsgId:g.clientMsgId,content:g.content})}En(r,s,p,h,M,d),F.length&&de(p)}if(l.type==="ack"&&x.remove(l.clientMsgId),l.type==="prekeyBundle"){l.bundle&&(Ye=!0,z.x3dhSendTo(l.bundle).then(g=>{const b=[...P.splice(0),...H.splice(0)];for(const B of b)zn(B.clientMsgId,B.text,g);M.render(h)}));return}if(l.type==="message"&&h.e2e){const g=fn(l.message.content);if(g&&!z.ready){z.x3dhReceiveFrom(g.x3dhIK,g.x3dhEK,g.x3dhSPK).then(async()=>{await z.openFrame(l),h.apply(l),M.render(h)});return}}if(l.type==="peerkey"){z.onPeerKey(l.key).then(()=>{Dn(),M.render(h)});return}(async()=>{if(h.e2e&&await z.openFrame(l),h.apply(l),l.type==="manifest"&&(y==null||y()),l.type==="message"&&l.message.senderId!==s&&!l.message.internal&&(_(),L()),h.e2e&&p&&!m){m=!0;const g=await z.initX3DH();I.send({type:"uploadPrekeys",...g});const b=await z.begin();I.send({type:"pubkey",conversationId:p,key:b})}M.render(h)})()}}),I.connect(),M.render(h);const se=n.launcher?We(n):null,he={close:()=>{i=!0,clearTimeout(t),I.close(),S==null||S.remove(),M.destroy(),Ge.destroy(),f&&k&&f.removeEventListener("change",k),v&&(document.removeEventListener("keydown",v),v=null),ne.delete(n.el),se&&ce.get(se)===he&&ce.delete(se)}};return ne.set(n.el,he),se&&ce.set(se,he),he}const Un="wss://api.paramms.com/ws";let V=null,j=null,G={};function An(n,e){const t=n.profileId??n.appId;if(!t)throw new Error("Relay: `appId` is required (your chatroom id, e.g. 'p_...').");const i=n.subjectId??(n.listingId?`listing_${n.listingId}`:void 0),s=n.subjectTitle?{title:n.subjectTitle,...n.subjectMeta?{subtitle:n.subjectMeta}:{},...n.subjectPrice!=null?{tags:[`$${n.subjectPrice.toLocaleString()}`]}:{},...n.subjectStatus?{status:n.subjectStatus}:{}}:void 0,o=n.name||n.email||n.avatar?{...n.name?{name:n.name}:{},...n.email?{email:n.email}:{},...n.avatar?{avatar:n.avatar}:{}}:void 0;return{el:e,url:n.url??Un,profileId:t,...n.apiUrl?{apiUrl:n.apiUrl}:{},...i?{subjectId:i}:{},...n.token?{token:n.token}:{},...n.userId?{userId:n.userId}:{},...s?{subject:s}:{},...o?{user:o}:{},...n.accent?{accent:n.accent}:{},...n.translateLang?{translateLang:n.translateLang}:{},...n.launcherMessage?{launcherMessage:n.launcherSubtitle?{title:n.launcherMessage,subtitle:n.launcherSubtitle}:n.launcherMessage}:{},launcher:n.launcher??!0,position:n.position??"bottom-right"}}function Bn(){return(!j||!j.isConnected)&&(j=document.createElement("div"),j.id="relay-widget-root",document.body.appendChild(j)),j}function Ve(n){try{V==null||V.close(),V=Pn(An(n,Bn()))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}function Xe(n){G={...n},Ve(G)}function Kn(n){G={...G,...n},Ve(G)}function Ln(){V==null||V.close(),V=null,j==null||j.remove(),j=null,G={}}function Ce(n,e){switch(n){case"boot":Xe(e??{});break;case"update":case"identify":Kn(e??{});break;case"shutdown":Ln();break;default:console.warn("[Relay] unknown command:",n)}}function Mn(){if(typeof document>"u")return null;const n=document.querySelector("script[data-relay-app]"),e=n==null?void 0:n.dataset.relayApp;if(!e)return null;const t=n.dataset,i={appId:e};t.relayUser&&(i.userId=t.relayUser),t.relayToken&&(i.token=t.relayToken),t.relayListing&&(i.listingId=t.relayListing),t.relayAccent&&(i.accent=t.relayAccent),t.relayUrl&&(i.url=t.relayUrl);const s=t.relayPosition;return(s==="bottom-left"||s==="bottom-right")&&(i.position=s),t.relayLauncherMessage&&(i.launcherMessage=t.relayLauncherMessage),t.relayLauncherSubtitle&&(i.launcherSubtitle=t.relayLauncherSubtitle),t.relayLauncher==="false"&&(i.launcher=!1),i}if(typeof window<"u"){const n=window,e=n.Relay&&n.Relay.q?n.Relay.q:[];n.Relay=Ce;let t=!1;for(const i of e){const[s,o]=i;s==="boot"&&(t=!0),Ce(s,o)}if(!t){const i=n.relaySettings??Mn();i&&Xe(i)}}return q.Relay=Ce,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"}),q}({});
|
|
189
|
+
`;function Ln(){if(typeof document>"u"||document.getElementById(pt))return;const n=document.createElement("style");n.id=pt,n.textContent=Bn,document.head.appendChild(n)}function c(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function Mn(n){try{return new Date(n).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}catch{return""}}function qe(n){var e;switch(n.kind){case"text":return n.text;case"system":return typeof((e=n.data)==null?void 0:e.message)=="string"?String(n.data.message):n.event;case"card":return[n.title,n.body].filter(Boolean).join(" — ");case"attachment":return n.name??n.url;case"form":return n.prompt;case"appointment":return`📅 ${n.title} — ${new Date(n.startIso).toLocaleString()}`}}class zn{constructor(e,t,i,o={}){a(this,"scroll");a(this,"chips");a(this,"typing");a(this,"quick");a(this,"formHost");a(this,"csatPanel");a(this,"awayNotice");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,"cobrowseBtn");a(this,"cobrowseCanvas");a(this,"cobrowseToolbar");a(this,"cobrowseHint");a(this,"cobrowseActive",!1);a(this,"cobrowseColor","#f5713c");a(this,"lastAnnotationVersion",-1);a(this,"storeRef",null);a(this,"scrollCleanup",null);a(this,"translationCache",new Map);a(this,"showingTranslation",new Set);a(this,"subjectBuilt",!1);var I,E,L,T,H,R,W,ee,k,$;this.root=e,this.me=t,this.h=i,this.cfg=o,Ln(),e.replaceChildren(),e.classList.add("ocw"),o.accent&&e.style.setProperty("--ocw-accent",o.accent);const s=c("div","ocw-head");if(this.h.onBack){const b=c("button","ocw-back","‹");b.type="button",b.setAttribute("aria-label","Back"),b.addEventListener("click",()=>this.h.onBack()),s.append(b)}const r=c("div","ocw-avatar");if((I=o.userInfo)!=null&&I.avatar){const b=document.createElement("img");b.src=o.userInfo.avatar,b.alt=o.userInfo.name??"You",b.style.cssText="width:100%;height:100%;border-radius:50%;object-fit:cover",r.append(b)}else r.textContent=(E=o.userInfo)!=null&&E.name?o.userInfo.name[0].toUpperCase():"🧑";s.append(r);const h=c("div","ocw-head-main");this.headerName=c("div","ocw-head-name",((L=o.subject)==null?void 0:L.ownerLabel)??((T=o.subject)==null?void 0:T.title)??""),h.append(this.headerName),(H=o.subject)!=null&&H.subtitle&&h.append(c("div","ocw-head-meta",o.subject.subtitle)),s.append(h),this.statusBadge=c("span","ocw-badge",((R=o.subject)==null?void 0:R.status)??""),(W=o.subject)!=null&&W.status||(this.statusBadge.style.display="none"),s.append(this.statusBadge),this.e2eBadge=c("span","ocw-e2e","🔒 E2E"),this.e2eBadge.style.display="none",s.append(this.e2eBadge),this.connStatus=c("span","ocw-conn-status"),this.connStatus.style.display="none",s.append(this.connStatus),this.cobrowseBtn=c("button","ocw-menu ocw-cobrowse-btn","🖍"),this.cobrowseBtn.title="Shared whiteboard — draw to point things out together",this.cobrowseBtn.addEventListener("click",()=>{this.cobrowseActive=!this.cobrowseActive,this.updateCobrowseUI()}),s.append(this.cobrowseBtn),s.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 d=c("div","ocw-typing-bubble");d.append(c("div","ocw-typing-dot"),c("div","ocw-typing-dot"),c("div","ocw-typing-dot")),this.typing.append(c("div","ocw-dot","🧑"),d),this.quick=c("div","ocw-quick");for(const b of o.quickReplies??[]){const P=c("button",void 0,b);P.addEventListener("click",()=>{this.h.onSend(b),this.quick.style.display="none"}),this.quick.append(P)}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=((ee=o.i18n)==null?void 0:ee.placeholder)??"Message…";const f=c("button","ocw-sendbtn");f.type="button";const y=(k=o.i18n)==null?void 0:k.send;y?(f.textContent=y,f.classList.add("ocw-sendbtn-label"),f.setAttribute("aria-label",y)):(f.innerHTML=Pn,f.setAttribute("aria-label","Send message")),f.disabled=!0,this.sendBtn=f,f.addEventListener("click",()=>this.flushSend()),this.input.addEventListener("input",()=>{var b,P;this.sendBtn.disabled=this.input.value.trim().length===0,this.autoGrowInput(),this.storeRef&&!this.storeRef.messages().some(q=>q.senderRole==="guest")?(P=(b=this.h).onDeflectQuery)==null||P.call(b,this.input.value):this.hideDeflection()}),this.input.addEventListener("keydown",b=>{b.isComposing||b.keyCode===229||(b.key==="Enter"&&!b.shiftKey?(b.preventDefault(),this.flushSend()):this.signalTyping())});const l=c("button","ocw-attach","📎");l.title="Attach image or file";const w=document.createElement("input");w.type="file",w.accept="image/*,.pdf,.txt,.doc,.docx",w.style.display="none",l.addEventListener("click",()=>w.click()),w.addEventListener("change",()=>{var b;(b=w.files)!=null&&b[0]&&this.h.onAttach&&this.h.onAttach(w.files[0]),w.value=""});const u=c("div","ocw-input");u.append(l,w,this.input,f);const C=c("div","ocw-footer");(($=o.i18n)==null?void 0:$.poweredBy)!==void 0?C.textContent=o.i18n.poweredBy:C.innerHTML='Powered by <a href="https://relay.paramms.com" target="_blank" rel="noopener">Relay</a>',this.footer=C,e.append(s,this.chips,this.scroll,this.typing,this.quick,this.formHost,this.csatPanel,this.preChatPanel,this.deflectPanel,this.awayNotice,u,this.footer),this.cobrowseCanvas=c("canvas","ocw-cobrowse-canvas"),this.cobrowseToolbar=c("div","ocw-cobrowse-toolbar");for(const b of["#f5713c","#1c1b1a","#2563eb","#16a34a","#dc2626"]){const P=c("button","ocw-cobrowse-swatch");P.style.background=b,P.type="button",b===this.cobrowseColor&&P.classList.add("sel"),P.addEventListener("click",()=>{this.cobrowseColor=b;for(const q of this.cobrowseToolbar.querySelectorAll(".ocw-cobrowse-swatch"))q.classList.remove("sel");P.classList.add("sel")}),this.cobrowseToolbar.append(P)}const v=c("button","ocw-cobrowse-clear","Clear");v.addEventListener("click",()=>{var b,P;return(P=(b=this.h).onAnnotateClear)==null?void 0:P.call(b)}),this.cobrowseToolbar.append(v),this.cobrowseHint=c("div","ocw-cobrowse-hint","🖍 Draw to point things out — visible to both sides"),e.append(this.cobrowseCanvas,this.cobrowseToolbar,this.cobrowseHint),this.bindCobrowsePointerEvents();const g=b=>{e.classList.toggle("ocw-compact",b>0&&b<An)};g(e.clientWidth),typeof ResizeObserver<"u"&&(this.compactObserver=new ResizeObserver(b=>{var q;const P=((q=b[0])==null?void 0:q.contentRect.width)??e.clientWidth;g(P)}),this.compactObserver.observe(e))}getScrollEl(){return this.scroll}setScrollCleanup(e){var t;(t=this.scrollCleanup)==null||t.call(this),this.scrollCleanup=e}destroy(){var e,t;(e=this.scrollCleanup)==null||e.call(this),this.scrollCleanup=null,this.typingTimer&&(clearTimeout(this.typingTimer),this.typingTimer=null),(t=this.compactObserver)==null||t.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 l,w,u,C,v;if(this.storeRef=e,this.cobrowseBtn.classList.toggle("show",!!e.subject),!e.subject&&this.cobrowseActive&&(this.cobrowseActive=!1,this.updateCobrowseUI()),this.cobrowseActive&&e.annotationVersion!==this.lastAnnotationVersion&&(this.lastAnnotationVersion=e.annotationVersion,this.resizeCobrowseCanvas(),this.redrawCobrowse()),e.accent&&this.root.style.setProperty("--ocw-accent",e.accent),this.e2eBadge.style.display=e.e2e?"inline-flex":"none",this.buildSubjectCard(e),e.subject){const g=(l=this.cfg.subject)==null?void 0:l.ownerLabel;g&&(this.headerName.textContent=g)}this.quick.style.display=e.messages().length===0?"flex":"none",this.chips.replaceChildren();const t=e.visibleActions();this.chips.style.display=t.length?"flex":"none";for(const g of t)this.chips.append(this.chipEl(g));const i=this.scroll.scrollHeight,o=this.scroll.scrollTop;if(this.scroll.replaceChildren(),this.subjectCard.childNodes.length&&this.scroll.append(this.subjectCard),e.hasMoreHistory){const g=c("div","ocw-load-more");g.textContent="↑ Loading earlier messages…",g.style.pointerEvents="none",this.scroll.append(g)}let s=0;for(const g of e.messages())this.scroll.append(this.messageEl(g,e)),g.senderId!==this.me&&g.seq>s&&(s=g.seq);o>20?this.scroll.scrollTop=this.scroll.scrollHeight-i+o:this.scroll.scrollTop=this.scroll.scrollHeight,s>0&&this.h.onReadUpTo(s);const r=[...e.typing];this.typing.classList.toggle("active",r.length>0);const h=this.typing.querySelector(".ocw-typing-bubble");h&&h.setAttribute("aria-label",r.length?"typing":""),this.footer.style.display=e.whiteLabel?"none":"block";const d=e.messages().some(g=>g.senderRole==="guest");if(!!((w=e.preChat)!=null&&w.enabled)&&!this.preChatDone&&!d&&(e.preChat.showWhen!=="offline"||e.offline))this.preChatBuilt||this.buildPreChatPanel(e.preChat),this.preChatPanel.style.display="block",this.awayNotice.style.display="none",(u=this.root.querySelector(".ocw-input"))==null||u.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 g=this.awayNotice.lastChild;g.textContent=e.offlineMessage||((C=this.cfg.i18n)==null?void 0:C.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";(v=this.root.querySelector(".ocw-input"))==null||v.style.removeProperty("display")}const y=["resolved","closed","sold","issued","checked_out"];this.h.onCsat&&!this.csatSubmitted&&y.includes(e.state)&&e.messages().length>0&&(this.csatPanel.style.display==="none"&&this.buildCsatPanel(),this.csatPanel.style.display="block")}setConnStatus(e,t){if(e==="open"){this.connStatus.style.display="none";return}this.connStatus.style.display="";const i=e==="error";this.connStatus.className=`ocw-conn-status${i?" err":e==="reconnecting"?" warn":""}`,this.connStatus.textContent=i?`⚠ ${t??"Chat unavailable"}`:e==="reconnecting"?t??"↻ 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 t=c("div","ocw-offline-form"),i={};for(const f of e.fields??["name","email"]){const y=c("input","ocw-offline-input");y.type=f==="email"?"email":f==="phone"?"tel":"text",y.placeholder=f==="name"?"Your name":f==="email"?"Your email":"Your phone number",i[f]=y,t.append(y)}let o=null;if((d=e.topics)!=null&&d.length){o=c("select",void 0);const f=document.createElement("option");f.value="",f.textContent="What is this about?",o.append(f);for(const y of e.topics){const l=document.createElement("option");l.value=y,l.textContent=y,o.append(l)}t.append(o)}let s=null,r=null;if(e.callbackOption){const f=c("label","ocw-prechat-cb");s=document.createElement("input"),s.type="checkbox",f.append(s,document.createTextNode("📞 Request a call back")),t.append(f),i.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")),t.append(r))}const h=c("button","ocw-offline-submit","Start chat");h.type="button",h.addEventListener("click",()=>{var w,u,C,v,g,I,E;const f=(w=i.email)==null?void 0:w.value.trim();if(i.email&&(!f||!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f))){i.email.focus();return}const y=!!(s!=null&&s.checked),l=(((u=i.phone)==null?void 0:u.value)??(r==null?void 0:r.value)??"").trim();if(y&&!l){(C=i.phone??r)==null||C.focus();return}if(o&&((v=e.topics)!=null&&v.length)&&!o.value){o.focus();return}h.disabled=!0,this.completePreChat(),(E=(I=this.h).onPreChat)==null||E.call(I,{...(g=i.name)!=null&&g.value.trim()?{name:i.name.value.trim()}:{},...f?{email:f}:{},...l?{phone:l}:{},...o!=null&&o.value?{topic:o.value}:{},...y?{callback:!0}:{}})}),t.append(h),this.preChatPanel.append(t)}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 t of e.slice(0,3)){const i=c("button","ocw-deflect-card");i.append(c("div","ocw-deflect-q",t.title),c("div","ocw-deflect-a",t.answer)),i.addEventListener("click",()=>i.classList.toggle("open")),this.deflectPanel.append(i)}this.deflectPanel.style.display="flex"}hideDeflection(){this.deflectPanel.style.display="none",this.deflectPanel.replaceChildren()}buildCsatPanel(){this.csatPanel.replaceChildren(),this.csatPanel.append(c("div","ocw-csat-title","How did we do?"));const e=c("div","ocw-csat-stars"),t=[];for(let i=1;i<=5;i++){const o=c("button","ocw-csat-star","★");o.dataset.score=String(i),o.addEventListener("mouseenter",()=>t.forEach((s,r)=>s.classList.toggle("lit",r<i))),o.addEventListener("mouseleave",()=>t.forEach(s=>s.classList.remove("lit"))),o.addEventListener("click",()=>{var s,r;this.csatSubmitted=!0,this.csatPanel.replaceChildren(c("div","ocw-csat-done",`Thanks for your ${i}★ rating!`)),(r=(s=this.h).onCsat)==null||r.call(s,i)}),t.push(o),e.append(o)}this.csatPanel.append(e)}updateCobrowseUI(){this.cobrowseCanvas.classList.toggle("active",this.cobrowseActive),this.cobrowseToolbar.classList.toggle("active",this.cobrowseActive),this.cobrowseHint.classList.toggle("active",this.cobrowseActive),this.cobrowseBtn.classList.toggle("on",this.cobrowseActive),this.cobrowseActive&&(this.resizeCobrowseCanvas(),this.redrawCobrowse())}resizeCobrowseCanvas(){this.cobrowseCanvas.width=this.root.clientWidth||1,this.cobrowseCanvas.height=this.root.clientHeight||1}drawStroke(e){const t=this.cobrowseCanvas.getContext("2d");if(!t||e.points.length<2)return;const i=this.cobrowseCanvas.width,o=this.cobrowseCanvas.height;t.strokeStyle=e.color,t.lineWidth=Math.max(1,e.width*Math.min(i,o)),t.lineJoin="round",t.lineCap="round",t.beginPath(),t.moveTo(e.points[0].x*i,e.points[0].y*o);for(const s of e.points.slice(1))t.lineTo(s.x*i,s.y*o);t.stroke()}redrawCobrowse(){var t;const e=this.cobrowseCanvas.getContext("2d");if(e){e.clearRect(0,0,this.cobrowseCanvas.width,this.cobrowseCanvas.height);for(const i of((t=this.storeRef)==null?void 0:t.annotations)??[])this.drawStroke(i)}}bindCobrowsePointerEvents(){let e=!1,t=[];const i=r=>{const h=this.cobrowseCanvas.getBoundingClientRect(),d=h.width>0?(r.clientX-h.left)/h.width:0,f=h.height>0?(r.clientY-h.top)/h.height:0;return{x:Math.min(1,Math.max(0,d)),y:Math.min(1,Math.max(0,f))}},o=.006;this.cobrowseCanvas.addEventListener("pointerdown",r=>{this.cobrowseActive&&(e=!0,t=[i(r)],this.cobrowseCanvas.setPointerCapture(r.pointerId))}),this.cobrowseCanvas.addEventListener("pointermove",r=>{e&&(t.push(i(r)),this.redrawCobrowse(),this.drawStroke({points:t,color:this.cobrowseColor,width:o}))});const s=r=>{var h,d;if(e){e=!1,t.length>1&&((d=(h=this.h).onAnnotate)==null||d.call(h,{id:`an_${Date.now()}_${Math.random().toString(36).slice(2)}`,points:t,color:this.cobrowseColor,width:o})),t=[];try{this.cobrowseCanvas.releasePointerCapture(r.pointerId)}catch{}}};this.cobrowseCanvas.addEventListener("pointerup",s),this.cobrowseCanvas.addEventListener("pointercancel",s)}buildSubjectCard(e){if(this.subjectBuilt)return;const t=e.subject,i=this.cfg.subject,o=(t==null?void 0:t.title)??(i==null?void 0:i.title);if(!o)return;this.subjectBuilt=!0,this.subjectCard.replaceChildren(),this.subjectCard.append(c("div","ocw-subject-title",o)),i!=null&&i.subtitle&&this.subjectCard.append(c("div","ocw-subject-sub",i.subtitle));const s=c("div","ocw-tags");if(t)for(const[h,d]of Object.entries(t.fields))s.append(c("span","ocw-tag",`${h}: ${d}`));else for(const h of(i==null?void 0:i.tags)??[])s.append(c("span","ocw-tag",h));s.childNodes.length&&this.subjectCard.append(s);const r=(t==null?void 0:t.state)??(i==null?void 0:i.status);r&&(this.statusBadge.textContent=r,this.statusBadge.style.display="inline-flex")}chipEl(e){const t=c("button","ocw-chip",e.icon?`${e.icon} ${e.label}`:e.label);return t.dataset.actionId=e.id,t.addEventListener("click",async()=>{var i;e.confirm&&!await this.confirm(e.label)||((i=e.input)!=null&&i.length?this.openForm(e):this.h.onInvoke(e.id))}),t}confirm(e){return new Promise(t=>{const i=c("div","ocw-modal"),o=c("div","ocw-modal-card");o.append(c("div","ocw-modal-title",e)),o.append(c("div","ocw-modal-body",`Confirm “${e}”?`));const s=c("div","ocw-modal-actions"),r=c("button","ocw-modal-cancel","Cancel"),h=c("button","ocw-modal-ok","Confirm"),d=f=>{i.remove(),t(f)};r.addEventListener("click",()=>d(!1)),h.addEventListener("click",()=>d(!0)),i.addEventListener("click",f=>{f.target===i&&d(!1)}),s.append(r,h),o.append(s),i.append(o),this.root.append(i),h.focus()})}openForm(e){var h,d;this.formHost.replaceChildren();const t=c("div","ocw-form");t.append(c("div","ocw-form-title",e.icon?`${e.icon} ${e.label}`:e.label));const i=new Map;for(const f of e.input??[]){const y=c("label","ocw-form-row");if(y.append(c("span","ocw-form-lbl",f.label)),f.type==="select"&&((h=f.options)!=null&&h.length)){const l=c("select","ocw-form-input");f.required||l.append(c("option",void 0,"— select —"));for(const w of f.options){const u=c("option");u.value=w,u.textContent=w,l.append(u)}f.required&&(l.required=!0),y.append(l),i.set(f.name,l)}else{const l=c("input","ocw-form-input");l.type=f.type==="number"?"number":f.type==="date"?"datetime-local":"text",f.required&&(l.required=!0),y.append(l),i.set(f.name,l)}t.append(y)}const o=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 f={};for(const[y,l]of i){if(l.required&&!l.value){l.style.borderColor="#e5484d";return}f[y]=l.type==="number"?Number(l.value):l.value}this.formHost.replaceChildren(),this.h.onInvoke(e.id,f)}),o.append(s,r),t.append(o),this.formHost.append(t),(d=i.values().next().value)==null||d.focus()}messageEl(e,t){var l;if(e.senderRole==="system"){const w=c("div","ocw-sys");return w.textContent=e.deletedAt?"message deleted":qe(e.content),w}const i=e.senderId===this.me,o=!!e.internal,s=c("div",`ocw-row ${o?"ocw-note mine":i?"mine":"theirs"} ${e.senderRole==="bot"?"ocw-bot":""}`);!i&&!o&&s.append(c("div","ocw-dot",e.senderRole==="bot"?"🤖":"🧑"));const r=c("div"),h=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",r.append(w)}const d=c("div","ocw-bubble");let f=null;if(e.deletedAt)d.append(c("span","ocw-deleted","message deleted"));else if(e.content.kind==="attachment"){const w=e.content;if((l=w.mime)!=null&&l.startsWith("image/")){const u=document.createElement("img");u.src=w.url,u.alt=w.name??"image",u.style.cssText="max-width:220px;max-height:160px;border-radius:10px;display:block;cursor:pointer",u.addEventListener("click",()=>window.open(w.url,"_blank")),d.append(u)}else{const u=document.createElement("a");u.href=w.url,u.target="_blank",u.rel="noopener",u.style.cssText="display:flex;align-items:center;gap:8px;color:inherit;text-decoration:none",u.append(c("span",void 0,"📄"),c("span",void 0,w.name??"file")),d.append(u)}}else if(e.content.kind==="appointment"){const w=e.content,u=c("div","ocw-appt");u.append(c("div","ocw-appt-title",`📅 ${w.title}`)),u.append(c("div","ocw-appt-time",new Date(w.startIso).toLocaleString()+" – "+new Date(w.endIso).toLocaleTimeString())),w.location&&u.append(c("div","ocw-appt-loc",`📍 ${w.location}`)),w.description&&u.append(c("div","ocw-appt-desc",w.description));const C=c("div","ocw-appt-links"),v=document.createElement("a");v.href=w.googleUrl,v.target="_blank",v.rel="noopener",v.className="ocw-appt-btn",v.textContent="📅 Add to Google Calendar";const g=document.createElement("a");g.href=w.icalUrl,g.download=`${w.title}.ics`,g.className="ocw-appt-btn ocw-appt-btn-sec",g.textContent="🍎 Apple / iCal",C.append(v,g),u.append(C),d.append(u)}else f=document.createTextNode(qe(e.content)),d.append(f),e.editedAt&&d.append(c("span","ocw-edited","(edited)"));if(h.append(d),!i&&!o&&this.h.onTranslate&&e.content.kind==="text"&&!e.deletedAt&&e.seq>0&&f){const w=e.content.text;if(w.trim()){const u=c("button","ocw-translate-btn","🌐");u.type="button",u.title="Translate",u.addEventListener("click",C=>{if(C.stopPropagation(),this.showingTranslation.has(e.id)){this.showingTranslation.delete(e.id),f.textContent=w,u.textContent="🌐",u.title="Translate";return}const v=this.translationCache.get(e.id);if(v!==void 0){this.showingTranslation.add(e.id),f.textContent=v,u.textContent="↩",u.title="Show original";return}u.textContent="⏳",this.h.onTranslate(w).then(g=>{if(g===null){u.textContent="⚠️",u.title="Translation unavailable",setTimeout(()=>{u.textContent="🌐",u.title="Translate"},1500);return}this.translationCache.set(e.id,g),this.showingTranslation.add(e.id),f.textContent=g,u.textContent="↩",u.title="Show original"})}),h.append(u)}}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 u=c("button",void 0,"✏️");u.title="Edit",u.addEventListener("click",C=>{C.stopPropagation();const v=qe(e.content),g=document.createElement("textarea");g.value=v,g.rows=Math.min(4,Math.ceil(v.length/40)+1),g.style.cssText="width:100%;resize:vertical;border:1px solid var(--ocw-accent);border-radius:8px;padding:6px 10px;font:inherit;font-size:14px;background:#fff;color:#1c1b1a;box-sizing:border-box";const I=c("button","ocw-form-submit","Save");I.style.cssText="margin-top:6px;padding:5px 14px;font-size:13px";const E=c("button","ocw-form-cancel","Cancel");E.style.cssText="margin-top:6px;padding:5px 10px;font-size:13px";const L=c("div");L.style.cssText="display:flex;gap:6px;justify-content:flex-end",L.append(E,I);const T=c("div");T.append(g,L),d.replaceChildren(T),g.focus(),g.select();const H=()=>d.replaceChildren(f??document.createTextNode(v));E.addEventListener("click",H),I.addEventListener("click",()=>{const R=g.value.trim();R&&R!==v&&this.h.onEdit(e.id,R),H()}),g.addEventListener("keydown",R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),I.click()),R.key==="Escape"&&H()})}),w.append(u)}if(this.h.onDelete){const u=c("button","del","🗑");u.title="Delete",u.addEventListener("click",C=>{C.stopPropagation(),this.h.onDelete(e.id)}),w.append(u)}h.append(w)}if(r.append(h),this.h.onReact&&!e.deletedAt&&e.seq>0){const w=c("div","ocw-react-wrap"),u=c("div","ocw-react");if(e.reactions&&Object.keys(e.reactions).length)for(const[g,I]of Object.entries(e.reactions)){const E=c("button",`ocw-react-pill${I.includes(this.me)?" mine":""}`,`${g} ${I.length}`);E.addEventListener("click",()=>{var L,T;return(T=(L=this.h).onReact)==null?void 0:T.call(L,e.id,g,I.includes(this.me))}),u.append(E)}const C=c("button","ocw-react-btn","+"),v=c("div","ocw-react-picker");for(const g of Un){const I=c("button",void 0,g);I.addEventListener("click",E=>{var T,H,R,W;E.stopPropagation();const L=(H=(T=e.reactions)==null?void 0:T[g])==null?void 0:H.includes(this.me);(W=(R=this.h).onReact)==null||W.call(R,e.id,g,!!L),v.style.display="none"}),v.append(I)}v.style.display="none",C.addEventListener("click",g=>{g.stopPropagation();const I=v.style.display==="none";v.style.display=I?"flex":"none",I&&document.addEventListener("click",()=>{v.style.display="none"},{once:!0})}),u.append(C),w.append(u,v),r.append(w)}else e.reactions&&Object.keys(e.reactions).length&&r.append(c("div","ocw-react",Object.entries(e.reactions).map(([w,u])=>`${w}${u.length}`).join(" ")));const y=c("div","ocw-time ocw-meta",Mn(e.ts));if(i&&e.status){const w=c("span",`ocw-tick${e.status==="read"?" read":e.status==="delivered"?" delivered":""}`,Kn(e.status));y.append(w)}return i&&e.seq>0&&t.lastReadByOthers>=e.seq&&y.append(c("span","ocw-seen"," · Seen")),r.append(y),s.append(r),s}}function Kn(n){switch(n){case"read":return"✓✓";case"delivered":return"✓✓";case"sent":return"✓";default:return"🕓"}}const $n=20;function Fe(n,e){var d;const t=n.trim().replace(/\/+$/,""),i=(d=t.match(/^(https|http|wss|ws):\/\//))==null?void 0:d[1],o=i?i==="https"||i==="wss":!0,s=(i?t.slice(i.length+3):t).replace(/\/ws$/,""),r=e?e.trim().replace(/\/+$/,""):`${o?"https":"http"}://${s}`;return{wsUrl:`${o?"wss":"ws"}://${s}/ws`,httpBase:r}}function Dn(n){return Fe(n).httpBase}function Rn(n,e,t,i){const o=`beforeSeq=${t}&limit=${i}`;return[`${n}/conversations/${e}/messages?${o}`,`${n}/conversations/${e}/history?${o}`]}async function ut(n,e,t,i,o=$n){for(const s of Rn(n,e,i,o))try{const r=await fetch(s,{headers:{authorization:`Bearer ${t}`}});if(!r.ok)continue;const h=await r.json();return{messages:h.messages??[],hasMore:h.hasMore??!1}}catch{}return null}async function _n(n,e,t,i,o,s){const r=s?s.replace(/\/+$/,""):Dn(n),h=await ut(r,t,e,Number.MAX_SAFE_INTEGER);if(!h||(h.messages.length?(i.apply({type:"sync",conversationId:t,messages:h.messages}),i.apply({type:"history",conversationId:t,messages:[],hasMore:h.hasMore}),o.render(i)):i.apply({type:"history",conversationId:t,messages:[],hasMore:!1}),!h.hasMore))return;let d=!1;const f=async()=>{if(d||!i.hasMoreHistory)return;d=!0;const u=i.messages()[0];if(!u){d=!1;return}const C=await ut(r,t,e,u.seq);C&&(i.apply({type:"history",conversationId:t,messages:C.messages,hasMore:C.hasMore}),o.render(i)),d=!1},y=o.getScrollEl();if(!y)return;let l=!1;setTimeout(()=>{l=!0},300);const w=()=>{l&&y.scrollTop<80&&i.hasMoreHistory&&!d&&f()};y.addEventListener("scroll",w,{passive:!0}),o.setScrollCleanup(()=>y.removeEventListener("scroll",w))}const xe=new WeakMap,Te=new Map;function ft(n){return`relay-launcher::${n.profileId}::${n.subjectId??""}`}let ye=null;function jn(){if(ye&&ye.state!=="closed")return ye;try{return ye=new AudioContext,ye}catch{return null}}function wt(n){var ke,Se,xt,yt,bt;xe.has(n.el)&&(xe.get(n.el).close(),xe.delete(n.el)),n.launcher&&((ke=Te.get(ft(n)))==null||ke.close());const e=Qe();let t,i=!1;const o=n.token??n.userId??e,s=o!==e?e:void 0,{wsUrl:r,httpBase:h}=Fe(n.url,n.apiUrl);let d=new cn(o);const f=n.subjectId?`${o}::${n.subjectId}`:o,y=new gn(f);let l,w=!1,u=null,C=null,v=null,g=null;!n.launcher&&!n.el.style.height&&n.el.clientHeight===0&&(n.el.style.width=n.el.style.width||"100%",n.el.style.height="600px");for(const p of y.load())d.addOptimistic(p.clientMsgId,p.content);let I=null,E=null,L=0,T=!n.launcher;if(n.launcher){const x=(n.position??"bottom-right").includes("right");I=document.createElement("div"),I.style.cssText=`position:fixed;${x?"right:20px":"left:20px"};bottom:20px;z-index:9999;display:flex;flex-direction:column;align-items:${x?"flex-end":"flex-start"};gap:12px`;const S=document.createElement("div"),j=typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(max-width: 479px)"):null,Be=D=>{n.el.classList.toggle("ocw-fs",D),S.style.cssText=D?["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:16px","overflow:hidden","box-shadow:0 8px 40px rgba(0,0,0,.18)","display:none","flex-direction:column","background:#fff","transform-origin:bottom "+(x?"right":"left"),"transition:opacity .18s,transform .18s","opacity:0","transform:scale(.95)"].join(";")};Be((j==null?void 0:j.matches)??!1);const Le=D=>Be(D.matches);j==null||j.addEventListener("change",Le),u=j,C=Le,n.el.style.cssText="width:100%;height:100%;overflow:hidden",S.append(n.el);const Ve='<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>',Xe='<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:${n.accent??"#4F63F5"}`,"color:#fff;border:none;cursor:pointer","box-shadow:0 4px 16px rgba(0,0,0,.25)","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)"},E=document.createElement("span"),E.style.cssText="position:absolute;top:-4px;right:-4px;background:#ef4444;color:#fff;border-radius:50%;width:20px;height:20px;font-size:11px;font-weight:700;display:none;align-items:center;justify-content:center";const Me=()=>{V.innerHTML=T?Xe:Ve,V.setAttribute("aria-label",T?"Close chat":"Open chat"),V.setAttribute("aria-expanded",String(T)),V.append(E)};Me(),I.append(S,V),document.body.append(I);const Ge=`ocw-teaser-dismissed::${n.profileId}`,ze=typeof n.launcherMessage=="string"?{title:n.launcherMessage}:n.launcherMessage;let K=null;const Zn=()=>{try{return sessionStorage.getItem(Ge)==="1"}catch{return!1}},Qn='<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>',mt=()=>{const D=ze!=null&&ze.title?ze:d.launcherMessage??void 0;if(!(!!(D!=null&&D.title)&&!T&&!Zn())){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",D.title),K.style.cssText=["max-width:280px","background:#fff","border-radius:14px","box-shadow:0 6px 28px rgba(0,0,0,.16)","padding:14px 40px 14px 16px","position:relative","cursor:pointer","font-family:inherit",`align-self:${x?"flex-end":"flex-start"}`,"animation:ocw-teaser-in .22s ease-out"].join(";");const Je=document.createElement("div");if(Je.textContent=D.title,Je.style.cssText="font-size:15px;font-weight:600;color:#111;line-height:1.35",K.append(Je),D.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 Ze=document.createElement("span");Ze.innerHTML=Qn,Ze.style.cssText=`color:${n.accent??"#4F63F5"};display:inline-flex`;const kt=document.createElement("span");kt.textContent=D.subtitle,ne.append(Ze,kt),K.append(ne)}const pe=document.createElement("button");pe.type="button",pe.setAttribute("aria-label","Dismiss"),pe.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>',pe.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",pe.addEventListener("click",ne=>{ne.stopPropagation();try{sessionStorage.setItem(Ge,"1")}catch{}K&&(K.remove(),K=null)}),K.append(pe);const vt=()=>{T||(T=!0,Ye(!0),Me(),L=0,E&&(E.style.display="none"),K&&(K.remove(),K=null))};K.addEventListener("click",vt),K.addEventListener("keydown",ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),vt())}),I.insertBefore(K,V)};if(!document.getElementById("ocw-teaser-style")){const D=document.createElement("style");D.id="ocw-teaser-style",D.textContent="@keyframes ocw-teaser-in{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",document.head.append(D)}g=mt,mt();const Ye=D=>{D?(S.style.display="flex",requestAnimationFrame(()=>{S.style.opacity="1",S.style.transform="scale(1)"})):(S.style.opacity="0",S.style.transform="scale(.95)",setTimeout(()=>{T||(S.style.display="none")},180))};V.addEventListener("click",()=>{if(T=!T,Ye(T),Me(),T){L=0,E&&(E.style.display="none");try{sessionStorage.setItem(Ge,"1")}catch{}}g==null||g()}),v=D=>{D.key==="Escape"&&T&&(T=!1,Ye(!1),Me())},document.addEventListener("keydown",v)}const H=()=>{T||(L++,E&&(E.textContent=String(L),E.style.display="flex"))},R=()=>{try{const p=jn();if(!p)return;p.state==="suspended"&&p.resume().catch(()=>{});const x=p.createOscillator(),S=p.createGain();x.connect(S),S.connect(p.destination),x.frequency.setValueAtTime(880,p.currentTime),x.frequency.exponentialRampToValueAtTime(440,p.currentTime+.15),S.gain.setValueAtTime(.3,p.currentTime),S.gain.exponentialRampToValueAtTime(.001,p.currentTime+.3),x.start(),x.stop(p.currentTime+.3)}catch{}},W=[],ee=p=>{for(;W.length;){const x=W.shift();y.add({clientMsgId:x.clientMsgId,content:x.content,ts:Date.now()}),k.send({type:"send",conversationId:p,clientMsgId:x.clientMsgId,content:x.content})}};let k;const $=new En(`ocw-e2e-${n.profileId}`);let b=!1;const P=[],q=[];let me=!1;const de=(p,x)=>{$.sealText(x).then(S=>{l&&k.send({type:"send",conversationId:l,clientMsgId:p,content:S})})},Pe=(p,x,S)=>{$.sealText(x,S).then(j=>{l&&k.send({type:"send",conversationId:l,clientMsgId:p,content:j})})},m=()=>{for(;P.length;){const p=P.shift();de(p.clientMsgId,p.text)}for(;q.length;){const p=q.shift();de(p.clientMsgId,p.text)}},M=p=>{k.send({type:"fetchPrekey",targetUserId:p})},N=n.i18n??{},G=["ar","he","fa","ur"],F=typeof navigator<"u"?(navigator.language??"").slice(0,2).toLowerCase():"";G.includes(F)&&!n.el.dir&&(n.el.dir="rtl",n.el.style.fontFamily=n.el.style.fontFamily||"Tahoma,Arial,system-ui,sans-serif");const Y=new dn,U=`oc_prechat_${n.profileId}_${o.slice(-8)}`,z=new zn(n.el,o,{onSend(p){const x=`cm_${Math.random().toString(36).slice(2)}`,S={kind:"text",text:p};d.addOptimistic(x,S),z.render(d),d.e2e?$.ready?de(x,p):me?q.push({clientMsgId:x,text:p}):(P.push({clientMsgId:x,text:p}),d.assignedAgentId&&M(d.assignedAgentId)):l?(y.add({clientMsgId:x,content:S,ts:Date.now()}),k.send({type:"send",conversationId:l,clientMsgId:x,content:S})):W.push({clientMsgId:x,content:S})},async onAttach(p){if(!l)return;const x=`${h}/upload?name=${encodeURIComponent(p.name)}`,S=`cm_${Math.random().toString(36).slice(2)}`;d.addOptimistic(S,{kind:"text",text:`📎 Uploading ${p.name}…`}),z.render(d);try{const j=await fetch(x,{method:"POST",headers:{"content-type":p.type,authorization:`Bearer ${o}`},body:p});if(!j.ok)throw new Error(`Upload failed: ${j.status}`);const{url:Be,name:Le,mime:Ve,size:Xe}=await j.json();k.send({type:"send",conversationId:l,clientMsgId:S,content:{kind:"attachment",url:Be,name:Le,mime:Ve,size:Xe}})}catch(j){d.addOptimistic(S,{kind:"text",text:`⚠️ Upload failed: ${j.message}`}),z.render(d)}},onInvoke(p,x){l&&k.send({type:"invoke",conversationId:l,actionId:p,clientInvokeId:`iv_${Math.random().toString(36).slice(2)}`,...x?{inputs:x}:{}})},onTyping(p,x){l&&k.send({type:"typing",conversationId:l,isTyping:p,...x?{preview:x}:{}})},onPreChat(p){try{localStorage.setItem(U,"1")}catch{}k.send({type:"open",profileId:n.profileId,...n.subjectId?{subjectId:n.subjectId}:{},userInfo:{...p.name?{name:p.name}:{},...p.email?{email:p.email}:{},...p.phone||p.topic?{meta:{...p.phone?{phone:p.phone}:{},...p.topic?{topic:p.topic}:{}}}:{}}});const x=p.callback?`📞 Call-back requested${p.phone?`: ${p.phone}`:""}${p.topic?` — ${p.topic}`:""}`:p.topic?`Topic: ${p.topic}`:"";x&&l&&!d.e2e&&k.send({type:"send",conversationId:l,clientMsgId:`pc_${Math.random().toString(36).slice(2,12)}`,content:{kind:"text",text:x}})},onDeflectQuery(p){if(i)return;clearTimeout(t);const x=p.trim();if(x.length<3){z.hideDeflection();return}t=setTimeout(()=>{fetch(`${h}/kb/search?profileId=${encodeURIComponent(n.profileId)}&q=${encodeURIComponent(x.slice(0,200))}`).then(S=>S.ok?S.json():{articles:[]}).then(S=>z.showDeflection(S.articles??[])).catch(()=>z.hideDeflection())},350)},onReadUpTo(p){l&&k.send({type:"read",conversationId:l,seq:p})},onLoadMore(){if(!l||!d.e2e)return;const p=d.messages()[0];p&&k.send({type:"history",conversationId:l,beforeSeq:p.seq,limit:20})},onEdit(p,x){l&&k.send({type:"edit",conversationId:l,messageId:p,content:{kind:"text",text:x}})},onDelete(p){l&&k.send({type:"delete",conversationId:l,messageId:p})},onReact(p,x,S){l&&k.send({type:"react",conversationId:l,messageId:p,emoji:x,remove:S})},onCsat(p){l&&fetch(`${h}/conversations/${l}/csat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${o}`},body:JSON.stringify({score:p})}).catch(()=>{})},onAnnotate(p){l&&k.send({type:"annotate",conversationId:l,stroke:p})},onAnnotateClear(){l&&k.send({type:"annotate_clear",conversationId:l})},...n.translateLang?{async onTranslate(p){try{const x=await fetch(`${h}/translate`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify({text:p,targetLang:n.translateLang})});if(!x.ok)return null;const{translated:S}=await x.json();return S}catch{return null}}}:{},...n.onBack?{onBack:n.onBack}:{}},{...n.subject?{subject:n.subject}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.accent?{accent:n.accent}:{},...(Se=n.user)!=null&&Se.name||(xt=n.user)!=null&&xt.avatar?{userInfo:{...n.user.name?{name:n.user.name}:{},...n.user.avatar?{avatar:n.user.avatar}:{}}}:{},i18n:N});try{localStorage.getItem(U)&&z.completePreChat()}catch{}const he=n.user&&(n.user.name||n.user.email||n.user.avatar||n.user.meta)?{...n.user.name?{name:n.user.name}:{},...n.user.email?{email:n.user.email}:{},...n.user.avatar?{avatar:n.user.avatar}:{},...n.user.meta?{meta:n.user.meta}:{}}:void 0,ve={type:"open",profileId:n.profileId,...n.kind==="direct"&&n.peerId?{kind:"direct",peerId:n.peerId}:n.subjectId?{subjectId:n.subjectId}:{},...s?{linkFrom:s}:{},...he?{userInfo:he}:{},...typeof location<"u"?{pageUrl:location.href}:{},...typeof document<"u"&&document.title?{pageTitle:document.title}:{},...(yt=n.subject)!=null&&yt.title?{subjectTitle:n.subject.title}:{},...(bt=n.subject)!=null&&bt.subtitle?{subjectMeta:n.subject.subtitle}:{}};k=new hn({...n.refreshToken?{refreshToken:n.refreshToken}:{},url:r,token:o,open:ve,getCursor:()=>d.highestSeq(),onStatusChange:(p,x)=>z.setConnStatus(p,x),onFrame(p){if(Y.apply(p),p.type==="opened"){if(l=p.conversation.id,!w){w=!0;for(const x of y.load())k.send({type:"send",conversationId:l,clientMsgId:x.clientMsgId,content:x.content})}_n(r,o,l,d,z,h),W.length&&ee(l)}if(p.type==="ack"&&y.remove(p.clientMsgId),p.type==="prekeyBundle"){p.bundle&&(me=!0,$.x3dhSendTo(p.bundle).then(x=>{const S=[...P.splice(0),...q.splice(0)];for(const j of S)Pe(j.clientMsgId,j.text,x);z.render(d)}));return}if(p.type==="message"&&d.e2e){const x=Tn(p.message.content);if(x&&!$.ready){$.x3dhReceiveFrom(x.x3dhIK,x.x3dhEK,x.x3dhSPK).then(async()=>{await $.openFrame(p),d.apply(p),z.render(d)});return}}if(p.type==="peerkey"){$.onPeerKey(p.key).then(()=>{m(),z.render(d)});return}(async()=>{if(d.e2e&&await $.openFrame(p),d.apply(p),p.type==="manifest"&&(g==null||g()),p.type==="message"&&p.message.senderId!==o&&!p.message.internal&&(H(),R()),d.e2e&&l&&!b){b=!0;const x=await $.initX3DH();k.send({type:"uploadPrekeys",...x});const S=await $.begin();k.send({type:"pubkey",conversationId:l,key:S})}z.render(d)})()}}),k.connect(),z.render(d);const ae=n.launcher?ft(n):null,te={close:()=>{i=!0,clearTimeout(t),k.close(),I==null||I.remove(),z.destroy(),Y.destroy(),u&&C&&u.removeEventListener("change",C),v&&(document.removeEventListener("keydown",v),v=null),xe.delete(n.el),ae&&Te.get(ae)===te&&Te.delete(ae)}};return xe.set(n.el,te),ae&&Te.set(ae,te),te}const Oe="wss://api.paramms.com/ws";function Hn(n,e){const t=n.profileId??n.appId;if(!t)throw new Error("Relay: `profileId` is required (your chatroom id, e.g. 'p_...').");const i=n.subjectId??(n.listingId?`listing_${n.listingId}`:void 0),o=n.launcher??!0,s=n.contextTitle??n.listingTitle??n.subjectTitle,r=n.contextSubtitle??n.listingMeta??n.subjectMeta,h=n.contextStatus??n.listingStatus??n.subjectStatus,d=n.listingPrice??n.subjectPrice,f=s?{title:s,...r?{subtitle:r}:{},...d!=null?{tags:[`$${d.toLocaleString()}`]}:{},...h?{status:h}:{}}:void 0,y=n.subject??f,l=n.userName??n.name,w=n.userEmail??n.email,u=n.userAvatar??n.avatar,C=l||w||u?{...l?{name:l}:{},...w?{email:w}:{},...u?{avatar:u}:{}}:void 0,v=n.user??C,g=n.launcherMessage&&typeof n.launcherMessage=="object"?n.launcherMessage:n.launcherMessage?n.launcherSubtitle?{title:n.launcherMessage,subtitle:n.launcherSubtitle}:n.launcherMessage:void 0;return{el:e,url:n.url??Oe,profileId:t,...n.apiUrl?{apiUrl:n.apiUrl}:{},...i?{subjectId:i}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...y?{subject:y}:{},...v?{user:v}:{},...n.quickReplies?{quickReplies:n.quickReplies}:{},...n.i18n?{i18n:n.i18n}:{},...n.accent?{accent:n.accent}:{},...n.translateLang?{translateLang:n.translateLang}:{},...g?{launcherMessage:g}:{},...n.inbox&&!o?{onBack:()=>{be=!0,Ue(re)}}:{},launcher:o,position:n.position??"bottom-right"}}let Z=null,_=null,se=!1,re={},be=!1,Q=null;function Nn(n,e){const t=!e&&!!n.el;if(se&&!t&&(_.innerHTML="",_=null,se=!1),t){const i=typeof n.el=="string"?document.querySelector(n.el):n.el;i instanceof HTMLElement?(_&&_!==i&&!se&&_.remove(),_=i,se=!0):console.error(`[Relay] \`el\` ("${String(n.el)}") did not match any element — falling back to an auto-created host.`)}return(!_||!se&&!_.isConnected)&&(_=document.createElement("div"),_.id="relay-widget-root",document.body.appendChild(_),se=!1),!e&&n.height&&(_.style.height=n.height,_.style.width||(_.style.width="100%")),_}function Ue(n){try{const e=n.launcher??!0;Q==null||Q(),Q=null,Z==null||Z.close(),Z=null;const t=Nn(n,e);if(n.inbox&&!e&&be){qn(n,t);return}Z=wt(Hn(n,t))}catch(e){console.error("[Relay]",e instanceof Error?e.message:e)}}async function qn(n,e){const t=n.profileId??n.appId;if(!t){console.error("[Relay] `inbox` requires `profileId`.");return}e.innerHTML="";const i=document.createElement("div");i.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;background:#fff";const o=document.createElement("div");o.style.cssText="position:absolute;inset:0";const s=document.createElement("div");s.style.cssText="position:absolute;inset:0;display:none";const r=document.createElement("button");r.type="button",r.setAttribute("aria-label","Close"),r.textContent="✕",r.style.cssText="position:absolute;top:8px;right:8px;z-index:20;width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,.05);border:none;color:#1c1b1a;font-size:16px;line-height:1;cursor:pointer",r.onclick=()=>{be=!1,Ue(re)},i.append(o,s,r),e.appendChild(i);let h=null,d=null;Q=()=>{d==null||d.close(),h==null||h.close(),e.innerHTML=""};const{mountChatList:f}=await Promise.resolve().then(()=>Jn);if(!o.isConnected)return;const y=l=>{r.style.display="none",d==null||d.close(),d=wt({el:s,url:n.url??Oe,...n.apiUrl?{apiUrl:n.apiUrl}:{},profileId:l.profileId??t,...l.kind==="direct"&&l.peerId?{kind:"direct",peerId:l.peerId}:l.subjectId?{subjectId:l.subjectId}:{},...n.token?{token:n.token}:{},...n.refreshToken?{refreshToken:n.refreshToken}:{},...n.userId?{userId:n.userId}:{},...n.userId||n.userName||n.userEmail||n.userAvatar?{user:{...n.userName?{name:n.userName}:{},...n.userEmail?{email:n.userEmail}:{},...n.userAvatar?{avatar:n.userAvatar}:{}}}:{},...l.subjectTitle?{subject:{title:l.subjectTitle,...l.subjectMeta?{subtitle:l.subjectMeta}:{}}}:{},...n.accent?{accent:n.accent}:{},launcher:!1,onBack:()=>{d==null||d.close(),d=null,s.style.display="none",o.style.display="",r.style.display="",h==null||h.refresh()}}),o.style.display="none",s.style.display=""};h=f({el:o,url:n.url??Oe,...n.apiUrl?{apiUrl:n.apiUrl}:{},profileId:t,scope:n.inboxScope??"tenant",onSelect:y,onNewChat:()=>y({profileId:t}),...n.token?{token:n.token}:{},...n.userId?{userId:n.userId}:{},...n.accent?{accent:n.accent}:{}})}function gt(n){be=!1,re={...n},Ue(re)}function Fn(n){re={...re,...n},Ue(re)}function On(){Q==null||Q(),Q=null,Z==null||Z.close(),Z=null,_&&!se&&_.remove(),_=null,se=!1,be=!1,re={}}function We(n,e){switch(n){case"boot":gt(e??{});break;case"update":case"identify":Fn(e??{});break;case"shutdown":On();break;default:console.warn("[Relay] unknown command:",n)}}function Wn(){if(typeof document>"u")return null;const n=document.querySelector("script[data-relay-app]")??document.querySelector("script[data-relay-profile-id]"),e=n==null?void 0:n.dataset,t=(e==null?void 0:e.relayApp)??(e==null?void 0:e.relayProfileId);if(!t)return null;const i={profileId:t};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.relayUrl&&(i.url=e.relayUrl);const o=e.relayPosition;(o==="bottom-left"||o==="bottom-right")&&(i.position=o),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);const s=e.relayInboxScope;return(s==="tenant"||s==="profile")&&(i.inboxScope=s),i}if(typeof window<"u"){const n=window,e=n.Relay&&n.Relay.q?n.Relay.q:[];n.Relay=We;let t=!1;for(const i of e){const[o,s]=i;o==="boot"&&(t=!0),We(o,s)}if(!t){const i=n.relaySettings??Wn();i&>(i)}}function Vn(n){const e=Math.floor((Date.now()-n)/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 t=Math.floor(e/86400);if(t<=7)return`${t}d`;try{return new Date(n).toLocaleDateString(void 0,{month:"short",day:"numeric"})}catch{return`${t}d`}}const Xn='<svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z" fill="currentColor" fill-opacity="0.12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function A(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}const Gn=`
|
|
190
|
+
.ocl { --ocl-accent:#f5713c; --ocl-bg:#f3efe9; --ocl-card:#fff; --ocl-line:#ececec; --ocl-ink:#1c1b1a; --ocl-mut:#9b9690;
|
|
191
|
+
display:flex; flex-direction:column; height:100%; background:var(--ocl-bg);
|
|
192
|
+
font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif; color:var(--ocl-ink); overflow:hidden; }
|
|
193
|
+
.ocl-head { display:flex; align-items:center; padding:14px 16px 10px; background:var(--ocl-card); border-bottom:1px solid var(--ocl-line); }
|
|
194
|
+
.ocl-title { flex:1; display:flex; align-items:center; color:var(--ocl-accent); }
|
|
195
|
+
.ocl-title svg { width:24px; height:24px; display:block; }
|
|
196
|
+
.ocl-retry { margin-top:14px; border:none; background:var(--ocl-accent); color:#fff; border-radius:20px; padding:8px 20px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
|
|
197
|
+
.ocl-search-wrap { padding:8px 12px; background:var(--ocl-card); border-bottom:1px solid var(--ocl-line); }
|
|
198
|
+
.ocl-search { width:100%; box-sizing:border-box; border:none; background:var(--ocl-bg); border-radius:20px; padding:8px 14px; font:inherit; font-size:14px; outline:none; }
|
|
199
|
+
.ocl-body { flex:1; overflow-y:auto; }
|
|
200
|
+
.ocl-section { padding:6px 16px 4px; font-size:11px; font-weight:700; color:var(--ocl-mut); text-transform:uppercase; letter-spacing:.5px; background:var(--ocl-bg); }
|
|
201
|
+
.ocl-empty { padding:40px 20px; text-align:center; color:var(--ocl-mut); font-size:14px; }
|
|
202
|
+
.ocl-row { display:flex; align-items:center; gap:12px; padding:11px 16px; background:var(--ocl-card); border:none; width:100%; text-align:left; cursor:pointer; border-bottom:1px solid var(--ocl-line); transition:background .1s; }
|
|
203
|
+
.ocl-row:hover { background:#f7f5f2; }
|
|
204
|
+
.ocl-row.unread { background:var(--ocl-card); }
|
|
205
|
+
.ocl-av { width:46px; height:46px; border-radius:50%; background:var(--ocl-accent); color:#fff; font-size:18px; font-weight:700; display:flex; align-items:center; justify-content:center; flex:none; position:relative; }
|
|
206
|
+
.ocl-dot { position:absolute; bottom:1px; right:1px; width:12px; height:12px; border-radius:50%; border:2px solid var(--ocl-card); background:var(--ocl-mut); }
|
|
207
|
+
.ocl-dot.open { background:#22c55e; }
|
|
208
|
+
.ocl-dot.waiting { background:#f59e0b; }
|
|
209
|
+
.ocl-info { flex:1; min-width:0; }
|
|
210
|
+
.ocl-name { font-size:15px; font-weight:600; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; margin-bottom:2px; }
|
|
211
|
+
.ocl-row.unread .ocl-name { font-weight:700; }
|
|
212
|
+
.ocl-preview { font-size:13px; color:var(--ocl-mut); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
|
|
213
|
+
.ocl-row.unread .ocl-preview { color:var(--ocl-ink); }
|
|
214
|
+
.ocl-right { display:flex; flex-direction:column; align-items:flex-end; gap:4px; flex:none; }
|
|
215
|
+
.ocl-time { font-size:11px; color:var(--ocl-mut); }
|
|
216
|
+
.ocl-row.unread .ocl-time { color:var(--ocl-accent); font-weight:600; }
|
|
217
|
+
.ocl-badge { background:var(--ocl-accent); color:#fff; border-radius:999px; font-size:11px; font-weight:700; min-width:20px; height:20px; padding:0 5px; display:flex; align-items:center; justify-content:center; }
|
|
218
|
+
.ocl-spinner { padding:24px; text-align:center; color:var(--ocl-mut); font-size:13px; }
|
|
219
|
+
.ocl-compose { border:none; background:var(--ocl-bg); color:var(--ocl-ink); width:32px; height:32px; border-radius:50%; font-size:15px; cursor:pointer; }
|
|
220
|
+
.ocl-compose:hover { background:var(--ocl-line); }
|
|
221
|
+
.ocl-start { margin-top:12px; border:none; background:var(--ocl-accent); color:#fff; border-radius:20px; padding:8px 18px; font:inherit; font-size:13px; font-weight:600; cursor:pointer; }
|
|
222
|
+
/* Compact sizing keyed on the LIST'S OWN width (ResizeObserver toggles
|
|
223
|
+
* .ocl-compact below 400px) — covers phones and narrow desktop embeds alike.
|
|
224
|
+
* Search must be ≥16px in compact or iOS zooms the page on focus. */
|
|
225
|
+
.ocl-compact .ocl-row { padding:13px 14px; }
|
|
226
|
+
.ocl-compact .ocl-search { font-size:16px; }
|
|
227
|
+
.ocl-compact .ocl-compose { width:36px; height:36px; }
|
|
228
|
+
`;function Yn(n){const e=n.token??n.userId??Qe(),{httpBase:t,wsUrl:i}=Fe(n.url,n.apiUrl),o=n.i18n??{},s=n.accent??"#4F63F5";if(!document.getElementById("ocl-styles")){const m=document.createElement("style");m.id="ocl-styles",m.textContent=Gn,document.head.append(m)}const r=A("div","ocl");r.style.setProperty("--ocl-accent",s);const h=A("div","ocl-head"),d=A("span","ocl-title");if(d.setAttribute("role","img"),d.setAttribute("aria-label",o.title??"Messages"),d.innerHTML=Xn,h.append(d),n.onNewChat){const m=A("button","ocl-compose","✎");m.title=o.newChat??"New conversation",m.addEventListener("click",()=>n.onNewChat()),h.append(m)}const f=A("div","ocl-search-wrap"),y=A("input","ocl-search");y.placeholder=o.search??"🔍 Search",y.type="search",f.append(y);const l=A("div","ocl-body");l.append(A("div","ocl-spinner","Loading…")),r.append(h,f,l),n.el.replaceChildren(r);const w=m=>{r.classList.toggle("ocl-compact",m>0&&m<400)};w(r.clientWidth);let u=null;if(typeof ResizeObserver<"u"&&(u=new ResizeObserver(m=>{var M;return w(((M=m[0])==null?void 0:M.contentRect.width)??r.clientWidth)}),u.observe(r)),!n.profileId&&!n.tenantId)throw new Error("[relay chatlist] provide profileId or tenantId");let C;const v=`ocl_seen_${n.profileId??`t_${n.tenantId}`}_${(n.userId??e).slice(-8)}`;let g={};try{g=JSON.parse(localStorage.getItem(v)??"{}")}catch{}const I=()=>{try{localStorage.setItem(v,JSON.stringify(g))}catch{}};let E=[],L=!1;const T=async()=>{const m=n.profileId?`profileId=${encodeURIComponent(n.profileId)}${n.scope==="tenant"?"&scope=tenant":""}`:`tenantId=${encodeURIComponent(n.tenantId)}`,M=`${t}/conversations/mine?${m}`,N={authorization:`Bearer ${e}`};let G;try{G=await fetch(M,{headers:N})}catch{G=await fetch(M,{headers:N})}if(!G.ok)return[];const F=await G.json();return F.defaultProfileId&&(C=F.defaultProfileId),(F.conversations??[]).sort((Y,U)=>U.updatedAt-Y.updatedAt)},H=(m,M)=>{if(L)return;const N=M?m.filter(U=>R(U).toLowerCase().includes(M)||(U.lastMessage??"").toLowerCase().includes(M)):m;if(l.replaceChildren(),!N.length){const U=A("div","ocl-empty",M?"No results.":o.empty??"No conversations yet.");if(!M&&n.onNewChat){U.append(A("br"));const z=A("button","ocl-start",o.newChat??"Start a conversation");z.addEventListener("click",()=>n.onNewChat()),U.append(z)}l.append(U);return}const G=U=>(U.lastSeq??0)>(g[U.id]??0),F=N.filter(G),Y=N.filter(U=>!G(U));if(F.length){l.append(A("div","ocl-section",`${o.unread??"Unread"} (${F.length})`));for(const U of F)l.append(W(U,G(U)))}if(Y.length){l.append(A("div","ocl-section",F.length?o.all??"All conversations":""));for(const U of Y)l.append(W(U,!1))}},R=m=>m.subjectTitle??(m.kind==="direct"?m.peerId??"Direct message":"General enquiry"),W=(m,M)=>{var ke;const N=R(m),G=(((ke=N.match(new RegExp("\\p{L}","u")))==null?void 0:ke[0])??N.trim()[0]??"?").toUpperCase(),F=m.lastSeq??0,Y=M?Math.max(1,F-(g[m.id]??0)):0,U=A("button",`ocl-row${M?" unread":""}`),z=A("div","ocl-av",G),he=A("div","ocl-dot");m.state==="open"?he.classList.add("open"):m.state==="awaiting_staff"&&he.classList.add("waiting"),z.append(he),U.append(z);const ve=A("div","ocl-info");ve.append(A("div","ocl-name",N));const ae={open:"Open",awaiting_staff:"Waiting for reply…",resolved:"Resolved ✓",closed:"Closed"};ve.append(A("div","ocl-preview",m.lastMessage??ae[m.state]??m.state)),U.append(ve);const te=A("div","ocl-right");return te.append(A("div","ocl-time",Vn(m.updatedAt))),Y>0&&te.append(A("div","ocl-badge",String(Y>99?"99+":Y))),U.append(te),U.addEventListener("click",()=>{var Se;F>0&&(g[m.id]=F,I()),U.classList.remove("unread"),(Se=te.querySelector(".ocl-badge"))==null||Se.remove(),n.onSelect(m)}),U},ee=()=>{L||T().then(m=>{L||(E=m,H(m,y.value.trim().toLowerCase()))}).catch(m=>{if(L)return;console.error(`[chat-widget] failed to load conversations from ${t}/conversations/mine — check the apiUrl/CORS config.`,m);const M=A("div","ocl-empty",o.error??"Could not load conversations.");M.append(A("br"));const N=A("button","ocl-retry",o.retry??"Retry");N.addEventListener("click",()=>{l.replaceChildren(A("div","ocl-spinner","Loading…")),ee()}),M.append(N),l.replaceChildren(M)})};y.addEventListener("input",()=>H(E,y.value.trim().toLowerCase())),ee();let k=null,$,b,P=0,q=!1;const me=()=>{b||(b=setTimeout(()=>{b=void 0,ee()},300))},de=()=>{if(!L){try{k=new WebSocket(i)}catch{Pe();return}k.binaryType="arraybuffer",k.onopen=()=>{P=0,k.send(He({type:"auth",token:e})),k.send(He({type:"subscribe_inbox"})),q&&me(),q=!0},k.onmessage=m=>{const M=st(new Uint8Array(m.data));M&&M.type==="inbox_event"&&me()},k.onclose=()=>{k=null,Pe()},k.onerror=()=>{try{k==null||k.close()}catch{}}}},Pe=()=>{if(L||$)return;const m=Math.min(15e3,500*2**P++)+Math.random()*250;$=setTimeout(()=>{$=void 0,de()},m)};return de(),{refresh:ee,close(){L=!0,$&&clearTimeout($),b&&clearTimeout(b),u==null||u.disconnect(),u=null;try{k==null||k.close()}catch{}k=null,n.el.replaceChildren()},defaultProfileId(){return n.profileId??C}}}const Jn=Object.freeze(Object.defineProperty({__proto__:null,mountChatList:Yn},Symbol.toStringTag,{value:"Module"}));return J.Relay=We,Object.defineProperty(J,Symbol.toStringTag,{value:"Module"}),J}({});
|
|
195
229
|
//# sourceMappingURL=embed.js.map
|