@magicx-eng/ai-autocomplete-vanilla 0.9.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var ge=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ct=(i,e)=>{for(var t in e)ge(i,t,{get:e[t],enumerable:!0})},pt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lt(e))!dt.call(i,r)&&r!==t&&ge(i,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return i};var ut=i=>pt(ge({},"__esModule",{value:!0}),i);var jt={};ct(jt,{AIAutocomplete:()=>ue,ATTRIBUTION_URL:()=>ye,ModeController:()=>R,SKIPPED_PARAM_TEXT:()=>fe,buildAttributionUrl:()=>ne,buildQuery:()=>v,buildSubmitResult:()=>L,createStore:()=>le,cursorIsAtEnd:()=>V,extractPlainText:()=>_,getCursorOffset:()=>w,getFooterHint:()=>ie,plainTextLength:()=>j,previousGraphemeBoundary:()=>X,renderEditableContent:()=>ae,setCursorOffset:()=>C,withSkippedParams:()=>O});module.exports=ut(jt);var H=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var mt="https://api.ai-autocomplete.com",F=`${mt}/api/suggest`,Ee=new WeakMap;function N(i){return i?.type==="accessToken"}function gt(i){if(!(!i||N(i)))return i}function B(i){let e=Ee.get(i.getAccessToken);return e||(e=new H(i),Ee.set(i.getAccessToken,e)),e}function K(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function U(i){let e=gt(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var fe="skipped";function O(i,e){if(e.length===0)return i;let t=new Set(i.map(r=>r.type)),n=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:fe,kind:null}));return n.length>0?[...i,...n]:i}var ft="0.9.0",Te=!1;function ht(){return crypto.randomUUID()}function bt(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function xt(i,e,t,n,r,o,a){let s=e.find(l=>l.type==="contact"&&l.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof s=="number"?s:void 0;return{data:{raw_query:i,completed_params:O(e.map(l=>bt(l,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(l=>({type:l.type,value:l.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d}},meta:{request_id:ht(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ft,session_id:n}}}async function Ae(i,e,t,n,r){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:r})}async function Ie(i,e,t){let n=t.apiConfig,r=!t.maskCompletedText,o=xt(i,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),a=K(n),s=n?.endpoint??F,d=JSON.stringify(o);if(N(n)){let p=B(n),u=await p.getToken(),f=await Ae(s,a,u,d,t.signal);if(f.status===401){let h=await p.getToken(!0);f=await Ae(s,a,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=U(n);!l&&!Te&&(Te=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(a.Authorization=l);let c=await fetch(s,{method:"POST",headers:a,body:d,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function v(i,e){let t=i,n={},r=[],o=[],a=0;for(let s of e){let d=(n[s.type]??0)+1;n[s.type]=d;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,p=f=>{let h=t.indexOf(s.text,f);for(;h!==-1&&o.some(y=>h<y.end&&h+s.text.length>y.start);)h=t.indexOf(s.text,h+1);return h},u=p(a);if(u===-1&&(u=p(0)),u!==-1){t=t.slice(0,u)+c+t.slice(u+s.text.length);let f=c.length-s.text.length;for(let h of o)h.start>=u+s.text.length&&(h.start+=f,h.end+=f);o.push({start:u,end:u+c.length}),a=u>=a?u+c.length:a+f}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function T(i,e,t){return e>0||!t?e:i.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function $(i,e,t){return e===0&&i.length>0&&t.length>0&&t.toLowerCase().startsWith(i.toLowerCase())}function A(i,e,t){let n=i.slice(e);if(t||e===0||i[e-1]===" ")return n;let r=n.indexOf(" ");return r===-1?"":n.slice(r+1)}function Oe(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let n=t.split(" "),r=e.toLowerCase();for(let o=0;o<n.length;o++){let a=n.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return i.length-s}}return 0}function I(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let n=t.toLowerCase();return i.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(n))}function k(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let n=t.toLowerCase();return i.find(r=>r.is_tappable&&r.text.toLowerCase()===n)??null}function ke(i,e){return e?i.map(t=>{let n=e[t.type];if(!n)return t;let r=n("");return r?{...t,options:r}:t}):i}function De(i,e){let t=0,n=e;for(let r of i)t+=r.value.length,r.type!=="text"&&(n=Math.max(n,t));return n}function Le(i,e){let t=0;for(let n of i){let r=t+n.value.length;if(n.type==="text"&&r>e&&n.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Me(i,e){let t=[],n=new Set;for(let r of[...i,...e])r.type==="placeholder"||n.has(r.type)||(n.add(r.type),t.push({type:r.type,text:r.text}));return t}function Re(i,e,t){if(i===e)return t;let n=Math.min(i.length,e.length),r=0;for(;r<n&&i[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<n-r&&i[i.length-1-o]===e[e.length-1-o];)o++;return i.length-o<=t?t+(e.length-i.length):null}function he(i,e){let t=[],n=[],r=0;for(let o of e){let a=i.indexOf(o.text,r);if(a===-1){n.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:n}}function Ne(i,e,t){let n=[],r=[],o=0;for(let a of t){let s=i.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=i.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}n.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:n,missing:r}}function _e(i,e,t=[]){let n=he(i,e).located,r=Ne(i,n,t).located,o=[...n.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,c)=>l.start-c.start),a=[],s=0;for(let l of o)l.start>s&&a.push({type:"text",value:i.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=i.slice(s);return d&&a.push({type:"text",value:d}),a}function He(i,e){let{located:t,missing:n}=he(i,e);return{valid:t.map(r=>r.param),invalid:n}}function q(i,e,t){let n=he(i,e).located,{located:r,missing:o}=Ne(i,n,t);return{valid:r.map(a=>a.param),invalid:o}}function yt(i){if(i instanceof Error)return i;try{return new Error(String(i))}catch{return new Error("Unknown error")}}var St=100,Pt=300,vt=2,Q=class{constructor(e,t,n,r,o,a,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=n;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.callbacks=s;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(n=>{(n.text!==e||n.completedParams!==t)&&(e=n.text,t=n.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let n=new AbortController;this.abortController=n;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:n.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?Me(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await Ie(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),c=ke(d.data.suggestions??[],this.getOptionOverrides()),p=d.data.input??[],u=p[p.length-1],f=this.store.get().text,h,y;if(u?.state==="in_progress"){y=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:o}else y=!1,h=o;let g=c.filter(x=>x.type!=="placeholder")[0],m=null;if(g){let x=A(f,h,y),S=k(g.options,x);S&&(m={id:crypto.randomUUID(),placeholder:"",type:g.type,text:S.text,kind:S.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:S.metadata},c=c.filter(P=>P!==g),this.callbacks.onAutoMatch?.({active:g,matched:S,rawQuery:e}))}this.store.set(x=>{let S=m?[...x.completedParams,m]:x.completedParams,P=q(x.text,S,l).valid;return{suggestions:c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:y,identifiedParams:P,...m?{completedParams:S}:{}}})}catch(a){let s=yt(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=n=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),a=T(r.text,r.filterBase,o),s=A(r.text,a,r.filterInProgress),l=r.suggestions.filter(m=>m.type!=="placeholder")[0],p=(l?I(l.options,s):[]).filter(m=>m.is_tappable),u=l?k(l.options,s)!==null:!1,f=s.trim().length>0;if(p.length>0&&!u&&f||$(r.text,r.completedParams.length,o))return!1;let{rawQuery:h,completedParams:y}=v(r.text,r.completedParams),b=h.length<r.lastRawQuery.length,g=Math.abs(h.length-r.lastRawQuery.length);return b||g>=n?(this.doFetch(h,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(vt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},St),this.slowDebounceTimer=setTimeout(()=>t(1),Pt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Be='[contenteditable="false"]',D;function Ct(){if(D!==void 0)return D;let i=globalThis.Intl.Segmenter;if(!i)return D=null,null;try{D=new i(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function G(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Be))return!0;t=t.parentNode}return!1}function W(i){return(i.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(e){return G(e,i)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function _(i){let e=W(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function j(i){let e=W(i),t=0,n=e.nextNode();for(;n;)t+=n.data.length,n=e.nextNode();return t}function w(i){let e=(i.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,n=e.anchorOffset;if(!t||!i.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(G(r,i)&&r!==i)return null;let o=0;for(let a=0;a<n&&a<r.childNodes.length;a++)o+=Ke(r.childNodes[a],i);return o+Fe(r,i)}return t.nodeType!==Node.TEXT_NODE||G(t,i)?null:Fe(t,i)+n}function Ke(i,e){if(i.nodeType===Node.TEXT_NODE)return G(i,e)?0:i.data.length;if(i.nodeType!==Node.ELEMENT_NODE)return 0;let t=i;if(t.matches(Be))return 0;let n=0;for(let r of Array.from(t.childNodes))n+=Ke(r,e);return n}function Fe(i,e){let t=W(e),n=0,r=t.nextNode();for(;r;){if(r===i||i.nodeType===Node.ELEMENT_NODE&&i.contains(r))return n;n+=r.data.length,r=t.nextNode()}return n}function C(i,e){let t=i.ownerDocument??document,n=t.getSelection();if(!n)return;let r=Math.max(0,Math.min(e,j(i))),o=W(i),a=0,s=null,d=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(r<a+u){s=l,d=r-a;break}if(r===a+u){let f=o.nextNode();f?(s=f,d=0):(s=l,d=u);break}a+=u,c=l,l=o.nextNode()}let p=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==i&&i.contains(u)?d===0?p.setStartBefore(u):d===s.data.length?p.setStartAfter(u):p.setStart(s,d):p.setStart(s,d)}else c?p.setStart(c,c.data.length):p.setStart(i,0);p.collapse(!0),n.removeAllRanges(),n.addRange(p)}function V(i){let e=w(i);return e==null?!1:e>=j(i)}function X(i,e){if(e<=0)return 0;let t=Ct();if(!t)return e-1;let n=i.slice(0,e),r=0;for(let{index:o}of t.segment(n))o<e&&(r=o);return r}function L(i,e,t=[]){let{rawQuery:n,completedParams:r}=v(i,e);return{query:i.trim(),raw_query:n,completed_params:O(r,t)}}function be(i,e){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?V(i):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function xe(i){return i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?w(i):null}var z=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:n,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=be(e.target,t),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;this.store.set({activeDropdownIndex:s[0]});break}if(e.preventDefault(),s.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let p=s.indexOf(t.activeDropdownIndex),u=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let p=be(e.target,t),u=!!t.editingParam;if(!p&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(s.length===0)return;this.store.set({activeDropdownIndex:f});break}if(s.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),c=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o<o-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(c,p);break}be(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let l=xe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,c);break}if(this.ctx.startEditingParamAtCaret){let l=xe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=xe(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n):a&&a(L(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((u,f)=>u.is_tappable?f:-1).filter(u=>u!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let u=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:u});break}e.preventDefault();let c=l.indexOf(t.activeDropdownIndex),p;if(c<0)p=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;p=(c+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[p]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(l,c)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}getTappableIndices(e){let n=this.store.get().filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of n)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let n=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;n;){let r=getComputedStyle(n).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(n===e)break;n=n.parentElement}return this.ctx.columns}clickOrSelect(e,t,n){let r=document.getElementById(`${n}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),n=e.suggestions.filter(s=>s.type!=="placeholder");if(n.length===0)return;let r=n[0],o=n.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.ctx.fetchNow?.()}};var Y=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),n=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=n.length)return;let r=n[e],o=n.filter((l,c)=>c!==e),a=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],d=this.store.peek({suggestions:s}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var J=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,n){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(n);return}try{let o=await r.fetch(e,t);if(t.aborted||!n())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!n())return;this.commit(d)}catch(o){if(t.aborted||wt(o))return;this.logOnce(o),this.clear(n)}}}clearNow(){this.commit([])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function wt(i){return i instanceof Error&&i.name==="AbortError"}function Ue(i,e){let t=e.dropdownTrigger??"auto",n=e.closeDropdownOnBlur??!0,a=i.filteredOptionsLength>0||i.activePillHasNoOptions||i.hasProducts;if(i.inEditMode){let s=n?i.isFocused:!0;return a&&s}if(t==="auto"){let s=n?i.isFocused:!0,d=i.text.replace(/\s+$/,"").length,l=i.caretOffset==null||i.caretOffset>=d;return(a||i.isLoading)&&s&&l}return t==="manual"?(a||i.isLoading)&&i.pillTapped:!1}function $e(i,e){let t=_e(i.text,i.completedParams,i.identifiedParams),n=i.suggestions.filter(m=>m.type!=="placeholder"),r=n[0],o=r?e.optionOverrides?.[r.type]:void 0,a=i.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),s=T(i.text,Math.min(i.filterBase,i.text.length),a),l=s===0&&$(i.text,i.completedParams.length,a)?"":A(i.text,s,i.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],p=i.editingParam!=null&&i.editingAnchor!=null,u;if(p&&i.editingParam&&i.editingAnchor!=null){let m=i.editingParam.id,x=i.completedParams.some(E=>E.id===m),S=i.caretOffset??i.editingAnchor,P=x?"":i.text.slice(i.editingAnchor,S);u=I(i.editingParam.options,P)}else u=I(c,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(m=>m.is_tappable));let h=m=>f?m.is_tappable:!0,y;if(p){let m=i.editingParam?.options??[];y=i.editingParam!=null&&m.filter(h).length===0}else{let m=r?o?o("")??r.options??[]:r.options??[]:[];y=r!=null&&m.filter(h).length===0}let b=Ue({inEditMode:p,filteredOptionsLength:u.length,isFocused:i.isFocused,text:i.text,caretOffset:i.caretOffset,isLoading:i.isLoading,pillTapped:i.pillTapped,activePillHasNoOptions:y,hasProducts:i.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=b&&i.activeDropdownIndex>=0&&!!u[i.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:n,filteredOptions:u,placeholderText:a,isDropdownOpen:b,isActivePillSelected:g}}function Z(i){return i.mode==="fresh"?Et(i):Tt(i)}function Et(i){let{text:e,completedParams:t,suggestions:n,filterBase:r,filterInProgress:o}=i,s=n.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let d=n.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),c=A(e,l,o),p=k(s.options,c);if(!p)return null;let u=p.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-p.text.length),y=h+p.text.length,b=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,x={id:crypto.randomUUID(),placeholder:"",type:s.type,text:b,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:n.filter(S=>S!==s),filterBase:m,newParamId:x.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function Tt(i){let{text:e,completedParams:t,editingParam:n,editingAnchor:r,editingTail:o}=i;if(t.some(x=>x.id===n.id))return null;let a=e.slice(r,o),s=k(n.options,a);if(!s)return null;let d=s.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),p=c+s.text.length,u=e.slice(c,p),h=p<e.length&&e[p]===" "?p+1:p,y={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:u,kind:s.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:s.metadata},b=t.length,g=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,g);if(S!==-1){if(S>=h){b=x;break}g=S+t[x].text.length}}let m=[...t];return m.splice(b,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function ee(i,e,t){let n=i.slice(0,e),r=i.slice(t),o=(n===""||n.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:n+r,removed:t-e+(o?1:0)}}var te=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let n=t.completedParams.find(a=>a.id===e);if(!n)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:n,editingAnchor:o,editingTail:o+n.text.length,caretOffset:o+n.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null||!t.completedParams.some(d=>d.id===n.id))return!1;let{text:a}=e===""?ee(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(d=>({text:a,completedParams:d.completedParams.filter(l=>l.id!==n.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),n={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(n.editingParam=null,n.editingAnchor=null,n.editingTail=null,n.activeDropdownIndex=-1):t.editingTail!=null&&(n.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(n),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(g=>g.text!==e.text).map(g=>g.text)});let a=t.text.slice(0,r),s=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",c=l?`${d} `:d,p=a+c+s,u=r+c.length+(l?0:1),f={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:d,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},h=t.completedParams.findIndex(g=>g.id===n.id),y=t.completedParams.filter(g=>g.id!==n.id),b=h>=0?Math.min(h,y.length):y.length;y.splice(b,0,f),this.deps.store.set({text:p,completedParams:y,newParamId:f.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(u)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Z({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var ye="https://ai-autocomplete.com";function ne(i=ye){try{if(typeof window>"u"||!window.location)return i;let e=window.location.hostname;if(!e)return i;let t=new URL(i);return t.searchParams.set("utm_source",e),t.toString()}catch{return i}}function ie(i,e){return i?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var qe="data-aia-key";function M(i,e,t){let n=new Map;for(let a of Array.from(i.children)){let s=a.getAttribute(qe);s!=null&&n.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],d=t.keyOf(s,a);r.add(d);let l=n.get(d);l||(l=t.create(s,a),l.setAttribute(qe,d)),t.update?.(l,s,a),i.children[a]!==l&&i.insertBefore(l,i.children[a]??null),o.push(l)}for(let[a,s]of n)r.has(a)||s.remove();return o}var Qe=[125,69];function Ge(i,e){return e?1:i===0?.7:i===1?.4:.2}function re(i,e,t,n,r=!1,o=!1,a=!1){let s=i.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",i.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<Qe.length;d++){let l=Qe[d],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Ge(d,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let d of s.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();M(s,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(d,l,c)=>{let p=d,u=a&&c===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),p.className=f.join(" "),p.style.width="",p.style.opacity=String(Ge(c,u)),o?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>n(c))}})}function Se(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var At="Products";function We(i,e,t,n,r){let o=i.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=At;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),i.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&M(a,e,{keyOf:s=>It(s),create:s=>Ot(s,n,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function Pe(i,e){let t=i.querySelectorAll("[data-aia-product]");for(let n of t)n.tabIndex=e?0:-1}function It(i){return[i.id,i.title,i.url,i.imageUrl,i.price,i.vendor].map(e=>e??"").join("\0")}function Ot(i,e,t){let n=document.createElement("a");n.className="magicx-aia-product",n.setAttribute("data-aia-product",""),n.setAttribute("role","option"),n.setAttribute("aria-selected","false"),n.href=i.url,n.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",i.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=i.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");n.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",i.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=i.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=i.title,o.appendChild(a),i.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=i.price,o.appendChild(s)}return n.appendChild(o),n.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(i))}),n.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(i))}),n.addEventListener("focus",()=>t(!0)),n.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),n}function je(i,e,t,n,r,o,a,s=""){let d=i.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),i.appendChild(d)),Dt(d,e,t,n,r,o,a),kt(d,s)}function kt(i,e){i.dataset.aiaGroup!==e&&(i.dataset.aiaGroup=e,i.scrollTop=0)}function Dt(i,e,t,n,r,o,a){let s=a?"1":"0";M(i,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Lt(d,a),update:(d,l,c)=>{let p=c===t&&!a;d.id=`${o}-option-${c}`,d.dataset.aiaIndex=String(c),d.setAttribute("aria-selected",String(p)),d.classList.toggle("magicx-aia-option--highlighted",p),!a&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),n(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let u=Number.parseInt(d.dataset.aiaIndex??"-1",10);u>=0&&r(u)}):(d.onclick=null,d.onmouseenter=null)}})}function Lt(i,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!i.is_tappable?-1:0;let n=["magicx-aia-option"];i.is_tappable?n.push("magicx-aia-option--tappable"):n.push("magicx-aia-option--non-tappable"),t.className=n.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=i.icon?`${i.icon} ${i.text}`:i.text,a.appendChild(s),i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,a.appendChild(d)}return t.appendChild(a),t}var Mt=[159,119,164];function oe(i){let e=document.createElement("div");return e.id=i,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function se(i,e){let{filteredOptions:t,activeIndex:n,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:p}=e,u=s&&a.length>0,f=t.length>0,h=e.products.length>0,y=r&&(f||u||o||h);if(y?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible"),o?i.setAttribute("data-aia-loading",""):i.removeAttribute("data-aia-loading"),!y){Pe(i,!1);return}h?i.setAttribute("data-aia-has-products",""):i.removeAttribute("data-aia-has-products");let b=i.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),i.appendChild(b));let g=u||o&&s,m=b.querySelector(".magicx-aia-pill-bar");g?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),re(m,a,0,p,!0,o,d)):m&&m.remove();let x=e.suggestions[0],S=x?`${x.type} ${x.text}`:"";je(b,t,n,l,c,e.listboxId,o,S);let P=b.querySelector(".magicx-aia-skeleton-bars");if(o&&!f){if(!P){P=document.createElement("div"),P.className="magicx-aia-skeleton-bars",P.setAttribute("data-aia-skeleton-bars","");for(let st of Mt){let me=document.createElement("span");me.className="magicx-aia-skeleton-bar",me.style.width=`${st}px`,P.appendChild(me)}b.appendChild(P)}}else P&&P.remove();We(b,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Pe(i,!0);let E=b.querySelector(".magicx-aia-footer")??_t(),ot=n>=0&&!!t[n]?.is_tappable;Nt(E,ie(ot,e.isInputEmpty)),E.isConnected||b.appendChild(E),Rt(b,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Rt(i,e){let t=e.map(n=>i.querySelector(`:scope > ${n}`)).filter(n=>n!==null);for(let n=0;n<t.length;n++)i.children[n]!==t[n]&&i.insertBefore(t[n],i.children[n]??null)}function Nt(i,{key:e,hint:t}){let n=i.querySelector(".magicx-aia-footer-key"),r=i.querySelector(".magicx-aia-footer-hint");!n||!r||(n.textContent!==e&&(n.textContent=e),r.textContent!==t&&(r.textContent=t))}function _t(){let i=document.createElement("footer");i.className="magicx-aia-footer",i.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let n=document.createElement("kbd");n.className="magicx-aia-footer-key",n.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(n,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ne(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),i.append(e),i}function Ve(i,e){let t=oe(e.listboxId);return i.appendChild(t),{dropdown:t}}function ve(i,e,t){se(i.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill,onProductSelect:t.selectProduct,onProductFocusChange:n=>t.store.set({isFocused:n})})}function ae(i){let{input:e,segments:t,newParamId:n,editingParamId:r,placeholderText:o,isFocused:a}=i,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(b=>`${b.type}:${b.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===l&&(n??"")===c&&(r??"")===p)return;let u=a?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=n??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),y=0;for(let b of t)if(y+=b.value.length,b.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=b.param.id;let m=b.param.id===n,x=b.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];m&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),g.className=S.join(" "),g.textContent=b.value,h.appendChild(g)}else if(b.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=b.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.textContent=b.value,h.appendChild(g)}else h.appendChild(f.createTextNode(b.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(y),u!=null&&C(e,Math.max(0,Math.min(u,y)))}var Ht='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Xe(){let i=document.createElement("button");return i.type="button",i.className="magicx-aia-submit",i.setAttribute("aria-label","Submit"),i.setAttribute("data-aia-submit",""),i.innerHTML=Ht,i}function Ft(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ze(i,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let n=t.getBoundingClientRect(),r=i.getBoundingClientRect();n.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ye(i,e){let{listboxId:t}=e,n=oe(t);i.appendChild(n);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",i.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Ft()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=Xe(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let c=new AbortController,{signal:p}=c,u=!1,f=0,h=()=>{let g=_(a),x=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(x)},y=()=>{let g=(a.ownerDocument??document).getSelection();if(!g||g.rangeCount===0)return null;let m=g.anchorNode;return!m||!a.contains(m)?null:(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||a.focus()},{signal:p}),a.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(a)))},{signal:p});let b=a.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let g=b.getSelection();if(!g||g.rangeCount===0||!a.contains(g.anchorNode))return;let m=y(),x=e.store.get().editingParam?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-f<50||e.handleCaretMove(w(a))},{signal:p}),a.addEventListener("compositionstart",()=>{u=!0},{signal:p}),a.addEventListener("compositionend",()=>{u=!1,h()},{signal:p}),a.addEventListener("beforeinput",g=>{let m=g,x=m.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){g.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&g.preventDefault()}},{signal:p}),a.addEventListener("paste",g=>{g.preventDefault();let m=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let x=a.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let E=x.createTextNode(m);P.insertNode(E),P.setStartAfter(E),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:p}),a.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:p}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:p}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:p}),l&&l.addEventListener("click",g=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(L(m.text,m.completedParams,m.skippedParams))&&e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1){a.focus();let g=a.ownerDocument??document,m=g.getSelection(),x=m&&m.rangeCount>0&&a.contains(m.anchorNode);if(m&&!x){let S=g.createRange();S.selectNodeContents(a),S.collapse(!0),m.removeAllRanges(),m.addRange(S)}}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>ze(a,s));g.observe(a),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:n,submitButton:d,abort:c}}function Ce(i,e,t){let{input:n,inlinePillContainer:r,dropdown:o,submitButton:a}=i,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?n.setAttribute("aria-activedescendant",p):n.removeAttribute("aria-activedescendant"),a){let b=!!e.text||e.completedParams.length>0;a.disabled=!b}let u=n.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(ae({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?re(r,e.actionableSuggestions,0,d,!1,b,e.isActivePillSelected):Se(r)}else Se(r);ze(n,r),f?(n.focus(),C(n,e.caretOffset??e.text.length)):e.isFocused&&_(n)!==e.text&&C(n,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,y=h??e.actionableSuggestions[0];se(o,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:s==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:b=>c.set({activeDropdownIndex:b}),onPillClick:d,onProductSelect:t.selectProduct,onProductFocusChange:b=>c.set({isFocused:b})})}function Je(i,e){let t=i.actionableSuggestions[0];if(!t)return null;let n=i.filterBase,r=i.text.slice(0,n),o=r.length===0&&i.text.length===0,a=r.length===0&&i.text.length>0&&i.placeholderText.length>0&&i.placeholderText.toLowerCase().startsWith(i.text.toLowerCase());(o||a)&&i.placeholderText&&(r=`${i.placeholderText} `);let s=Oe(r,e.text);s>0&&(r=r.slice(0,r.length-s));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||a)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,p=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=p>=0?c.slice(p,p+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=i.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...i.completedParams,f],newParamId:f.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:i.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function le(i){let e=i,t=new Set,n=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},n.push([e,s]),!r){r=!0;try{let d=0;for(let l=n.shift();l;l=n.shift()){if(++d>1e4)throw n.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,p]=l;for(let u of t)u(c,p)}}catch(d){throw n.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Ze(i,e){let t,n,r=o=>(o!==t&&(t=o,n=e(o)),n);return{get:()=>{let o=i.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?i.set(a=>{let s={...a,...r(a)};return o(s)}):i.set(o)},peek:o=>{let a={...i.get(),...o};return{...a,...e(a)}},subscribe:o=>i.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var we=!1;function et(){if(we||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){we=!0;return}we=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=Bt,document.head.appendChild(i)}var Bt=`@layer layout {
1
+ "use strict";var ge=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var dt=Object.prototype.hasOwnProperty;var ct=(i,e)=>{for(var t in e)ge(i,t,{get:e[t],enumerable:!0})},pt=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lt(e))!dt.call(i,r)&&r!==t&&ge(i,r,{get:()=>e[r],enumerable:!(n=at(e,r))||n.enumerable});return i};var ut=i=>pt(ge({},"__esModule",{value:!0}),i);var jt={};ct(jt,{AIAutocomplete:()=>ue,ATTRIBUTION_URL:()=>ye,ModeController:()=>R,SKIPPED_PARAM_TEXT:()=>fe,buildAttributionUrl:()=>ne,buildQuery:()=>v,buildSubmitResult:()=>L,createStore:()=>le,cursorIsAtEnd:()=>V,extractPlainText:()=>_,getCursorOffset:()=>w,getFooterHint:()=>ie,plainTextLength:()=>j,previousGraphemeBoundary:()=>X,renderEditableContent:()=>ae,setCursorOffset:()=>C,withSkippedParams:()=>O});module.exports=ut(jt);var H=class{constructor(e){this.config=e;this.current=null;this.expiresAt=null;this.inFlightRefresh=null;e.accessToken&&(this.current=e.accessToken)}async getToken(e=!1){if(!e&&this.current&&!this.isExpired())return this.current;if(!e&&this.inFlightRefresh)return this.inFlightRefresh;this.inFlightRefresh=this.refresh();try{return await this.inFlightRefresh}finally{this.inFlightRefresh=null}}async refresh(){let e=await this.config.getAccessToken();return this.current=e.accessToken,this.expiresAt=e.expiresAt??null,this.current}isExpired(){return this.expiresAt==null?!1:Date.now()>=this.expiresAt-3e4}};var mt="https://api.ai-autocomplete.com",F=`${mt}/api/suggest`,Ee=new WeakMap;function N(i){return i?.type==="accessToken"}function gt(i){if(!(!i||N(i)))return i}function B(i){let e=Ee.get(i.getAccessToken);return e||(e=new H(i),Ee.set(i.getAccessToken,e)),e}function K(i){return{"Content-Type":"application/json",...i?.appIdentifier&&{"X-App-Identifier":i.appIdentifier},...i?.headers}}function U(i){let e=gt(i),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var fe="skipped";function O(i,e){if(e.length===0)return i;let t=new Set(i.map(r=>r.type)),n=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:fe,kind:null}));return n.length>0?[...i,...n]:i}var ft="0.9.1",Te=!1;function ht(){return crypto.randomUUID()}function bt(i,e){return{placeholder:i.placeholder,type:i.type,...e&&{text:i.text},kind:i.kind}}function xt(i,e,t,n,r,o,a){let s=e.find(l=>l.type==="contact"&&l.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof s=="number"?s:void 0;return{data:{raw_query:i,completed_params:O(e.map(l=>bt(l,t)),a??[]),...r&&r.length>0&&{identified_params:r.map(l=>({type:l.type,value:l.text}))},...o&&o.length>0&&{recently_suggested:o},...d!=null&&{contact_account_count:d}},meta:{request_id:ht(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:ft,session_id:n}}}async function Ae(i,e,t,n,r){return fetch(i,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:n,signal:r})}async function Ie(i,e,t){let n=t.apiConfig,r=!t.maskCompletedText,o=xt(i,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),a=K(n),s=n?.endpoint??F,d=JSON.stringify(o);if(N(n)){let p=B(n),u=await p.getToken(),f=await Ae(s,a,u,d,t.signal);if(f.status===401){let h=await p.getToken(!0);f=await Ae(s,a,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=U(n);!l&&!Te&&(Te=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(a.Authorization=l);let c=await fetch(s,{method:"POST",headers:a,body:d,signal:t.signal});if(!c.ok)throw new Error(`API error: ${c.status} ${c.statusText}`);return c.json()}function v(i,e){let t=i,n={},r=[],o=[],a=0;for(let s of e){let d=(n[s.type]??0)+1;n[s.type]=d;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,p=f=>{let h=t.indexOf(s.text,f);for(;h!==-1&&o.some(y=>h<y.end&&h+s.text.length>y.start);)h=t.indexOf(s.text,h+1);return h},u=p(a);if(u===-1&&(u=p(0)),u!==-1){t=t.slice(0,u)+c+t.slice(u+s.text.length);let f=c.length-s.text.length;for(let h of o)h.start>=u+s.text.length&&(h.start+=f,h.end+=f);o.push({start:u,end:u+c.length}),a=u>=a?u+c.length:a+f}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function T(i,e,t){return e>0||!t?e:i.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function $(i,e,t){return e===0&&i.length>0&&t.length>0&&t.toLowerCase().startsWith(i.toLowerCase())}function A(i,e,t){let n=i.slice(e);if(t||e===0||i[e-1]===" ")return n;let r=n.indexOf(" ");return r===-1?"":n.slice(r+1)}function Oe(i,e){let t=i.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let n=t.split(" "),r=e.toLowerCase();for(let o=0;o<n.length;o++){let a=n.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return i.length-s}}return 0}function I(i,e){if(!i)return[];let t=e.trimStart();if(!t)return i;let n=t.toLowerCase();return i.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(n))}function k(i,e){if(!i)return null;let t=e.trim();if(!t)return null;let n=t.toLowerCase();return i.find(r=>r.is_tappable&&r.text.toLowerCase()===n)??null}function ke(i,e){return e?i.map(t=>{let n=e[t.type];if(!n)return t;let r=n("");return r?{...t,options:r}:t}):i}function De(i,e){let t=0,n=e;for(let r of i)t+=r.value.length,r.type!=="text"&&(n=Math.max(n,t));return n}function Le(i,e){let t=0;for(let n of i){let r=t+n.value.length;if(n.type==="text"&&r>e&&n.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Me(i,e){let t=[],n=new Set;for(let r of[...i,...e])r.type==="placeholder"||n.has(r.type)||(n.add(r.type),t.push({type:r.type,text:r.text}));return t}function Re(i,e,t){if(i===e)return t;let n=Math.min(i.length,e.length),r=0;for(;r<n&&i[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<n-r&&i[i.length-1-o]===e[e.length-1-o];)o++;return i.length-o<=t?t+(e.length-i.length):null}function he(i,e){let t=[],n=[],r=0;for(let o of e){let a=i.indexOf(o.text,r);if(a===-1){n.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:n}}function Ne(i,e,t){let n=[],r=[],o=0;for(let a of t){let s=i.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=i.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}n.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:n,missing:r}}function _e(i,e,t=[]){let n=he(i,e).located,r=Ne(i,n,t).located,o=[...n.map(l=>({start:l.start,end:l.end,segment:{type:"completed",value:l.param.text,param:l.param}})),...r.map(l=>({start:l.start,end:l.end,segment:{type:"identified",value:l.param.text,param:l.param}}))].sort((l,c)=>l.start-c.start),a=[],s=0;for(let l of o)l.start>s&&a.push({type:"text",value:i.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=i.slice(s);return d&&a.push({type:"text",value:d}),a}function He(i,e){let{located:t,missing:n}=he(i,e);return{valid:t.map(r=>r.param),invalid:n}}function q(i,e,t){let n=he(i,e).located,{located:r,missing:o}=Ne(i,n,t);return{valid:r.map(a=>a.param),invalid:o}}function yt(i){if(i instanceof Error)return i;try{return new Error(String(i))}catch{return new Error("Unknown error")}}var St=100,Pt=300,vt=2,Q=class{constructor(e,t,n,r,o,a,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=n;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=a;this.callbacks=s;this.fetchVersion=0;this.abortController=null;this.debounceTimer=null;this.slowDebounceTimer=null;this.unsubscribe=null}start(){this.doFetch("",[]);let e=this.store.get().text,t=this.store.get().completedParams;this.unsubscribe=this.store.subscribe(n=>{(n.text!==e||n.completedParams!==t)&&(e=n.text,t=n.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let n=new AbortController;this.abortController=n;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:n.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?Me(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await Ie(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:n.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(x=>x.source==="identified").map(x=>({id:crypto.randomUUID(),type:x.type,text:x.text})),c=ke(d.data.suggestions??[],this.getOptionOverrides()),p=d.data.input??[],u=p[p.length-1],f=this.store.get().text,h,y;if(u?.state==="in_progress"){y=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:o}else y=!1,h=o;let g=c.filter(x=>x.type!=="placeholder")[0],m=null;if(g){let x=A(f,h,y),S=k(g.options,x);S&&(m={id:crypto.randomUUID(),placeholder:"",type:g.type,text:S.text,kind:S.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:S.metadata},c=c.filter(P=>P!==g),this.callbacks.onAutoMatch?.({active:g,matched:S,rawQuery:e}))}this.store.set(x=>{let S=m?[...x.completedParams,m]:x.completedParams,P=q(x.text,S,l).valid;return{suggestions:c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:y,identifiedParams:P,...m?{completedParams:S}:{}}})}catch(a){let s=yt(a);r===this.fetchVersion&&(this.store.set({error:s,isLoading:!1}),this.getOnError()?.(s))}finally{if(r===this.fetchVersion&&this.store.get().isLoading)try{this.store.set({isLoading:!1})}catch{}}}scheduleFetch(){if(this.clearTimers(),this.store.get().skipNextFetch){this.store.set({skipNextFetch:!1});return}let t=n=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),a=T(r.text,r.filterBase,o),s=A(r.text,a,r.filterInProgress),l=r.suggestions.filter(m=>m.type!=="placeholder")[0],p=(l?I(l.options,s):[]).filter(m=>m.is_tappable),u=l?k(l.options,s)!==null:!1,f=s.trim().length>0;if(p.length>0&&!u&&f||$(r.text,r.completedParams.length,o))return!1;let{rawQuery:h,completedParams:y}=v(r.text,r.completedParams),b=h.length<r.lastRawQuery.length,g=Math.abs(h.length-r.lastRawQuery.length);return b||g>=n?(this.doFetch(h,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(vt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},St),this.slowDebounceTimer=setTimeout(()=>t(1),Pt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Be='[contenteditable="false"]',D;function Ct(){if(D!==void 0)return D;let i=globalThis.Intl.Segmenter;if(!i)return D=null,null;try{D=new i(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function G(i,e){let t=i;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Be))return!0;t=t.parentNode}return!1}function W(i){return(i.ownerDocument??document).createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(e){return G(e,i)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function _(i){let e=W(i),t="",n=e.nextNode();for(;n;)t+=n.data,n=e.nextNode();return t}function j(i){let e=W(i),t=0,n=e.nextNode();for(;n;)t+=n.data.length,n=e.nextNode();return t}function w(i){let e=(i.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,n=e.anchorOffset;if(!t||!i.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(G(r,i)&&r!==i)return null;let o=0;for(let a=0;a<n&&a<r.childNodes.length;a++)o+=Ke(r.childNodes[a],i);return o+Fe(r,i)}return t.nodeType!==Node.TEXT_NODE||G(t,i)?null:Fe(t,i)+n}function Ke(i,e){if(i.nodeType===Node.TEXT_NODE)return G(i,e)?0:i.data.length;if(i.nodeType!==Node.ELEMENT_NODE)return 0;let t=i;if(t.matches(Be))return 0;let n=0;for(let r of Array.from(t.childNodes))n+=Ke(r,e);return n}function Fe(i,e){let t=W(e),n=0,r=t.nextNode();for(;r;){if(r===i||i.nodeType===Node.ELEMENT_NODE&&i.contains(r))return n;n+=r.data.length,r=t.nextNode()}return n}function C(i,e){let t=i.ownerDocument??document,n=t.getSelection();if(!n)return;let r=Math.max(0,Math.min(e,j(i))),o=W(i),a=0,s=null,d=0,l=o.nextNode(),c=null;for(;l;){let u=l.data.length;if(r<a+u){s=l,d=r-a;break}if(r===a+u){let f=o.nextNode();f?(s=f,d=0):(s=l,d=u);break}a+=u,c=l,l=o.nextNode()}let p=t.createRange();if(s){let u=s.parentElement?.closest('strong[data-seg="completed"]');u&&u!==i&&i.contains(u)?d===0?p.setStartBefore(u):d===s.data.length?p.setStartAfter(u):p.setStart(s,d):p.setStart(s,d)}else c?p.setStart(c,c.data.length):p.setStart(i,0);p.collapse(!0),n.removeAllRanges(),n.addRange(p)}function V(i){let e=w(i);return e==null?!1:e>=j(i)}function X(i,e){if(e<=0)return 0;let t=Ct();if(!t)return e-1;let n=i.slice(0,e),r=0;for(let{index:o}of t.segment(n))o<e&&(r=o);return r}function L(i,e,t=[]){let{rawQuery:n,completedParams:r}=v(i,e);return{query:i.trim(),raw_query:n,completed_params:O(r,t)}}function be(i,e){return i instanceof HTMLTextAreaElement||i instanceof HTMLInputElement?i.selectionStart!=null&&i.selectionStart===i.value.length:i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?V(i):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function xe(i){return i instanceof HTMLElement&&i.hasAttribute("data-aia-input")?w(i):null}var z=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:n,getOnSubmit:r}=this.ctx,o=this.getEffectiveColumns(),a=r(),s=this.getTappableIndices(o);if((e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)&&(e.key==="ArrowDown"||e.key==="ArrowUp"||e.key==="ArrowLeft"||e.key==="ArrowRight"))return;let d=this.ctx.getOptionsPosition()==="above";switch(e.key){case"ArrowDown":{let l=be(e.target,t),c=!!t.editingParam;if(!l&&!c&&t.activeDropdownIndex<0)break;if(t.activeDropdownIndex<0){if(d)break;if(e.preventDefault(),!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:s[0]??0});break}if(s.length===0)return;this.store.set({activeDropdownIndex:s[0]});break}if(e.preventDefault(),s.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/o);if(Math.floor(t.activeDropdownIndex/o)===f){this.store.set({activeDropdownIndex:-1});break}}let p=s.indexOf(t.activeDropdownIndex),u=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let p=be(e.target,t),u=!!t.editingParam;if(!p&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??s[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(s.length===0)return;this.store.set({activeDropdownIndex:f});break}if(s.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=s.indexOf(t.activeDropdownIndex),c=l>0?l-1:s.length-1;this.store.set({activeDropdownIndex:s[c]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o<o-1){let p=t.activeDropdownIndex+1;p<t.filteredOptions.length&&t.filteredOptions[p]?.is_tappable&&this.store.set({activeDropdownIndex:p})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let c=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(c,p);break}be(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l});break}if(!t.editingParam&&this.ctx.startEditingParamAtCaret){let l=xe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,c);break}if(this.ctx.startEditingParamAtCaret){let l=xe(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=xe(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable?this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,n):a&&a(L(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((u,f)=>u.is_tappable?f:-1).filter(u=>u!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let u=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:u});break}e.preventDefault();let c=l.indexOf(t.activeDropdownIndex),p;if(c<0)p=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;p=(c+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[p]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(l,c)}this.store.set({activeDropdownIndex:-1});break}}}firstTappableInBottomRow(e){let t=this.store.get();if(t.filteredOptions.length===0)return null;let r=Math.floor((t.filteredOptions.length-1)/e)*e;for(let o=r;o<t.filteredOptions.length;o++)if(t.filteredOptions[o]?.is_tappable)return o;return null}getTappableIndices(e){let n=this.store.get().filteredOptions.map((o,a)=>o.is_tappable?a:-1).filter(o=>o!==-1),r=Array.from({length:e},()=>[]);for(let o of n)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let n=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;n;){let r=getComputedStyle(n).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(n===e)break;n=n.parentElement}return this.ctx.columns}clickOrSelect(e,t,n){let r=document.getElementById(`${n}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),n=e.suggestions.filter(s=>s.type!=="placeholder");if(n.length===0)return;let r=n[0],o=n.slice(1),a=e.skippedParams.some(s=>s.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...a?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.ctx.fetchNow?.()}};var Y=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),n=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=n.length)return;let r=n[e],o=n.filter((l,c)=>c!==e),a=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=v(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:o.map(c=>c.text)})}let s=[...a,r,...o],d=this.store.peek({suggestions:s}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:s,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};var J=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,n){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(n);return}try{let o=await r.fetch(e,t);if(t.aborted||!n())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!n())return;this.commit(d)}catch(o){if(t.aborted||wt(o))return;this.logOnce(o),this.clear(n)}}}clearNow(){this.commit([])}clear(e){e()&&this.commit([])}commit(e){e.length===0&&this.store.get().products.length===0||this.store.set({products:e})}logOnce(e){this.hasLoggedError||(this.hasLoggedError=!0,console.warn("[AIAutocomplete] products.fetch/transform failed \u2014 the product strip is hidden. Later failures on this instance are not logged.",e))}};function wt(i){return i instanceof Error&&i.name==="AbortError"}function Ue(i,e){let t=e.dropdownTrigger??"auto",n=e.closeDropdownOnBlur??!0,a=i.filteredOptionsLength>0||i.activePillHasNoOptions||i.hasProducts;if(i.inEditMode){let s=n?i.isFocused:!0;return a&&s}if(t==="auto"){let s=n?i.isFocused:!0,d=i.text.replace(/\s+$/,"").length,l=i.caretOffset==null||i.caretOffset>=d;return(a||i.isLoading)&&s&&l}return t==="manual"?(a||i.isLoading)&&i.pillTapped:!1}function $e(i,e){let t=_e(i.text,i.completedParams,i.identifiedParams),n=i.suggestions.filter(m=>m.type!=="placeholder"),r=n[0],o=r?e.optionOverrides?.[r.type]:void 0,a=i.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),s=T(i.text,Math.min(i.filterBase,i.text.length),a),l=s===0&&$(i.text,i.completedParams.length,a)?"":A(i.text,s,i.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],p=i.editingParam!=null&&i.editingAnchor!=null,u;if(p&&i.editingParam&&i.editingAnchor!=null){let m=i.editingParam.id,x=i.completedParams.some(E=>E.id===m),S=i.caretOffset??i.editingAnchor,P=x?"":i.text.slice(i.editingAnchor,S);u=I(i.editingParam.options,P)}else u=I(c,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(m=>m.is_tappable));let h=m=>f?m.is_tappable:!0,y;if(p){let m=i.editingParam?.options??[];y=i.editingParam!=null&&m.filter(h).length===0}else{let m=r?o?o("")??r.options??[]:r.options??[]:[];y=r!=null&&m.filter(h).length===0}let b=Ue({inEditMode:p,filteredOptionsLength:u.length,isFocused:i.isFocused,text:i.text,caretOffset:i.caretOffset,isLoading:i.isLoading,pillTapped:i.pillTapped,activePillHasNoOptions:y,hasProducts:i.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=b&&i.activeDropdownIndex>=0&&!!u[i.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:n,filteredOptions:u,placeholderText:a,isDropdownOpen:b,isActivePillSelected:g}}function Z(i){return i.mode==="fresh"?Et(i):Tt(i)}function Et(i){let{text:e,completedParams:t,suggestions:n,filterBase:r,filterInProgress:o}=i,s=n.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let d=n.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),c=A(e,l,o),p=k(s.options,c);if(!p)return null;let u=p.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-p.text.length),y=h+p.text.length,b=e.slice(h,y),m=y<e.length&&e[y]===" "?y+1:y,x={id:crypto.randomUUID(),placeholder:"",type:s.type,text:b,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:n.filter(S=>S!==s),filterBase:m,newParamId:x.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function Tt(i){let{text:e,completedParams:t,editingParam:n,editingAnchor:r,editingTail:o}=i;if(t.some(x=>x.id===n.id))return null;let a=e.slice(r,o),s=k(n.options,a);if(!s)return null;let d=s.text.toLowerCase(),l=a.toLowerCase().lastIndexOf(d),c=r+Math.max(0,l),p=c+s.text.length,u=e.slice(c,p),h=p<e.length&&e[p]===" "?p+1:p,y={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:u,kind:s.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:s.metadata},b=t.length,g=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,g);if(S!==-1){if(S>=h){b=x;break}g=S+t[x].text.length}}let m=[...t];return m.splice(b,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function ee(i,e,t){let n=i.slice(0,e),r=i.slice(t),o=(n===""||n.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:n+r,removed:t-e+(o?1:0)}}var te=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let n=t.completedParams.find(a=>a.id===e);if(!n)return;let r=0,o=-1;for(let a of t.completedParams){let s=t.text.indexOf(a.text,r);if(s!==-1){if(a.id===e){o=s;break}r=s+a.text.length}}o<0||this.deps.store.set({editingParam:n,editingAnchor:o,editingTail:o+n.text.length,caretOffset:o+n.text.length,activeDropdownIndex:-1})}exit(){this.deps.store.get().editingParam&&this.deps.store.set({editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1})}replaceRange(e){let t=this.deps.store.get(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null||!t.completedParams.some(d=>d.id===n.id))return!1;let{text:a}=e===""?ee(t.text,r,o):{text:t.text.slice(0,r)+e+t.text.slice(o)},s=r+e.length;return this.deps.store.set(d=>({text:a,completedParams:d.completedParams.filter(l=>l.id!==n.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),n={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(n.editingParam=null,n.editingAnchor=null,n.editingTail=null,n.activeDropdownIndex=-1):t.editingTail!=null&&(n.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(n),this.tryPromote()}caretMove(e){let t=this.deps.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null&&e!=null&&(e<t.editingAnchor||e>t.editingTail)){this.deps.store.set({caretOffset:e,editingParam:null,editingAnchor:null,editingTail:null,activeDropdownIndex:-1});return}this.deps.store.set({caretOffset:e})}selectOption(e){let t=this.deps.store.get(),n=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!n||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:n.options.filter(g=>g.text!==e.text).map(g=>g.text)});let a=t.text.slice(0,r),s=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=s.length===0||s[0]!==" ",c=l?`${d} `:d,p=a+c+s,u=r+c.length+(l?0:1),f={id:crypto.randomUUID(),placeholder:"",type:n.suggestionType,text:d,kind:e.kind,suggestionType:n.suggestionType,suggestionPlaceholder:n.suggestionPlaceholder,options:n.options,metadata:e.metadata},h=t.completedParams.findIndex(g=>g.id===n.id),y=t.completedParams.filter(g=>g.id!==n.id),b=h>=0?Math.min(h,y.length):y.length;y.splice(b,0,f),this.deps.store.set({text:p,completedParams:y,newParamId:f.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(u)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=Z({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var ye="https://ai-autocomplete.com";function ne(i=ye){try{if(typeof window>"u"||!window.location)return i;let e=window.location.hostname;if(!e)return i;let t=new URL(i);return t.searchParams.set("utm_source",e),t.toString()}catch{return i}}function ie(i,e){return i?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var qe="data-aia-key";function M(i,e,t){let n=new Map;for(let a of Array.from(i.children)){let s=a.getAttribute(qe);s!=null&&n.set(s,a)}let r=new Set,o=[];for(let a=0;a<e.length;a++){let s=e[a],d=t.keyOf(s,a);r.add(d);let l=n.get(d);l||(l=t.create(s,a),l.setAttribute(qe,d)),t.update?.(l,s,a),i.children[a]!==l&&i.insertBefore(l,i.children[a]??null),o.push(l)}for(let[a,s]of n)r.has(a)||s.remove();return o}var Qe=[125,69];function Ge(i,e){return e?1:i===0?.7:i===1?.4:.2}function re(i,e,t,n,r=!1,o=!1,a=!1){let s=i.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",i.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<Qe.length;d++){let l=Qe[d],c=document.createElement("span");c.setAttribute("data-aia-pill-skeleton",""),c.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,c.style.width=`${l}px`,c.style.opacity=String(Ge(d,!1)),s.appendChild(c)}return}o?s.setAttribute("data-aia-pill-list-loading",""):s.removeAttribute("data-aia-pill-list-loading");for(let d of s.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();M(s,e,{keyOf:d=>`${d.type}-${d.text}`,create:d=>{let l=document.createElement("button");return l.type="button",l.tabIndex=-1,l.setAttribute("data-aia-pill",""),l.setAttribute("contenteditable","false"),l.textContent=d.text,l.addEventListener("mousedown",c=>c.preventDefault()),l},update:(d,l,c)=>{let p=d,u=a&&c===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),p.className=f.join(" "),p.style.width="",p.style.opacity=String(Ge(c,u)),o?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>n(c))}})}function Se(i){i.querySelector(".magicx-aia-pill-list")?.remove()}var At="Products";function We(i,e,t,n,r){let o=i.querySelector(".magicx-aia-products");if(e.length===0){o?.remove();return}if(!o){o=document.createElement("section"),o.className="magicx-aia-products",o.setAttribute("data-aia-products",""),o.setAttribute("role","group"),o.setAttribute("aria-labelledby",`${t}-products-label`);let s=document.createElement("div");s.className="magicx-aia-products-label",s.id=`${t}-products-label`,s.textContent=At;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),i.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&M(a,e,{keyOf:s=>It(s),create:s=>Ot(s,n,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function Pe(i,e){let t=i.querySelectorAll("[data-aia-product]");for(let n of t)n.tabIndex=e?0:-1}function It(i){return[i.id,i.title,i.url,i.imageUrl,i.price,i.vendor].map(e=>e??"").join("\0")}function Ot(i,e,t){let n=document.createElement("a");n.className="magicx-aia-product",n.setAttribute("data-aia-product",""),n.setAttribute("role","option"),n.setAttribute("aria-selected","false"),n.href=i.url,n.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",i.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=i.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");n.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",i.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=i.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=i.title,o.appendChild(a),i.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=i.price,o.appendChild(s)}return n.appendChild(o),n.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(i))}),n.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(i))}),n.addEventListener("focus",()=>t(!0)),n.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),n}function je(i,e,t,n,r,o,a,s=""){let d=i.querySelector(".aia-grid");if(e.length===0){d?.remove();return}d||(d=document.createElement("div"),d.className="aia-grid magicx-aia-grid",d.setAttribute("data-scroll",""),d.style.setProperty("--aia-grid-min","250px"),d.style.setProperty("--aia-grid-max","1fr"),d.style.setProperty("--aia-grid-gap","0"),i.appendChild(d)),Dt(d,e,t,n,r,o,a),kt(d,s)}function kt(i,e){i.dataset.aiaGroup!==e&&(i.dataset.aiaGroup=e,i.scrollTop=0)}function Dt(i,e,t,n,r,o,a){let s=a?"1":"0";M(i,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Lt(d,a),update:(d,l,c)=>{let p=c===t&&!a;d.id=`${o}-option-${c}`,d.dataset.aiaIndex=String(c),d.setAttribute("aria-selected",String(p)),d.classList.toggle("magicx-aia-option--highlighted",p),!a&&l.is_tappable?(d.onclick=()=>{d.classList.add("magicx-aia-option--pressed"),n(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let u=Number.parseInt(d.dataset.aiaIndex??"-1",10);u>=0&&r(u)}):(d.onclick=null,d.onmouseenter=null)}})}function Lt(i,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!i.is_tappable?-1:0;let n=["magicx-aia-option"];i.is_tappable?n.push("magicx-aia-option--tappable"):n.push("magicx-aia-option--non-tappable"),t.className=n.join(" ");let r=document.createElement("div");r.className="magicx-aia-streaks",t.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-streaks-vert",t.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-option-content";let s=document.createElement("span");if(s.className="magicx-aia-option-text",s.textContent=i.icon?`${i.icon} ${i.text}`:i.text,a.appendChild(s),i.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=i.tag,a.appendChild(d)}return t.appendChild(a),t}var Mt=[159,119,164];function oe(i){let e=document.createElement("div");return e.id=i,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function se(i,e){let{filteredOptions:t,activeIndex:n,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:p}=e,u=s&&a.length>0,f=t.length>0,h=e.products.length>0,y=r&&(f||u||o||h);if(y?i.classList.add("magicx-aia-dropdown--visible"):i.classList.remove("magicx-aia-dropdown--visible"),o?i.setAttribute("data-aia-loading",""):i.removeAttribute("data-aia-loading"),!y){Pe(i,!1);return}h?i.setAttribute("data-aia-has-products",""):i.removeAttribute("data-aia-has-products");let b=i.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),i.appendChild(b));let g=u||o&&s,m=b.querySelector(".magicx-aia-pill-bar");g?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),re(m,a,0,p,!0,o,d)):m&&m.remove();let x=e.suggestions[0],S=x?`${x.type} ${x.text}`:"";je(b,t,n,l,c,e.listboxId,o,S);let P=b.querySelector(".magicx-aia-skeleton-bars");if(o&&!f){if(!P){P=document.createElement("div"),P.className="magicx-aia-skeleton-bars",P.setAttribute("data-aia-skeleton-bars","");for(let st of Mt){let me=document.createElement("span");me.className="magicx-aia-skeleton-bar",me.style.width=`${st}px`,P.appendChild(me)}b.appendChild(P)}}else P&&P.remove();We(b,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Pe(i,!0);let E=b.querySelector(".magicx-aia-footer")??_t(),ot=n>=0&&!!t[n]?.is_tappable;Nt(E,ie(ot,e.isInputEmpty)),E.isConnected||b.appendChild(E),Rt(b,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Rt(i,e){let t=e.map(n=>i.querySelector(`:scope > ${n}`)).filter(n=>n!==null);for(let n=0;n<t.length;n++)i.children[n]!==t[n]&&i.insertBefore(t[n],i.children[n]??null)}function Nt(i,{key:e,hint:t}){let n=i.querySelector(".magicx-aia-footer-key"),r=i.querySelector(".magicx-aia-footer-hint");!n||!r||(n.textContent!==e&&(n.textContent=e),r.textContent!==t&&(r.textContent=t))}function _t(){let i=document.createElement("footer");i.className="magicx-aia-footer",i.setAttribute("data-aia-footer","");let e=document.createElement("div");e.className="aia-cluster magicx-aia-footer-row",e.setAttribute("data-align","center"),e.setAttribute("data-justify","between"),e.setAttribute("data-nowrap","");let t=document.createElement("div");t.className="aia-cluster magicx-aia-footer-hint-group",t.setAttribute("data-align","center"),t.style.setProperty("--aia-cluster-gap","5px");let n=document.createElement("kbd");n.className="magicx-aia-footer-key",n.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(n,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ne(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let a=document.createElement("span");a.className="magicx-aia-footer-brand",a.textContent="AI";let s=document.createElement("span");return s.className="magicx-aia-footer-badge",s.textContent="Autocomplete",o.append(a,s),e.append(t,o),i.append(e),i}function Ve(i,e){let t=oe(e.listboxId);return i.appendChild(t),{dropdown:t}}function ve(i,e,t){se(i.dropdown,{suggestions:e.actionableSuggestions.length>0?[{...e.actionableSuggestions[0],options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:e.actionableSuggestions,showPills:!0,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:t.selectOption,onHighlight:n=>t.store.set({activeDropdownIndex:n}),onPillClick:t.setActivePill,onProductSelect:t.selectProduct,onProductFocusChange:n=>t.store.set({isFocused:n})})}function ae(i){let{input:e,segments:t,newParamId:n,editingParamId:r,placeholderText:o,isFocused:a}=i,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(b=>`${b.type}:${b.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===l&&(n??"")===c&&(r??"")===p)return;let u=a?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=n??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),y=0;for(let b of t)if(y+=b.value.length,b.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=b.param.id;let m=b.param.id===n,x=b.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];m&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),g.className=S.join(" "),g.textContent=b.value,h.appendChild(g)}else if(b.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=b.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.textContent=b.value,h.appendChild(g)}else h.appendChild(f.createTextNode(b.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(y),u!=null&&C(e,Math.max(0,Math.min(u,y)))}var Ht='<svg width="18" height="18" viewBox="0 0 18 18" fill="none" role="img" aria-label="Submit"><path d="M9 14V4M9 4L4 9M9 4L14 9" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Xe(){let i=document.createElement("button");return i.type="button",i.className="magicx-aia-submit",i.setAttribute("aria-label","Submit"),i.setAttribute("data-aia-submit",""),i.innerHTML=Ht,i}function Ft(){let i=document.createElement("div");return i.setAttribute("contenteditable","plaintext-only"),i.contentEditable==="plaintext-only"}function ze(i,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let n=t.getBoundingClientRect(),r=i.getBoundingClientRect();n.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function Ye(i,e){let{listboxId:t}=e,n=oe(t);i.appendChild(n);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",i.appendChild(r);let o=document.createElement("div");o.className="magicx-aia-editor",o.setAttribute("data-aia-editor",""),r.appendChild(o);let a=document.createElement("div");a.className="magicx-aia-input",a.setAttribute("data-aia-input",""),a.setAttribute("contenteditable",Ft()?"plaintext-only":"true"),a.setAttribute("role","combobox"),a.setAttribute("aria-autocomplete","list"),a.setAttribute("aria-haspopup","listbox"),a.setAttribute("aria-controls",t),a.setAttribute("aria-expanded","false"),a.setAttribute("spellcheck","true"),a.setAttribute("enterkeyhint","send"),o.appendChild(a);let s=document.createElement("span");s.className="magicx-aia-pill-list-container",s.setAttribute("data-aia-pill-list-container",""),o.appendChild(s);let d=null,l=null;e.submitButton===void 0?(d=Xe(),r.appendChild(d),l=d):e.submitButton!==null&&(l=e.submitButton,l.hasAttribute("data-aia-submit")||l.setAttribute("data-aia-submit",""),r.appendChild(l));let c=new AbortController,{signal:p}=c,u=!1,f=0,h=()=>{let g=_(a),x=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(x)},y=()=>{let g=(a.ownerDocument??document).getSelection();if(!g||g.rangeCount===0)return null;let m=g.anchorNode;return!m||!a.contains(m)?null:(m.nodeType===Node.ELEMENT_NODE?m:m.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",g=>{g.target?.closest("[data-aia-pill]")||a.focus()},{signal:p}),a.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(a)))},{signal:p});let b=a.ownerDocument??document;if(b.addEventListener("selectionchange",()=>{let g=b.getSelection();if(!g||g.rangeCount===0||!a.contains(g.anchorNode))return;let m=g.isCollapsed?y():null,x=e.store.get().editingParam?.id??null;if(m&&m!==x){e.startEditingParam(m);return}performance.now()-f<50||e.handleCaretMove(w(a))},{signal:p}),a.addEventListener("compositionstart",()=>{u=!0},{signal:p}),a.addEventListener("compositionend",()=>{u=!1,h()},{signal:p}),a.addEventListener("beforeinput",g=>{let m=g,x=m.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){g.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":m.data??"";e.replaceEditingRange(S)&&g.preventDefault()}},{signal:p}),a.addEventListener("paste",g=>{g.preventDefault();let m=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!m)return;let x=a.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let E=x.createTextNode(m);P.insertNode(E),P.setStartAfter(E),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:p}),a.addEventListener("keydown",g=>e.handleKeyDown(g),{signal:p}),a.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:p}),a.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:p}),l&&l.addEventListener("click",g=>{let m=e.store.get();if(!(!!m.text||m.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(L(m.text,m.completedParams,m.skippedParams))&&e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1){a.focus();let g=a.ownerDocument??document,m=g.getSelection(),x=m&&m.rangeCount>0&&a.contains(m.anchorNode);if(m&&!x){let S=g.createRange();S.selectNodeContents(a),S.collapse(!0),m.removeAllRanges(),m.addRange(S)}}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>ze(a,s));g.observe(a),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:n,submitButton:d,abort:c}}function Ce(i,e,t){let{input:n,inlinePillContainer:r,dropdown:o,submitButton:a}=i,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=t;n.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?n.setAttribute("aria-activedescendant",p):n.removeAttribute("aria-activedescendant"),a){let b=!!e.text||e.completedParams.length>0;a.disabled=!b}let u=n.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(ae({input:n,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let b=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;b||e.actionableSuggestions.length>0?re(r,e.actionableSuggestions,0,d,!1,b,e.isActivePillSelected):Se(r)}else Se(r);ze(n,r),f?(n.focus(),C(n,e.caretOffset??e.text.length)):e.isFocused&&_(n)!==e.text&&C(n,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,y=h??e.actionableSuggestions[0];se(o,{suggestions:y?[{...y,options:e.filteredOptions}]:[],filteredOptions:e.filteredOptions,activeIndex:e.activeDropdownIndex,isOpen:e.isDropdownOpen,isLoading:e.isLoading&&!e.editingParam&&!e.inSelectionAnimation,listboxId:t.listboxId,pills:h?[h]:e.actionableSuggestions,showPills:s==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:b=>c.set({activeDropdownIndex:b}),onPillClick:d,onProductSelect:t.selectProduct,onProductFocusChange:b=>c.set({isFocused:b})})}function Je(i,e){let t=i.actionableSuggestions[0];if(!t)return null;let n=i.filterBase,r=i.text.slice(0,n),o=r.length===0&&i.text.length===0,a=r.length===0&&i.text.length>0&&i.placeholderText.length>0&&i.placeholderText.toLowerCase().startsWith(i.text.toLowerCase());(o||a)&&i.placeholderText&&(r=`${i.placeholderText} `);let s=Oe(r,e.text);s>0&&(r=r.slice(0,r.length-s));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,c=(o||a)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,p=c.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=p>=0?c.slice(p,p+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=i.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...i.completedParams,f],newParamId:f.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:i.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:h}}function le(i){let e=i,t=new Set,n=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},n.push([e,s]),!r){r=!0;try{let d=0;for(let l=n.shift();l;l=n.shift()){if(++d>1e4)throw n.length=0,new Error("createStore: notifications did not settle after 10000 deliveries \u2014 a listener is likely calling set() on every notification");let[c,p]=l;for(let u of t)u(c,p)}}catch(d){throw n.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function Ze(i,e){let t,n,r=o=>(o!==t&&(t=o,n=e(o)),n);return{get:()=>{let o=i.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?i.set(a=>{let s={...a,...r(a)};return o(s)}):i.set(o)},peek:o=>{let a={...i.get(),...o};return{...a,...e(a)}},subscribe:o=>i.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var we=!1;function et(){if(we||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){we=!0;return}we=!0;let i=document.createElement("style");i.setAttribute("data-magicx-aia",""),i.textContent=Bt,document.head.appendChild(i)}var Bt=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;