@aikaara/chat-sdk 0.9.4 → 0.9.5

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.
@@ -248,7 +248,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
248
248
  </svg>
249
249
  </button>
250
250
  </div>
251
- `}setStatus(e){this.setAttribute("status",e)}}const _h=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Nt(c){if(_h.test(c))return c;let e=kh(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function kh(c){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return c.replace(/[&<>"']/g,t=>e[t])}const Sh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Eh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Ut(c){const e=document.createElement("template");return e.innerHTML=c,fl(e.content),e.innerHTML}function fl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!Sh.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=Eh[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}fl(t)}}class dl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!e)return!1;const t=e.trim().toLowerCase();return t==="chat_initiated"||t==="group created"||t==="file_uploaded"||t==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(r=>t.includes(r)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment")||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
251
+ `}setStatus(e){this.setAttribute("status",e)}}const _h=/<\s*(br|i|b|em|strong|small|sub|sup|p|div|span|ul|ol|li|a|img|code|pre)\b/i;function Nt(c){if(_h.test(c))return c;let e=kh(c);return e=e.replace(/```(\w*)\n([\s\S]*?)```/g,(t,r,a)=>`<pre><code>${a.trim()}</code></pre>`),e=e.replace(/`([^`]+)`/g,"<code>$1</code>"),e=e.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),e=e.replace(/\*(.+?)\*/g,"<em>$1</em>"),e=e.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),e=e.replace(/\n/g,"<br>"),e}function kh(c){const e={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};return c.replace(/[&<>"']/g,t=>e[t])}const Sh=new Set(["p","br","hr","strong","em","b","i","u","s","small","sub","sup","code","pre","a","img","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","span","div","table","thead","tbody","tr","th","td"]),Eh={a:new Set(["href","target","rel"]),img:new Set(["src","alt","width","height"]),code:new Set(["class"]),pre:new Set(["class"]),span:new Set(["class"]),div:new Set(["class"])};function Ut(c){const e=document.createElement("template");return e.innerHTML=c,fl(e.content),e.innerHTML}function fl(c){const e=Array.from(c.childNodes);for(const t of e)if(t.nodeType===Node.ELEMENT_NODE){const r=t,a=r.tagName.toLowerCase();if(!Sh.has(a)){const s=document.createTextNode(r.textContent||"");c.replaceChild(s,t);continue}const n=Eh[a]||new Set,i=Array.from(r.attributes);for(const s of i)n.has(s.name)||r.removeAttribute(s.name);if(r.hasAttribute("href")){const s=r.getAttribute("href")||"";!s.startsWith("http://")&&!s.startsWith("https://")&&!s.startsWith("/")&&r.removeAttribute("href")}fl(t)}}function xh(c){const e=Date.now()-c.getTime(),t=Math.round(e/1e3);if(t<5)return"just now";if(t<60)return`${t}s ago`;const r=Math.round(t/60);if(r<60)return`${r} min ago`;const a=Math.round(r/60);if(a<24)return`${a} hr ago`;const n=Math.round(a/24);return n===1?"Yesterday":n<7?`${n} d ago`:c.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}class dl extends HTMLElement{shadow;container;welcomeMessage="";showTimestamps=!0;timestampFormat="time";hideSystemMessages=[];linkHandlers=[];getLinkBearer=null;setHideSystemMessages(e){this.hideSystemMessages=(e??[]).map(t=>t.toLowerCase())}setTimestampFormat(e){this.timestampFormat=e,e==="none"&&(this.showTimestamps=!1)}templateLayout="inside";setTemplateLayout(e){this.templateLayout=e}shouldHideMessage(e){if(!e)return!1;const t=e.trim().toLowerCase();return t==="chat_initiated"||t==="group created"||t==="file_uploaded"||t==="file_upload"?!0:this.hideSystemMessages.length?this.hideSystemMessages.some(r=>t.includes(r)):!1}setLinkConfig(e,t){this.linkHandlers=e,this.getLinkBearer=t??null}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.addEventListener("template-action",e=>{const t=e.detail;this.dispatchEvent(new CustomEvent("message-action",{detail:t,bubbles:!0,composed:!0}))}),this.addEventListener("click",e=>{const t=e.composedPath?.()??[],r=t.find(n=>n&&n.tagName==="A");!r||!r.href||r.dataset.noModal!==void 0||r.target==="_blank"||r.classList.contains("attachment")||t.some(n=>{if(!n||!n.classList)return!1;const i=n.classList;return i.contains("bubble")&&i.contains("user")})||/^https?:\/\//i.test(r.href)&&(e.preventDefault(),this.handleLinkClick(r.href,r.textContent?.trim()||void 0))}),this.shadow.innerHTML=`
252
252
  <style>
253
253
  :host {
254
254
  display: flex;
@@ -401,7 +401,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
401
401
  }
402
402
  </style>
403
403
  <div class="message-list"></div>
404
- `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ut(Nt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ut(Nt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=Ut(Nt(e.content))):(a.innerHTML=Ut(Nt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e);switch(this.timestampFormat){case"datetime":return`${t.toLocaleDateString(void 0,{month:"short",day:"2-digit"})}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"date":return t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>xh(e,y.match)),a=r?.target??"iframe";if(a==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(a==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const s=Ah(e),o=pl(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(l.authorization=`Bearer ${y}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(io(r.fetch.body,s)));let p=null;try{const y=await fetch(o,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,y=>{const f=r.props??{setData:p};for(const[b,k]of Object.entries(f)){const m=y[b];typeof m=="function"&&m.call(y,k)}const g=b=>{const k=b,m=k.detail?.message??k.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...k.detail?.attributes??{}}},bubbles:!0,composed:!0})))};y.addEventListener("aikaara-plan-select",g),y.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function xh(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function Ah(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function pl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function io(c,e){if(typeof c=="string")return pl(c,e);if(Array.isArray(c))return c.map(t=>io(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=io(a,e);return t}return c}class gl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",a=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",o=e==="user"?document.createTextNode(t).textContent||"":Ut(Nt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
404
+ `,this.container=this.shadow.querySelector(".message-list"),this.welcomeMessage&&this.renderMessages([])}setWelcomeMessage(e){this.welcomeMessage=e}setShowTimestamps(e){this.showTimestamps=e}renderMessages(e){if(!this.container)return;if(this.container.innerHTML="",e.length===0&&this.welcomeMessage){this.container.innerHTML=`<div class="welcome">${Ut(Nt(this.welcomeMessage))}</div>`;return}const t=this.computeConsumedIds(e);for(const r of e)this.appendMessageElement(r,t.has(r.externalId??r.id));this.scrollToBottom()}computeConsumedIds(e){const t=new Set;let r=-1;for(let a=e.length-1;a>=0;a--)if(e[a].role==="user"){r=a;break}for(let a=0;a<e.length;a++){const n=e[a];if(n.role==="user"){const i=n.metadata?.attributes?.action;i?.message_id&&t.add(i.message_id)}n.role!=="user"&&n.template?.contentType&&a<r&&t.add(n.externalId??n.id)}return t}addMessage(e){const t=this.container.querySelector(".welcome");t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}updateStreamingContent(e){const t=this.container.querySelector('[data-streaming="true"] .bubble');t&&(t.innerHTML=Ut(Nt(e)),t.classList.add("streaming-cursor"),this.scrollToBottom())}finalizeStreaming(){const e=this.container.querySelector('[data-streaming="true"]');e&&(e.removeAttribute("data-streaming"),e.querySelector(".bubble")?.classList.remove("streaming-cursor"))}showTypingIndicator(){this.removeTypingIndicator();const e=document.createElement("div");e.classList.add("typing-indicator"),e.setAttribute("data-typing","true"),e.innerHTML='<span class="dot"></span><span class="dot"></span><span class="dot"></span>',this.container.appendChild(e),this.scrollToBottom()}removeTypingIndicator(){this.container.querySelector('[data-typing="true"]')?.remove()}appendMessageElement(e,t=!1){if(e.role==="user"&&e.content?.trim()==="CHAT_INITIATED"||this.shouldHideMessage(e.content))return;if(e.role==="system"){const o=document.createElement("div");o.classList.add("message-wrap","system"),o.dataset.messageId=e.id,e.externalId&&(o.dataset.externalId=e.externalId);const l=document.createElement("aikaara-system-pill");l.setAttribute("text",e.content||""),this.showTimestamps&&e.createdAt&&l.setAttribute("subtext",this.formatTime(e.createdAt)),o.appendChild(l),this.container.appendChild(o);return}const r=document.createElement("div");r.classList.add("message-wrap",e.role),e.status==="streaming"&&r.setAttribute("data-streaming","true"),e.externalId&&(r.dataset.externalId=e.externalId),r.dataset.messageId=e.id;const a=document.createElement("div");a.classList.add("bubble",e.role);const i=!!e.template?.contentType&&e.role!=="user";e.role==="user"?a.textContent=e.content:i?e.content&&(a.innerHTML=Ut(Nt(e.content))):(a.innerHTML=Ut(Nt(e.content||"")),e.status==="streaming"&&a.classList.add("streaming-cursor"));let s=null;if(e.template?.contentType){const o=document.createElement("aikaara-template-renderer");o.setAttribute("content-type",e.template.contentType),e.template.templateId&&o.setAttribute("template-id",e.template.templateId);const l=e.externalId??e.id;l&&o.setAttribute("message-id",l),o.setPayload(e.template.payload),t&&(o.dataset.consumed="true"),this.templateLayout==="outside"?(o.classList.add("template-outside"),s=o):a.appendChild(o)}if(e.attachments?.length){const o=document.createElement("div");o.classList.add("attachments");for(const l of e.attachments){const u=document.createElement("a");u.classList.add("attachment"),u.href=l.fileUrl,u.target="_blank",u.rel="noopener noreferrer",u.textContent=`📎 ${l.fileName}`,o.appendChild(u)}a.appendChild(o)}if(r.appendChild(a),s&&r.appendChild(s),this.showTimestamps&&e.createdAt||e.role==="user"&&e.status){const o=document.createElement("div");if(o.classList.add("timestamp"),this.showTimestamps&&e.createdAt&&(o.textContent=this.formatTime(e.createdAt)),e.role==="user"&&e.status){const l=document.createElement("span");l.classList.add("status-tick"),e.status==="read"&&l.classList.add("read"),l.textContent={sending:" ○",sent:" ✓",delivered:" ✓✓",read:" ✓✓"}[e.status]??"",o.appendChild(l)}r.appendChild(o)}this.container.appendChild(r)}upsertMessage(e){const t=this.findRenderedMessage(e);t&&t.remove(),this.appendMessageElement(e),this.scrollToBottom()}findRenderedMessage(e){if(e.externalId){const t=this.container.querySelector(`[data-external-id="${CSS.escape(e.externalId)}"]`);if(t)return t}return this.container.querySelector(`[data-message-id="${CSS.escape(e.id)}"]`)}scrollToBottom(){requestAnimationFrame(()=>{this.container.scrollTop=this.container.scrollHeight})}formatTime(e){try{const t=new Date(e),r=t.toLocaleDateString(void 0,{month:"short",day:"2-digit"});switch(this.timestampFormat){case"datetime":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;case"datetime-seconds":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`;case"datetime-24":return`${r}, ${t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1})}`;case"date":return r;case"relative":return xh(t);case"time-24":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",hour12:!1});case"time-seconds":return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit",second:"2-digit"});case"none":return"";default:return t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}}catch{return""}}async handleLinkClick(e,t){const r=this.linkHandlers.find(y=>Ah(e,y.match)),a=r?.target??"iframe";if(a==="tab"){window.open(e,"_blank","noopener,noreferrer");return}const n=this.getOrCreateModal(),i=r?.title??t??"Link";if(a==="iframe"||!r?.fetch||!r.render){requestAnimationFrame(()=>n.show?.(e,i));return}const s=Ih(e),o=pl(r.fetch.url,s),l={accept:"application/json",...r.fetch.headers??{}},u=r.fetch.authHeader??"session";if(u!=="none"&&this.getLinkBearer){const y=await this.getLinkBearer(u);y&&(l.authorization=`Bearer ${y}`)}const d={method:r.fetch.method??"GET",headers:l};r.fetch.body&&(l["content-type"]="application/json",d.body=JSON.stringify(io(r.fetch.body,s)));let p=null;try{const y=await fetch(o,d);y.ok&&(p=await y.json().catch(()=>null))}catch(y){console.warn("[aikaara-chat-sdk] linkHandler fetch failed",y)}requestAnimationFrame(()=>{n.showElement?.(r.render,i,y=>{const f=r.props??{setData:p};for(const[b,k]of Object.entries(f)){const m=y[b];typeof m=="function"&&m.call(y,k)}const g=b=>{const k=b,m=k.detail?.message??k.detail?.label;m&&(n.close?.(),this.dispatchEvent(new CustomEvent("message-action",{detail:{text:m,attributes:{...k.detail?.attributes??{}}},bubbles:!0,composed:!0})))};y.addEventListener("aikaara-plan-select",g),y.addEventListener("aikaara-select",g)})})}getOrCreateModal(){let e=document.querySelector("aikaara-link-modal");return e||(e=document.createElement("aikaara-link-modal"),document.body.appendChild(e)),e}}function Ah(c,e){const t=e.replace(/[.+^${}()|[\]\\]/g,"\\$&");return new RegExp("^"+t.replace(/\*/g,".*").replace(/\?/g,".")+"$","i").test(c)}function Ih(c){try{const e=new URL(c),t={};return e.searchParams.forEach((r,a)=>{t[a]=r}),t}catch{return{}}}function pl(c,e){return c.replace(/\{(\w+)\}/g,(t,r)=>e[r]??"")}function io(c,e){if(typeof c=="string")return pl(c,e);if(Array.isArray(c))return c.map(t=>io(t,e));if(c&&typeof c=="object"){const t={};for(const[r,a]of Object.entries(c))t[r]=io(a,e);return t}return c}class gl extends HTMLElement{shadow;templatePayload=null;attachments=[];static get observedAttributes(){return["role","content","timestamp","content-type","template-id","inner-message","message-id","status"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}setTemplatePayload(e){this.templatePayload=e,this.render()}setAttachments(e){this.attachments=e,this.render()}render(){const e=this.getAttribute("role")||"user",t=this.getAttribute("content")||"",r=this.getAttribute("timestamp")||"",a=this.getAttribute("status")||"",n=this.getAttribute("content-type")||"",i=this.getAttribute("template-id")||"",s=this.getAttribute("inner-message")||"",o=e==="user"?document.createTextNode(t).textContent||"":Ut(Nt(t)),l=e==="user"&&a,u=a==="sending"?"○":a==="sent"?"✓":a==="delivered"||a==="read"?"✓✓":"";this.shadow.innerHTML=`
405
405
  <style>
406
406
  :host { display: flex; flex-direction: column; }
407
407
  :host([role="user"]) { align-items: flex-end; }
@@ -479,8 +479,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
479
479
  </div>
480
480
  `:""}
481
481
  `;const d=this.shadow.querySelector("aikaara-template-renderer");d&&this.templatePayload!==null&&d.setPayload(this.templatePayload,s),d&&d.addEventListener("template-action",p=>{this.dispatchEvent(new CustomEvent("message-action",{detail:p.detail,bubbles:!0,composed:!0}))})}renderAttachments(){return this.attachments.length?`<div class="attachments">${this.attachments.map(t=>`<a class="attachment" href="${ml(t.fileUrl)}" target="_blank" rel="noopener noreferrer">
482
- 📎 ${Ih(t.fileName)}
483
- </a>`).join("")}</div>`:""}}function ml(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Ih(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class bl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",a=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",s=t?`
482
+ 📎 ${Th(t.fileName)}
483
+ </a>`).join("")}</div>`:""}}function ml(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function Th(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class bl extends HTMLElement{shadow;textarea;sendBtn;attachBtn;fileInput;_disabled=!1;_uploading=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","disable-attach","accept","multiple","attach-position","send-shape"]}connectedCallback(){const e=this.getAttribute("placeholder")||"Type a message...",t=!this.hasAttribute("disable-attach"),r=this.getAttribute("accept")??"",a=this.hasAttribute("multiple"),n=this.getAttribute("attach-position")==="right",i=this.getAttribute("send-shape")==="square",s=t?`
484
484
  <button class="attach-btn" aria-label="Attach file" type="button">
485
485
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
486
486
  <path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"/>
@@ -669,14 +669,14 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
669
669
  <span class="message"></span>
670
670
  <button class="dismiss">Dismiss</button>
671
671
  </div>
672
- `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const oo=new Map;function _l(c){const e=oo.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{oo.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return oo.set(c,t),t}function Th(c,e=5e3){return new Promise((t,r)=>{const a=setTimeout(()=>r(new Error(`Custom element <${c}> not registered within ${e}ms`)),e);customElements.whenDefined(c).then(()=>{clearTimeout(a),t()})})}function Ch(c){const e=`template:${c}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[c]}class Oh extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",()=>{this.dataset.consumed="true"})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
672
+ `,this.container=this.shadow.querySelector(".banner"),this.shadow.querySelector(".dismiss")?.addEventListener("click",()=>this.hide())}show(e,t){const r=this.container.querySelector(".message");r&&(r.textContent=e),this.container.classList.add("visible"),this.dismissTimer&&clearTimeout(this.dismissTimer),t&&(this.dismissTimer=setTimeout(()=>this.hide(),t))}hide(){this.container.classList.remove("visible"),this.dismissTimer&&(clearTimeout(this.dismissTimer),this.dismissTimer=null)}}const oo=new Map;function _l(c){const e=oo.get(c);if(e)return e;const t=new Promise((r,a)=>{const n=document.querySelector(`script[data-aikaara-src="${CSS.escape(c)}"]`);if(n){n.dataset.aikaaraReady==="1"?r():(n.addEventListener("load",()=>r(),{once:!0}),n.addEventListener("error",()=>a(new Error(`Failed to load ${c}`)),{once:!0}));return}const i=document.createElement("script");i.src=c,i.async=!0,i.crossOrigin="anonymous",i.dataset.aikaaraSrc=c,i.addEventListener("load",()=>{i.dataset.aikaaraReady="1",r()},{once:!0}),i.addEventListener("error",()=>{oo.delete(c),a(new Error(`Failed to load ${c}`))},{once:!0}),document.head.appendChild(i)});return oo.set(c,t),t}function Ch(c,e=5e3){return new Promise((t,r)=>{const a=setTimeout(()=>r(new Error(`Custom element <${c}> not registered within ${e}ms`)),e);customElements.whenDefined(c).then(()=>{clearTimeout(a),t()})})}function Oh(c){const e=`template:${c}`,t=window.__aikaara_descriptor__?.components?.[e];return t&&t.kind==="iife-element"?{render:t.tag,scriptUrl:t.scriptUrl,props:t.props}:window.__aikaara_descriptor__?.templates?.[c]}class Ph extends HTMLElement{shadow;payloadData=null;innerMessage="";renderGen=0;static get observedAttributes(){return["content-type","template-id","message-id"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render(),this.addEventListener("template-action",()=>{this.dataset.consumed="true"})}attributeChangedCallback(){this.render()}setPayload(e,t){this.payloadData=e,t!==void 0&&(this.innerMessage=t),this.render()}render(){const e=this.getAttribute("content-type")??"",t=this.getAttribute("template-id")??"";for(this.renderGen+=1,this.shadow.innerHTML=`
673
673
  <style>
674
674
  :host { display: block; }
675
675
  :host([data-consumed]) ::slotted(*) { display: none !important; }
676
676
  ::slotted(*) { display: block; }
677
677
  </style>
678
678
  <slot></slot>
679
- `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Ch(t):void 0,a=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(a)&&_l(r.scriptUrl).then(()=>Th(a)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(a)){const n=document.createElement(a);if(r?.props){for(const[i,s]of Object.entries(r.props))if(typeof n[i]=="function")try{n[i](s)}catch(o){console.warn(`[aikaara-template-renderer] props.${i} threw on <${a}>`,o)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n);return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(o=>{const l=typeof o.title=="string"?o.title:"",u=o.message;return{label:l||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const a=document.createElement("aikaara-option-list");a.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(a);return}if(t==="submit"){const a=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;a.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(a);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>vf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:a})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Mh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Ph=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Mh(c){const e={};for(const[t,r]of Object.entries(c))Ph.has(t)||(e[t]=r);return e}class Rh extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
679
+ `;this.firstChild;)this.removeChild(this.firstChild);if(!e)return;const r=t?Oh(t):void 0,a=r?.render??(t?`aikaara-template-${t}`:`aikaara-template-${e}`);if(r?.scriptUrl&&!customElements.get(a)&&_l(r.scriptUrl).then(()=>Ch(a)).then(()=>this.render()).catch(n=>console.warn(`[aikaara-template-renderer] failed to lazy-load ${r.scriptUrl}`,n)),customElements.get(a)){const n=document.createElement(a);if(r?.props){for(const[i,s]of Object.entries(r.props))if(typeof n[i]=="function")try{n[i](s)}catch(o){console.warn(`[aikaara-template-renderer] props.${i} threw on <${a}>`,o)}}n.setPayload?.(this.payloadData,this.innerMessage),this.appendChild(n);return}if(Array.isArray(this.payloadData)){const n=this.payloadData;if(n.length>0&&n.every(s=>s&&typeof s=="object"&&!Array.isArray(s)&&!("type"in s)&&!("data"in s)&&typeof s.message=="string")){const s=document.createElement("aikaara-option-list");s.setPayload({name:"quick-reply",type:"button",options:n.map(o=>{const l=typeof o.title=="string"?o.title:"",u=o.message;return{label:l||u,value:u}})}),this.appendChild(s);return}for(const s of n)this.mountField(s)}else if(this.payloadData&&typeof this.payloadData=="object"){const n=this.payloadData;typeof n.message=="string"&&(n.okLabel||n.action||n.ok)&&this.mountModal(n)}}mountField(e){if(!e||typeof e!="object")return;const t=e.type??e.data?.type;if(t==="link"){this.mountLinkButton(e);return}const r=e.data;if(r){if(t==="checkbox"||t==="radio"||t==="button"){const a=document.createElement("aikaara-option-list");a.setPayload({name:r.name??"",title:r.title,options:r.options??[],type:t}),this.appendChild(a);return}if(t==="submit"){const a=document.createElement("aikaara-submit-action"),n=this.getAttribute("message-id")??void 0;a.setPayload({name:r.name??"Submit",action:r.action??{message:r.name??"Submit"},messageId:n}),this.appendChild(a);return}t==="modal"&&this.mountModal({message:r.message??"",okLabel:r.okLabel,cancelLabel:r.cancelLabel,action:r.action})}}mountLinkButton(e){const t=this.renderGen;Promise.resolve().then(()=>wf).then(({registerAikaaraLinkButton:r,AikaaraLinkButton:a})=>{if(t!==this.renderGen)return;r();const n=document.createElement("aikaara-link-button");n.setPayload({name:e.name??"Open",url:e.url??"",openLinkInNewTab:e.openLinkInNewTab,orderId:e.orderId,extra:Rh(e),messageId:this.getAttribute("message-id")??void 0}),this.appendChild(n)})}mountModal(e){const t=document.createElement("aikaara-modal-action");t.setPayload(e),this.appendChild(t)}}const Mh=new Set(["type","url","name","openLinkInNewTab","orderId"]);function Rh(c){const e={};for(const[t,r]of Object.entries(c))Mh.has(t)||(e[t]=r);return e}class jh extends HTMLElement{shadow;static get observedAttributes(){return["text","subtext"]}constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}attributeChangedCallback(){this.render()}render(){const e=this.getAttribute("text")??this.textContent??"",t=this.getAttribute("subtext")??"";this.shadow.innerHTML=`
680
680
  <style>
681
681
  :host {
682
682
  display: flex;
@@ -703,7 +703,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
703
703
  </style>
704
704
  <span class="pill">${kl(e)}</span>
705
705
  ${t?`<span class="sub">${kl(t)}</span>`:""}
706
- `}}function kl(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class jh extends HTMLElement{shadow;data=null;selected=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,a=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],s=this.selected.has(i.value);this.shadow.innerHTML=`
706
+ `}}function kl(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Lh extends HTMLElement{shadow;data=null;selected=new Set;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.selected.clear(),this.render()}getValues(){return{name:this.data?.name??"",values:[...this.selected],type:this.data?.type??"checkbox"}}toggle(e){this.data&&(this.data.type==="radio"||this.data.type==="button"?(this.selected.clear(),this.selected.add(e)):this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.data.type==="button"?this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e,attributes:{action:{[this.data.name]:e}}},bubbles:!0,composed:!0})):this.dispatchEvent(new CustomEvent("option-change",{detail:this.getValues(),bubbles:!0,composed:!0})),this.render())}render(){if(!this.data){this.shadow.innerHTML="";return}const{title:e,options:t,type:r}=this.data,a=r==="checkbox";if(r==="checkbox"&&t.length===1&&(t[0]?.label??"").trim()===""&&(e??"").trim()!==""){const i=t[0],s=this.selected.has(i.value);this.shadow.innerHTML=`
707
707
  <style>
708
708
  :host { display: block; margin: 8px 0; }
709
709
  .row {
@@ -789,7 +789,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
789
789
  ${Lr(i.label)}
790
790
  </button>`).join("")}
791
791
  </div>
792
- `,this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Lr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Sl(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Lh extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const a=r.getValues?.();a?.name&&(e[a.name]=a.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
792
+ `,this.shadow.querySelectorAll("button.opt").forEach(i=>{i.addEventListener("click",()=>this.toggle(i.dataset.value||""))})}}function Lr(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}function Sl(c){return String(c).replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}class Nh extends HTMLElement{shadow;data=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.render()}collectFormValues(){const e={},t=this.closest("aikaara-template-renderer")??this.parentElement;return t&&t.querySelectorAll("aikaara-option-list").forEach(r=>{const a=r.getValues?.();a?.name&&(e[a.name]=a.values)}),e}handleClick(){if(!this.data)return;const e=this.data.action??{message:this.data.name},t=this.collectFormValues(),r={...this.data.messageId?{message_id:this.data.messageId}:{},...t};e.formAction&&(r.formAction=e.formAction),e.requestType&&(r.requestType=e.requestType),this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e.message,attributes:{action:r}},bubbles:!0,composed:!0}))}render(){if(!this.data){this.shadow.innerHTML="";return}const e=this.data.name;this.shadow.innerHTML=`
793
793
  <style>
794
794
  :host { display: block; margin: 12px 0 4px; }
795
795
  button {
@@ -807,8 +807,8 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
807
807
  button:hover { background: var(--aikaara-submit-hover-bg, var(--aikaara-primary-hover, #4f46e5)); }
808
808
  button:disabled { opacity: var(--aikaara-submit-disabled-opacity, 0.5); cursor: not-allowed; }
809
809
  </style>
810
- <button type="button">${Nh(e)}</button>
811
- `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Nh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Uh extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
810
+ <button type="button">${Uh(e)}</button>
811
+ `,this.shadow.querySelector("button").addEventListener("click",()=>this.handleClick())}}function Uh(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Bh extends HTMLElement{shadow;data=null;dismissed=!1;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setPayload(e){this.data=e,this.dismissed=!1,this.render()}dismiss(){this.dismissed=!0,this.render()}handleOk(){if(!this.data)return;const e=this.data.action;this.dispatchEvent(new CustomEvent("template-action",{detail:{text:e?.message??this.data.message,attributes:{action:{confirmed:!0,requestType:e?.requestType??"postBackToBotPlatform"}}},bubbles:!0,composed:!0})),this.dismiss()}render(){if(!this.data||this.dismissed){this.shadow.innerHTML="";return}const e=this.data.okLabel??"Ok",t=this.data.cancelLabel;this.shadow.innerHTML=`
812
812
  <style>
813
813
  :host { all: initial; }
814
814
  .overlay {
@@ -856,7 +856,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
856
856
  </div>
857
857
  </div>
858
858
  </div>
859
- `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function so(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Bh extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),a=this.tokenGetter??r;if(!a){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(l=>l.toLowerCase()==="x-api-key"),s=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);s&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=s);const o=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Rl({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:o,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:a,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:l=>this.dispatchEvent(new CustomEvent("error",{detail:l}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(l){this.dispatchEvent(new CustomEvent("error",{detail:l}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Fh extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let a=!1;this.iframe.addEventListener("load",()=>{a=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{a||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const a=this.shadow.querySelector(".modal-title");a&&(a.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
859
+ `,this.shadow.querySelector("button.ok").addEventListener("click",()=>this.handleOk()),this.shadow.querySelector("button.cancel")?.addEventListener("click",()=>this.dismiss())}}function so(c){return String(c).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[e])}class Fh extends HTMLElement{static get observedAttributes(){return["slug","user-id","user-name","user-token","department-id","config-base","api-key"]}tokenGetter;apiKey;configHeaders;identity;credentialProviders;mounted=null;mountInflight=null;connectedCallback(){this.style.display||(this.style.display="flex"),this.style.flexDirection||(this.style.flexDirection="column"),this.style.minHeight||(this.style.minHeight="0"),this.tryMount()}disconnectedCallback(){this.mounted?.destroy(),this.mounted=null}attributeChangedCallback(){this.isConnected&&(this.mounted?.destroy(),this.mounted=null,this.tryMount())}async refreshAuth(){await this.mounted?.refreshAuth()}async tryMount(){if(this.mountInflight)return this.mountInflight;const e=this.getAttribute("slug"),t=this.getAttribute("user-id");if(!e||!t)return;const r=this.getAttribute("user-token"),a=this.tokenGetter??r;if(!a){this.dispatchEvent(new CustomEvent("error",{detail:new Error("aikaara-chat: user-token attribute or tokenGetter property required")}));return}const n={...this.configHeaders??{}},i=Object.keys(n).find(l=>l.toLowerCase()==="x-api-key"),s=this.apiKey??this.getAttribute("api-key")??(i?n[i]:void 0);s&&(i&&i!=="X-Api-Key"&&delete n[i],n["X-Api-Key"]=s);const o=Object.keys(n).length>0?n:void 0;return this.mountInflight=(async()=>{try{this.mounted=await Rl({container:this,slug:e,configBase:this.getAttribute("config-base")??void 0,configHeaders:o,user:{id:t,name:this.getAttribute("user-name")??void 0,departmentId:this.getAttribute("department-id")??void 0,token:a,identity:this.identity,credentialProviders:this.credentialProviders},hooks:{onError:l=>this.dispatchEvent(new CustomEvent("error",{detail:l}))}}),this.dispatchEvent(new CustomEvent("ready",{detail:{requestId:this.mounted.requestId,fullName:this.mounted.fullName}}))}catch(l){this.dispatchEvent(new CustomEvent("error",{detail:l}))}finally{this.mountInflight=null}})(),this.mountInflight}}class Dh extends HTMLElement{shadow;root=null;iframe=null;fallbackTimer=null;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.root||this.render()}show(e,t){if(this.root||this.render(),!this.root||!this.iframe)return;const r=this.shadow.querySelector(".modal-title");r&&(r.textContent=t||"Link"),this.swapBody("iframe"),this.iframe.src=e,this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{url:e},bubbles:!0,composed:!0})),this.fallbackTimer&&window.clearTimeout(this.fallbackTimer);let a=!1;this.iframe.addEventListener("load",()=>{a=!0},{once:!0}),this.fallbackTimer=window.setTimeout(()=>{a||(this.close(),window.open(e,"_blank","noopener,noreferrer"))},3500)}showElement(e,t,r){if(this.root||this.render(),!this.root)return;const a=this.shadow.querySelector(".modal-title");a&&(a.textContent=t||"Details"),this.swapBody("element");const n=this.shadow.querySelector(".modal-body-element");if(n){n.innerHTML="";const i=document.createElement(e);n.appendChild(i),requestAnimationFrame(()=>r?.(i))}this.root.classList.add("open"),this.dispatchEvent(new CustomEvent("aikaara-link-modal-open",{detail:{element:e},bubbles:!0,composed:!0}))}swapBody(e){if(!this.iframe)return;const t=this.shadow.querySelector(".modal-body-element");e==="iframe"?(this.iframe.style.display="",t&&(t.style.display="none")):(this.iframe.style.display="none",t&&(t.style.display=""))}close(){this.root&&(this.root.classList.remove("open"),this.iframe&&(this.iframe.src="about:blank"),this.fallbackTimer&&(window.clearTimeout(this.fallbackTimer),this.fallbackTimer=null),this.dispatchEvent(new CustomEvent("aikaara-link-modal-close",{bubbles:!0,composed:!0})))}render(){this.shadow.innerHTML=`
860
860
  <style>
861
861
  :host { display: block; }
862
862
  .backdrop {
@@ -906,7 +906,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
906
906
  <div class="modal-body-element" style="display:none; flex:1; overflow:auto; padding:18px;"></div>
907
907
  </div>
908
908
  </div>
909
- `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const Dh=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],$h=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class Wh extends HTMLElement{shadow;data=null;columns=$h;features=Dh;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
909
+ `,this.root=this.shadow.querySelector(".backdrop"),this.iframe=this.shadow.querySelector("iframe"),this.shadow.querySelector(".modal-close")?.addEventListener("click",()=>this.close()),this.root?.addEventListener("click",t=>{t.target===this.root&&this.close()}),document.addEventListener("keydown",t=>{t.key==="Escape"&&this.classList.contains("open")&&this.close()})}}const $h=[{label:"Self-filing guidance"},{label:"Smart tax suggestions"},{label:"Auto-fetch 26AS / AIS"},{label:"Notice management"},{label:"Dedicated tax expert"},{label:"End-to-end filing"},{label:"Document handling"}],Wh=[{label:"DIY",match:["DIY","DIY_SALARY"],selectLabel:"Select DIY — Without Notice (₹{price}/yr)",postback:"Without Notice",features:[!0,!0,!0,!1,!1,!1,!1]},{label:"DIY + Notice",match:["NOTICE_DIY","DIY_NOTICE"],selectLabel:"Select DIY — With Notice (₹{price}/yr)",postback:"With Notice",features:[!0,!0,!0,!0,!1,!1,!1]},{label:"Assisted",match:["ASSISTED"],selectLabel:"Switch to Assisted (₹{price}/yr)",postback:"Assisted",features:[!0,!0,!0,!0,!0,!0,!0]}];class qh extends HTMLElement{shadow;data=null;columns=Wh;features=$h;constructor(){super(),this.shadow=this.attachShadow({mode:"open"})}connectedCallback(){this.render()}setData(e){this.data=e,this.render()}setColumns(e){this.columns=e,this.render()}setFeatures(e){this.features=e,this.render()}priceFor(e){if(!this.data?.data)return null;for(const t of this.data.data)if(e.match.includes(t.planType))return t.planMaster?.basePrice??null;return null}render(){const e=this.columns,t=this.features;this.shadow.innerHTML=`
910
910
  <style>
911
911
  :host {
912
912
  display: block;
@@ -983,7 +983,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
983
983
  <small>Tap to select</small>
984
984
  </button>`}).join("")}
985
985
  </div>
986
- `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function lo(){const c=[["aikaara-chat-widget",cl],["aikaara-chat-bubble",ul],["aikaara-chat-header",hl],["aikaara-message-list",dl],["aikaara-message-bubble",gl],["aikaara-chat-input",bl],["aikaara-typing-indicator",yl],["aikaara-streaming-message",vl],["aikaara-error-banner",wl],["aikaara-template-renderer",Oh],["aikaara-system-pill",Rh],["aikaara-option-list",jh],["aikaara-submit-action",Lh],["aikaara-modal-action",Uh],["aikaara-chat",Bh],["aikaara-link-modal",Fh],["aikaara-compare-plans",Wh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function qh(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 Nr(c){return typeof c=="function"?await c():c}class El{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 Nr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=co(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),g=qh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function xl(c){const e={};for(const t of c.spec){const r=await Hh(t,c.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 Hh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return zh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Kh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function zh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Ur(c){try{return c()}catch{return}}function Kh(c){return c.replace(/["\\]/g,"\\$&")}const Vh=1800;class Al{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 xl({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 a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)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(a,{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 s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,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??Vh;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 Gh=3e4,Yh=2e3,Qh=100;async function Il(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Jh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Xh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=nf(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Gh;return{token:await rf({type:r,key:a,origins:n,timeoutMs:i}),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 a=Zh(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=ef(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Qh,i=await tf(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Tl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Il(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 Jh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Xh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function Zh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function ef(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Cl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function tf(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Cl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function rf(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function nf(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Cl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function of(){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(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 uo(c,e){return`${sf}:${c}:${e}`}function af(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function lf(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function cf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function uf(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[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Nr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",g=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),g<i.length&&hf(y,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,b),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function hf(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 Ol(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.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 ff(c,e){return c.replace("{projectId}",e).replace("{uuid}",of().replace(/-/g,""))}function Pl(c){const e=c._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=>_l(r)))}async function Ml(c){const e={...c.config??(c.configUrl?await Ol(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Pl(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 a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:af(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??ff(s,a);(!i||c.forceNewConversation)&&a&&lf(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.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,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?ll({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),g={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,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,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,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(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;"),c.container.appendChild(b),{widget:b,requestId:o,config:g,destroy(){b.remove()}}}function df(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 Rl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Ol(t,c.configHeaders)}catch(w){if(!c.fallbackConfig)throw w;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,w)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Pl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[w,E]of Object.entries(a.templates)){const v=`template:${w}`;a.components[v]||!E?.scriptUrl||!E?.render||(a.components[v]={kind:"iife-element",scriptUrl:E.scriptUrl,tag:E.render,...E.props?{props:E.props}:{}})}}if(window.__aikaara_descriptor__={templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let n=null,i=c.user.id,s=c.user.name,o="",l=c.user.token,u=null;if(a.sso?.tokenSource){u=new Tl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const w=await u.get();l=async()=>(await u.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=w.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const w=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;n=await new Al({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:w}).get(),i=n.extUid||i,s=s??n.displayName,o=n.userToken}a.preflight&&a.preflight.length&&await uf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new El(a.auth,l),p=await d.get(),y=p.fullName||s||i;window.__aikaara_runtime__={getChatJwt:async()=>(await d.get()).token,identity:c.user.identity,slug:c.slug};const f=u&&a.sso?.autoRefresh?async()=>{try{return await u.refresh(),d.reset(),(await d.get()).token}catch(w){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",w),null}}:null,g=a.upload,b=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Nr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?al({...g,authHeader:b}):g&&g.mode==="direct"?no({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Ml({container:df(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:y,departmentId:c.user.departmentId,senderFullname:y},tokenProvider:async()=>(await d.get()).token,historyTokenProvider:async()=>(await d.get()).token,uploadAdapter:k,historyAdapter:c.hooks?.history,conversationId:p.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async w=>w==="none"?null:w==="chat"?(await d.get()).token:Nr(c.user.token)});return Object.assign(m,{fullName:y,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}function pf(c){lo();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,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function gf(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class jl 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=`
986
+ `,this.shadow.querySelectorAll("button.action").forEach(r=>{r.addEventListener("click",()=>{const a=Number(r.dataset.col),n=e[a];n&&this.dispatchEvent(new CustomEvent("aikaara-plan-select",{detail:{planType:n.match[0],message:n.postback,label:n.label},bubbles:!0,composed:!0}))})})}}function ao(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function lo(){const c=[["aikaara-chat-widget",cl],["aikaara-chat-bubble",ul],["aikaara-chat-header",hl],["aikaara-message-list",dl],["aikaara-message-bubble",gl],["aikaara-chat-input",bl],["aikaara-typing-indicator",yl],["aikaara-streaming-message",vl],["aikaara-error-banner",wl],["aikaara-template-renderer",Ph],["aikaara-system-pill",jh],["aikaara-option-list",Lh],["aikaara-submit-action",Nh],["aikaara-modal-action",Bh],["aikaara-chat",Fh],["aikaara-link-modal",Dh],["aikaara-compare-plans",qh]];for(const[e,t]of c)customElements.get(e)||customElements.define(e,t)}lo();function co(c,e,t=""){if(!e)return t;const r=e.split(".");let a=c;for(const n of r)if(a&&typeof a=="object"&&n in a)a=a[n];else return t;return typeof a=="string"?a:t}function Hh(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 Nr(c){return typeof c=="function"?await c():c}class El{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 Nr(this.sessionToken),t=this.descriptor.authHeader??"Authorization",r=this.descriptor.authHeaderTemplate??"Bearer {token}",a={accept:"application/json",...this.descriptor.headers??{},[t]:r.replace("{token}",e)},n=this.descriptor.method??"POST",i={method:n,headers:a};n==="POST"&&(a["content-type"]="application/json",i.body=JSON.stringify(this.descriptor.body??{}));const s=await fetch(this.descriptor.endpoint,i);if(!s.ok){const b=await s.text().catch(()=>"");throw new Error(`Session auth failed: ${s.status} ${b.slice(0,200)}`)}const o=await s.json().catch(()=>({})),l=co(o,this.descriptor.tokenPath??"data.token"),u=this.descriptor.tokenStripPrefix,d=u?l.replace(new RegExp(`^${u}`,"i"),"").trim():l;if(!d)throw new Error("Session auth response missing token");const p=co(o,this.descriptor.requestIdPath??"data.requestId"),y=this.cache?.requestId||p;if(!y)throw new Error("Session auth response missing requestId");const f=co(o,this.descriptor.fullNamePath??"data.fullName"),g=Hh(d)||Date.now()+3600*1e3;return this.cache={token:d,requestId:y,fullName:f,expiresAt:g},this.cache}}async function xl(c){const e={};for(const t of c.spec){const r=await zh(t,c.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 zh(c,e){const t=c.key??c.name;switch(c.source){case"cookie":return Kh(t);case"localStorage":return Ur(()=>window.localStorage.getItem(t)??void 0);case"sessionStorage":return Ur(()=>window.sessionStorage.getItem(t)??void 0);case"url_param":return Ur(()=>new URL(window.location.href).searchParams.get(t)??void 0);case"header_meta":return Ur(()=>document.querySelector(`meta[name="${Vh(t)}"]`)?.content??void 0);case"callback":{const r=e?.[c.name];if(!r)return;const a=await r();return typeof a=="string"?a:void 0}default:return}}function Kh(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function Ur(c){try{return c()}catch{return}}function Vh(c){return c.replace(/["\\]/g,"\\$&")}const Gh=1800;class Al{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 xl({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 a=this.opts.descriptor.exchangeEndpoint||this.opts.exchangeUrl;if(!a)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(a,{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 s=(await n.json().catch(()=>({}))).user??{},o=String(s.ext_uid??s.extUid??""),l=String(s.token??s.user_token??s.userToken??"");if(!o)throw new Error("SSO exchange response missing user.ext_uid");if(!l)throw new Error("SSO exchange response missing user.token");const u={id:s.id,extUid:o,userToken:l,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??Gh;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 Yh=3e4,Qh=2e3,Jh=100;async function Il(c){const{descriptor:e}=c,t=e.tokenSourceConfig??{};switch(e.tokenSource){case"init":{if(!c.initToken)throw new Ke("init","No init token supplied to Aikaara.init({token})");return{token:c.initToken,source:"init"}}case"query":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Xh(r);if(!a)throw new Ke("query",`?${r}= not present`);return{token:a,source:"query"}}case"hash":{const r=typeof t.key=="string"&&t.key?t.key:"token",a=Zh(r);if(!a)throw new Ke("hash",`#${r}= not present`);return{token:a,source:"hash"}}case"postmsg":{const r=typeof t.type=="string"?t.type:"",a=typeof t.key=="string"&&t.key?t.key:"token",n=of(typeof t.origins=="string"?t.origins:""),i=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Yh;return{token:await nf({type:r,key:a,origins:n,timeoutMs:i}),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 a=ef(r);if(!a)throw new Ke("cookie",`cookie "${r}" not set`);return{token:a,source:"cookie"}}case"storage":{const r=t.store==="session"?"session":"local",a=typeof t.key=="string"&&t.key?t.key:"",n=typeof t.path=="string"?t.path:"";if(!a)throw new Ke("storage","storage.key not configured");const i=tf(r,a,n);if(!i)throw new Ke("storage",`${r}Storage["${a}"] not set`);return{token:i,source:"storage"}}case"global":{const r=typeof t.path=="string"?t.path:"";if(!r)throw new Ke("global","global.path not configured");const a=typeof t.timeoutMs=="number"&&t.timeoutMs>0?t.timeoutMs:Qh,n=typeof t.intervalMs=="number"&&t.intervalMs>0?t.intervalMs:Jh,i=await rf(r,a,n);if(!i)throw new Ke("global",`window.${r} not present`);return{token:i,source:"global"}}default:{const r=e.tokenSource;throw new Ke("unknown",`Unknown tokenSource ${JSON.stringify(r)}`)}}}class Tl{constructor(e){this.opts=e}cached=null;get descriptor(){return this.opts.descriptor}async get(){if(this.cached)return this.cached;const e=await Il(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 Xh(c){if(!(typeof window>"u"))try{return new URL(window.location.href).searchParams.get(c)??void 0}catch{return}}function Zh(c){if(!(typeof window>"u"))try{const e=window.location.hash.replace(/^#/,"");return new URLSearchParams(e).get(c)??void 0}catch{return}}function ef(c){if(typeof document>"u")return;const e=encodeURIComponent(c),t=document.cookie?document.cookie.split("; "):[];for(const r of t){const a=r.indexOf("=");if(a===-1)continue;const n=r.slice(0,a);if(n===c||n===e)try{return decodeURIComponent(r.slice(a+1))}catch{return r.slice(a+1)}}}function tf(c,e,t){if(!(typeof window>"u"))try{const a=(c==="session"?window.sessionStorage:window.localStorage).getItem(e);if(a==null)return;if(!t)return a;let n;try{n=JSON.parse(a)}catch{return a}const i=Cl(n,t);return typeof i=="string"?i:void 0}catch{return}}async function rf(c,e,t){if(typeof window>"u")return;const r=Date.now()+e;for(;Date.now()<r;){const a=Cl(window,c);if(typeof a=="string"&&a.length>0)return a;if(typeof a=="function")try{const n=a();if(typeof n=="string"&&n.length>0)return n}catch{}await new Promise(n=>setTimeout(n,t))}}function nf(c){return new Promise((e,t)=>{if(typeof window>"u"){t(new Ke("postmsg","no window"));return}const r=()=>{window.removeEventListener("message",n),clearTimeout(a)},a=setTimeout(()=>{r(),t(new Ke("postmsg",`timeout after ${c.timeoutMs}ms`))},c.timeoutMs),n=i=>{if(c.origins.length>0&&!c.origins.includes(i.origin))return;const s=i.data;if(!s||typeof s!="object")return;const o=s;if(c.type&&o.type!==c.type)return;const l=o[c.key];typeof l=="string"&&l.length>0&&(r(),e(l))};window.addEventListener("message",n)})}function of(c){return c?c.split(/[,\s]+/).map(e=>e.trim()).filter(Boolean):[]}function Cl(c,e){if(!e)return c;const t=e.split(".").filter(Boolean);let r=c;for(const a of t)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}function sf(){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(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 af="aikaara_chat:requestId";function uo(c,e){return`${af}:${c}:${e}`}function lf(c,e){try{return localStorage.getItem(uo(c,e))}catch{return null}}function cf(c,e,t){try{localStorage.setItem(uo(c,e),t)}catch{}}function uf(c,e){try{localStorage.removeItem(uo(c,e))}catch{}}async function hf(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[s,o]of Object.entries(e.identity))typeof o=="string"&&(t[s]=o);const r=s=>s.replace(/\{(\w+)\}/g,(o,l)=>l in t?t[l]:""),a=s=>{if(typeof s=="string")return r(s);if(Array.isArray(s))return s.map(a);if(s&&typeof s=="object"){const o={};for(const[l,u]of Object.entries(s))o[l]=a(u);return o}return s},n=await Nr(e.sessionToken),i=[800,1500,3e3,5e3,8e3];for(let s=0;s<c.length;s++){const o=c[s],l=r(o.url),u=o.method??(o.body?"POST":"GET"),d={accept:"application/json",...o.headers??{}};if((o.authHeader??"session")==="session"){const b=o.authHeaderTemplate??"Bearer {token}";d.authorization=b.replace("{token}",n)}const p={method:u,headers:d};o.body&&(d["content-type"]="application/json",p.body=JSON.stringify(a(o.body)));let y=0,f="",g=0;for(;;)try{const b=await fetch(l,p);if(b.ok)break;if(y=b.status,f=await b.text().catch(()=>""),g<i.length&&ff(y,f)){const m=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} ${u} ${l} → ${y} (transient). Retry #${g} in ${m}ms.`),await new Promise(w=>setTimeout(w,m));continue}const k=`Preflight #${s} ${u} ${l} → ${y} ${f.slice(0,200)}`;if(o.soft){console.warn("[aikaara-chat-sdk]",k);break}throw new Error(k)}catch(b){if(g<i.length){const k=i[g++];console.warn(`[aikaara-chat-sdk] preflight #${s} threw, retry #${g} in ${k}ms`,b),await new Promise(m=>setTimeout(m,k));continue}if(o.soft){console.warn(`[aikaara-chat-sdk] preflight #${s} soft-failed:`,b);break}throw b}}}function ff(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 Ol(c,e){const t=await fetch(c,{method:"GET",headers:{accept:"application/json",...e??{}}});if(!t.ok){const a=await t.text().catch(()=>"");throw new Error(`Widget config fetch failed: ${t.status} ${t.statusText} ${a.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 df(c,e){return c.replace("{projectId}",e).replace("{uuid}",sf().replace(/-/g,""))}function Pl(c){const e=c._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=>_l(r)))}async function Ml(c){const e={...c.config??(c.configUrl?await Ol(c.configUrl,c.configHeaders):{}),...c.overrides??{}};Pl(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 a=r?.projectId??"",n=c.identity.userId,i=c.forceNewConversation?null:lf(n,a),s=r?.requestIdTemplate??"support-group-{projectId}-{uuid}",o=c.conversationId??i??df(s,a);(!i||c.forceNewConversation)&&a&&cf(n,a,o);const l=await c.tokenProvider(),u=c.tokenProvider,d=c.historyTokenProvider??u,p=r?{mqttEndpoint:r.mqttEndpoint,jwtToken:l,userId:n,userName:c.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,...c.identity.departmentId?{departmentId:c.identity.departmentId}:r.messageDefaults?.departmentId?{departmentId:r.messageDefaults.departmentId}:{}},fileTemplate:r.fileTemplate,topicTemplates:r.topicTemplates,debug:r.debug,senderFullname:c.identity.senderFullname??c.identity.userName,tokenProvider:u}:void 0,y=c.uploadAdapter??(e.uploadEndpoint?no({endpoint:e.uploadEndpoint,fieldName:e.uploadFieldName,extraFields:e.uploadExtraFields}):void 0),f=c.historyAdapter??(e.historyApiBase?ll({apiBase:e.historyApiBase,pageSize:e.historyPageSize??200,pathTemplate:e.historyPathTemplate,extraHeaders:e.historyHeaders,getToken:d}):void 0),g={transport:t,baseUrl:"",userToken:c.userToken??n,conversationId:o,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,showHeader:e.showHeader,hideSystemMessages:e.hideSystemMessages,timestampFormat:e.timestampFormat,input:e.input,templateLayout:e.templateLayout,tiledesk:p,tiledeskIdentity:{userId:n,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(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;"),c.container.appendChild(b),{widget:b,requestId:o,config:g,destroy(){b.remove()}}}function pf(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 Rl(c){const e=(c.configBase??"https://api.aikaara.com").replace(/\/$/,""),t=`${e}/api/v1/widget_configs/${encodeURIComponent(c.slug)}`;let r=null;try{r=await Ol(t,c.configHeaders)}catch(w){if(!c.fallbackConfig)throw w;console.warn(`[aikaara-chat-sdk] Widget config fetch failed for slug "${c.slug}" — using fallbackConfig.`,w)}const a={...c.fallbackConfig??{},...r??{},...c.overrides??{}};if(Pl(a),a.templates&&Object.keys(a.templates).length>0){a.components={...a.components??{}};for(const[w,E]of Object.entries(a.templates)){const v=`template:${w}`;a.components[v]||!E?.scriptUrl||!E?.render||(a.components[v]={kind:"iife-element",scriptUrl:E.scriptUrl,tag:E.render,...E.props?{props:E.props}:{}})}}if(window.__aikaara_descriptor__={templates:a.templates,components:a.components,razorpay:a.razorpay,title:a.title},!a.auth)throw new Error(`mountFromSlug: widget_configs/${c.slug} descriptor must include "auth" block`);let n=null,i=c.user.id,s=c.user.name,o="",l=c.user.token,u=null;if(a.sso?.tokenSource){u=new Tl({descriptor:{provider:a.sso.provider,flow:a.sso.flow,skipLogin:a.sso.skipLogin,autoRefresh:a.sso.autoRefresh,tokenSource:a.sso.tokenSource,tokenSourceConfig:a.sso.tokenSourceConfig,fallback:a.sso.fallback,map:a.sso.map},initToken:c.user.partnerToken});const w=await u.get();l=async()=>(await u.get()).token,c.user.identity&&!c.user.identity.partnerToken&&(c.user.identity.partnerToken=w.token)}else if(a.sso&&a.sso.collect&&a.sso.collect.length>0){const w=`${e}/api/v1/projects/by-slug/${encodeURIComponent(c.slug)}/sso_exchange`;n=await new Al({descriptor:a.sso,providers:c.user.credentialProviders,exchangeUrl:w}).get(),i=n.extUid||i,s=s??n.displayName,o=n.userToken}a.preflight&&a.preflight.length&&await hf(a.preflight,{sessionToken:l,userId:i,projectId:a.tiledesk?.projectId??"",slug:c.slug,identity:c.user.identity});const d=new El(a.auth,l),p=await d.get(),y=p.fullName||s||i;window.__aikaara_runtime__={getChatJwt:async()=>(await d.get()).token,identity:c.user.identity,slug:c.slug};const f=u&&a.sso?.autoRefresh?async()=>{try{return await u.refresh(),d.reset(),(await d.get()).token}catch(w){return console.warn("[aikaara-chat-sdk] partner auto-refresh failed",w),null}}:null,g=a.upload,b=async()=>`Bearer ${g&&"tokenSource"in g&&g.tokenSource==="chat"?(await d.get()).token:await Nr(c.user.token)}`,k=c.hooks?.upload??(g&&g.mode==="presigned-3step"?al({...g,authHeader:b}):g&&g.mode==="direct"?no({endpoint:g.endpoint,fieldName:g.fieldName,extraFields:g.extraFields,headers:async()=>({authorization:await b()})}):void 0),m=await Ml({container:pf(c.container),config:a,userToken:o||void 0,identity:{userId:i,userName:y,departmentId:c.user.departmentId,senderFullname:y},tokenProvider:async()=>(await d.get()).token,historyTokenProvider:async()=>(await d.get()).token,uploadAdapter:k,historyAdapter:c.hooks?.history,conversationId:p.requestId,onError:c.hooks?.onError,onMessage:c.hooks?.onMessage,getLinkBearer:async w=>w==="none"?null:w==="chat"?(await d.get()).token:Nr(c.user.token)});return Object.assign(m,{fullName:y,requestId:p.requestId,descriptor:a,async refreshAuth(){d.reset(),await d.get()},async refreshPartnerAuth(){return f?f():null}})}function gf(c){lo();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,a]of Object.entries(t)){const n=c[r];n!=null&&e.setAttribute(a,String(n))}return e.configure(c),document.body.appendChild(e),e}function mf(){const c=document.querySelector("aikaara-chat-widget");c&&c.remove()}class jl 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=`
987
987
  <style>
988
988
  :host { display: block; margin-top: 8px; }
989
989
  button {
@@ -1004,7 +1004,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
1004
1004
  button[disabled] { opacity: 0.5; cursor: not-allowed; }
1005
1005
  </style>
1006
1006
  <button type="button" ${e?"":"disabled"}>
1007
- ${mf(e?.name??"Open")}
1007
+ ${bf(e?.name??"Open")}
1008
1008
  <span aria-hidden="true">↗</span>
1009
1009
  </button>
1010
- `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,orderId:a,extra:n,messageId:i}=this.payload,s=r?"tab":"modal",o=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:a,openedIn:s,extra:n,messageId:i},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(o))if(r)window.open(e,"_blank","noopener,noreferrer");else{const u=bf();requestAnimationFrame(()=>u?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:a,openedIn:s,...n??{}},...i?{message_id:i}:{}}},bubbles:!0,composed:!0}))}}function mf(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function bf(){if(typeof document>"u")return null;let c=document.querySelector("aikaara-link-modal");if(!c){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),c=e}return c}function yf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",jl)}const vf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:jl,registerAikaaraLinkButton:yf},Symbol.toStringTag,{value:"Module"}));return Ce.ActionCableClient=Dr,Ce.AikaaraChatBubble=ul,Ce.AikaaraChatClient=ol,Ce.AikaaraChatHeader=hl,Ce.AikaaraChatInput=bl,Ce.AikaaraChatWidget=cl,Ce.AikaaraErrorBanner=wl,Ce.AikaaraMessageBubble=gl,Ce.AikaaraMessageList=dl,Ce.AikaaraStreamingMessage=vl,Ce.AikaaraTypingIndicator=yl,Ce.ApiClient=yo,Ce.ChannelSubscription=po,Ce.ConnectionManager=bo,Ce.ConversationManager=So,Ce.EventEmitter=Zt,Ce.FormBridge=gh,Ce.MessageStore=vo,Ce.SessionAuthAdapter=El,Ce.SsoExchangeAdapter=Al,Ce.TiledeskTransport=el,Ce.TokenDiscoveryError=Ke,Ce.TokenDiscoveryReader=Tl,Ce.clearPersistedConversationId=cf,Ce.collectSsoCredentials=xl,Ce.createFetchUploadAdapter=no,Ce.createPresigned3StepUploadAdapter=al,Ce.createTiledeskHistoryAdapter=ll,Ce.discoverToken=Il,Ce.extractTiledeskFileEnvelope=nl,Ce.inferTiledeskRole=rl,Ce.isTiledeskSelfEcho=tl,Ce.mount=pf,Ce.mountFromSlug=Rl,Ce.mountTenantWidget=Ml,Ce.parseTiledeskTemplate=to,Ce.registerComponents=lo,Ce.unmount=gf,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"}),Ce})({});
1010
+ `,this.shadow.querySelector("button")?.addEventListener("click",()=>this.handleClick())}handleClick(){if(!this.payload)return;const{url:e,name:t,openLinkInNewTab:r,orderId:a,extra:n,messageId:i}=this.payload,s=r?"tab":"modal",o=new CustomEvent("aikaara-link-action",{detail:{url:e,name:t,orderId:a,openedIn:s,extra:n,messageId:i},bubbles:!0,composed:!0,cancelable:!0});if(this.dispatchEvent(o))if(r)window.open(e,"_blank","noopener,noreferrer");else{const u=yf();requestAnimationFrame(()=>u?.show?.(e,t))}this.dispatchEvent(new CustomEvent("template-action",{detail:{text:t,attributes:{action:{type:"link",url:e,orderId:a,openedIn:s,...n??{}},...i?{message_id:i}:{}}},bubbles:!0,composed:!0}))}}function bf(c){return c.replace(/[&<>"']/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[e])}function yf(){if(typeof document>"u")return null;let c=document.querySelector("aikaara-link-modal");if(!c){const e=document.createElement("aikaara-link-modal");document.body.appendChild(e),c=e}return c}function vf(){typeof customElements>"u"||customElements.get("aikaara-link-button")||customElements.define("aikaara-link-button",jl)}const wf=Object.freeze(Object.defineProperty({__proto__:null,AikaaraLinkButton:jl,registerAikaaraLinkButton:vf},Symbol.toStringTag,{value:"Module"}));return Ce.ActionCableClient=Dr,Ce.AikaaraChatBubble=ul,Ce.AikaaraChatClient=ol,Ce.AikaaraChatHeader=hl,Ce.AikaaraChatInput=bl,Ce.AikaaraChatWidget=cl,Ce.AikaaraErrorBanner=wl,Ce.AikaaraMessageBubble=gl,Ce.AikaaraMessageList=dl,Ce.AikaaraStreamingMessage=vl,Ce.AikaaraTypingIndicator=yl,Ce.ApiClient=yo,Ce.ChannelSubscription=po,Ce.ConnectionManager=bo,Ce.ConversationManager=So,Ce.EventEmitter=Zt,Ce.FormBridge=gh,Ce.MessageStore=vo,Ce.SessionAuthAdapter=El,Ce.SsoExchangeAdapter=Al,Ce.TiledeskTransport=el,Ce.TokenDiscoveryError=Ke,Ce.TokenDiscoveryReader=Tl,Ce.clearPersistedConversationId=uf,Ce.collectSsoCredentials=xl,Ce.createFetchUploadAdapter=no,Ce.createPresigned3StepUploadAdapter=al,Ce.createTiledeskHistoryAdapter=ll,Ce.discoverToken=Il,Ce.extractTiledeskFileEnvelope=nl,Ce.inferTiledeskRole=rl,Ce.isTiledeskSelfEcho=tl,Ce.mount=gf,Ce.mountFromSlug=Rl,Ce.mountTenantWidget=Ml,Ce.parseTiledeskTemplate=to,Ce.registerComponents=lo,Ce.unmount=mf,Object.defineProperty(Ce,Symbol.toStringTag,{value:"Module"}),Ce})({});
package/dist/headless.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./MountTenant-CLSvsaX7.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-Cz8W90_R.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;
@@ -2058,7 +2058,7 @@ export declare interface WidgetConfig extends ChatClientConfig {
2058
2058
  persistConversation?: boolean;
2059
2059
  showHeader?: boolean;
2060
2060
  hideSystemMessages?: string[];
2061
- timestampFormat?: 'time' | 'datetime' | 'date' | 'none';
2061
+ timestampFormat?: 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
2062
2062
  input?: {
2063
2063
  attachPosition?: 'left' | 'right';
2064
2064
  sendButtonShape?: 'circle' | 'square';
@@ -2111,12 +2111,15 @@ export declare interface WidgetConfigDescriptor {
2111
2111
  hideSystemMessages?: string[];
2112
2112
  /**
2113
2113
  * Timestamp display under each bubble.
2114
- * - `time` (default): locale time, e.g. "11:26 AM" / "23:14".
2114
+ * - `time` (default): locale time 12h, e.g. "11:26 AM".
2115
+ * - `time-24`: 24h clock, e.g. "23:14".
2116
+ * - `time-seconds`: locale time including seconds, e.g. "11:26:35 AM".
2115
2117
  * - `datetime`: short month/day + time, e.g. "May 08, 11:26 AM".
2116
- * - `date`: short month/day only.
2118
+ * - `date`: short month/day only, e.g. "May 08".
2119
+ * - `relative`: "just now" / "5 min ago" / "Yesterday".
2117
2120
  * - `none`: equivalent to `showTimestamps: false`.
2118
2121
  */
2119
- timestampFormat?: 'time' | 'datetime' | 'date' | 'none';
2122
+ timestampFormat?: 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
2120
2123
  /** Composer styling — attach button position and send button shape. */
2121
2124
  input?: {
2122
2125
  /** Where the paperclip button sits relative to the textarea. Default `left`. */
package/dist/headless.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { E as s } from "./MountTenant-B-CCyWWA.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-B-CCyWWA.mjs";
1
+ import { E as s } from "./MountTenant-BFBaHtZU.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-BFBaHtZU.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-CLSvsaX7.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-Cz8W90_R.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.d.ts CHANGED
@@ -233,7 +233,7 @@ export declare class AikaaraMessageList extends HTMLElement {
233
233
  private linkHandlers;
234
234
  private getLinkBearer;
235
235
  setHideSystemMessages(items: string[]): void;
236
- setTimestampFormat(fmt: 'time' | 'datetime' | 'date' | 'none'): void;
236
+ setTimestampFormat(fmt: TimestampFormat): void;
237
237
  private templateLayout;
238
238
  setTemplateLayout(layout: 'inside' | 'outside'): void;
239
239
  /** Returns true when a message should be hidden by the descriptor's
@@ -1652,6 +1652,8 @@ export declare interface TiledeskTransportConfig {
1652
1652
  debug?: boolean;
1653
1653
  }
1654
1654
 
1655
+ declare type TimestampFormat = 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
1656
+
1655
1657
  export declare interface TokenDiscoveryDescriptor {
1656
1658
  /** `"partner"` today; reserved for future SSO families. */
1657
1659
  provider?: string;
@@ -1820,7 +1822,7 @@ export declare interface WidgetConfig extends ChatClientConfig {
1820
1822
  persistConversation?: boolean;
1821
1823
  showHeader?: boolean;
1822
1824
  hideSystemMessages?: string[];
1823
- timestampFormat?: 'time' | 'datetime' | 'date' | 'none';
1825
+ timestampFormat?: 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
1824
1826
  input?: {
1825
1827
  attachPosition?: 'left' | 'right';
1826
1828
  sendButtonShape?: 'circle' | 'square';
@@ -1873,12 +1875,15 @@ export declare interface WidgetConfigDescriptor {
1873
1875
  hideSystemMessages?: string[];
1874
1876
  /**
1875
1877
  * Timestamp display under each bubble.
1876
- * - `time` (default): locale time, e.g. "11:26 AM" / "23:14".
1878
+ * - `time` (default): locale time 12h, e.g. "11:26 AM".
1879
+ * - `time-24`: 24h clock, e.g. "23:14".
1880
+ * - `time-seconds`: locale time including seconds, e.g. "11:26:35 AM".
1877
1881
  * - `datetime`: short month/day + time, e.g. "May 08, 11:26 AM".
1878
- * - `date`: short month/day only.
1882
+ * - `date`: short month/day only, e.g. "May 08".
1883
+ * - `relative`: "just now" / "5 min ago" / "Yesterday".
1879
1884
  * - `none`: equivalent to `showTimestamps: false`.
1880
1885
  */
1881
- timestampFormat?: 'time' | 'datetime' | 'date' | 'none';
1886
+ timestampFormat?: 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
1882
1887
  /** Composer styling — attach button position and send button shape. */
1883
1888
  input?: {
1884
1889
  /** Where the paperclip button sits relative to the textarea. Default `left`. */
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { r as o } from "./MountTenant-B-CCyWWA.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-B-CCyWWA.mjs";
1
+ import { r as o } from "./MountTenant-BFBaHtZU.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-BFBaHtZU.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-CLSvsaX7.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-Cz8W90_R.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.d.ts CHANGED
@@ -291,7 +291,7 @@ export declare class AikaaraMessageList extends HTMLElement {
291
291
  private linkHandlers;
292
292
  private getLinkBearer;
293
293
  setHideSystemMessages(items: string[]): void;
294
- setTimestampFormat(fmt: 'time' | 'datetime' | 'date' | 'none'): void;
294
+ setTimestampFormat(fmt: TimestampFormat): void;
295
295
  private templateLayout;
296
296
  setTemplateLayout(layout: 'inside' | 'outside'): void;
297
297
  /** Returns true when a message should be hidden by the descriptor's
@@ -1067,6 +1067,8 @@ declare interface TiledeskTransportConfig_2 {
1067
1067
  debug?: boolean;
1068
1068
  }
1069
1069
 
1070
+ declare type TimestampFormat = 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
1071
+
1070
1072
  declare interface ToolCall {
1071
1073
  id: string;
1072
1074
  type: 'function';
@@ -1168,7 +1170,7 @@ declare interface WidgetConfig extends ChatClientConfig {
1168
1170
  persistConversation?: boolean;
1169
1171
  showHeader?: boolean;
1170
1172
  hideSystemMessages?: string[];
1171
- timestampFormat?: 'time' | 'datetime' | 'date' | 'none';
1173
+ timestampFormat?: 'time' | 'time-24' | 'time-seconds' | 'datetime' | 'datetime-seconds' | 'datetime-24' | 'date' | 'relative' | 'none';
1172
1174
  input?: {
1173
1175
  attachPosition?: 'left' | 'right';
1174
1176
  sendButtonShape?: 'circle' | 'square';
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, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-B-CCyWWA.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, h as l, J as d, K as m, i as p, L as C, N as h, O as b, j as M, r as c } from "./MountTenant-BFBaHtZU.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.9.4",
3
+ "version": "0.9.5",
4
4
  "type": "module",
5
5
  "description": "Aikaara Chat SDK — embeddable chat widget and headless client",
6
6
  "license": "MIT",