@aikaara/chat-sdk 1.1.18 → 1.1.19

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.
@@ -1468,4 +1468,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1468
1468
  }
1469
1469
  .save-btn:hover { filter: brightness(1.07); }
1470
1470
  .save-btn:active { filter: brightness(0.95); }
1471
- `}}function St(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ye(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function oc(){const l=[["aikaara-chat-widget",Ul],["aikaara-chat-bubble",Bl],["aikaara-chat-header",Dl],["aikaara-message-list",$l],["aikaara-message-bubble",Hl],["aikaara-chat-input",Wl],["aikaara-typing-indicator",zl],["aikaara-streaming-message",Vl],["aikaara-error-banner",Gl],["aikaara-template-renderer",Yl],["aikaara-system-pill",Ql],["aikaara-option-list",Jl],["aikaara-submit-action",Xl],["aikaara-modal-action",Zl],["aikaara-chat",ec],["aikaara-link-modal",tc],["aikaara-compare-plans",rc],["aikaara-smart-edit-modal",nc],["aikaara-schema-form",ic]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}oc();function lr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function qs(l){try{const e=l.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Zt(l){return typeof l=="function"?await l():l}class sc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=qs(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Zt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=lr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=lr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=lr(a,this.descriptor.fullNamePath??"data.fullName"),g=lr(a,this.descriptor.userPath??"data.userId"),b=qs(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ac(l){const e={};for(const t of l.spec){const r=await Wd(t,l.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function Wd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return zd(t);case"localStorage":return cr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return cr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return cr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return cr(()=>document.querySelector(`meta[name="${Vd(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function zd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function cr(l){try{return l()}catch{return}}function Vd(l){return l.replace(/["\\]/g,"\\$&")}const Gd=1800;class lc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await ac({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Gd;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Kd=3e4,Yd=2e3,Qd=100;async function cc(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Jd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Xd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=nf(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Kd;return{token:await rf({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Zd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=ef(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Qd,o=await tf(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class uc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await cc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Jd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function Xd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Zd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function ef(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=hc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function tf(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=hc(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function rf(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function nf(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function hc(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function of(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const sf="aikaara_chat:requestId";function vo(l,e){return`${sf}:${l}:${e}`}function dc(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function af(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function lf(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function cf(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Zt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&uf(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function uf(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function fc(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function pc(l,e){return l.replace("{projectId}",e).replace("{uuid}",of().replace(/-/g,""))}function mc(l){const e=l._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Kl(r)))}async function gc(l){const e={...l.config??(l.configUrl?await fc(l.configUrl,l.configHeaders):{}),...l.overrides??{}};mc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:dc(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??pc(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&af(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?yo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?Ml({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:l.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function hf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function bc(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await fc(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(mc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Zt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new uc({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new lc({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await cf(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new sc(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?dc(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?pc(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Zt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?Pl({...x,authHeader:v}):x&&x.mode==="direct"?yo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await gc({container:hf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Zt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}exports.ActionCableClient=en;exports.AikaaraChat=ec;exports.AikaaraChatBubble=Bl;exports.AikaaraChatClient=Ol;exports.AikaaraChatHeader=Dl;exports.AikaaraChatInput=Wl;exports.AikaaraChatWidget=Ul;exports.AikaaraComparePlans=rc;exports.AikaaraErrorBanner=Gl;exports.AikaaraLinkModal=tc;exports.AikaaraMessageBubble=Hl;exports.AikaaraMessageList=$l;exports.AikaaraModalAction=Zl;exports.AikaaraOptionList=Jl;exports.AikaaraSchemaForm=ic;exports.AikaaraSmartEditModal=nc;exports.AikaaraStreamingMessage=Vl;exports.AikaaraSubmitAction=Xl;exports.AikaaraSystemPill=Ql;exports.AikaaraTemplateRenderer=Yl;exports.AikaaraTypingIndicator=zl;exports.ApiClient=zs;exports.ChannelSubscription=Hs;exports.ConnectionManager=Ws;exports.ConversationManager=Ks;exports.EventEmitter=to;exports.MessageStore=Vs;exports.SessionAuthAdapter=sc;exports.SsoExchangeAdapter=lc;exports.TiledeskTransport=Al;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=uc;exports.clearPersistedConversationId=lf;exports.collectSsoCredentials=ac;exports.createFetchUploadAdapter=yo;exports.createPresigned3StepUploadAdapter=Pl;exports.createTiledeskHistoryAdapter=Ml;exports.discoverToken=cc;exports.extractTiledeskFileEnvelope=Cl;exports.inferTiledeskRole=Tl;exports.isTiledeskSelfEcho=Il;exports.mount=gc;exports.mountFromSlug=bc;exports.parseTiledeskTemplate=bo;exports.registerComponents=oc;
1471
+ `}}function St(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Ye(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function oc(){const l=[["aikaara-chat-widget",Ul],["aikaara-chat-bubble",Bl],["aikaara-chat-header",Dl],["aikaara-message-list",$l],["aikaara-message-bubble",Hl],["aikaara-chat-input",Wl],["aikaara-typing-indicator",zl],["aikaara-streaming-message",Vl],["aikaara-error-banner",Gl],["aikaara-template-renderer",Yl],["aikaara-system-pill",Ql],["aikaara-option-list",Jl],["aikaara-submit-action",Xl],["aikaara-modal-action",Zl],["aikaara-chat",ec],["aikaara-link-modal",tc],["aikaara-compare-plans",rc],["aikaara-smart-edit-modal",nc],["aikaara-schema-form",ic]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}oc();function lr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function qs(l){try{const e=l.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Zt(l){return typeof l=="function"?await l():l}class sc{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=qs(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Zt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=lr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=lr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=lr(a,this.descriptor.fullNamePath??"data.fullName"),g=lr(a,this.descriptor.userPath??"data.userId"),b=qs(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ac(l){const e={};for(const t of l.spec){const r=await Wd(t,l.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function Wd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return zd(t);case"localStorage":return cr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return cr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return cr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return cr(()=>document.querySelector(`meta[name="${Vd(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function zd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function cr(l){try{return l()}catch{return}}function Vd(l){return l.replace(/["\\]/g,"\\$&")}const Gd=1800;class lc{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await ac({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Gd;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Kd=3e4,Yd=2e3,Qd=100;async function cc(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Jd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Xd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=nf(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Kd;return{token:await rf({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Zd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=ef(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Qd,o=await tf(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class uc{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await cc(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function Jd(l){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===l)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Xd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Zd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function ef(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=hc(n,t);return typeof o=="string"?o:void 0}catch{return}}async function tf(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=hc(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function rf(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function nf(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function hc(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function of(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const sf="aikaara_chat:requestId";function vo(l,e){return`${sf}:${l}:${e}`}function dc(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function af(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function lf(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function cf(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Zt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&uf(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function uf(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function fc(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function pc(l,e){return l.replace("{projectId}",e).replace("{uuid}",of().replace(/-/g,""))}function mc(l){const e=l._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>Kl(r)))}async function gc(l){const e={...l.config??(l.configUrl?await fc(l.configUrl,l.configHeaders):{}),...l.overrides??{}};mc(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:dc(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??pc(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&af(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?yo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?Ml({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:l.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function hf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function bc(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await fc(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(mc(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Zt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new uc({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new lc({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await cf(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new sc(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?dc(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?pc(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Zt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?Pl({...x,authHeader:v}):x&&x.mode==="direct"?yo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await gc({container:hf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Zt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}exports.ActionCableClient=en;exports.AikaaraChat=ec;exports.AikaaraChatBubble=Bl;exports.AikaaraChatClient=Ol;exports.AikaaraChatHeader=Dl;exports.AikaaraChatInput=Wl;exports.AikaaraChatWidget=Ul;exports.AikaaraComparePlans=rc;exports.AikaaraErrorBanner=Gl;exports.AikaaraLinkModal=tc;exports.AikaaraMessageBubble=Hl;exports.AikaaraMessageList=$l;exports.AikaaraModalAction=Zl;exports.AikaaraOptionList=Jl;exports.AikaaraSchemaForm=ic;exports.AikaaraSmartEditModal=nc;exports.AikaaraStreamingMessage=Vl;exports.AikaaraSubmitAction=Xl;exports.AikaaraSystemPill=Ql;exports.AikaaraTemplateRenderer=Yl;exports.AikaaraTypingIndicator=zl;exports.ApiClient=zs;exports.ChannelSubscription=Hs;exports.ConnectionManager=Ws;exports.ConversationManager=Ks;exports.EventEmitter=to;exports.MessageStore=Vs;exports.SessionAuthAdapter=sc;exports.SsoExchangeAdapter=lc;exports.TiledeskTransport=Al;exports.TokenDiscoveryError=Ke;exports.TokenDiscoveryReader=uc;exports.clearPersistedConversationId=lf;exports.collectSsoCredentials=ac;exports.createFetchUploadAdapter=yo;exports.createPresigned3StepUploadAdapter=Pl;exports.createTiledeskHistoryAdapter=Ml;exports.discoverToken=cc;exports.extractTiledeskFileEnvelope=Cl;exports.inferTiledeskRole=Tl;exports.isTiledeskSelfEcho=Il;exports.mount=gc;exports.mountFromSlug=bc;exports.parseTiledeskTemplate=bo;exports.registerComponents=oc;
@@ -16349,7 +16349,13 @@ class Ye extends Error {
16349
16349
  function Yd(l) {
16350
16350
  if (!(typeof window > "u"))
16351
16351
  try {
16352
- return new URL(window.location.href).searchParams.get(l) ?? void 0;
16352
+ const e = window.location.search.slice(1);
16353
+ for (const t of e.split("&")) {
16354
+ const r = t.indexOf("=");
16355
+ if (r !== -1 && decodeURIComponent(t.slice(0, r)) === l)
16356
+ return decodeURIComponent(t.slice(r + 1));
16357
+ }
16358
+ return;
16353
16359
  } catch {
16354
16360
  return;
16355
16361
  }
@@ -1468,7 +1468,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1468
1468
  }
1469
1469
  .save-btn:hover { filter: brightness(1.07); }
1470
1470
  .save-btn:active { filter: brightness(0.95); }
1471
- `}}function Ot(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",bd],["aikaara-system-pill",_d],["aikaara-option-list",kd],["aikaara-submit-action",xd],["aikaara-modal-action",Ed],["aikaara-chat",Ad],["aikaara-link-modal",Id],["aikaara-compare-plans",Od],["aikaara-smart-edit-modal",Pd],["aikaara-schema-form",Ld]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Fl(l){try{const e=l.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Xt(l){return typeof l=="function"?await l():l}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Fl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=Hr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=Hr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),b=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await jd(t,l.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function jd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Nd(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${Ud(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function Nd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Wr(l){try{return l()}catch{return}}function Ud(l){return l.replace(/["\\]/g,"\\$&")}const Bd=1800;class Hl{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await ql({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Bd;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Dd=3e4,Fd=2e3,$d=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=qd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Hd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=Kd(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dd;return{token:await Gd({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Wd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=zd(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Fd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:$d,o=await Vd(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function qd(l){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(l)??void 0}catch{return}}function Hd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Wd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function zd(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=Vl(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Vd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Vl(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Gd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Kd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function Yd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const Qd="aikaara_chat:requestId";function vo(l,e){return`${Qd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Jd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Xd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Zd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Xt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&ef(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function ef(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Yd().replace(/-/g,""))}function Ql(l){const e=l._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:Gl(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??Yl(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&Jd(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:l.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function tf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new zl({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new Hl({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await Zd(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new $l(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?Gl(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?Yl(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Xt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?gl({...x,authHeader:v}):x&&x.mode==="direct"?uo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Jl({container:tf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Xt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}function rf(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,i]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(i,String(n))}return e.configure(l),document.body.appendChild(e),e}function nf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1471
+ `}}function Ot(l){return l.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function Qe(l){return l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function yo(){const l=[["aikaara-chat-widget",xl],["aikaara-chat-bubble",Sl],["aikaara-chat-header",El],["aikaara-message-list",Il],["aikaara-message-bubble",Cl],["aikaara-chat-input",Pl],["aikaara-typing-indicator",Ml],["aikaara-streaming-message",Rl],["aikaara-error-banner",Ll],["aikaara-template-renderer",bd],["aikaara-system-pill",_d],["aikaara-option-list",kd],["aikaara-submit-action",xd],["aikaara-modal-action",Ed],["aikaara-chat",Ad],["aikaara-link-modal",Id],["aikaara-compare-plans",Od],["aikaara-smart-edit-modal",Pd],["aikaara-schema-form",Ld]];for(const[e,t]of l)customElements.get(e)||customElements.define(e,t)}yo();function Hr(l,e,t=""){if(!e)return t;const r=e.split(".");let i=l;for(const n of r)if(i&&typeof i=="object"&&n in i)i=i[n];else return t;return typeof i=="string"?i:t}function Fl(l){try{const e=l.split(".")[1];if(!e)return 0;const t=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return typeof t.exp=="number"?t.exp*1e3:0}catch{return 0}}async function Xt(l){return typeof l=="function"?await l():l}class $l{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}prime(e,t={}){if(!e)return;const r=Fl(e)||Date.now()+3600*1e3;this.cache={token:e,requestId:t.requestId??this.cache?.requestId??"",fullName:t.fullName??this.cache?.fullName??"",userId:t.userId??this.cache?.userId??"",expiresAt:r}}async get(){const e=this.descriptor.expiryBufferMs??6e4,t=Date.now();return this.cache&&this.cache.expiresAt>t+e?this.cache:this.inflight?this.inflight:(this.inflight=this.fetchOnce().finally(()=>{this.inflight=null}),this.inflight)}async fetchOnce(){const e=await Xt(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",i={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",o={method:n,headers:i};n==="POST"&&(i["content-type"]="application/json",o.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,o);if(!s.ok){const k=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${k.slice(0,200)}`)}const a=await s.json().catch(()=>({})),c=Hr(a,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,h=u?c.replace(new RegExp(`^${u}`,"i"),"").trim():c;if(!h)throw new Error("Session auth response missing token");const p=Hr(a,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p||"",f=Hr(a,this.descriptor.fullNamePath??"data.fullName"),g=Hr(a,this.descriptor.userPath??"data.userId"),b=Fl(h)||Date.now()+3600*1e3;return this.cache={token:h,requestId:y,fullName:f,userId:g,expiresAt:b},this.cache}}async function ql(l){const e={};for(const t of l.spec){const r=await jd(t,l.providers);if(r!==void 0&&r!=="")e[t.name]=r;else{if(t.required)throw new Error(`[aikaara-chat-sdk] SSO credential "${t.name}" is required but ${t.source}`+(t.key?`[${t.key}]`:"")+" returned no value");t.default!==void 0&&(e[t.name]=t.default)}}return e}async function jd(l,e){const t=l.key??l.name;switch(l.source){case"cookie":return Nd(t);case"localStorage":return Wr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Wr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Wr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Wr(()=>document.querySelector(`meta[name="${Ud(t)}"]`)?.content??void 0);case"callback":{const r=e?.[l.name];if(!r)return;const i=await r();return typeof i=="string"?i:void 0}default:return}}function Nd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function Wr(l){try{return l()}catch{return}}function Ud(l){return l.replace(/["\\]/g,"\\$&")}const Bd=1800;class Hl{constructor(e){this.opts=e,this.cache=this.loadCache()}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null,this.clearCache()}async get(e=!1){if(!e){const t=this.cache;if(t&&(!t.expiresAt||t.expiresAt>Date.now()))return t}return this.inflight?this.inflight:(this.inflight=this.exchange().finally(()=>{this.inflight=null}),this.inflight)}async exchange(){if(!this.opts.descriptor.collect||this.opts.descriptor.collect.length===0)throw new Error("[aikaara-chat-sdk] SsoExchangeAdapter.exchange() requires descriptor.sso.collect; v2 partner-token flow should be handled by TokenDiscoveryReader instead.");const e=await ql({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),r={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(r["X-Api-Key"]=this.opts.descriptor.apiKey);const i=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!i)throw new Error("[aikaara-chat-sdk] SSO exchange URL not resolved — set descriptor.sso.exchangeEndpoint or pass `exchangeUrl` (mountFromSlug derives it from configBase + slug).");const n=await fetch(i,{method:"POST",headers:r,body:t});if(!n.ok){const h=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${h.slice(0,240)}`)}const s=(await n.json().catch(()=>({}))).user??{},a=String(s.ext_uid??s.extUid??""),c=String(s.token??s.user_token??s.userToken??"");if(!a)throw new Error("SSO exchange response missing user.ext_uid");if(!c)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:a,userToken:c,email:typeof s.email=="string"?s.email:void 0,displayName:typeof s.display_name=="string"?s.display_name:typeof s.displayName=="string"?s.displayName:void 0,properties:s.properties&&typeof s.properties=="object"?s.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Bd;if(!(!this.opts.descriptor.cacheKey||e<=0))return Date.now()+e*1e3}loadCache(){const e=this.opts.descriptor.cacheKey;if(!e)return null;try{const t=window.localStorage.getItem(e);if(!t)return null;const r=JSON.parse(t);return r.expiresAt&&r.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):r}catch{return null}}persistCache(e){const t=this.opts.descriptor.cacheKey;if(t)try{window.localStorage.setItem(t,JSON.stringify(e))}catch{}}clearCache(){const e=this.opts.descriptor.cacheKey;if(e)try{window.localStorage.removeItem(e)}catch{}}}const Dd=3e4,Fd=2e3,$d=100;async function Wl(l){const{descriptor:e}=l,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!l.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:l.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=qd(r);if(!i)throw new Ke("query",`?${r}= not present`);return{token:i,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",i=Hd(r);if(!i)throw new Ke("hash",`#${r}= not present`);return{token:i,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",i=typeof t.key=="string"&&t.key?t.key:"token",n=Kd(typeof t.origins=="string"?t.origins:""),o=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Dd;return{token:await Gd({type:r,key:i,origins:n,timeoutMs:o}),source:"postmsg"}}case"cookie":{const r=typeof t.name=="string"&&t.name?t.name:"";if(!r)throw new Ke("cookie","cookie.name not configured");const i=Wd(r);if(!i)throw new Ke("cookie",`cookie "${r}" not set`);return{token:i,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",i=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!i)throw new Ke("storage","storage.key not configured");const o=zd(r,i,n);if(!o)throw new Ke("storage",`${r}Storage["${i}"] not set`);return{token:o,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Fd,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:$d,o=await Vd(r,i,n);if(!o)throw new Ke("global",`window.${r} not present`);return{token:o,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class zl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Wl(this.opts);return this.cached=e,e}async refresh(){return this.opts.descriptor.tokenSource==="init"?this.cached?this.cached:this.get():(this.cached=null,this.get())}}class Ke extends Error{constructor(e,t){super(`[aikaara-chat-sdk] token-discovery (${e}): ${t}`),this.source=e,this.name="TokenDiscoveryError"}}function qd(l){if(!(typeof window>"u"))try{const e=window.location.search.slice(1);for(const t of e.split("&")){const r=t.indexOf("=");if(r!==-1&&decodeURIComponent(t.slice(0,r))===l)return decodeURIComponent(t.slice(r+1))}return}catch{return}}function Hd(l){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(l)??void 0}catch{return}}function Wd(l){if(typeof document>"u")return;const e=encodeURIComponent(l),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const i=r.indexOf("=");if(i===-1)continue;const n=r.slice(0,i);if(n===l||n===e)try{return decodeURIComponent(r.slice(i+1))}catch{return r.slice(i+1)}}}function zd(l,e,t){if(!(typeof window>"u"))try{const i=(l==="session"?window.sessionStorage:window.localStorage).getItem(e);if(i==null)return;if(!t)return i;let n;try{n=JSON.parse(i)}catch{return i}const o=Vl(n,t);return typeof o=="string"?o:void 0}catch{return}}async function Vd(l,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const i=Vl(window,l);if(typeof i=="string"&&i.length>0)return i;if(typeof i=="function")try{const n=i();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function Gd(l){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(i)},i=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${l.timeoutMs}ms`))},l.timeoutMs),n=o=>{if(l.origins.length>0&&!l.origins.includes(o.origin))return;const s=o.data;if(!s||typeof s!="object")return;const a=s;if(l.type&&a.type!==l.type)return;const c=a[l.key];typeof c=="string"&&c.length>0&&(r(),e(c))};window.addEventListener("message",n)})}function Kd(l){return l?l.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Vl(l,e){if(!e)return l;const t=e.split(".").filter(Boolean);let r=l;for(const i of t)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function Yd(){const l=typeof crypto<"u"?crypto:null;if(l?.randomUUID)return l.randomUUID();if(l?.getRandomValues){const e=new Uint8Array(16);l.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}return"xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}const Qd="aikaara_chat:requestId";function vo(l,e){return`${Qd}:${l}:${e}`}function Gl(l,e){try{return localStorage.getItem(vo(l,e))}catch{return null}}function Jd(l,e,t){try{localStorage.setItem(vo(l,e),t)}catch{}}function Xd(l,e){try{localStorage.removeItem(vo(l,e))}catch{}}async function Zd(l,e){console.log("[aikaara-chat-sdk] preflight running",l.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[a,c]of Object.entries(e.identity))typeof c=="string"&&(t[a]=c);const r=a=>a.replace(/\{(\w+)\}/g,(c,u)=>u in t?t[u]:""),i=a=>{if(typeof a=="string")return r(a);if(Array.isArray(a))return a.map(i);if(a&&typeof a=="object"){const c={};for(const[u,h]of Object.entries(a))c[u]=i(h);return c}return a},n=await Xt(e.sessionToken),o={},s=[800,1500,3e3,5e3,8e3];for(let a=0;a<l.length;a++){const c=l[a],u=r(c.url),h=c.method??(c.body?"POST":"GET"),p={accept:"application/json",...c.headers??{}};if((c.authHeader??"session")==="session"){const m=c.authHeaderTemplate??"Bearer {token}";p.authorization=m.replace("{token}",n)}const y={method:h,headers:p};c.body&&(p["content-type"]="application/json",y.body=JSON.stringify(i(c.body)));let f=0,g="",b=0,k=null;for(;;)try{const m=await fetch(u,y);if(m.ok){k=m;break}if(f=m.status,g=await m.text().catch(()=>""),b<s.length&&ef(f,g)){const x=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} ${h} ${u} → ${f} (transient). Retry #${b} in ${x}ms.`),await new Promise(v=>setTimeout(v,x));continue}const w=`Preflight #${a} ${h} ${u} → ${f} ${g.slice(0,200)}`;if(c.soft){console.warn("[aikaara-chat-sdk]",w);break}throw new Error(w)}catch(m){if(b<s.length){const w=s[b++];console.warn(`[aikaara-chat-sdk] preflight #${a} threw, retry #${b} in ${w}ms`,m),await new Promise(x=>setTimeout(x,w));continue}if(c.soft){console.warn(`[aikaara-chat-sdk] preflight #${a} soft-failed:`,m);break}throw m}if(k&&c.capture&&c.capture.as)try{const m=await k.clone().text();let w=m;try{w=JSON.parse(m)}catch{}if(c.capture.path)for(const x of c.capture.path.split("."))if(w&&typeof w=="object"&&x in w)w=w[x];else{w=void 0;break}if(typeof w=="string"&&w.length>0){let x=w;c.capture.stripPrefix&&x.startsWith(c.capture.stripPrefix)&&(x=x.slice(c.capture.stripPrefix.length)),o[c.capture.as]=x,t[c.capture.as]=x,console.log(`[aikaara-chat-sdk] preflight #${a} captured ${c.capture.as} (${x.slice(0,24)}…)`)}}catch(m){console.warn(`[aikaara-chat-sdk] preflight #${a} capture failed`,m)}}return{captured:o}}function ef(l,e){if(l===503||l===504||l===502)return!0;if(l===401||l===403)return e.trim().length===0;if(l===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Kl(l,e){const t=await fetch(l,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const i=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${i.slice(0,200)}`)}const r=await t.json();if(r&&typeof r=="object"){if("config"in r)return r.config;if("data"in r)return r.data}return r}function Yl(l,e){return l.replace("{projectId}",e).replace("{uuid}",Yd().replace(/-/g,""))}function Ql(l){const e=l._preload;if(!Array.isArray(e)||e.length===0)return;const t=Array.from(new Set(e.map(r=>r&&typeof r=="object"?r.scriptUrl:null).filter(r=>typeof r=="string"&&r.length>0)));t.length!==0&&Promise.allSettled(t.map(r=>jl(r)))}async function Jl(l){const e={...l.config??(l.configUrl?await Kl(l.configUrl,l.configHeaders):{}),...l.overrides??{}};Ql(e);const t=e.transport??"tiledesk",r=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!r)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const i=r?.projectId??"",n=l.identity.userId,o=l.forceNewConversation?null:Gl(n,i),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",a=l.conversationId??o??Yl(s,i);(l.conversationId||!o||l.forceNewConversation)&&i&&Jd(n,i,a);const c=await l.tokenProvider(),u=l.tokenProvider,h=l.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:c,userId:n,userName:l.identity.userName,projectId:r.projectId,appId:r.appId,mqttUsername:r.mqttUsername,protocolId:r.protocolId,protocolVersion:r.protocolVersion,keepAliveSec:r.keepAliveSec,connectTimeoutMs:r.connectTimeoutMs,maxReconnectAttempts:r.maxReconnectAttempts,reconnectMaxDelayMs:r.reconnectMaxDelayMs,wildcardSubscribe:r.wildcardSubscribe,enablePresence:r.enablePresence,autoInitiateOnEmpty:r.autoInitiateOnEmpty,chatInitiatedAttributes:r.chatInitiatedAttributes,messageDefaults:{...r.messageDefaults,...l.identity.departmentId?{departmentId:l.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:l.identity.senderFullname??l.identity.userName,tokenProvider:u}:void 0,y=l.uploadAdapter??(e.uploadEndpoint?uo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=l.historyAdapter??(e.historyApiBase?bl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:h}):void 0),g={transport:t,baseUrl:"",userToken:l.userToken??n,conversationId:a,display:e.display??"embed",position:e.position,primaryColor:e.theme?.primary??e.primaryColor,title:e.title,subtitle:e.subtitle,avatarUrl:e.avatarUrl,width:e.width,height:e.height,borderRadius:e.theme?.radius??e.borderRadius,fontFamily:e.theme?.font??e.fontFamily,themeTokens:e.theme,linkHandlers:e.linkHandlers,getLinkBearer:l.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,chatActions:e.chatActions,tiledesk:p,tiledeskIdentity:{userId:n,userName:l.identity.userName,departmentId:l.identity.departmentId,senderFullname:l.identity.senderFullname??l.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:l.onError,onMessage:l.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(g),g.title&&b.setAttribute("title",g.title),g.primaryColor&&b.setAttribute("primary-color",g.primaryColor),g.display&&b.setAttribute("display",g.display),g.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;--aikaara-close-btn-display:none;"),l.container.appendChild(b),{widget:b,requestId:a,config:g,destroy(){b.remove()}}}function tf(l){if(typeof l!="string")return l;const e=document.querySelector(l);if(!e)throw new Error(`mountFromSlug: container "${l}" not found`);return e}async function Xl(l){const e=(l.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(l.slug)}`;let r=null;try{r=await Kl(t,l.configHeaders)}catch(I){if(!l.fallbackConfig)throw I;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${l.slug}" — using fallbackConfig.`,I)}const i={...l.fallbackConfig??{},...r??{},...l.overrides??{}};if(Ql(i),i.templates&&Object.keys(i.templates).length>0){i.components={...i.components??{}};for(const[I,O]of Object.entries(i.templates)){const P=`template:${I}`;i.components[P]||!O?.scriptUrl||!O?.render||(i.components[P]={kind:"iife-element",scriptUrl:O.scriptUrl,tag:O.render,...O.props?{props:O.props}:{}})}}const n=window;if(n.__aikaara_descriptor__={...n.__aikaara_descriptor__??{},templates:i.templates,components:i.components,razorpay:i.razorpay,title:i.title,cloud:i.cloud??n.__aikaara_descriptor__?.cloud,upload:i.upload??n.__aikaara_descriptor__?.upload,themeSource:i.themeSource??n.__aikaara_descriptor__?.themeSource,api:i.api,auth:i.auth},!i.auth)throw new Error(`mountFromSlug: widget_configs/${l.slug} descriptor must include "auth" block`);let o=null,s=l.user.id,a=l.user.name,c="",u=l.user.token,h=null;const p=await Xt(l.user.token).catch(()=>""),y=typeof p=="string"&&p.length>0;if(!y&&i.sso?.tokenSource){h=new zl({descriptor:{provider:i.sso.provider,flow:i.sso.flow,skipLogin:i.sso.skipLogin,autoRefresh:i.sso.autoRefresh,tokenSource:i.sso.tokenSource,tokenSourceConfig:i.sso.tokenSourceConfig,fallback:i.sso.fallback,map:i.sso.map},initToken:l.user.partnerToken});const I=await h.get();u=async()=>(await h.get()).token,l.user.identity&&!l.user.identity.partnerToken&&(l.user.identity.partnerToken=I.token)}else if(!y&&i.sso&&i.sso.collect&&i.sso.collect.length>0){const I=`${e}/api/v1/projects/by-slug/${encodeURIComponent(l.slug)}/sso_exchange`;o=await new Hl({descriptor:i.sso,providers:l.user.credentialProviders,exchangeUrl:I}).get(),s=o.extUid||s,a=a??o.displayName,c=o.userToken}let f="",g="";if(i.preflight&&i.preflight.length){const I=await Zd(i.preflight,{sessionToken:u,userId:s,projectId:i.tiledesk?.projectId??"",slug:l.slug,identity:l.user.identity});if(I.captured.sessionToken){f=I.captured.sessionToken;const O=f;u=()=>O}I.captured.userId&&(s=I.captured.userId),I.captured.requestId&&(g=I.captured.requestId)}const b=new $l(i.auth,u);if(f){const I=i.tiledesk?.projectId??"",O=I?Gl(s,I):null,P=i.tiledesk?.requestIdTemplate??"support-group-{projectId}-{uuid}",N=O??(I?Yl(P,I):"");b.prime(f,{requestId:N,fullName:a})}const k=await b.get();s=s||k.userId;const m=k.fullName||a||s;window.__aikaara_runtime__={getChatJwt:async()=>(await b.get()).token,identity:l.user.identity,slug:l.slug,configBase:e};const w=h&&i.sso?.autoRefresh?async()=>{try{return await h.refresh(),b.reset(),(await b.get()).token}catch(I){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",I),null}}:null,x=i.upload,v=async()=>`Bearer ${x&&"tokenSource"in x&&x.tokenSource==="chat"?(await b.get()).token:await Xt(l.user.token)}`,E=l.hooks?.upload??(x&&x.mode==="presigned-3step"?gl({...x,authHeader:v}):x&&x.mode==="direct"?uo({endpoint:x.endpoint,fieldName:x.fieldName,extraFields:x.extraFields,headers:async()=>({authorization:await v()})}):void 0),S=await Jl({container:tf(l.container),config:i,userToken:c||void 0,identity:{userId:s,userName:m,departmentId:l.user.departmentId,senderFullname:m},tokenProvider:async()=>(await b.get()).token,historyTokenProvider:async()=>(await b.get()).token,uploadAdapter:E,historyAdapter:l.hooks?.history,conversationId:k.requestId||g||void 0,onError:l.hooks?.onError,onMessage:l.hooks?.onMessage,getLinkBearer:async I=>I==="none"?null:I==="chat"?(await b.get()).token:Xt(l.user.token)});return Object.assign(S,{fullName:m,requestId:k.requestId,descriptor:i,async refreshAuth(){b.reset(),await b.get()},async refreshPartnerAuth(){return w?w():null}})}function rf(l){yo();const e=document.createElement("aikaara-chat-widget"),t={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[r,i]of Object.entries(t)){const n=l[r];n!=null&&e.setAttribute(i,String(n))}return e.configure(l),document.body.appendChild(e),e}function nf(){const l=document.querySelector("aikaara-chat-widget");l&&l.remove()}class Zl extends HTMLElement{shadow;payload=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.payload=e,this.render()}render(){const e=this.payload;this.shadow.innerHTML=`
1472
1472
  <style>
1473
1473
  :host { display: block; margin-top: 8px; }
1474
1474
  button {
package/dist/headless.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-B-n1xvto.cjs");class s extends e.EventEmitter{registration=null;pendingEdits=[];constructor(t){super(),this.setupListeners(t)}registerForm(t){this.registration=t;const i=this.pendingEdits.filter(r=>r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId));if(i.length>0){for(const r of i)t.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId)))}}unregisterForm(t,i){this.registration?.entityType===t&&String(this.registration?.entityId)===String(i)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(t,i,r){this.registration&&this.registration.entityType===t&&String(this.registration.entityId)===String(i)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:t,entityId:i,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:t,entity_id:i,fields:r}),this.emit("edit:pending",{entityType:t,entityId:i,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(t){const i=t instanceof Error?t.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:i}),{success:!1,error:i}}}async requestTest(t){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(t),{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Test failed"}}}setupListeners(t){t.on("action:edit_entity",i=>{this.pushFieldUpdates(i.entity_type,i.entity_id,i.fields)}),t.on("action:save_entity",i=>{this.requestSave()}),t.on("action:test_tool",i=>{this.emit("test:triggered",{toolId:i.tool_id,parameters:i.parameters}),this.requestTest(i.parameters)})}}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.FormBridge=s;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-DsDbh_2_.cjs");class s extends e.EventEmitter{registration=null;pendingEdits=[];constructor(t){super(),this.setupListeners(t)}registerForm(t){this.registration=t;const i=this.pendingEdits.filter(r=>r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId));if(i.length>0){for(const r of i)t.onFieldUpdate(r.fields),this.emit("edit:applied",{entityType:r.entity_type,entityId:r.entity_id,fields:r.fields});this.pendingEdits=this.pendingEdits.filter(r=>!(r.entity_type===t.entityType&&String(r.entity_id)===String(t.entityId)))}}unregisterForm(t,i){this.registration?.entityType===t&&String(this.registration?.entityId)===String(i)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(t,i,r){this.registration&&this.registration.entityType===t&&String(this.registration.entityId)===String(i)?(this.registration.onFieldUpdate(r),this.emit("edit:applied",{entityType:t,entityId:i,fields:r})):(this.pendingEdits.push({action:"edit_entity",entity_type:t,entity_id:i,fields:r}),this.emit("edit:pending",{entityType:t,entityId:i,fields:r}))}async requestSave(){if(!this.registration)return{success:!1,error:"No form registered"};try{return await this.registration.onSave(),this.emit("save:success",{entityType:this.registration.entityType,entityId:this.registration.entityId}),{success:!0}}catch(t){const i=t instanceof Error?t.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:i}),{success:!1,error:i}}}async requestTest(t){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(t),{success:!0}}catch(i){return{success:!1,error:i instanceof Error?i.message:"Test failed"}}}setupListeners(t){t.on("action:edit_entity",i=>{this.pushFieldUpdates(i.entity_type,i.entity_id,i.fields)}),t.on("action:save_entity",i=>{this.requestSave()}),t.on("action:test_tool",i=>{this.emit("test:triggered",{toolId:i.tool_id,parameters:i.parameters}),this.requestTest(i.parameters)})}}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatClient=e.AikaaraChatClient;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.FormBridge=s;
package/dist/headless.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { E as s } from "./MountTenant-DdxGoxgX.mjs";
2
- import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-DdxGoxgX.mjs";
1
+ import { E as s } from "./MountTenant-QL3ds6__.mjs";
2
+ import { A as p, b as l, k as g, C as c, l as h, m as y, M as u, S as m, n as f, T, o as S, p as _, q as v, s as E, t as C, u as F, v as k, w as A, x as I, y as x, z as U, B as q, D as M, F as b } from "./MountTenant-QL3ds6__.mjs";
3
3
  class a extends s {
4
4
  registration = null;
5
5
  pendingEdits = [];
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-B-n1xvto.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,n]of Object.entries(i)){const r=a[o];r!=null&&t.setAttribute(n,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-DsDbh_2_.cjs"),s=require("./headless.cjs");function l(a){e.registerComponents();const t=document.createElement("aikaara-chat-widget"),i={baseUrl:"base-url",userToken:"user-token",apiKey:"api-key",title:"title",subtitle:"subtitle",theme:"theme",primaryColor:"primary-color",position:"position",width:"width",height:"height",placeholder:"placeholder",welcomeMessage:"welcome-message",avatarUrl:"avatar-url"};for(const[o,n]of Object.entries(i)){const r=a[o];r!=null&&t.setAttribute(n,String(r))}return t.configure(a),document.body.appendChild(t),t}function d(){const a=document.querySelector("aikaara-chat-widget");a&&a.remove()}exports.ActionCableClient=e.ActionCableClient;exports.AikaaraChatBubble=e.AikaaraChatBubble;exports.AikaaraChatClient=e.AikaaraChatClient;exports.AikaaraChatHeader=e.AikaaraChatHeader;exports.AikaaraChatInput=e.AikaaraChatInput;exports.AikaaraChatWidget=e.AikaaraChatWidget;exports.AikaaraErrorBanner=e.AikaaraErrorBanner;exports.AikaaraMessageBubble=e.AikaaraMessageBubble;exports.AikaaraMessageList=e.AikaaraMessageList;exports.AikaaraStreamingMessage=e.AikaaraStreamingMessage;exports.AikaaraTypingIndicator=e.AikaaraTypingIndicator;exports.ApiClient=e.ApiClient;exports.ChannelSubscription=e.ChannelSubscription;exports.ConnectionManager=e.ConnectionManager;exports.ConversationManager=e.ConversationManager;exports.EventEmitter=e.EventEmitter;exports.MessageStore=e.MessageStore;exports.SessionAuthAdapter=e.SessionAuthAdapter;exports.SsoExchangeAdapter=e.SsoExchangeAdapter;exports.TiledeskTransport=e.TiledeskTransport;exports.TokenDiscoveryError=e.TokenDiscoveryError;exports.TokenDiscoveryReader=e.TokenDiscoveryReader;exports.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;exports.discoverToken=e.discoverToken;exports.extractTiledeskFileEnvelope=e.extractTiledeskFileEnvelope;exports.inferTiledeskRole=e.inferTiledeskRole;exports.isTiledeskSelfEcho=e.isTiledeskSelfEcho;exports.mountFromSlug=e.mountFromSlug;exports.mountTenantWidget=e.mount;exports.parseTiledeskTemplate=e.parseTiledeskTemplate;exports.registerComponents=e.registerComponents;exports.FormBridge=s.FormBridge;exports.mount=l;exports.unmount=d;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { r as o } from "./MountTenant-DdxGoxgX.mjs";
2
- import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-DdxGoxgX.mjs";
1
+ import { r as o } from "./MountTenant-QL3ds6__.mjs";
2
+ import { A as u, a as m, b as k, c as g, d as h, e as A, f as C, g as T, h as b, i as v, j as f, k as y, C as S, l as w, m as E, E as M, M as x, S as B, n as F, T as U, o as D, p as I, q as j, s as q, t as H, u as P, v as R, w as W, x as z, y as K, z as L, B as O, D as G, F as J } from "./MountTenant-QL3ds6__.mjs";
3
3
  import { FormBridge as Q } from "./headless.mjs";
4
4
  function l(e) {
5
5
  o();
package/dist/ui.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-B-n1xvto.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraComparePlans=a.AikaaraComparePlans;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraLinkModal=a.AikaaraLinkModal;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraSchemaForm=a.AikaaraSchemaForm;exports.AikaaraSmartEditModal=a.AikaaraSmartEditModal;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./MountTenant-DsDbh_2_.cjs");exports.AikaaraChat=a.AikaaraChat;exports.AikaaraChatBubble=a.AikaaraChatBubble;exports.AikaaraChatHeader=a.AikaaraChatHeader;exports.AikaaraChatInput=a.AikaaraChatInput;exports.AikaaraChatWidget=a.AikaaraChatWidget;exports.AikaaraComparePlans=a.AikaaraComparePlans;exports.AikaaraErrorBanner=a.AikaaraErrorBanner;exports.AikaaraLinkModal=a.AikaaraLinkModal;exports.AikaaraMessageBubble=a.AikaaraMessageBubble;exports.AikaaraMessageList=a.AikaaraMessageList;exports.AikaaraModalAction=a.AikaaraModalAction;exports.AikaaraOptionList=a.AikaaraOptionList;exports.AikaaraSchemaForm=a.AikaaraSchemaForm;exports.AikaaraSmartEditModal=a.AikaaraSmartEditModal;exports.AikaaraStreamingMessage=a.AikaaraStreamingMessage;exports.AikaaraSubmitAction=a.AikaaraSubmitAction;exports.AikaaraSystemPill=a.AikaaraSystemPill;exports.AikaaraTemplateRenderer=a.AikaaraTemplateRenderer;exports.AikaaraTypingIndicator=a.AikaaraTypingIndicator;exports.registerComponents=a.registerComponents;
package/dist/ui.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g as m, h as d, J as l, K as g, L as h, N as p, i as C, O as M, P as b, Q as c, j as S, r as u } from "./MountTenant-DdxGoxgX.mjs";
1
+ import { G as i, a as s, c as e, d as t, e as A, H as k, f as n, I as o, g as m, h as d, J as l, K as g, L as h, N as p, i as C, O as M, P as b, Q as c, j as S, r as u } from "./MountTenant-QL3ds6__.mjs";
2
2
  export {
3
3
  i as AikaaraChat,
4
4
  s as AikaaraChatBubble,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aikaara/chat-sdk",
3
- "version": "1.1.18",
3
+ "version": "1.1.19",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",