@magicx-eng/ai-autocomplete-vanilla 0.10.1 → 0.11.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/README.md CHANGED
@@ -84,6 +84,7 @@ const ac = new AIAutocomplete(container, {
84
84
  dropdownTrigger: "auto", // "auto" | "manual" | "hidden"
85
85
  closeDropdownOnBlur: true, // false = keep dropdown open even when input loses focus
86
86
  showNonTappableOptions: true, // false = hide non-tappable options from the dropdown
87
+ showSkipButton: true, // false = hide the pill bar's trailing "skip" button
87
88
 
88
89
  // Focus
89
90
  autoFocus: true, // focus the input on mount (Tier 1 only)
@@ -374,6 +375,7 @@ unsub();
374
375
  | `selectOption(option)` | Select a dropdown option. Updates text, creates completed param, triggers shimmer. |
375
376
  | `setActiveDropdownIndex(index)` | Set the highlighted option (for mouse hover). |
376
377
  | `setActivePill(index)` | Reorder pills — moves pill at `index` to front (active). |
378
+ | `skipActivePill()` | Skip the active pill — same action as → / the dropdown's skip button. Records it in `skippedParams`; no-ops during re-edit and the post-selection window. Use it to drive a custom skip affordance (e.g. with `showSkipButton: false`). |
377
379
  | `removeLastParam()` | Remove the last completed param from state. The text stays in the input as plain text. |
378
380
  | `clearNewParamId()` | Clear shimmer animation state. |
379
381
  | `reset()` | Clear all state, re-fetch initial suggestions, and start a new session (rotates `session_id`). Call this after handling submit. |
@@ -556,6 +558,8 @@ For styling beyond the CSS variables, target these stable `data-aia-*` attribute
556
558
  | `[data-aia-submit]` | Submit button |
557
559
  | `[data-aia-pill]` | Each unfilled-suggestion pill |
558
560
  | `[data-aia-pillbar]` | Pill bar container inside the dropdown |
561
+ | `[data-aia-pill-scroll]` | Scrollable pill region inside the bar — carries the horizontal scroll and right-edge fade mask |
562
+ | `[data-aia-skip]` | The pill bar's trailing "skip" button. Tune via `--aia-skip-font-size` / `--aia-skip-color` / `--aia-skip-color-hover` / `--aia-skip-hover-bg` |
559
563
  | `[data-aia-option]` | Each suggestion option |
560
564
  | `[data-aia-dropdown]` | The dropdown root (listbox). Carries `data-aia-has-products` while the product strip has cards. |
561
565
  | `[data-aia-products]` | Product strip section (label + row) |
package/dist/index.d.mts CHANGED
@@ -339,6 +339,18 @@ interface CoreOptions {
339
339
  closeDropdownOnBlur?: boolean;
340
340
  /** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
341
341
  showNonTappableOptions?: boolean;
342
+ /**
343
+ * When true (default), the dropdown's pill bar ends in a small "skip" button
344
+ * that dismisses the active pill — same action as pressing → at the end of
345
+ * the input. It sits at the trailing edge of the bar: visually top-right when
346
+ * the dropdown opens below the input, bottom-right when `optionsPosition` is
347
+ * "above" (the stack is reversed). Set to false to hide it. When pills render
348
+ * elsewhere (`pillPlacement: "inline"` / `"hidden"`) the bar renders as a
349
+ * skip-only row holding just the button; it hides during re-edit, on the
350
+ * loading skeleton, and while the input is empty (appearing alongside the
351
+ * footer's "→ to skip" hint once the user has typed) either way.
352
+ */
353
+ showSkipButton?: boolean;
342
354
  /** Render mode. Default: "full". */
343
355
  renderMode?: RenderMode;
344
356
  /**
@@ -516,6 +528,30 @@ declare class AIAutocomplete {
516
528
  */
517
529
  selectProduct(product: Product): void;
518
530
  handleTextChange(value: string): void;
531
+ /**
532
+ * Skip the currently active pill (always index 0 of the actionable
533
+ * suggestions) and promote the next pill to active. Invoked by ArrowRight at
534
+ * the end of the input and by the dropdown's skip button; headless consumers
535
+ * rendering their own skip affordance call it directly.
536
+ *
537
+ * The skipped suggestion is recorded in `skippedParams` so every subsequent
538
+ * request (and the submit result) carries it as a `completed_params` entry
539
+ * with `text: "skipped"` — otherwise the server has no way to know the user
540
+ * declined it and keeps suggesting the same parameter. Deduped by type: the
541
+ * same type skipped twice is one entry.
542
+ *
543
+ * When the last pill is removed there are no options left to show, so the
544
+ * dropdown closes on its own. We also clear `pillTapped` in that case: in
545
+ * `manual` mode the dropdown then stays closed until the user taps again,
546
+ * while in `auto` mode it reopens by itself once the fetch we fire here
547
+ * returns fresh suggestions. While cached pills remain we don't fetch — the
548
+ * next pill is shown from cache and the skip rides along on whatever request
549
+ * goes out next. Unlike an option selection, which fetches on every answer so
550
+ * the next parameter is conditioned on it, a skip does not fetch on its own:
551
+ * a decline carries less signal than an answer, and skipping through several
552
+ * pills would otherwise cost a round-trip each.
553
+ */
554
+ skipActivePill(): void;
519
555
  handleKeyDown(e: KeyboardEvent): void;
520
556
  setFocused(focused: boolean): void;
521
557
  /**
package/dist/index.d.ts CHANGED
@@ -339,6 +339,18 @@ interface CoreOptions {
339
339
  closeDropdownOnBlur?: boolean;
340
340
  /** When true (default), non-tappable options are rendered in the dropdown alongside tappable ones. Set to false to hide them entirely. */
341
341
  showNonTappableOptions?: boolean;
342
+ /**
343
+ * When true (default), the dropdown's pill bar ends in a small "skip" button
344
+ * that dismisses the active pill — same action as pressing → at the end of
345
+ * the input. It sits at the trailing edge of the bar: visually top-right when
346
+ * the dropdown opens below the input, bottom-right when `optionsPosition` is
347
+ * "above" (the stack is reversed). Set to false to hide it. When pills render
348
+ * elsewhere (`pillPlacement: "inline"` / `"hidden"`) the bar renders as a
349
+ * skip-only row holding just the button; it hides during re-edit, on the
350
+ * loading skeleton, and while the input is empty (appearing alongside the
351
+ * footer's "→ to skip" hint once the user has typed) either way.
352
+ */
353
+ showSkipButton?: boolean;
342
354
  /** Render mode. Default: "full". */
343
355
  renderMode?: RenderMode;
344
356
  /**
@@ -516,6 +528,30 @@ declare class AIAutocomplete {
516
528
  */
517
529
  selectProduct(product: Product): void;
518
530
  handleTextChange(value: string): void;
531
+ /**
532
+ * Skip the currently active pill (always index 0 of the actionable
533
+ * suggestions) and promote the next pill to active. Invoked by ArrowRight at
534
+ * the end of the input and by the dropdown's skip button; headless consumers
535
+ * rendering their own skip affordance call it directly.
536
+ *
537
+ * The skipped suggestion is recorded in `skippedParams` so every subsequent
538
+ * request (and the submit result) carries it as a `completed_params` entry
539
+ * with `text: "skipped"` — otherwise the server has no way to know the user
540
+ * declined it and keeps suggesting the same parameter. Deduped by type: the
541
+ * same type skipped twice is one entry.
542
+ *
543
+ * When the last pill is removed there are no options left to show, so the
544
+ * dropdown closes on its own. We also clear `pillTapped` in that case: in
545
+ * `manual` mode the dropdown then stays closed until the user taps again,
546
+ * while in `auto` mode it reopens by itself once the fetch we fire here
547
+ * returns fresh suggestions. While cached pills remain we don't fetch — the
548
+ * next pill is shown from cache and the skip rides along on whatever request
549
+ * goes out next. Unlike an option selection, which fetches on every answer so
550
+ * the next parameter is conditioned on it, a skip does not fetch on its own:
551
+ * a decline carries less signal than an answer, and skipping through several
552
+ * pills would otherwise cost a round-trip each.
553
+ */
554
+ skipActivePill(): void;
519
555
  handleKeyDown(e: KeyboardEvent): void;
520
556
  setFocused(focused: boolean): void;
521
557
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var xe=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var mt=Object.getOwnPropertyNames;var gt=Object.prototype.hasOwnProperty;var ft=(n,e)=>{for(var t in e)xe(n,t,{get:e[t],enumerable:!0})},ht=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of mt(e))!gt.call(n,r)&&r!==t&&xe(n,r,{get:()=>e[r],enumerable:!(i=ut(e,r))||i.enumerable});return n};var bt=n=>ht(xe({},"__esModule",{value:!0}),n);var rn={};ft(rn,{AIAutocomplete:()=>he,ATTRIBUTION_URL:()=>Ce,ModeController:()=>R,OPTIONS_GRID_MOBILE_QUERY:()=>H,SKIPPED_PARAM_TEXT:()=>ye,buildAttributionUrl:()=>se,buildQuery:()=>v,buildSubmitResult:()=>M,computeOptionsGridLayout:()=>ee,createStore:()=>ue,cursorIsAtEnd:()=>X,extractPlainText:()=>_,getCursorOffset:()=>w,getFooterHint:()=>ae,isOptionsGridMobileViewport:()=>ne,optionsGridTemplateColumns:()=>te,plainTextLength:()=>j,previousGraphemeBoundary:()=>z,renderEditableContent:()=>pe,setCursorOffset:()=>C,withSkippedParams:()=>O});module.exports=bt(rn);var B=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 xt="https://api.ai-autocomplete.com",F=`${xt}/api/suggest`,Oe=new WeakMap;function N(n){return n?.type==="accessToken"}function yt(n){if(!(!n||N(n)))return n}function K(n){let e=Oe.get(n.getAccessToken);return e||(e=new B(n),Oe.set(n.getAccessToken,e)),e}function U(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function $(n){let e=yt(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var ye="skipped";function O(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:ye,kind:null}));return i.length>0?[...n,...i]:n}var St="0.10.1",ke=!1;function Pt(){return crypto.randomUUID()}function vt(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Ct(n,e,t,i,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:n,completed_params:O(e.map(l=>vt(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:Pt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:St,session_id:i}}}async function Le(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function Me(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Ct(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),a=U(i),s=i?.endpoint??F,d=JSON.stringify(o);if(N(i)){let p=K(i),u=await p.getToken(),f=await Le(s,a,u,d,t.signal);if(f.status===401){let b=await p.getToken(!0);f=await Le(s,a,b,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=$(i);!l&&!ke&&(ke=!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(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let d=(i[s.type]??0)+1;i[s.type]=d;let c=`{{${s.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,p=f=>{let b=t.indexOf(s.text,f);for(;b!==-1&&o.some(y=>b<y.end&&b+s.text.length>y.start);)b=t.indexOf(s.text,b+1);return b},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 b of o)b.start>=u+s.text.length&&(b.start+=f,b.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(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function G(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function I(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function De(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function A(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function k(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function Re(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function Ne(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function _e(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function He(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function Be(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function Se(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function Fe(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function Ke(n,e,t=[]){let i=Se(n,e).located,r=Fe(n,i,t).located,o=[...i.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:n.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=n.slice(s);return d&&a.push({type:"text",value:d}),a}function Ue(n,e){let{located:t,missing:i}=Se(n,e);return{valid:t.map(r=>r.param),invalid:i}}function q(n,e,t){let i=Se(n,e).located,{located:r,missing:o}=Fe(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function wt(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var Et=100,Tt=300,It=2,Q=class{constructor(e,t,i,r,o,a,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;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(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?He(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await Me(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.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=Re(d.data.suggestions??[],this.getOptionOverrides()),p=d.data.input??[],u=p[p.length-1],f=this.store.get().text,b,y;if(u?.state==="in_progress"){y=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());b=x!==-1?x:o}else y=!1,b=o;let g=c.filter(x=>x.type!=="placeholder")[0],m=null;if(g){let x=I(f,b,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:b,filterInProgress:y,identifiedParams:P,...m?{completedParams:S}:{}}})}catch(a){let s=wt(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=i=>{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=I(r.text,a,r.filterInProgress),l=r.suggestions.filter(m=>m.type!=="placeholder")[0],p=(l?A(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||G(r.text,r.completedParams.length,o))return!1;let{rawQuery:b,completedParams:y}=v(r.text,r.completedParams),h=b.length<r.lastRawQuery.length,g=Math.abs(b.length-r.lastRawQuery.length);return h||g>=i?(this.doFetch(b,y),!0):!1};this.debounceTimer=setTimeout(()=>{t(It)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},Et),this.slowDebounceTimer=setTimeout(()=>t(1),Tt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Ge='[contenteditable="false"]',L;function At(){if(L!==void 0)return L;let n=globalThis.Intl.Segmenter;if(!n)return L=null,null;try{L=new n(void 0,{granularity:"grapheme"})}catch{L=null}return L??null}function W(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Ge))return!0;t=t.parentNode}return!1}function V(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return W(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function _(n){let e=V(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function j(n){let e=V(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function w(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(W(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=qe(r.childNodes[a],n);return o+$e(r,n)}return t.nodeType!==Node.TEXT_NODE||W(t,n)?null:$e(t,n)+i}function qe(n,e){if(n.nodeType===Node.TEXT_NODE)return W(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Ge))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=qe(r,e);return i}function $e(n,e){let t=V(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function C(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,j(n))),o=V(n),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!==n&&n.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(n,0);p.collapse(!0),i.removeAllRanges(),i.addRange(p)}function X(n){let e=w(n);return e==null?!1:e>=j(n)}function z(n,e){if(e<=0)return 0;let t=At();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function M(n,e,t=[]){let{rawQuery:i,completedParams:r}=v(n,e);return{query:n.trim(),raw_query:i,completed_params:O(r,t)}}function Pe(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?X(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ve(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?w(n):null}var Y=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,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=Pe(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=Pe(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}Pe(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=ve(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=ve(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=ve(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,i):a&&a(M(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 i=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 i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}removeActivePill(){let e=this.store.get(),t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.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 J=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.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 Z=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||Ot(o))return;this.logOnce(o),this.clear(i)}}}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 Ot(n){return n instanceof Error&&n.name==="AbortError"}var H="(max-width: 768px)";var kt="var(--aia-option-row-height, 37px)",Lt="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function ee(n,e){let t=(i,r)=>({cols:i,rows:r,maxHeight:`calc(${r} * ${kt} + ${Lt})`});return e?t(1,Math.min(n,5)):n>=5&&n<=6?t(2,Math.ceil(n/2)):t(1,Math.min(n,4))}function te(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function ne(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(H).matches}function Qe(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(a||n.isLoading)&&s&&l}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function We(n,e){let t=Ke(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(m=>m.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(m=>m.type==="placeholder").map(m=>m.text).join(" "),s=T(n.text,Math.min(n.filterBase,n.text.length),a),l=s===0&&G(n.text,n.completedParams.length,a)?"":I(n.text,s,n.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],p=n.editingParam!=null&&n.editingAnchor!=null,u;if(p&&n.editingParam&&n.editingAnchor!=null){let m=n.editingParam.id,x=n.completedParams.some(E=>E.id===m),S=n.caretOffset??n.editingAnchor,P=x?"":n.text.slice(n.editingAnchor,S);u=A(n.editingParam.options,P)}else u=A(c,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(m=>m.is_tappable));let b=m=>f?m.is_tappable:!0,y;if(p){let m=n.editingParam?.options??[];y=n.editingParam!=null&&m.filter(b).length===0}else{let m=r?o?o("")??r.options??[]:r.options??[]:[];y=r!=null&&m.filter(b).length===0}let h=Qe({inEditMode:p,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:y,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=h&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,placeholderText:a,isDropdownOpen:h,isActivePillSelected:g}}function ie(n){return n.mode==="fresh"?Mt(n):Dt(n)}function Mt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(S=>S.type!=="placeholder")[0];if(!s?.options)return null;let d=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),c=I(e,l,o),p=k(s.options,c);if(!p)return null;let u=p.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),b=f>=0?f:Math.max(0,e.length-p.text.length),y=b+p.text.length,h=e.slice(b,y),m=y<e.length&&e[y]===" "?y+1:y,x={id:crypto.randomUUID(),placeholder:"",type:s.type,text:h,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:i.filter(S=>S!==s),filterBase:m,newParamId:x.id,caretOffset:m,activeDropdownIndex:-1},caretPos:m}}function Dt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(x=>x.id===i.id))return null;let a=e.slice(r,o),s=k(i.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),b=p<e.length&&e[p]===" "?p+1:p,y={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:u,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},h=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>=b){h=x;break}g=S+t[x].text.length}}let m=[...t];return m.splice(h,0,y),{patch:{text:e,completedParams:m,newParamId:y.id,filterBase:b,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:b,activeDropdownIndex:-1},caretPos:b}}function re(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var oe=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(a=>a.id===e);if(!i)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:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.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(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(d=>d.id===i.id))return!1;let{text:a}=e===""?re(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!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),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(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.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:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},b=t.completedParams.findIndex(g=>g.id===i.id),y=t.completedParams.filter(g=>g.id!==i.id),h=b>=0?Math.min(b,y.length):y.length;y.splice(h,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),this.deps.fetchNow()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ie({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 Ce="https://ai-autocomplete.com";function se(n=Ce){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function ae(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ve="data-aia-key";function D(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(Ve);s!=null&&i.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=i.get(d);l||(l=t.create(s,a),l.setAttribute(Ve,d)),t.update?.(l,s,a),n.children[a]!==l&&n.insertBefore(l,n.children[a]??null),o.push(l)}for(let[a,s]of i)r.has(a)||s.remove();return o}var je=[125,69];function Xe(n,e){return e?1:n===0?.7:n===1?.4:.2}function le(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<je.length;d++){let l=je[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(Xe(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();D(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(Xe(c,u)),o?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>i(c))}})}function we(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Rt="Products";function ze(n,e,t,i,r){let o=n.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=Rt;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&D(a,e,{keyOf:s=>Nt(s),create:s=>_t(s,i,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function Ee(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Nt(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function _t(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}function Ht(n,e){let{cols:t,maxHeight:i}=ee(e,ne());n.style.gridTemplateColumns=te(t),n.style.setProperty("--aia-grid-max-height",i)}function Ye(n,e,t,i,r,o,a,s=""){let d=n.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"),n.appendChild(d)),Ht(d,e.length),Ft(d,e,t,i,r,o,a),Bt(d,s)}function Bt(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function Ft(n,e,t,i,r,o,a){let s=a?"1":"0";D(n,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Kt(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"),i(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 Kt(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.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=n.icon?`${n.icon} ${n.text}`:n.text,a.appendChild(s),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,a.appendChild(d)}return t.appendChild(a),t}var Ut=[159,119,164];function de(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function ce(n,e){let{filteredOptions:t,activeIndex:i,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,b=e.products.length>0,y=r&&(f||u||o||b);if(y?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!y){Ee(n,!1);return}b?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let h=n.querySelector(".aia-stack");h||(h=document.createElement("div"),h.className="aia-stack",h.style.setProperty("--aia-stack-space","8px"),n.appendChild(h));let g=u||o&&s,m=h.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",""),h.insertBefore(m,h.firstChild)),le(m,a,0,p,!0,o,d)):m&&m.remove();let x=e.suggestions[0],S=x?`${x.type} ${x.text}`:"";Ye(h,t,i,l,c,e.listboxId,o,S);let P=h.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 pt of Ut){let be=document.createElement("span");be.className="magicx-aia-skeleton-bar",be.style.width=`${pt}px`,P.appendChild(be)}h.appendChild(P)}}else P&&P.remove();ze(h,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Ee(n,!0);let E=h.querySelector(".magicx-aia-footer")??qt(),ct=i>=0&&!!t[i]?.is_tappable;Gt(E,ae(ct,e.isInputEmpty)),E.isConnected||h.appendChild(E),$t(h,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function $t(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function Gt(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function qt(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.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 i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=se(),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),n.append(e),n}function Je(n,e){let t=de(e.listboxId);return n.appendChild(t),{dropdown:t}}function Te(n,e,t){ce(n.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:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Qt=6,Wt=.3;function Ze(n){return n<=0?"0px":`${(-Math.min(Wt,2*Qt/n)).toFixed(3)}px`}function pe(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(h=>`${h.type}:${h.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===l&&(i??"")===c&&(r??"")===p)return;let u=a?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,b=f.createDocumentFragment(),y=0;for(let h of t)if(y+=h.value.length,h.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=h.param.id;let m=h.param.id===i,x=h.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.style.letterSpacing=Ze(h.value.length),g.textContent=h.value,b.appendChild(g)}else if(h.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=h.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.style.letterSpacing=Ze(h.value.length),g.textContent=h.value,b.appendChild(g)}else b.appendChild(f.createTextNode(h.value));e.replaceChildren(b),e.dataset.aiaTextLength=String(y),u!=null&&C(e,Math.max(0,Math.min(u,y)))}var Vt='<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 et(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=Vt,n}function jt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function tt(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function nt(n,e){let{listboxId:t}=e,i=de(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.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",jt()?"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=et(),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,b=()=>{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(),b(),e.handleCaretAfterInput(w(a)))},{signal:p});let h=a.ownerDocument??document;if(h.addEventListener("selectionchange",()=>{let g=h.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,b()},{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),b()},{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(M(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(()=>tt(a,s));g.observe(a),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:d,abort:c}}function Ie(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?i.setAttribute("aria-activedescendant",p):i.removeAttribute("aria-activedescendant"),a){let h=!!e.text||e.completedParams.length>0;a.disabled=!h}let u=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(pe({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let h=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;h||e.actionableSuggestions.length>0?le(r,e.actionableSuggestions,0,d,!1,h,e.isActivePillSelected):we(r)}else we(r);tt(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&_(i)!==e.text&&C(i,e.text.length);let b=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,y=b??e.actionableSuggestions[0];ce(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:b?[b]:e.actionableSuggestions,showPills:s==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:h=>c.set({activeDropdownIndex:h}),onPillClick:d,onProductSelect:t.selectProduct,onProductFocusChange:h=>c.set({isFocused:h})})}function it(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=De(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},b=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(y=>y.text!==e.text).map(y=>y.text)},consumedSuggestion:t,remainingActionable:b}}function ue(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!r){r=!0;try{let d=0;for(let l=i.shift();l;l=i.shift()){if(++d>1e4)throw i.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 i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function rt(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var Ae=!1;function ot(){if(Ae||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Ae=!0;return}Ae=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Xt,document.head.appendChild(n)}var Xt=`@layer layout {
1
+ "use strict";var ve=Object.defineProperty;var ft=Object.getOwnPropertyDescriptor;var ht=Object.getOwnPropertyNames;var bt=Object.prototype.hasOwnProperty;var xt=(n,e)=>{for(var t in e)ve(n,t,{get:e[t],enumerable:!0})},St=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ht(e))!bt.call(n,r)&&r!==t&&ve(n,r,{get:()=>e[r],enumerable:!(i=ft(e,r))||i.enumerable});return n};var yt=n=>St(ve({},"__esModule",{value:!0}),n);var ln={};xt(ln,{AIAutocomplete:()=>ye,ATTRIBUTION_URL:()=>Ae,ModeController:()=>B,OPTIONS_GRID_MOBILE_QUERY:()=>K,SKIPPED_PARAM_TEXT:()=>Ce,buildAttributionUrl:()=>ce,buildQuery:()=>v,buildSubmitResult:()=>N,computeOptionsGridLayout:()=>re,createStore:()=>he,cursorIsAtEnd:()=>Z,extractPlainText:()=>F,getCursorOffset:()=>T,getFooterHint:()=>pe,isOptionsGridMobileViewport:()=>se,optionsGridTemplateColumns:()=>oe,plainTextLength:()=>J,previousGraphemeBoundary:()=>ee,renderEditableContent:()=>fe,setCursorOffset:()=>C,withSkippedParams:()=>M});module.exports=yt(ln);var $=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 Pt="https://api.ai-autocomplete.com",G=`${Pt}/api/suggest`,De=new WeakMap;function H(n){return n?.type==="accessToken"}function vt(n){if(!(!n||H(n)))return n}function q(n){let e=De.get(n.getAccessToken);return e||(e=new $(n),De.set(n.getAccessToken,e)),e}function Q(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function W(n){let e=vt(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var Ce="skipped";function M(n,e){if(e.length===0)return n;let t=new Set(n.map(r=>r.type)),i=e.filter(r=>!t.has(r.type)).map(r=>({placeholder:"",type:r.type,text:Ce,kind:null}));return i.length>0?[...n,...i]:n}var Ct="0.11.1",Re=!1;function wt(){return crypto.randomUUID()}function Et(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function Tt(n,e,t,i,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:n,completed_params:M(e.map(l=>Et(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:wt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:Ct,session_id:i}}}async function Ne(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function _e(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=Tt(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),a=Q(i),s=i?.endpoint??G,d=JSON.stringify(o);if(H(i)){let p=q(i),m=await p.getToken(),f=await Ne(s,a,m,d,t.signal);if(f.status===401){let h=await p.getToken(!0);f=await Ne(s,a,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=W(i);!l&&!Re&&(Re=!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(n,e){let t=n,i={},r=[],o=[],a=0;for(let s of e){let d=(i[s.type]??0)+1;i[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(S=>h<S.end&&h+s.text.length>S.start);)h=t.indexOf(s.text,h+1);return h},m=p(a);if(m===-1&&(m=p(0)),m!==-1){t=t.slice(0,m)+c+t.slice(m+s.text.length);let f=c.length-s.text.length;for(let h of o)h.start>=m+s.text.length&&(h.start+=f,h.end+=f);o.push({start:m,end:m+c.length}),a=m>=a?m+c.length:a+f}r.push({...s,placeholder:c})}return{rawQuery:t,completedParams:r}}function O(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function V(n,e,t){return e===0&&n.length>0&&t.length>0&&t.toLowerCase().startsWith(n.toLowerCase())}function k(n,e,t){let i=n.slice(e);if(t||e===0||n[e-1]===" ")return i;let r=i.indexOf(" ");return r===-1?"":i.slice(r+1)}function Be(n,e){let t=n.trimEnd().replace(/\s+/g," ");if(t.length===0||e.length===0)return 0;let i=t.split(" "),r=e.toLowerCase();for(let o=0;o<i.length;o++){let a=i.slice(o).join(" ");if(r.startsWith(a.toLowerCase())){let s=t.length-a.length;return n.length-s}}return 0}function L(n,e){if(!n)return[];let t=e.trimStart();if(!t)return n;let i=t.toLowerCase();return n.filter(r=>!r.is_tappable||r.text.toLowerCase().includes(i))}function D(n,e){if(!n)return null;let t=e.trim();if(!t)return null;let i=t.toLowerCase();return n.find(r=>r.is_tappable&&r.text.toLowerCase()===i)??null}function He(n,e){return e?n.map(t=>{let i=e[t.type];if(!i)return t;let r=i("");return r?{...t,options:r}:t}):n}function Fe(n,e){let t=0,i=e;for(let r of n)t+=r.value.length,r.type!=="text"&&(i=Math.max(i,t));return i}function Ke(n,e){let t=0;for(let i of n){let r=t+i.value.length;if(i.type==="text"&&r>e&&i.value.slice(Math.max(e-t,0)).trim().length>0)return!1;t=r}return!0}function Ue(n,e){let t=[],i=new Set;for(let r of[...n,...e])r.type==="placeholder"||i.has(r.type)||(i.add(r.type),t.push({type:r.type,text:r.text}));return t}function $e(n,e,t){if(n===e)return t;let i=Math.min(n.length,e.length),r=0;for(;r<i&&n[r]===e[r];)r++;if(r>=t)return t;let o=0;for(;o<i-r&&n[n.length-1-o]===e[e.length-1-o];)o++;return n.length-o<=t?t+(e.length-n.length):null}function we(n,e){let t=[],i=[],r=0;for(let o of e){let a=n.indexOf(o.text,r);if(a===-1){i.push(o);continue}t.push({start:a,end:a+o.text.length,param:o}),r=a+o.text.length}return{located:t,missing:i}}function Ge(n,e,t){let i=[],r=[],o=0;for(let a of t){let s=n.indexOf(a.text,o);for(;s!==-1&&e.some(d=>s<d.end&&s+a.text.length>d.start);)s=n.indexOf(a.text,s+1);if(s===-1){r.push(a);continue}i.push({start:s,end:s+a.text.length,param:a}),o=s+a.text.length}return{located:i,missing:r}}function qe(n,e,t=[]){let i=we(n,e).located,r=Ge(n,i,t).located,o=[...i.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:n.slice(s,l.start)}),a.push(l.segment),s=l.end;let d=n.slice(s);return d&&a.push({type:"text",value:d}),a}function Qe(n,e){let{located:t,missing:i}=we(n,e);return{valid:t.map(r=>r.param),invalid:i}}function j(n,e,t){let i=we(n,e).located,{located:r,missing:o}=Ge(n,i,t);return{valid:r.map(a=>a.param),invalid:o}}function At(n){if(n instanceof Error)return n;try{return new Error(String(n))}catch{return new Error("Unknown error")}}var It=100,Ot=300,kt=2,X=class{constructor(e,t,i,r,o,a,s={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;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(i=>{(i.text!==e||i.completedParams!==t)&&(e=i.text,t=i.completedParams,this.scheduleFetch())})}dispose(){this.abortController?.abort(),this.clearTimers(),this.unsubscribe?.()}async doFetch(e,t){this.abortController?.abort();let i=new AbortController;this.abortController=i;let r=++this.fetchVersion,o=this.store.get().text.length;try{this.callbacks.onRequest?.({query:this.store.get().text,signal:i.signal,isCurrent:()=>r===this.fetchVersion})}catch{}try{this.store.set({isLoading:!0,error:null});let a=this.store.get(),s=a.pendingSpan?Ue(a.pendingSpan.snapshot,a.actionableSuggestions):void 0,d=await _e(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:a.identifiedParams,recentlySuggested:s,skippedParams:a.skippedParams});if(r!==this.fetchVersion)return;let l=(d.data.input??[]).filter(b=>b.source==="identified").map(b=>({id:crypto.randomUUID(),type:b.type,text:b.text})),c=He(d.data.suggestions??[],this.getOptionOverrides()),p=d.data.input??[],m=p[p.length-1],f=this.store.get().text,h,S;if(m?.state==="in_progress"){S=!0;let b=f.toLowerCase().lastIndexOf(m.text.toLowerCase());h=b!==-1?b:o}else S=!1,h=o;let g=c.filter(b=>b.type!=="placeholder")[0],u=null;if(g){let b=k(f,h,S),y=D(g.options,b);y&&(u={id:crypto.randomUUID(),placeholder:"",type:g.type,text:y.text,kind:y.kind,suggestionType:g.type,suggestionPlaceholder:g.text,options:g.options??[],metadata:y.metadata},c=c.filter(P=>P!==g),this.callbacks.onAutoMatch?.({active:g,matched:y,rawQuery:e}))}this.store.set(b=>{let y=u?[...b.completedParams,u]:b.completedParams,P=j(b.text,y,l).valid,E=new Set(a.skippedParams.map(w=>w.id)),U=new Set(b.skippedParams.filter(w=>!E.has(w.id)).map(w=>w.type));return{suggestions:U.size>0?c.filter(w=>w.type==="placeholder"||!U.has(w.type)):c,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:S,identifiedParams:P,...u?{completedParams:y}:{}}})}catch(a){let s=At(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=i=>{let r=this.store.get();if(!r.text&&r.completedParams.length===0)return this.doFetch("",[]),!0;let o=r.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),a=O(r.text,r.filterBase,o),s=k(r.text,a,r.filterInProgress),l=r.suggestions.filter(u=>u.type!=="placeholder")[0],p=(l?L(l.options,s):[]).filter(u=>u.is_tappable),m=l?D(l.options,s)!==null:!1,f=s.trim().length>0;if(p.length>0&&!m&&f||V(r.text,r.completedParams.length,o))return!1;let{rawQuery:h,completedParams:S}=v(r.text,r.completedParams),x=h.length<r.lastRawQuery.length,g=Math.abs(h.length-r.lastRawQuery.length);return x||g>=i?(this.doFetch(h,S),!0):!1};this.debounceTimer=setTimeout(()=>{t(kt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},It),this.slowDebounceTimer=setTimeout(()=>t(1),Ot)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Ve='[contenteditable="false"]',R;function Lt(){if(R!==void 0)return R;let n=globalThis.Intl.Segmenter;if(!n)return R=null,null;try{R=new n(void 0,{granularity:"grapheme"})}catch{R=null}return R??null}function z(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Ve))return!0;t=t.parentNode}return!1}function Y(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return z(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function F(n){let e=Y(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function J(n){let e=Y(n),t=0,i=e.nextNode();for(;i;)t+=i.data.length,i=e.nextNode();return t}function T(n){let e=(n.ownerDocument??document).getSelection();if(!e||e.rangeCount===0)return null;let t=e.anchorNode,i=e.anchorOffset;if(!t||!n.contains(t))return null;if(t.nodeType===Node.ELEMENT_NODE){let r=t;if(z(r,n)&&r!==n)return null;let o=0;for(let a=0;a<i&&a<r.childNodes.length;a++)o+=je(r.childNodes[a],n);return o+We(r,n)}return t.nodeType!==Node.TEXT_NODE||z(t,n)?null:We(t,n)+i}function je(n,e){if(n.nodeType===Node.TEXT_NODE)return z(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Ve))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=je(r,e);return i}function We(n,e){let t=Y(e),i=0,r=t.nextNode();for(;r;){if(r===n||n.nodeType===Node.ELEMENT_NODE&&n.contains(r))return i;i+=r.data.length,r=t.nextNode()}return i}function C(n,e){let t=n.ownerDocument??document,i=t.getSelection();if(!i)return;let r=Math.max(0,Math.min(e,J(n))),o=Y(n),a=0,s=null,d=0,l=o.nextNode(),c=null;for(;l;){let m=l.data.length;if(r<a+m){s=l,d=r-a;break}if(r===a+m){let f=o.nextNode();f?(s=f,d=0):(s=l,d=m);break}a+=m,c=l,l=o.nextNode()}let p=t.createRange();if(s){let m=s.parentElement?.closest('strong[data-seg="completed"]');m&&m!==n&&n.contains(m)?d===0?p.setStartBefore(m):d===s.data.length?p.setStartAfter(m):p.setStart(s,d):p.setStart(s,d)}else c?p.setStart(c,c.data.length):p.setStart(n,0);p.collapse(!0),i.removeAllRanges(),i.addRange(p)}function Z(n){let e=T(n);return e==null?!1:e>=J(n)}function ee(n,e){if(e<=0)return 0;let t=Lt();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:o}of t.segment(i))o<e&&(r=o);return r}function N(n,e,t=[]){let{rawQuery:i,completedParams:r}=v(n,e);return{query:n.trim(),raw_query:i,completed_params:M(r,t)}}function Ee(n,e){return n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?n.selectionStart!=null&&n.selectionStart===n.value.length:n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?Z(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function Te(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?T(n):null}var te=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,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=Ee(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),m=p<s.length-1?p+1:0;this.store.set({activeDropdownIndex:s[m]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let p=Ee(e.target,t),m=!!t.editingParam;if(!p&&!m)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}Ee(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.ctx.skipActivePill());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=Te(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=Te(e.target);l!=null&&this.ctx.startEditingParamAtCaret(l)&&e.preventDefault()}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=Te(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,i):a&&a(N(t.text,t.completedParams,t.skippedParams))&&this.ctx.afterSubmit?.();break}case"Tab":{let l=t.filteredOptions.map((m,f)=>m.is_tappable?f:-1).filter(m=>m!==-1);if(l.length===0)break;if(!t.isDropdownOpen){if(t.actionableSuggestions.length===0)break;e.preventDefault();let m=e.shiftKey?l[l.length-1]:l[0];this.store.set({pillTapped:!0,activeDropdownIndex:m});break}e.preventDefault();let c=l.indexOf(t.activeDropdownIndex),p;if(c<0)p=e.shiftKey?l.length-1:0;else{let m=e.shiftKey?-1:1;p=(c+m+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 i=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 i)r[o%e].push(o);return r.flat()}getEffectiveColumns(){let e=document.getElementById(this.ctx.listboxId);if(!e)return this.ctx.columns;let i=document.getElementById(`${this.ctx.listboxId}-option-0`)?.parentElement??null;for(;i;){let r=getComputedStyle(i).gridTemplateColumns;if(r&&r!=="none"){let o=r.split(" ").filter(Boolean).length;if(o>0)return o}if(i===e)break;i=i.parentElement}return this.ctx.columns}clickOrSelect(e,t,i){let r=document.getElementById(`${i}-option-${e}`);r?r.click():this.ctx.selectOption(t[e])}};var ne=class{constructor(e,t={}){this.store=e;this.callbacks=t}setActivePill(e){let t=this.store.get(),i=t.suggestions.filter(l=>l.type!=="placeholder");if(e<0||e>=i.length)return;let r=i[e],o=i.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 ie=class{constructor(e,t){this.store=e;this.getConfig=t;this.hasLoggedError=!1}async run(e,t,i){let r=this.getConfig();if(r){if(e.trim().length===0){this.clear(i);return}try{let o=await r.fetch(e,t);if(t.aborted||!i())return;let a=r.transform(o),s=Array.isArray(a)?a:[],d=r.limit!=null?s.slice(0,r.limit):s;if(t.aborted||!i())return;this.commit(d)}catch(o){if(t.aborted||Mt(o))return;this.logOnce(o),this.clear(i)}}}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 Mt(n){return n instanceof Error&&n.name==="AbortError"}var K="(max-width: 768px)";var Dt="var(--aia-option-row-height, 37px)",Rt="var(--aia-grid-scroll-top, 0px) + var(--aia-grid-scroll-bottom, 0px)";function re(n,e){let t=(i,r)=>({cols:i,rows:r,maxHeight:`calc(${r} * ${Dt} + ${Rt})`});return e?t(1,Math.min(n,5)):n>=5&&n<=6?t(2,Math.ceil(n/2)):t(1,Math.min(n,4))}function oe(n){return Array.from({length:n},()=>"minmax(0,1fr)").join(" ")}function se(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(K).matches}function Xe(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,a=n.filteredOptionsLength>0||n.activePillHasNoOptions||n.hasProducts;if(n.inEditMode){let s=i?n.isFocused:!0;return a&&s}if(t==="auto"){let s=i?n.isFocused:!0,d=n.text.replace(/\s+$/,"").length,l=n.caretOffset==null||n.caretOffset>=d;return(a||n.isLoading)&&s&&l}return t==="manual"?(a||n.isLoading)&&n.pillTapped:!1}function ze(n,e){let t=qe(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(u=>u.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,a=n.suggestions.filter(u=>u.type==="placeholder").map(u=>u.text).join(" "),s=O(n.text,Math.min(n.filterBase,n.text.length),a),l=s===0&&V(n.text,n.completedParams.length,a)?"":k(n.text,s,n.filterInProgress),c=r?o?o(l.trim())??r.options??[]:r.options??[]:[],p=n.editingParam!=null&&n.editingAnchor!=null,m;if(p&&n.editingParam&&n.editingAnchor!=null){let u=n.editingParam.id,b=n.completedParams.some(E=>E.id===u),y=n.caretOffset??n.editingAnchor,P=b?"":n.text.slice(n.editingAnchor,y);m=L(n.editingParam.options,P)}else m=L(c,l);let f=e.showNonTappableOptions===!1;f&&(m=m.filter(u=>u.is_tappable));let h=u=>f?u.is_tappable:!0,S;if(p){let u=n.editingParam?.options??[];S=n.editingParam!=null&&u.filter(h).length===0}else{let u=r?o?o("")??r.options??[]:r.options??[]:[];S=r!=null&&u.filter(h).length===0}let x=Xe({inEditMode:p,filteredOptionsLength:m.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:S,hasProducts:n.products.length>0},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),g=x&&n.activeDropdownIndex>=0&&!!m[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:m,placeholderText:a,isDropdownOpen:x,isActivePillSelected:g}}function ae(n){return n.mode==="fresh"?Nt(n):_t(n)}function Nt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,s=i.filter(y=>y.type!=="placeholder")[0];if(!s?.options)return null;let d=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),l=O(e,r,d),c=k(e,l,o),p=D(s.options,c);if(!p)return null;let m=p.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(m),h=f>=0?f:Math.max(0,e.length-p.text.length),S=h+p.text.length,x=e.slice(h,S),u=S<e.length&&e[S]===" "?S+1:S,b={id:crypto.randomUUID(),placeholder:"",type:s.type,text:x,kind:p.kind,suggestionType:s.type,suggestionPlaceholder:s.text,options:s.options??[],metadata:p.metadata};return{patch:{text:e,completedParams:[...t,b],suggestions:i.filter(y=>y!==s),filterBase:u,newParamId:b.id,caretOffset:u,activeDropdownIndex:-1},caretPos:u}}function _t(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(b=>b.id===i.id))return null;let a=e.slice(r,o),s=D(i.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,m=e.slice(c,p),h=p<e.length&&e[p]===" "?p+1:p,S={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:m,kind:s.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:s.metadata},x=t.length,g=0;for(let b=0;b<t.length;b++){let y=e.indexOf(t[b].text,g);if(y!==-1){if(y>=h){x=b;break}g=y+t[b].text.length}}let u=[...t];return u.splice(x,0,S),{patch:{text:e,completedParams:u,newParamId:S.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}function le(n,e,t){let i=n.slice(0,e),r=n.slice(t),o=(i===""||i.endsWith(" "))&&r.startsWith(" ");return o&&(r=r.slice(1)),{text:i+r,removed:t-e+(o?1:0)}}var de=class{constructor(e){this.deps=e}start(e){let t=this.deps.store.get();if(t.editingParam?.id===e)return;let i=t.completedParams.find(a=>a.id===e);if(!i)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:i,editingAnchor:o,editingTail:o+i.text.length,caretOffset:o+i.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(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null||!t.completedParams.some(d=>d.id===i.id))return!1;let{text:a}=e===""?le(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!==i.id),editingTail:s,caretOffset:s,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(s),this.tryPromote(),!0}caretAfterInput(e){let t=this.deps.store.get(),i={caretOffset:e};t.editingParam&&t.editingAnchor!=null&&e!=null&&(e<t.editingAnchor?(i.editingParam=null,i.editingAnchor=null,i.editingTail=null,i.activeDropdownIndex=-1):t.editingTail!=null&&(i.editingTail=Math.max(t.editingTail,e))),this.deps.store.set(i),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(),i=t.editingParam,r=t.editingAnchor,o=t.editingTail;if(!i||r==null||o==null)return;this.deps.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.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,m=r+c.length+(l?0:1),f={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:d,kind:e.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:e.metadata},h=t.completedParams.findIndex(g=>g.id===i.id),S=t.completedParams.filter(g=>g.id!==i.id),x=h>=0?Math.min(h,S.length):S.length;S.splice(x,0,f),this.deps.store.set({text:p,completedParams:S,newParamId:f.id,filterBase:m,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:m,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(m),this.deps.fetchNow()}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=ae({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 Ae="https://ai-autocomplete.com";function ce(n=Ae){try{if(typeof window>"u"||!window.location)return n;let e=window.location.hostname;if(!e)return n;let t=new URL(n);return t.searchParams.set("utm_source",e),t.toString()}catch{return n}}function pe(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Ye="data-aia-key";function _(n,e,t){let i=new Map;for(let a of Array.from(n.children)){let s=a.getAttribute(Ye);s!=null&&i.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=i.get(d);l||(l=t.create(s,a),l.setAttribute(Ye,d)),t.update?.(l,s,a),n.children[a]!==l&&n.insertBefore(l,n.children[a]??null),o.push(l)}for(let[a,s]of i)r.has(a)||s.remove();return o}var Je=[125,69];function Ze(n,e){return e?1:n===0?.7:n===1?.4:.2}function ue(n,e,t,i,r=!1,o=!1,a=!1){let s=n.querySelector(".magicx-aia-pill-list");if(s||(s=document.createElement("span"),s.className="magicx-aia-pill-list",n.appendChild(s)),o&&e.length===0){s.setAttribute("data-aia-pill-list-loading",""),s.innerHTML="";for(let d=0;d<Je.length;d++){let l=Je[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(Ze(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();_(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,m=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(Ze(c,m)),o?(p.setAttribute("data-aia-loading",""),p.disabled=!0,p.onclick=null):(p.removeAttribute("data-aia-loading"),p.disabled=!1,p.onclick=()=>i(c))}})}function Ie(n){n.querySelector(".magicx-aia-pill-list")?.remove()}var Bt="Products";function et(n,e,t,i,r){let o=n.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=Bt;let d=document.createElement("div");d.className="magicx-aia-products-row",d.setAttribute("data-aia-products-row",""),o.append(s,d),n.appendChild(o)}let a=o.querySelector(".magicx-aia-products-row");a&&_(a,e,{keyOf:s=>Ht(s),create:s=>Ft(s,i,r),update:(s,d,l)=>{s.id=`${t}-product-${l}`,s.dataset.aiaIndex=String(l)}})}function Oe(n,e){let t=n.querySelectorAll("[data-aia-product]");for(let i of t)i.tabIndex=e?0:-1}function Ht(n){return[n.id,n.title,n.url,n.imageUrl,n.price,n.vendor].map(e=>e??"").join("\0")}function Ft(n,e,t){let i=document.createElement("a");i.className="magicx-aia-product",i.setAttribute("data-aia-product",""),i.setAttribute("role","option"),i.setAttribute("aria-selected","false"),i.href=n.url,i.tabIndex=0;let r=document.createElement("span");if(r.className="magicx-aia-product-media",n.imageUrl){let s=document.createElement("img");s.className="magicx-aia-product-image",s.src=n.imageUrl,s.alt="",s.loading="lazy",s.decoding="async",r.appendChild(s)}else r.setAttribute("data-aia-product-placeholder","");i.appendChild(r);let o=document.createElement("span");if(o.className="magicx-aia-product-body",n.vendor){let s=document.createElement("span");s.className="magicx-aia-product-vendor",s.textContent=n.vendor,o.appendChild(s)}let a=document.createElement("span");if(a.className="magicx-aia-product-title",a.textContent=n.title,o.appendChild(a),n.price){let s=document.createElement("span");s.className="magicx-aia-product-price",s.textContent=n.price,o.appendChild(s)}return i.appendChild(o),i.addEventListener("click",s=>{s.metaKey||s.ctrlKey||s.shiftKey||s.altKey||s.button!==0||(s.preventDefault(),e(n))}),i.addEventListener("keydown",s=>{s.key!=="Enter"&&s.key!==" "||(s.preventDefault(),e(n))}),i.addEventListener("focus",()=>t(!0)),i.addEventListener("blur",s=>{s.relatedTarget?.closest("[data-aia-dropdown]")||t(!1)}),i}function Kt(n,e){let{cols:t,maxHeight:i}=re(e,se());n.style.gridTemplateColumns=oe(t),n.style.setProperty("--aia-grid-max-height",i)}function tt(n,e,t,i,r,o,a,s=""){let d=n.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"),n.appendChild(d)),Kt(d,e.length),$t(d,e,t,i,r,o,a),Ut(d,s)}function Ut(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function $t(n,e,t,i,r,o,a){let s=a?"1":"0";_(n,e,{keyOf:d=>`${d.text}\0${s}`,create:d=>Gt(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"),i(l),setTimeout(()=>d.classList.remove("magicx-aia-option--pressed"),500)},d.onmouseenter=()=>{let m=Number.parseInt(d.dataset.aiaIndex??"-1",10);m>=0&&r(m)}):(d.onclick=null,d.onmouseenter=null)}})}function Gt(n,e){let t=document.createElement("div");t.setAttribute("role","option"),t.setAttribute("data-aia-option",""),e&&t.setAttribute("data-aia-loading",""),t.tabIndex=e||!n.is_tappable?-1:0;let i=["magicx-aia-option"];n.is_tappable?i.push("magicx-aia-option--tappable"):i.push("magicx-aia-option--non-tappable"),t.className=i.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=n.icon?`${n.icon} ${n.text}`:n.text,a.appendChild(s),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,a.appendChild(d)}return t.appendChild(a),t}var qt=[159,119,164];function me(n){let e=document.createElement("div");return e.id=n,e.setAttribute("role","listbox"),e.setAttribute("data-aia-dropdown",""),e.className="magicx-aia-dropdown",e.addEventListener("mousedown",t=>t.preventDefault()),e}function ge(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:a,showPills:s,isActivePillSelected:d,onSelect:l,onHighlight:c,onPillClick:p,onSkip:m}=e,f=a.length>0,h=s&&f,S=t.length>0,x=e.products.length>0,g=r&&(S||h||o||x);if(g?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),o?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!g){Oe(n,!1);return}x?n.setAttribute("data-aia-has-products",""):n.removeAttribute("data-aia-has-products");let u=n.querySelector(".aia-stack");u||(u=document.createElement("div"),u.className="aia-stack",u.style.setProperty("--aia-stack-space","8px"),n.appendChild(u));let b=e.showSkipButton&&f&&!e.isInputEmpty,y=h||o&&s||b,P=u.querySelector(".magicx-aia-pill-bar");if(y){P||(P=document.createElement("div"),P.className="magicx-aia-pill-bar aia-cluster",P.setAttribute("data-nowrap",""),P.setAttribute("data-aia-pillbar",""),u.insertBefore(P,u.firstChild));let I=P.querySelector(".magicx-aia-pill-scroll");I||(I=document.createElement("span"),I.className="magicx-aia-pill-scroll",I.setAttribute("data-aia-pill-scroll",""),P.insertBefore(I,P.firstChild)),ue(I,s?a:[],0,p,!0,o&&s,d),Wt(P,b,o||e.skipDisabled,a[0],m)}else P&&P.remove();let E=e.suggestions[0],U=E?`${E.type} ${E.text}`:"";tt(u,t,i,l,c,e.listboxId,o,U);let A=u.querySelector(".magicx-aia-skeleton-bars");if(o&&!S){if(!A){A=document.createElement("div"),A.className="magicx-aia-skeleton-bars",A.setAttribute("data-aia-skeleton-bars","");for(let I of qt){let Pe=document.createElement("span");Pe.className="magicx-aia-skeleton-bar",Pe.style.width=`${I}px`,A.appendChild(Pe)}u.appendChild(A)}}else A&&A.remove();et(u,e.products,e.listboxId,e.onProductSelect,e.onProductFocusChange),Oe(n,!0);let w=u.querySelector(".magicx-aia-footer")??jt(),gt=i>=0&&!!t[i]?.is_tappable;Vt(w,pe(gt,e.isInputEmpty)),w.isConnected||u.appendChild(w),Qt(u,[".magicx-aia-pill-bar",".aia-grid",".magicx-aia-skeleton-bars",".magicx-aia-products",".magicx-aia-footer"])}function Qt(n,e){let t=e.map(i=>n.querySelector(`:scope > ${i}`)).filter(i=>i!==null);for(let i=0;i<t.length;i++)n.children[i]!==t[i]&&n.insertBefore(t[i],n.children[i]??null)}function Wt(n,e,t,i,r){let o=n.querySelector(".magicx-aia-skip");if(!e){o?.remove();return}o||(o=document.createElement("button"),o.type="button",o.tabIndex=-1,o.className="magicx-aia-skip",o.setAttribute("data-aia-skip",""),o.textContent="skip",o.addEventListener("mousedown",a=>a.preventDefault()),n.appendChild(o)),o.setAttribute("aria-label",i?`Skip ${i.text}`:"Skip"),o.disabled=t,o.onclick=t?null:()=>r()}function Vt(n,{key:e,hint:t}){let i=n.querySelector(".magicx-aia-footer-key"),r=n.querySelector(".magicx-aia-footer-hint");!i||!r||(i.textContent!==e&&(i.textContent=e),r.textContent!==t&&(r.textContent=t))}function jt(){let n=document.createElement("footer");n.className="magicx-aia-footer",n.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 i=document.createElement("kbd");i.className="magicx-aia-footer-key",i.textContent="tab";let r=document.createElement("span");r.className="magicx-aia-footer-hint",r.textContent="to select",t.append(i,r);let o=document.createElement("a");o.className="aia-cluster magicx-aia-footer-brand-link",o.setAttribute("data-align","center"),o.href=ce(),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),n.append(e),n}function nt(n,e){let t=me(e.listboxId);return n.appendChild(t),{dropdown:t}}function ke(n,e,t){ge(n.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,showSkipButton:t.showSkipButton&&!e.editingParam,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill,onSkip:t.skipActivePill,onProductSelect:t.selectProduct,onProductFocusChange:i=>t.store.set({isFocused:i})})}var Xt=6,zt=.3;function it(n){return n<=0?"0px":`${(-Math.min(zt,2*Xt/n)).toFixed(3)}px`}function fe(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:a}=n,s=t.length===0;e.dataset.aiaEmpty=s?"true":"false",s&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(x=>`${x.type}:${x.value}`).join("\0"),l=e.dataset.segKey??"",c=e.dataset.newParamId??"",p=e.dataset.editingParamId??"";if(d===l&&(i??"")===c&&(r??"")===p)return;let m=a?T(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),S=0;for(let x of t)if(S+=x.value.length,x.type==="completed"){let g=f.createElement("strong");g.dataset.seg="completed",g.dataset.paramId=x.param.id;let u=x.param.id===i,b=x.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];u&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),b&&y.push("magicx-aia-segment--editing"),g.className=y.join(" "),g.style.letterSpacing=it(x.value.length),g.textContent=x.value,h.appendChild(g)}else if(x.type==="identified"){let g=f.createElement("strong");g.dataset.seg="identified",g.dataset.paramId=x.param.id,g.className="magicx-aia-segment magicx-aia-segment--completed",g.style.letterSpacing=it(x.value.length),g.textContent=x.value,h.appendChild(g)}else h.appendChild(f.createTextNode(x.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(S),m!=null&&C(e,Math.max(0,Math.min(m,S)))}var Yt='<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 rt(){let n=document.createElement("button");return n.type="button",n.className="magicx-aia-submit",n.setAttribute("aria-label","Submit"),n.setAttribute("data-aia-submit",""),n.innerHTML=Yt,n}function Jt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function ot(n,e){let t=e.firstElementChild;if(!t){e.removeAttribute("data-aia-pill-wrapped");return}let i=t.getBoundingClientRect(),r=n.getBoundingClientRect();i.top>=r.bottom-2?e.setAttribute("data-aia-pill-wrapped",""):e.removeAttribute("data-aia-pill-wrapped")}function st(n,e){let{listboxId:t}=e,i=me(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.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",Jt()?"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=rt(),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,m=!1,f=0,h=()=>{let g=F(a),b=g.length>0&&g[0]!==g[0].toUpperCase()?g[0].toUpperCase()+g.slice(1):g;e.handleChange(b)},S=()=>{let g=(a.ownerDocument??document).getSelection();if(!g||g.rangeCount===0)return null;let u=g.anchorNode;return!u||!a.contains(u)?null:(u.nodeType===Node.ELEMENT_NODE?u:u.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",()=>{m||(f=performance.now(),h(),e.handleCaretAfterInput(T(a)))},{signal:p});let x=a.ownerDocument??document;if(x.addEventListener("selectionchange",()=>{let g=x.getSelection();if(!g||g.rangeCount===0||!a.contains(g.anchorNode))return;let u=g.isCollapsed?S():null,b=e.store.get().editingParam?.id??null;if(u&&u!==b){e.startEditingParam(u);return}performance.now()-f<50||e.handleCaretMove(T(a))},{signal:p}),a.addEventListener("compositionstart",()=>{m=!0},{signal:p}),a.addEventListener("compositionend",()=>{m=!1,h()},{signal:p}),a.addEventListener("beforeinput",g=>{let u=g,b=u.inputType;if(b==="insertParagraph"||b==="insertLineBreak"||b==="insertFromDrop"){g.preventDefault();return}if(b.startsWith("insert")||b.startsWith("delete")){let y=b.startsWith("delete")?"":u.data??"";e.replaceEditingRange(y)&&g.preventDefault()}},{signal:p}),a.addEventListener("paste",g=>{g.preventDefault();let u=(g.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!u)return;let b=a.ownerDocument??document,y=b.getSelection();if(!y||y.rangeCount===0)return;let P=y.getRangeAt(0);if(!a.contains(P.startContainer))return;P.deleteContents();let E=b.createTextNode(u);P.insertNode(E),P.setStartAfter(E),P.collapse(!0),y.removeAllRanges(),y.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 u=e.store.get();if(!(!!u.text||u.completedParams.length>0)||!e.onSubmit)return;g.stopPropagation(),e.onSubmit(N(u.text,u.completedParams,u.skippedParams))&&e.afterSubmit?.()},{signal:p}),e.autoFocus!==!1){a.focus();let g=a.ownerDocument??document,u=g.getSelection(),b=u&&u.rangeCount>0&&a.contains(u.anchorNode);if(u&&!b){let y=g.createRange();y.selectNodeContents(a),y.collapse(!0),u.removeAllRanges(),u.addRange(y)}}if(typeof ResizeObserver<"u"){let g=new ResizeObserver(()=>ot(a,s));g.observe(a),c.signal.addEventListener("abort",()=>g.disconnect(),{once:!0})}return{input:a,inlinePillContainer:s,dropdown:i,submitButton:d,abort:c}}function Le(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:a}=n,{pillPlacement:s,setActivePill:d,selectOption:l,store:c}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let p=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(p?i.setAttribute("aria-activedescendant",p):i.removeAttribute("aria-activedescendant"),a){let x=!!e.text||e.completedParams.length>0;a.disabled=!x}let m=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==m;if(fe({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),s==="inline"){let x=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;x||e.actionableSuggestions.length>0?ue(r,e.actionableSuggestions,0,d,!1,x,e.isActivePillSelected):Ie(r)}else Ie(r);ot(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&F(i)!==e.text&&C(i,e.text.length);let h=e.editingParam?{type:e.editingParam.suggestionType,text:e.editingParam.suggestionPlaceholder,required:!0,options:e.editingParam.options}:null,S=h??e.actionableSuggestions[0];ge(o,{suggestions:S?[{...S,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",showSkipButton:t.showSkipButton&&!e.editingParam,skipDisabled:e.inSelectionAnimation,isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,products:e.products,onSelect:l,onHighlight:x=>c.set({activeDropdownIndex:x}),onPillClick:d,onSkip:t.skipActivePill,onProductSelect:t.selectProduct,onProductFocusChange:x=>c.set({isFocused:x})})}function at(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),o=r.length===0&&n.text.length===0,a=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||a)&&n.placeholderText&&(r=`${n.placeholderText} `);let s=Be(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()),m=p>=0?c.slice(p,p+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:m,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:c,filterBase:c.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:c.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:!0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(S=>S.text!==e.text).map(S=>S.text)},consumedSuggestion:t,remainingActionable:h}}function he(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let a=typeof o=="function"?o(e):o,s=e;if(e={...e,...a},i.push([e,s]),!r){r=!0;try{let d=0;for(let l=i.shift();l;l=i.shift()){if(++d>1e4)throw i.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 m of t)m(c,p)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function lt(n,e){let t,i,r=o=>(o!==t&&(t=o,i=e(o)),i);return{get:()=>{let o=n.get();return{...o,...r(o)}},set:o=>{typeof o=="function"?n.set(a=>{let s={...a,...r(a)};return o(s)}):n.set(o)},peek:o=>{let a={...n.get(),...o};return{...a,...e(a)}},subscribe:o=>n.subscribe((a,s)=>{let d={...s,...r(s)},l={...a,...r(a)};o(l,d)})}}var Me=!1;function dt(){if(Me||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){Me=!0;return}Me=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Zt,document.head.appendChild(n)}var Zt=`@layer layout {
2
2
  .aia-stack {
3
3
  display: flex;
4
4
  flex-direction: column;
@@ -359,9 +359,72 @@
359
359
 
360
360
  /* --- Pill bar (inside dropdown) ---
361
361
  The dropdown container owns the 10px/8px edge padding and the 8px section
362
- gaps (matching Figma); the pill row itself adds none. */
362
+ gaps (matching Figma); the pill row itself adds none. The horizontal scroll
363
+ + fade live on the inner .magicx-aia-pill-scroll wrapper, NOT the bar: the
364
+ trailing skip button is the bar's other child, and a mask on the bar would
365
+ fade it out along with the overflowing pills it's meant to sit beside. */
363
366
  .magicx-aia-pill-bar {
364
367
  padding: 0;
368
+ overflow: hidden;
369
+ }
370
+
371
+ .magicx-aia-pill-scroll {
372
+ display: inline-flex;
373
+ align-items: center;
374
+ flex: 1 1 auto;
375
+ min-width: 0;
376
+ overflow-x: auto;
377
+ overflow-y: hidden;
378
+ scrollbar-width: none;
379
+ mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 48px), transparent 100%);
380
+ -webkit-mask-image: linear-gradient(to right, #000 0, #000 calc(100% - 48px), transparent 100%);
381
+ }
382
+
383
+ .magicx-aia-pill-scroll::-webkit-scrollbar {
384
+ display: none;
385
+ }
386
+
387
+ /* --- Skip button (trailing edge of the pill bar) ---
388
+ Dismisses the active pill \u2014 same action as pressing \u2192 at the end of the
389
+ input. The auto inline-start margin pushes it to the bar's far edge, so it
390
+ reads top-right below the input and bottom-right when optionsPosition is
391
+ "above" (the stack reverses, taking the bar with it). Typography follows the
392
+ footer hint (same quiet chrome register), not the pills \u2014 it must read as an
393
+ escape hatch, not another parameter. */
394
+ .magicx-aia-skip {
395
+ display: inline-flex;
396
+ align-items: center;
397
+ margin-inline-start: auto;
398
+ flex-shrink: 0;
399
+ padding: 5px 8px;
400
+ border: none;
401
+ /* Matches the completed-param chip radius, so the hover fill reads as a
402
+ soft rectangle rather than a capsule. */
403
+ border-radius: 6px;
404
+ background: transparent;
405
+ font-family: inherit;
406
+ font-size: var(--aia-skip-font-size, 10px);
407
+ line-height: 18px;
408
+ color: var(--aia-skip-color, var(--aia-footer-hint-color, #505050));
409
+ cursor: pointer;
410
+ white-space: nowrap;
411
+ transition:
412
+ color 150ms ease-out,
413
+ background-color 150ms ease-out;
414
+ }
415
+
416
+ .magicx-aia-skip:hover {
417
+ color: var(--aia-skip-color-hover, var(--aia-pill-color, var(--aia-color-text-muted, #c1c4cb)));
418
+ /* Same fill as a highlighted option row (--aia-option-bg), so the hover
419
+ reads with the dropdown's own hover language and stays visible on both
420
+ mode surfaces. */
421
+ background: var(--aia-skip-hover-bg, var(--aia-option-bg, transparent));
422
+ }
423
+
424
+ .magicx-aia-skip:disabled {
425
+ pointer-events: none;
426
+ cursor: default;
427
+ opacity: 0.5;
365
428
  }
366
429
 
367
430
  /* --- Fallback loading skeleton bars (only when no cached options) --- */
@@ -1445,5 +1508,5 @@
1445
1508
  animation-duration: 0s !important;
1446
1509
  transition-duration: 0s !important;
1447
1510
  }
1448
- `;var me=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var ge=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...a)=>t(...a);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var fe=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var R=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function zt(n){return(n??F).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Yt(n){return N(n)?`Bearer ${await K(n).getToken()}`:$(n)}async function st(n){try{let e=zt(n.apiConfig?.endpoint),t=U(n.apiConfig),i=await Yt(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var Jt="newParam",at="suggestionRemoval",Zt="selectionAnimation",en=650,tn=0;function nn(){return`:ac-${++tn}:`}var lt=500;function dt(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var he=class{constructor(e,t={}){this.inputStore=ue(dt());this._listboxId=nn();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new fe;this.boundary=new me;this.subscriberCount=0;this.emitter=new ge(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=rt(this.inputStore,i=>We(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new J(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new oe({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new Z(this.store,()=>this.opts.products),this.fetchController=new Q(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new Y(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),fetchNow:()=>this.fetchNow()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:a}=q(i.text,i.completedParams,i.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let a=o.anchor;if(i.text!==r.text){let d=Be(r.text,i.text,a);if(d===null){this.store.set({pendingSpan:null});return}a=d}i.text.slice(a).trim().length===0||_e(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(ot(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...dt(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:d,removed:l}=re(i,r,o);return this.store.set(c=>({text:d,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-l):c.filterBase,d.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=z(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(d=>({text:s,filterBase:Math.min(d.filterBase,s.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),C(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.handleChange(e)}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products;Object.assign(this.opts,e),"products"in e&&e.products!==t&&this.productsController.clearNow(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=it(t,e);if(i){if(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(at),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(at,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},lt)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(Zt,()=>this.store.set({inSelectionAnimation:!1}),lt)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");st({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new R(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),selectProduct:r=>this.selectProduct(r),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=nt(this.container,t);let i=()=>{this.domRefs&&Ie(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Ie(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),selectProduct:i=>this.selectProduct(i)};this.dropdownRefs=Je(this.container,e);let t=()=>{this.dropdownRefs&&Te(this.dropdownRefs,this.store.get(),e)};this.subscribeBatchedRender(t),this.subscribeViewportBreakpoint(t),Te(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(H),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(Jt,()=>this.store.set({newParamId:null}),en)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Ue(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=T(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Ne(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);A(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=v(e.text,e.completedParams);this.fetchController.doFetch(t,i)}maybePromoteExactMatch(e){let t=this.store.get(),i=ie({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,ModeController,OPTIONS_GRID_MOBILE_QUERY,SKIPPED_PARAM_TEXT,buildAttributionUrl,buildQuery,buildSubmitResult,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,isOptionsGridMobileViewport,optionsGridTemplateColumns,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset,withSkippedParams});
1511
+ `;var be=class{constructor(){this.reported=new Set}run(e,t){try{return t()}catch(i){this.report(e,i,e);return}}runListener(e,t,i=e){try{return t(),!0}catch(r){return this.report(e,r,i),!1}}report(e,t,i){this.reported.has(i)||(this.reported.add(i),console.error(`[AIAutocomplete] "${e}" threw. The error is contained \u2014 SDK state is unaffected. Later failures of "${e}" on this instance are not logged.`,t))}};var xe=class{constructor(e){this.boundary=e;this.listeners={};this.keys=new WeakMap;this.registrationCount=0}on(e,t){let i=`${String(e)}#${++this.registrationCount}`,r=(...a)=>t(...a);this.keys.set(r,i);let o=this.listeners[e];return o||(o=new Set,this.listeners[e]=o),o.add(r),()=>{this.listeners[e]?.delete(r)}}emit(e,...t){let i=this.listeners[e];if(!i)return!0;let r=!0;for(let o of i)this.boundary.runListener(String(e),()=>o(...t),this.keys.get(o)??String(e))||(r=!1);return r}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var Se=class{constructor(){this.timers=new Map}schedule(e,t,i){this.clear(e);let r=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,r)}clear(e){let t=this.timers.get(e);t!==void 0&&(clearTimeout(t),this.timers.delete(e))}clearAll(){for(let e of this.timers.values())clearTimeout(e);this.timers.clear()}};var B=class{constructor(e,t="auto",i){this.container=e;this.mode=t;this.onResolve=i;this.mediaQuery=null;this.onSystemChange=e=>{this.setResolved(e.matches?"dark":"light")};this.apply()}setMode(e){this.detachListener(),this.mode=e,this.apply()}destroy(){this.detachListener()}apply(){this.mode==="auto"?(this.mediaQuery??(this.mediaQuery=window.matchMedia("(prefers-color-scheme: dark)")),this.mediaQuery.addEventListener("change",this.onSystemChange),this.setResolved(this.mediaQuery.matches?"dark":"light")):this.setResolved(this.mode)}setResolved(e){this.container.dataset.mode=e,this.onResolve?.(e)}detachListener(){this.mediaQuery?.removeEventListener("change",this.onSystemChange)}};function en(n){return(n??G).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function tn(n){return H(n)?`Bearer ${await q(n).getToken()}`:W(n)}async function ct(n){try{let e=en(n.apiConfig?.endpoint),t=Q(n.apiConfig),i=await tn(n.apiConfig);i&&(t.Authorization=i);let r=JSON.stringify({source:n.source,session_id:n.sessionId,type:n.type,at:new Date().toISOString(),query_data:n.queryData});await fetch(e,{method:"POST",headers:t,body:r})}catch{}}var nn="newParam",pt="suggestionRemoval",rn="selectionAnimation",on=650,sn=0;function an(){return`:ac-${++sn}:`}var ut=500;function mt(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],products:[],activeDropdownIndex:-1,newParamId:null,isLoading:!1,isReady:!1,error:null,filterBase:0,filterInProgress:!1,pillTapped:!1,skipNextFetch:!1,lastRawQuery:"",isFocused:!1,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:null,inSelectionAnimation:!1}}var ye=class{constructor(e,t={}){this.inputStore=he(mt());this._listboxId=an();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new Se;this.boundary=new be;this.subscriberCount=0;this.emitter=new xe(this.boundary);this.sessionId=crypto.randomUUID();this.emitSubmit=e=>this.emitter.emit("submit",e);this.emitError=e=>this.emitter.emit("error",e);this.container=e,this.opts=t,this.renderMode=t.renderMode??"full",this.store=lt(this.inputStore,i=>ze(i,this.deriveOpts())),t.onSubmit&&this.emitter.on("submit",t.onSubmit),t.onError&&this.emitter.on("error",t.onError),t.onChange&&this.emitter.on("change",t.onChange),t.onParamsChange&&this.emitter.on("paramsChange",t.onParamsChange),t.onStateChange&&this.emitter.on("stateChange",t.onStateChange),t.onFocus&&this.emitter.on("focus",t.onFocus),t.onBlur&&this.emitter.on("blur",t.onBlur),t.onProductSelect&&this.emitter.on("productSelect",t.onProductSelect),t.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new ne(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new de({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer(),fetchNow:()=>this.fetchNow()}),this.productsController=new ie(this.store,()=>this.opts.products),this.fetchController=new X(this.store,()=>this.opts.apiConfig,()=>this.deriveOpts().optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onRequest:({query:i,signal:r,isCurrent:o})=>{this.productsController.run(i,r,o).catch(()=>{})},onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(a=>a.text!==r.text).map(a=>a.text)})}}),this.keyboardController=new te(this.store,{columns:t.columns??2,listboxId:this.listboxId,getOnSubmit:()=>this.emitter.hasListeners("submit")?this.emitSubmit:void 0,getOptionsPosition:()=>this.opts.optionsPosition??"below",afterSubmit:this.renderMode==="full"?()=>this.reset():void 0,selectOption:i=>this.selectOption(i),removeParamAtCaret:i=>this.removeParamAtCaret(i),startEditingParamAtCaret:i=>this.startEditingParamAtCaret(i),exitEditMode:()=>this.exitEditMode(),skipActivePill:()=>this.skipActivePill()}),this.unsubscribers.push(this.store.subscribe((i,r)=>{i.text!==r.text&&this.emitter.emit("change",i.text),i.completedParams!==r.completedParams&&this.emitter.emit("paramsChange",i.completedParams),i.isFocused!==r.isFocused&&(i.isFocused?this.emitter.emit("focus"):this.emitter.emit("blur")),this.emitter.emit("stateChange",i)})),this.unsubscribers.push(this.store.subscribe(()=>this.maybeExitReEditOnNoMatch())),this.unsubscribers.push(this.store.subscribe((i,r)=>{if(i.text===r.text&&i.completedParams===r.completedParams||i.identifiedParams.length===0)return;let{valid:o,invalid:a}=j(i.text,i.completedParams,i.identifiedParams);a.length>0&&this.store.set({identifiedParams:o})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let o=i.pendingSpan;if(!o||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let a=o.anchor;if(i.text!==r.text){let d=$e(r.text,i.text,a);if(d===null){this.store.set({pendingSpan:null});return}a=d}i.text.slice(a).trim().length===0||Ke(i.segments,a)?this.store.set({pendingSpan:null}):a!==o.anchor&&this.store.set({pendingSpan:{anchor:a,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(dt(),this.setupContainer()),this.renderMode==="full"?this.buildAndRenderFull():this.renderMode==="dropdown"&&this.buildAndRenderDropdown(),this.fetchController.start()}focus(){this.domRefs?.input.focus()}blur(){this.domRefs?.input.blur()}reset(){let e=this.store.get().isFocused;this.store.set({...mt(),isFocused:e,skipNextFetch:!0}),this.sessionId=crypto.randomUUID(),this.fetchController.doFetch("",[])}destroy(){this.fetchController.dispose(),this.modeController?.destroy(),this.timers.clearAll(),this.emitter.clear();for(let e of this.unsubscribers)e();this.unsubscribers=[],this.domRefs?.abort.abort(),this.domRefs=null,this.dropdownRefs=null,this.renderMode!=="headless"&&(this.container.innerHTML="")}setMode(e){this.modeController?.setMode(e)}setValue(e){this.store.set({text:e})}setCompletedParams(e){this.store.set({completedParams:e})}setActivePill(e){this.pillsController.setActivePill(e);let t=this.store.get().text.length;this.store.set({caretOffset:t,isFocused:!0}),this.scheduleSetCursor(t)}removeLastParam(){this.pillsController.removeLastParam()}findChipSpanAt(e){let t=0;for(let i of this.store.get().segments){let r=t;if(t+=i.value.length,i.type!=="text"&&e>r&&e<=t)return{kind:i.type,param:i.param,start:r,end:t}}return null}withoutChip(e,t){return t.kind==="completed"?{completedParams:e.completedParams.filter(i=>i.id!==t.param.id)}:{identifiedParams:e.identifiedParams.filter(i=>i.id!==t.param.id)}}removeParamAtCaret(e){let t=this.findChipSpanAt(e);if(!t)return!1;let{text:i}=this.store.get(),{start:r,end:o}=t;if(e===o){let{text:d,removed:l}=le(i,r,o);return this.store.set(c=>({text:d,filterBase:Math.min(c.filterBase>r?Math.max(r,c.filterBase-l):c.filterBase,d.length),...this.withoutChip(c,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(r),!0}let a=ee(i,e),s=i.slice(0,a)+i.slice(e);return this.store.set(d=>({text:s,filterBase:Math.min(d.filterBase,s.length),...this.withoutChip(d,t),pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(a),!0}startEditingParamAtCaret(e){let t=this.findChipSpanAt(e);return!t||t.kind!=="completed"||t.end!==e?!1:(this.reEdit.start(t.param.id),this.store.get().editingParam?.id===t.param.id)}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;if(t)t.input.focus(),C(t.input,e);else{let i=this.opts.setCursor;i&&this.boundary.runListener("setCursor",()=>i(e))}})}clearNewParamId(){this.store.set({newParamId:null})}startEditingParam(e){this.reEdit.start(e)}replaceEditingRange(e){return this.reEdit.replaceRange(e)}exitEditMode(){this.reEdit.exit()}handleCaretAfterInput(e){this.reEdit.caretAfterInput(e)}handleCaretMove(e){this.reEdit.caretMove(e)}setActiveDropdownIndex(e){this.store.set({activeDropdownIndex:e})}selectProduct(e){this.emitter.emit("productSelect",e)}handleTextChange(e){this.handleChange(e)}skipActivePill(){let e=this.store.get();if(e.editingParam||e.inSelectionAnimation)return;let t=e.suggestions.filter(s=>s.type==="placeholder"),i=e.suggestions.filter(s=>s.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.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.fetchNow()}handleKeyDown(e){this.keyboardController.handleKeyDown(e)}setFocused(e){this.store.get().isFocused!==e&&this.store.set({isFocused:e})}subscribe(e){let t=`subscribe#${++this.subscriberCount}`;return this.store.subscribe(i=>{this.boundary.runListener("subscribe",()=>e(i),t)})}getState(){return this.store.get()}get listboxId(){return this._listboxId}get isReady(){return this.store.get().isReady}on(e,t){return this.emitter.on(e,t)}update(e){let t=this.opts.products;Object.assign(this.opts,e),"products"in e&&e.products!==t&&this.productsController.clearNow(),e.mode!==void 0&&this.modeController?.setMode(e.mode),e.optionsPosition!==void 0&&(this.container.dataset.optionsPosition=e.optionsPosition),e.animations!==void 0&&(this.container.dataset.animations=e.animations?"on":"off"),e.pillPlacement!==void 0&&(this.container.dataset.pillPlacement=e.pillPlacement,this.store.set({})),(e.dropdownTrigger!==void 0||e.closeDropdownOnBlur!==void 0||e.showNonTappableOptions!==void 0||e.showSkipButton!==void 0)&&this.store.set({}),e.value!==void 0&&this.store.set({text:e.value}),e.completedParams!==void 0&&this.store.set({completedParams:e.completedParams})}selectOption(e){let t=this.store.get();if(t.editingParam&&t.editingAnchor!=null&&t.editingTail!=null){this.reEdit.selectOption(e);return}let i=at(t,e);if(i){if(this.fireTelemetry("option",{raw_query:v(t.text,t.completedParams).rawQuery,selected_option:i.telemetry.selectedOption,other_options:i.telemetry.otherOptions}),this.store.set(i.patch),this.startSelectionAnimationTimer(),this.timers.clear(pt),i.remainingActionable>0){let r=i.consumedSuggestion;this.timers.schedule(pt,()=>{this.store.get().suggestions.includes(r)&&this.store.set(o=>({suggestions:o.suggestions.filter(a=>a!==r)}))},ut)}this.fetchNow()}}startSelectionAnimationTimer(){this.timers.schedule(rn,()=>this.store.set({inSelectionAnimation:!1}),ut)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");ct({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}deriveOpts(){let e=this.opts.optionOverrides;if(!e)return this.opts;if(e!==this.rawOverrides){this.rawOverrides=e;let t={};for(let[i,r]of Object.entries(e))t[i]=o=>this.boundary.run(`optionOverrides.${i}`,()=>r(o));this.wrappedOverrides=t}return{...this.opts,optionOverrides:this.wrappedOverrides}}setupContainer(){this.container.classList.add("magicx-aia"),this.container.dataset.pillPlacement=this.renderMode==="dropdown"?"dropdown":this.opts.pillPlacement??"dropdown",this.container.dataset.optionsPosition=this.opts.optionsPosition??"below",this.container.dataset.animations=this.opts.animations??!0?"on":"off",this.modeController=new B(this.container,this.opts.mode??"auto")}buildAndRenderFull(){let e=this,t={store:this.store,listboxId:this.listboxId,get pillPlacement(){return e.opts.pillPlacement??"dropdown"},get showSkipButton(){return e.opts.showSkipButton??!0},get onSubmit(){return e.emitter.hasListeners("submit")?e.emitSubmit:void 0},afterSubmit:()=>e.reset(),submitButton:this.opts.submitButton,autoFocus:this.opts.autoFocus??!0,selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r),handleKeyDown:r=>this.keyboardController.handleKeyDown(r),handleChange:r=>this.handleChange(r),startEditingParam:r=>this.startEditingParam(r),handleCaretAfterInput:r=>this.handleCaretAfterInput(r),handleCaretMove:r=>this.handleCaretMove(r),replaceEditingRange:r=>this.replaceEditingRange(r)};this.domRefs=st(this.container,t);let i=()=>{this.domRefs&&Le(this.domRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),Le(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e=this,t={store:this.store,listboxId:this.listboxId,get showSkipButton(){return e.opts.showSkipButton??!0},selectOption:r=>this.selectOption(r),setActivePill:r=>this.pillsController.setActivePill(r),skipActivePill:()=>this.skipActivePill(),selectProduct:r=>this.selectProduct(r)};this.dropdownRefs=nt(this.container,t);let i=()=>{this.dropdownRefs&&ke(this.dropdownRefs,this.store.get(),t)};this.subscribeBatchedRender(i),this.subscribeViewportBreakpoint(i),ke(this.dropdownRefs,this.store.get(),t),this.subscribeNewParamTimer()}subscribeViewportBreakpoint(e){if(typeof window>"u"||typeof window.matchMedia!="function")return;let t=window.matchMedia(K),i=()=>e();t.addEventListener("change",i),this.unsubscribers.push(()=>t.removeEventListener("change",i))}subscribeBatchedRender(e){let t=!1;this.unsubscribers.push(this.store.subscribe(()=>{t||(t=!0,queueMicrotask(()=>{t=!1,e()}))}))}subscribeNewParamTimer(){this.unsubscribers.push(this.store.subscribe((e,t)=>{e.newParamId&&e.newParamId!==t.newParamId&&this.timers.schedule(nn,()=>this.store.set({newParamId:null}),on)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Qe(e,t.completedParams);r.length>0&&this.store.set({completedParams:i}),this.maybePromoteExactMatch(e),this.maybeOpenPendingSpan()}maybeOpenPendingSpan(){let e=this.store.get();if(e.pendingSpan||e.actionableSuggestions.length===0)return;let t=O(e.text,Math.min(e.filterBase,e.text.length),e.placeholderText),i=Fe(e.segments,t);e.text.slice(i).trim().length!==0&&this.store.set({pendingSpan:{anchor:i,snapshot:e.actionableSuggestions}})}maybeExitReEditOnNoMatch(){let e=this.store.get();if(!e.editingParam||e.editingAnchor==null||e.completedParams.some(o=>o.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);L(e.editingParam.options,i).some(o=>o.is_tappable)||(this.reEdit.exit(),this.fetchNow())}fetchNow(){let e=this.store.get(),{rawQuery:t,completedParams:i}=v(e.text,e.completedParams);this.fetchController.doFetch(t,i)}maybePromoteExactMatch(e){let t=this.store.get(),i=ae({mode:"fresh",text:e,completedParams:t.completedParams,suggestions:t.suggestions,filterBase:t.filterBase,filterInProgress:t.filterInProgress});i&&this.store.set(i.patch)}};0&&(module.exports={AIAutocomplete,ATTRIBUTION_URL,ModeController,OPTIONS_GRID_MOBILE_QUERY,SKIPPED_PARAM_TEXT,buildAttributionUrl,buildQuery,buildSubmitResult,computeOptionsGridLayout,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,isOptionsGridMobileViewport,optionsGridTemplateColumns,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset,withSkippedParams});
1449
1512
  //# sourceMappingURL=index.js.map