@magicx-eng/ai-autocomplete-vanilla 0.6.0 → 0.7.0
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 +13 -1
- package/dist/index.d.mts +68 -1
- package/dist/index.d.ts +68 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -323,7 +323,19 @@ The object passed to `onSubmit`:
|
|
|
323
323
|
|---|---|---|
|
|
324
324
|
| `query` | `string` | Plain text as the user sees it. |
|
|
325
325
|
| `raw_query` | `string` | Text with placeholder tokens (e.g. `"Create a {{TASK_1}}"`). |
|
|
326
|
-
| `completed_params` | `CompletedParam[]` | Array of filled parameter values. |
|
|
326
|
+
| `completed_params` | `CompletedParam[]` | Array of filled parameter values, followed by any the user skipped (see below). |
|
|
327
|
+
|
|
328
|
+
#### Skipped parameters
|
|
329
|
+
|
|
330
|
+
Pressing <kbd>→</kbd> at the end of the input dismisses the active pill. The dismissal is reported to the server — and included in `completed_params` here — as an entry with no placeholder and the sentinel text `"skipped"`:
|
|
331
|
+
|
|
332
|
+
```ts
|
|
333
|
+
{ placeholder: "", type: "goal", text: "skipped", kind: null }
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Skipped entries are appended after the filled params (they have no position in the query) and are deduped by type. A skip is dropped if a param of the same type ends up filled anyway. Skipping the last available pill triggers an immediate request so the server can suggest something else; earlier skips ride along on the next request. `reset()` clears them.
|
|
337
|
+
|
|
338
|
+
> **Reading `state.skippedParams` directly:** the array is append-only until `reset()`. The "drop a skip whose type got filled" rule is applied when the payload is built, not by pruning the array — so if the user skips `goal` and later fills one, the raw array still holds the `goal` entry. That's deliberate: the filter self-heals if they then delete that param's text, where pruning would discard the signal for good. Apply the same rule yourself with the exported `withSkippedParams(completedParams, skippedParams)`.
|
|
327
339
|
|
|
328
340
|
### Event Subscription
|
|
329
341
|
|
package/dist/index.d.mts
CHANGED
|
@@ -78,6 +78,30 @@ interface CompletedParamState extends CompletedParam {
|
|
|
78
78
|
options: SuggestionOption[];
|
|
79
79
|
metadata?: Record<string, unknown>;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* A suggestion the user dismissed with the skip key (→) instead of filling.
|
|
83
|
+
*
|
|
84
|
+
* Client-only bookkeeping. A skipped suggestion has no text in the input, so
|
|
85
|
+
* it can't live in `completedParams` — that array is reconciled against the
|
|
86
|
+
* input on every keystroke and anything missing from the text is dropped.
|
|
87
|
+
* Skipped entries are folded into the wire `completed_params` array (with
|
|
88
|
+
* `text: "skipped"`, no placeholder) only when a request or a submit result is
|
|
89
|
+
* built. See `withSkippedParams`.
|
|
90
|
+
*
|
|
91
|
+
* The array is append-only until `reset()` — a skip is filtered out at
|
|
92
|
+
* build time when a param of its type ended up filled, not pruned here.
|
|
93
|
+
* That's deliberate: the filter self-heals if the user later deletes that
|
|
94
|
+
* param's text (the skip reappears in the payload), where pruning would have
|
|
95
|
+
* discarded the signal permanently. Consumers reading this array directly
|
|
96
|
+
* should apply the same filter — `withSkippedParams` is exported for it.
|
|
97
|
+
*/
|
|
98
|
+
interface SkippedParamState {
|
|
99
|
+
id: string;
|
|
100
|
+
/** The skipped suggestion's `type` (e.g. "goal"). */
|
|
101
|
+
type: string;
|
|
102
|
+
/** The suggestion's display text at skip time. Introspection only — never sent. */
|
|
103
|
+
suggestionPlaceholder: string;
|
|
104
|
+
}
|
|
81
105
|
/**
|
|
82
106
|
* Client-side state for an LLM-identified param. Tentative — replaced
|
|
83
107
|
* wholesale from each response (latest wins) and dropped when its text no
|
|
@@ -142,6 +166,15 @@ interface CoreInputState {
|
|
|
142
166
|
* override or overlap completed params.
|
|
143
167
|
*/
|
|
144
168
|
identifiedParams: IdentifiedParamState[];
|
|
169
|
+
/**
|
|
170
|
+
* Suggestions the user dismissed with the skip key (→). Held apart from
|
|
171
|
+
* `completedParams` because they have no text in the input; folded into the
|
|
172
|
+
* wire `completed_params` array (as `text: "skipped"`) on every request and
|
|
173
|
+
* on the submit result. Append-only until `reset()` — see
|
|
174
|
+
* {@link SkippedParamState} for why skips of a since-filled type are
|
|
175
|
+
* filtered at build time rather than pruned here.
|
|
176
|
+
*/
|
|
177
|
+
skippedParams: SkippedParamState[];
|
|
145
178
|
/**
|
|
146
179
|
* Open while the user has unresolved trailing text: anchored at the covered
|
|
147
180
|
* offset where they started typing, snapshotting the actionable suggestions
|
|
@@ -393,6 +426,8 @@ declare class AIAutocomplete {
|
|
|
393
426
|
* subscription early-returns on subsequent fires.
|
|
394
427
|
*/
|
|
395
428
|
private maybeExitReEditOnNoMatch;
|
|
429
|
+
/** Fire an immediate (undebounced) fetch for the current text + params. */
|
|
430
|
+
private fetchNow;
|
|
396
431
|
/**
|
|
397
432
|
* When the user has typed text that exactly matches (case-insensitive) one
|
|
398
433
|
* of the active suggestion's options, promote it to a completed param right
|
|
@@ -536,4 +571,36 @@ declare class ModeController {
|
|
|
536
571
|
private detachListener;
|
|
537
572
|
}
|
|
538
573
|
|
|
539
|
-
|
|
574
|
+
/**
|
|
575
|
+
* Sentinel `text` marking a `completed_params` entry the user skipped (→)
|
|
576
|
+
* rather than filled. Sent regardless of `maskCompletedText` — it's a fixed
|
|
577
|
+
* marker, never user-entered content.
|
|
578
|
+
*/
|
|
579
|
+
declare const SKIPPED_PARAM_TEXT = "skipped";
|
|
580
|
+
/**
|
|
581
|
+
* Folds skipped suggestions into a wire `completed_params` array so the server
|
|
582
|
+
* learns which parameters the user dismissed and can stop re-suggesting them.
|
|
583
|
+
*
|
|
584
|
+
* Skipped entries carry no placeholder: nothing was substituted into
|
|
585
|
+
* `raw_query`, so a `{{TYPE_N}}` token would point at text that doesn't exist.
|
|
586
|
+
* They're appended after the real params for the same reason — they have no
|
|
587
|
+
* position in the query.
|
|
588
|
+
*
|
|
589
|
+
* A skip is dropped when a param of the same type ends up filled anyway (the
|
|
590
|
+
* user skipped `goal`, then typed one): sending both would tell the server the
|
|
591
|
+
* parameter is simultaneously answered and declined.
|
|
592
|
+
*/
|
|
593
|
+
declare function withSkippedParams(completed: CompletedParam[], skipped: SkippedParamState[]): CompletedParam[];
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Builds the `AutocompleteResult` handed to `onSubmit`: the placeholder-
|
|
597
|
+
* tokenized raw query plus the completed params, with skipped suggestions
|
|
598
|
+
* folded in (see {@link withSkippedParams}).
|
|
599
|
+
*
|
|
600
|
+
* Shared by every submit path — vanilla Enter / submit button, the React Tier 1
|
|
601
|
+
* component, the Angular Tier 1 component — so they can't drift on what a
|
|
602
|
+
* result contains.
|
|
603
|
+
*/
|
|
604
|
+
declare function buildSubmitResult(text: string, completedParams: CompletedParamState[], skippedParams?: SkippedParamState[]): AutocompleteResult;
|
|
605
|
+
|
|
606
|
+
export { AIAutocomplete, type APIConfig, type APIKeyConfig, ATTRIBUTION_URL, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteRequest, type AutocompleteResponse, type AutocompleteResult, type CompletedParam, type CompletedParamState, type CoreOptions, type CoreState, type IdentifiedParam, type IdentifiedParamState, type InputItem, ModeController, type OptionOverrides, type RecentlySuggested, type RenderMode, SKIPPED_PARAM_TEXT, type Segment, type SkippedParamState, type Store, type Suggestion, type SuggestionOption, type TaskKind, buildAttributionUrl, buildQuery, buildSubmitResult, createStore, cursorIsAtEnd, extractPlainText, getCursorOffset, getFooterHint, plainTextLength, previousGraphemeBoundary, renderEditableContent, setCursorOffset, withSkippedParams };
|
package/dist/index.d.ts
CHANGED
|
@@ -78,6 +78,30 @@ interface CompletedParamState extends CompletedParam {
|
|
|
78
78
|
options: SuggestionOption[];
|
|
79
79
|
metadata?: Record<string, unknown>;
|
|
80
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* A suggestion the user dismissed with the skip key (→) instead of filling.
|
|
83
|
+
*
|
|
84
|
+
* Client-only bookkeeping. A skipped suggestion has no text in the input, so
|
|
85
|
+
* it can't live in `completedParams` — that array is reconciled against the
|
|
86
|
+
* input on every keystroke and anything missing from the text is dropped.
|
|
87
|
+
* Skipped entries are folded into the wire `completed_params` array (with
|
|
88
|
+
* `text: "skipped"`, no placeholder) only when a request or a submit result is
|
|
89
|
+
* built. See `withSkippedParams`.
|
|
90
|
+
*
|
|
91
|
+
* The array is append-only until `reset()` — a skip is filtered out at
|
|
92
|
+
* build time when a param of its type ended up filled, not pruned here.
|
|
93
|
+
* That's deliberate: the filter self-heals if the user later deletes that
|
|
94
|
+
* param's text (the skip reappears in the payload), where pruning would have
|
|
95
|
+
* discarded the signal permanently. Consumers reading this array directly
|
|
96
|
+
* should apply the same filter — `withSkippedParams` is exported for it.
|
|
97
|
+
*/
|
|
98
|
+
interface SkippedParamState {
|
|
99
|
+
id: string;
|
|
100
|
+
/** The skipped suggestion's `type` (e.g. "goal"). */
|
|
101
|
+
type: string;
|
|
102
|
+
/** The suggestion's display text at skip time. Introspection only — never sent. */
|
|
103
|
+
suggestionPlaceholder: string;
|
|
104
|
+
}
|
|
81
105
|
/**
|
|
82
106
|
* Client-side state for an LLM-identified param. Tentative — replaced
|
|
83
107
|
* wholesale from each response (latest wins) and dropped when its text no
|
|
@@ -142,6 +166,15 @@ interface CoreInputState {
|
|
|
142
166
|
* override or overlap completed params.
|
|
143
167
|
*/
|
|
144
168
|
identifiedParams: IdentifiedParamState[];
|
|
169
|
+
/**
|
|
170
|
+
* Suggestions the user dismissed with the skip key (→). Held apart from
|
|
171
|
+
* `completedParams` because they have no text in the input; folded into the
|
|
172
|
+
* wire `completed_params` array (as `text: "skipped"`) on every request and
|
|
173
|
+
* on the submit result. Append-only until `reset()` — see
|
|
174
|
+
* {@link SkippedParamState} for why skips of a since-filled type are
|
|
175
|
+
* filtered at build time rather than pruned here.
|
|
176
|
+
*/
|
|
177
|
+
skippedParams: SkippedParamState[];
|
|
145
178
|
/**
|
|
146
179
|
* Open while the user has unresolved trailing text: anchored at the covered
|
|
147
180
|
* offset where they started typing, snapshotting the actionable suggestions
|
|
@@ -393,6 +426,8 @@ declare class AIAutocomplete {
|
|
|
393
426
|
* subscription early-returns on subsequent fires.
|
|
394
427
|
*/
|
|
395
428
|
private maybeExitReEditOnNoMatch;
|
|
429
|
+
/** Fire an immediate (undebounced) fetch for the current text + params. */
|
|
430
|
+
private fetchNow;
|
|
396
431
|
/**
|
|
397
432
|
* When the user has typed text that exactly matches (case-insensitive) one
|
|
398
433
|
* of the active suggestion's options, promote it to a completed param right
|
|
@@ -536,4 +571,36 @@ declare class ModeController {
|
|
|
536
571
|
private detachListener;
|
|
537
572
|
}
|
|
538
573
|
|
|
539
|
-
|
|
574
|
+
/**
|
|
575
|
+
* Sentinel `text` marking a `completed_params` entry the user skipped (→)
|
|
576
|
+
* rather than filled. Sent regardless of `maskCompletedText` — it's a fixed
|
|
577
|
+
* marker, never user-entered content.
|
|
578
|
+
*/
|
|
579
|
+
declare const SKIPPED_PARAM_TEXT = "skipped";
|
|
580
|
+
/**
|
|
581
|
+
* Folds skipped suggestions into a wire `completed_params` array so the server
|
|
582
|
+
* learns which parameters the user dismissed and can stop re-suggesting them.
|
|
583
|
+
*
|
|
584
|
+
* Skipped entries carry no placeholder: nothing was substituted into
|
|
585
|
+
* `raw_query`, so a `{{TYPE_N}}` token would point at text that doesn't exist.
|
|
586
|
+
* They're appended after the real params for the same reason — they have no
|
|
587
|
+
* position in the query.
|
|
588
|
+
*
|
|
589
|
+
* A skip is dropped when a param of the same type ends up filled anyway (the
|
|
590
|
+
* user skipped `goal`, then typed one): sending both would tell the server the
|
|
591
|
+
* parameter is simultaneously answered and declined.
|
|
592
|
+
*/
|
|
593
|
+
declare function withSkippedParams(completed: CompletedParam[], skipped: SkippedParamState[]): CompletedParam[];
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* Builds the `AutocompleteResult` handed to `onSubmit`: the placeholder-
|
|
597
|
+
* tokenized raw query plus the completed params, with skipped suggestions
|
|
598
|
+
* folded in (see {@link withSkippedParams}).
|
|
599
|
+
*
|
|
600
|
+
* Shared by every submit path — vanilla Enter / submit button, the React Tier 1
|
|
601
|
+
* component, the Angular Tier 1 component — so they can't drift on what a
|
|
602
|
+
* result contains.
|
|
603
|
+
*/
|
|
604
|
+
declare function buildSubmitResult(text: string, completedParams: CompletedParamState[], skippedParams?: SkippedParamState[]): AutocompleteResult;
|
|
605
|
+
|
|
606
|
+
export { AIAutocomplete, type APIConfig, type APIKeyConfig, ATTRIBUTION_URL, type AccessTokenConfig, type AccessTokenResult, type AppearanceMode, type AutocompleteRequest, type AutocompleteResponse, type AutocompleteResult, type CompletedParam, type CompletedParamState, type CoreOptions, type CoreState, type IdentifiedParam, type IdentifiedParamState, type InputItem, ModeController, type OptionOverrides, type RecentlySuggested, type RenderMode, SKIPPED_PARAM_TEXT, type Segment, type SkippedParamState, type Store, type Suggestion, type SuggestionOption, type TaskKind, buildAttributionUrl, buildQuery, buildSubmitResult, createStore, cursorIsAtEnd, extractPlainText, getCursorOffset, getFooterHint, plainTextLength, previousGraphemeBoundary, renderEditableContent, setCursorOffset, withSkippedParams };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var le=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Je=Object.prototype.hasOwnProperty;var Ze=(n,e)=>{for(var t in e)le(n,t,{get:e[t],enumerable:!0})},et=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ye(e))!Je.call(n,r)&&r!==t&&le(n,r,{get:()=>e[r],enumerable:!(i=Xe(e,r))||i.enumerable});return n};var tt=n=>et(le({},"__esModule",{value:!0}),n);var Mt={};Ze(Mt,{AIAutocomplete:()=>se,ATTRIBUTION_URL:()=>pe,ModeController:()=>M,buildAttributionUrl:()=>X,buildQuery:()=>P,createStore:()=>ie,cursorIsAtEnd:()=>q,extractPlainText:()=>L,getCursorOffset:()=>w,getFooterHint:()=>Y,plainTextLength:()=>Q,previousGraphemeBoundary:()=>G,renderEditableContent:()=>ne,setCursorOffset:()=>C});module.exports=tt(Mt);var R=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 nt="https://api.ai-autocomplete.com",N=`${nt}/api/suggest`,he=new WeakMap;function k(n){return n?.type==="accessToken"}function it(n){if(!(!n||k(n)))return n}function _(n){let e=he.get(n.getAccessToken);return e||(e=new R(n),he.set(n.getAccessToken,e)),e}function F(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function H(n){let e=it(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var rt="0.6.0",be=!1;function ot(){return crypto.randomUUID()}function st(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function at(n,e,t,i,r,s){let o=e.find(d=>d.type==="contact"&&d.metadata?.contact_account_count)?.metadata?.contact_account_count,a=typeof o=="number"?o:void 0;return{data:{raw_query:n,completed_params:e.map(d=>st(d,t)),...r&&r.length>0&&{identified_params:r.map(d=>({type:d.type,value:d.text}))},...s&&s.length>0&&{recently_suggested:s},...a!=null&&{contact_account_count:a}},meta:{request_id:ot(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:rt,session_id:i}}}async function xe(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ye(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,s=at(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested),o=F(i),a=i?.endpoint??N,d=JSON.stringify(s);if(k(i)){let c=_(i),u=await c.getToken(),f=await xe(a,o,u,d,t.signal);if(f.status===401){let h=await c.getToken(!0);f=await xe(a,o,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=H(i);!l&&!be&&(be=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(o.Authorization=l);let p=await fetch(a,{method:"POST",headers:o,body:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function P(n,e){let t=n,i={},r=[],s=[],o=0;for(let a of e){let d=(i[a.type]??0)+1;i[a.type]=d;let p=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,c=f=>{let h=t.indexOf(a.text,f);for(;h!==-1&&s.some(b=>h<b.end&&h+a.text.length>b.start);)h=t.indexOf(a.text,h+1);return h},u=c(o);if(u===-1&&(u=c(0)),u!==-1){t=t.slice(0,u)+p+t.slice(u+a.text.length);let f=p.length-a.text.length;for(let h of s)h.start>=u+a.text.length&&(h.start+=f,h.end+=f);s.push({start:u,end:u+p.length}),o=u>=o?u+p.length:o+f}r.push({...a,placeholder:p})}return{rawQuery:t,completedParams:r}}function T(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(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 Se(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 s=0;s<i.length;s++){let o=i.slice(s).join(" ");if(r.startsWith(o.toLowerCase())){let a=t.length-o.length;return n.length-a}}return 0}function I(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 O(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 ve(n,e){return e?n.map(t=>{let i=e[t.type];return i?{...t,options:i("")}:t}):n}function Pe(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 Ce(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 we(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 Te(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 s=0;for(;s<i-r&&n[n.length-1-s]===e[e.length-1-s];)s++;return n.length-s<=t?t+(e.length-n.length):null}function de(n,e){let t=[],i=[],r=0;for(let s of e){let o=n.indexOf(s.text,r);if(o===-1){i.push(s);continue}t.push({start:o,end:o+s.text.length,param:s}),r=o+s.text.length}return{located:t,missing:i}}function Ee(n,e,t){let i=[],r=[],s=0;for(let o of t){let a=n.indexOf(o.text,s);for(;a!==-1&&e.some(d=>a<d.end&&a+o.text.length>d.start);)a=n.indexOf(o.text,a+1);if(a===-1){r.push(o);continue}i.push({start:a,end:a+o.text.length,param:o}),s=a+o.text.length}return{located:i,missing:r}}function Ie(n,e,t=[]){let i=de(n,e).located,r=Ee(n,i,t).located,s=[...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,p)=>l.start-p.start),o=[],a=0;for(let l of s)l.start>a&&o.push({type:"text",value:n.slice(a,l.start)}),o.push(l.segment),a=l.end;let d=n.slice(a);return d&&o.push({type:"text",value:d}),o}function Ae(n,e){let{located:t,missing:i}=de(n,e);return{valid:t.map(r=>r.param),invalid:i}}function B(n,e,t){let i=de(n,e).located,{located:r,missing:s}=Ee(n,i,t);return{valid:r.map(o=>o.param),invalid:s}}var lt=100,dt=300,ct=2,K=class{constructor(e,t,i,r,s,o,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=s;this.getSessionId=o;this.callbacks=a;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,s=this.store.get().text.length;this.store.set({isLoading:!0,error:null});try{let o=this.store.get(),a=o.pendingSpan?we(o.pendingSpan.snapshot,o.actionableSuggestions):void 0,d=await ye(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:o.identifiedParams,recentlySuggested:a});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})),p=ve(d.data.suggestions??[],this.getOptionOverrides()),c=d.data.input??[],u=c[c.length-1],f=this.store.get().text,h,b;if(u?.state==="in_progress"){b=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:s}else b=!1,h=s;let m=p.filter(x=>x.type!=="placeholder")[0],g=null;if(m){let x=E(f,h,b),y=O(m.options,x);y&&(g={id:crypto.randomUUID(),placeholder:"",type:m.type,text:y.text,kind:y.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:y.metadata},p=p.filter(v=>v!==m),this.callbacks.onAutoMatch?.({active:m,matched:y,rawQuery:e}))}this.store.set(x=>{let y=g?[...x.completedParams,g]:x.completedParams,v=B(x.text,y,l).valid;return{suggestions:p,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:b,identifiedParams:v,...g?{completedParams:y}:{}}})}catch(o){if(r===this.fetchVersion){let a=o instanceof Error?o:new Error(String(o));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}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 s=r.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),o=T(r.text,r.filterBase,s),a=E(r.text,o,r.filterInProgress),l=r.suggestions.filter(g=>g.type!=="placeholder")[0],c=(l?I(l.options,a):[]).filter(g=>g.is_tappable),u=l?O(l.options,a)!==null:!1,f=a.trim().length>0;if(c.length>0&&!u&&f||r.completedParams.length===0&&r.text.length>0&&s.length>0&&s.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:h,completedParams:b}=P(r.text,r.completedParams),S=h.length<r.lastRawQuery.length,m=Math.abs(h.length-r.lastRawQuery.length);return S||m>=i?(this.doFetch(h,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(ct)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},lt),this.slowDebounceTimer=setTimeout(()=>t(1),dt)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var De='[contenteditable="false"]',D;function pt(){if(D!==void 0)return D;let n=globalThis.Intl.Segmenter;if(!n)return D=null,null;try{D=new n(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function U(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(De))return!0;t=t.parentNode}return!1}function $(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return U(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function L(n){let e=$(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function Q(n){let e=$(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(U(r,n)&&r!==n)return null;let s=0;for(let o=0;o<i&&o<r.childNodes.length;o++)s+=Me(r.childNodes[o],n);return s+Oe(r,n)}return t.nodeType!==Node.TEXT_NODE||U(t,n)?null:Oe(t,n)+i}function Me(n,e){if(n.nodeType===Node.TEXT_NODE)return U(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(De))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=Me(r,e);return i}function Oe(n,e){let t=$(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,Q(n))),s=$(n),o=0,a=null,d=0,l=s.nextNode(),p=null;for(;l;){let u=l.data.length;if(r<o+u){a=l,d=r-o;break}if(r===o+u){let f=s.nextNode();f?(a=f,d=0):(a=l,d=u);break}o+=u,p=l,l=s.nextNode()}let c=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?d===0?c.setStartBefore(u):d===a.data.length?c.setStartAfter(u):c.setStart(a,d):c.setStart(a,d)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function q(n){let e=w(n);return e==null?!1:e>=Q(n)}function G(n,e){if(e<=0)return 0;let t=pt();if(!t)return e-1;let i=n.slice(0,e),r=0;for(let{index:s}of t.segment(i))s<e&&(r=s);return r}function ce(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")?q(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ut(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?w(n):null}var W=class{constructor(e,t){this.store=e;this.ctx=t}handleKeyDown(e){let t=this.store.get(),{listboxId:i,getOnSubmit:r}=this.ctx,s=this.getEffectiveColumns(),o=r(),a=this.getTappableIndices(s);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=ce(e.target,t),p=!!t.editingParam;if(!l&&!p&&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:a[0]??0});break}if(a.length===0)return;this.store.set({activeDropdownIndex:a[0]});break}if(e.preventDefault(),a.length===0)return;if(t.filteredOptions.length>0){let f=Math.floor((t.filteredOptions.length-1)/s);if(Math.floor(t.activeDropdownIndex/s)===f){this.store.set({activeDropdownIndex:-1});break}}let c=a.indexOf(t.activeDropdownIndex),u=c<a.length-1?c+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let c=ce(e.target,t),u=!!t.editingParam;if(!c&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(s)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(a.length===0)return;this.store.set({activeDropdownIndex:f});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<s){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),p=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s<s-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(p,c);break}ce(e.target,t)&&t.actionableSuggestions.length>=1&&(e.preventDefault(),this.removeActivePill());break}case"ArrowLeft":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%s>0){let l=t.activeDropdownIndex-1;l>=0&&t.filteredOptions[l]?.is_tappable&&this.store.set({activeDropdownIndex:l})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=ut(e.target);if(l==null)break;this.ctx.removeParamAtCaret(l)&&e.preventDefault();break}case"Enter":{if(e.preventDefault(),t.activeDropdownIndex>=0&&t.filteredOptions[t.activeDropdownIndex]?.is_tappable)this.clickOrSelect(t.activeDropdownIndex,t.filteredOptions,i);else if(o){let{rawQuery:l,completedParams:p}=P(t.text,t.completedParams);o({query:t.text.trim(),raw_query:l,completed_params:p}),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 p=l.indexOf(t.activeDropdownIndex),c;if(p<0)c=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;c=(p+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[c]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(l,p)}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 s=r;s<t.filteredOptions.length;s++)if(t.filteredOptions[s]?.is_tappable)return s;return null}getTappableIndices(e){let i=this.store.get().filteredOptions.map((s,o)=>s.is_tappable?o:-1).filter(s=>s!==-1),r=Array.from({length:e},()=>[]);for(let s of i)r[s%e].push(s);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 s=r.split(" ").filter(Boolean).length;if(s>0)return s}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.slice(1);this.store.set({suggestions:[...t,...r],pillTapped:r.length>0,activeDropdownIndex:-1})}};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],s=i.filter((l,p)=>p!==e),o=t.suggestions.filter(l=>l.type==="placeholder");if(this.callbacks.onPillSelected){let{rawQuery:l}=P(t.text,t.completedParams);this.callbacks.onPillSelected({rawQuery:l,selectedPill:r.text,otherPills:s.map(p=>p.text)})}let a=[...o,r,...s],d=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function ke(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,s=n.filteredOptionsLength>0||n.activePillHasNoOptions;if(n.inEditMode){let o=i?n.isFocused:!0;return s&&o}if(t==="auto"){let o=i?n.isFocused:!0,a=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=a;return(s||n.isLoading)&&o&&d}return t==="manual"?(s||n.isLoading)&&n.pillTapped:!1}function Le(n,e){let t=Ie(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],s=r?e.optionOverrides?.[r.type]:void 0,o=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=T(n.text,Math.min(n.filterBase,n.text.length),o),l=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=r?s?s(l.trim()):r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,u;if(c&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,x=n.completedParams.some(A=>A.id===g),y=n.caretOffset??n.editingAnchor,v=x?"":n.text.slice(n.editingAnchor,y);u=I(n.editingParam.options,v)}else u=I(p,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(g=>g.is_tappable));let h=g=>f?g.is_tappable:!0,b;if(c){let g=n.editingParam?.options??[];b=n.editingParam!=null&&g.filter(h).length===0}else{let g=r?s?s(""):r.options??[]:[];b=r!=null&&g.filter(h).length===0}let S=ke({inEditMode:c,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:b},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),m=S&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,placeholderText:o,isDropdownOpen:S,isActivePillSelected:m}}function V(n){return n.mode==="fresh"?mt(n):gt(n)}function mt(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:s}=n,a=i.filter(y=>y.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(y=>y.type==="placeholder").map(y=>y.text).join(" "),l=T(e,r,d),p=E(e,l,s),c=O(a.options,p);if(!c)return null;let u=c.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-c.text.length),b=h+c.text.length,S=e.slice(h,b),g=b<e.length&&e[b]===" "?b+1:b,x={id:crypto.randomUUID(),placeholder:"",type:a.type,text:S,kind:c.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:i.filter(y=>y!==a),filterBase:g,newParamId:x.id,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}function gt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:s}=n;if(t.some(x=>x.id===i.id))return null;let o=e.slice(r,s),a=O(i.options,o);if(!a)return null;let d=a.text.toLowerCase(),l=o.toLowerCase().lastIndexOf(d),p=r+Math.max(0,l),c=p+a.text.length,u=e.slice(p,c),h=c<e.length&&e[c]===" "?c+1:c,b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:u,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},S=t.length,m=0;for(let x=0;x<t.length;x++){let y=e.indexOf(t[x].text,m);if(y!==-1){if(y>=h){S=x;break}m=y+t[x].text.length}}let g=[...t];return g.splice(S,0,b),{patch:{text:e,completedParams:g,newParamId:b.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}var z=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(o=>o.id===e);if(!i)return;let r=0,s=-1;for(let o of t.completedParams){let a=t.text.indexOf(o.text,r);if(a!==-1){if(o.id===e){s=a;break}r=a+o.text.length}}s<0||this.deps.store.set({editingParam:i,editingAnchor:s,editingTail:s+i.text.length,caretOffset:s+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,s=t.editingTail;if(!i||r==null||s==null||!t.completedParams.some(d=>d.id===i.id))return!1;let o=t.text.slice(0,r)+e+t.text.slice(s),a=r+e.length;return this.deps.store.set(d=>({text:o,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),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,s=t.editingTail;if(!i||r==null||s==null)return;this.deps.fireTelemetry("option",{raw_query:P(t.text,t.completedParams).rawQuery,selected_option:e.text,other_options:i.options.filter(m=>m.text!==e.text).map(m=>m.text)});let o=t.text.slice(0,r),a=t.text.slice(s),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${d} `:d,c=o+p+a,u=r+p.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(m=>m.id===i.id),b=t.completedParams.filter(m=>m.id!==i.id),S=h>=0?Math.min(h,b.length):b.length;b.splice(S,0,f),this.deps.store.set({text:c,completedParams:b,newParamId:f.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(u)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=V({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 pe="https://ai-autocomplete.com";function X(n=pe){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 Y(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Re="data-aia-key";function J(n,e,t){let i=new Map;for(let o of Array.from(n.children)){let a=o.getAttribute(Re);a!=null&&i.set(a,o)}let r=new Set,s=[];for(let o=0;o<e.length;o++){let a=e[o],d=t.keyOf(a,o);r.add(d);let l=i.get(d);l||(l=t.create(a,o),l.setAttribute(Re,d)),t.update?.(l,a,o),n.children[o]!==l&&n.insertBefore(l,n.children[o]??null),s.push(l)}for(let[o,a]of i)r.has(o)||a.remove();return s}var Ne=[125,69];function _e(n,e){return e?1:n===0?.7:n===1?.4:.2}function Z(n,e,t,i,r=!1,s=!1,o=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),s&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let d=0;d<Ne.length;d++){let l=Ne[d],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(_e(d,!1)),a.appendChild(p)}return}s?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let d of a.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();J(a,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",p=>p.preventDefault()),l},update:(d,l,p)=>{let c=d,u=o&&p===t&&!s,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),s&&f.push("magicx-aia-pill--skeleton"),c.className=f.join(" "),c.style.width="",c.style.opacity=String(_e(p,u)),s?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>i(p))}})}function ue(n){n.querySelector(".magicx-aia-pill-list")?.remove()}function Fe(n,e,t,i,r,s,o,a=""){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,t,i,r,s,o),ft(d,a)}function ft(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function ht(n,e,t,i,r,s,o){let a=o?"1":"0";J(n,e,{keyOf:d=>`${d.text}\0${a}`,create:d=>bt(d,o),update:(d,l,p)=>{let c=p===t&&!o;d.id=`${s}-option-${p}`,d.dataset.aiaIndex=String(p),d.setAttribute("aria-selected",String(c)),d.classList.toggle("magicx-aia-option--highlighted",c),!o&&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 bt(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 s=document.createElement("div");s.className="magicx-aia-streaks-vert",t.appendChild(s);let o=document.createElement("span");o.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,o.appendChild(a),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,o.appendChild(d)}return t.appendChild(o),t}var xt=[159,119,164];function ee(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 te(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:s,pills:o,showPills:a,isActivePillSelected:d,onSelect:l,onHighlight:p,onPillClick:c}=e,u=a&&o.length>0,f=t.length>0,h=r&&(f||u||s);if(h?n.classList.add("magicx-aia-dropdown--visible"):n.classList.remove("magicx-aia-dropdown--visible"),s?n.setAttribute("data-aia-loading",""):n.removeAttribute("data-aia-loading"),!h)return;let b=n.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),n.appendChild(b));let S=u||s&&a,m=b.querySelector(".magicx-aia-pill-bar");S?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),Z(m,o,0,c,!0,s,d)):m&&m.remove();let g=e.suggestions[0],x=g?`${g.type} ${g.text}`:"";Fe(b,t,i,l,p,e.listboxId,s,x);let y=b.querySelector(".magicx-aia-skeleton-bars");if(s&&!f){if(!y){y=document.createElement("div"),y.className="magicx-aia-skeleton-bars",y.setAttribute("data-aia-skeleton-bars","");for(let ze of xt){let ae=document.createElement("span");ae.className="magicx-aia-skeleton-bar",ae.style.width=`${ze}px`,y.appendChild(ae)}b.appendChild(y)}}else y&&y.remove();let v=b.querySelector(".magicx-aia-footer")??St(),A=i>=0&&!!t[i]?.is_tappable;yt(v,Y(A,e.isInputEmpty)),b.lastElementChild!==v&&b.appendChild(v)}function yt(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 St(){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 s=document.createElement("a");s.className="aia-cluster magicx-aia-footer-brand-link",s.setAttribute("data-align","center"),s.href=X(),s.target="_blank",s.rel="noopener noreferrer",s.style.setProperty("--aia-cluster-gap","2px");let o=document.createElement("span");o.className="magicx-aia-footer-brand",o.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",s.append(o,a),e.append(t,s),n.append(e),n}function He(n,e){let t=ee(e.listboxId);return n.appendChild(t),{dropdown:t}}function me(n,e,t){te(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,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function ne(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:s,isFocused:o}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&s?e.dataset.placeholder=s:delete e.dataset.placeholder;let d=t.map(S=>`${S.type}:${S.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(d===l&&(i??"")===p&&(r??"")===c)return;let u=o?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),b=0;for(let S of t)if(b+=S.value.length,S.type==="completed"){let m=f.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=S.param.id;let g=S.param.id===i,x=S.param.id===r,y=["magicx-aia-segment","magicx-aia-segment--completed"];g&&y.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&y.push("magicx-aia-segment--editing"),m.className=y.join(" "),m.textContent=S.value,h.appendChild(m)}else if(S.type==="identified"){let m=f.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=S.param.id,m.className="magicx-aia-segment magicx-aia-segment--completed",m.textContent=S.value,h.appendChild(m)}else h.appendChild(f.createTextNode(S.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(b),u!=null&&C(e,Math.max(0,Math.min(u,b)))}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 Be(){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 Pt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Ke(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 Ue(n,e){let{listboxId:t}=e,i=ee(t);n.appendChild(i);let r=document.createElement("div");r.className="magicx-aia-input-wrapper",n.appendChild(r);let s=document.createElement("div");s.className="magicx-aia-editor",s.setAttribute("data-aia-editor",""),r.appendChild(s);let o=document.createElement("div");o.className="magicx-aia-input",o.setAttribute("data-aia-input",""),o.setAttribute("contenteditable",Pt()?"plaintext-only":"true"),o.setAttribute("role","combobox"),o.setAttribute("aria-autocomplete","list"),o.setAttribute("aria-haspopup","listbox"),o.setAttribute("aria-controls",t),o.setAttribute("aria-expanded","false"),o.setAttribute("spellcheck","true"),o.setAttribute("enterkeyhint","send"),s.appendChild(o);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),s.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=Be(),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 p=new AbortController,{signal:c}=p,u=!1,f=0,h=()=>{let m=L(o),x=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(x)},b=()=>{let m=(o.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.anchorNode;return!g||!o.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||o.focus()},{signal:c}),o.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(o)))},{signal:c});let S=o.ownerDocument??document;if(S.addEventListener("selectionchange",()=>{let m=S.getSelection();if(!m||m.rangeCount===0||!o.contains(m.anchorNode))return;let g=b(),x=e.store.get().editingParam?.id??null;if(g&&g!==x){e.startEditingParam(g);return}performance.now()-f<50||e.handleCaretMove(w(o))},{signal:c}),o.addEventListener("compositionstart",()=>{u=!0},{signal:c}),o.addEventListener("compositionend",()=>{u=!1,h()},{signal:c}),o.addEventListener("beforeinput",m=>{let g=m,x=g.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){m.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let y=x.startsWith("delete")?"":g.data??"";e.replaceEditingRange(y)&&m.preventDefault()}},{signal:c}),o.addEventListener("paste",m=>{m.preventDefault();let g=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let x=o.ownerDocument??document,y=x.getSelection();if(!y||y.rangeCount===0)return;let v=y.getRangeAt(0);if(!o.contains(v.startContainer))return;v.deleteContents();let A=x.createTextNode(g);v.insertNode(A),v.setStartAfter(A),v.collapse(!0),y.removeAllRanges(),y.addRange(v),h()},{signal:c}),o.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:c}),o.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),o.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),l&&l.addEventListener("click",m=>{let g=e.store.get();if(!(!!g.text||g.completedParams.length>0)||!e.onSubmit)return;m.stopPropagation();let{rawQuery:y,completedParams:v}=P(g.text,g.completedParams);e.onSubmit({query:g.text.trim(),raw_query:y,completed_params:v}),e.afterSubmit?.()},{signal:c}),e.autoFocus!==!1){o.focus();let m=o.ownerDocument??document,g=m.getSelection(),x=g&&g.rangeCount>0&&o.contains(g.anchorNode);if(g&&!x){let y=m.createRange();y.selectNodeContents(o),y.collapse(!0),g.removeAllRanges(),g.addRange(y)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Ke(o,a));m.observe(o),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:o,inlinePillContainer:a,dropdown:i,submitButton:d,abort:p}}function ge(n,e,t){let{input:i,inlinePillContainer:r,dropdown:s,submitButton:o}=n,{pillPlacement:a,setActivePill:d,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),o){let S=!!e.text||e.completedParams.length>0;o.disabled=!S}let u=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(ne({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let S=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;S||e.actionableSuggestions.length>0?Z(r,e.actionableSuggestions,0,d,!1,S,e.isActivePillSelected):ue(r)}else ue(r);Ke(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&L(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,b=h??e.actionableSuggestions[0];te(s,{suggestions:b?[{...b,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:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:S=>p.set({activeDropdownIndex:S}),onPillClick:d})}function $e(n,e){let t=n.actionableSuggestions[0];if(!t)return null;let i=n.filterBase,r=n.text.slice(0,i),s=r.length===0&&n.text.length===0,o=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(s||o)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=Se(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,p=(s||o)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=c>=0?p.slice(c,c+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:h}}function ie(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:s=>{let o=typeof s=="function"?s(e):s,a=e;if(e={...e,...o},i.push([e,a]),!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[p,c]=l;for(let u of t)u(p,c)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:s=>(t.add(s),()=>{t.delete(s)})}}function Qe(n,e){let t,i,r=s=>(s!==t&&(t=s,i=e(s)),i);return{get:()=>{let s=n.get();return{...s,...r(s)}},set:s=>{typeof s=="function"?n.set(o=>{let a={...o,...r(o)};return s(a)}):n.set(s)},peek:s=>{let o={...n.get(),...s};return{...o,...e(o)}},subscribe:s=>n.subscribe((o,a)=>{let d={...a,...r(a)},l={...o,...r(o)};s(l,d)})}}var fe=!1;function qe(){if(fe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){fe=!0;return}fe=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Ct,document.head.appendChild(n)}var Ct=`@layer layout {
|
|
1
|
+
"use strict";var ce=Object.defineProperty;var Ze=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.prototype.hasOwnProperty;var nt=(n,e)=>{for(var t in e)ce(n,t,{get:e[t],enumerable:!0})},it=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of et(e))!tt.call(n,r)&&r!==t&&ce(n,r,{get:()=>e[r],enumerable:!(i=Ze(e,r))||i.enumerable});return n};var rt=n=>it(ce({},"__esModule",{value:!0}),n);var Rt={};nt(Rt,{AIAutocomplete:()=>le,ATTRIBUTION_URL:()=>ge,ModeController:()=>L,SKIPPED_PARAM_TEXT:()=>pe,buildAttributionUrl:()=>J,buildQuery:()=>v,buildSubmitResult:()=>M,createStore:()=>oe,cursorIsAtEnd:()=>W,extractPlainText:()=>N,getCursorOffset:()=>w,getFooterHint:()=>Z,plainTextLength:()=>G,previousGraphemeBoundary:()=>j,renderEditableContent:()=>re,setCursorOffset:()=>C,withSkippedParams:()=>O});module.exports=rt(Rt);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 ot="https://api.ai-autocomplete.com",F=`${ot}/api/suggest`,Se=new WeakMap;function R(n){return n?.type==="accessToken"}function st(n){if(!(!n||R(n)))return n}function H(n){let e=Se.get(n.getAccessToken);return e||(e=new _(n),Se.set(n.getAccessToken,e)),e}function B(n){return{"Content-Type":"application/json",...n?.appIdentifier&&{"X-App-Identifier":n.appIdentifier},...n?.headers}}function K(n){let e=st(n),t=e?.apiKey;return t?(e?.authScheme??"Bearer")==="Basic"?`Basic ${btoa(t)}`:`Bearer ${t}`:null}var pe="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:pe,kind:null}));return i.length>0?[...n,...i]:n}var at="0.7.0",ye=!1;function lt(){return crypto.randomUUID()}function dt(n,e){return{placeholder:n.placeholder,type:n.type,...e&&{text:n.text},kind:n.kind}}function ct(n,e,t,i,r,o,s){let a=e.find(l=>l.type==="contact"&&l.metadata?.contact_account_count)?.metadata?.contact_account_count,d=typeof a=="number"?a:void 0;return{data:{raw_query:n,completed_params:O(e.map(l=>dt(l,t)),s??[]),...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:lt(),request_at:new Date().toISOString(),language:typeof navigator<"u"?navigator.language:"en-US",client_version:at,session_id:i}}}async function Pe(n,e,t,i,r){return fetch(n,{method:"POST",headers:{...e,Authorization:`Bearer ${t}`},body:i,signal:r})}async function ve(n,e,t){let i=t.apiConfig,r=!t.maskCompletedText,o=ct(n,e,r,t.sessionId,t.identifiedParams,t.recentlySuggested,t.skippedParams),s=B(i),a=i?.endpoint??F,d=JSON.stringify(o);if(R(i)){let c=H(i),u=await c.getToken(),f=await Pe(a,s,u,d,t.signal);if(f.status===401){let h=await c.getToken(!0);f=await Pe(a,s,h,d,t.signal)}if(!f.ok)throw new Error(`API error: ${f.status} ${f.statusText}`);return f.json()}let l=K(i);!l&&!ye&&(ye=!0,console.warn("[AIAutocomplete] No apiKey in apiConfig. Requests will be sent without an Authorization header.")),l&&(s.Authorization=l);let p=await fetch(a,{method:"POST",headers:s,body:d,signal:t.signal});if(!p.ok)throw new Error(`API error: ${p.status} ${p.statusText}`);return p.json()}function v(n,e){let t=n,i={},r=[],o=[],s=0;for(let a of e){let d=(i[a.type]??0)+1;i[a.type]=d;let p=`{{${a.type.toUpperCase().replace(/\s+/g,"_")}_${d}}}`,c=f=>{let h=t.indexOf(a.text,f);for(;h!==-1&&o.some(b=>h<b.end&&h+a.text.length>b.start);)h=t.indexOf(a.text,h+1);return h},u=c(s);if(u===-1&&(u=c(0)),u!==-1){t=t.slice(0,u)+p+t.slice(u+a.text.length);let f=p.length-a.text.length;for(let h of o)h.start>=u+a.text.length&&(h.start+=f,h.end+=f);o.push({start:u,end:u+p.length}),s=u>=s?u+p.length:s+f}r.push({...a,placeholder:p})}return{rawQuery:t,completedParams:r}}function T(n,e,t){return e>0||!t?e:n.toLowerCase().startsWith(t.toLowerCase())?t.length:e}function E(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 Ce(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 s=i.slice(o).join(" ");if(r.startsWith(s.toLowerCase())){let a=t.length-s.length;return n.length-a}}return 0}function I(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 we(n,e){return e?n.map(t=>{let i=e[t.type];return i?{...t,options:i("")}:t}):n}function Te(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 Ee(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 Ie(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 Ae(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 ue(n,e){let t=[],i=[],r=0;for(let o of e){let s=n.indexOf(o.text,r);if(s===-1){i.push(o);continue}t.push({start:s,end:s+o.text.length,param:o}),r=s+o.text.length}return{located:t,missing:i}}function Oe(n,e,t){let i=[],r=[],o=0;for(let s of t){let a=n.indexOf(s.text,o);for(;a!==-1&&e.some(d=>a<d.end&&a+s.text.length>d.start);)a=n.indexOf(s.text,a+1);if(a===-1){r.push(s);continue}i.push({start:a,end:a+s.text.length,param:s}),o=a+s.text.length}return{located:i,missing:r}}function ke(n,e,t=[]){let i=ue(n,e).located,r=Oe(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,p)=>l.start-p.start),s=[],a=0;for(let l of o)l.start>a&&s.push({type:"text",value:n.slice(a,l.start)}),s.push(l.segment),a=l.end;let d=n.slice(a);return d&&s.push({type:"text",value:d}),s}function De(n,e){let{located:t,missing:i}=ue(n,e);return{valid:t.map(r=>r.param),invalid:i}}function U(n,e,t){let i=ue(n,e).located,{located:r,missing:o}=Oe(n,i,t);return{valid:r.map(s=>s.param),invalid:o}}var pt=100,ut=300,mt=2,$=class{constructor(e,t,i,r,o,s,a={}){this.store=e;this.getApiConfig=t;this.getOptionOverrides=i;this.getMaskCompletedText=r;this.getOnError=o;this.getSessionId=s;this.callbacks=a;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;this.store.set({isLoading:!0,error:null});try{let s=this.store.get(),a=s.pendingSpan?Ie(s.pendingSpan.snapshot,s.actionableSuggestions):void 0,d=await ve(e,t,{sessionId:this.getSessionId(),maskCompletedText:this.getMaskCompletedText(),signal:i.signal,apiConfig:this.getApiConfig(),identifiedParams:s.identifiedParams,recentlySuggested:a,skippedParams:s.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})),p=we(d.data.suggestions??[],this.getOptionOverrides()),c=d.data.input??[],u=c[c.length-1],f=this.store.get().text,h,b;if(u?.state==="in_progress"){b=!0;let x=f.toLowerCase().lastIndexOf(u.text.toLowerCase());h=x!==-1?x:o}else b=!1,h=o;let m=p.filter(x=>x.type!=="placeholder")[0],g=null;if(m){let x=E(f,h,b),S=k(m.options,x);S&&(g={id:crypto.randomUUID(),placeholder:"",type:m.type,text:S.text,kind:S.kind,suggestionType:m.type,suggestionPlaceholder:m.text,options:m.options??[],metadata:S.metadata},p=p.filter(P=>P!==m),this.callbacks.onAutoMatch?.({active:m,matched:S,rawQuery:e}))}this.store.set(x=>{let S=g?[...x.completedParams,g]:x.completedParams,P=U(x.text,S,l).valid;return{suggestions:p,isLoading:!1,isReady:d.data.is_ready??!1,lastRawQuery:e,activeDropdownIndex:-1,filterBase:h,filterInProgress:b,identifiedParams:P,...g?{completedParams:S}:{}}})}catch(s){if(r===this.fetchVersion){let a=s instanceof Error?s:new Error(String(s));this.store.set({error:a,isLoading:!1}),this.getOnError()?.(a)}}}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(g=>g.type==="placeholder").map(g=>g.text).join(" "),s=T(r.text,r.filterBase,o),a=E(r.text,s,r.filterInProgress),l=r.suggestions.filter(g=>g.type!=="placeholder")[0],c=(l?I(l.options,a):[]).filter(g=>g.is_tappable),u=l?k(l.options,a)!==null:!1,f=a.trim().length>0;if(c.length>0&&!u&&f||r.completedParams.length===0&&r.text.length>0&&o.length>0&&o.toLowerCase().startsWith(r.text.toLowerCase()))return!1;let{rawQuery:h,completedParams:b}=v(r.text,r.completedParams),y=h.length<r.lastRawQuery.length,m=Math.abs(h.length-r.lastRawQuery.length);return y||m>=i?(this.doFetch(h,b),!0):!1};this.debounceTimer=setTimeout(()=>{t(mt)&&this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer)},pt),this.slowDebounceTimer=setTimeout(()=>t(1),ut)}clearTimers(){this.debounceTimer&&clearTimeout(this.debounceTimer),this.slowDebounceTimer&&clearTimeout(this.slowDebounceTimer),this.debounceTimer=null,this.slowDebounceTimer=null}};var Le='[contenteditable="false"]',D;function gt(){if(D!==void 0)return D;let n=globalThis.Intl.Segmenter;if(!n)return D=null,null;try{D=new n(void 0,{granularity:"grapheme"})}catch{D=null}return D??null}function Q(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===Node.ELEMENT_NODE&&t.matches(Le))return!0;t=t.parentNode}return!1}function q(n){return(n.ownerDocument??document).createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(e){return Q(e,n)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}})}function N(n){let e=q(n),t="",i=e.nextNode();for(;i;)t+=i.data,i=e.nextNode();return t}function G(n){let e=q(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(Q(r,n)&&r!==n)return null;let o=0;for(let s=0;s<i&&s<r.childNodes.length;s++)o+=Re(r.childNodes[s],n);return o+Me(r,n)}return t.nodeType!==Node.TEXT_NODE||Q(t,n)?null:Me(t,n)+i}function Re(n,e){if(n.nodeType===Node.TEXT_NODE)return Q(n,e)?0:n.data.length;if(n.nodeType!==Node.ELEMENT_NODE)return 0;let t=n;if(t.matches(Le))return 0;let i=0;for(let r of Array.from(t.childNodes))i+=Re(r,e);return i}function Me(n,e){let t=q(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,G(n))),o=q(n),s=0,a=null,d=0,l=o.nextNode(),p=null;for(;l;){let u=l.data.length;if(r<s+u){a=l,d=r-s;break}if(r===s+u){let f=o.nextNode();f?(a=f,d=0):(a=l,d=u);break}s+=u,p=l,l=o.nextNode()}let c=t.createRange();if(a){let u=a.parentElement?.closest('strong[data-seg="completed"]');u&&u!==n&&n.contains(u)?d===0?c.setStartBefore(u):d===a.data.length?c.setStartAfter(u):c.setStart(a,d):c.setStart(a,d)}else p?c.setStart(p,p.data.length):c.setStart(n,0);c.collapse(!0),i.removeAllRanges(),i.addRange(c)}function W(n){let e=w(n);return e==null?!1:e>=G(n)}function j(n,e){if(e<=0)return 0;let t=gt();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 me(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")?W(n):e?.caretOffset!=null?e.caretOffset>=e.text.length:!1}function ft(n){return n instanceof HTMLElement&&n.hasAttribute("data-aia-input")?w(n):null}var V=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(),s=r(),a=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=me(e.target,t),p=!!t.editingParam;if(!l&&!p&&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:a[0]??0});break}if(a.length===0)return;this.store.set({activeDropdownIndex:a[0]});break}if(e.preventDefault(),a.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 c=a.indexOf(t.activeDropdownIndex),u=c<a.length-1?c+1:0;this.store.set({activeDropdownIndex:a[u]});break}case"ArrowUp":{if(t.activeDropdownIndex<0){if(!d)break;let c=me(e.target,t),u=!!t.editingParam;if(!c&&!u)break;e.preventDefault();let f=this.firstTappableInBottomRow(o)??a[0]??0;if(!t.isDropdownOpen&&t.actionableSuggestions.length>0){this.store.set({pillTapped:!0,activeDropdownIndex:f});break}if(a.length===0)return;this.store.set({activeDropdownIndex:f});break}if(a.length===0)break;if(e.preventDefault(),t.activeDropdownIndex<o){this.store.set({activeDropdownIndex:-1});break}let l=a.indexOf(t.activeDropdownIndex),p=l>0?l-1:a.length-1;this.store.set({activeDropdownIndex:a[p]});break}case"ArrowRight":{if(t.activeDropdownIndex>=0){if(e.preventDefault(),t.activeDropdownIndex%o<o-1){let c=t.activeDropdownIndex+1;c<t.filteredOptions.length&&t.filteredOptions[c]?.is_tappable&&this.store.set({activeDropdownIndex:c})}break}if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){e.preventDefault();let p=e.target.closest("[data-aia-input]")??e.target,c=t.editingTail;this.ctx.exitEditMode?.(),C(p,c);break}me(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&&e.target instanceof HTMLElement&&t.editingAnchor!=null){e.preventDefault();let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingAnchor;this.ctx.exitEditMode?.(),C(l,p);break}break}case"Backspace":{if(t.editingParam||!this.ctx.removeParamAtCaret)break;let l=ft(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):s&&(s(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 p=l.indexOf(t.activeDropdownIndex),c;if(p<0)c=e.shiftKey?l.length-1:0;else{let u=e.shiftKey?-1:1;c=(p+u+l.length)%l.length}this.store.set({activeDropdownIndex:l[c]});break}case"Escape":{if(t.editingParam&&e.target instanceof HTMLElement&&t.editingTail!=null){let l=e.target.closest("[data-aia-input]")??e.target,p=t.editingTail;this.ctx.exitEditMode?.(),C(l,p)}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,s)=>o.is_tappable?s:-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(a=>a.type==="placeholder"),i=e.suggestions.filter(a=>a.type!=="placeholder");if(i.length===0)return;let r=i[0],o=i.slice(1),s=e.skippedParams.some(a=>a.type===r.type);this.store.set({suggestions:[...t,...o],pillTapped:o.length>0,activeDropdownIndex:-1,...s?{}:{skippedParams:[...e.skippedParams,{id:crypto.randomUUID(),type:r.type,suggestionPlaceholder:r.text}]}}),o.length===0&&this.ctx.fetchNow?.()}};var X=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,p)=>p!==e),s=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(p=>p.text)})}let a=[...s,r,...o],d=this.store.peek({suggestions:a}).filteredOptions.findIndex(l=>l.is_tappable);this.store.set({suggestions:a,pillTapped:!0,activeDropdownIndex:d})}removeLastParam(){this.store.get().completedParams.length!==0&&this.store.set(t=>({completedParams:t.completedParams.slice(0,-1),activeDropdownIndex:-1}))}};function Ne(n,e){let t=e.dropdownTrigger??"auto",i=e.closeDropdownOnBlur??!0,o=n.filteredOptionsLength>0||n.activePillHasNoOptions;if(n.inEditMode){let s=i?n.isFocused:!0;return o&&s}if(t==="auto"){let s=i?n.isFocused:!0,a=n.text.replace(/\s+$/,"").length,d=n.caretOffset==null||n.caretOffset>=a;return(o||n.isLoading)&&s&&d}return t==="manual"?(o||n.isLoading)&&n.pillTapped:!1}function _e(n,e){let t=ke(n.text,n.completedParams,n.identifiedParams),i=n.suggestions.filter(g=>g.type!=="placeholder"),r=i[0],o=r?e.optionOverrides?.[r.type]:void 0,s=n.suggestions.filter(g=>g.type==="placeholder").map(g=>g.text).join(" "),a=T(n.text,Math.min(n.filterBase,n.text.length),s),l=n.lastRawQuery!==""||a>0?E(n.text,a,n.filterInProgress):"",p=r?o?o(l.trim()):r.options??[]:[],c=n.editingParam!=null&&n.editingAnchor!=null,u;if(c&&n.editingParam&&n.editingAnchor!=null){let g=n.editingParam.id,x=n.completedParams.some(A=>A.id===g),S=n.caretOffset??n.editingAnchor,P=x?"":n.text.slice(n.editingAnchor,S);u=I(n.editingParam.options,P)}else u=I(p,l);let f=e.showNonTappableOptions===!1;f&&(u=u.filter(g=>g.is_tappable));let h=g=>f?g.is_tappable:!0,b;if(c){let g=n.editingParam?.options??[];b=n.editingParam!=null&&g.filter(h).length===0}else{let g=r?o?o(""):r.options??[]:[];b=r!=null&&g.filter(h).length===0}let y=Ne({inEditMode:c,filteredOptionsLength:u.length,isFocused:n.isFocused,text:n.text,caretOffset:n.caretOffset,isLoading:n.isLoading,pillTapped:n.pillTapped,activePillHasNoOptions:b},{dropdownTrigger:e.dropdownTrigger,closeDropdownOnBlur:e.closeDropdownOnBlur}),m=y&&n.activeDropdownIndex>=0&&!!u[n.activeDropdownIndex]?.is_tappable;return{segments:t,actionableSuggestions:i,filteredOptions:u,placeholderText:s,isDropdownOpen:y,isActivePillSelected:m}}function z(n){return n.mode==="fresh"?ht(n):bt(n)}function ht(n){let{text:e,completedParams:t,suggestions:i,filterBase:r,filterInProgress:o}=n,a=i.filter(S=>S.type!=="placeholder")[0];if(!a?.options)return null;let d=i.filter(S=>S.type==="placeholder").map(S=>S.text).join(" "),l=T(e,r,d),p=E(e,l,o),c=k(a.options,p);if(!c)return null;let u=c.text.toLowerCase(),f=e.toLowerCase().lastIndexOf(u),h=f>=0?f:Math.max(0,e.length-c.text.length),b=h+c.text.length,y=e.slice(h,b),g=b<e.length&&e[b]===" "?b+1:b,x={id:crypto.randomUUID(),placeholder:"",type:a.type,text:y,kind:c.kind,suggestionType:a.type,suggestionPlaceholder:a.text,options:a.options??[],metadata:c.metadata};return{patch:{text:e,completedParams:[...t,x],suggestions:i.filter(S=>S!==a),filterBase:g,newParamId:x.id,caretOffset:g,activeDropdownIndex:-1},caretPos:g}}function bt(n){let{text:e,completedParams:t,editingParam:i,editingAnchor:r,editingTail:o}=n;if(t.some(x=>x.id===i.id))return null;let s=e.slice(r,o),a=k(i.options,s);if(!a)return null;let d=a.text.toLowerCase(),l=s.toLowerCase().lastIndexOf(d),p=r+Math.max(0,l),c=p+a.text.length,u=e.slice(p,c),h=c<e.length&&e[c]===" "?c+1:c,b={id:crypto.randomUUID(),placeholder:"",type:i.suggestionType,text:u,kind:a.kind,suggestionType:i.suggestionType,suggestionPlaceholder:i.suggestionPlaceholder,options:i.options,metadata:a.metadata},y=t.length,m=0;for(let x=0;x<t.length;x++){let S=e.indexOf(t[x].text,m);if(S!==-1){if(S>=h){y=x;break}m=S+t[x].text.length}}let g=[...t];return g.splice(y,0,b),{patch:{text:e,completedParams:g,newParamId:b.id,filterBase:h,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:h,activeDropdownIndex:-1},caretPos:h}}var Y=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(s=>s.id===e);if(!i)return;let r=0,o=-1;for(let s of t.completedParams){let a=t.text.indexOf(s.text,r);if(a!==-1){if(s.id===e){o=a;break}r=a+s.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 s=t.text.slice(0,r)+e+t.text.slice(o),a=r+e.length;return this.deps.store.set(d=>({text:s,completedParams:d.completedParams.filter(l=>l.id!==i.id),editingTail:a,caretOffset:a,activeDropdownIndex:-1})),this.deps.scheduleSetCursor(a),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(m=>m.text!==e.text).map(m=>m.text)});let s=t.text.slice(0,r),a=t.text.slice(o),d=r===0&&e.text.length>0?e.text[0].toUpperCase()+e.text.slice(1):e.text,l=a.length===0||a[0]!==" ",p=l?`${d} `:d,c=s+p+a,u=r+p.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(m=>m.id===i.id),b=t.completedParams.filter(m=>m.id!==i.id),y=h>=0?Math.min(h,b.length):b.length;b.splice(y,0,f),this.deps.store.set({text:c,completedParams:b,newParamId:f.id,filterBase:u,editingParam:null,editingAnchor:null,editingTail:null,caretOffset:u,activeDropdownIndex:-1,pillTapped:!1,skipNextFetch:!0,inSelectionAnimation:!0}),this.deps.startSelectionAnimationTimer(),this.deps.scheduleSetCursor(u)}tryPromote(){let e=this.deps.store.get();if(!e.editingParam||e.editingAnchor==null||e.editingTail==null)return;let t=z({mode:"edit",text:e.text,completedParams:e.completedParams,editingParam:e.editingParam,editingAnchor:e.editingAnchor,editingTail:e.editingTail});t&&(this.deps.store.set(t.patch),this.deps.scheduleSetCursor(t.caretPos))}};var ge="https://ai-autocomplete.com";function J(n=ge){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 Z(n,e){return n?{key:"enter",hint:"to proceed"}:e?{key:"tab",hint:"to select"}:{key:"\u2192",hint:"to skip"}}var Fe="data-aia-key";function ee(n,e,t){let i=new Map;for(let s of Array.from(n.children)){let a=s.getAttribute(Fe);a!=null&&i.set(a,s)}let r=new Set,o=[];for(let s=0;s<e.length;s++){let a=e[s],d=t.keyOf(a,s);r.add(d);let l=i.get(d);l||(l=t.create(a,s),l.setAttribute(Fe,d)),t.update?.(l,a,s),n.children[s]!==l&&n.insertBefore(l,n.children[s]??null),o.push(l)}for(let[s,a]of i)r.has(s)||a.remove();return o}var He=[125,69];function Be(n,e){return e?1:n===0?.7:n===1?.4:.2}function te(n,e,t,i,r=!1,o=!1,s=!1){let a=n.querySelector(".magicx-aia-pill-list");if(a||(a=document.createElement("span"),a.className="magicx-aia-pill-list",n.appendChild(a)),o&&e.length===0){a.setAttribute("data-aia-pill-list-loading",""),a.innerHTML="";for(let d=0;d<He.length;d++){let l=He[d],p=document.createElement("span");p.setAttribute("data-aia-pill-skeleton",""),p.className=`magicx-aia-pill magicx-aia-pill--skeleton${r?" magicx-aia-pill--rounded":""}`,p.style.width=`${l}px`,p.style.opacity=String(Be(d,!1)),a.appendChild(p)}return}o?a.setAttribute("data-aia-pill-list-loading",""):a.removeAttribute("data-aia-pill-list-loading");for(let d of a.querySelectorAll("[data-aia-pill-skeleton]"))d.remove();ee(a,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",p=>p.preventDefault()),l},update:(d,l,p)=>{let c=d,u=s&&p===t&&!o,f=["magicx-aia-pill"];r&&f.push("magicx-aia-pill--rounded"),o&&f.push("magicx-aia-pill--skeleton"),c.className=f.join(" "),c.style.width="",c.style.opacity=String(Be(p,u)),o?(c.setAttribute("data-aia-loading",""),c.disabled=!0,c.onclick=null):(c.removeAttribute("data-aia-loading"),c.disabled=!1,c.onclick=()=>i(p))}})}function fe(n){n.querySelector(".magicx-aia-pill-list")?.remove()}function Ke(n,e,t,i,r,o,s,a=""){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)),St(d,e,t,i,r,o,s),xt(d,a)}function xt(n,e){n.dataset.aiaGroup!==e&&(n.dataset.aiaGroup=e,n.scrollTop=0)}function St(n,e,t,i,r,o,s){let a=s?"1":"0";ee(n,e,{keyOf:d=>`${d.text}\0${a}`,create:d=>yt(d,s),update:(d,l,p)=>{let c=p===t&&!s;d.id=`${o}-option-${p}`,d.dataset.aiaIndex=String(p),d.setAttribute("aria-selected",String(c)),d.classList.toggle("magicx-aia-option--highlighted",c),!s&&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 yt(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 s=document.createElement("span");s.className="magicx-aia-option-content";let a=document.createElement("span");if(a.className="magicx-aia-option-text",a.textContent=n.icon?`${n.icon} ${n.text}`:n.text,s.appendChild(a),n.tag){let d=document.createElement("span");d.className="magicx-aia-option-tag",d.textContent=n.tag,s.appendChild(d)}return t.appendChild(s),t}var Pt=[159,119,164];function ne(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 ie(n,e){let{filteredOptions:t,activeIndex:i,isOpen:r,isLoading:o,pills:s,showPills:a,isActivePillSelected:d,onSelect:l,onHighlight:p,onPillClick:c}=e,u=a&&s.length>0,f=t.length>0,h=r&&(f||u||o);if(h?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"),!h)return;let b=n.querySelector(".aia-stack");b||(b=document.createElement("div"),b.className="aia-stack",b.style.setProperty("--aia-stack-space","8px"),n.appendChild(b));let y=u||o&&a,m=b.querySelector(".magicx-aia-pill-bar");y?(m||(m=document.createElement("div"),m.className="magicx-aia-pill-bar aia-cluster",m.setAttribute("data-nowrap",""),m.setAttribute("data-aia-pillbar",""),b.insertBefore(m,b.firstChild)),te(m,s,0,c,!0,o,d)):m&&m.remove();let g=e.suggestions[0],x=g?`${g.type} ${g.text}`:"";Ke(b,t,i,l,p,e.listboxId,o,x);let S=b.querySelector(".magicx-aia-skeleton-bars");if(o&&!f){if(!S){S=document.createElement("div"),S.className="magicx-aia-skeleton-bars",S.setAttribute("data-aia-skeleton-bars","");for(let Je of Pt){let de=document.createElement("span");de.className="magicx-aia-skeleton-bar",de.style.width=`${Je}px`,S.appendChild(de)}b.appendChild(S)}}else S&&S.remove();let P=b.querySelector(".magicx-aia-footer")??Ct(),A=i>=0&&!!t[i]?.is_tappable;vt(P,Z(A,e.isInputEmpty)),b.lastElementChild!==P&&b.appendChild(P)}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 Ct(){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=J(),o.target="_blank",o.rel="noopener noreferrer",o.style.setProperty("--aia-cluster-gap","2px");let s=document.createElement("span");s.className="magicx-aia-footer-brand",s.textContent="AI";let a=document.createElement("span");return a.className="magicx-aia-footer-badge",a.textContent="Autocomplete",o.append(s,a),e.append(t,o),n.append(e),n}function Ue(n,e){let t=ne(e.listboxId);return n.appendChild(t),{dropdown:t}}function he(n,e,t){ie(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,onSelect:t.selectOption,onHighlight:i=>t.store.set({activeDropdownIndex:i}),onPillClick:t.setActivePill})}function re(n){let{input:e,segments:t,newParamId:i,editingParamId:r,placeholderText:o,isFocused:s}=n,a=t.length===0;e.dataset.aiaEmpty=a?"true":"false",a&&o?e.dataset.placeholder=o:delete e.dataset.placeholder;let d=t.map(y=>`${y.type}:${y.value}`).join("\0"),l=e.dataset.segKey??"",p=e.dataset.newParamId??"",c=e.dataset.editingParamId??"";if(d===l&&(i??"")===p&&(r??"")===c)return;let u=s?w(e):null;e.dataset.segKey=d,e.dataset.newParamId=i??"",e.dataset.editingParamId=r??"";let f=e.ownerDocument??document,h=f.createDocumentFragment(),b=0;for(let y of t)if(b+=y.value.length,y.type==="completed"){let m=f.createElement("strong");m.dataset.seg="completed",m.dataset.paramId=y.param.id;let g=y.param.id===i,x=y.param.id===r,S=["magicx-aia-segment","magicx-aia-segment--completed"];g&&S.push("magicx-aia-shimmer-revealed","magicx-aia-shimmer-sweep"),x&&S.push("magicx-aia-segment--editing"),m.className=S.join(" "),m.textContent=y.value,h.appendChild(m)}else if(y.type==="identified"){let m=f.createElement("strong");m.dataset.seg="identified",m.dataset.paramId=y.param.id,m.className="magicx-aia-segment magicx-aia-segment--completed",m.textContent=y.value,h.appendChild(m)}else h.appendChild(f.createTextNode(y.value));e.replaceChildren(h),e.dataset.aiaTextLength=String(b),u!=null&&C(e,Math.max(0,Math.min(u,b)))}var wt='<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 $e(){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=wt,n}function Tt(){let n=document.createElement("div");return n.setAttribute("contenteditable","plaintext-only"),n.contentEditable==="plaintext-only"}function Qe(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 qe(n,e){let{listboxId:t}=e,i=ne(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 s=document.createElement("div");s.className="magicx-aia-input",s.setAttribute("data-aia-input",""),s.setAttribute("contenteditable",Tt()?"plaintext-only":"true"),s.setAttribute("role","combobox"),s.setAttribute("aria-autocomplete","list"),s.setAttribute("aria-haspopup","listbox"),s.setAttribute("aria-controls",t),s.setAttribute("aria-expanded","false"),s.setAttribute("spellcheck","true"),s.setAttribute("enterkeyhint","send"),o.appendChild(s);let a=document.createElement("span");a.className="magicx-aia-pill-list-container",a.setAttribute("data-aia-pill-list-container",""),o.appendChild(a);let d=null,l=null;e.submitButton===void 0?(d=$e(),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 p=new AbortController,{signal:c}=p,u=!1,f=0,h=()=>{let m=N(s),x=m.length>0&&m[0]!==m[0].toUpperCase()?m[0].toUpperCase()+m.slice(1):m;e.handleChange(x)},b=()=>{let m=(s.ownerDocument??document).getSelection();if(!m||m.rangeCount===0)return null;let g=m.anchorNode;return!g||!s.contains(g)?null:(g.nodeType===Node.ELEMENT_NODE?g:g.parentElement)?.closest('strong[data-seg="completed"][data-param-id]')?.dataset.paramId??null};r.addEventListener("click",m=>{m.target?.closest("[data-aia-pill]")||s.focus()},{signal:c}),s.addEventListener("input",()=>{u||(f=performance.now(),h(),e.handleCaretAfterInput(w(s)))},{signal:c});let y=s.ownerDocument??document;if(y.addEventListener("selectionchange",()=>{let m=y.getSelection();if(!m||m.rangeCount===0||!s.contains(m.anchorNode))return;let g=b(),x=e.store.get().editingParam?.id??null;if(g&&g!==x){e.startEditingParam(g);return}performance.now()-f<50||e.handleCaretMove(w(s))},{signal:c}),s.addEventListener("compositionstart",()=>{u=!0},{signal:c}),s.addEventListener("compositionend",()=>{u=!1,h()},{signal:c}),s.addEventListener("beforeinput",m=>{let g=m,x=g.inputType;if(x==="insertParagraph"||x==="insertLineBreak"||x==="insertFromDrop"){m.preventDefault();return}if(x.startsWith("insert")||x.startsWith("delete")){let S=x.startsWith("delete")?"":g.data??"";e.replaceEditingRange(S)&&m.preventDefault()}},{signal:c}),s.addEventListener("paste",m=>{m.preventDefault();let g=(m.clipboardData?.getData("text/plain")??"").replace(/\r?\n/g," ");if(!g)return;let x=s.ownerDocument??document,S=x.getSelection();if(!S||S.rangeCount===0)return;let P=S.getRangeAt(0);if(!s.contains(P.startContainer))return;P.deleteContents();let A=x.createTextNode(g);P.insertNode(A),P.setStartAfter(A),P.collapse(!0),S.removeAllRanges(),S.addRange(P),h()},{signal:c}),s.addEventListener("keydown",m=>e.handleKeyDown(m),{signal:c}),s.addEventListener("focus",()=>e.store.set({isFocused:!0}),{signal:c}),s.addEventListener("blur",()=>e.store.set({isFocused:!1}),{signal:c}),l&&l.addEventListener("click",m=>{let g=e.store.get();!(g.text||g.completedParams.length>0)||!e.onSubmit||(m.stopPropagation(),e.onSubmit(M(g.text,g.completedParams,g.skippedParams)),e.afterSubmit?.())},{signal:c}),e.autoFocus!==!1){s.focus();let m=s.ownerDocument??document,g=m.getSelection(),x=g&&g.rangeCount>0&&s.contains(g.anchorNode);if(g&&!x){let S=m.createRange();S.selectNodeContents(s),S.collapse(!0),g.removeAllRanges(),g.addRange(S)}}if(typeof ResizeObserver<"u"){let m=new ResizeObserver(()=>Qe(s,a));m.observe(s),p.signal.addEventListener("abort",()=>m.disconnect(),{once:!0})}return{input:s,inlinePillContainer:a,dropdown:i,submitButton:d,abort:p}}function be(n,e,t){let{input:i,inlinePillContainer:r,dropdown:o,submitButton:s}=n,{pillPlacement:a,setActivePill:d,selectOption:l,store:p}=t;i.setAttribute("aria-expanded",String(e.isDropdownOpen));let c=e.activeDropdownIndex>=0?`${t.listboxId}-option-${e.activeDropdownIndex}`:"";if(c?i.setAttribute("aria-activedescendant",c):i.removeAttribute("aria-activedescendant"),s){let y=!!e.text||e.completedParams.length>0;s.disabled=!y}let u=i.dataset.newParamId??"",f=e.newParamId!==null&&e.newParamId!==u;if(re({input:i,segments:e.segments,newParamId:e.newParamId,editingParamId:e.editingParam?.id??null,placeholderText:e.placeholderText,isFocused:e.isFocused}),a==="inline"){let y=e.isLoading&&!e.editingParam&&!e.inSelectionAnimation;y||e.actionableSuggestions.length>0?te(r,e.actionableSuggestions,0,d,!1,y,e.isActivePillSelected):fe(r)}else fe(r);Qe(i,r),f?(i.focus(),C(i,e.caretOffset??e.text.length)):e.isFocused&&N(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,b=h??e.actionableSuggestions[0];ie(o,{suggestions:b?[{...b,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:a==="dropdown",isActivePillSelected:e.isActivePillSelected,isInputEmpty:e.text.trim().length===0,onSelect:l,onHighlight:y=>p.set({activeDropdownIndex:y}),onPillClick:d})}function Ge(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,s=r.length===0&&n.text.length>0&&n.placeholderText.length>0&&n.placeholderText.toLowerCase().startsWith(n.text.toLowerCase());(o||s)&&n.placeholderText&&(r=`${n.placeholderText} `);let a=Ce(r,e.text);a>0&&(r=r.slice(0,r.length-a));let d=r.length>0&&r[r.length-1]!==" ",l=`${r}${d?" ":""}${e.text} `,p=(o||s)&&l.length>0?l[0].toUpperCase()+l.slice(1):l,c=p.toLowerCase().lastIndexOf(e.text.toLowerCase()),u=c>=0?p.slice(c,c+e.text.length):e.text,f={id:crypto.randomUUID(),placeholder:"",type:t.type,text:u,kind:e.kind,suggestionType:t.type,suggestionPlaceholder:t.text,options:t.options??[],metadata:e.metadata},h=n.actionableSuggestions.length-1;return{patch:{text:p,filterBase:p.length,completedParams:[...n.completedParams,f],newParamId:f.id,caretOffset:p.length,pillTapped:!1,activeDropdownIndex:-1,skipNextFetch:h>0,inSelectionAnimation:!0,pendingSpan:null},telemetry:{selectedOption:e.text,otherOptions:n.filteredOptions.filter(b=>b.text!==e.text).map(b=>b.text)},consumedSuggestion:t,remainingActionable:h}}function oe(n){let e=n,t=new Set,i=[],r=!1;return{get:()=>e,set:o=>{let s=typeof o=="function"?o(e):o,a=e;if(e={...e,...s},i.push([e,a]),!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[p,c]=l;for(let u of t)u(p,c)}}catch(d){throw i.length=0,d}finally{r=!1}}},subscribe:o=>(t.add(o),()=>{t.delete(o)})}}function We(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(s=>{let a={...s,...r(s)};return o(a)}):n.set(o)},peek:o=>{let s={...n.get(),...o};return{...s,...e(s)}},subscribe:o=>n.subscribe((s,a)=>{let d={...a,...r(a)},l={...s,...r(s)};o(l,d)})}}var xe=!1;function je(){if(xe||typeof document>"u")return;if(document.querySelector("style[data-magicx-aia]")){xe=!0;return}xe=!0;let n=document.createElement("style");n.setAttribute("data-magicx-aia",""),n.textContent=Et,document.head.appendChild(n)}var Et=`@layer layout {
|
|
2
2
|
.aia-stack {
|
|
3
3
|
display: flex;
|
|
4
4
|
flex-direction: column;
|
|
@@ -1186,5 +1186,5 @@
|
|
|
1186
1186
|
animation-duration: 0s !important;
|
|
1187
1187
|
transition-duration: 0s !important;
|
|
1188
1188
|
}
|
|
1189
|
-
`;var re=class{constructor(){this.listeners={}}on(e,t){let i=(...s)=>t(...s),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var oe=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 M=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 wt(n){return(n??N).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function Tt(n){return k(n)?`Bearer ${await _(n).getToken()}`:H(n)}async function Ge(n){try{let e=wt(n.apiConfig?.endpoint),t=F(n.apiConfig),i=await Tt(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 Et="newParam",We="suggestionRemoval",It="selectionAnimation",At=650,Ot=0;function Dt(){return`:ac-${++Ot}:`}var je=500;function Ve(){return{text:"",completedParams:[],identifiedParams:[],pendingSpan:null,suggestions:[],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 se=class{constructor(e,t={}){this.inputStore=ie(Ve());this._listboxId=Dt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new oe;this.emitter=new re;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=Qe(this.inputStore,i=>Le(i,this.opts)),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.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:s})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:s})}}),this.reEdit=new z({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new K(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:s})=>{this.fireTelemetry("option",{raw_query:s,selected_option:r.text,other_options:(i.options??[]).filter(o=>o.text!==r.text).map(o=>o.text)})}}),this.keyboardController=new W(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),exitEditMode:()=>this.exitEditMode()}),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:s,invalid:o}=B(i.text,i.completedParams,i.identifiedParams);o.length>0&&this.store.set({identifiedParams:s})})),this.unsubscribers.push(this.store.subscribe((i,r)=>{let s=i.pendingSpan;if(!s||i.text===r.text&&i.completedParams===r.completedParams&&i.identifiedParams===r.identifiedParams)return;let o=s.anchor;if(i.text!==r.text){let d=Te(r.text,i.text,o);if(d===null){this.store.set({pendingSpan:null});return}o=d}i.text.slice(o).trim().length===0||Ce(i.segments,o)?this.store.set({pendingSpan:null}):o!==s.anchor&&this.store.set({pendingSpan:{anchor:o,snapshot:s.snapshot}})})),this.renderMode!=="headless"&&(qe(),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({...Ve(),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()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,s=0;for(let o=0;o<r.length;o++){let a=r[o],d=i.indexOf(a.text,s);if(d===-1)continue;let l=d,p=d+a.text.length;if(e>l&&e<=p){let c=G(i,e),u=i.slice(0,c)+i.slice(e),f=r.filter((h,b)=>b!==o);return this.store.set(h=>({text:u,filterBase:Math.min(h.filterBase,u.length),completedParams:f,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(c),!0}s=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),C(t.input,e)):this.opts.setCursor?.(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})}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){return this.store.subscribe(t=>e(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){Object.assign(this.opts,e),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=$e(t,e);if(i&&(this.fireTelemetry("option",{raw_query:P(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(We),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(We,()=>{this.store.set(s=>({suggestions:s.suggestions.filter(o=>o!==r)}))},je)}}startSelectionAnimationTimer(){this.timers.schedule(It,()=>this.store.set({inSelectionAnimation:!1}),je)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ge({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}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 M(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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=Ue(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&ge(this.domRefs,this.store.get(),t)}),ge(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=He(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&me(this.dropdownRefs,this.store.get(),e)}),me(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}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(Et,()=>this.store.set({newParamId:null}),At)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=Ae(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=Pe(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(a=>a.id===e.editingParam?.id))return;let t=e.caretOffset??e.editingAnchor,i=e.text.slice(e.editingAnchor,t);if(I(e.editingParam.options,i).some(a=>a.is_tappable))return;this.reEdit.exit();let{rawQuery:s,completedParams:o}=P(e.text,e.completedParams);this.fetchController.doFetch(s,o)}maybePromoteExactMatch(e){let t=this.store.get(),i=V({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,buildAttributionUrl,buildQuery,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset});
|
|
1189
|
+
`;var se=class{constructor(){this.listeners={}}on(e,t){let i=(...o)=>t(...o),r=this.listeners[e];return r||(r=new Set,this.listeners[e]=r),r.add(i),()=>{this.listeners[e]?.delete(i)}}emit(e,...t){let i=this.listeners[e];if(i)for(let r of i)r(...t)}hasListeners(e){return(this.listeners[e]?.size??0)>0}clear(){this.listeners={}}};var ae=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 L=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 It(n){return(n??F).replace(/\/suggest(\?|#|$)/,"/telemetry/events$1")}async function At(n){return R(n)?`Bearer ${await H(n).getToken()}`:K(n)}async function Ve(n){try{let e=It(n.apiConfig?.endpoint),t=B(n.apiConfig),i=await At(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 Ot="newParam",Xe="suggestionRemoval",kt="selectionAnimation",Dt=650,Mt=0;function Lt(){return`:ac-${++Mt}:`}var ze=500;function Ye(){return{text:"",completedParams:[],identifiedParams:[],skippedParams:[],pendingSpan:null,suggestions:[],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 le=class{constructor(e,t={}){this.inputStore=oe(Ye());this._listboxId=Lt();this.modeController=null;this.unsubscribers=[];this.domRefs=null;this.dropdownRefs=null;this.timers=new ae;this.emitter=new se;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=We(this.inputStore,i=>_e(i,this.opts)),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.value!==void 0&&this.store.set({text:t.value}),t.completedParams!==void 0&&this.store.set({completedParams:t.completedParams}),this.pillsController=new X(this.store,{onPillSelected:({rawQuery:i,selectedPill:r,otherPills:o})=>{this.fireTelemetry("pill",{raw_query:i,selected_pill:r,other_pills:o})}}),this.reEdit=new Y({store:this.store,scheduleSetCursor:i=>this.scheduleSetCursor(i),fireTelemetry:(i,r)=>this.fireTelemetry(i,r),startSelectionAnimationTimer:()=>this.startSelectionAnimationTimer()}),this.fetchController=new $(this.store,()=>this.opts.apiConfig,()=>this.opts.optionOverrides,()=>this.opts.maskCompletedText,()=>this.emitter.hasListeners("error")?this.emitError:void 0,()=>this.sessionId,{onAutoMatch:({active:i,matched:r,rawQuery:o})=>{this.fireTelemetry("option",{raw_query:o,selected_option:r.text,other_options:(i.options??[]).filter(s=>s.text!==r.text).map(s=>s.text)})}}),this.keyboardController=new V(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),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:s}=U(i.text,i.completedParams,i.identifiedParams);s.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 s=o.anchor;if(i.text!==r.text){let d=Ae(r.text,i.text,s);if(d===null){this.store.set({pendingSpan:null});return}s=d}i.text.slice(s).trim().length===0||Ee(i.segments,s)?this.store.set({pendingSpan:null}):s!==o.anchor&&this.store.set({pendingSpan:{anchor:s,snapshot:o.snapshot}})})),this.renderMode!=="headless"&&(je(),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({...Ye(),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()}removeParamAtCaret(e){let t=this.store.get(),{text:i,completedParams:r}=t,o=0;for(let s=0;s<r.length;s++){let a=r[s],d=i.indexOf(a.text,o);if(d===-1)continue;let l=d,p=d+a.text.length;if(e>l&&e<=p){let c=j(i,e),u=i.slice(0,c)+i.slice(e),f=r.filter((h,b)=>b!==s);return this.store.set(h=>({text:u,filterBase:Math.min(h.filterBase,u.length),completedParams:f,pillTapped:!1,activeDropdownIndex:-1})),this.scheduleSetCursor(c),!0}o=p}return!1}scheduleSetCursor(e){queueMicrotask(()=>{let t=this.domRefs;t?(t.input.focus(),C(t.input,e)):this.opts.setCursor?.(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})}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){return this.store.subscribe(t=>e(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){Object.assign(this.opts,e),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=Ge(t,e);if(i&&(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(Xe),i.remainingActionable>0)){let r=i.consumedSuggestion;this.timers.schedule(Xe,()=>{this.store.set(o=>({suggestions:o.suggestions.filter(s=>s!==r)}))},ze)}}startSelectionAnimationTimer(){this.timers.schedule(kt,()=>this.store.set({inSelectionAnimation:!1}),ze)}fireTelemetry(e,t){let i=this.opts.source??(this.renderMode==="full"?"full-sdk":"headless-sdk");Ve({source:i,sessionId:this.sessionId,type:e,queryData:t,apiConfig:this.opts.apiConfig})}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 L(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:i=>this.selectOption(i),setActivePill:i=>this.pillsController.setActivePill(i),handleKeyDown:i=>this.keyboardController.handleKeyDown(i),handleChange:i=>this.handleChange(i),startEditingParam:i=>this.startEditingParam(i),handleCaretAfterInput:i=>this.handleCaretAfterInput(i),handleCaretMove:i=>this.handleCaretMove(i),replaceEditingRange:i=>this.replaceEditingRange(i)};this.domRefs=qe(this.container,t),this.subscribeBatchedRender(()=>{this.domRefs&&be(this.domRefs,this.store.get(),t)}),be(this.domRefs,this.store.get(),t),this.subscribeNewParamTimer()}buildAndRenderDropdown(){let e={store:this.store,listboxId:this.listboxId,selectOption:t=>this.selectOption(t),setActivePill:t=>this.pillsController.setActivePill(t)};this.dropdownRefs=Ue(this.container,e),this.subscribeBatchedRender(()=>{this.dropdownRefs&&he(this.dropdownRefs,this.store.get(),e)}),he(this.dropdownRefs,this.store.get(),e),this.subscribeNewParamTimer()}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(Ot,()=>this.store.set({newParamId:null}),Dt)}))}handleChange(e){let t=this.store.get();this.store.set({text:e,pillTapped:!1,activeDropdownIndex:-1});let{valid:i,invalid:r}=De(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=Te(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);I(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=z({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,SKIPPED_PARAM_TEXT,buildAttributionUrl,buildQuery,buildSubmitResult,createStore,cursorIsAtEnd,extractPlainText,getCursorOffset,getFooterHint,plainTextLength,previousGraphemeBoundary,renderEditableContent,setCursorOffset,withSkippedParams});
|
|
1190
1190
|
//# sourceMappingURL=index.js.map
|