@aikaara/chat-sdk 0.7.7 → 0.7.8

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.
@@ -14536,7 +14536,7 @@ function Bh(c) {
14536
14536
  return e;
14537
14537
  }
14538
14538
  async function Dh(c) {
14539
- const e = (c.configBase ?? "https://api.aikaara.com").replace(/\/$/, ""), t = `${e}/widget_configs/${encodeURIComponent(c.slug)}`;
14539
+ const e = (c.configBase ?? "https://api.aikaara.com").replace(/\/$/, ""), t = `${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;
14540
14540
  let n = null;
14541
14541
  try {
14542
14542
  n = await ol(t, c.configHeaders);
@@ -962,4 +962,4 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
962
962
  <small>Tap to select</small>
963
963
  </button>`}).join("")}
964
964
  </div>
965
- `,this.shadow.querySelectorAll("button.action").forEach(n=>{n.addEventListener("click",()=>{const l=Number(n.dataset.col),r=e[l];r&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:r.match[0],message:r.postback,label:r.label},bubbles:!0,composed:!0}))})})}}function Hr(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function jl(){const c=[["aikaara-chat-widget",gl],["aikaara-chat-bubble",ml],["aikaara-chat-header",bl],["aikaara-message-list",vl],["aikaara-message-bubble",_l],["aikaara-chat-input",Sl],["aikaara-typing-indicator",kl],["aikaara-streaming-message",El],["aikaara-error-banner",xl],["aikaara-template-renderer",Al],["aikaara-system-pill",Il],["aikaara-option-list",Tl],["aikaara-submit-action",Cl],["aikaara-modal-action",Ol],["aikaara-chat",Pl],["aikaara-link-modal",Ml],["aikaara-compare-plans",Rl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}jl();function zr(c,e,t=""){if(!e)return t;const n=e.split(".");let l=c;for(const r of n)if(l&&typeof l=="object"&&r in l)l=l[r];else return t;return typeof l=="string"?l:t}function Ih(c){try{const e=c.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 Or(c){return typeof c=="function"?await c():c}class Ll{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}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 Or(this.sessionToken),t=this.descriptor.authHeader??"Authorization",n=this.descriptor.authHeaderTemplate??"Bearer {token}",l={accept:"application/json",...this.descriptor.headers??{},[t]:n.replace("{token}",e)},r=this.descriptor.method??"POST",i={method:r,headers:l};r==="POST"&&(l["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const b=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${b.slice(0,200)}`)}const s=await o.json().catch(()=>({})),a=zr(s,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?a.replace(new RegExp(`^${u}`,"i"),"").trim():a;if(!d)throw new Error("Session auth response missing token");const p=zr(s,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=zr(s,this.descriptor.fullNamePath??"data.fullName"),m=Ih(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:m},this.cache}}async function Nl(c){const e={};for(const t of c.spec){const n=await Th(t,c.providers);if(n!==void 0&&n!=="")e[t.name]=n;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 Th(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Ch(t);case"localStorage":return rr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return rr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return rr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return rr(()=>document.querySelector(`meta[name="${Oh(t)}"]`)?.content??void 0);case"callback":{const n=e?.[c.name];if(!n)return;const l=await n();return typeof l=="string"?l:void 0}default:return}}function Ch(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const n of t){const l=n.indexOf("=");if(l===-1)continue;const r=n.slice(0,l);if(r===c||r===e)try{return decodeURIComponent(n.slice(l+1))}catch{return n.slice(l+1)}}}function rr(c){try{return c()}catch{return}}function Oh(c){return c.replace(/["\\]/g,"\\$&")}const Ph=1800;class Ul{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(){const e=await Nl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),n={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(n["X-Api-Key"]=this.opts.descriptor.apiKey);const l=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!l)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 r=await fetch(l,{method:"POST",headers:n,body:t});if(!r.ok){const d=await r.text().catch(()=>"");throw new Error(`SSO exchange failed: ${r.status} ${d.slice(0,240)}`)}const o=(await r.json().catch(()=>({}))).user??{},s=String(o.ext_uid??o.extUid??""),a=String(o.token??o.user_token??o.userToken??"");if(!s)throw new Error("SSO exchange response missing user.ext_uid");if(!a)throw new Error("SSO exchange response missing user.token");const u={id:o.id,extUid:s,userToken:a,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Ph;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 n=JSON.parse(t);return n.expiresAt&&n.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):n}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{}}}function Mh(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.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 Rh="aikaara_chat:requestId";function co(c,e){return`${Rh}:${c}:${e}`}function jh(c,e){try{return localStorage.getItem(co(c,e))}catch{return null}}function Lh(c,e,t){try{localStorage.setItem(co(c,e),t)}catch{}}function Nh(c,e){try{localStorage.removeItem(co(c,e))}catch{}}async function Uh(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[o,s]of Object.entries(e.identity))typeof s=="string"&&(t[o]=s);const n=o=>o.replace(/\{(\w+)\}/g,(s,a)=>a in t?t[a]:""),l=o=>{if(typeof o=="string")return n(o);if(Array.isArray(o))return o.map(l);if(o&&typeof o=="object"){const s={};for(const[a,u]of Object.entries(o))s[a]=l(u);return s}return o},r=await Or(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let o=0;o<c.length;o++){const s=c[o],a=n(s.url),u=s.method??(s.body?"POST":"GET"),d={accept:"application/json",...s.headers??{}};if((s.authHeader??"session")==="session"){const b=s.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",r)}const p={method:u,headers:d};s.body&&(d["content-type"]="application/json",p.body=JSON.stringify(l(s.body)));let y=0,f="",m=0;for(;;)try{const b=await fetch(a,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),m<i.length&&Bh(y,f)){const g=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} ${u} ${a} → ${y} (transient). Retry #${m} in ${g}ms.`),await new Promise(_=>setTimeout(_,g));continue}const S=`Preflight #${o} ${u} ${a} → ${y} ${f.slice(0,200)}`;if(s.soft){console.warn("[aikaara-chat-sdk]",S);break}throw new Error(S)}catch(b){if(m<i.length){const S=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} threw, retry #${m} in ${S}ms`,b),await new Promise(g=>setTimeout(g,S));continue}if(s.soft){console.warn(`[aikaara-chat-sdk] preflight #${o} soft-failed:`,b);break}throw b}}}function Bh(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Bl(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const l=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${l.slice(0,200)}`)}const n=await t.json();if(n&&typeof n=="object"){if("config"in n)return n.config;if("data"in n)return n.data}return n}function Dh(c,e){return c.replace("{projectId}",e).replace("{uuid}",Mh().replace(/-/g,""))}async function Dl(c){const e={...c.config??(c.configUrl?await Bl(c.configUrl,c.configHeaders):{}),...c.overrides??{}},t=e.transport??"tiledesk",n=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!n)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const l=n?.projectId??"",r=c.identity.userId,i=c.forceNewConversation?null:jh(r,l),o=n?.requestIdTemplate??"support-group-{projectId}-{uuid}",s=c.conversationId??i??Dh(o,l);(!i||c.forceNewConversation)&&l&&Lh(r,l,s);const a=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=n?{mqttEndpoint:n.mqttEndpoint,jwtToken:a,userId:r,userName:c.identity.userName,projectId:n.projectId,appId:n.appId,mqttUsername:n.mqttUsername,protocolId:n.protocolId,protocolVersion:n.protocolVersion,keepAliveSec:n.keepAliveSec,connectTimeoutMs:n.connectTimeoutMs,maxReconnectAttempts:n.maxReconnectAttempts,reconnectMaxDelayMs:n.reconnectMaxDelayMs,wildcardSubscribe:n.wildcardSubscribe,enablePresence:n.enablePresence,autoInitiateOnEmpty:n.autoInitiateOnEmpty,chatInitiatedAttributes:n.chatInitiatedAttributes,messageDefaults:{...n.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:n.messageDefaults?.departmentId?{departmentId:n.messageDefaults.departmentId}:{}},fileTemplate:n.fileTemplate,topicTemplates:n.topicTemplates,debug:n.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?lo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?pl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),m={transport:t,baseUrl:"",userToken:c.userToken??r,conversationId:s,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:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,tiledesk:p,tiledeskIdentity:{userId:r,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(m),m.title&&b.setAttribute("title",m.title),m.primaryColor&&b.setAttribute("primary-color",m.primaryColor),m.display&&b.setAttribute("display",m.display),m.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:s,config:m,destroy(){b.remove()}}}function Fh(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Fl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/widget_configs/${encodeURIComponent(c.slug)}`;let n=null;try{n=await Bl(t,c.configHeaders)}catch(b){if(!c.fallbackConfig)throw b;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,b)}const l={...c.fallbackConfig??{},...n??{},...c.overrides??{}};if(window.__aikaara_descriptor__={templates:l.templates},!l.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let r=null,i=c.user.id,o=c.user.name,s="";if(l.sso){const b=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;r=await new Ul({descriptor:l.sso,providers:c.user.credentialProviders,exchangeUrl:b}).get(),i=r.extUid||i,o=o??r.displayName,s=r.userToken}l.preflight&&l.preflight.length&&await Uh(l.preflight,{sessionToken:c.user.token,userId:i,projectId:l.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const a=new Ll(l.auth,c.user.token),u=await a.get(),d=u.fullName||o||i,p=l.upload,y=async()=>`Bearer ${p&&"tokenSource"in p&&p.tokenSource==="chat"?(await a.get()).token:await Or(c.user.token)}`,f=c.hooks?.upload??(p&&p.mode==="presigned-3step"?dl({...p,authHeader:y}):p&&p.mode==="direct"?lo({endpoint:p.endpoint,fieldName:p.fieldName,extraFields:p.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await Dl({container:Fh(c.container),config:l,userToken:s||void 0,identity:{userId:i,userName:d,departmentId:c.user.departmentId,senderFullname:d},tokenProvider:async()=>(await a.get()).token,historyTokenProvider:async()=>(await a.get()).token,uploadAdapter:f,historyAdapter:c.hooks?.history,conversationId:u.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async b=>b==="none"?null:b==="chat"?(await a.get()).token:Or(c.user.token)});return Object.assign(m,{fullName:d,requestId:u.requestId,descriptor:l,async refreshAuth(){a.reset(),await a.get()}})}exports.ActionCableClient=Kr;exports.AikaaraChat=Pl;exports.AikaaraChatBubble=ml;exports.AikaaraChatClient=fl;exports.AikaaraChatHeader=bl;exports.AikaaraChatInput=Sl;exports.AikaaraChatWidget=gl;exports.AikaaraComparePlans=Rl;exports.AikaaraErrorBanner=xl;exports.AikaaraLinkModal=Ml;exports.AikaaraMessageBubble=_l;exports.AikaaraMessageList=vl;exports.AikaaraModalAction=Ol;exports.AikaaraOptionList=Tl;exports.AikaaraStreamingMessage=El;exports.AikaaraSubmitAction=Cl;exports.AikaaraSystemPill=Il;exports.AikaaraTemplateRenderer=Al;exports.AikaaraTypingIndicator=kl;exports.ApiClient=Ts;exports.ChannelSubscription=As;exports.ConnectionManager=Is;exports.ConversationManager=Os;exports.EventEmitter=Ki;exports.MessageStore=Cs;exports.SessionAuthAdapter=Ll;exports.SsoExchangeAdapter=Ul;exports.TiledeskTransport=ll;exports.clearPersistedConversationId=Nh;exports.collectSsoCredentials=Nl;exports.createFetchUploadAdapter=lo;exports.createPresigned3StepUploadAdapter=dl;exports.createTiledeskHistoryAdapter=pl;exports.extractTiledeskFileEnvelope=hl;exports.inferTiledeskRole=ul;exports.isTiledeskSelfEcho=cl;exports.mount=Dl;exports.mountFromSlug=Fl;exports.parseTiledeskTemplate=ao;exports.registerComponents=jl;
965
+ `,this.shadow.querySelectorAll("button.action").forEach(n=>{n.addEventListener("click",()=>{const l=Number(n.dataset.col),r=e[l];r&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:r.match[0],message:r.postback,label:r.label},bubbles:!0,composed:!0}))})})}}function Hr(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function jl(){const c=[["aikaara-chat-widget",gl],["aikaara-chat-bubble",ml],["aikaara-chat-header",bl],["aikaara-message-list",vl],["aikaara-message-bubble",_l],["aikaara-chat-input",Sl],["aikaara-typing-indicator",kl],["aikaara-streaming-message",El],["aikaara-error-banner",xl],["aikaara-template-renderer",Al],["aikaara-system-pill",Il],["aikaara-option-list",Tl],["aikaara-submit-action",Cl],["aikaara-modal-action",Ol],["aikaara-chat",Pl],["aikaara-link-modal",Ml],["aikaara-compare-plans",Rl]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}jl();function zr(c,e,t=""){if(!e)return t;const n=e.split(".");let l=c;for(const r of n)if(l&&typeof l=="object"&&r in l)l=l[r];else return t;return typeof l=="string"?l:t}function Ih(c){try{const e=c.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 Or(c){return typeof c=="function"?await c():c}class Ll{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}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 Or(this.sessionToken),t=this.descriptor.authHeader??"Authorization",n=this.descriptor.authHeaderTemplate??"Bearer {token}",l={accept:"application/json",...this.descriptor.headers??{},[t]:n.replace("{token}",e)},r=this.descriptor.method??"POST",i={method:r,headers:l};r==="POST"&&(l["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const b=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${b.slice(0,200)}`)}const s=await o.json().catch(()=>({})),a=zr(s,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?a.replace(new RegExp(`^${u}`,"i"),"").trim():a;if(!d)throw new Error("Session auth response missing token");const p=zr(s,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=zr(s,this.descriptor.fullNamePath??"data.fullName"),m=Ih(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:m},this.cache}}async function Nl(c){const e={};for(const t of c.spec){const n=await Th(t,c.providers);if(n!==void 0&&n!=="")e[t.name]=n;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 Th(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Ch(t);case"localStorage":return rr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return rr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return rr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return rr(()=>document.querySelector(`meta[name="${Oh(t)}"]`)?.content??void 0);case"callback":{const n=e?.[c.name];if(!n)return;const l=await n();return typeof l=="string"?l:void 0}default:return}}function Ch(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const n of t){const l=n.indexOf("=");if(l===-1)continue;const r=n.slice(0,l);if(r===c||r===e)try{return decodeURIComponent(n.slice(l+1))}catch{return n.slice(l+1)}}}function rr(c){try{return c()}catch{return}}function Oh(c){return c.replace(/["\\]/g,"\\$&")}const Ph=1800;class Ul{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(){const e=await Nl({spec:this.opts.descriptor.collect,providers:this.opts.providers}),t=JSON.stringify({credentials:e}),n={accept:"application/json","content-type":"application/json",...this.opts.descriptor.headers??{}};this.opts.descriptor.apiKey&&(n["X-Api-Key"]=this.opts.descriptor.apiKey);const l=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!l)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 r=await fetch(l,{method:"POST",headers:n,body:t});if(!r.ok){const d=await r.text().catch(()=>"");throw new Error(`SSO exchange failed: ${r.status} ${d.slice(0,240)}`)}const o=(await r.json().catch(()=>({}))).user??{},s=String(o.ext_uid??o.extUid??""),a=String(o.token??o.user_token??o.userToken??"");if(!s)throw new Error("SSO exchange response missing user.ext_uid");if(!a)throw new Error("SSO exchange response missing user.token");const u={id:o.id,extUid:s,userToken:a,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=u,this.persistCache(u),u}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??Ph;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 n=JSON.parse(t);return n.expiresAt&&n.expiresAt<Date.now()?(window.localStorage.removeItem(e),null):n}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{}}}function Mh(){const c=typeof crypto<"u"?crypto:null;if(c?.randomUUID)return c.randomUUID();if(c?.getRandomValues){const e=new Uint8Array(16);c.getRandomValues(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128;const t=[...e].map(n=>n.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 Rh="aikaara_chat:requestId";function co(c,e){return`${Rh}:${c}:${e}`}function jh(c,e){try{return localStorage.getItem(co(c,e))}catch{return null}}function Lh(c,e,t){try{localStorage.setItem(co(c,e),t)}catch{}}function Nh(c,e){try{localStorage.removeItem(co(c,e))}catch{}}async function Uh(c,e){console.log("[aikaara-chat-sdk] preflight running",c.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[o,s]of Object.entries(e.identity))typeof s=="string"&&(t[o]=s);const n=o=>o.replace(/\{(\w+)\}/g,(s,a)=>a in t?t[a]:""),l=o=>{if(typeof o=="string")return n(o);if(Array.isArray(o))return o.map(l);if(o&&typeof o=="object"){const s={};for(const[a,u]of Object.entries(o))s[a]=l(u);return s}return o},r=await Or(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let o=0;o<c.length;o++){const s=c[o],a=n(s.url),u=s.method??(s.body?"POST":"GET"),d={accept:"application/json",...s.headers??{}};if((s.authHeader??"session")==="session"){const b=s.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",r)}const p={method:u,headers:d};s.body&&(d["content-type"]="application/json",p.body=JSON.stringify(l(s.body)));let y=0,f="",m=0;for(;;)try{const b=await fetch(a,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),m<i.length&&Bh(y,f)){const g=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} ${u} ${a} → ${y} (transient). Retry #${m} in ${g}ms.`),await new Promise(_=>setTimeout(_,g));continue}const S=`Preflight #${o} ${u} ${a} → ${y} ${f.slice(0,200)}`;if(s.soft){console.warn("[aikaara-chat-sdk]",S);break}throw new Error(S)}catch(b){if(m<i.length){const S=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} threw, retry #${m} in ${S}ms`,b),await new Promise(g=>setTimeout(g,S));continue}if(s.soft){console.warn(`[aikaara-chat-sdk] preflight #${o} soft-failed:`,b);break}throw b}}}function Bh(c,e){if(c===503||c===504||c===502)return!0;if(c===401||c===403)return e.trim().length===0;if(c===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function Bl(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const l=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${l.slice(0,200)}`)}const n=await t.json();if(n&&typeof n=="object"){if("config"in n)return n.config;if("data"in n)return n.data}return n}function Dh(c,e){return c.replace("{projectId}",e).replace("{uuid}",Mh().replace(/-/g,""))}async function Dl(c){const e={...c.config??(c.configUrl?await Bl(c.configUrl,c.configHeaders):{}),...c.overrides??{}},t=e.transport??"tiledesk",n=e.tiledesk;if((t==="tiledesk"||t==="dual")&&!n)throw new Error("mount: descriptor.tiledesk is required for tiledesk/dual transport");const l=n?.projectId??"",r=c.identity.userId,i=c.forceNewConversation?null:jh(r,l),o=n?.requestIdTemplate??"support-group-{projectId}-{uuid}",s=c.conversationId??i??Dh(o,l);(!i||c.forceNewConversation)&&l&&Lh(r,l,s);const a=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=n?{mqttEndpoint:n.mqttEndpoint,jwtToken:a,userId:r,userName:c.identity.userName,projectId:n.projectId,appId:n.appId,mqttUsername:n.mqttUsername,protocolId:n.protocolId,protocolVersion:n.protocolVersion,keepAliveSec:n.keepAliveSec,connectTimeoutMs:n.connectTimeoutMs,maxReconnectAttempts:n.maxReconnectAttempts,reconnectMaxDelayMs:n.reconnectMaxDelayMs,wildcardSubscribe:n.wildcardSubscribe,enablePresence:n.enablePresence,autoInitiateOnEmpty:n.autoInitiateOnEmpty,chatInitiatedAttributes:n.chatInitiatedAttributes,messageDefaults:{...n.messageDefaults,...c.identity.departmentId?{departmentId:c.identity.departmentId}:n.messageDefaults?.departmentId?{departmentId:n.messageDefaults.departmentId}:{}},fileTemplate:n.fileTemplate,topicTemplates:n.topicTemplates,debug:n.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?lo({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?pl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),m={transport:t,baseUrl:"",userToken:c.userToken??r,conversationId:s,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:c.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,tiledesk:p,tiledeskIdentity:{userId:r,userName:c.identity.userName,departmentId:c.identity.departmentId,senderFullname:c.identity.senderFullname??c.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:c.onError,onMessage:c.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(m),m.title&&b.setAttribute("title",m.title),m.primaryColor&&b.setAttribute("primary-color",m.primaryColor),m.display&&b.setAttribute("display",m.display),m.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),c.container.appendChild(b),{widget:b,requestId:s,config:m,destroy(){b.remove()}}}function Fh(c){if(typeof c!="string")return c;const e=document.querySelector(c);if(!e)throw new Error(`mountFromSlug: container "${c}" not found`);return e}async function Fl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let n=null;try{n=await Bl(t,c.configHeaders)}catch(b){if(!c.fallbackConfig)throw b;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,b)}const l={...c.fallbackConfig??{},...n??{},...c.overrides??{}};if(window.__aikaara_descriptor__={templates:l.templates},!l.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let r=null,i=c.user.id,o=c.user.name,s="";if(l.sso){const b=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;r=await new Ul({descriptor:l.sso,providers:c.user.credentialProviders,exchangeUrl:b}).get(),i=r.extUid||i,o=o??r.displayName,s=r.userToken}l.preflight&&l.preflight.length&&await Uh(l.preflight,{sessionToken:c.user.token,userId:i,projectId:l.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const a=new Ll(l.auth,c.user.token),u=await a.get(),d=u.fullName||o||i,p=l.upload,y=async()=>`Bearer ${p&&"tokenSource"in p&&p.tokenSource==="chat"?(await a.get()).token:await Or(c.user.token)}`,f=c.hooks?.upload??(p&&p.mode==="presigned-3step"?dl({...p,authHeader:y}):p&&p.mode==="direct"?lo({endpoint:p.endpoint,fieldName:p.fieldName,extraFields:p.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await Dl({container:Fh(c.container),config:l,userToken:s||void 0,identity:{userId:i,userName:d,departmentId:c.user.departmentId,senderFullname:d},tokenProvider:async()=>(await a.get()).token,historyTokenProvider:async()=>(await a.get()).token,uploadAdapter:f,historyAdapter:c.hooks?.history,conversationId:u.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async b=>b==="none"?null:b==="chat"?(await a.get()).token:Or(c.user.token)});return Object.assign(m,{fullName:d,requestId:u.requestId,descriptor:l,async refreshAuth(){a.reset(),await a.get()}})}exports.ActionCableClient=Kr;exports.AikaaraChat=Pl;exports.AikaaraChatBubble=ml;exports.AikaaraChatClient=fl;exports.AikaaraChatHeader=bl;exports.AikaaraChatInput=Sl;exports.AikaaraChatWidget=gl;exports.AikaaraComparePlans=Rl;exports.AikaaraErrorBanner=xl;exports.AikaaraLinkModal=Ml;exports.AikaaraMessageBubble=_l;exports.AikaaraMessageList=vl;exports.AikaaraModalAction=Ol;exports.AikaaraOptionList=Tl;exports.AikaaraStreamingMessage=El;exports.AikaaraSubmitAction=Cl;exports.AikaaraSystemPill=Il;exports.AikaaraTemplateRenderer=Al;exports.AikaaraTypingIndicator=kl;exports.ApiClient=Ts;exports.ChannelSubscription=As;exports.ConnectionManager=Is;exports.ConversationManager=Os;exports.EventEmitter=Ki;exports.MessageStore=Cs;exports.SessionAuthAdapter=Ll;exports.SsoExchangeAdapter=Ul;exports.TiledeskTransport=ll;exports.clearPersistedConversationId=Nh;exports.collectSsoCredentials=Nl;exports.createFetchUploadAdapter=lo;exports.createPresigned3StepUploadAdapter=dl;exports.createTiledeskHistoryAdapter=pl;exports.extractTiledeskFileEnvelope=hl;exports.inferTiledeskRole=ul;exports.isTiledeskSelfEcho=cl;exports.mount=Dl;exports.mountFromSlug=Fl;exports.parseTiledeskTemplate=ao;exports.registerComponents=jl;
@@ -962,7 +962,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
962
962
  <small>Tap to select</small>
963
963
  </button>`}).join("")}
964
964
  </div>
965
- `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const l=Number(r.dataset.col),n=e[l];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function so(u){return u.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function ao(){const u=[["aikaara-chat-widget",il],["aikaara-chat-bubble",ol],["aikaara-chat-header",sl],["aikaara-message-list",ll],["aikaara-message-bubble",cl],["aikaara-chat-input",fl],["aikaara-typing-indicator",dl],["aikaara-streaming-message",pl],["aikaara-error-banner",gl],["aikaara-template-renderer",bh],["aikaara-system-pill",wh],["aikaara-option-list",_h],["aikaara-submit-action",kh],["aikaara-modal-action",Eh],["aikaara-chat",xh],["aikaara-link-modal",Ah],["aikaara-compare-plans",Ch]];for(const[e,t]of u)customElements.get(e)||customElements.define(e,t)}ao();function lo(u,e,t=""){if(!e)return t;const r=e.split(".");let l=u;for(const n of r)if(l&&typeof l=="object"&&n in l)l=l[n];else return t;return typeof l=="string"?l:t}function Oh(u){try{const e=u.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 Lr(u){return typeof u=="function"?await u():u}class yl{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}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 Lr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",l={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:l};n==="POST"&&(l["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const b=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${b.slice(0,200)}`)}const s=await o.json().catch(()=>({})),a=lo(s,this.descriptor.tokenPath??"data.token"),c=this.descriptor.tokenStripPrefix,d=c?a.replace(new RegExp(`^${c}`,"i"),"").trim():a;if(!d)throw new Error("Session auth response missing token");const p=lo(s,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=lo(s,this.descriptor.fullNamePath??"data.fullName"),m=Oh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:m},this.cache}}async function vl(u){const e={};for(const t of u.spec){const r=await Ph(t,u.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 Ph(u,e){const t=u.key??u.name;switch(u.source){case"cookie":return Mh(t);case"localStorage":return Nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Nr(()=>document.querySelector(`meta[name="${Rh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[u.name];if(!r)return;const l=await r();return typeof l=="string"?l:void 0}default:return}}function Mh(u){if(typeof document>"u")return;const e=encodeURIComponent(u),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const l=r.indexOf("=");if(l===-1)continue;const n=r.slice(0,l);if(n===u||n===e)try{return decodeURIComponent(r.slice(l+1))}catch{return r.slice(l+1)}}}function Nr(u){try{return u()}catch{return}}function Rh(u){return u.replace(/["\\]/g,"\\$&")}const jh=1800;class wl{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(){const e=await vl({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 l=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!l)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(l,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const o=(await n.json().catch(()=>({}))).user??{},s=String(o.ext_uid??o.extUid??""),a=String(o.token??o.user_token??o.userToken??"");if(!s)throw new Error("SSO exchange response missing user.ext_uid");if(!a)throw new Error("SSO exchange response missing user.token");const c={id:o.id,extUid:s,userToken:a,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=c,this.persistCache(c),c}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??jh;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{}}}function Lh(){const u=typeof crypto<"u"?crypto:null;if(u?.randomUUID)return u.randomUUID();if(u?.getRandomValues){const e=new Uint8Array(16);u.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 Nh="aikaara_chat:requestId";function uo(u,e){return`${Nh}:${u}:${e}`}function Uh(u,e){try{return localStorage.getItem(uo(u,e))}catch{return null}}function Bh(u,e,t){try{localStorage.setItem(uo(u,e),t)}catch{}}function Fh(u,e){try{localStorage.removeItem(uo(u,e))}catch{}}async function Dh(u,e){console.log("[aikaara-chat-sdk] preflight running",u.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[o,s]of Object.entries(e.identity))typeof s=="string"&&(t[o]=s);const r=o=>o.replace(/\{(\w+)\}/g,(s,a)=>a in t?t[a]:""),l=o=>{if(typeof o=="string")return r(o);if(Array.isArray(o))return o.map(l);if(o&&typeof o=="object"){const s={};for(const[a,c]of Object.entries(o))s[a]=l(c);return s}return o},n=await Lr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let o=0;o<u.length;o++){const s=u[o],a=r(s.url),c=s.method??(s.body?"POST":"GET"),d={accept:"application/json",...s.headers??{}};if((s.authHeader??"session")==="session"){const b=s.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:c,headers:d};s.body&&(d["content-type"]="application/json",p.body=JSON.stringify(l(s.body)));let y=0,f="",m=0;for(;;)try{const b=await fetch(a,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),m<i.length&&$h(y,f)){const g=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} ${c} ${a} → ${y} (transient). Retry #${m} in ${g}ms.`),await new Promise(_=>setTimeout(_,g));continue}const k=`Preflight #${o} ${c} ${a} → ${y} ${f.slice(0,200)}`;if(s.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(m<i.length){const k=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} threw, retry #${m} in ${k}ms`,b),await new Promise(g=>setTimeout(g,k));continue}if(s.soft){console.warn(`[aikaara-chat-sdk] preflight #${o} soft-failed:`,b);break}throw b}}}function $h(u,e){if(u===503||u===504||u===502)return!0;if(u===401||u===403)return e.trim().length===0;if(u===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function _l(u,e){const t=await fetch(u,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const l=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${l.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 Wh(u,e){return u.replace("{projectId}",e).replace("{uuid}",Lh().replace(/-/g,""))}async function kl(u){const e={...u.config??(u.configUrl?await _l(u.configUrl,u.configHeaders):{}),...u.overrides??{}},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 l=r?.projectId??"",n=u.identity.userId,i=u.forceNewConversation?null:Uh(n,l),o=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",s=u.conversationId??i??Wh(o,l);(!i||u.forceNewConversation)&&l&&Bh(n,l,s);const a=await u.tokenProvider(),c=u.tokenProvider,d=u.historyTokenProvider??c,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:a,userId:n,userName:u.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,...u.identity.departmentId?{departmentId:u.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:u.identity.senderFullname??u.identity.userName,tokenProvider:c}:void 0,y=u.uploadAdapter??(e.uploadEndpoint?ro({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=u.historyAdapter??(e.historyApiBase?nl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),m={transport:t,baseUrl:"",userToken:u.userToken??n,conversationId:s,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:u.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,tiledesk:p,tiledeskIdentity:{userId:n,userName:u.identity.userName,departmentId:u.identity.departmentId,senderFullname:u.identity.senderFullname??u.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:u.onError,onMessage:u.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(m),m.title&&b.setAttribute("title",m.title),m.primaryColor&&b.setAttribute("primary-color",m.primaryColor),m.display&&b.setAttribute("display",m.display),m.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),u.container.appendChild(b),{widget:b,requestId:s,config:m,destroy(){b.remove()}}}function qh(u){if(typeof u!="string")return u;const e=document.querySelector(u);if(!e)throw new Error(`mountFromSlug: container "${u}" not found`);return e}async function Sl(u){const e=(u.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/widget_configs/${encodeURIComponent(u.slug)}`;let r=null;try{r=await _l(t,u.configHeaders)}catch(b){if(!u.fallbackConfig)throw b;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${u.slug}" — using fallbackConfig.`,b)}const l={...u.fallbackConfig??{},...r??{},...u.overrides??{}};if(window.__aikaara_descriptor__={templates:l.templates},!l.auth)throw new Error(`mountFromSlug: widget_configs/${u.slug} descriptor must include "auth" block`);let n=null,i=u.user.id,o=u.user.name,s="";if(l.sso){const b=`${e}/api/v1/projects/by-slug/${encodeURIComponent(u.slug)}/sso_exchange`;n=await new wl({descriptor:l.sso,providers:u.user.credentialProviders,exchangeUrl:b}).get(),i=n.extUid||i,o=o??n.displayName,s=n.userToken}l.preflight&&l.preflight.length&&await Dh(l.preflight,{sessionToken:u.user.token,userId:i,projectId:l.tiledesk?.projectId??"",slug:u.slug,identity:u.user.identity});const a=new yl(l.auth,u.user.token),c=await a.get(),d=c.fullName||o||i,p=l.upload,y=async()=>`Bearer ${p&&"tokenSource"in p&&p.tokenSource==="chat"?(await a.get()).token:await Lr(u.user.token)}`,f=u.hooks?.upload??(p&&p.mode==="presigned-3step"?rl({...p,authHeader:y}):p&&p.mode==="direct"?ro({endpoint:p.endpoint,fieldName:p.fieldName,extraFields:p.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await kl({container:qh(u.container),config:l,userToken:s||void 0,identity:{userId:i,userName:d,departmentId:u.user.departmentId,senderFullname:d},tokenProvider:async()=>(await a.get()).token,historyTokenProvider:async()=>(await a.get()).token,uploadAdapter:f,historyAdapter:u.hooks?.history,conversationId:c.requestId,onError:u.hooks?.onError,onMessage:u.hooks?.onMessage,getLinkBearer:async b=>b==="none"?null:b==="chat"?(await a.get()).token:Lr(u.user.token)});return Object.assign(m,{fullName:d,requestId:c.requestId,descriptor:l,async refreshAuth(){a.reset(),await a.get()}})}function Hh(u){ao();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,l]of Object.entries(t)){const n=u[r];n!=null&&e.setAttribute(l,String(n))}return e.configure(u),document.body.appendChild(e),e}function zh(){const u=document.querySelector("aikaara-chat-widget");u&&u.remove()}class El 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=`
965
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const l=Number(r.dataset.col),n=e[l];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function so(u){return u.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function ao(){const u=[["aikaara-chat-widget",il],["aikaara-chat-bubble",ol],["aikaara-chat-header",sl],["aikaara-message-list",ll],["aikaara-message-bubble",cl],["aikaara-chat-input",fl],["aikaara-typing-indicator",dl],["aikaara-streaming-message",pl],["aikaara-error-banner",gl],["aikaara-template-renderer",bh],["aikaara-system-pill",wh],["aikaara-option-list",_h],["aikaara-submit-action",kh],["aikaara-modal-action",Eh],["aikaara-chat",xh],["aikaara-link-modal",Ah],["aikaara-compare-plans",Ch]];for(const[e,t]of u)customElements.get(e)||customElements.define(e,t)}ao();function lo(u,e,t=""){if(!e)return t;const r=e.split(".");let l=u;for(const n of r)if(l&&typeof l=="object"&&n in l)l=l[n];else return t;return typeof l=="string"?l:t}function Oh(u){try{const e=u.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 Lr(u){return typeof u=="function"?await u():u}class yl{constructor(e,t){this.descriptor=e,this.sessionToken=t}cache=null;inflight=null;reset(){this.cache=null,this.inflight=null}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 Lr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",l={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:l};n==="POST"&&(l["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const o=await fetch(this.descriptor.endpoint,i);if(!o.ok){const b=await o.text().catch(()=>"");throw new Error(`Session auth failed: ${o.status} ${b.slice(0,200)}`)}const s=await o.json().catch(()=>({})),a=lo(s,this.descriptor.tokenPath??"data.token"),c=this.descriptor.tokenStripPrefix,d=c?a.replace(new RegExp(`^${c}`,"i"),"").trim():a;if(!d)throw new Error("Session auth response missing token");const p=lo(s,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=lo(s,this.descriptor.fullNamePath??"data.fullName"),m=Oh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:m},this.cache}}async function vl(u){const e={};for(const t of u.spec){const r=await Ph(t,u.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 Ph(u,e){const t=u.key??u.name;switch(u.source){case"cookie":return Mh(t);case"localStorage":return Nr(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Nr(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Nr(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Nr(()=>document.querySelector(`meta[name="${Rh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[u.name];if(!r)return;const l=await r();return typeof l=="string"?l:void 0}default:return}}function Mh(u){if(typeof document>"u")return;const e=encodeURIComponent(u),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const l=r.indexOf("=");if(l===-1)continue;const n=r.slice(0,l);if(n===u||n===e)try{return decodeURIComponent(r.slice(l+1))}catch{return r.slice(l+1)}}}function Nr(u){try{return u()}catch{return}}function Rh(u){return u.replace(/["\\]/g,"\\$&")}const jh=1800;class wl{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(){const e=await vl({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 l=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!l)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(l,{method:"POST",headers:r,body:t});if(!n.ok){const d=await n.text().catch(()=>"");throw new Error(`SSO exchange failed: ${n.status} ${d.slice(0,240)}`)}const o=(await n.json().catch(()=>({}))).user??{},s=String(o.ext_uid??o.extUid??""),a=String(o.token??o.user_token??o.userToken??"");if(!s)throw new Error("SSO exchange response missing user.ext_uid");if(!a)throw new Error("SSO exchange response missing user.token");const c={id:o.id,extUid:s,userToken:a,email:typeof o.email=="string"?o.email:void 0,displayName:typeof o.display_name=="string"?o.display_name:typeof o.displayName=="string"?o.displayName:void 0,properties:o.properties&&typeof o.properties=="object"?o.properties:void 0,expiresAt:this.computeExpiry()};return this.cache=c,this.persistCache(c),c}computeExpiry(){const e=this.opts.descriptor.cacheTtlSec??jh;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{}}}function Lh(){const u=typeof crypto<"u"?crypto:null;if(u?.randomUUID)return u.randomUUID();if(u?.getRandomValues){const e=new Uint8Array(16);u.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 Nh="aikaara_chat:requestId";function uo(u,e){return`${Nh}:${u}:${e}`}function Uh(u,e){try{return localStorage.getItem(uo(u,e))}catch{return null}}function Bh(u,e,t){try{localStorage.setItem(uo(u,e),t)}catch{}}function Fh(u,e){try{localStorage.removeItem(uo(u,e))}catch{}}async function Dh(u,e){console.log("[aikaara-chat-sdk] preflight running",u.length,"steps");const t={userId:e.userId,projectId:e.projectId,slug:e.slug};if(e.identity)for(const[o,s]of Object.entries(e.identity))typeof s=="string"&&(t[o]=s);const r=o=>o.replace(/\{(\w+)\}/g,(s,a)=>a in t?t[a]:""),l=o=>{if(typeof o=="string")return r(o);if(Array.isArray(o))return o.map(l);if(o&&typeof o=="object"){const s={};for(const[a,c]of Object.entries(o))s[a]=l(c);return s}return o},n=await Lr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let o=0;o<u.length;o++){const s=u[o],a=r(s.url),c=s.method??(s.body?"POST":"GET"),d={accept:"application/json",...s.headers??{}};if((s.authHeader??"session")==="session"){const b=s.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:c,headers:d};s.body&&(d["content-type"]="application/json",p.body=JSON.stringify(l(s.body)));let y=0,f="",m=0;for(;;)try{const b=await fetch(a,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),m<i.length&&$h(y,f)){const g=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} ${c} ${a} → ${y} (transient). Retry #${m} in ${g}ms.`),await new Promise(_=>setTimeout(_,g));continue}const k=`Preflight #${o} ${c} ${a} → ${y} ${f.slice(0,200)}`;if(s.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(m<i.length){const k=i[m++];console.warn(`[aikaara-chat-sdk] preflight #${o} threw, retry #${m} in ${k}ms`,b),await new Promise(g=>setTimeout(g,k));continue}if(s.soft){console.warn(`[aikaara-chat-sdk] preflight #${o} soft-failed:`,b);break}throw b}}}function $h(u,e){if(u===503||u===504||u===502)return!0;if(u===401||u===403)return e.trim().length===0;if(u===500){const t=e.toLowerCase();return t.includes("customernew")||t.includes("is null")||t.includes("not yet ready")}return!1}async function _l(u,e){const t=await fetch(u,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const l=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${l.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 Wh(u,e){return u.replace("{projectId}",e).replace("{uuid}",Lh().replace(/-/g,""))}async function kl(u){const e={...u.config??(u.configUrl?await _l(u.configUrl,u.configHeaders):{}),...u.overrides??{}},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 l=r?.projectId??"",n=u.identity.userId,i=u.forceNewConversation?null:Uh(n,l),o=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",s=u.conversationId??i??Wh(o,l);(!i||u.forceNewConversation)&&l&&Bh(n,l,s);const a=await u.tokenProvider(),c=u.tokenProvider,d=u.historyTokenProvider??c,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:a,userId:n,userName:u.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,...u.identity.departmentId?{departmentId:u.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:u.identity.senderFullname??u.identity.userName,tokenProvider:c}:void 0,y=u.uploadAdapter??(e.uploadEndpoint?ro({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=u.historyAdapter??(e.historyApiBase?nl({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),m={transport:t,baseUrl:"",userToken:u.userToken??n,conversationId:s,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:u.getLinkBearer,welcomeMessage:e.welcomeMessage,placeholder:e.placeholder,showTimestamps:e.showTimestamps,persistConversation:e.persistConversation,tiledesk:p,tiledeskIdentity:{userId:n,userName:u.identity.userName,departmentId:u.identity.departmentId,senderFullname:u.identity.senderFullname??u.identity.userName},templateActionAttributes:e.templateActionAttributes,uploadAdapter:y,historyAdapter:f,onError:u.onError,onMessage:u.onMessage},b=document.createElement("aikaara-chat-widget");return b.configure(m),m.title&&b.setAttribute("title",m.title),m.primaryColor&&b.setAttribute("primary-color",m.primaryColor),m.display&&b.setAttribute("display",m.display),m.display==="embed"&&(b.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;"),u.container.appendChild(b),{widget:b,requestId:s,config:m,destroy(){b.remove()}}}function qh(u){if(typeof u!="string")return u;const e=document.querySelector(u);if(!e)throw new Error(`mountFromSlug: container "${u}" not found`);return e}async function Sl(u){const e=(u.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(u.slug)}`;let r=null;try{r=await _l(t,u.configHeaders)}catch(b){if(!u.fallbackConfig)throw b;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${u.slug}" — using fallbackConfig.`,b)}const l={...u.fallbackConfig??{},...r??{},...u.overrides??{}};if(window.__aikaara_descriptor__={templates:l.templates},!l.auth)throw new Error(`mountFromSlug: widget_configs/${u.slug} descriptor must include "auth" block`);let n=null,i=u.user.id,o=u.user.name,s="";if(l.sso){const b=`${e}/api/v1/projects/by-slug/${encodeURIComponent(u.slug)}/sso_exchange`;n=await new wl({descriptor:l.sso,providers:u.user.credentialProviders,exchangeUrl:b}).get(),i=n.extUid||i,o=o??n.displayName,s=n.userToken}l.preflight&&l.preflight.length&&await Dh(l.preflight,{sessionToken:u.user.token,userId:i,projectId:l.tiledesk?.projectId??"",slug:u.slug,identity:u.user.identity});const a=new yl(l.auth,u.user.token),c=await a.get(),d=c.fullName||o||i,p=l.upload,y=async()=>`Bearer ${p&&"tokenSource"in p&&p.tokenSource==="chat"?(await a.get()).token:await Lr(u.user.token)}`,f=u.hooks?.upload??(p&&p.mode==="presigned-3step"?rl({...p,authHeader:y}):p&&p.mode==="direct"?ro({endpoint:p.endpoint,fieldName:p.fieldName,extraFields:p.extraFields,headers:async()=>({authorization:await y()})}):void 0),m=await kl({container:qh(u.container),config:l,userToken:s||void 0,identity:{userId:i,userName:d,departmentId:u.user.departmentId,senderFullname:d},tokenProvider:async()=>(await a.get()).token,historyTokenProvider:async()=>(await a.get()).token,uploadAdapter:f,historyAdapter:u.hooks?.history,conversationId:c.requestId,onError:u.hooks?.onError,onMessage:u.hooks?.onMessage,getLinkBearer:async b=>b==="none"?null:b==="chat"?(await a.get()).token:Lr(u.user.token)});return Object.assign(m,{fullName:d,requestId:c.requestId,descriptor:l,async refreshAuth(){a.reset(),await a.get()}})}function Hh(u){ao();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,l]of Object.entries(t)){const n=u[r];n!=null&&e.setAttribute(l,String(n))}return e.configure(u),document.body.appendChild(e),e}function zh(){const u=document.querySelector("aikaara-chat-widget");u&&u.remove()}class El 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=`
966
966
  <style>
967
967
  :host { display: block; margin-top: 8px; }
968
968
  button {
package/dist/headless.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./MountTenant-DiXJuVIV.cjs");class r extends i.EventEmitter{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(s=>s.entity_type===e.entityType&&String(s.entity_id)===String(e.entityId));if(t.length>0){for(const s of t)e.onFieldUpdate(s.fields),this.emit("edit:applied",{entityType:s.entity_type,entityId:s.entity_id,fields:s.fields});this.pendingEdits=this.pendingEdits.filter(s=>!(s.entity_type===e.entityType&&String(s.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,s){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(s),this.emit("edit:applied",{entityType:e,entityId:t,fields:s})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:s}),this.emit("edit:pending",{entityType:e,entityId:t,fields:s}))}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(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}exports.ActionCableClient=i.ActionCableClient;exports.AikaaraChatClient=i.AikaaraChatClient;exports.ApiClient=i.ApiClient;exports.ChannelSubscription=i.ChannelSubscription;exports.ConnectionManager=i.ConnectionManager;exports.ConversationManager=i.ConversationManager;exports.EventEmitter=i.EventEmitter;exports.MessageStore=i.MessageStore;exports.SessionAuthAdapter=i.SessionAuthAdapter;exports.SsoExchangeAdapter=i.SsoExchangeAdapter;exports.TiledeskTransport=i.TiledeskTransport;exports.clearPersistedConversationId=i.clearPersistedConversationId;exports.collectSsoCredentials=i.collectSsoCredentials;exports.createFetchUploadAdapter=i.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=i.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=i.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=i.extractTiledeskFileEnvelope;exports.inferTiledeskRole=i.inferTiledeskRole;exports.isTiledeskSelfEcho=i.isTiledeskSelfEcho;exports.mountFromSlug=i.mountFromSlug;exports.mountTenantWidget=i.mount;exports.parseTiledeskTemplate=i.parseTiledeskTemplate;exports.FormBridge=r;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("./MountTenant-CCzIgtae.cjs");class r extends i.EventEmitter{registration=null;pendingEdits=[];constructor(e){super(),this.setupListeners(e)}registerForm(e){this.registration=e;const t=this.pendingEdits.filter(s=>s.entity_type===e.entityType&&String(s.entity_id)===String(e.entityId));if(t.length>0){for(const s of t)e.onFieldUpdate(s.fields),this.emit("edit:applied",{entityType:s.entity_type,entityId:s.entity_id,fields:s.fields});this.pendingEdits=this.pendingEdits.filter(s=>!(s.entity_type===e.entityType&&String(s.entity_id)===String(e.entityId)))}}unregisterForm(e,t){this.registration?.entityType===e&&String(this.registration?.entityId)===String(t)&&(this.registration=null)}get currentForm(){return this.registration}pushFieldUpdates(e,t,s){this.registration&&this.registration.entityType===e&&String(this.registration.entityId)===String(t)?(this.registration.onFieldUpdate(s),this.emit("edit:applied",{entityType:e,entityId:t,fields:s})):(this.pendingEdits.push({action:"edit_entity",entity_type:e,entity_id:t,fields:s}),this.emit("edit:pending",{entityType:e,entityId:t,fields:s}))}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(e){const t=e instanceof Error?e.message:"Save failed";return this.emit("save:error",{entityType:this.registration.entityType,entityId:this.registration.entityId,error:t}),{success:!1,error:t}}}async requestTest(e){if(!this.registration?.onTest)return{success:!1,error:"Current form does not support testing"};try{return await this.registration.onTest(e),{success:!0}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Test failed"}}}setupListeners(e){e.on("action:edit_entity",t=>{this.pushFieldUpdates(t.entity_type,t.entity_id,t.fields)}),e.on("action:save_entity",t=>{this.requestSave()}),e.on("action:test_tool",t=>{this.emit("test:triggered",{toolId:t.tool_id,parameters:t.parameters}),this.requestTest(t.parameters)})}}exports.ActionCableClient=i.ActionCableClient;exports.AikaaraChatClient=i.AikaaraChatClient;exports.ApiClient=i.ApiClient;exports.ChannelSubscription=i.ChannelSubscription;exports.ConnectionManager=i.ConnectionManager;exports.ConversationManager=i.ConversationManager;exports.EventEmitter=i.EventEmitter;exports.MessageStore=i.MessageStore;exports.SessionAuthAdapter=i.SessionAuthAdapter;exports.SsoExchangeAdapter=i.SsoExchangeAdapter;exports.TiledeskTransport=i.TiledeskTransport;exports.clearPersistedConversationId=i.clearPersistedConversationId;exports.collectSsoCredentials=i.collectSsoCredentials;exports.createFetchUploadAdapter=i.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=i.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=i.createTiledeskHistoryAdapter;exports.extractTiledeskFileEnvelope=i.extractTiledeskFileEnvelope;exports.inferTiledeskRole=i.inferTiledeskRole;exports.isTiledeskSelfEcho=i.isTiledeskSelfEcho;exports.mountFromSlug=i.mountFromSlug;exports.mountTenantWidget=i.mount;exports.parseTiledeskTemplate=i.parseTiledeskTemplate;exports.FormBridge=r;
@@ -1026,7 +1026,7 @@ export declare interface SlugMountedWidget extends MountedTenantWidget {
1026
1026
  export declare interface SlugMountOptions {
1027
1027
  /** Container element or CSS selector (e.g. `#chat`). */
1028
1028
  container: HTMLElement | string;
1029
- /** Tenant identifier — the SDK fetches `${configBase}/widget_configs/${slug}`. */
1029
+ /** Tenant identifier — the SDK fetches `${configBase}/api/v1/widget_configs/${slug}`. */
1030
1030
  slug: string;
1031
1031
  /** Defaults to `https://api.aikaara.com`. Override for self-hosted aikaara. */
1032
1032
  configBase?: string;
package/dist/headless.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { E as s } from "./MountTenant-5pQsm4CF.mjs";
2
- import { A as p, b as l, k as g, C as h, l as c, m as y, M as u, S as m, n as f, T as S, o as T, p as _, q as E, s as v, t as C, u as F, v as A, w as k, x as I, y as x, z as U } from "./MountTenant-5pQsm4CF.mjs";
1
+ import { E as s } from "./MountTenant-B3tAZZRN.mjs";
2
+ import { A as p, b as l, k as g, C as h, l as c, m as y, M as u, S as m, n as f, T as S, o as T, p as _, q as E, s as v, t as C, u as F, v as A, w as k, x as I, y as x, z as U } from "./MountTenant-B3tAZZRN.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-DiXJuVIV.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[n,o]of Object.entries(i)){const r=a[n];r!=null&&t.setAttribute(o,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.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;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-CCzIgtae.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[n,o]of Object.entries(i)){const r=a[n];r!=null&&t.setAttribute(o,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.clearPersistedConversationId=e.clearPersistedConversationId;exports.collectSsoCredentials=e.collectSsoCredentials;exports.createFetchUploadAdapter=e.createFetchUploadAdapter;exports.createPresigned3StepUploadAdapter=e.createPresigned3StepUploadAdapter;exports.createTiledeskHistoryAdapter=e.createTiledeskHistoryAdapter;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.d.ts CHANGED
@@ -917,7 +917,7 @@ export declare interface SlugMountedWidget extends MountedTenantWidget {
917
917
  export declare interface SlugMountOptions {
918
918
  /** Container element or CSS selector (e.g. `#chat`). */
919
919
  container: HTMLElement | string;
920
- /** Tenant identifier — the SDK fetches `${configBase}/widget_configs/${slug}`. */
920
+ /** Tenant identifier — the SDK fetches `${configBase}/api/v1/widget_configs/${slug}`. */
921
921
  slug: string;
922
922
  /** Defaults to `https://api.aikaara.com`. Override for self-hosted aikaara. */
923
923
  configBase?: string;
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { r as o } from "./MountTenant-5pQsm4CF.mjs";
2
- import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as b, h as f, i as S, j as T, k as v, C as y, l as w, m as M, E, M as x, S as B, n as F, T as U, o as I, p as j, q, s as H, t as P, u as W, v as z, w as K, x as L, y as O, z as R } from "./MountTenant-5pQsm4CF.mjs";
1
+ import { r as o } from "./MountTenant-B3tAZZRN.mjs";
2
+ import { A as u, a as m, b as g, c as h, d as k, e as A, f as C, g as b, h as f, i as S, j as T, k as v, C as y, l as w, m as M, E, M as x, S as B, n as F, T as U, o as I, p as j, q, s as H, t as P, u as W, v as z, w as K, x as L, y as O, z as R } from "./MountTenant-B3tAZZRN.mjs";
3
3
  import { FormBridge as G } 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-DiXJuVIV.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.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-CCzIgtae.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.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 { B as i, a as s, c as e, d as t, e as A, D as k, f as n, F as o, g, h as l, G as d, H as m, i as p, I as C, J as h, K as b, j as M, r as c } from "./MountTenant-5pQsm4CF.mjs";
1
+ import { B as i, a as s, c as e, d as t, e as A, D as k, f as n, F as o, g, h as l, G as d, H as m, i as p, I as C, J as h, K as b, j as M, r as c } from "./MountTenant-B3tAZZRN.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": "0.7.7",
3
+ "version": "0.7.8",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",