@cloudflare/ai-search-snippet 0.0.29 → 0.0.31

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.
@@ -1,9 +1,9 @@
1
- (function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.SearchSnippet={}))})(this,(function(p){"use strict";var Z=Object.defineProperty;var Q=(p,h,w)=>h in p?Z(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>Q(p,typeof h!="symbol"?h+"":h,w);const h=["Searching...","Digging through results...","Scanning the knowledge base...","Finding the best matches...","Sifting through the data...","Almost there...","Looking far and wide...","Connecting the dots...","Rummaging through pages...","Hunting down answers..."];function L(c,i){let e;return function(...s){const r=()=>{clearTimeout(e),c(...s)};clearTimeout(e),e=setTimeout(r,i)}}function d(c){const i=document.createElement("div");return i.textContent=c,i.innerHTML}function I(c){return new DOMParser().parseFromString(c,"text/html").documentElement.textContent||""}function O(c){const i=new Date(c),t=new Date().getTime()-i.getTime();if(t<6e4)return"Just now";if(t<36e5){const s=Math.floor(t/6e4);return`${s} ${s===1?"minute":"minutes"} ago`}if(t<864e5){const s=Math.floor(t/36e5);return`${s} ${s===1?"hour":"hours"} ago`}return i.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function z(c){return new Date(c).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function T(c="id"){return`${c}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function u(c,i){return c!==null?c:i}function m(c,i){return c===null?i:c==="true"||c===""}function x(c,i){if(c===null)return i;const e=Number.parseInt(c,10);return Number.isNaN(e)?i:e}function v(c,i){return new CustomEvent(c,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function k(c){if(!c)throw new Error("API URL is required");return new A(c)}class A{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i={},e,t){const s=e==="search"?"snippet-search":"snippet-chat-completions";return fetch(`${this.baseUrl}/${e}`,{method:"POST",body:JSON.stringify({messages:[{role:"user",content:i.query}],stream:i.streaming,max_results:i.maxResults,...e==="search"&&{ai_search_options:{retrieval:{metadata_only:!0}}}}),headers:{"Content-Type":"application/json","cf-ai-search-source":s},signal:t})}async search(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);try{const n=await this.request({query:i,streaming:!1,maxResults:e.maxResults||30},"search",r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");const o=await n.json();if(o.success&&o.result)return o.result.chunks.map(l=>({type:"result",id:l.id,title:I(l.item.metadata?.title),description:l.item.metadata?.description?I(l.item.metadata?.description):"",timestamp:l.item.timestamp??void 0,url:l.item.key,image:l.item.metadata?.image||void 0,metadata:l.item.metadata}));throw o.success===!1?new Error(o.error):new Error("Unknown error")}finally{this.unregisterRequest(t)}}async*searchStream(i,e){const t=this.generateRequestId(),s=new AbortController,r=e?.signal||s.signal;this.registerRequest(t,s);const n=await this.request({query:i,streaming:!0},"ai-search",r);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let o="";const l=n.body.getReader(),b=new TextDecoder;for(;;){const{done:g,value:M}=await l.read();if(g)break;const J=b.decode(M,{stream:!0});o+=J}yield{type:"result",id:"",title:"",description:o.replaceAll("data: ","").trim().split(`
1
+ (function(p,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(p=typeof globalThis<"u"?globalThis:p||self,h(p.SearchSnippet={}))})(this,(function(p){"use strict";var ie=Object.defineProperty;var re=(p,h,w)=>h in p?ie(p,h,{enumerable:!0,configurable:!0,writable:!0,value:w}):p[h]=w;var a=(p,h,w)=>re(p,typeof h!="symbol"?h+"":h,w);const h=["Searching...","Digging through results...","Scanning the knowledge base...","Finding the best matches...","Sifting through the data...","Almost there...","Looking far and wide...","Connecting the dots...","Rummaging through pages...","Hunting down answers..."];function I(o,i){let e;function t(...s){clearTimeout(e),e=setTimeout(()=>{o(...s)},i)}return t.cancel=()=>clearTimeout(e),t}function d(o){const i=document.createElement("div");return i.textContent=o,i.innerHTML}function z(o){return new DOMParser().parseFromString(o,"text/html").documentElement.textContent||""}function V(o){const i=new Date(o),t=new Date().getTime()-i.getTime();if(t<6e4)return"Just now";if(t<36e5){const s=Math.floor(t/6e4);return`${s} ${s===1?"minute":"minutes"} ago`}if(t<864e5){const s=Math.floor(t/36e5);return`${s} ${s===1?"hour":"hours"} ago`}return i.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function A(o){return new Date(o).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function T(o="id"){return`${o}-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function u(o,i){return o!==null?o:i}function v(o,i){return o===null?i:o==="true"||o===""}function k(o,i){if(o===null)return i;const e=Number.parseInt(o,10);return Number.isNaN(e)?i:e}function b(o,i){return new CustomEvent(o,{detail:i,bubbles:!0,composed:!0,cancelable:!0})}function C(o){if(!o)throw new Error("API URL is required");return new q(o)}function y(o){return o!==null&&typeof o=="object"&&!Array.isArray(o)}function $(...o){const i={};for(const e of o)if(e)for(const[t,s]of Object.entries(e)){const r=i[t];y(r)&&y(s)?i[t]=$(r,s):i[t]=s}return i}function K(o,i){if(!y(i))return o;const e=new URLSearchParams;for(const[l,m]of Object.entries(i))m!=null&&e.append(l,String(m));const t=e.toString();if(!t)return o;const s=o.indexOf("#"),r=s===-1?o:o.slice(0,s),n=s===-1?"":o.slice(s),c=r.includes("?")?"&":"?";return`${r}${c}${t}${n}`}function G(o){if(!y(o))return{};const i={};for(const[e,t]of Object.entries(o))t!=null&&(i[e]=String(t));return i}function F(o){return y(o)?o:void 0}class q{constructor(i){a(this,"activeRequests",new Map);a(this,"baseUrl");this.baseUrl=i.replace(/\/$/,"")}request(i,e,t,s){const r=e==="search"?"snippet-search":"snippet-chat-completions",n=K(`${this.baseUrl}/${e}`,s?.queryParams);return fetch(n,{method:"POST",body:JSON.stringify($(F(s?.body),i)),headers:{...G(s?.headers),"Content-Type":"application/json","cf-ai-search-source":r},signal:t})}async search(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);try{const n=await this.request({messages:[{role:"user",content:i}],stream:!1,max_results:e.maxResults??30,ai_search_options:{retrieval:{metadata_only:!0}}},"search",r,e.request);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");const c=await n.json();if(c.success&&c.result)return c.result.chunks.map(l=>({type:"result",id:l.id,title:z(l.item.metadata?.title),description:l.item.metadata?.description?z(l.item.metadata?.description):"",timestamp:l.item.timestamp??void 0,url:l.item.key,image:l.item.metadata?.image||void 0,metadata:l.item.metadata}));throw c.success===!1?new Error(c.error):new Error("Unknown error")}finally{this.unregisterRequest(t)}}async*searchStream(i,e={}){const t=this.generateRequestId(),s=new AbortController,r=e.signal||s.signal;this.registerRequest(t,s);const n=await this.request({messages:[{role:"user",content:i}],stream:!0,...e.maxResults!==void 0&&{max_results:e.maxResults}},"ai-search",r,e.request);if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("Response body is empty");let c="";const l=n.body.getReader(),m=new TextDecoder;for(;;){const{done:g,value:L}=await l.read();if(g)break;const se=m.decode(L,{stream:!0});c+=se}yield{type:"result",id:"",title:"",description:c.replaceAll("data: ","").trim().split(`
2
2
 
3
- `).map(g=>JSON.parse(g)).map(g=>g.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=await this.request({query:i,streaming:!1},"chat/completions",s);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);if(!r.body)throw new Error("Response body is empty");yield{type:"text",message:(await r.json()).choices.map(o=>o.message.content).join("")}}cancelRequest(i){const e=this.activeRequests.get(i);e&&(e.controller.abort(),this.unregisterRequest(i))}cancelAllRequests(){for(const[i]of this.activeRequests)this.cancelRequest(i)}registerRequest(i,e){this.activeRequests.set(i,{id:i,controller:e,timestamp:Date.now()})}unregisterRequest(i){this.activeRequests.delete(i)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}const C=`Powered by <a href="https://workers.cloudflare.com/product/ai-search" target="_blank" rel="noopener noreferrer">Cloudflare AI Search <svg width="32" height="10" viewBox="0 0 412 186" xmlns="http://www.w3.org/2000/svg" aria-label="Cloudflare" role="img">
3
+ `).map(g=>JSON.parse(g)).map(g=>g.response).join(""),url:"",metadata:{}}}async*chat(i,e){const t=new AbortController,s=e?.signal||t.signal,r=await this.request({messages:[{role:"user",content:i}],stream:!1},"chat/completions",s);if(!r.ok)throw new Error(`HTTP error! status: ${r.status}`);if(!r.body)throw new Error("Response body is empty");yield{type:"text",message:(await r.json()).choices.map(c=>c.message.content).join("")}}cancelRequest(i){const e=this.activeRequests.get(i);e&&(e.controller.abort(),this.unregisterRequest(i))}cancelAllRequests(){for(const[i]of this.activeRequests)this.cancelRequest(i)}registerRequest(i,e){this.activeRequests.set(i,{id:i,controller:e,timestamp:Date.now()})}unregisterRequest(i){this.activeRequests.delete(i)}generateRequestId(){return`req-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}}const S=`Powered by <a href="https://workers.cloudflare.com/product/ai-search" target="_blank" rel="noopener noreferrer">Cloudflare AI Search <svg width="32" height="10" viewBox="0 0 412 186" xmlns="http://www.w3.org/2000/svg" aria-label="Cloudflare" role="img">
4
4
  <path fill="#f38020" d="m280.8395,183.31456c11,-26 -4,-38 -19,-38l-148,-2c-4,0 -4,-6 1,-7l150,-2c17,-1 37,-15 43,-33c0,0 10,-21 9,-24a97,97 0 0 0 -187,-11c-38,-25 -78,9 -69,46c-48,3 -65,46 -60,72c0,1 1,2 3,2l274,0c1,0 3,-1 3,-3z"/>
5
5
  <path fill="#faae40" d="m330.8395,81.31456c-4,0 -6,-1 -7,1l-5,21c-5,16 3,30 20,31l32,2c4,0 4,6 -1,7l-33,1c-36,4 -46,39 -46,39c0,2 0,3 2,3l113,0l3,-2a81,81 0 0 0 -78,-103"/>
6
- </svg></a>`,$=`
6
+ </svg></a>`,R=`
7
7
  /* Chat container */
8
8
  .chat-container {
9
9
  display: flex;
@@ -320,7 +320,7 @@
320
320
  .chat-message-bubble a:hover {
321
321
  text-decoration: none;
322
322
  }
323
- `,S=`
323
+ `,E=`
324
324
  :host {
325
325
  /* Colors - Light Mode */
326
326
  --search-snippet-primary-color: #2563eb;
@@ -754,9 +754,9 @@
754
754
  padding: var(--search-snippet-spacing-xs) 0;
755
755
  text-align: center;
756
756
  }
757
- `;function j(c){let i=c;i=V(i),i=i.replace(/```([\s\S]*?)```/g,(n,o)=>`<pre><code>${o.trim()}</code></pre>`);const e=i.split(`
758
- `),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const o=e[n],l=o.match(/^(#{1,6})\s+(.+)$/);if(l){const g=l[1].length,M=l[2];t.push(`<h${g}>${y(M)}</h${g}>`);continue}if(o.match(/^---+$/)){t.push("<hr />");continue}if(o.match(/^>\s+/)){const g=o.replace(/^>\s+/,"");t.push(`<blockquote>${y(g)}</blockquote>`);continue}const b=o.match(/^[-*]\s+(.+)$/);if(b){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${y(b[1])}</li>`);continue}const f=o.match(/^\d+\.\s+(.+)$/);if(f){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${y(f[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),o.trim()===""){t.push("<br />");continue}t.push(`<p>${y(o)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
759
- `)}function y(c){let i=c;return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>"),i=i.replace(/___(.+?)___/g,"<strong><em>$1</em></strong>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.+?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/_(.+?)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),i}function V(c){const i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return c.replace(/[&<>"']/g,e=>i[e]||e)}class B{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"inputElement",null);a(this,"messagesContainer",null);a(this,"sendButton",null);a(this,"messages",[]);a(this,"isStreaming",!1);a(this,"currentStreamingMessageId",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.render(),this.attachEventListeners()}render(){this.container.innerHTML=`
757
+ `;function Y(o){let i=o;i=J(i),i=i.replace(/```([\s\S]*?)```/g,(n,c)=>`<pre><code>${c.trim()}</code></pre>`);const e=i.split(`
758
+ `),t=[];let s=!1,r="";for(let n=0;n<e.length;n++){const c=e[n],l=c.match(/^(#{1,6})\s+(.+)$/);if(l){const g=l[1].length,L=l[2];t.push(`<h${g}>${x(L)}</h${g}>`);continue}if(c.match(/^---+$/)){t.push("<hr />");continue}if(c.match(/^>\s+/)){const g=c.replace(/^>\s+/,"");t.push(`<blockquote>${x(g)}</blockquote>`);continue}const m=c.match(/^[-*]\s+(.+)$/);if(m){(!s||r!=="ul")&&(s&&t.push(`</${r}>`),t.push("<ul>"),s=!0,r="ul"),t.push(`<li>${x(m[1])}</li>`);continue}const f=c.match(/^\d+\.\s+(.+)$/);if(f){(!s||r!=="ol")&&(s&&t.push(`</${r}>`),t.push("<ol>"),s=!0,r="ol"),t.push(`<li>${x(f[1])}</li>`);continue}if(s&&(t.push(`</${r}>`),s=!1,r=""),c.trim()===""){t.push("<br />");continue}t.push(`<p>${x(c)}</p>`)}return s&&t.push(`</${r}>`),t.join(`
759
+ `)}function x(o){let i=o;return i=i.replace(/`([^`]+)`/g,"<code>$1</code>"),i=i.replace(/\*\*\*(.+?)\*\*\*/g,"<strong><em>$1</em></strong>"),i=i.replace(/___(.+?)___/g,"<strong><em>$1</em></strong>"),i=i.replace(/\*\*(.+?)\*\*/g,"<strong>$1</strong>"),i=i.replace(/__(.+?)__/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/_(.+?)_/g,"<em>$1</em>"),i=i.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),i}function J(o){const i={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};return o.replace(/[&<>"']/g,e=>i[e]||e)}class B{constructor(i,e,t){a(this,"container");a(this,"client");a(this,"props");a(this,"inputElement",null);a(this,"messagesContainer",null);a(this,"sendButton",null);a(this,"messages",[]);a(this,"isStreaming",!1);a(this,"currentStreamingMessageId",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputResize",null);a(this,"handleInputKeydown",null);a(this,"handleSendClick",null);this.container=i,this.client=e,this.props=t,this.render(),this.attachEventListeners()}render(){this.container.innerHTML=`
760
760
  <div class="chat-container">
761
761
  <div class="chat-messages">
762
762
  <div class="chat-empty">
@@ -784,7 +784,7 @@
784
784
  </div>
785
785
  </div>
786
786
  </div>
787
- `,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e={id:T("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=T("msg"),s={id:t,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(s),this.currentStreamingMessageId=t,this.renderMessages(!0);try{const r=this.client.chat(i);let n="";for await(const l of r)if(l.type==="text"&&l.message)n+=l.message,this.updateStreamingMessage(t,n);else if(l.type==="error"){this.showErrorInMessage(t,l.message||"Unknown error");break}const o=this.messages.findIndex(l=>l.id===t);o!==-1&&(this.messages[o].content=n),this.container.dispatchEvent(v("message",{message:s}))}catch(r){this.showErrorInMessage(t,r.message),this.container.dispatchEvent(v("error",{error:{message:r.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}addMessage(i){this.messages.push(i),this.renderMessages()}updateStreamingMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=e,this.renderMessages(!0))}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`Error: ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=`
787
+ `,this.messagesContainer=this.container.querySelector(".chat-messages"),this.inputElement=this.container.querySelector(".chat-input"),this.sendButton=this.container.querySelector(".chat-send-button")}attachEventListeners(){!this.inputElement||!this.sendButton||(this.handleInputResize=i=>{const e=i.target;e.style.height="auto",e.style.height=`${e.scrollHeight}px`},this.inputElement.addEventListener("input",this.handleInputResize),this.handleInputKeydown=i=>{i.key==="Enter"&&!i.shiftKey&&(i.preventDefault(),this.handleSendMessage())},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleSendClick=()=>{this.handleSendMessage()},this.sendButton.addEventListener("click",this.handleSendClick))}async handleSendMessage(){if(!this.inputElement||this.isStreaming)return;const i=this.inputElement.value.trim();i.length!==0&&(this.inputElement.value="",this.inputElement.style.height="auto",await this.sendMessage(i))}async sendMessage(i){const e={id:T("msg"),role:"user",content:i,timestamp:Date.now()};this.addMessage(e),this.renderMessages(!0),this.setStreamingState(!0);const t=T("msg"),s={id:t,role:"assistant",content:"",timestamp:Date.now()};this.addMessage(s),this.currentStreamingMessageId=t,this.renderMessages(!0);try{const r=this.client.chat(i);let n="";for await(const l of r)if(l.type==="text"&&l.message)n+=l.message,this.updateStreamingMessage(t,n);else if(l.type==="error"){this.showErrorInMessage(t,l.message||"Unknown error");break}const c=this.messages.findIndex(l=>l.id===t);c!==-1&&(this.messages[c].content=n),this.container.dispatchEvent(b("message",{message:s}))}catch(r){this.showErrorInMessage(t,r.message),this.container.dispatchEvent(b("error",{error:{message:r.message,code:"CHAT_ERROR"}}))}finally{this.setStreamingState(!1),this.renderMessages(),this.currentStreamingMessageId=null}}addMessage(i){this.messages.push(i),this.renderMessages()}updateStreamingMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=e,this.renderMessages(!0))}showErrorInMessage(i,e){const t=this.messages.findIndex(s=>s.id===i);t!==-1&&(this.messages[t].content=`Error: ${e}`,this.renderMessages())}renderMessages(i=!1){if(!this.messagesContainer)return;if(this.messages.length===0){this.messagesContainer.innerHTML=`
788
788
  <div class="chat-empty">
789
789
  <svg class="chat-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
790
790
  <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
@@ -799,16 +799,16 @@
799
799
  <div class="chat-message-avatar">${s}</div>
800
800
  <div class="chat-message-content">
801
801
  <div class="chat-message-bubble">
802
- ${i.content?`<div class="chat-message-text">${j(i.content)}</div>`:""}
802
+ ${i.content?`<div class="chat-message-text">${Y(i.content)}</div>`:""}
803
803
  ${e?`<div class="chat-streaming"><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="chat-streaming-dot"></span><span class="loading-text">${h[this.loadingMessageIndex]}</span></div>`:""}
804
804
  </div>
805
805
  <div class="chat-message-metadata">
806
- <span class="chat-message-time">${O(i.timestamp)}</span>
806
+ <span class="chat-message-time">${V(i.timestamp)}</span>
807
807
  </div>
808
808
  </div>
809
809
  </div>
810
- `}scrollToBottom(){this.messagesContainer&&requestAnimationFrame(()=>{this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)})}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':"<span>Send</span>"),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length,this.isStreaming&&this.renderMessages(!0)},2500)}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){this.clearLoadingMessages(),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const q="chat-bubble-snippet";class R extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
811
- ${$}
810
+ `}scrollToBottom(){this.messagesContainer&&requestAnimationFrame(()=>{this.messagesContainer&&(this.messagesContainer.scrollTop=this.messagesContainer.scrollHeight)})}setStreamingState(i){this.isStreaming=i,this.inputElement&&(this.inputElement.disabled=i),this.sendButton&&(this.sendButton.disabled=i,this.sendButton.innerHTML=i?'<div class="loading"></div>':"<span>Send</span>"),i?this.startLoadingMessages():this.clearLoadingMessages()}startLoadingMessages(){this.loadingMessageIndex=Math.floor(Math.random()*h.length),this.loadingMessageInterval=setInterval(()=>{this.loadingMessageIndex=(this.loadingMessageIndex+1)%h.length,this.isStreaming&&this.renderMessages(!0)},2500)}clearLoadingMessages(){this.loadingMessageInterval&&(clearInterval(this.loadingMessageInterval),this.loadingMessageInterval=null)}getMessages(){return[...this.messages]}clearMessages(){this.messages=[],this.renderMessages()}setMessages(i){this.messages=[...i],this.renderMessages()}destroy(){this.clearLoadingMessages(),this.isStreaming&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputResize&&this.inputElement.removeEventListener("input",this.handleInputResize),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.sendButton&&this.handleSendClick&&this.sendButton.removeEventListener("click",this.handleSendClick),this.handleInputResize=null,this.handleInputKeydown=null,this.handleSendClick=null}}const H="chat-bubble-snippet";class N extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"isExpanded",!1);a(this,"isMinimized",!1);a(this,"handleBubbleClick",null);a(this,"handleCloseClick",null);a(this,"handleMinimizeClick",null);a(this,"handleClearClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatBubbleSnippet: api-url attribute is required"),this.client=null;return}try{this.client=C(e.apiUrl)}catch(t){console.error("ChatBubbleSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${E}
811
+ ${R}
812
812
  ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.container.className="chat-bubble-widget",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getBubbleStyles(){return`
813
813
  .chat-bubble-widget {
814
814
  position: var(--chat-bubble-position);
@@ -982,14 +982,14 @@ ${this.getBubbleStyles()}`,this.container=document.createElement("div"),this.con
982
982
  </div>
983
983
  </div>
984
984
  <div class="chat-content"></div>
985
- ${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
985
+ ${this.getProps().hideBranding?"":`<div class="powered-by">${S}</div>`}
986
986
  </div>
987
987
  `}attachEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick=()=>this.toggleChat(),this.handleCloseClick=()=>this.closeChat(),this.handleMinimizeClick=()=>this.toggleMinimize(),this.handleClearClick=()=>this.clearChat(),e?.addEventListener("click",this.handleBubbleClick),t?.addEventListener("click",this.handleCloseClick),s?.addEventListener("click",this.handleMinimizeClick),r?.addEventListener("click",this.handleClearClick)}removeEventListeners(){const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".close-button"),s=this.shadow.querySelector(".minimize-button"),r=this.shadow.querySelector(".clear-button");this.handleBubbleClick&&e?.removeEventListener("click",this.handleBubbleClick),this.handleCloseClick&&t?.removeEventListener("click",this.handleCloseClick),this.handleMinimizeClick&&s?.removeEventListener("click",this.handleMinimizeClick),this.handleClearClick&&r?.removeEventListener("click",this.handleClearClick),this.handleBubbleClick=null,this.handleCloseClick=null,this.handleMinimizeClick=null,this.handleClearClick=null}toggleChat(){this.isExpanded=!this.isExpanded;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");this.isExpanded?(e?.classList.add("hidden"),t?.classList.add("expanded"),this.initializeChatView()):(e?.classList.remove("hidden"),t?.classList.remove("expanded"))}closeChat(){this.isExpanded=!1,this.isMinimized=!1;const e=this.shadow.querySelector(".bubble-button"),t=this.shadow.querySelector(".chat-window");e?.classList.remove("hidden"),t?.classList.remove("expanded","minimized")}toggleMinimize(){this.isMinimized=!this.isMinimized;const e=this.shadow.querySelector(".chat-window");this.isMinimized?e?.classList.add("minimized"):e?.classList.remove("minimized")}initializeChatView(){if(this.chatView)return;const e=this.shadow.querySelector(".chat-content");if(!e)return;if(!this.client){e.innerHTML=`
988
988
  <div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
989
989
  <strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
990
990
  </div>
991
- `;return}const t=this.getProps();this.chatView=new B(e,this.client,t)}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.chatView?.clearMessages()}async sendMessage(e){this.chatView&&await this.chatView.sendMessage(e)}getMessages(){return this.chatView?.getMessages()||[]}}customElements.get(q)||customElements.define(q,R);const H="chat-page-snippet",N="chat-page-sessions";class _ extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"sessions",[]);a(this,"currentSessionId",null);a(this,"sidebarCollapsed",!1);a(this,"handleClearClick",null);a(this,"handleNewChatClick",null);a(this,"handleToggleSidebarClick",null);a(this,"handleChatListClick",null);a(this,"handleMessageEvent",null);this.shadow=this.attachShadow({mode:"open"}),this.loadSessions()}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.saveCurrentSession(),this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?(this.initializeClient(),this.setupView()):e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=k(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${S}
992
- ${$}
991
+ `;return}const t=this.getProps();this.chatView=new B(e,this.client,t)}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.chatView?.clearMessages()}async sendMessage(e){this.chatView&&await this.chatView.sendMessage(e)}getMessages(){return this.chatView?.getMessages()||[]}}customElements.get(H)||customElements.define(H,N);const O="chat-page-snippet",_="chat-page-sessions";class P extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"chatView",null);a(this,"container",null);a(this,"sessions",[]);a(this,"currentSessionId",null);a(this,"sidebarCollapsed",!1);a(this,"handleClearClick",null);a(this,"handleNewChatClick",null);a(this,"handleToggleSidebarClick",null);a(this,"handleChatListClick",null);a(this,"handleMessageEvent",null);this.shadow=this.attachShadow({mode:"open"}),this.loadSessions()}static get observedAttributes(){return["api-url","placeholder","theme","hide-branding"]}connectedCallback(){this.render(),this.initializeClient(),this.setupView(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.saveCurrentSession(),this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?(this.initializeClient(),this.setupView()):e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Type a message..."),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1)}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("ChatPageSnippet: api-url attribute is required"),this.client=null;return}try{this.client=C(e.apiUrl)}catch(t){console.error("ChatPageSnippet:",t)}}render(){const e=document.createElement("style");e.textContent=`${E}
992
+ ${R}
993
993
  ${this.getPageStyles()}`,this.container=document.createElement("div"),this.container.className="chat-page-container",this.container.innerHTML=this.getBaseHTML(),this.shadow.innerHTML="",this.shadow.appendChild(e),this.shadow.appendChild(this.container),this.attachEventListeners()}getPageStyles(){return`
994
994
  :host {
995
995
  display: block;
@@ -1275,7 +1275,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1275
1275
  New Chat
1276
1276
  </button>
1277
1277
  <div class="chat-list"></div>
1278
- ${this.getProps().hideBranding?"":`<div class="powered-by">${C}</div>`}
1278
+ ${this.getProps().hideBranding?"":`<div class="powered-by">${S}</div>`}
1279
1279
  </div>
1280
1280
  <div class="chat-main">
1281
1281
  <div class="chat-page-header">
@@ -1309,7 +1309,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1309
1309
  <div style="padding: 16px; color: var(--search-snippet-error-color, #ef4444); font-family: var(--search-snippet-font-family, sans-serif); font-size: var(--search-snippet-font-size-base, 14px);">
1310
1310
  <strong>Error:</strong> The <code>api-url</code> attribute is required. Please provide a valid API URL.
1311
1311
  </div>
1312
- `);return}if(!e)return;const t=this.getProps();if(this.chatView=new B(e,this.client,t),this.sessions.length===0)this.createNewChat();else{const s=this.sessions[0];this.switchToSession(s.id)}this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent),this.renderChatList()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}loadSessions(){try{const e=localStorage.getItem(N);e&&(this.sessions=JSON.parse(e),this.sessions.sort((t,s)=>s.updatedAt-t.updatedAt))}catch(e){console.error("Failed to load chat sessions:",e)}}saveSessions(){try{localStorage.setItem(N,JSON.stringify(this.sessions))}catch(e){console.error("Failed to save chat sessions:",e)}}saveCurrentSession(){if(!this.currentSessionId||!this.chatView)return;const e=this.sessions.findIndex(t=>t.id===this.currentSessionId);e!==-1&&(this.sessions[e].messages=this.chatView.getMessages(),this.sessions[e].updatedAt=Date.now(),this.saveSessions())}updateSessionTitle(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);if(e&&e.messages.length>0&&e.title==="New Chat"){const t=e.messages.find(s=>s.role==="user");t&&(e.title=t.content.slice(0,50)+(t.content.length>50?"...":""),this.saveSessions())}}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:"New Chat",messages:[],createdAt:Date.now(),updatedAt:Date.now()};this.sessions.unshift(e),this.currentSessionId=e.id,this.saveSessions(),this.chatView?.clearMessages(),this.renderChatList()}switchToSession(e){if(e===this.currentSessionId)return;this.saveCurrentSession();const t=this.sessions.find(s=>s.id===e);t&&this.chatView&&(this.currentSessionId=e,this.chatView.setMessages(t.messages),this.renderChatList())}deleteSession(e){const t=this.sessions.findIndex(s=>s.id===e);t!==-1&&(this.sessions.splice(t,1),this.saveSessions(),e===this.currentSessionId&&(this.sessions.length>0?this.switchToSession(this.sessions[0].id):this.createNewChat()),this.renderChatList())}clearCurrentChat(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);e&&(e.messages=[],e.title="New Chat",e.updatedAt=Date.now(),this.saveSessions()),this.chatView?.clearMessages(),this.renderChatList()}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed,this.shadow.querySelector(".chat-sidebar")?.classList.toggle("collapsed",this.sidebarCollapsed)}onChatListClick(e){const t=e.target,s=t.closest(".chat-list-item-delete");if(s){e.stopPropagation();const n=s.getAttribute("data-session-id");n&&this.deleteSession(n);return}const r=t.closest(".chat-list-item");if(r){const n=r.getAttribute("data-session-id");n&&this.switchToSession(n)}}renderChatList(){const e=this.shadow.querySelector(".chat-list");if(e){if(this.sessions.length===0){e.innerHTML='<div class="chat-list-empty">No chats yet</div>';return}e.innerHTML=this.sessions.map(t=>this.renderChatListItem(t)).join("")}}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt);return`
1312
+ `);return}if(!e)return;const t=this.getProps();if(this.chatView=new B(e,this.client,t),this.sessions.length===0)this.createNewChat();else{const s=this.sessions[0];this.switchToSession(s.id)}this.handleMessageEvent=()=>{this.saveCurrentSession(),this.updateSessionTitle(),this.renderChatList()},e.addEventListener("message",this.handleMessageEvent),this.renderChatList()}generateSessionId(){return`session_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}loadSessions(){try{const e=localStorage.getItem(_);e&&(this.sessions=JSON.parse(e),this.sessions.sort((t,s)=>s.updatedAt-t.updatedAt))}catch(e){console.error("Failed to load chat sessions:",e)}}saveSessions(){try{localStorage.setItem(_,JSON.stringify(this.sessions))}catch(e){console.error("Failed to save chat sessions:",e)}}saveCurrentSession(){if(!this.currentSessionId||!this.chatView)return;const e=this.sessions.findIndex(t=>t.id===this.currentSessionId);e!==-1&&(this.sessions[e].messages=this.chatView.getMessages(),this.sessions[e].updatedAt=Date.now(),this.saveSessions())}updateSessionTitle(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);if(e&&e.messages.length>0&&e.title==="New Chat"){const t=e.messages.find(s=>s.role==="user");t&&(e.title=t.content.slice(0,50)+(t.content.length>50?"...":""),this.saveSessions())}}createNewChat(){this.saveCurrentSession();const e={id:this.generateSessionId(),title:"New Chat",messages:[],createdAt:Date.now(),updatedAt:Date.now()};this.sessions.unshift(e),this.currentSessionId=e.id,this.saveSessions(),this.chatView?.clearMessages(),this.renderChatList()}switchToSession(e){if(e===this.currentSessionId)return;this.saveCurrentSession();const t=this.sessions.find(s=>s.id===e);t&&this.chatView&&(this.currentSessionId=e,this.chatView.setMessages(t.messages),this.renderChatList())}deleteSession(e){const t=this.sessions.findIndex(s=>s.id===e);t!==-1&&(this.sessions.splice(t,1),this.saveSessions(),e===this.currentSessionId&&(this.sessions.length>0?this.switchToSession(this.sessions[0].id):this.createNewChat()),this.renderChatList())}clearCurrentChat(){if(!this.currentSessionId)return;const e=this.sessions.find(t=>t.id===this.currentSessionId);e&&(e.messages=[],e.title="New Chat",e.updatedAt=Date.now(),this.saveSessions()),this.chatView?.clearMessages(),this.renderChatList()}toggleSidebar(){this.sidebarCollapsed=!this.sidebarCollapsed,this.shadow.querySelector(".chat-sidebar")?.classList.toggle("collapsed",this.sidebarCollapsed)}onChatListClick(e){const t=e.target,s=t.closest(".chat-list-item-delete");if(s){e.stopPropagation();const n=s.getAttribute("data-session-id");n&&this.deleteSession(n);return}const r=t.closest(".chat-list-item");if(r){const n=r.getAttribute("data-session-id");n&&this.switchToSession(n)}}renderChatList(){const e=this.shadow.querySelector(".chat-list");if(e){if(this.sessions.length===0){e.innerHTML='<div class="chat-list-empty">No chats yet</div>';return}e.innerHTML=this.sessions.map(t=>this.renderChatListItem(t)).join("")}}renderChatListItem(e){const t=e.id===this.currentSessionId,s=this.formatDate(e.updatedAt);return`
1313
1313
  <div class="chat-list-item ${t?"active":""}" data-session-id="${e.id}">
1314
1314
  <div class="chat-list-item-content">
1315
1315
  <div class="chat-list-item-title">${this.escapeHTML(e.title)}</div>
@@ -1321,7 +1321,7 @@ ${this.getPageStyles()}`,this.container=document.createElement("div"),this.conta
1321
1321
  </svg>
1322
1322
  </button>
1323
1323
  </div>
1324
- `}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(H)||customElements.define(H,_);const K=`
1324
+ `}formatDate(e){const t=new Date(e),r=new Date().getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24));return n===0?t.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):n===1?"Yesterday":n<7?t.toLocaleDateString(void 0,{weekday:"long"}):t.toLocaleDateString(void 0,{month:"short",day:"numeric"})}escapeHTML(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}updateTheme(e){(e==="light"||e==="dark"?e:null)===null&&this.hasAttribute("theme")&&this.getAttribute("theme")!=="auto"&&this.removeAttribute("theme")}cleanup(){this.removeEventListeners(),this.client&&this.client.cancelAllRequests(),this.chatView&&this.chatView.destroy()}clearChat(){this.clearCurrentChat()}async sendMessage(e){this.chatView&&(await this.chatView.sendMessage(e),this.saveCurrentSession())}getMessages(){return this.chatView?.getMessages()||[]}getSessions(){return[...this.sessions]}getCurrentSession(){return this.sessions.find(e=>e.id===this.currentSessionId)||null}}customElements.get(O)||customElements.define(O,P);const W=`
1325
1325
  /* Search view states */
1326
1326
  .search-view {
1327
1327
  transition: var(--search-snippet-transition-slow);
@@ -1691,8 +1691,8 @@ a.search-result-item:focus-visible {
1691
1691
  border-radius: 2px;
1692
1692
  font-weight: var(--search-snippet-font-weight-medium);
1693
1693
  }
1694
- `,P="search-bar-snippet",G=10,F=100;class E extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"container",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"searchButton",null);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more"]}connectedCallback(){this.initializeClient(),this.render(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),hideBranding:m(this.getAttribute("hide-branding"),!1),showUrl:m(this.getAttribute("show-url"),!1),showDate:m(this.getAttribute("show-date"),!1),hideThumbnails:m(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=k(e.apiUrl)}catch(t){console.error("SearchBarSnippet:",t)}}render(){const e=this.getProps(),t=r=>this.performSearch(r);this.debouncedSearch=L(t,e.debounceMs||400);const s=document.createElement("style");s.textContent=`${S}
1695
- ${K}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
1694
+ `,U="search-bar-snippet",X=10,Z=100;class M extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"container",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"searchButton",null);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleInputChange",null);a(this,"handleInputKeydownEnter",null);a(this,"handleInputKeydownEscape",null);a(this,"handleSearchButtonClick",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","debounce-ms","theme","hide-branding","show-url","show-date","hide-thumbnails","see-more","request-options"]}connectedCallback(){this.initializeClient(),this.render(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:k(this.getAttribute("max-results"),10),debounceMs:k(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),hideBranding:v(this.getAttribute("hide-branding"),!1),showUrl:v(this.getAttribute("show-url"),!1),showDate:v(this.getAttribute("show-date"),!1),hideThumbnails:v(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchBarSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchBarSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=C(e.apiUrl)}catch(t){console.error("SearchBarSnippet:",t)}}render(){const e=this.getProps(),t=r=>this.performSearch(r);this.debouncedSearch=I(t,e.debounceMs||400);const s=document.createElement("style");s.textContent=`${E}
1695
+ ${W}`,this.container=document.createElement("div"),this.container.className="container",this.container.innerHTML=`
1696
1696
  <div class="search-view">
1697
1697
  <div class="search-input-wrapper">
1698
1698
  <svg xmlns="http://www.w3.org/2000/svg" class="search-icon" height="24px" viewBox="0 -960 960 960" width="24px" fill="currentColor"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Z"/></svg>
@@ -1714,7 +1714,7 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
1714
1714
  </div>
1715
1715
  </div>
1716
1716
  </div>
1717
- `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal,maxResults:F}),s=this.getProps(),r=t.slice(0,s.maxResults||G);this.displayResults(r,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=r.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`Found ${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<div class="search-footer">
1717
+ `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(this.container),this.inputElement=this.container.querySelector(".search-input"),this.resultsContainer=this.container.querySelector(".search-results-wrapper"),this.searchButton=this.container.querySelector(".search-submit-button"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachEventListeners(){this.inputElement&&(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):this.showEmptyState()},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydownEnter=e=>{if(e.key==="Enter"){const t=e.target.value.trim();t.length>0&&this.performSearch(t)}},this.inputElement.addEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape=e=>{e.key==="Escape"&&this.inputElement&&(this.inputElement.value="")},window.addEventListener("keydown",this.handleInputKeydownEscape),this.searchButton&&(this.handleSearchButtonClick=()=>{const e=this.inputElement?.value.trim()||"";e.length>0&&this.performSearch(e)},this.searchButton.addEventListener("click",this.handleSearchButtonClick)))}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:Z,request:this.getRequestOptions()}),s=this.getProps(),r=t.slice(0,s.maxResults||X);this.displayResults(r,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=r.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,c=s>e.length,l=c?`Showing ${e.length} of ${s} results`:`Found ${s} result${s===1?"":"s"}`,m=r.seeMore&&c?`<div class="search-footer">
1718
1718
  <a href="${d(r.seeMore+encodeURIComponent(t))}" class="search-see-more">
1719
1719
  <span>See more results</span>
1720
1720
  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
@@ -1729,8 +1729,8 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
1729
1729
  <div class="search-results">
1730
1730
  ${e.map(g=>this.renderResult(g)).join("")}
1731
1731
  </div>
1732
- ${b}
1733
- `;this.resultsContainer.innerHTML=f,this.attachResultHandlers()}renderResult(e){const t=this.getProps(),s=t.hideThumbnails?"":this.renderResultImage(e.image,e.title),r=e.url?d(e.url):"#",n=t.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${d(z(e.timestamp))}</div>`:"",o=t.showUrl&&e.url||n?`<div class="search-result-metadata">
1732
+ ${m}
1733
+ `;this.resultsContainer.innerHTML=f,this.attachResultHandlers()}renderResult(e){const t=this.getProps(),s=t.hideThumbnails?"":this.renderResultImage(e.image,e.title),r=e.url?d(e.url):"#",n=t.showDate&&e.timestamp!==void 0?`<div class="search-result-date">${d(A(e.timestamp))}</div>`:"",c=t.showUrl&&e.url||n?`<div class="search-result-metadata">
1734
1734
  ${t.showUrl&&e.url?`<span class="search-result-url">${d(e.url)}</span>`:'<span class="search-result-url search-result-url-empty"></span>'}
1735
1735
  ${n}
1736
1736
  </div>`:"";return`
@@ -1739,7 +1739,7 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
1739
1739
  <div class="search-result-content">
1740
1740
  <div class="search-result-title">${d(e.title||"")}</div>
1741
1741
  <div class="search-result-snippet">${d(e.description||"")}</div>
1742
- ${o}
1742
+ ${c}
1743
1743
  </div>
1744
1744
  </a>
1745
1745
  `}renderResultImage(e,t){const s='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>';return e?`
@@ -1788,7 +1788,7 @@ ${K}`,this.container=document.createElement("div"),this.container.className="con
1788
1788
  <div class="error">
1789
1789
  <strong>Error:</strong> ${d(e)}
1790
1790
  </div>
1791
- `)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(P)||customElements.define(P,E);const Y=`
1791
+ `)}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.client&&this.client.cancelAllRequests(),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydownEnter&&this.inputElement.removeEventListener("keydown",this.handleInputKeydownEnter),this.handleInputKeydownEscape&&window.removeEventListener("keydown",this.handleInputKeydownEscape)),this.searchButton&&this.handleSearchButtonClick&&this.searchButton.removeEventListener("click",this.handleSearchButtonClick),this.handleInputChange=null,this.handleInputKeydownEnter=null,this.handleInputKeydownEscape=null,this.handleSearchButtonClick=null}async search(e){await this.performSearch(e)}}customElements.get(U)||customElements.define(U,M);const Q=`
1792
1792
  /* Modal backdrop */
1793
1793
  .modal-backdrop {
1794
1794
  position: fixed;
@@ -2225,8 +2225,8 @@ a.modal-result-item:focus-visible {
2225
2225
  .modal-container.open {
2226
2226
  animation: modal-slide-in var(--search-snippet-transition) ease-out;
2227
2227
  }
2228
- `,D="search-modal-snippet",W=10,X=100;class U extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"backdrop",null);a(this,"modal",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"footerCount",null);a(this,"isOpen",!1);a(this,"results",[]);a(this,"activeIndex",-1);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more"]}connectedCallback(){this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(v("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:x(this.getAttribute("max-results"),10),debounceMs:x(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),shortcut:u(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:m(this.getAttribute("hide-branding"),!1),showUrl:m(this.getAttribute("show-url"),!1),showDate:m(this.getAttribute("show-date"),!1),hideThumbnails:m(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=k(e.apiUrl)}catch(t){console.error("SearchModalSnippet:",t)}}render(){const e=this.getProps(),t=o=>this.performSearch(o);this.debouncedSearch=L(t,e.debounceMs||300);const s=document.createElement("style");s.textContent=`${S}
2229
- ${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=document.createElement("div");n.innerHTML=`
2228
+ `,D="search-modal-snippet",ee=10,te=100;class j extends HTMLElement{constructor(){super();a(this,"shadow");a(this,"client",null);a(this,"backdrop",null);a(this,"modal",null);a(this,"inputElement",null);a(this,"resultsContainer",null);a(this,"footerCount",null);a(this,"isOpen",!1);a(this,"results",[]);a(this,"activeIndex",-1);a(this,"debouncedSearch",null);a(this,"currentSearchController",null);a(this,"loadingMessageInterval",null);a(this,"loadingMessageIndex",0);a(this,"handleGlobalKeydown",null);a(this,"handleInputChange",null);a(this,"handleInputKeydown",null);a(this,"handleBackdropClick",null);a(this,"savedBodyStyles",null);a(this,"savedHtmlOverflow",null);this.shadow=this.attachShadow({mode:"open"})}static get observedAttributes(){return["api-url","placeholder","max-results","theme","shortcut","use-meta-key","debounce-ms","hide-branding","show-url","show-date","hide-thumbnails","see-more","request-options"]}connectedCallback(){this.initializeClient(),this.render(),this.attachGlobalKeyboardShortcut(),this.dispatchEvent(b("ready",void 0))}disconnectedCallback(){this.cleanup()}attributeChangedCallback(e,t,s){t!==s&&(e==="api-url"?this.initializeClient():e==="theme"&&this.updateTheme(s))}getProps(){return{apiUrl:u(this.getAttribute("api-url"),""),placeholder:u(this.getAttribute("placeholder"),"Search..."),maxResults:k(this.getAttribute("max-results"),10),debounceMs:k(this.getAttribute("debounce-ms"),300),theme:u(this.getAttribute("theme"),"auto"),shortcut:u(this.getAttribute("shortcut"),"k"),useMetaKey:this.getAttribute("use-meta-key")!=="false",hideBranding:v(this.getAttribute("hide-branding"),!1),showUrl:v(this.getAttribute("show-url"),!1),showDate:v(this.getAttribute("show-date"),!1),hideThumbnails:v(this.getAttribute("hide-thumbnails"),!1),seeMore:u(this.getAttribute("see-more"),"")}}getRequestOptions(){const e=this.getAttribute("request-options");if(e)try{const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("request-options must be a JSON object");return t}catch(t){console.error("SearchModalSnippet: invalid request-options attribute",t);return}}initializeClient(){const e=this.getProps();if(!e.apiUrl){console.error("SearchModalSnippet: api-url attribute is required"),this.client=null,this.showMissingApiUrlError();return}try{this.client=C(e.apiUrl)}catch(t){console.error("SearchModalSnippet:",t)}}render(){const e=this.getProps(),t=c=>this.performSearch(c);this.debouncedSearch=I(t,e.debounceMs||300);const s=document.createElement("style");s.textContent=`${E}
2229
+ ${Q}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${S}</div>`,n=document.createElement("div");n.innerHTML=`
2230
2230
  <div class="modal-backdrop" role="presentation"></div>
2231
2231
  <div class="modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
2232
2232
  <div class="modal-header">
@@ -2269,12 +2269,12 @@ ${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=do
2269
2269
  ${r}
2270
2270
  </div>
2271
2271
  </div>
2272
- `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(v("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{streaming:!1,signal:this.currentSearchController.signal,maxResults:X}),s=this.getProps();this.results=t.slice(0,s.maxResults||W),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(console.log({results:e,query:t,totalResults:s}),this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=e.map((f,g)=>this.renderResult(f,g)).join(""),o=s>e.length,l=o?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,b=r.seeMore&&o?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
2272
+ `,this.shadow.innerHTML="",this.shadow.appendChild(s),this.shadow.appendChild(n),this.backdrop=this.shadow.querySelector(".modal-backdrop"),this.modal=this.shadow.querySelector(".modal-container"),this.inputElement=this.shadow.querySelector(".modal-search-input"),this.resultsContainer=this.shadow.querySelector(".modal-results"),this.footerCount=this.shadow.querySelector(".modal-results-count"),this.attachEventListeners(),this.client||this.showMissingApiUrlError()}attachGlobalKeyboardShortcut(){const e=this.getProps(),t=e.shortcut?.toLowerCase()||"k";this.handleGlobalKeydown=s=>{(e.useMetaKey&&s.metaKey||s.ctrlKey)&&s.key.toLowerCase()===t&&!this.isOpen&&(s.preventDefault(),this.open())},document.addEventListener("keydown",this.handleGlobalKeydown)}attachEventListeners(){!this.inputElement||!this.backdrop||(this.handleInputChange=e=>{const s=e.target.value.trim();s.length>0&&this.debouncedSearch?this.debouncedSearch(s):(this.debouncedSearch?.cancel(),this.currentSearchController?.abort(),this.results=[],this.activeIndex=-1,this.showEmptyState())},this.inputElement.addEventListener("input",this.handleInputChange),this.handleInputKeydown=e=>{switch(e.key){case"ArrowDown":e.preventDefault(),this.navigateResults(1);break;case"ArrowUp":e.preventDefault(),this.navigateResults(-1);break;case"Enter":e.preventDefault(),this.selectActiveResult();break;case"Escape":e.preventDefault(),this.close();break}},this.inputElement.addEventListener("keydown",this.handleInputKeydown),this.handleBackdropClick=e=>{e.target===this.backdrop&&this.close()},this.backdrop.addEventListener("click",this.handleBackdropClick))}navigateResults(e){if(this.results.length===0)return;const t=this.activeIndex+e;t<0?this.activeIndex=this.results.length-1:t>=this.results.length?this.activeIndex=0:this.activeIndex=t,this.updateActiveResult()}updateActiveResult(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");e&&(e.forEach((t,s)=>{s===this.activeIndex?(t.classList.add("active"),t.setAttribute("aria-selected","true"),t.scrollIntoView({block:"nearest"})):(t.classList.remove("active"),t.setAttribute("aria-selected","false"))}),this.inputElement&&this.activeIndex>=0?this.inputElement.setAttribute("aria-activedescendant",`result-${this.activeIndex}`):this.inputElement&&this.inputElement.removeAttribute("aria-activedescendant"))}selectActiveResult(){if(this.activeIndex<0||this.activeIndex>=this.results.length){const s=this.inputElement?.value.trim();s&&s.length>0&&this.performSearch(s);return}const e=this.results[this.activeIndex];this.dispatchEvent(b("result-select",{result:e,index:this.activeIndex}));const t=this.resultsContainer?.querySelector(`.modal-result-item[data-index="${this.activeIndex}"]`);t&&e.url&&t.click(),this.close()}async performSearch(e){if(!this.client){this.showMissingApiUrlError();return}this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.currentSearchController=new AbortController,this.showLoadingState();try{const t=await this.client.search(e,{signal:this.currentSearchController.signal,maxResults:te,request:this.getRequestOptions()}),s=this.getProps();this.results=t.slice(0,s.maxResults||ee),this.activeIndex=this.results.length>0?0:-1,this.displayResults(this.results,e,t.length)}catch(t){if(t.name==="AbortError")return;this.showErrorState(t.message)}finally{this.currentSearchController=null}}displayResults(e,t,s=e.length){if(this.clearLoadingInterval(),!this.resultsContainer)return;if(e.length===0){this.showNoResultsState(t);return}const r=this.getProps(),n=e.map((f,g)=>this.renderResult(f,g)).join(""),c=s>e.length,l=c?`Showing ${e.length} of ${s} results`:`${s} result${s===1?"":"s"}`,m=r.seeMore&&c?`<a href="${d(r.seeMore+encodeURIComponent(t))}" class="modal-see-more">
2273
2273
  <span>See more results</span>
2274
2274
  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
2275
- </a>`:"";this.resultsContainer.innerHTML=n+b,this.footerCount&&(this.footerCount.textContent=l),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?d(e.url):"#",o=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${d(z(e.timestamp))}</div>`:"",l=s.showUrl&&e.url||o?`<div class="modal-result-metadata">
2275
+ </a>`:"";this.resultsContainer.innerHTML=n+m,this.footerCount&&(this.footerCount.textContent=l),this.inputElement&&this.inputElement.setAttribute("aria-expanded","true"),this.attachResultHandlers(),this.updateActiveResult()}renderResult(e,t){const s=this.getProps(),r=s.hideThumbnails?"":this.renderResultImage(e.image,e.title),n=e.url?d(e.url):"#",c=s.showDate&&e.timestamp!==void 0?`<div class="modal-result-date">${d(A(e.timestamp))}</div>`:"",l=s.showUrl&&e.url||c?`<div class="modal-result-metadata">
2276
2276
  ${s.showUrl&&e.url?`<span class="modal-result-url">${d(e.url)}</span>`:'<span class="modal-result-url modal-result-url-empty"></span>'}
2277
- ${o}
2277
+ ${c}
2278
2278
  </div>`:"";return`
2279
2279
  <a
2280
2280
  href="${n}"
@@ -2308,7 +2308,7 @@ ${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=do
2308
2308
  <div class="modal-result-image-container">
2309
2309
  <div class="modal-result-image-placeholder">${s}</div>
2310
2310
  </div>
2311
- `}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",o=>{o.preventDefault()}),s.addEventListener("mouseenter",()=>{this.activeIndex=r,this.updateActiveResult()})}),this.resultsContainer?.querySelectorAll(".modal-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".modal-result-image-container");r?.querySelector(".modal-result-image-loading")?.remove();const n=r?.querySelector(".modal-result-image-placeholder");n&&(n.style.display="flex"),s.style.display="none"})})}renderEmptyState(){return`
2311
+ `}attachResultHandlers(){const e=this.resultsContainer?.querySelectorAll(".modal-result-item");if(!e)return;e.forEach((s,r)=>{s.getAttribute("href")==="#"&&s.addEventListener("click",c=>{c.preventDefault()}),s.addEventListener("mouseenter",()=>{this.activeIndex=r,this.updateActiveResult()})}),this.resultsContainer?.querySelectorAll(".modal-result-image")?.forEach(s=>{s.addEventListener("load",()=>{s.classList.add("loaded"),s.closest(".modal-result-image-container")?.querySelector(".modal-result-image-loading")?.remove()}),s.addEventListener("error",()=>{const r=s.closest(".modal-result-image-container");r?.querySelector(".modal-result-image-loading")?.remove();const n=r?.querySelector(".modal-result-image-placeholder");n&&(n.style.display="flex"),s.style.display="none"})})}renderEmptyState(){return`
2312
2312
  <div class="modal-empty">
2313
2313
  <svg class="modal-empty-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
2314
2314
  <circle cx="11" cy="11" r="8"></circle>
@@ -2334,5 +2334,5 @@ ${Y}`;const r=e.hideBranding?"":`<div class="powered-by-inline">${C}</div>`,n=do
2334
2334
  <div class="error">
2335
2335
  <strong>Error:</strong> ${d(e)}
2336
2336
  </div>
2337
- `,this.footerCount&&(this.footerCount.textContent="Error"))}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width},this.savedHtmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(v("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(v("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(D)||customElements.define(D,U),p.AISearchClient=A,p.ChatBubbleSnippet=R,p.ChatPageSnippet=_,p.SearchBarSnippet=E,p.SearchModalSnippet=U,p.default=E,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2337
+ `,this.footerCount&&(this.footerCount.textContent="Error"))}showMissingApiUrlError(){this.resultsContainer&&this.showErrorState("The api-url attribute is required. Please provide a valid API URL.")}updateTheme(e){const t=e==="light"||e==="dark"||e==="auto"?e:"auto";t==="auto"?this.removeAttribute("theme"):this.setAttribute("theme",t)}lockBodyScroll(){const e=window.scrollY;this.savedBodyStyles={overflow:document.body.style.overflow,position:document.body.style.position,top:document.body.style.top,width:document.body.style.width},this.savedHtmlOverflow=document.documentElement.style.overflow,document.documentElement.style.overflow="hidden",document.body.style.overflow="hidden",document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.width="100%"}unlockBodyScroll(){if(!this.savedBodyStyles)return;const e=Math.abs(Number.parseInt(document.body.style.top||"0",10));document.documentElement.style.overflow=this.savedHtmlOverflow||"",document.body.style.overflow=this.savedBodyStyles.overflow,document.body.style.position=this.savedBodyStyles.position,document.body.style.top=this.savedBodyStyles.top,document.body.style.width=this.savedBodyStyles.width,window.scrollTo(0,e),this.savedBodyStyles=null,this.savedHtmlOverflow=null}cleanup(){this.clearLoadingInterval(),this.currentSearchController&&(this.currentSearchController.abort(),this.currentSearchController=null),this.handleGlobalKeydown&&(document.removeEventListener("keydown",this.handleGlobalKeydown),this.handleGlobalKeydown=null),this.inputElement&&(this.handleInputChange&&this.inputElement.removeEventListener("input",this.handleInputChange),this.handleInputKeydown&&this.inputElement.removeEventListener("keydown",this.handleInputKeydown)),this.backdrop&&this.handleBackdropClick&&this.backdrop.removeEventListener("click",this.handleBackdropClick),this.handleInputChange=null,this.handleInputKeydown=null,this.handleBackdropClick=null,this.client&&this.client.cancelAllRequests()}open(){this.isOpen||(this.isOpen=!0,this.backdrop?.classList.add("open"),this.modal?.classList.add("open"),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.inputElement?.focus()})}),this.lockBodyScroll(),this.dispatchEvent(b("open",void 0)))}close(){this.isOpen&&(this.isOpen=!1,this.backdrop?.classList.remove("open"),this.modal?.classList.remove("open"),this.inputElement&&(this.inputElement.value=""),this.results=[],this.activeIndex=-1,this.showEmptyState(),this.unlockBodyScroll(),this.dispatchEvent(b("close",void 0)))}toggle(){this.isOpen?this.close():this.open()}async search(e){this.isOpen||this.open(),this.inputElement&&(this.inputElement.value=e),await this.performSearch(e)}getResults(){return[...this.results]}isModalOpen(){return this.isOpen}}customElements.get(D)||customElements.define(D,j),p.AISearchClient=q,p.ChatBubbleSnippet=N,p.ChatPageSnippet=P,p.SearchBarSnippet=M,p.SearchModalSnippet=j,p.default=M,Object.defineProperties(p,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
2338
2338
  //# sourceMappingURL=search-snippet.umd.js.map