@smart-cloud/ai-kit-ui 1.3.4 → 1.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(Ae?`
31
- Follow these additional instructions: ${Ae}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),Z=await I.run(async({signal:X,onStatus:ue})=>(await(0,G.prompt)({messages:Y,images:[oe],outputLanguage:"en",responseConstraint:cr},{signal:X,onStatus:ue,context:x,modeOverride:i,onDeviceTimeoutOverride:n})).result);if(!Z){M("");return}let le=(B&&B!=="auto"?B:null)||dt(),J=wt(Z).trim();try{re("Translating result...");let X=await I.run(async({signal:ue})=>await mr(J,le,{signal:ue,context:x,modeOverride:i,onDeviceTimeoutOverride:n,silent:!0}));M(X)}catch(X){M(J),console.warn("AI Kit: failed to parse SEO JSON",X)}break}}}catch(v){Me(v instanceof Error?v.message:r.I18n.get("An unknown error occurred."))}re(void 0)}},[W,I,Ae,ve,B,fe,je,x,m,ke,Ve,Re,Te]),tt=(0,K.useCallback)(async()=>{await xe("backend-only")},[xe]),yt=(0,K.useCallback)(i=>{switch(m){case"proofread":return(0,c.jsx)($e.IconCircleDashedCheck,{className:i});case"translate":return(0,c.jsx)($e.IconLanguage,{className:i});case"summarize":return(0,c.jsx)($e.IconSum,{className:i});case"rewrite":case"write":return(0,c.jsx)($e.IconPencilCode,{className:i});case"generateImageMetadata":case"generatePostMetadata":return(0,c.jsx)($e.IconSeo,{className:i});default:return(0,c.jsx)(G.AiKitFeatureIcon,{mode:m,className:i})}},[m]),At=(0,K.useCallback)(()=>{switch(m){case"proofread":return I.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return I.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return I.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return I.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return I.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[W,I.lastSource,m]),R=(0,K.useCallback)(()=>{switch(m){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[W,m]),O=(0,K.useCallback)(async()=>{Qe(!1),M(null),Me(null),Q.current=!1,I.reset(),H||he()},[he,Q,I,H]),V=(0,K.useCallback)(async()=>{I.busy&&I.cancel()},[I.busy]);(0,K.useEffect)(()=>{!ge||!g||!Re||I.busy||U||Q.current||(Q.current=!0,queueMicrotask(()=>{xe(ye)}))},[I.busy,Q,ge,Re,g,U,xe,ye]),(0,K.useEffect)(()=>{Te&&m!=="proofread"&&(Re||(Ne(!0),Q.current=!0))},[Te,Re,m]),(0,K.useEffect)(()=>{let i=!0;return(async()=>{try{await(0,G.waitForAiKitReady)();let v=await an();i&&Fe(v)}catch(v){console.error(v),i&&Fe(!1)}})(),()=>{i=!1}},[]);let we=(0,K.useMemo)(()=>{let i=[];if(m==="translate"){let v=G.LANGUAGE_OPTIONS.find(Y=>Y.value===Ve)?.label;i.push(r.I18n.get("Input language")+": "+(v?r.I18n.get(v):"auto"))}if(B&&D?.outputLanguage){let v=G.LANGUAGE_OPTIONS.find(Y=>Y.value===B)?.label;i.push(r.I18n.get("Output language")+": "+(v?r.I18n.get(v):B))}return m==="summarize"&&ke&&D?.type&&i.push(r.I18n.get("Type")+": "+r.I18n.get(ke)),(m==="write"||m==="rewrite")&&je&&D?.tone&&i.push(r.I18n.get("Tone")+": "+r.I18n.get(je)),(m==="write"||m==="rewrite"||m==="summarize")&&ve&&D?.length&&i.push(r.I18n.get("Length")+": "+r.I18n.get(ve)),Ae?.trim()&&D?.instructions&&i.push(r.I18n.get("Instructions")+": \u2713"),i.length?i.join(" \u2022 "):r.I18n.get("No overrides")},[W,m,Ve,B,ke,je,ve,Ae]),F={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},se=p==="modal"?f.Modal.Root:f.Group,me=p==="modal"?f.Modal.Content:f.Group,be=p==="modal"?f.Modal.Body:f.Group,ft=L==="collapse"?f.Collapse:f.Stack,st=L==="horizontal"?f.Group:f.Stack;return(0,K.useEffect)(()=>{if(!(p!=="modal"||!ge))return document.body.style.overflow="hidden",document.body.onkeydown=i=>{i.key==="Escape"&&(i.preventDefault(),O())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[O,p]),(0,c.jsxs)(c.Fragment,{children:[H&&(0,c.jsx)(f.Button,{leftSection:ne&&(ae?(0,c.jsx)("span",{dangerouslySetInnerHTML:{__html:ae}}):yt()),className:te?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ge,onClick:()=>Qe(!0),"data-ai-kit-open-button":!0,children:te&&r.I18n.get(E||ht)}),ge&&(0,c.jsxs)(se,{opened:!0,className:"ai-feature-root",onClose:O,padding:"md",gap:"md",size:"md",portalProps:p==="modal"?{target:ze,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Be,"data-ai-kit-variation":p,children:[p==="modal"&&(0,c.jsx)(f.Modal.Overlay,{}),(0,c.jsxs)(me,{w:"100%",style:{left:0},children:[p==="modal"&&(0,c.jsxs)(f.Modal.Header,{style:{zIndex:1e3},children:[yt("ai-feature-title-icon"),(0,c.jsx)(f.Modal.Title,{children:r.I18n.get(ht)}),(0,c.jsx)(f.Modal.CloseButton,{})]}),(0,c.jsx)(be,{w:"100%",style:{zIndex:1001},children:(0,c.jsxs)(Tt,{enabled:p!=="modal",working:I.busy,variation:p,children:[(0,c.jsxs)(f.Stack,{gap:"sm",mb:"sm",p:"sm",children:[Ce&&(0,c.jsx)(f.Alert,{color:"red",children:r.I18n.get(Ce)}),Te&&m!=="proofread"&&(0,c.jsxs)(f.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,c.jsxs)(f.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>Ne(i=>!i):void 0,children:[L==="collapse"&&(0,c.jsxs)(f.Stack,{gap:0,children:[(0,c.jsx)(f.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,c.jsx)(f.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:we})]}),L==="collapse"&&(0,c.jsx)(f.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:i=>{i.stopPropagation(),Ne(v=>!v)},children:at?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,c.jsxs)(ft,{in:at,children:[L==="collapse"&&(0,c.jsx)(f.Divider,{my:"sm"}),(0,c.jsxs)(st,{gap:"xs",justify:"space-between",children:[m==="write"&&D?.text&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.TextInput,{size:"xs",className:"ai-feature-option",styles:F,disabled:I.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:fe||"",onChange:i=>{let v=i.target.value;Je(v),P?.({text:v})}})}),(m==="write"||m==="rewrite"||m==="generateImageMetadata"||m==="generatePostMetadata")&&D?.instructions&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.TextInput,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:Ae||"",onChange:i=>{let v=i.target.value;mt(v),P?.({instructions:v})}})}),m==="translate"&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",styles:F,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...G.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,v)=>i.label.localeCompare(v.label))],value:Ve||"auto",onChange:i=>{let v=i;Xe(v),Ke(void 0),P?.({inputLanguage:v})}})}),D?.outputLanguage&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",styles:F,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[m==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...G.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,v)=>i.label.localeCompare(v.label))],value:B||ka.settings.defaultOutputLanguage||(m==="rewrite"?"auto":""),onChange:i=>{let v=i;rt(v),Ke(void 0),P?.({outputLanguage:v})}})}),m==="summarize"&&D?.type&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:ke||"key-points",onChange:i=>{let v=i;Ct(v),P?.({type:v})}})}),(m==="write"||m==="rewrite")&&D?.tone&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:m==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:je||(m==="write"?"neutral":"as-is"),onChange:i=>{let v=i;Pe(v),P?.({tone:v})}})}),(m==="write"||m==="rewrite"||m==="summarize")&&D?.length&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:m==="write"||m==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:ve||(m==="rewrite"?"as-is":"short"),onChange:i=>{let v=i;pt(v),P?.({length:v})}})}),m==="summarize"||m==="write"||m==="rewrite"&&D?.outputFormat&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:ie||"markdown",onChange:i=>{let v=i;et(v),P?.({outputFormat:v})}})})]})]})]}),I.busy&&it&&(0,c.jsx)(Tt,{enabled:p==="modal",working:!0,variation:p,children:(0,c.jsxs)(f.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,c.jsx)(f.Loader,{size:"sm"}),(0,c.jsx)(f.Input.Label,{className:"ai-feature-status-text",children:it})]})}),U&&(0,c.jsxs)(f.Stack,{mt:"md",children:[m==="proofread"&&(U.corrections.length===0?(0,c.jsx)(f.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,c.jsx)(ca,{original:fe,corrections:U.corrections}),U.correctedInput?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,c.jsx)(f.Group,{c:"pre",className:"ai-feature-generated-content",children:U.correctedInput})]}):null]})),m==="generateImageMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:U.alt_text||"",onChange:i=>M({...U,alt_text:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:U.title||"",onChange:i=>M({...U,title:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:U.caption||"",onChange:i=>M({...U,caption:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:U.description||"",onChange:i=>M({...U,description:i.target.value})})]}),m==="generatePostMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:U.title||"",onChange:i=>M({...U,title:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:U.excerpt||"",onChange:i=>M({...U,excerpt:i.target.value})})]}),m!=="proofread"&&m!=="generateImageMetadata"&&m!=="generatePostMetadata"&&typeof U=="string"&&(0,c.jsx)(ba,{value:U,editable:!!l,onChange:i=>{M(i)}})]}),U===""&&(0,c.jsx)(ba,{value:U,editable:!1})]}),(0,c.jsxs)(f.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[I.busy&&(0,c.jsx)(f.Button,{variant:"outline",size:"sm",onClick:V,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!I.busy&&(0,c.jsx)(f.Button,{variant:"filled",size:"sm",disabled:!Re,onClick:()=>xe(),"data-ai-kit-generate-button":!0,children:At()}),!I.busy&&I.lastSource==="on-device"&&We&&Ee&&(0,c.jsx)(f.Button,{variant:"filled",size:"sm",disabled:!Re,onClick:tt,"data-ai-kit-regenerate-on-backend-button":!0,children:R()}),!I.busy&&y&&(0,c.jsx)(f.Button,{variant:"outline",size:"sm",disabled:!U||m==="proofread"&&U.corrections.length===0,onClick:async()=>{y(ie==="html"?await qt(U):U),O()},"data-ai-kit-accept-button":!0,children:r.I18n.get(ee)}),(0,c.jsx)(f.Button,{variant:"default",size:"sm",onClick:O,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,c.jsx)(Nt,{variation:p})]})})]})]})]})};function ba(e){let{value:a,editable:g,onChange:l}=e;return g?(0,c.jsxs)(f.Stack,{p:0,gap:"sm",children:[(0,c.jsx)(f.Input.Label,{children:r.I18n.get("Generated content")}),(0,c.jsx)(f.Textarea,{value:a,onChange:n=>l?.(n.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,c.jsx)(f.Input.Label,{children:r.I18n.get("Preview")}),(0,c.jsx)(f.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,c.jsx)(ln.default,{remarkPlugins:[un.default],children:a})})]}):(0,c.jsx)(f.Stack,{className:"ai-feature-generated-content",children:a?(0,c.jsx)(ln.default,{remarkPlugins:[un.default],children:a}):(0,c.jsx)(f.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var ya=ct(hr);var h=require("@mantine/core"),pe=require("@tabler/icons-react"),zt=require("@smart-cloud/ai-kit-core"),va=require("@wordpress/data"),A=require("aws-amplify/utils"),o=require("react"),wa=He(require("react-markdown"),1),Ta=He(require("remark-gfm"),1);var fr="ai-kit-chatbot-attachments",Ze="attachments";var dn=null;function kr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function Yt(){if(!kr())return null;dn||(dn=new Promise(e=>{try{let a=window.indexedDB.open(fr,1);a.onerror=()=>e(null),a.onblocked=()=>e(null),a.onupgradeneeded=()=>{let g=a.result;g.objectStoreNames.contains(Ze)||g.createObjectStore(Ze,{keyPath:"id"})},a.onsuccess=()=>e(a.result)}catch(a){console.warn("[AiChatbot] IndexedDB is not available",a),e(null)}}));try{return await dn}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function cn(e,a){let g=await Yt();return g?new Promise((l,n)=>{try{let p=g.transaction(Ze,e),z=p.objectStore(Ze),H=a(z);p.oncomplete=()=>l(H),p.onerror=()=>n(p.error),p.onabort=()=>n(p.error)}catch(p){n(p)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function gn(e,a,g){await vr();let l={id:e,blob:a,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await cn("readwrite",p=>(p.put(l),e))}async function mn(e){let a=await Yt();return a?new Promise((g,l)=>{try{let n=a.transaction(Ze,"readonly"),p=n.objectStore(Ze).get(e);p.onsuccess=()=>{let z=p.result;g(z??null)},p.onerror=()=>l(p.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function br(e){await cn("readwrite",a=>{a.delete(e)})}async function Jt(){await cn("readwrite",e=>{e.clear()})}async function pn(e){let a=await Yt();a&&await new Promise((g,l)=>{try{let n=a.transaction(Ze,"readwrite"),p=n.objectStore(Ze),z=p.getAllKeys();z.onsuccess=()=>{let H=z.result;for(let te of H){let ne=String(te);e.has(ne)||p.delete(te)}},z.onerror=()=>l(z.error),n.oncomplete=()=>g(),n.onerror=()=>l(n.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yr=50*1024*1024;async function Ar(){let e=await Yt();return e?new Promise((a,g)=>{try{let l=e.transaction(Ze,"readonly"),n=l.objectStore(Ze).getAll();n.onsuccess=()=>{let p=n.result||[];a(p)},n.onerror=()=>g(n.error),l.onerror=()=>g(l.error),l.onabort=()=>g(l.error)}catch(l){g(l)}}).catch(a=>(console.warn("[AiChatbot] Failed to get all attachments",a),[])):[]}async function vr(){let e=await Ar();if(e.length===0)return;let a=e.sort((p,z)=>p.createdAt-z.createdAt),g=a.reduce((p,z)=>p+z.size,0),l=[],n=0;for(;g>yr&&n<a.length;){let p=a[n];p&&(l.push(p.id),g-=p.size),n++}for(let p of l)await br(p);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");A.I18n.putVocabularies(ut);var Vt=1440*60*1e3,hn=!1,wr=1,Tr="localstorage",Rt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,$t={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function gt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Sr=4,Rr=5*1024*1024,Ir=e=>{let a=(e?.name||"").toString(),g=(e?.code||"").toString(),l=(e?.message||"").toString();return a==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},zr=(e,a)=>{if(!e)return null;let g=e.step,l=A.I18n.get((e.message??"").trim()),n=typeof e.progress=="number"?e.progress:null,p=n==null?null:Math.round(n*100);switch(g){case"decide":return l||A.I18n.get("Checking capabilities...");case"on-device:init":return l||A.I18n.get("Initializing on-device AI...");case"on-device:download":return p==null?l||A.I18n.get("Downloading model..."):l||`${A.I18n.get("Downloading model...")} ${p}%`;case"on-device:ready":return l||A.I18n.get("On-device model ready...");case"on-device:run":return l||A.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return A.I18n.get(a.assistantThinkingLabel??$t.assistantThinkingLabel);case"done":return l||A.I18n.get("Done.");case"error":return l||A.I18n.get("An error occurred.");default:return l||null}};function fn(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var It=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},_t=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},Sa=e=>{!e||e.length===0||e.forEach(a=>_t(a.objectUrl))},Aa=e=>{e.forEach(a=>Sa(a.attachments))},Cr=e=>{let{rootElement:a,store:g,previewMode:l,title:n,openButtonTitle:p,openButtonIcon:z,showOpenButtonTitle:H=!0,showOpenButtonIcon:te=!0,colorMode:ne,language:E,onClose:ae,context:Ee,placeholder:ee,maxImages:L,maxImageBytes:m,historyStorage:x=Tr,emptyHistoryAfterDays:ye=wr,labels:Be,openButtonIconLayout:$="top",openButtonPosition:he="bottom-right"}=e,y=(0,o.useMemo)(()=>({...$t,...Be||{}}),[Be]),P=bt(),[W,ze]=(0,o.useState)(""),[D,Te]=(0,o.useState)([]),[w,re]=(0,o.useState)(null),[ge,Qe]=(0,o.useState)(!1),[at,Ne]=(0,o.useState)(0),We=(0,o.useRef)(null),Fe=(0,o.useRef)([]),Ce=(0,o.useRef)(null),Me=(0,o.useRef)(null),U=(0,o.useRef)(null),[M,fe]=(0,o.useState)([]),[Je,oe]=(0,o.useState)(null),[Ae,mt]=(0,o.useState)(!1),[Se,Ke]=(0,o.useState)(!1),[Ve,Xe]=(0,o.useState)(!1),[ie,et]=(0,o.useState)(!1),[B,rt]=(0,o.useState)(!0),[ve,pt]=(0,o.useState)(null),[je,Pe]=(0,o.useState)(!1),[ke,Ct]=(0,o.useState)(null),[Q,ht]=(0,o.useState)(null),[ot,Ge]=(0,o.useState)(!1),[Re,I]=(0,o.useState)(null),it=(0,o.useRef)(Re);(0,o.useEffect)(()=>{it.current=Re},[Re]);let xe=(0,o.useRef)(null),tt=(0,o.useRef)(!1),[yt,At]=(0,o.useState)(null),R=(0,o.useRef)(null),O=(0,o.useRef)(null),V=(0,o.useRef)(null),we=(0,o.useRef)(null),F=(0,o.useCallback)(t=>{t.forEach(d=>_t(d.objectUrl))},[]),se=(0,o.useCallback)(()=>{F(le.current),Te([]),R.current&&(R.current.value="")},[F]),me=(0,o.useCallback)(()=>{J.current&&_t(J.current.objectUrl),re(null),Fe.current=[],Ne(0)},[]),be=(0,o.useCallback)(async()=>{try{ze(""),me();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(t,{mimeType:"audio/webm"}),b=new AudioContext,u=b.createMediaStreamSource(t),C=b.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),Ce.current=b,Me.current=C;let T=new Uint8Array(C.fftSize),N=()=>{if(!Me.current)return;Me.current.getByteTimeDomainData(T);let _=0;for(let Ue=0;Ue<T.length;Ue++){let kt=(T[Ue]-128)/128;_+=kt*kt}let Ie=Math.sqrt(_/T.length),De=Math.min(100,Ie*200);Ne(De),U.current=requestAnimationFrame(N)};N(),Fe.current=[];let q=Date.now();d.ondataavailable=_=>{_.data.size>0&&Fe.current.push(_.data)},d.onstop=()=>{let _=new Blob(Fe.current,{type:"audio/webm"}),Ie=(Date.now()-q)/1e3,De=It(_);De&&re({id:gt("composer-audio"),blob:_,objectUrl:De,duration:Ie}),t.getTracks().forEach(Ue=>Ue.stop()),U.current&&(cancelAnimationFrame(U.current),U.current=null),Ce.current&&(Ce.current.close(),Ce.current=null),Me.current=null,Ne(0)},We.current=d,d.start(),Qe(!0)}catch(t){console.error("Failed to start recording:",t)}},[me]),ft=(0,o.useCallback)(()=>{We.current&&ge&&(We.current.stop(),Qe(!1))},[ge]);(0,o.useEffect)(()=>()=>{U.current&&cancelAnimationFrame(U.current),Ce.current&&Ce.current.close(),me()},[me]);let[st,i]=(0,o.useState)(null),v=(0,o.useRef)(W),Y=(0,o.useRef)(M),Z=(0,o.useRef)(st),le=(0,o.useRef)(D),J=(0,o.useRef)(w);(0,o.useEffect)(()=>{v.current=W},[W]),(0,o.useEffect)(()=>{le.current=D},[D]),(0,o.useEffect)(()=>{J.current=w},[w]),(0,o.useEffect)(()=>{Y.current=M},[M]),(0,o.useEffect)(()=>{Z.current=st},[st]),(0,o.useEffect)(()=>{E&&A.I18n.setLanguage(E||"en")},[E]);let X=(0,va.useSelect)(()=>(0,zt.getStoreSelect)(g).isShowChatbotPreview()),ue=(0,o.useMemo)(()=>Math.max(0,L??Sr),[L]),qe=(0,o.useMemo)(()=>Math.max(0,m??Rr),[m]),nt=M.length>0,de=(0,o.useMemo)(()=>P.busy&&Re==="chat",[P.busy,Re]),Xt=(0,o.useMemo)(()=>de?!1:W.trim().length>0||w!==null,[W,de,w]),vt=(0,o.useMemo)(()=>{let t=p||y.askMeLabel;return A.I18n.get(t)},[p,y.askMeLabel,E]),Ma=(0,o.useMemo)(()=>{let t=n||y.modalTitle;return A.I18n.get(t)},[n,y.modalTitle,E]),Pa=(0,o.useMemo)(()=>{let t=ee||y.placeholder;return A.I18n.get(t)},[ee,y.placeholder,E]),bn=(0,o.useMemo)(()=>{let t="ai-docs-ask",d=`ai-open-btn--${he}`;return`${t} ${d}`},[he]),Et=(0,o.useCallback)(()=>{let t=we.current;if(t)try{let d=window.innerHeight||document.documentElement.clientHeight,b=360,u=1e3,C=Math.floor(d*.8),T=Math.max(b,Math.min(C,u));t.style.height=`${T}px`}catch{}},[]),xt=(0,o.useCallback)(()=>{let t=Q;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[Q]),yn=(0,o.useCallback)(()=>{et(!1),Se&&Ke(!1),Xe(!1),ae?.()},[Se,ae]);(0,o.useEffect)(()=>{if(ie)return Et(),window.addEventListener("resize",Et),()=>window.removeEventListener("resize",Et)},[ie,Et]),(0,o.useEffect)(()=>{if(!(!ie||!Se))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[ie,Se,yn]);let An=(0,o.useMemo)(()=>D.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[D]);(0,o.useEffect)(()=>{nt||rt(!0)},[nt]),(0,o.useEffect)(()=>()=>{F(le.current)},[F]),(0,o.useEffect)(()=>{let t=Q;if(!t)return;let d=()=>{let b=t.scrollHeight-(t.scrollTop+t.clientHeight);rt(b<20)};return t.addEventListener("scroll",d),()=>{t.removeEventListener("scroll",d)}},[ie,Q]),(0,o.useEffect)(()=>{if(!B)return;let t=Q;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[M,P.busy,B,Q]),(0,o.useEffect)(()=>{ie||pt(null)},[ie]);let vn=(0,o.useMemo)(()=>P.busy?zr(P.statusEvent,y)||A.I18n.get("Working\u2026"):null,[P.busy,P.statusEvent,E,y]),Da=(0,o.useMemo)(()=>{for(let t=M.length-1;t>=0;t--){let d=M[t];if(d.role==="user"&&d.clientStatus==="canceled")return d.id}return null},[M]),Lt=(0,o.useCallback)(t=>{fe(d=>{let b=[...d].map((T,N)=>({m:T,i:N})).reverse().find(T=>T.m.role==="user"&&T.m.clientStatus==="pending")?.i;if(b==null)return d;let u=d.slice(),C=u[b];return u[b]={...C,clientStatus:t??void 0},u})},[fe]),Bt=(0,o.useCallback)(()=>{if(!(!P.busy||it.current!=="chat")){tt.current=!0;try{P.cancel()}catch{}Lt("canceled"),I(null),oe(null),xt()}},[P,Lt,xt]),Ea=(0,o.useCallback)(t=>{let d=le.current,b=Array.from(t.target.files||[]),u=Math.max(0,ue-d.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let T of b){if(C.length>=u)break;let N=/image\/(jpeg|png|gif|webp)/i.test(T.type),q=T.size<=qe,_=[...d,...C].some(De=>De.file.name===T.name&&De.file.size===T.size&&De.file.lastModified===T.lastModified);if(!N||!q||_)continue;let Ie=It(T);Ie&&C.push({id:gt("composer-image"),file:T,objectUrl:Ie})}C.length&&Te(T=>[...T,...C]),t.currentTarget.value=""},[ue,qe]),Ba=(0,o.useCallback)(t=>{Te(d=>{if(t<0||t>=d.length)return d;let b=d[t];return b&&_t(b.objectUrl),d.filter((u,C)=>C!==t)})},[]),lt=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(Je)return lt.current&&(window.clearTimeout(lt.current),lt.current=null),lt.current=window.setTimeout(()=>{oe(null),lt.current=null},6e3),()=>{lt.current&&(window.clearTimeout(lt.current),lt.current=null)}},[Je]);let wn=(0,o.useCallback)(async(t,d)=>{let b=x!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async T=>{let N=gt("attachment-image"),q;if(b)try{q=await gn(N,T.file,{name:T.file.name,type:T.file.type,size:T.file.size})??void 0}catch(Ie){console.warn("[AiChatbot] Failed to persist image",Ie)}let _=It(T.file);return{id:N,name:T.file.name,type:T.file.type||"application/octet-stream",size:T.file.size,blobId:q,objectUrl:_??void 0,blob:T.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(d){let C=gt("attachment-audio"),T;if(b)try{T=await gn(C,d.blob,{name:`audio-${Date.now()}.webm`,type:d.blob.type,size:d.blob.size})??void 0}catch(q){console.warn("[AiChatbot] Failed to persist audio",q)}let N=It(d.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:d.blob.type||"audio/webm",size:d.blob.size,blobId:T,objectUrl:N??void 0,blob:d.blob,duration:d.duration,mediaType:"audio"})}return u},[x]),Tn=(0,o.useCallback)(async t=>{let d=[];for(let b of t){let u;if(b.attachments&&b.attachments.length>0){u=[];for(let C of b.attachments){let T;if(C.blobId)try{T=(await mn(C.blobId))?.blob??void 0}catch(q){console.warn("[AiChatbot] Failed to hydrate attachment",q)}if(!T)continue;let N=T?It(T):null;u.push({...C,objectUrl:N??void 0,blob:T??void 0})}}d.push({...b,attachments:u})}return d},[]),Sn=(0,o.useCallback)(async t=>{if(!t||t.length===0){se();return}let d=[];for(let b of t){let u=b.blob;if(!u&&b.blobId)try{u=(await mn(b.blobId))?.blob??void 0}catch(N){console.warn("[AiChatbot] Failed to reload attachment",N)}if(!u)continue;let C=u instanceof File?u:new File([u],b.name||"attachment",{type:b.type||u.type||"application/octet-stream"}),T=It(C);if(T&&(d.push({id:gt("composer-image"),file:C,objectUrl:T}),d.length>=ue))break}if(d.length===0){se();return}Te(b=>(F(b),d)),R.current&&(R.current.value="")},[se,F,ue]),en=(0,o.useCallback)((t,d)=>{t&&pt({url:t,title:d})},[]),Ka=(0,o.useCallback)(()=>{pt(null)},[]),Rn=(0,o.useCallback)(()=>{Aa(Y.current),se(),me(),fe([]),oe(null),V.current=null,i(null),rt(!0),mt(!1);let t=fn(x);if(t)try{t.removeItem(Rt)}catch{}Jt()},[se,me,x]),Ua=(0,o.useCallback)(()=>{mt(!0)},[]),Oa=(0,o.useCallback)(()=>{P.busy&&it.current==="chat"&&Bt(),Rn()},[P.busy,Bt,Rn]),In=(0,o.useCallback)(()=>{mt(!1)},[]),zn=(0,o.useCallback)(async(t,d)=>{if(!P.busy)try{let b=V.current&&Date.now()-V.current.storedAt<ye*Vt?V.current.id:void 0;if(!b)return;I("feedback"),oe(null),await P.run(async({signal:u,onStatus:C})=>(await(0,zt.sendFeedbackMessage)({sessionId:b,feedbackMessageId:t,feedbackType:d},{signal:u,onStatus:C,context:Ee}),null)),oe(null)}catch(b){let u=b?.message?.trim()||A.I18n.get("An error occurred.");oe(u),console.error("Failed to send feedback",b)}finally{I(b=>b==="feedback"?null:b)}},[P,E]),Cn=(0,o.useCallback)((t,d)=>{fe(b=>b.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===d?{...u,feedback:void 0}:{...u,feedback:d})),zn(t,d)},[zn]),Kt=(0,o.useCallback)(async()=>{let t=v.current.trim(),d=J.current;if(!t&&!d||P.busy)return;tt.current=!1,oe(null),I("chat");let b=[...le.current],u=await wn(b,d),C=gt("user"),T=Date.now(),N={id:C,role:"user",content:t||(d?"[Audio message]":""),createdAt:T,clientStatus:"pending",attachments:u.length?u:void 0};ze(""),se(),me(),fe(q=>[...q,N]),ie||et(!0),xt();try{let q=V.current&&Date.now()-V.current.storedAt<ye*Vt?V.current.id:void 0,_=await P.run(async({signal:De,onStatus:Ue})=>await(0,zt.sendChatMessage)({sessionId:q,message:t||void 0,audio:d?.blob,images:b.map($a=>$a.file)},{signal:De,onStatus:Ue,context:Ee}));if(tt.current){Lt("canceled");return}if(!_)throw new Error(A.I18n.get(P.error??y.emptyResponseLabel));_.sessionId&&(V.current={id:_.sessionId,storedAt:Date.now()});let Ie={id:_.metadata?.messageId||gt("assistant"),role:"assistant",content:_.result||"",citations:_.citations,createdAt:Date.now()};fe(De=>[...De.map(kt=>kt.id===C?{...kt,clientStatus:void 0}:kt),Ie]),i(T)}catch(q){if(console.error("Error during ask()",q),tt.current||Ir(q)){Lt("canceled");return}let _=q?.message?.trim()||A.I18n.get(y.unexpectedErrorLabel);fe(Ie=>[...Ie.map(Ue=>Ue.id===C?{...Ue,clientStatus:void 0}:Ue),{id:gt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${_}`,createdAt:Date.now()}]),i(T)}finally{I(q=>q==="chat"?null:q),tt.current=!1,O.current&&O.current.focus(),xt()}},[P,wn,se,me,ie,xt,Lt,y.emptyResponseLabel,y.unexpectedErrorLabel,E]),Na=(0,o.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Xt&&Kt())},[Kt,Xt]),ja=(0,o.useCallback)(()=>{et(!0)},[]);(0,o.useEffect)(()=>()=>{xe.current!=null&&(cancelAnimationFrame(xe.current),xe.current=null)},[]);let Ga=(0,o.useCallback)(()=>{Ke(t=>{let d=!t;return xe.current!=null&&(cancelAnimationFrame(xe.current),xe.current=null),d?(Xe(!0),requestAnimationFrame(()=>{xe.current=requestAnimationFrame(()=>{Xe(!1),xe.current=null})})):Xe(!1),d})},[]),Ha=(0,o.useCallback)(t=>{ze(t.content),(async()=>(await Sn(t.attachments),fe(d=>d.filter(b=>b.id!==t.id)),Sa(t.attachments),queueMicrotask(()=>O.current?.focus())))()},[Sn]),xn=(0,o.useMemo)(()=>te?z?(0,s.jsx)("img",{src:z,className:"ai-open-btn-icon",alt:A.I18n.get(y.askMeLabel||vt)}):(0,s.jsx)(pe.IconMessage,{size:18}):null,[te,z,y,vt,E]),Wa=(0,o.useMemo)(()=>{let t=xn,d=H?(0,s.jsx)(h.Text,{inherit:!0,children:vt}):null;if(!te&&!d)return null;if(!te)return d;if(!H)return t;switch($){case"top":return(0,s.jsxs)(h.Stack,{gap:4,align:"center",children:[t,d]});case"bottom":return(0,s.jsxs)(h.Stack,{gap:4,align:"center",children:[d,t]});case"right":return(0,s.jsxs)(h.Group,{gap:6,align:"center",children:[d,t]});default:return(0,s.jsxs)(h.Group,{gap:6,align:"center",children:[t,d]})}},[xn,te,H,vt,$]),Fa=(0,o.useMemo)(()=>de,[de]),qa=(0,o.useMemo)(()=>!de,[de]),Ya=(0,o.useMemo)(()=>Je||(nt?A.I18n.get(y.readyLabel):A.I18n.get(y.readyEmptyLabel)),[Je,nt,y.readyLabel,y.readyEmptyLabel,E]),Ja=(0,o.useMemo)(()=>de?A.I18n.get(y.cancelLabel):A.I18n.get(y.sendLabel),[de,y.cancelLabel,y.sendLabel,E]),Va=(0,o.useMemo)(()=>de?(0,s.jsx)(pe.IconPlayerStop,{size:18}):(0,s.jsx)(pe.IconSend,{size:18}),[de]),_a=(0,o.useCallback)(()=>{if(de){Bt();return}Kt()},[de,Bt,Kt]);return(0,o.useEffect)(()=>{if(!ie||!ke||!Q)return;let t=()=>{let q=window.getComputedStyle(Q).overflowY,_=q==="auto"||q==="scroll",Ie=Math.ceil(Q.scrollHeight),De=Math.floor(Q.clientHeight),Ue=Ie>De;return _&&Ue},d=!1,b=N=>{if(!t())return;N.preventDefault();let q=Q.scrollHeight-Q.clientHeight;Q.scrollTop=Math.max(0,Math.min(q,Q.scrollTop+N.deltaY))},u=()=>{let N=t();Ge(N),N!==d&&(d=N,d?ke.addEventListener("wheel",b,{passive:!1}):ke.removeEventListener("wheel",b))};u();let C=new ResizeObserver(u);C.observe(Q);let T=new MutationObserver(u);return T.observe(Q,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{d&&ke.removeEventListener("wheel",b),C.disconnect(),T.disconnect(),window.removeEventListener("resize",u)}},[ie,ke,Q]),(0,o.useEffect)(()=>{let t=!1,d=fn(x);if(!d){x==="nostorage"&&Jt(),Pe(!0);return}return(async()=>{try{let b=d.getItem(Rt);if(!b){Pe(!0);return}let u=JSON.parse(b),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>ye*Vt){d.removeItem(Rt),await Jt(),Pe(!0);return}let N=(Array.isArray(u.messages)?u.messages:[]).map(_=>_?.role==="user"&&_.clientStatus==="pending"?{..._,clientStatus:"canceled"}:_),q=await Tn(N);if(t){Aa(q);return}fe(q),i(C),u.session&&u.session.id&&(V.current=u.session)}catch(b){console.warn("[AiChatbot] Failed to load history",b);try{d.removeItem(Rt)}catch{}}finally{t||Pe(!0)}})(),()=>{t=!0}},[x,ye,Tn]),(0,o.useEffect)(()=>{if(!je)return;let t=fn(x);if(!t)return;let d=Z.current;if(!d)return;if(Date.now()-d>ye*Vt){try{t.removeItem(Rt)}catch{}pn(new Set);return}let b=M.map(({attachments:T,...N})=>({...N,attachments:T?.map(({objectUrl:q,blob:_,...Ie})=>Ie)})),u={version:1,lastUserSentAt:d,session:V.current,messages:b};try{t.setItem(Rt,JSON.stringify(u))}catch{}let C=new Set;b.forEach(T=>{T.attachments?.forEach(N=>{N.blobId&&C.add(N.blobId)})}),pn(C)},[je,M,st,x,ye]),l&&!X||!l&&X?null:(0,s.jsxs)(h.Group,{className:bn,children:[!ie&&(0,s.jsx)(h.Button,{variant:"filled",className:H?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:ja,"aria-label":vt,title:vt,"data-ai-kit-open-button":!0,children:Wa}),ie&&(0,s.jsx)(h.Modal.Root,{ref:we,opened:ie,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:yn,className:bn+" ai-chat-container"+(Se?" maximized":"")+(Se&&Ve?" ai-max-enter":""),portalProps:{target:a,reuseTargetNode:!0},"data-ai-kit-theme":ne,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:Ct,children:[(0,s.jsxs)(h.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(h.Modal.Title,{className:"ai-chat-title",children:Ma}),(0,s.jsxs)(h.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(h.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:Ga,title:Se?A.I18n.get(y.restoreSizeLabel):A.I18n.get(y.maximizeLabel),"aria-label":Se?A.I18n.get(y.restoreSizeLabel):A.I18n.get(y.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Se?(0,s.jsx)(pe.IconMinimize,{size:16}):(0,s.jsx)(pe.IconMaximize,{size:16})}),(0,s.jsx)(h.Modal.CloseButton,{"aria-label":A.I18n.get(y.closeChatLabel)})]})]}),(0,s.jsxs)(h.Modal.Body,{className:"ai-chat-scroll",ref:ht,"data-scrollable":ot?"true":"false",children:[M.map(t=>{let d=t.role==="user",b=d&&t.clientStatus==="canceled"&&t.id===Da;return(0,s.jsx)(h.Group,{justify:d?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>At(t.id),onMouseLeave:()=>At(u=>u===t.id?null:u),children:(0,s.jsxs)(h.Stack,{gap:4,w:"100%",style:{alignItems:d?"flex-end":"flex-start"},children:[(0,s.jsxs)(h.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(h.Text,{className:"ai-chat-header",children:[(0,s.jsx)(h.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:d?A.I18n.get(y.userLabel):A.I18n.get(y.assistantLabel)}),"\xA0",(0,s.jsx)(h.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(wa.default,{remarkPlugins:[Ta.default],children:t.content}):(0,s.jsx)(h.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(h.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(h.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>en(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||A.I18n.get("View image"),"aria-label":u.name||A.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:A.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(h.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(h.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(h.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:A.I18n.get("Audio no longer available")})},u.id))]}),b&&(0,s.jsxs)(h.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:A.I18n.get(y.notSentLabel)})}),yt===t.id&&(0,s.jsx)(h.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Ha(t),title:A.I18n.get(y.editLabel),"aria-label":A.I18n.get(y.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(pe.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(h.Stack,{className:"ai-citations",children:[(0,s.jsx)(h.Text,{fw:"bold",size:"sm",mb:"xs",children:A.I18n.get(y.referencesLabel)}),(0,s.jsx)(h.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let T=u.sourceUrl||u.url,N=u.title||T||`${A.I18n.get(y.referenceLabel)} #${C+1}`;return(0,s.jsxs)(h.List.Item,{children:[T?(0,s.jsx)(h.Anchor,{href:T,target:"_blank",rel:"noreferrer",children:N}):(0,s.jsx)(h.Text,{children:N}),u.snippet?(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(h.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(h.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>Cn(t.id,"accepted"),"aria-label":A.I18n.get(y.acceptResponseLabel),disabled:P.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(h.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>Cn(t.id,"rejected"),"aria-label":A.I18n.get(y.rejectResponseLabel),disabled:P.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Fa&&(0,s.jsx)(h.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(h.Stack,{className:"ai-chat-bubble typing",children:[vn?(0,s.jsx)(h.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:vn})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),qa&&(0,s.jsx)(h.Group,{className:"ai-status-line",children:(0,s.jsx)(h.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:Ya})})}),(0,s.jsxs)(h.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(h.Modal,{opened:Ae,onClose:In,centered:!0,title:A.I18n.get("Reset conversation"),style:{position:"fixed"},left:0,children:[(0,s.jsx)(h.Text,{size:"sm",children:A.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(h.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(h.Button,{variant:"default",onClick:In,"data-ai-kit-no-button":!0,children:A.I18n.get("No")}),(0,s.jsx)(h.Button,{color:"var(--ai-kit-color-danger, red)",onClick:Oa,disabled:!nt&&!de,"data-ai-kit-yes-button":!0,children:A.I18n.get("Yes")})]})]}),(0,s.jsx)(h.Group,{children:(0,s.jsx)(h.Textarea,{className:"ai-message",ref:O,placeholder:Pa,value:W,onChange:t=>{ze(t.target.value),w&&me()},onKeyDown:Na,rows:3,disabled:ge||!!w})}),hn&&ge&&(0,s.jsxs)(h.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:A.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${at}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),hn&&w&&!ge&&(0,s.jsxs)(h.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[A.I18n.get("Audio recorded")," (",Math.round(w.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:w.objectUrl})]}),(0,s.jsxs)(h.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(h.Group,{justify:"flex-start",children:(0,s.jsx)(h.Button,{variant:"light",leftSection:(0,s.jsx)(pe.IconTrash,{size:18}),onClick:Ua,disabled:!nt&&!de,"data-ai-kit-reset-button":!0,children:A.I18n.get(y.resetLabel)})}),(0,s.jsxs)(h.Group,{justify:"flex-end",children:[hn&&(0,s.jsx)(s.Fragment,{children:w?(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconX,{size:18}),onClick:me,disabled:de,title:A.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:A.I18n.get("Clear")}):(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconMicrophone,{size:18}),onClick:ge?ft:be,disabled:de,title:ge?A.I18n.get("Stop recording"):A.I18n.get("Record audio"),color:ge?"red":void 0,"data-ai-kit-microphone-button":!0,children:ge?A.I18n.get("Stop"):A.I18n.get("Record")})}),ue>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconPaperclip,{size:18}),onClick:()=>R.current?.click(),disabled:D.length>=ue||de||ge||!!w,title:A.I18n.get(y.addImageLabel),"data-ai-kit-add-image-button":!0,children:A.I18n.get(y.addLabel)}),(0,s.jsx)(h.Input,{ref:R,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Ea})]}),(0,s.jsx)(h.Button,{leftSection:Va,variant:"filled",onClick:_a,disabled:!de&&!Xt,"data-ai-kit-send-button":!0,children:Ja})]})]}),An.length>0&&(0,s.jsx)(h.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:An.map(({url:t,title:d},b)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":d||A.I18n.get("View image"),onClick:()=>en(t,d),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),en(t,d))},children:(0,s.jsx)(h.Button,{variant:"white",onClick:u=>{u.stopPropagation(),Ba(b)},"aria-label":A.I18n.get(y.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:A.I18n.get(y.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},D[b]?.id??b))})]})]})}),(0,s.jsx)(h.Modal,{opened:!!ve,onClose:Ka,centered:!0,size:"auto",title:ve?.title||A.I18n.get("Image preview"),children:ve&&(0,s.jsx)("img",{src:ve.url,alt:ve.title||A.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},Ra=ct(Cr,{showOpenButton:!0,variation:"modal"});var S=require("@mantine/core"),Zt=require("@smart-cloud/ai-kit-core"),ce=require("aws-amplify/utils"),j=require("react"),za=He(require("react-markdown"),1),Ca=He(require("rehype-raw"),1),xa=He(require("remark-gfm"),1),kn=require("@tabler/icons-react"),Qt=require("@tabler/icons-react");var k=require("react/jsx-runtime");ce.I18n.putVocabularies(ut);var Ia=!1;function xr(e){let a=e?.citations?.docs??[],g=e?.citations?.chunks??[],l=new Map;for(let n of a)l.set(n.docId,{doc:n,chunks:[]});for(let n of g){let p=l.get(n.docId);p?p.chunks.push(n):l.set(n.docId,{doc:{docId:n.docId},chunks:[n]})}return Array.from(l.values())}var Lr=e=>{let{autoRun:a=!0,context:g,title:l,searchButtonIcon:n,showSearchButtonTitle:p=!0,showSearchButtonIcon:z=!0,showSources:H=!0,topK:te=10,getSearchText:ne,variation:E,rootElement:ae,colorMode:Ee,language:ee,onClose:L,onClickDoc:m,showOpenButton:x=!1,openButtonTitle:ye,openButtonIcon:Be,showOpenButtonTitle:$=!0,showOpenButtonIcon:he=!0}=e,[y,P]=(0,j.useState)(""),[W,ze]=(0,j.useState)(!x),[D,Te]=(0,j.useState)(!1),[w,re]=(0,j.useState)(null),[ge,Qe]=(0,j.useState)(0),at=(0,j.useRef)(null),Ne=(0,j.useRef)([]),We=(0,j.useRef)(null),Fe=(0,j.useRef)(null),Ce=(0,j.useRef)(null),Me=(0,j.useRef)(null),U=1440*60*1e3,{busy:M,error:fe,statusEvent:Je,result:oe,run:Ae,cancel:mt,reset:Se}=bt(),Ke=(0,j.useRef)(!1),Ve=oe?.sessionId,Xe=oe?.citations?.docs??[],ie=oe?.citations?.chunks??[],et=oe?.citations?.anchors??[],B=oe?.result??"",rt=(0,j.useMemo)(()=>{if(z)return n?.trim()?(0,k.jsx)("img",{src:n,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,k.jsx)(kn.IconSearch,{size:18})},[n,z]),ve=(0,j.useMemo)(()=>(ee&&ce.I18n.setLanguage(ee||"en"),ce.I18n.get(l||"Search with AI-Kit")),[ee]),pt=(0,j.useCallback)(R=>(0,k.jsx)(kn.IconSearch,{className:R,size:18}),[]),je=(0,j.useMemo)(()=>Je?ce.I18n.get("Searching\u2026"):null,[ee,Je]),Pe=(0,j.useMemo)(()=>y||ne,[y,ne]),ke=(0,j.useMemo)(()=>{if(M)return!1;let R=typeof Pe=="function"?Pe():Pe;return!!(R&&R.trim().length>0||w)},[Pe,M,w]),Ct=(0,j.useCallback)(async()=>{try{P("");let R=await navigator.mediaDevices.getUserMedia({audio:!0}),O=new MediaRecorder(R,{mimeType:"audio/webm"}),V=new AudioContext,we=V.createMediaStreamSource(R),F=V.createAnalyser();F.fftSize=2048,F.smoothingTimeConstant=.8,we.connect(F),We.current=V,Fe.current=F;let se=new Uint8Array(F.fftSize),me=()=>{if(!Fe.current)return;Fe.current.getByteTimeDomainData(se);let be=0;for(let i=0;i<se.length;i++){let v=(se[i]-128)/128;be+=v*v}let ft=Math.sqrt(be/se.length),st=Math.min(100,ft*200);Qe(st),Ce.current=requestAnimationFrame(me)};me(),Ne.current=[],O.ondataavailable=be=>{be.data.size>0&&Ne.current.push(be.data)},O.onstop=()=>{let be=new Blob(Ne.current,{type:"audio/webm"});re(be),R.getTracks().forEach(ft=>ft.stop()),Ce.current&&(cancelAnimationFrame(Ce.current),Ce.current=null),We.current&&(We.current.close(),We.current=null),Fe.current=null,Qe(0)},at.current=O,O.start(),Te(!0)}catch(R){console.error("Failed to start recording:",R)}},[]),Q=(0,j.useCallback)(()=>{at.current&&D&&(at.current.stop(),Te(!1))},[D]),ht=(0,j.useCallback)(()=>{re(null),Ne.current=[],Qe(0),Me.current=null},[]);(0,j.useEffect)(()=>()=>{Ce.current&&cancelAnimationFrame(Ce.current),We.current&&We.current.close()},[]);let ot=(0,j.useCallback)(async()=>{let R;if(!w){if(R=typeof Pe=="function"?Pe():Pe,!R)return;P(R)}console.log("Starting search with query:",R,"and audio:",w);let O=Date.now(),V=w&&Me.current?.blob===w&&O-Me.current.uploadTimestamp<U;w&&!V?(Me.current={blob:w,uploadTimestamp:O},console.log("Audio cache updated for new recording")):V&&console.log("Reusing cached audio (no re-upload needed within",Math.round((U-(O-Me.current.uploadTimestamp))/1e3),"seconds)"),Se(),await Ae(async({signal:we,onStatus:F})=>await(0,Zt.sendSearchMessage)({sessionId:Ve,...R&&{query:R},...w&&{audio:w},topK:te},{signal:we,onStatus:F,context:g}))},[g,Pe,w,Ae,Se,te,Ve]),Ge=(0,j.useCallback)(async()=>{ze(!1),Se(),Ke.current=!1,x||L()},[L,Se,Ke,x]);(0,j.useEffect)(()=>{!a||!ke||M||Ke.current||(Ke.current=!0,queueMicrotask(()=>{ot()}))},[M,Ke,ke,a,ot]),(0,j.useEffect)(()=>{ke||(Ke.current=!0)},[ke]);let Re=(0,j.useMemo)(()=>xr(oe),[oe]),I=(0,j.useMemo)(()=>{let R=new Map;return Xe.forEach((O,V)=>{O?.docId&&R.set(O.docId,V+1)}),R},[Xe]),it=(0,j.useMemo)(()=>{let R=new Map;return ie.forEach(O=>{O?.chunkId&&O?.docId&&R.set(O.chunkId,O.docId)}),R},[ie]),xe=(0,j.useMemo)(()=>{if(!B)return"";if(!et.length||I.size===0)return B;let R=[...et].filter(we=>Array.isArray(we?.chunkIds)&&we?.span?.end!==void 0).sort((we,F)=>{let se=we.span?.end??0,me=F.span?.end??0;return se-me}),O=0,V=[];for(let we of R){let F=we.span?.end;if(typeof F!="number"||F<O)continue;let se=Array.from(new Set((we.chunkIds??[]).map(be=>be?it.get(be):void 0).map(be=>be?I.get(be):void 0).filter(be=>typeof be=="number")));if(!se.length)continue;let me=Math.min(F,B.length);V.push(B.slice(O,me)),V.push(`<sup>${se.join(",")}</sup>`),O=me}return V.push(B.slice(O)),V.join("")},[et,B]),tt=E==="modal"?S.Modal.Root:S.Group,yt=E==="modal"?S.Modal.Content:S.Group,At=E==="modal"?S.Modal.Body:S.Group;return(0,j.useEffect)(()=>{if(!(E!=="modal"||!W))return document.body.style.overflow="hidden",document.body.onkeydown=R=>{R.key==="Escape"&&(R.preventDefault(),Ge())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[Ge,E]),(0,k.jsxs)(k.Fragment,{children:[x&&(0,k.jsx)(S.Button,{leftSection:he&&(Be?(0,k.jsx)("span",{dangerouslySetInnerHTML:{__html:Be}}):pt()),className:$?"doc-search-open-button":"doc-search-open-button-no-title",variant:"filled",disabled:W,onClick:()=>ze(!0),"data-ai-kit-open-button":!0,children:$&&ce.I18n.get(ye||ve)}),W&&(0,k.jsxs)(tt,{opened:!0,className:"doc-search-root",onClose:Ge,padding:"md",gap:"md",size:"xl",portalProps:E==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ee,"data-ai-kit-variation":E,children:[E==="modal"&&(0,k.jsx)(S.Modal.Overlay,{}),(0,k.jsxs)(yt,{w:"100%",style:{left:0},children:[E==="modal"&&(0,k.jsxs)(S.Modal.Header,{style:{zIndex:1e3},children:[(0,k.jsx)(Zt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,k.jsx)(S.Modal.Title,{children:ce.I18n.get(ve)}),(0,k.jsx)(S.Modal.CloseButton,{})]}),(0,k.jsx)(At,{w:"100%",style:{zIndex:1001},children:(0,k.jsx)(Tt,{enabled:E!=="modal",working:M,variation:E,children:(0,k.jsx)(S.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,k.jsxs)(S.Stack,{gap:"sm",children:[E!=="modal"&&(0,k.jsx)(S.Title,{order:4,style:{margin:0},children:ce.I18n.get(ve)}),(0,k.jsxs)(S.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,k.jsx)(S.TextInput,{style:{flex:1},value:y,onChange:R=>{P(R.currentTarget.value),w&&ht()},placeholder:w?ce.I18n.get("Audio recorded"):ce.I18n.get("Search the documentation\u2026"),disabled:M||D||!!w,onKeyDown:R=>{R.key==="Enter"&&ke&&(R.preventDefault(),ot())}}),Ia&&(0,k.jsx)(k.Fragment,{children:w?(0,k.jsx)(S.Button,{variant:"outline",size:"sm",color:"red",onClick:ht,disabled:M,title:ce.I18n.get("Clear audio"),children:(0,k.jsx)(Qt.IconMicrophoneOff,{size:18})}):(0,k.jsx)(S.Button,{variant:D?"filled":"outline",size:"sm",color:D?"red":"gray",onClick:D?Q:Ct,disabled:M,title:D?ce.I18n.get("Stop recording"):ce.I18n.get("Record audio"),style:D?{transform:`scale(${1+ge/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,k.jsx)(Qt.IconMicrophone,{size:18})})}),(0,k.jsx)(S.Button,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{ot()},disabled:!ke,className:p?"doc-search-button":"doc-search-button-no-title",children:p?ce.I18n.get("Search"):null}),M?(0,k.jsx)(S.Button,{variant:"outline",size:"sm",onClick:mt,children:ce.I18n.get("Stop")}):null]}),Ia&&(0,k.jsxs)(k.Fragment,{children:[D&&(0,k.jsxs)(S.Stack,{gap:"xs",children:[(0,k.jsxs)(S.Text,{size:"xs",c:"dimmed",children:[ce.I18n.get("Recording...")," \u{1F3A4}"]}),(0,k.jsx)(S.Progress,{value:ge,size:"sm",color:"red",animated:!0,striped:!0})]}),w&&!D&&(0,k.jsxs)(S.Stack,{gap:"xs",children:[(0,k.jsx)(S.Text,{size:"xs",c:"dimmed",children:ce.I18n.get("Recorded audio:")}),(0,k.jsx)("audio",{controls:!0,src:URL.createObjectURL(w),className:"ai-kit-audio-player"})]})]}),fe?(0,k.jsx)(S.Alert,{color:"red",title:ce.I18n.get("Error"),children:fe}):null,M&&je&&(0,k.jsx)(Tt,{enabled:E==="modal",working:!0,variation:E,children:(0,k.jsxs)(S.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,k.jsx)(S.Loader,{size:"sm"}),(0,k.jsx)(S.Text,{size:"sm",c:"dimmed",children:je})]})}),oe?.result?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(S.Divider,{}),(0,k.jsxs)(S.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:ce.I18n.get("AI Summary")}),(0,k.jsx)(za.default,{remarkPlugins:[xa.default],rehypePlugins:[Ca.default],"data-doc-search-result-content":!0,children:xe||B})]})]}):null,H&&(oe?.citations?.docs?.length||oe?.citations?.chunks?.length)?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(S.Divider,{}),(0,k.jsxs)(S.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:ce.I18n.get("Sources")}),Re.map(({doc:R})=>{let O=R.sourceUrl?.trim()||void 0,V=R.docId?I.get(R.docId):void 0,we=R.title?.trim()||R.docId,F=(0,k.jsxs)(S.Text,{fw:600,style:{display:"inline"},children:[V?`${V}. `:"",we]});return(0,k.jsx)(S.Paper,{withBorder:!0,radius:"md",p:"sm",children:(0,k.jsx)(S.Stack,{gap:"xs",children:(0,k.jsx)(S.Group,{justify:"space-between",align:"flex-start",children:(0,k.jsxs)(S.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[O?(0,k.jsx)(S.Anchor,{href:O,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:se=>{m&&(se.preventDefault(),m?.(R))},"data-doc-search-source-title":!0,children:F}):F,(0,k.jsx)(S.Anchor,{href:O,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:se=>{m&&(se.preventDefault(),m?.(R))},"data-doc-search-source-url":!0,children:R.sourceUrl}),R.author?(0,k.jsx)(S.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:R.author}):null,R.description?(0,k.jsx)(S.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:R.description}):null]})})})},R.docId)})]})]}):null,!M&&!fe&&!oe?.result?(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:ce.I18n.get("Enter a search query to start.")}):null,(0,k.jsx)(Nt,{variation:E})]})})})})]})]})]})},La=ct(Lr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
31
+ Follow these additional instructions: ${Ae}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),Z=await I.run(async({signal:X,onStatus:ue})=>(await(0,G.prompt)({messages:Y,images:[oe],outputLanguage:"en",responseConstraint:cr},{signal:X,onStatus:ue,context:x,modeOverride:i,onDeviceTimeoutOverride:n})).result);if(!Z){M("");return}let le=(B&&B!=="auto"?B:null)||dt(),J=wt(Z).trim();try{re("Translating result...");let X=await I.run(async({signal:ue})=>await mr(J,le,{signal:ue,context:x,modeOverride:i,onDeviceTimeoutOverride:n,silent:!0}));M(X)}catch(X){M(J),console.warn("AI Kit: failed to parse SEO JSON",X)}break}}}catch(v){Me(v instanceof Error?v.message:r.I18n.get("An unknown error occurred."))}re(void 0)}},[W,I,Ae,ve,B,fe,je,x,m,ke,Ve,Re,Te]),tt=(0,K.useCallback)(async()=>{await xe("backend-only")},[xe]),yt=(0,K.useCallback)(i=>{switch(m){case"proofread":return(0,c.jsx)($e.IconCircleDashedCheck,{className:i});case"translate":return(0,c.jsx)($e.IconLanguage,{className:i});case"summarize":return(0,c.jsx)($e.IconSum,{className:i});case"rewrite":case"write":return(0,c.jsx)($e.IconPencilCode,{className:i});case"generateImageMetadata":case"generatePostMetadata":return(0,c.jsx)($e.IconSeo,{className:i});default:return(0,c.jsx)(G.AiKitFeatureIcon,{mode:m,className:i})}},[m]),At=(0,K.useCallback)(()=>{switch(m){case"proofread":return I.lastSource?r.I18n.get("Proofread again"):r.I18n.get("Proofread");case"translate":return I.lastSource?r.I18n.get("Translate again"):r.I18n.get("Translate");case"rewrite":return I.lastSource?r.I18n.get("Rewrite again"):r.I18n.get("Rewrite");case"summarize":return I.lastSource?r.I18n.get("Summarize again"):r.I18n.get("Summarize");default:return I.lastSource?r.I18n.get("Regenerate"):r.I18n.get("Generate")}},[W,I.lastSource,m]),R=(0,K.useCallback)(()=>{switch(m){case"proofread":return r.I18n.get("Proofread on Backend");case"translate":return r.I18n.get("Translate on Backend");case"rewrite":return r.I18n.get("Rewrite on Backend");case"summarize":return r.I18n.get("Summarize on Backend");default:return r.I18n.get("Regenerate on Backend")}},[W,m]),O=(0,K.useCallback)(async()=>{Qe(!1),M(null),Me(null),Q.current=!1,I.reset(),H||he()},[he,Q,I,H]),V=(0,K.useCallback)(async()=>{I.busy&&I.cancel()},[I.busy]);(0,K.useEffect)(()=>{!ge||!g||!Re||I.busy||U||Q.current||(Q.current=!0,queueMicrotask(()=>{xe(ye)}))},[I.busy,Q,ge,Re,g,U,xe,ye]),(0,K.useEffect)(()=>{Te&&m!=="proofread"&&(Re||(Ne(!0),Q.current=!0))},[Te,Re,m]),(0,K.useEffect)(()=>{let i=!0;return(async()=>{try{await(0,G.waitForAiKitReady)();let v=await an();i&&Fe(v)}catch(v){console.error(v),i&&Fe(!1)}})(),()=>{i=!1}},[]);let we=(0,K.useMemo)(()=>{let i=[];if(m==="translate"){let v=G.LANGUAGE_OPTIONS.find(Y=>Y.value===Ve)?.label;i.push(r.I18n.get("Input language")+": "+(v?r.I18n.get(v):"auto"))}if(B&&D?.outputLanguage){let v=G.LANGUAGE_OPTIONS.find(Y=>Y.value===B)?.label;i.push(r.I18n.get("Output language")+": "+(v?r.I18n.get(v):B))}return m==="summarize"&&ke&&D?.type&&i.push(r.I18n.get("Type")+": "+r.I18n.get(ke)),(m==="write"||m==="rewrite")&&je&&D?.tone&&i.push(r.I18n.get("Tone")+": "+r.I18n.get(je)),(m==="write"||m==="rewrite"||m==="summarize")&&ve&&D?.length&&i.push(r.I18n.get("Length")+": "+r.I18n.get(ve)),Ae?.trim()&&D?.instructions&&i.push(r.I18n.get("Instructions")+": \u2713"),i.length?i.join(" \u2022 "):r.I18n.get("No overrides")},[W,m,Ve,B,ke,je,ve,Ae]),F={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},se=p==="modal"?f.Modal.Root:f.Group,me=p==="modal"?f.Modal.Content:f.Group,be=p==="modal"?f.Modal.Body:f.Group,ft=L==="collapse"?f.Collapse:f.Stack,st=L==="horizontal"?f.Group:f.Stack;return(0,K.useEffect)(()=>{if(!(p!=="modal"||!ge))return document.body.style.overflow="hidden",document.body.onkeydown=i=>{i.key==="Escape"&&(i.preventDefault(),O())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[O,p]),(0,c.jsxs)(c.Fragment,{children:[H&&(0,c.jsx)(f.Button,{leftSection:ne&&(ae?(0,c.jsx)("span",{dangerouslySetInnerHTML:{__html:ae}}):yt()),className:te?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ge,onClick:()=>Qe(!0),"data-ai-kit-open-button":!0,children:te&&r.I18n.get(E||ht)}),ge&&(0,c.jsxs)(se,{opened:!0,className:"ai-feature-root",onClose:O,padding:"md",gap:"md",size:"md",portalProps:p==="modal"?{target:ze,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Be,"data-ai-kit-variation":p,children:[p==="modal"&&(0,c.jsx)(f.Modal.Overlay,{}),(0,c.jsxs)(me,{w:"100%",style:{left:0},children:[p==="modal"&&(0,c.jsxs)(f.Modal.Header,{style:{zIndex:1e3},children:[yt("ai-feature-title-icon"),(0,c.jsx)(f.Modal.Title,{children:r.I18n.get(ht)}),(0,c.jsx)(f.Modal.CloseButton,{})]}),(0,c.jsx)(be,{w:"100%",style:{zIndex:1001},children:(0,c.jsxs)(Tt,{enabled:p!=="modal",working:I.busy,variation:p,children:[(0,c.jsxs)(f.Stack,{gap:"sm",mb:"sm",p:"sm",children:[Ce&&(0,c.jsx)(f.Alert,{color:"red",children:r.I18n.get(Ce)}),Te&&m!=="proofread"&&(0,c.jsxs)(f.Paper,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":L,children:[(0,c.jsxs)(f.Group,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:L==="collapse"?()=>Ne(i=>!i):void 0,children:[L==="collapse"&&(0,c.jsxs)(f.Stack,{gap:0,children:[(0,c.jsx)(f.Text,{size:"sm",fw:600,style:{lineHeight:1.1},children:r.I18n.get("Options")}),(0,c.jsx)(f.Text,{size:"xs",c:"dimmed",style:{marginTop:2},children:we})]}),L==="collapse"&&(0,c.jsx)(f.Button,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:i=>{i.stopPropagation(),Ne(v=>!v)},children:at?r.I18n.get("Hide"):r.I18n.get("Show")})]}),(0,c.jsxs)(ft,{in:at,children:[L==="collapse"&&(0,c.jsx)(f.Divider,{my:"sm"}),(0,c.jsxs)(st,{gap:"xs",justify:"space-between",children:[m==="write"&&D?.text&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The topic or subject for the AI to write about."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.TextInput,{size:"xs",className:"ai-feature-option",styles:F,disabled:I.busy,label:r.I18n.get("Topic"),description:L!=="horizontal"?r.I18n.get("The topic or subject for the AI to write about."):void 0,value:fe||"",onChange:i=>{let v=i.target.value;Je(v),P?.({text:v})}})}),(m==="write"||m==="rewrite"||m==="generateImageMetadata"||m==="generatePostMetadata")&&D?.instructions&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("Additional instructions to guide the AI."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.TextInput,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Instructions"),description:L!=="horizontal"?r.I18n.get("Additional instructions to guide the AI."):void 0,value:Ae||"",onChange:i=>{let v=i.target.value;mt(v),P?.({instructions:v})}})}),m==="translate"&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The language of the input text."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",styles:F,className:"ai-feature-option",label:r.I18n.get("Input language"),description:L!=="horizontal"?r.I18n.get("The language of the input text."):void 0,data:[{value:"auto",label:r.I18n.get("Auto-detect")},...G.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,v)=>i.label.localeCompare(v.label))],value:Ve||"auto",onChange:i=>{let v=i;Xe(v),Ke(void 0),P?.({inputLanguage:v})}})}),D?.outputLanguage&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",styles:F,className:"ai-feature-option",label:r.I18n.get("Output language"),description:L!=="horizontal"?r.I18n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[m==="rewrite"?{value:"auto",label:r.I18n.get("Auto-detect")}:void 0].filter(Boolean),...G.LANGUAGE_OPTIONS.map(i=>({value:i.value,label:r.I18n.get(i.label)})).sort((i,v)=>i.label.localeCompare(v.label))],value:B||ka.settings.defaultOutputLanguage||(m==="rewrite"?"auto":""),onChange:i=>{let v=i;rt(v),Ke(void 0),P?.({outputLanguage:v})}})}),m==="summarize"&&D?.type&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The summary style to generate."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Type"),description:L!=="horizontal"?r.I18n.get("The summary style to generate."):void 0,data:[{value:"headline",label:r.I18n.get("Headline")},{value:"key-points",label:r.I18n.get("Key Points")},{value:"teaser",label:r.I18n.get("Teaser")},{value:"tldr",label:r.I18n.get("TL;DR")}],value:ke||"key-points",onChange:i=>{let v=i;Ct(v),P?.({type:v})}})}),(m==="write"||m==="rewrite")&&D?.tone&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The tone or style for the AI to use."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Tone"),description:L!=="horizontal"?r.I18n.get("The tone or style for the AI to use."):void 0,data:m==="write"?[{value:"neutral",label:r.I18n.get("Neutral")},{value:"formal",label:r.I18n.get("Formal")},{value:"casual",label:r.I18n.get("Casual")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"more-formal",label:r.I18n.get("More formal")},{value:"more-casual",label:r.I18n.get("More casual")}],value:je||(m==="write"?"neutral":"as-is"),onChange:i=>{let v=i;Pe(v),P?.({tone:v})}})}),(m==="write"||m==="rewrite"||m==="summarize")&&D?.length&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The target output length."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Length"),description:L!=="horizontal"?r.I18n.get("The target output length."):void 0,data:m==="write"||m==="summarize"?[{value:"short",label:r.I18n.get("Short")},{value:"medium",label:r.I18n.get("Medium")},{value:"long",label:r.I18n.get("Long")}]:[{value:"as-is",label:r.I18n.get("As-Is")},{value:"shorter",label:r.I18n.get("Shorter")},{value:"longer",label:r.I18n.get("Longer")}],value:ve||(m==="rewrite"?"as-is":"short"),onChange:i=>{let v=i;pt(v),P?.({length:v})}})}),m==="summarize"||m==="write"||m==="rewrite"&&D?.outputFormat&&(0,c.jsx)(f.Tooltip,{label:r.I18n.get("The format for the generated output."),disabled:L!=="horizontal",position:"top",children:(0,c.jsx)(f.Select,{disabled:I.busy,size:"xs",className:"ai-feature-option",styles:F,label:r.I18n.get("Output format"),description:L!=="horizontal"?r.I18n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:r.I18n.get("Plain Text")},{value:"markdown",label:r.I18n.get("Markdown")},{value:"html",label:r.I18n.get("HTML")}],value:ie||"markdown",onChange:i=>{let v=i;et(v),P?.({outputFormat:v})}})})]})]})]}),I.busy&&it&&(0,c.jsx)(Tt,{enabled:p==="modal",working:!0,variation:p,children:(0,c.jsxs)(f.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,c.jsx)(f.Loader,{size:"sm"}),(0,c.jsx)(f.Input.Label,{className:"ai-feature-status-text",children:it})]})}),U&&(0,c.jsxs)(f.Stack,{mt:"md",children:[m==="proofread"&&(U.corrections.length===0?(0,c.jsx)(f.Alert,{color:"green",children:r.I18n.get("No issues found. Your text looks great!")}):(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("p",{style:{marginTop:0,opacity:.85},children:r.I18n.get("Hover highlights to see explanations.")}),(0,c.jsx)(ca,{original:fe,corrections:U.corrections}),U.correctedInput?(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)("h4",{style:{marginTop:16,marginBottom:8},children:r.I18n.get("Corrected")}),(0,c.jsx)(f.Group,{c:"pre",className:"ai-feature-generated-content",children:U.correctedInput})]}):null]})),m==="generateImageMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Alt Text"),description:r.I18n.get("The alt text for the image."),value:U.alt_text||"",onChange:i=>M({...U,alt_text:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the image."),value:U.title||"",onChange:i=>M({...U,title:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Caption"),description:r.I18n.get("The caption for the image."),value:U.caption||"",onChange:i=>M({...U,caption:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Description"),description:r.I18n.get("The description for the image."),value:U.description||"",onChange:i=>M({...U,description:i.target.value})})]}),m==="generatePostMetadata"&&(0,c.jsxs)(c.Fragment,{children:[(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Title"),description:r.I18n.get("The title for the post."),value:U.title||"",onChange:i=>M({...U,title:i.target.value})}),(0,c.jsx)(f.TextInput,{readOnly:!l,label:r.I18n.get("Excerpt"),description:r.I18n.get("The excerpt for the post."),value:U.excerpt||"",onChange:i=>M({...U,excerpt:i.target.value})})]}),m!=="proofread"&&m!=="generateImageMetadata"&&m!=="generatePostMetadata"&&typeof U=="string"&&(0,c.jsx)(ba,{value:U,editable:!!l,onChange:i=>{M(i)}})]}),U===""&&(0,c.jsx)(ba,{value:U,editable:!1})]}),(0,c.jsxs)(f.Group,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[I.busy&&(0,c.jsx)(f.Button,{variant:"outline",size:"sm",onClick:V,"data-ai-kit-cancel-button":!0,children:r.I18n.get("Cancel")}),!I.busy&&(0,c.jsx)(f.Button,{variant:"filled",size:"sm",disabled:!Re,onClick:()=>xe(),"data-ai-kit-generate-button":!0,children:At()}),!I.busy&&I.lastSource==="on-device"&&We&&Ee&&(0,c.jsx)(f.Button,{variant:"filled",size:"sm",disabled:!Re,onClick:tt,"data-ai-kit-regenerate-on-backend-button":!0,children:R()}),!I.busy&&y&&(0,c.jsx)(f.Button,{variant:"outline",size:"sm",disabled:!U||m==="proofread"&&U.corrections.length===0,onClick:async()=>{y(ie==="html"?await qt(U):U),O()},"data-ai-kit-accept-button":!0,children:r.I18n.get(ee)}),(0,c.jsx)(f.Button,{variant:"default",size:"sm",onClick:O,"data-ai-kit-close-button":!0,children:r.I18n.get("Close")})]}),(0,c.jsx)(Nt,{variation:p})]})})]})]})]})};function ba(e){let{value:a,editable:g,onChange:l}=e;return g?(0,c.jsxs)(f.Stack,{p:0,gap:"sm",children:[(0,c.jsx)(f.Input.Label,{children:r.I18n.get("Generated content")}),(0,c.jsx)(f.Textarea,{value:a,onChange:n=>l?.(n.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),(0,c.jsx)(f.Input.Label,{children:r.I18n.get("Preview")}),(0,c.jsx)(f.Stack,{className:"ai-feature-generated-content ai-feature-preview",children:(0,c.jsx)(ln.default,{remarkPlugins:[un.default],children:a})})]}):(0,c.jsx)(f.Stack,{className:"ai-feature-generated-content",children:a?(0,c.jsx)(ln.default,{remarkPlugins:[un.default],children:a}):(0,c.jsx)(f.Alert,{color:"yellow",children:r.I18n.get("No content generated.")})})}var ya=ct(hr);var h=require("@mantine/core"),pe=require("@tabler/icons-react"),zt=require("@smart-cloud/ai-kit-core"),va=require("@wordpress/data"),A=require("aws-amplify/utils"),o=require("react"),wa=He(require("react-markdown"),1),Ta=He(require("remark-gfm"),1);var fr="ai-kit-chatbot-attachments",Ze="attachments";var dn=null;function kr(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function Yt(){if(!kr())return null;dn||(dn=new Promise(e=>{try{let a=window.indexedDB.open(fr,1);a.onerror=()=>e(null),a.onblocked=()=>e(null),a.onupgradeneeded=()=>{let g=a.result;g.objectStoreNames.contains(Ze)||g.createObjectStore(Ze,{keyPath:"id"})},a.onsuccess=()=>e(a.result)}catch(a){console.warn("[AiChatbot] IndexedDB is not available",a),e(null)}}));try{return await dn}catch(e){return console.warn("[AiChatbot] Failed to open attachment store",e),null}}async function cn(e,a){let g=await Yt();return g?new Promise((l,n)=>{try{let p=g.transaction(Ze,e),z=p.objectStore(Ze),H=a(z);p.oncomplete=()=>l(H),p.onerror=()=>n(p.error),p.onabort=()=>n(p.error)}catch(p){n(p)}}).catch(l=>(console.warn("[AiChatbot] Attachment store transaction failed",l),null)):null}async function gn(e,a,g){await vr();let l={id:e,blob:a,name:g.name,type:g.type,size:g.size,createdAt:Date.now()};return await cn("readwrite",p=>(p.put(l),e))}async function mn(e){let a=await Yt();return a?new Promise((g,l)=>{try{let n=a.transaction(Ze,"readonly"),p=n.objectStore(Ze).get(e);p.onsuccess=()=>{let z=p.result;g(z??null)},p.onerror=()=>l(p.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>(console.warn("[AiChatbot] Failed to load attachment",g),null)):null}async function br(e){await cn("readwrite",a=>{a.delete(e)})}async function Jt(){await cn("readwrite",e=>{e.clear()})}async function pn(e){let a=await Yt();a&&await new Promise((g,l)=>{try{let n=a.transaction(Ze,"readwrite"),p=n.objectStore(Ze),z=p.getAllKeys();z.onsuccess=()=>{let H=z.result;for(let te of H){let ne=String(te);e.has(ne)||p.delete(te)}},z.onerror=()=>l(z.error),n.oncomplete=()=>g(),n.onerror=()=>l(n.error),n.onabort=()=>l(n.error)}catch(n){l(n)}}).catch(g=>{console.warn("[AiChatbot] Failed to cleanup attachments",g)})}var yr=50*1024*1024;async function Ar(){let e=await Yt();return e?new Promise((a,g)=>{try{let l=e.transaction(Ze,"readonly"),n=l.objectStore(Ze).getAll();n.onsuccess=()=>{let p=n.result||[];a(p)},n.onerror=()=>g(n.error),l.onerror=()=>g(l.error),l.onabort=()=>g(l.error)}catch(l){g(l)}}).catch(a=>(console.warn("[AiChatbot] Failed to get all attachments",a),[])):[]}async function vr(){let e=await Ar();if(e.length===0)return;let a=e.sort((p,z)=>p.createdAt-z.createdAt),g=a.reduce((p,z)=>p+z.size,0),l=[],n=0;for(;g>yr&&n<a.length;){let p=a[n];p&&(l.push(p.id),g-=p.size),n++}for(let p of l)await br(p);l.length>0&&console.log(`[AiChatbot] Deleted ${l.length} old attachment(s) to enforce storage quota`)}var s=require("react/jsx-runtime");A.I18n.putVocabularies(ut);var Vt=1440*60*1e3,hn=!1,wr=1,Tr="localstorage",Rt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,$t={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function gt(e){return`${e}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Sr=4,Rr=5*1024*1024,Ir=e=>{let a=(e?.name||"").toString(),g=(e?.code||"").toString(),l=(e?.message||"").toString();return a==="AbortError"||g==="ABORT_ERR"||/abort|aborted|cancel/i.test(l)},zr=(e,a)=>{if(!e)return null;let g=e.step,l=A.I18n.get((e.message??"").trim()),n=typeof e.progress=="number"?e.progress:null,p=n==null?null:Math.round(n*100);switch(g){case"decide":return l||A.I18n.get("Checking capabilities...");case"on-device:init":return l||A.I18n.get("Initializing on-device AI...");case"on-device:download":return p==null?l||A.I18n.get("Downloading model..."):l||`${A.I18n.get("Downloading model...")} ${p}%`;case"on-device:ready":return l||A.I18n.get("On-device model ready...");case"on-device:run":return l||A.I18n.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return A.I18n.get(a.assistantThinkingLabel??$t.assistantThinkingLabel);case"done":return l||A.I18n.get("Done.");case"error":return l||A.I18n.get("An error occurred.");default:return l||null}};function fn(e){if(typeof window>"u")return null;try{return e==="localstorage"?window.localStorage:e==="sessionstorage"?window.sessionStorage:null}catch{return null}}var It=e=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(e)}catch{return null}},_t=e=>{if(e&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(e)}catch{}},Sa=e=>{!e||e.length===0||e.forEach(a=>_t(a.objectUrl))},Aa=e=>{e.forEach(a=>Sa(a.attachments))},Cr=e=>{let{rootElement:a,store:g,previewMode:l,title:n,openButtonTitle:p,openButtonIcon:z,showOpenButtonTitle:H=!0,showOpenButtonIcon:te=!0,colorMode:ne,language:E,onClose:ae,context:Ee,placeholder:ee,maxImages:L,maxImageBytes:m,historyStorage:x=Tr,emptyHistoryAfterDays:ye=wr,labels:Be,openButtonIconLayout:$="top",openButtonPosition:he="bottom-right"}=e,y=(0,o.useMemo)(()=>({...$t,...Be||{}}),[Be]),P=bt(),[W,ze]=(0,o.useState)(""),[D,Te]=(0,o.useState)([]),[w,re]=(0,o.useState)(null),[ge,Qe]=(0,o.useState)(!1),[at,Ne]=(0,o.useState)(0),We=(0,o.useRef)(null),Fe=(0,o.useRef)([]),Ce=(0,o.useRef)(null),Me=(0,o.useRef)(null),U=(0,o.useRef)(null),[M,fe]=(0,o.useState)([]),[Je,oe]=(0,o.useState)(null),[Ae,mt]=(0,o.useState)(!1),[Se,Ke]=(0,o.useState)(!1),[Ve,Xe]=(0,o.useState)(!1),[ie,et]=(0,o.useState)(!1),[B,rt]=(0,o.useState)(!0),[ve,pt]=(0,o.useState)(null),[je,Pe]=(0,o.useState)(!1),[ke,Ct]=(0,o.useState)(null),[Q,ht]=(0,o.useState)(null),[ot,Ge]=(0,o.useState)(!1),[Re,I]=(0,o.useState)(null),it=(0,o.useRef)(Re);(0,o.useEffect)(()=>{it.current=Re},[Re]);let xe=(0,o.useRef)(null),tt=(0,o.useRef)(!1),[yt,At]=(0,o.useState)(null),R=(0,o.useRef)(null),O=(0,o.useRef)(null),V=(0,o.useRef)(null),we=(0,o.useRef)(null),F=(0,o.useCallback)(t=>{t.forEach(d=>_t(d.objectUrl))},[]),se=(0,o.useCallback)(()=>{F(le.current),Te([]),R.current&&(R.current.value="")},[F]),me=(0,o.useCallback)(()=>{J.current&&_t(J.current.objectUrl),re(null),Fe.current=[],Ne(0)},[]),be=(0,o.useCallback)(async()=>{try{ze(""),me();let t=await navigator.mediaDevices.getUserMedia({audio:!0}),d=new MediaRecorder(t,{mimeType:"audio/webm"}),b=new AudioContext,u=b.createMediaStreamSource(t),C=b.createAnalyser();C.fftSize=2048,C.smoothingTimeConstant=.8,u.connect(C),Ce.current=b,Me.current=C;let T=new Uint8Array(C.fftSize),N=()=>{if(!Me.current)return;Me.current.getByteTimeDomainData(T);let _=0;for(let Ue=0;Ue<T.length;Ue++){let kt=(T[Ue]-128)/128;_+=kt*kt}let Ie=Math.sqrt(_/T.length),De=Math.min(100,Ie*200);Ne(De),U.current=requestAnimationFrame(N)};N(),Fe.current=[];let q=Date.now();d.ondataavailable=_=>{_.data.size>0&&Fe.current.push(_.data)},d.onstop=()=>{let _=new Blob(Fe.current,{type:"audio/webm"}),Ie=(Date.now()-q)/1e3,De=It(_);De&&re({id:gt("composer-audio"),blob:_,objectUrl:De,duration:Ie}),t.getTracks().forEach(Ue=>Ue.stop()),U.current&&(cancelAnimationFrame(U.current),U.current=null),Ce.current&&(Ce.current.close(),Ce.current=null),Me.current=null,Ne(0)},We.current=d,d.start(),Qe(!0)}catch(t){console.error("Failed to start recording:",t)}},[me]),ft=(0,o.useCallback)(()=>{We.current&&ge&&(We.current.stop(),Qe(!1))},[ge]);(0,o.useEffect)(()=>()=>{U.current&&cancelAnimationFrame(U.current),Ce.current&&Ce.current.close(),me()},[me]);let[st,i]=(0,o.useState)(null),v=(0,o.useRef)(W),Y=(0,o.useRef)(M),Z=(0,o.useRef)(st),le=(0,o.useRef)(D),J=(0,o.useRef)(w);(0,o.useEffect)(()=>{v.current=W},[W]),(0,o.useEffect)(()=>{le.current=D},[D]),(0,o.useEffect)(()=>{J.current=w},[w]),(0,o.useEffect)(()=>{Y.current=M},[M]),(0,o.useEffect)(()=>{Z.current=st},[st]),(0,o.useEffect)(()=>{E&&A.I18n.setLanguage(E||"en")},[E]);let X=(0,va.useSelect)(()=>(0,zt.getStoreSelect)(g).isShowChatbotPreview()),ue=(0,o.useMemo)(()=>Math.max(0,L??Sr),[L]),qe=(0,o.useMemo)(()=>Math.max(0,m??Rr),[m]),nt=M.length>0,de=(0,o.useMemo)(()=>P.busy&&Re==="chat",[P.busy,Re]),Xt=(0,o.useMemo)(()=>de?!1:W.trim().length>0||w!==null,[W,de,w]),vt=(0,o.useMemo)(()=>{let t=p||y.askMeLabel;return A.I18n.get(t)},[p,y.askMeLabel,E]),Ma=(0,o.useMemo)(()=>{let t=n||y.modalTitle;return A.I18n.get(t)},[n,y.modalTitle,E]),Pa=(0,o.useMemo)(()=>{let t=ee||y.placeholder;return A.I18n.get(t)},[ee,y.placeholder,E]),bn=(0,o.useMemo)(()=>{let t="ai-docs-ask",d=`ai-open-btn--${he}`;return`${t} ${d}`},[he]),Et=(0,o.useCallback)(()=>{let t=we.current;if(t)try{let d=window.innerHeight||document.documentElement.clientHeight,b=360,u=1e3,C=Math.floor(d*.8),T=Math.max(b,Math.min(C,u));t.style.height=`${T}px`}catch{}},[]),xt=(0,o.useCallback)(()=>{let t=Q;t&&window.setTimeout(()=>{try{t.scrollTop=t.scrollHeight}catch{}},50)},[Q]),yn=(0,o.useCallback)(()=>{et(!1),Se&&Ke(!1),Xe(!1),ae?.()},[Se,ae]);(0,o.useEffect)(()=>{if(ie)return Et(),window.addEventListener("resize",Et),()=>window.removeEventListener("resize",Et)},[ie,Et]),(0,o.useEffect)(()=>{if(!(!ie||!Se))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[ie,Se,yn]);let An=(0,o.useMemo)(()=>D.map(t=>({id:t.id,url:t.objectUrl,title:t.file.name})),[D]);(0,o.useEffect)(()=>{nt||rt(!0)},[nt]),(0,o.useEffect)(()=>()=>{F(le.current)},[F]),(0,o.useEffect)(()=>{let t=Q;if(!t)return;let d=()=>{let b=t.scrollHeight-(t.scrollTop+t.clientHeight);rt(b<20)};return t.addEventListener("scroll",d),()=>{t.removeEventListener("scroll",d)}},[ie,Q]),(0,o.useEffect)(()=>{if(!B)return;let t=Q;t&&t.scrollHeight>t.clientHeight&&(t.scrollTop=t.scrollHeight)},[M,P.busy,B,Q]),(0,o.useEffect)(()=>{ie||pt(null)},[ie]);let vn=(0,o.useMemo)(()=>P.busy?zr(P.statusEvent,y)||A.I18n.get("Working\u2026"):null,[P.busy,P.statusEvent,E,y]),Da=(0,o.useMemo)(()=>{for(let t=M.length-1;t>=0;t--){let d=M[t];if(d.role==="user"&&d.clientStatus==="canceled")return d.id}return null},[M]),Lt=(0,o.useCallback)(t=>{fe(d=>{let b=[...d].map((T,N)=>({m:T,i:N})).reverse().find(T=>T.m.role==="user"&&T.m.clientStatus==="pending")?.i;if(b==null)return d;let u=d.slice(),C=u[b];return u[b]={...C,clientStatus:t??void 0},u})},[fe]),Bt=(0,o.useCallback)(()=>{if(!(!P.busy||it.current!=="chat")){tt.current=!0;try{P.cancel()}catch{}Lt("canceled"),I(null),oe(null),xt()}},[P,Lt,xt]),Ea=(0,o.useCallback)(t=>{let d=le.current,b=Array.from(t.target.files||[]),u=Math.max(0,ue-d.length);if(u===0){t.currentTarget.value="";return}let C=[];for(let T of b){if(C.length>=u)break;let N=/image\/(jpeg|png|gif|webp)/i.test(T.type),q=T.size<=qe,_=[...d,...C].some(De=>De.file.name===T.name&&De.file.size===T.size&&De.file.lastModified===T.lastModified);if(!N||!q||_)continue;let Ie=It(T);Ie&&C.push({id:gt("composer-image"),file:T,objectUrl:Ie})}C.length&&Te(T=>[...T,...C]),t.currentTarget.value=""},[ue,qe]),Ba=(0,o.useCallback)(t=>{Te(d=>{if(t<0||t>=d.length)return d;let b=d[t];return b&&_t(b.objectUrl),d.filter((u,C)=>C!==t)})},[]),lt=(0,o.useRef)(null);(0,o.useEffect)(()=>{if(Je)return lt.current&&(window.clearTimeout(lt.current),lt.current=null),lt.current=window.setTimeout(()=>{oe(null),lt.current=null},6e3),()=>{lt.current&&(window.clearTimeout(lt.current),lt.current=null)}},[Je]);let wn=(0,o.useCallback)(async(t,d)=>{let b=x!=="nostorage",u=[];if(t.length>0){let C=await Promise.all(t.map(async T=>{let N=gt("attachment-image"),q;if(b)try{q=await gn(N,T.file,{name:T.file.name,type:T.file.type,size:T.file.size})??void 0}catch(Ie){console.warn("[AiChatbot] Failed to persist image",Ie)}let _=It(T.file);return{id:N,name:T.file.name,type:T.file.type||"application/octet-stream",size:T.file.size,blobId:q,objectUrl:_??void 0,blob:T.file,mediaType:"image"}}));u.push(...C.filter(Boolean))}if(d){let C=gt("attachment-audio"),T;if(b)try{T=await gn(C,d.blob,{name:`audio-${Date.now()}.webm`,type:d.blob.type,size:d.blob.size})??void 0}catch(q){console.warn("[AiChatbot] Failed to persist audio",q)}let N=It(d.blob);u.push({id:C,name:`audio-${Date.now()}.webm`,type:d.blob.type||"audio/webm",size:d.blob.size,blobId:T,objectUrl:N??void 0,blob:d.blob,duration:d.duration,mediaType:"audio"})}return u},[x]),Tn=(0,o.useCallback)(async t=>{let d=[];for(let b of t){let u;if(b.attachments&&b.attachments.length>0){u=[];for(let C of b.attachments){let T;if(C.blobId)try{T=(await mn(C.blobId))?.blob??void 0}catch(q){console.warn("[AiChatbot] Failed to hydrate attachment",q)}if(!T)continue;let N=T?It(T):null;u.push({...C,objectUrl:N??void 0,blob:T??void 0})}}d.push({...b,attachments:u})}return d},[]),Sn=(0,o.useCallback)(async t=>{if(!t||t.length===0){se();return}let d=[];for(let b of t){let u=b.blob;if(!u&&b.blobId)try{u=(await mn(b.blobId))?.blob??void 0}catch(N){console.warn("[AiChatbot] Failed to reload attachment",N)}if(!u)continue;let C=u instanceof File?u:new File([u],b.name||"attachment",{type:b.type||u.type||"application/octet-stream"}),T=It(C);if(T&&(d.push({id:gt("composer-image"),file:C,objectUrl:T}),d.length>=ue))break}if(d.length===0){se();return}Te(b=>(F(b),d)),R.current&&(R.current.value="")},[se,F,ue]),en=(0,o.useCallback)((t,d)=>{t&&pt({url:t,title:d})},[]),Ka=(0,o.useCallback)(()=>{pt(null)},[]),Rn=(0,o.useCallback)(()=>{Aa(Y.current),se(),me(),fe([]),oe(null),V.current=null,i(null),rt(!0),mt(!1);let t=fn(x);if(t)try{t.removeItem(Rt)}catch{}Jt()},[se,me,x]),Ua=(0,o.useCallback)(()=>{mt(!0)},[]),Oa=(0,o.useCallback)(()=>{P.busy&&it.current==="chat"&&Bt(),Rn()},[P.busy,Bt,Rn]),In=(0,o.useCallback)(()=>{mt(!1)},[]),zn=(0,o.useCallback)(async(t,d)=>{if(!P.busy)try{let b=V.current&&Date.now()-V.current.storedAt<ye*Vt?V.current.id:void 0;if(!b)return;I("feedback"),oe(null),await P.run(async({signal:u,onStatus:C})=>(await(0,zt.sendFeedbackMessage)({sessionId:b,feedbackMessageId:t,feedbackType:d},{signal:u,onStatus:C,context:Ee}),null)),oe(null)}catch(b){let u=b?.message?.trim()||A.I18n.get("An error occurred.");oe(u),console.error("Failed to send feedback",b)}finally{I(b=>b==="feedback"?null:b)}},[P,E]),Cn=(0,o.useCallback)((t,d)=>{fe(b=>b.map(u=>u.id!==t||u.role!=="assistant"?u:u.feedback===d?{...u,feedback:void 0}:{...u,feedback:d})),zn(t,d)},[zn]),Kt=(0,o.useCallback)(async()=>{let t=v.current.trim(),d=J.current;if(!t&&!d||P.busy)return;tt.current=!1,oe(null),I("chat");let b=[...le.current],u=await wn(b,d),C=gt("user"),T=Date.now(),N={id:C,role:"user",content:t||(d?"[Audio message]":""),createdAt:T,clientStatus:"pending",attachments:u.length?u:void 0};ze(""),se(),me(),fe(q=>[...q,N]),ie||et(!0),xt();try{let q=V.current&&Date.now()-V.current.storedAt<ye*Vt?V.current.id:void 0,_=await P.run(async({signal:De,onStatus:Ue})=>await(0,zt.sendChatMessage)({sessionId:q,message:t||void 0,audio:d?.blob,images:b.map($a=>$a.file)},{signal:De,onStatus:Ue,context:Ee}));if(tt.current){Lt("canceled");return}if(!_)throw new Error(A.I18n.get(P.error??y.emptyResponseLabel));_.sessionId&&(V.current={id:_.sessionId,storedAt:Date.now()});let Ie={id:_.metadata?.messageId||gt("assistant"),role:"assistant",content:_.result||"",citations:_.citations,createdAt:Date.now()};fe(De=>[...De.map(kt=>kt.id===C?{...kt,clientStatus:void 0}:kt),Ie]),i(T)}catch(q){if(console.error("Error during ask()",q),tt.current||Ir(q)){Lt("canceled");return}let _=q?.message?.trim()||A.I18n.get(y.unexpectedErrorLabel);fe(Ie=>[...Ie.map(Ue=>Ue.id===C?{...Ue,clientStatus:void 0}:Ue),{id:gt("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${_}`,createdAt:Date.now()}]),i(T)}finally{I(q=>q==="chat"?null:q),tt.current=!1,O.current&&O.current.focus(),xt()}},[P,wn,se,me,ie,xt,Lt,y.emptyResponseLabel,y.unexpectedErrorLabel,E]),Na=(0,o.useCallback)(t=>{t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Xt&&Kt())},[Kt,Xt]),ja=(0,o.useCallback)(()=>{et(!0)},[]);(0,o.useEffect)(()=>()=>{xe.current!=null&&(cancelAnimationFrame(xe.current),xe.current=null)},[]);let Ga=(0,o.useCallback)(()=>{Ke(t=>{let d=!t;return xe.current!=null&&(cancelAnimationFrame(xe.current),xe.current=null),d?(Xe(!0),requestAnimationFrame(()=>{xe.current=requestAnimationFrame(()=>{Xe(!1),xe.current=null})})):Xe(!1),d})},[]),Ha=(0,o.useCallback)(t=>{ze(t.content),(async()=>(await Sn(t.attachments),fe(d=>d.filter(b=>b.id!==t.id)),Sa(t.attachments),queueMicrotask(()=>O.current?.focus())))()},[Sn]),xn=(0,o.useMemo)(()=>te?z?(0,s.jsx)("img",{src:z,className:"ai-open-btn-icon",alt:A.I18n.get(y.askMeLabel||vt)}):(0,s.jsx)(pe.IconMessage,{size:18}):null,[te,z,y,vt,E]),Wa=(0,o.useMemo)(()=>{let t=xn,d=H?(0,s.jsx)(h.Text,{inherit:!0,children:vt}):null;if(!te&&!d)return null;if(!te)return d;if(!H)return t;switch($){case"top":return(0,s.jsxs)(h.Stack,{gap:4,align:"center",children:[t,d]});case"bottom":return(0,s.jsxs)(h.Stack,{gap:4,align:"center",children:[d,t]});case"right":return(0,s.jsxs)(h.Group,{gap:6,align:"center",children:[d,t]});default:return(0,s.jsxs)(h.Group,{gap:6,align:"center",children:[t,d]})}},[xn,te,H,vt,$]),Fa=(0,o.useMemo)(()=>de,[de]),qa=(0,o.useMemo)(()=>!de,[de]),Ya=(0,o.useMemo)(()=>Je||(nt?A.I18n.get(y.readyLabel):A.I18n.get(y.readyEmptyLabel)),[Je,nt,y.readyLabel,y.readyEmptyLabel,E]),Ja=(0,o.useMemo)(()=>de?A.I18n.get(y.cancelLabel):A.I18n.get(y.sendLabel),[de,y.cancelLabel,y.sendLabel,E]),Va=(0,o.useMemo)(()=>de?(0,s.jsx)(pe.IconPlayerStop,{size:18}):(0,s.jsx)(pe.IconSend,{size:18}),[de]),_a=(0,o.useCallback)(()=>{if(de){Bt();return}Kt()},[de,Bt,Kt]);return(0,o.useEffect)(()=>{if(!ie||!ke||!Q)return;let t=()=>{let q=window.getComputedStyle(Q).overflowY,_=q==="auto"||q==="scroll",Ie=Math.ceil(Q.scrollHeight),De=Math.floor(Q.clientHeight),Ue=Ie>De;return _&&Ue},d=!1,b=N=>{if(!t())return;N.preventDefault();let q=Q.scrollHeight-Q.clientHeight;Q.scrollTop=Math.max(0,Math.min(q,Q.scrollTop+N.deltaY))},u=()=>{let N=t();Ge(N),N!==d&&(d=N,d?ke.addEventListener("wheel",b,{passive:!1}):ke.removeEventListener("wheel",b))};u();let C=new ResizeObserver(u);C.observe(Q);let T=new MutationObserver(u);return T.observe(Q,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",u),()=>{d&&ke.removeEventListener("wheel",b),C.disconnect(),T.disconnect(),window.removeEventListener("resize",u)}},[ie,ke,Q]),(0,o.useEffect)(()=>{let t=!1,d=fn(x);if(!d){x==="nostorage"&&Jt(),Pe(!0);return}return(async()=>{try{let b=d.getItem(Rt);if(!b){Pe(!0);return}let u=JSON.parse(b),C=typeof u?.lastUserSentAt=="number"?u.lastUserSentAt:null;if(!C||Date.now()-C>ye*Vt){d.removeItem(Rt),await Jt(),Pe(!0);return}let N=(Array.isArray(u.messages)?u.messages:[]).map(_=>_?.role==="user"&&_.clientStatus==="pending"?{..._,clientStatus:"canceled"}:_),q=await Tn(N);if(t){Aa(q);return}fe(q),i(C),u.session&&u.session.id&&(V.current=u.session)}catch(b){console.warn("[AiChatbot] Failed to load history",b);try{d.removeItem(Rt)}catch{}}finally{t||Pe(!0)}})(),()=>{t=!0}},[x,ye,Tn]),(0,o.useEffect)(()=>{if(!je)return;let t=fn(x);if(!t)return;let d=Z.current;if(!d)return;if(Date.now()-d>ye*Vt){try{t.removeItem(Rt)}catch{}pn(new Set);return}let b=M.map(({attachments:T,...N})=>({...N,attachments:T?.map(({objectUrl:q,blob:_,...Ie})=>Ie)})),u={version:1,lastUserSentAt:d,session:V.current,messages:b};try{t.setItem(Rt,JSON.stringify(u))}catch{}let C=new Set;b.forEach(T=>{T.attachments?.forEach(N=>{N.blobId&&C.add(N.blobId)})}),pn(C)},[je,M,st,x,ye]),l&&!X||!l&&X?null:(0,s.jsxs)(h.Group,{className:bn,children:[!ie&&(0,s.jsx)(h.Button,{variant:"filled",className:H?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:ja,"aria-label":vt,title:vt,"data-ai-kit-open-button":!0,children:Wa}),ie&&(0,s.jsx)(h.Modal.Root,{ref:we,opened:ie,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:yn,className:bn+" ai-chat-container"+(Se?" maximized":"")+(Se&&Ve?" ai-max-enter":""),portalProps:{target:a,reuseTargetNode:!0},"data-ai-kit-theme":ne,"data-ai-kit-variation":"modal",children:(0,s.jsxs)("div",{className:"ai-chat-container-internal",ref:Ct,children:[(0,s.jsxs)(h.Modal.Header,{className:"ai-chat-header-bar",children:[(0,s.jsx)(h.Modal.Title,{className:"ai-chat-title",children:Ma}),(0,s.jsxs)(h.Group,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&(0,s.jsx)(h.ActionIcon,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:Ga,title:Se?A.I18n.get(y.restoreSizeLabel):A.I18n.get(y.maximizeLabel),"aria-label":Se?A.I18n.get(y.restoreSizeLabel):A.I18n.get(y.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Se?(0,s.jsx)(pe.IconMinimize,{size:16}):(0,s.jsx)(pe.IconMaximize,{size:16})}),(0,s.jsx)(h.Modal.CloseButton,{"aria-label":A.I18n.get(y.closeChatLabel)})]})]}),(0,s.jsxs)(h.Modal.Body,{className:"ai-chat-scroll",ref:ht,"data-scrollable":ot?"true":"false",children:[M.map(t=>{let d=t.role==="user",b=d&&t.clientStatus==="canceled"&&t.id===Da;return(0,s.jsx)(h.Group,{justify:d?"flex-end":"flex-start",className:"ai-chat-row "+t.role,onMouseEnter:()=>At(t.id),onMouseLeave:()=>At(u=>u===t.id?null:u),children:(0,s.jsxs)(h.Stack,{gap:4,w:"100%",style:{alignItems:d?"flex-end":"flex-start"},children:[(0,s.jsxs)(h.Stack,{className:"ai-chat-bubble",children:[(0,s.jsxs)(h.Text,{className:"ai-chat-header",children:[(0,s.jsx)(h.Text,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:d?A.I18n.get(y.userLabel):A.I18n.get(y.assistantLabel)}),"\xA0",(0,s.jsx)(h.Text,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(t.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),t.role==="assistant"?(0,s.jsx)(wa.default,{remarkPlugins:[Ta.default],children:t.content}):(0,s.jsx)(h.Text,{size:"sm",miw:"100px",children:t.content})]}),t.attachments&&t.attachments.length>0&&(0,s.jsxs)(h.Stack,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).length>0&&(0,s.jsx)(h.Group,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:t.attachments.filter(u=>u.mediaType==="image"||!u.mediaType&&u.type.startsWith("image/")).map(u=>(0,s.jsx)("button",{type:"button",className:"thumb",style:{backgroundImage:u.objectUrl?`url(${u.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>en(u.objectUrl,u.name),disabled:!u.objectUrl,title:u.name||A.I18n.get("View image"),"aria-label":u.name||A.I18n.get("View image"),children:!u.objectUrl&&(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:A.I18n.get("Image no longer available")})},u.id))}),t.attachments.filter(u=>u.mediaType==="audio"||!u.mediaType&&u.type.startsWith("audio/")).map(u=>(0,s.jsx)(h.Box,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:u.objectUrl?(0,s.jsxs)(h.Stack,{gap:"xs",children:[(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:u.objectUrl,preload:"metadata"}),u.duration&&(0,s.jsxs)(h.Text,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(u.duration),"s"]})]}):(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:A.I18n.get("Audio no longer available")})},u.id))]}),b&&(0,s.jsxs)(h.Group,{justify:"flex-end",gap:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:A.I18n.get(y.notSentLabel)})}),yt===t.id&&(0,s.jsx)(h.ActionIcon,{size:"sm",variant:"subtle",onClick:()=>Ha(t),title:A.I18n.get(y.editLabel),"aria-label":A.I18n.get(y.editLabel),"data-ai-kit-edit-button":!0,children:(0,s.jsx)(pe.IconPencil,{size:14})})]}),t.citations&&t.citations.length>0&&(0,s.jsxs)(h.Stack,{className:"ai-citations",children:[(0,s.jsx)(h.Text,{fw:"bold",size:"sm",mb:"xs",children:A.I18n.get(y.referencesLabel)}),(0,s.jsx)(h.List,{spacing:"xs",size:"sm",children:t.citations.map((u,C)=>{let T=u.sourceUrl||u.url,N=u.title||T||`${A.I18n.get(y.referenceLabel)} #${C+1}`;return(0,s.jsxs)(h.List.Item,{children:[T?(0,s.jsx)(h.Anchor,{href:T,target:"_blank",rel:"noreferrer",children:N}):(0,s.jsx)(h.Text,{children:N}),u.snippet?(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",mt:4,children:u.snippet}):null]},C)})})]}),t.role==="assistant"&&(0,s.jsxs)(h.Group,{className:"ai-feedback",gap:"xs",children:[(0,s.jsx)(h.Button,{className:t.feedback==="accepted"?"active":void 0,onClick:()=>Cn(t.id,"accepted"),"aria-label":A.I18n.get(y.acceptResponseLabel),disabled:P.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),(0,s.jsx)(h.Button,{type:"button",className:t.feedback==="rejected"?"active":void 0,onClick:()=>Cn(t.id,"rejected"),"aria-label":A.I18n.get(y.rejectResponseLabel),disabled:P.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},t.id)}),Fa&&(0,s.jsx)(h.Group,{justify:"flex-start",className:"ai-chat-row assistant status",children:(0,s.jsxs)(h.Stack,{className:"ai-chat-bubble typing",children:[vn?(0,s.jsx)(h.Text,{size:"sm",c:"dimmed",children:(0,s.jsx)("em",{children:vn})}):null,(0,s.jsxs)("div",{className:"typing-indicator",children:[(0,s.jsx)("span",{}),(0,s.jsx)("span",{}),(0,s.jsx)("span",{})]})]})})]}),qa&&(0,s.jsx)(h.Group,{className:"ai-status-line",children:(0,s.jsx)(h.Text,{className:"ai-status-text",children:(0,s.jsx)("em",{children:Ya})})}),(0,s.jsxs)(h.Stack,{className:"ai-box ai-box-open",children:[(0,s.jsxs)(h.Modal,{opened:Ae,onClose:In,centered:!0,title:A.I18n.get("Reset conversation"),style:{position:"fixed"},left:0,children:[(0,s.jsx)(h.Text,{size:"sm",children:A.I18n.get("Are you sure you want to reset the conversation?")}),(0,s.jsxs)(h.Group,{justify:"flex-end",mt:"md",children:[(0,s.jsx)(h.Button,{variant:"default",onClick:In,"data-ai-kit-no-button":!0,children:A.I18n.get("No")}),(0,s.jsx)(h.Button,{color:"var(--ai-kit-color-danger, red)",onClick:Oa,disabled:!nt&&!de,"data-ai-kit-yes-button":!0,children:A.I18n.get("Yes")})]})]}),(0,s.jsx)(h.Group,{children:(0,s.jsx)(h.Textarea,{className:"ai-message",ref:O,placeholder:Pa,value:W,onChange:t=>{ze(t.target.value),w&&me()},onKeyDown:Na,rows:3,disabled:ge||!!w})}),hn&&ge&&(0,s.jsxs)(h.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsx)("em",{children:A.I18n.get("Recording...")})}),(0,s.jsx)("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:(0,s.jsx)("div",{style:{width:`${at}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),hn&&w&&!ge&&(0,s.jsxs)(h.Stack,{gap:"xs",mt:"xs",children:[(0,s.jsx)(h.Text,{size:"xs",c:"dimmed",children:(0,s.jsxs)("em",{children:[A.I18n.get("Audio recorded")," (",Math.round(w.duration),"s)"]})}),(0,s.jsx)("audio",{className:"ai-kit-audio-player",controls:!0,src:w.objectUrl})]}),(0,s.jsxs)(h.Group,{className:"ai-actions",justify:"space-between",w:"100%",children:[(0,s.jsx)(h.Group,{justify:"flex-start",children:(0,s.jsx)(h.Button,{variant:"light",leftSection:(0,s.jsx)(pe.IconTrash,{size:18}),onClick:Ua,disabled:!nt&&!de,"data-ai-kit-reset-button":!0,children:A.I18n.get(y.resetLabel)})}),(0,s.jsxs)(h.Group,{justify:"flex-end",children:[hn&&(0,s.jsx)(s.Fragment,{children:w?(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconX,{size:18}),onClick:me,disabled:de,title:A.I18n.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:A.I18n.get("Clear")}):(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconMicrophone,{size:18}),onClick:ge?ft:be,disabled:de,title:ge?A.I18n.get("Stop recording"):A.I18n.get("Record audio"),color:ge?"red":void 0,"data-ai-kit-microphone-button":!0,children:ge?A.I18n.get("Stop"):A.I18n.get("Record")})}),ue>0&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(h.Button,{variant:"outline",leftSection:(0,s.jsx)(pe.IconPaperclip,{size:18}),onClick:()=>R.current?.click(),disabled:D.length>=ue||de||ge||!!w,title:A.I18n.get(y.addImageLabel),"data-ai-kit-add-image-button":!0,children:A.I18n.get(y.addLabel)}),(0,s.jsx)(h.Input,{ref:R,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Ea})]}),(0,s.jsx)(h.Button,{leftSection:Va,variant:"filled",onClick:_a,disabled:!de&&!Xt,"data-ai-kit-send-button":!0,children:Ja})]})]}),An.length>0&&(0,s.jsx)(h.Group,{className:"ai-thumbs",mt:"xs",gap:"xs",children:An.map(({url:t,title:d},b)=>(0,s.jsx)("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:t?`url(${t})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":d||A.I18n.get("View image"),onClick:()=>en(t,d),onKeyDown:u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),en(t,d))},children:(0,s.jsx)(h.Button,{variant:"white",onClick:u=>{u.stopPropagation(),Ba(b)},"aria-label":A.I18n.get(y.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:A.I18n.get(y.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},D[b]?.id??b))})]})]})}),(0,s.jsx)(h.Modal,{opened:!!ve,onClose:Ka,centered:!0,size:"auto",title:ve?.title||A.I18n.get("Image preview"),children:ve&&(0,s.jsx)("img",{src:ve.url,alt:ve.title||A.I18n.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},Ra=ct(Cr,{showOpenButton:!0,variation:"modal"});var S=require("@mantine/core"),Zt=require("@smart-cloud/ai-kit-core"),ce=require("aws-amplify/utils"),j=require("react"),za=He(require("react-markdown"),1),Ca=He(require("rehype-raw"),1),xa=He(require("remark-gfm"),1),kn=require("@tabler/icons-react"),Qt=require("@tabler/icons-react");var k=require("react/jsx-runtime");ce.I18n.putVocabularies(ut);var Ia=!1;function xr(e){let a=e?.citations?.docs??[],g=e?.citations?.chunks??[],l=new Map;for(let n of a)l.set(n.docId,{doc:n,chunks:[]});for(let n of g){let p=l.get(n.docId);p?p.chunks.push(n):l.set(n.docId,{doc:{docId:n.docId},chunks:[n]})}return Array.from(l.values())}var Lr=e=>{let{autoRun:a=!0,context:g,title:l,searchButtonIcon:n,showSearchButtonTitle:p=!0,showSearchButtonIcon:z=!0,showSources:H=!0,topK:te=10,getSearchText:ne,variation:E,rootElement:ae,colorMode:Ee,language:ee,onClose:L,onClickDoc:m,showOpenButton:x=!1,openButtonTitle:ye,openButtonIcon:Be,showOpenButtonTitle:$=!0,showOpenButtonIcon:he=!0}=e,[y,P]=(0,j.useState)(""),[W,ze]=(0,j.useState)(!x),[D,Te]=(0,j.useState)(!1),[w,re]=(0,j.useState)(null),[ge,Qe]=(0,j.useState)(0),at=(0,j.useRef)(null),Ne=(0,j.useRef)([]),We=(0,j.useRef)(null),Fe=(0,j.useRef)(null),Ce=(0,j.useRef)(null),Me=(0,j.useRef)(null),U=1440*60*1e3,{busy:M,error:fe,statusEvent:Je,result:oe,run:Ae,cancel:mt,reset:Se}=bt(),Ke=(0,j.useRef)(!1),Ve=oe?.sessionId,Xe=oe?.citations?.docs??[],ie=oe?.citations?.chunks??[],et=oe?.citations?.anchors??[],B=oe?.result??"",rt=(0,j.useMemo)(()=>{if(z)return n?.trim()?(0,k.jsx)("img",{src:n,alt:"",style:{width:18,height:18,objectFit:"contain"}}):(0,k.jsx)(kn.IconSearch,{size:18})},[n,z]),ve=(0,j.useMemo)(()=>(ee&&ce.I18n.setLanguage(ee||"en"),ce.I18n.get(l||"Search with AI-Kit")),[ee]),pt=(0,j.useCallback)(R=>(0,k.jsx)(kn.IconSearch,{className:R,size:18}),[]),je=(0,j.useMemo)(()=>Je?ce.I18n.get("Searching\u2026"):null,[ee,Je]),Pe=(0,j.useMemo)(()=>y||ne,[y,ne]),ke=(0,j.useMemo)(()=>{if(M)return!1;let R=typeof Pe=="function"?Pe():Pe;return!!(R&&R.trim().length>0||w)},[Pe,M,w]),Ct=(0,j.useCallback)(async()=>{try{P("");let R=await navigator.mediaDevices.getUserMedia({audio:!0}),O=new MediaRecorder(R,{mimeType:"audio/webm"}),V=new AudioContext,we=V.createMediaStreamSource(R),F=V.createAnalyser();F.fftSize=2048,F.smoothingTimeConstant=.8,we.connect(F),We.current=V,Fe.current=F;let se=new Uint8Array(F.fftSize),me=()=>{if(!Fe.current)return;Fe.current.getByteTimeDomainData(se);let be=0;for(let i=0;i<se.length;i++){let v=(se[i]-128)/128;be+=v*v}let ft=Math.sqrt(be/se.length),st=Math.min(100,ft*200);Qe(st),Ce.current=requestAnimationFrame(me)};me(),Ne.current=[],O.ondataavailable=be=>{be.data.size>0&&Ne.current.push(be.data)},O.onstop=()=>{let be=new Blob(Ne.current,{type:"audio/webm"});re(be),R.getTracks().forEach(ft=>ft.stop()),Ce.current&&(cancelAnimationFrame(Ce.current),Ce.current=null),We.current&&(We.current.close(),We.current=null),Fe.current=null,Qe(0)},at.current=O,O.start(),Te(!0)}catch(R){console.error("Failed to start recording:",R)}},[]),Q=(0,j.useCallback)(()=>{at.current&&D&&(at.current.stop(),Te(!1))},[D]),ht=(0,j.useCallback)(()=>{re(null),Ne.current=[],Qe(0),Me.current=null},[]);(0,j.useEffect)(()=>()=>{Ce.current&&cancelAnimationFrame(Ce.current),We.current&&We.current.close()},[]);let ot=(0,j.useCallback)(async()=>{let R;if(!w){if(R=typeof Pe=="function"?Pe():Pe,!R)return;P(R)}console.log("Starting search with query:",R,"and audio:",w);let O=Date.now(),V=w&&Me.current?.blob===w&&O-Me.current.uploadTimestamp<U;w&&!V?(Me.current={blob:w,uploadTimestamp:O},console.log("Audio cache updated for new recording")):V&&console.log("Reusing cached audio (no re-upload needed within",Math.round((U-(O-Me.current.uploadTimestamp))/1e3),"seconds)"),Se(),await Ae(async({signal:we,onStatus:F})=>await(0,Zt.sendSearchMessage)({sessionId:Ve,...R&&{query:R},...w&&{audio:w},topK:te},{signal:we,onStatus:F,context:g}))},[g,Pe,w,Ae,Se,te,Ve]),Ge=(0,j.useCallback)(async()=>{ze(!1),Se(),Ke.current=!1,x||L()},[L,Se,Ke,x]);(0,j.useEffect)(()=>{!a||!ke||M||Ke.current||(Ke.current=!0,queueMicrotask(()=>{ot()}))},[M,Ke,ke,a,ot]),(0,j.useEffect)(()=>{ke||(Ke.current=!0)},[ke]);let Re=(0,j.useMemo)(()=>xr(oe),[oe]),I=(0,j.useMemo)(()=>{let R=new Map;return Xe.forEach((O,V)=>{O?.docId&&R.set(O.docId,V+1)}),R},[Xe]),it=(0,j.useMemo)(()=>{let R=new Map;return ie.forEach(O=>{O?.chunkId&&O?.docId&&R.set(O.chunkId,O.docId)}),R},[ie]),xe=(0,j.useMemo)(()=>{if(!B)return"";if(!et.length||I.size===0)return B;let R=[...et].filter(we=>Array.isArray(we?.chunkIds)&&we?.span?.end!==void 0).sort((we,F)=>{let se=we.span?.end??0,me=F.span?.end??0;return se-me}),O=0,V=[];for(let we of R){let F=we.span?.end;if(typeof F!="number"||F<O)continue;let se=Array.from(new Set((we.chunkIds??[]).map(be=>be?it.get(be):void 0).map(be=>be?I.get(be):void 0).filter(be=>typeof be=="number")));if(!se.length)continue;let me=Math.min(F,B.length);V.push(B.slice(O,me)),V.push(`<sup>${se.join(",")}</sup>`),O=me}return V.push(B.slice(O)),V.join("")},[et,B]),tt=E==="modal"?S.Modal.Root:S.Group,yt=E==="modal"?S.Modal.Content:S.Group,At=E==="modal"?S.Modal.Body:S.Group;return(0,j.useEffect)(()=>{if(!(E!=="modal"||!W))return document.body.style.overflow="hidden",document.body.onkeydown=R=>{R.key==="Escape"&&(R.preventDefault(),Ge())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[Ge,E]),(0,k.jsxs)(k.Fragment,{children:[x&&(0,k.jsx)(S.Button,{leftSection:he&&(Be?(0,k.jsx)("span",{dangerouslySetInnerHTML:{__html:Be}}):pt()),className:$?"doc-search-button":"doc-search-button-no-title",variant:"filled",disabled:W,onClick:()=>ze(!0),"data-ai-kit-open-button":!0,children:$&&ce.I18n.get(ye||ve)}),W&&(0,k.jsxs)(tt,{opened:!0,className:"doc-search-root",onClose:Ge,padding:"md",gap:"md",size:"xl",portalProps:E==="modal"?{target:ae,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ee,"data-ai-kit-variation":E,children:[E==="modal"&&(0,k.jsx)(S.Modal.Overlay,{}),(0,k.jsxs)(yt,{w:"100%",style:{left:0},children:[E==="modal"&&(0,k.jsxs)(S.Modal.Header,{style:{zIndex:1e3},children:[(0,k.jsx)(Zt.AiKitDocSearchIcon,{className:"doc-search-title-icon"}),(0,k.jsx)(S.Modal.Title,{children:ce.I18n.get(ve)}),(0,k.jsx)(S.Modal.CloseButton,{})]}),(0,k.jsx)(At,{w:"100%",style:{zIndex:1001},children:(0,k.jsx)(Tt,{enabled:E!=="modal",working:M,variation:E,children:(0,k.jsx)(S.Paper,{shadow:"sm",radius:"md",p:"md",children:(0,k.jsxs)(S.Stack,{gap:"sm",children:[E!=="modal"&&(0,k.jsx)(S.Title,{order:4,style:{margin:0},children:ce.I18n.get(ve)}),(0,k.jsxs)(S.Group,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[(0,k.jsx)(S.TextInput,{style:{flex:1},value:y,onChange:R=>{P(R.currentTarget.value),w&&ht()},placeholder:w?ce.I18n.get("Audio recorded"):ce.I18n.get("Search the documentation\u2026"),disabled:M||D||!!w,onKeyDown:R=>{R.key==="Enter"&&ke&&(R.preventDefault(),ot())}}),Ia&&(0,k.jsx)(k.Fragment,{children:w?(0,k.jsx)(S.Button,{variant:"outline",size:"sm",color:"red",onClick:ht,disabled:M,title:ce.I18n.get("Clear audio"),children:(0,k.jsx)(Qt.IconMicrophoneOff,{size:18})}):(0,k.jsx)(S.Button,{variant:D?"filled":"outline",size:"sm",color:D?"red":"gray",onClick:D?Q:Ct,disabled:M,title:D?ce.I18n.get("Stop recording"):ce.I18n.get("Record audio"),style:D?{transform:`scale(${1+ge/300})`,transition:"transform 0.1s ease-out"}:void 0,children:(0,k.jsx)(Qt.IconMicrophone,{size:18})})}),(0,k.jsx)(S.Button,{variant:"filled",size:"sm",leftSection:rt,onClick:()=>{ot()},disabled:!ke,className:p?"doc-search-button":"doc-search-button-no-title",children:p?ce.I18n.get("Search"):null}),M?(0,k.jsx)(S.Button,{variant:"outline",size:"sm",onClick:mt,children:ce.I18n.get("Stop")}):null]}),Ia&&(0,k.jsxs)(k.Fragment,{children:[D&&(0,k.jsxs)(S.Stack,{gap:"xs",children:[(0,k.jsxs)(S.Text,{size:"xs",c:"dimmed",children:[ce.I18n.get("Recording...")," \u{1F3A4}"]}),(0,k.jsx)(S.Progress,{value:ge,size:"sm",color:"red",animated:!0,striped:!0})]}),w&&!D&&(0,k.jsxs)(S.Stack,{gap:"xs",children:[(0,k.jsx)(S.Text,{size:"xs",c:"dimmed",children:ce.I18n.get("Recorded audio:")}),(0,k.jsx)("audio",{controls:!0,src:URL.createObjectURL(w),className:"ai-kit-audio-player"})]})]}),fe?(0,k.jsx)(S.Alert,{color:"red",title:ce.I18n.get("Error"),children:fe}):null,M&&je&&(0,k.jsx)(Tt,{enabled:E==="modal",working:!0,variation:E,children:(0,k.jsxs)(S.Group,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[(0,k.jsx)(S.Loader,{size:"sm"}),(0,k.jsx)(S.Text,{size:"sm",c:"dimmed",children:je})]})}),oe?.result?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(S.Divider,{}),(0,k.jsxs)(S.Stack,{gap:"xs","data-doc-search-result":!0,children:[(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:ce.I18n.get("AI Summary")}),(0,k.jsx)(za.default,{remarkPlugins:[xa.default],rehypePlugins:[Ca.default],"data-doc-search-result-content":!0,children:xe||B})]})]}):null,H&&(oe?.citations?.docs?.length||oe?.citations?.chunks?.length)?(0,k.jsxs)(k.Fragment,{children:[(0,k.jsx)(S.Divider,{}),(0,k.jsxs)(S.Stack,{gap:"sm","data-doc-search-sources":!0,children:[(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:ce.I18n.get("Sources")}),Re.map(({doc:R})=>{let O=R.sourceUrl?.trim()||void 0,V=R.docId?I.get(R.docId):void 0,we=R.title?.trim()||R.docId,F=(0,k.jsxs)(S.Text,{fw:600,style:{display:"inline"},children:[V?`${V}. `:"",we]});return(0,k.jsx)(S.Paper,{withBorder:!0,radius:"md",p:"sm",children:(0,k.jsx)(S.Stack,{gap:"xs",children:(0,k.jsx)(S.Group,{justify:"space-between",align:"flex-start",children:(0,k.jsxs)(S.Stack,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[O?(0,k.jsx)(S.Anchor,{href:O,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:se=>{m&&(se.preventDefault(),m?.(R))},"data-doc-search-source-title":!0,children:F}):F,(0,k.jsx)(S.Anchor,{href:O,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:se=>{m&&(se.preventDefault(),m?.(R))},"data-doc-search-source-url":!0,children:R.sourceUrl}),R.author?(0,k.jsx)(S.Text,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:R.author}):null,R.description?(0,k.jsx)(S.Text,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:R.description}):null]})})})},R.docId)})]})]}):null,!M&&!fe&&!oe?.result?(0,k.jsx)(S.Text,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:ce.I18n.get("Enter a search query to start.")}):null,(0,k.jsx)(Nt,{variation:E})]})})})})]})]})]})},La=ct(Lr);0&&(module.exports={AiChatbot,AiFeature,DEFAULT_CHATBOT_LABELS,DocSearch,isBackendConfigured,markdownToHtml,readDefaultOutputLanguage,stripCodeFence,translations,useAiRun,withAiKitShell});
package/dist/index.js CHANGED
@@ -28,4 +28,4 @@ Guidelines:
28
28
  - caption: optional context users might see below the image; keep short.
29
29
  - description: 1\u20132 short sentences; can include context/usage if known.
30
30
  `+(be?`
31
- Follow these additional instructions: ${be}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),Y=await v.run(async({signal:V,onStatus:re})=>(await Ca({messages:N,images:[ee],outputLanguage:"en",responseConstraint:lo},{signal:V,onStatus:re,context:S,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!Y){I("");return}let ae=(M&&M!=="auto"?M:null)||Tt(),j=Yt(Y).trim();try{X("Translating result...");let V=await v.run(async({signal:re})=>await co(j,ae,{signal:re,context:S,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));I(V)}catch(V){I(j),console.warn("AI Kit: failed to parse SEO JSON",V)}break}}}catch(k){De(k instanceof Error?k.message:n.get("An unknown error occurred."))}X(void 0)}},[K,v,be,ye,M,ge,Ge,S,u,me,_e,Se,we]),et=pt(async()=>{await Le("backend-only")},[Le]),Pt=pt(o=>{switch(u){case"proofread":return h(no,{className:o});case"translate":return h(ao,{className:o});case"summarize":return h(io,{className:o});case"rewrite":case"write":return h(ro,{className:o});case"generateImageMetadata":case"generatePostMetadata":return h(oo,{className:o});default:return h(Vr,{mode:u,className:o})}},[u]),Dt=pt(()=>{switch(u){case"proofread":return v.lastSource?n.get("Proofread again"):n.get("Proofread");case"translate":return v.lastSource?n.get("Translate again"):n.get("Translate");case"rewrite":return v.lastSource?n.get("Rewrite again"):n.get("Rewrite");case"summarize":return v.lastSource?n.get("Summarize again"):n.get("Summarize");default:return v.lastSource?n.get("Regenerate"):n.get("Generate")}},[K,v.lastSource,u]),A=pt(()=>{switch(u){case"proofread":return n.get("Proofread on Backend");case"translate":return n.get("Translate on Backend");case"rewrite":return n.get("Rewrite on Backend");case"summarize":return n.get("Summarize on Backend");default:return n.get("Regenerate on Backend")}},[K,u]),D=pt(async()=>{Ze(!1),I(null),De(null),J.current=!1,v.reset(),B||ce()},[ce,J,v,B]),H=pt(async()=>{v.busy&&v.cancel()},[v.busy]);ln(()=>{!ie||!c||!Se||v.busy||P||J.current||(J.current=!0,queueMicrotask(()=>{Le(ke)}))},[v.busy,J,ie,Se,c,P,Le,ke]),ln(()=>{we&&u!=="proofread"&&(Se||(je(!0),J.current=!0))},[we,Se,u]),ln(()=>{let o=!0;return(async()=>{try{await Xr();let k=await ka();o&&Fe(k)}catch(k){console.error(k),o&&Fe(!1)}})(),()=>{o=!1}},[]);let Ae=Vt(()=>{let o=[];if(u==="translate"){let k=sn.find(N=>N.value===_e)?.label;o.push(n.get("Input language")+": "+(k?n.get(k):"auto"))}if(M&&x?.outputLanguage){let k=sn.find(N=>N.value===M)?.label;o.push(n.get("Output language")+": "+(k?n.get(k):M))}return u==="summarize"&&me&&x?.type&&o.push(n.get("Type")+": "+n.get(me)),(u==="write"||u==="rewrite")&&Ge&&x?.tone&&o.push(n.get("Tone")+": "+n.get(Ge)),(u==="write"||u==="rewrite"||u==="summarize")&&ye&&x?.length&&o.push(n.get("Length")+": "+n.get(ye)),be?.trim()&&x?.instructions&&o.push(n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):n.get("No overrides")},[K,u,_e,M,me,Ge,ye,be]),U={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},ne=d==="modal"?zt.Root:ct,se=d==="modal"?zt.Content:ct,pe=d==="modal"?zt.Body:ct,At=R==="collapse"?Wr:ht,ut=R==="horizontal"?ct:ht;return ln(()=>{if(!(d!=="modal"||!ie))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),D())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[D,d]),he(_t,{children:[B&&h(It,{leftSection:Z&&(Q?h("span",{dangerouslySetInnerHTML:{__html:Q}}):Pt()),className:$?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ie,onClick:()=>Ze(!0),"data-ai-kit-open-button":!0,children:$&&n.get(L||yt)}),ie&&he(ne,{opened:!0,className:"ai-feature-root",onClose:D,padding:"md",gap:"md",size:"md",portalProps:d==="modal"?{target:Ce,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ue,"data-ai-kit-variation":d,children:[d==="modal"&&h(zt.Overlay,{}),he(se,{w:"100%",style:{left:0},children:[d==="modal"&&he(zt.Header,{style:{zIndex:1e3},children:[Pt("ai-feature-title-icon"),h(zt.Title,{children:n.get(yt)}),h(zt.CloseButton,{})]}),h(pe,{w:"100%",style:{zIndex:1001},children:he(Ut,{enabled:d!=="modal",working:v.busy,variation:d,children:[he(ht,{gap:"sm",mb:"sm",p:"sm",children:[xe&&h(Sn,{color:"red",children:n.get(xe)}),we&&u!=="proofread"&&he(Yr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[he(ct,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>je(o=>!o):void 0,children:[R==="collapse"&&he(ht,{gap:0,children:[h(za,{size:"sm",fw:600,style:{lineHeight:1.1},children:n.get("Options")}),h(za,{size:"xs",c:"dimmed",style:{marginTop:2},children:Ae})]}),R==="collapse"&&h(It,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),je(k=>!k)},children:ot?n.get("Hide"):n.get("Show")})]}),he(At,{in:ot,children:[R==="collapse"&&h(Fr,{my:"sm"}),he(ut,{gap:"xs",justify:"space-between",children:[u==="write"&&x?.text&&h(mt,{label:n.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:h(gt,{size:"xs",className:"ai-feature-option",styles:U,disabled:v.busy,label:n.get("Topic"),description:R!=="horizontal"?n.get("The topic or subject for the AI to write about."):void 0,value:ge||"",onChange:o=>{let k=o.target.value;Ve(k),C?.({text:k})}})}),(u==="write"||u==="rewrite"||u==="generateImageMetadata"||u==="generatePostMetadata")&&x?.instructions&&h(mt,{label:n.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:h(gt,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Instructions"),description:R!=="horizontal"?n.get("Additional instructions to guide the AI."):void 0,value:be||"",onChange:o=>{let k=o.target.value;kt(k),C?.({instructions:k})}})}),u==="translate"&&h(mt,{label:n.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",styles:U,className:"ai-feature-option",label:n.get("Input language"),description:R!=="horizontal"?n.get("The language of the input text."):void 0,data:[{value:"auto",label:n.get("Auto-detect")},...sn.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:_e||"auto",onChange:o=>{let k=o;Qe(k),Oe(void 0),C?.({inputLanguage:k})}})}),x?.outputLanguage&&h(mt,{label:n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",styles:U,className:"ai-feature-option",label:n.get("Output language"),description:R!=="horizontal"?n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[u==="rewrite"?{value:"auto",label:n.get("Auto-detect")}:void 0].filter(Boolean),...sn.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:M||Ma.settings.defaultOutputLanguage||(u==="rewrite"?"auto":""),onChange:o=>{let k=o;it(k),Oe(void 0),C?.({outputLanguage:k})}})}),u==="summarize"&&x?.type&&h(mt,{label:n.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Type"),description:R!=="horizontal"?n.get("The summary style to generate."):void 0,data:[{value:"headline",label:n.get("Headline")},{value:"key-points",label:n.get("Key Points")},{value:"teaser",label:n.get("Teaser")},{value:"tldr",label:n.get("TL;DR")}],value:me||"key-points",onChange:o=>{let k=o;Wt(k),C?.({type:k})}})}),(u==="write"||u==="rewrite")&&x?.tone&&h(mt,{label:n.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Tone"),description:R!=="horizontal"?n.get("The tone or style for the AI to use."):void 0,data:u==="write"?[{value:"neutral",label:n.get("Neutral")},{value:"formal",label:n.get("Formal")},{value:"casual",label:n.get("Casual")}]:[{value:"as-is",label:n.get("As-Is")},{value:"more-formal",label:n.get("More formal")},{value:"more-casual",label:n.get("More casual")}],value:Ge||(u==="write"?"neutral":"as-is"),onChange:o=>{let k=o;Ee(k),C?.({tone:k})}})}),(u==="write"||u==="rewrite"||u==="summarize")&&x?.length&&h(mt,{label:n.get("The target output length."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Length"),description:R!=="horizontal"?n.get("The target output length."):void 0,data:u==="write"||u==="summarize"?[{value:"short",label:n.get("Short")},{value:"medium",label:n.get("Medium")},{value:"long",label:n.get("Long")}]:[{value:"as-is",label:n.get("As-Is")},{value:"shorter",label:n.get("Shorter")},{value:"longer",label:n.get("Longer")}],value:ye||(u==="rewrite"?"as-is":"short"),onChange:o=>{let k=o;bt(k),C?.({length:k})}})}),u==="summarize"||u==="write"||u==="rewrite"&&x?.outputFormat&&h(mt,{label:n.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Output format"),description:R!=="horizontal"?n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:n.get("Plain Text")},{value:"markdown",label:n.get("Markdown")},{value:"html",label:n.get("HTML")}],value:te||"markdown",onChange:o=>{let k=o;Xe(k),C?.({outputFormat:k})}})})]})]})]}),v.busy&&lt&&h(Ut,{enabled:d==="modal",working:!0,variation:d,children:he(ct,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[h(qr,{size:"sm"}),h(Rn.Label,{className:"ai-feature-status-text",children:lt})]})}),P&&he(ht,{mt:"md",children:[u==="proofread"&&(P.corrections.length===0?h(Sn,{color:"green",children:n.get("No issues found. Your text looks great!")}):he(_t,{children:[h("p",{style:{marginTop:0,opacity:.85},children:n.get("Hover highlights to see explanations.")}),h(Ia,{original:ge,corrections:P.corrections}),P.correctedInput?he(_t,{children:[h("h4",{style:{marginTop:16,marginBottom:8},children:n.get("Corrected")}),h(ct,{c:"pre",className:"ai-feature-generated-content",children:P.correctedInput})]}):null]})),u==="generateImageMetadata"&&he(_t,{children:[h(gt,{readOnly:!s,label:n.get("Alt Text"),description:n.get("The alt text for the image."),value:P.alt_text||"",onChange:o=>I({...P,alt_text:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the image."),value:P.title||"",onChange:o=>I({...P,title:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Caption"),description:n.get("The caption for the image."),value:P.caption||"",onChange:o=>I({...P,caption:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Description"),description:n.get("The description for the image."),value:P.description||"",onChange:o=>I({...P,description:o.target.value})})]}),u==="generatePostMetadata"&&he(_t,{children:[h(gt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the post."),value:P.title||"",onChange:o=>I({...P,title:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Excerpt"),description:n.get("The excerpt for the post."),value:P.excerpt||"",onChange:o=>I({...P,excerpt:o.target.value})})]}),u!=="proofread"&&u!=="generateImageMetadata"&&u!=="generatePostMetadata"&&typeof P=="string"&&h(Pa,{value:P,editable:!!s,onChange:o=>{I(o)}})]}),P===""&&h(Pa,{value:P,editable:!1})]}),he(ct,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[v.busy&&h(It,{variant:"outline",size:"sm",onClick:H,"data-ai-kit-cancel-button":!0,children:n.get("Cancel")}),!v.busy&&h(It,{variant:"filled",size:"sm",disabled:!Se,onClick:()=>Le(),"data-ai-kit-generate-button":!0,children:Dt()}),!v.busy&&v.lastSource==="on-device"&&We&&Ke&&h(It,{variant:"filled",size:"sm",disabled:!Se,onClick:et,"data-ai-kit-regenerate-on-backend-button":!0,children:A()}),!v.busy&&p&&h(It,{variant:"outline",size:"sm",disabled:!P||u==="proofread"&&P.corrections.length===0,onClick:async()=>{p(te==="html"?await wn(P):P),D()},"data-ai-kit-accept-button":!0,children:n.get(_)}),h(It,{variant:"default",size:"sm",onClick:D,"data-ai-kit-close-button":!0,children:n.get("Close")})]}),h(nn,{variation:d})]})})]})]})]})};function Pa(t){let{value:r,editable:c,onChange:s}=t;return c?he(ht,{p:0,gap:"sm",children:[h(Rn.Label,{children:n.get("Generated content")}),h(Jr,{value:r,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),h(Rn.Label,{children:n.get("Preview")}),h(ht,{className:"ai-feature-generated-content ai-feature-preview",children:h(xa,{remarkPlugins:[La],children:r})})]}):h(ht,{className:"ai-feature-generated-content",children:r?h(xa,{remarkPlugins:[La],children:r}):h(Sn,{color:"yellow",children:n.get("No content generated.")})})}var po=Rt(mo);import{ActionIcon as Ea,Anchor as vo,Box as wo,Button as Ye,Group as Pe,Input as To,List as Ba,Modal as Ct,Stack as Je,Text as Ie,Textarea as So}from"@mantine/core";import{IconMaximize as Ro,IconMessage as Io,IconMicrophone as zo,IconMinimize as Co,IconPaperclip as xo,IconPencil as Lo,IconPlayerStop as Mo,IconSend as Po,IconTrash as Do,IconX as Eo}from"@tabler/icons-react";import{getStoreSelect as Bo,sendChatMessage as Ko,sendFeedbackMessage as Uo}from"@smart-cloud/ai-kit-core";import{useSelect as Oo}from"@wordpress/data";import{I18n as f}from"aws-amplify/utils";import{useCallback as F,useEffect as le,useMemo as fe,useRef as ve,useState as ue}from"react";import No from"react-markdown";import jo from"remark-gfm";var ho="ai-kit-chatbot-attachments",$e="attachments";var In=null;function fo(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function un(){if(!fo())return null;In||(In=new Promise(t=>{try{let r=window.indexedDB.open(ho,1);r.onerror=()=>t(null),r.onblocked=()=>t(null),r.onupgradeneeded=()=>{let c=r.result;c.objectStoreNames.contains($e)||c.createObjectStore($e,{keyPath:"id"})},r.onsuccess=()=>t(r.result)}catch(r){console.warn("[AiChatbot] IndexedDB is not available",r),t(null)}}));try{return await In}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function zn(t,r){let c=await un();return c?new Promise((s,a)=>{try{let d=c.transaction($e,t),w=d.objectStore($e),B=r(w);d.oncomplete=()=>s(B),d.onerror=()=>a(d.error),d.onabort=()=>a(d.error)}catch(d){a(d)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Cn(t,r,c){await Ao();let s={id:t,blob:r,name:c.name,type:c.type,size:c.size,createdAt:Date.now()};return await zn("readwrite",d=>(d.put(s),t))}async function xn(t){let r=await un();return r?new Promise((c,s)=>{try{let a=r.transaction($e,"readonly"),d=a.objectStore($e).get(t);d.onsuccess=()=>{let w=d.result;c(w??null)},d.onerror=()=>s(d.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(c=>(console.warn("[AiChatbot] Failed to load attachment",c),null)):null}async function ko(t){await zn("readwrite",r=>{r.delete(t)})}async function dn(){await zn("readwrite",t=>{t.clear()})}async function Ln(t){let r=await un();r&&await new Promise((c,s)=>{try{let a=r.transaction($e,"readwrite"),d=a.objectStore($e),w=d.getAllKeys();w.onsuccess=()=>{let B=w.result;for(let $ of B){let Z=String($);t.has(Z)||d.delete($)}},w.onerror=()=>s(w.error),a.oncomplete=()=>c(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(c=>{console.warn("[AiChatbot] Failed to cleanup attachments",c)})}var bo=50*1024*1024;async function yo(){let t=await un();return t?new Promise((r,c)=>{try{let s=t.transaction($e,"readonly"),a=s.objectStore($e).getAll();a.onsuccess=()=>{let d=a.result||[];r(d)},a.onerror=()=>c(a.error),s.onerror=()=>c(s.error),s.onabort=()=>c(s.error)}catch(s){c(s)}}).catch(r=>(console.warn("[AiChatbot] Failed to get all attachments",r),[])):[]}async function Ao(){let t=await yo();if(t.length===0)return;let r=t.sort((d,w)=>d.createdAt-w.createdAt),c=r.reduce((d,w)=>d+w.size,0),s=[],a=0;for(;c>bo&&a<r.length;){let d=r[a];d&&(s.push(d.id),c-=d.size),a++}for(let d of s)await ko(d);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as Ua,jsx as g,jsxs as G}from"react/jsx-runtime";f.putVocabularies(wt);var cn=1440*60*1e3,Mn=!1,Go=1,Ho="localstorage",Nt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Dn={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function ft(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Wo=4,Fo=5*1024*1024,qo=t=>{let r=(t?.name||"").toString(),c=(t?.code||"").toString(),s=(t?.message||"").toString();return r==="AbortError"||c==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Yo=(t,r)=>{if(!t)return null;let c=t.step,s=f.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,d=a==null?null:Math.round(a*100);switch(c){case"decide":return s||f.get("Checking capabilities...");case"on-device:init":return s||f.get("Initializing on-device AI...");case"on-device:download":return d==null?s||f.get("Downloading model..."):s||`${f.get("Downloading model...")} ${d}%`;case"on-device:ready":return s||f.get("On-device model ready...");case"on-device:run":return s||f.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return f.get(r.assistantThinkingLabel??Dn.assistantThinkingLabel);case"done":return s||f.get("Done.");case"error":return s||f.get("An error occurred.");default:return s||null}};function Pn(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var jt=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},gn=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},Oa=t=>{!t||t.length===0||t.forEach(r=>gn(r.objectUrl))},Ka=t=>{t.forEach(r=>Oa(r.attachments))},Jo=t=>{let{rootElement:r,store:c,previewMode:s,title:a,openButtonTitle:d,openButtonIcon:w,showOpenButtonTitle:B=!0,showOpenButtonIcon:$=!0,colorMode:Z,language:L,onClose:Q,context:Ke,placeholder:_,maxImages:R,maxImageBytes:u,historyStorage:S=Ho,emptyHistoryAfterDays:ke=Go,labels:Ue,openButtonIconLayout:q="top",openButtonPosition:ce="bottom-right"}=t,p=fe(()=>({...Dn,...Ue||{}}),[Ue]),C=Kt(),[K,Ce]=ue(""),[x,we]=ue([]),[b,X]=ue(null),[ie,Ze]=ue(!1),[ot,je]=ue(0),We=ve(null),Fe=ve([]),xe=ve(null),De=ve(null),P=ve(null),[I,ge]=ue([]),[Ve,ee]=ue(null),[be,kt]=ue(!1),[Te,Oe]=ue(!1),[_e,Qe]=ue(!1),[te,Xe]=ue(!1),[M,it]=ue(!0),[ye,bt]=ue(null),[Ge,Ee]=ue(!1),[me,Wt]=ue(null),[J,yt]=ue(null),[st,He]=ue(!1),[Se,v]=ue(null),lt=ve(Se);le(()=>{lt.current=Se},[Se]);let Le=ve(null),et=ve(!1),[Pt,Dt]=ue(null),A=ve(null),D=ve(null),H=ve(null),Ae=ve(null),U=F(e=>{e.forEach(l=>gn(l.objectUrl))},[]),ne=F(()=>{U(ae.current),we([]),A.current&&(A.current.value="")},[U]),se=F(()=>{j.current&&gn(j.current.objectUrl),X(null),Fe.current=[],je(0)},[]),pe=F(async()=>{try{Ce(""),se();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),l=new MediaRecorder(e,{mimeType:"audio/webm"}),m=new AudioContext,i=m.createMediaStreamSource(e),T=m.createAnalyser();T.fftSize=2048,T.smoothingTimeConstant=.8,i.connect(T),xe.current=m,De.current=T;let y=new Uint8Array(T.fftSize),E=()=>{if(!De.current)return;De.current.getByteTimeDomainData(y);let W=0;for(let Ne=0;Ne<y.length;Ne++){let vt=(y[Ne]-128)/128;W+=vt*vt}let Re=Math.sqrt(W/y.length),Be=Math.min(100,Re*200);je(Be),P.current=requestAnimationFrame(E)};E(),Fe.current=[];let O=Date.now();l.ondataavailable=W=>{W.data.size>0&&Fe.current.push(W.data)},l.onstop=()=>{let W=new Blob(Fe.current,{type:"audio/webm"}),Re=(Date.now()-O)/1e3,Be=jt(W);Be&&X({id:ft("composer-audio"),blob:W,objectUrl:Be,duration:Re}),e.getTracks().forEach(Ne=>Ne.stop()),P.current&&(cancelAnimationFrame(P.current),P.current=null),xe.current&&(xe.current.close(),xe.current=null),De.current=null,je(0)},We.current=l,l.start(),Ze(!0)}catch(e){console.error("Failed to start recording:",e)}},[se]),At=F(()=>{We.current&&ie&&(We.current.stop(),Ze(!1))},[ie]);le(()=>()=>{P.current&&cancelAnimationFrame(P.current),xe.current&&xe.current.close(),se()},[se]);let[ut,o]=ue(null),k=ve(K),N=ve(I),Y=ve(ut),ae=ve(x),j=ve(b);le(()=>{k.current=K},[K]),le(()=>{ae.current=x},[x]),le(()=>{j.current=b},[b]),le(()=>{N.current=I},[I]),le(()=>{Y.current=ut},[ut]),le(()=>{L&&f.setLanguage(L||"en")},[L]);let V=Oo(()=>Bo(c).isShowChatbotPreview()),re=fe(()=>Math.max(0,R??Wo),[R]),qe=fe(()=>Math.max(0,u??Fo),[u]),tt=I.length>0,oe=fe(()=>C.busy&&Se==="chat",[C.busy,Se]),pn=fe(()=>oe?!1:K.trim().length>0||b!==null,[K,oe,b]),Et=fe(()=>{let e=d||p.askMeLabel;return f.get(e)},[d,p.askMeLabel,L]),Fa=fe(()=>{let e=a||p.modalTitle;return f.get(e)},[a,p.modalTitle,L]),qa=fe(()=>{let e=_||p.placeholder;return f.get(e)},[_,p.placeholder,L]),En=fe(()=>{let e="ai-docs-ask",l=`ai-open-btn--${ce}`;return`${e} ${l}`},[ce]),Xt=F(()=>{let e=Ae.current;if(e)try{let l=window.innerHeight||document.documentElement.clientHeight,m=360,i=1e3,T=Math.floor(l*.8),y=Math.max(m,Math.min(T,i));e.style.height=`${y}px`}catch{}},[]),Ft=F(()=>{let e=J;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[J]),Bn=F(()=>{Xe(!1),Te&&Oe(!1),Qe(!1),Q?.()},[Te,Q]);le(()=>{if(te)return Xt(),window.addEventListener("resize",Xt),()=>window.removeEventListener("resize",Xt)},[te,Xt]),le(()=>{if(!(!te||!Te))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[te,Te,Bn]);let Kn=fe(()=>x.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[x]);le(()=>{tt||it(!0)},[tt]),le(()=>()=>{U(ae.current)},[U]),le(()=>{let e=J;if(!e)return;let l=()=>{let m=e.scrollHeight-(e.scrollTop+e.clientHeight);it(m<20)};return e.addEventListener("scroll",l),()=>{e.removeEventListener("scroll",l)}},[te,J]),le(()=>{if(!M)return;let e=J;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[I,C.busy,M,J]),le(()=>{te||bt(null)},[te]);let Un=fe(()=>C.busy?Yo(C.statusEvent,p)||f.get("Working\u2026"):null,[C.busy,C.statusEvent,L,p]),Ya=fe(()=>{for(let e=I.length-1;e>=0;e--){let l=I[e];if(l.role==="user"&&l.clientStatus==="canceled")return l.id}return null},[I]),qt=F(e=>{ge(l=>{let m=[...l].map((y,E)=>({m:y,i:E})).reverse().find(y=>y.m.role==="user"&&y.m.clientStatus==="pending")?.i;if(m==null)return l;let i=l.slice(),T=i[m];return i[m]={...T,clientStatus:e??void 0},i})},[ge]),en=F(()=>{if(!(!C.busy||lt.current!=="chat")){et.current=!0;try{C.cancel()}catch{}qt("canceled"),v(null),ee(null),Ft()}},[C,qt,Ft]),Ja=F(e=>{let l=ae.current,m=Array.from(e.target.files||[]),i=Math.max(0,re-l.length);if(i===0){e.currentTarget.value="";return}let T=[];for(let y of m){if(T.length>=i)break;let E=/image\/(jpeg|png|gif|webp)/i.test(y.type),O=y.size<=qe,W=[...l,...T].some(Be=>Be.file.name===y.name&&Be.file.size===y.size&&Be.file.lastModified===y.lastModified);if(!E||!O||W)continue;let Re=jt(y);Re&&T.push({id:ft("composer-image"),file:y,objectUrl:Re})}T.length&&we(y=>[...y,...T]),e.currentTarget.value=""},[re,qe]),Va=F(e=>{we(l=>{if(e<0||e>=l.length)return l;let m=l[e];return m&&gn(m.objectUrl),l.filter((i,T)=>T!==e)})},[]),dt=ve(null);le(()=>{if(Ve)return dt.current&&(window.clearTimeout(dt.current),dt.current=null),dt.current=window.setTimeout(()=>{ee(null),dt.current=null},6e3),()=>{dt.current&&(window.clearTimeout(dt.current),dt.current=null)}},[Ve]);let On=F(async(e,l)=>{let m=S!=="nostorage",i=[];if(e.length>0){let T=await Promise.all(e.map(async y=>{let E=ft("attachment-image"),O;if(m)try{O=await Cn(E,y.file,{name:y.file.name,type:y.file.type,size:y.file.size})??void 0}catch(Re){console.warn("[AiChatbot] Failed to persist image",Re)}let W=jt(y.file);return{id:E,name:y.file.name,type:y.file.type||"application/octet-stream",size:y.file.size,blobId:O,objectUrl:W??void 0,blob:y.file,mediaType:"image"}}));i.push(...T.filter(Boolean))}if(l){let T=ft("attachment-audio"),y;if(m)try{y=await Cn(T,l.blob,{name:`audio-${Date.now()}.webm`,type:l.blob.type,size:l.blob.size})??void 0}catch(O){console.warn("[AiChatbot] Failed to persist audio",O)}let E=jt(l.blob);i.push({id:T,name:`audio-${Date.now()}.webm`,type:l.blob.type||"audio/webm",size:l.blob.size,blobId:y,objectUrl:E??void 0,blob:l.blob,duration:l.duration,mediaType:"audio"})}return i},[S]),Nn=F(async e=>{let l=[];for(let m of e){let i;if(m.attachments&&m.attachments.length>0){i=[];for(let T of m.attachments){let y;if(T.blobId)try{y=(await xn(T.blobId))?.blob??void 0}catch(O){console.warn("[AiChatbot] Failed to hydrate attachment",O)}if(!y)continue;let E=y?jt(y):null;i.push({...T,objectUrl:E??void 0,blob:y??void 0})}}l.push({...m,attachments:i})}return l},[]),jn=F(async e=>{if(!e||e.length===0){ne();return}let l=[];for(let m of e){let i=m.blob;if(!i&&m.blobId)try{i=(await xn(m.blobId))?.blob??void 0}catch(E){console.warn("[AiChatbot] Failed to reload attachment",E)}if(!i)continue;let T=i instanceof File?i:new File([i],m.name||"attachment",{type:m.type||i.type||"application/octet-stream"}),y=jt(T);if(y&&(l.push({id:ft("composer-image"),file:T,objectUrl:y}),l.length>=re))break}if(l.length===0){ne();return}we(m=>(U(m),l)),A.current&&(A.current.value="")},[ne,U,re]),hn=F((e,l)=>{e&&bt({url:e,title:l})},[]),_a=F(()=>{bt(null)},[]),Gn=F(()=>{Ka(N.current),ne(),se(),ge([]),ee(null),H.current=null,o(null),it(!0),kt(!1);let e=Pn(S);if(e)try{e.removeItem(Nt)}catch{}dn()},[ne,se,S]),$a=F(()=>{kt(!0)},[]),Za=F(()=>{C.busy&&lt.current==="chat"&&en(),Gn()},[C.busy,en,Gn]),Hn=F(()=>{kt(!1)},[]),Wn=F(async(e,l)=>{if(!C.busy)try{let m=H.current&&Date.now()-H.current.storedAt<ke*cn?H.current.id:void 0;if(!m)return;v("feedback"),ee(null),await C.run(async({signal:i,onStatus:T})=>(await Uo({sessionId:m,feedbackMessageId:e,feedbackType:l},{signal:i,onStatus:T,context:Ke}),null)),ee(null)}catch(m){let i=m?.message?.trim()||f.get("An error occurred.");ee(i),console.error("Failed to send feedback",m)}finally{v(m=>m==="feedback"?null:m)}},[C,L]),Fn=F((e,l)=>{ge(m=>m.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===l?{...i,feedback:void 0}:{...i,feedback:l})),Wn(e,l)},[Wn]),tn=F(async()=>{let e=k.current.trim(),l=j.current;if(!e&&!l||C.busy)return;et.current=!1,ee(null),v("chat");let m=[...ae.current],i=await On(m,l),T=ft("user"),y=Date.now(),E={id:T,role:"user",content:e||(l?"[Audio message]":""),createdAt:y,clientStatus:"pending",attachments:i.length?i:void 0};Ce(""),ne(),se(),ge(O=>[...O,E]),te||Xe(!0),Ft();try{let O=H.current&&Date.now()-H.current.storedAt<ke*cn?H.current.id:void 0,W=await C.run(async({signal:Be,onStatus:Ne})=>await Ko({sessionId:O,message:e||void 0,audio:l?.blob,images:m.map(ur=>ur.file)},{signal:Be,onStatus:Ne,context:Ke}));if(et.current){qt("canceled");return}if(!W)throw new Error(f.get(C.error??p.emptyResponseLabel));W.sessionId&&(H.current={id:W.sessionId,storedAt:Date.now()});let Re={id:W.metadata?.messageId||ft("assistant"),role:"assistant",content:W.result||"",citations:W.citations,createdAt:Date.now()};ge(Be=>[...Be.map(vt=>vt.id===T?{...vt,clientStatus:void 0}:vt),Re]),o(y)}catch(O){if(console.error("Error during ask()",O),et.current||qo(O)){qt("canceled");return}let W=O?.message?.trim()||f.get(p.unexpectedErrorLabel);ge(Re=>[...Re.map(Ne=>Ne.id===T?{...Ne,clientStatus:void 0}:Ne),{id:ft("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${W}`,createdAt:Date.now()}]),o(y)}finally{v(O=>O==="chat"?null:O),et.current=!1,D.current&&D.current.focus(),Ft()}},[C,On,ne,se,te,Ft,qt,p.emptyResponseLabel,p.unexpectedErrorLabel,L]),Qa=F(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),pn&&tn())},[tn,pn]),Xa=F(()=>{Xe(!0)},[]);le(()=>()=>{Le.current!=null&&(cancelAnimationFrame(Le.current),Le.current=null)},[]);let er=F(()=>{Oe(e=>{let l=!e;return Le.current!=null&&(cancelAnimationFrame(Le.current),Le.current=null),l?(Qe(!0),requestAnimationFrame(()=>{Le.current=requestAnimationFrame(()=>{Qe(!1),Le.current=null})})):Qe(!1),l})},[]),tr=F(e=>{Ce(e.content),(async()=>(await jn(e.attachments),ge(l=>l.filter(m=>m.id!==e.id)),Oa(e.attachments),queueMicrotask(()=>D.current?.focus())))()},[jn]),qn=fe(()=>$?w?g("img",{src:w,className:"ai-open-btn-icon",alt:f.get(p.askMeLabel||Et)}):g(Io,{size:18}):null,[$,w,p,Et,L]),nr=fe(()=>{let e=qn,l=B?g(Ie,{inherit:!0,children:Et}):null;if(!$&&!l)return null;if(!$)return l;if(!B)return e;switch(q){case"top":return G(Je,{gap:4,align:"center",children:[e,l]});case"bottom":return G(Je,{gap:4,align:"center",children:[l,e]});case"right":return G(Pe,{gap:6,align:"center",children:[l,e]});default:return G(Pe,{gap:6,align:"center",children:[e,l]})}},[qn,$,B,Et,q]),ar=fe(()=>oe,[oe]),rr=fe(()=>!oe,[oe]),or=fe(()=>Ve||(tt?f.get(p.readyLabel):f.get(p.readyEmptyLabel)),[Ve,tt,p.readyLabel,p.readyEmptyLabel,L]),ir=fe(()=>oe?f.get(p.cancelLabel):f.get(p.sendLabel),[oe,p.cancelLabel,p.sendLabel,L]),sr=fe(()=>oe?g(Mo,{size:18}):g(Po,{size:18}),[oe]),lr=F(()=>{if(oe){en();return}tn()},[oe,en,tn]);return le(()=>{if(!te||!me||!J)return;let e=()=>{let O=window.getComputedStyle(J).overflowY,W=O==="auto"||O==="scroll",Re=Math.ceil(J.scrollHeight),Be=Math.floor(J.clientHeight),Ne=Re>Be;return W&&Ne},l=!1,m=E=>{if(!e())return;E.preventDefault();let O=J.scrollHeight-J.clientHeight;J.scrollTop=Math.max(0,Math.min(O,J.scrollTop+E.deltaY))},i=()=>{let E=e();He(E),E!==l&&(l=E,l?me.addEventListener("wheel",m,{passive:!1}):me.removeEventListener("wheel",m))};i();let T=new ResizeObserver(i);T.observe(J);let y=new MutationObserver(i);return y.observe(J,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{l&&me.removeEventListener("wheel",m),T.disconnect(),y.disconnect(),window.removeEventListener("resize",i)}},[te,me,J]),le(()=>{let e=!1,l=Pn(S);if(!l){S==="nostorage"&&dn(),Ee(!0);return}return(async()=>{try{let m=l.getItem(Nt);if(!m){Ee(!0);return}let i=JSON.parse(m),T=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!T||Date.now()-T>ke*cn){l.removeItem(Nt),await dn(),Ee(!0);return}let E=(Array.isArray(i.messages)?i.messages:[]).map(W=>W?.role==="user"&&W.clientStatus==="pending"?{...W,clientStatus:"canceled"}:W),O=await Nn(E);if(e){Ka(O);return}ge(O),o(T),i.session&&i.session.id&&(H.current=i.session)}catch(m){console.warn("[AiChatbot] Failed to load history",m);try{l.removeItem(Nt)}catch{}}finally{e||Ee(!0)}})(),()=>{e=!0}},[S,ke,Nn]),le(()=>{if(!Ge)return;let e=Pn(S);if(!e)return;let l=Y.current;if(!l)return;if(Date.now()-l>ke*cn){try{e.removeItem(Nt)}catch{}Ln(new Set);return}let m=I.map(({attachments:y,...E})=>({...E,attachments:y?.map(({objectUrl:O,blob:W,...Re})=>Re)})),i={version:1,lastUserSentAt:l,session:H.current,messages:m};try{e.setItem(Nt,JSON.stringify(i))}catch{}let T=new Set;m.forEach(y=>{y.attachments?.forEach(E=>{E.blobId&&T.add(E.blobId)})}),Ln(T)},[Ge,I,ut,S,ke]),s&&!V||!s&&V?null:G(Pe,{className:En,children:[!te&&g(Ye,{variant:"filled",className:B?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:Xa,"aria-label":Et,title:Et,"data-ai-kit-open-button":!0,children:nr}),te&&g(Ct.Root,{ref:Ae,opened:te,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Bn,className:En+" ai-chat-container"+(Te?" maximized":"")+(Te&&_e?" ai-max-enter":""),portalProps:{target:r,reuseTargetNode:!0},"data-ai-kit-theme":Z,"data-ai-kit-variation":"modal",children:G("div",{className:"ai-chat-container-internal",ref:Wt,children:[G(Ct.Header,{className:"ai-chat-header-bar",children:[g(Ct.Title,{className:"ai-chat-title",children:Fa}),G(Pe,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&g(Ea,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:er,title:Te?f.get(p.restoreSizeLabel):f.get(p.maximizeLabel),"aria-label":Te?f.get(p.restoreSizeLabel):f.get(p.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Te?g(Co,{size:16}):g(Ro,{size:16})}),g(Ct.CloseButton,{"aria-label":f.get(p.closeChatLabel)})]})]}),G(Ct.Body,{className:"ai-chat-scroll",ref:yt,"data-scrollable":st?"true":"false",children:[I.map(e=>{let l=e.role==="user",m=l&&e.clientStatus==="canceled"&&e.id===Ya;return g(Pe,{justify:l?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>Dt(e.id),onMouseLeave:()=>Dt(i=>i===e.id?null:i),children:G(Je,{gap:4,w:"100%",style:{alignItems:l?"flex-end":"flex-start"},children:[G(Je,{className:"ai-chat-bubble",children:[G(Ie,{className:"ai-chat-header",children:[g(Ie,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:l?f.get(p.userLabel):f.get(p.assistantLabel)}),"\xA0",g(Ie,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?g(No,{remarkPlugins:[jo],children:e.content}):g(Ie,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&G(Je,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&g(Pe,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>g("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>hn(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||f.get("View image"),"aria-label":i.name||f.get("View image"),children:!i.objectUrl&&g(Ie,{size:"xs",c:"dimmed",children:f.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>g(wo,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?G(Je,{gap:"xs",children:[g("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&G(Ie,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):g(Ie,{size:"xs",c:"dimmed",children:f.get("Audio no longer available")})},i.id))]}),m&&G(Pe,{justify:"flex-end",gap:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:g("em",{children:f.get(p.notSentLabel)})}),Pt===e.id&&g(Ea,{size:"sm",variant:"subtle",onClick:()=>tr(e),title:f.get(p.editLabel),"aria-label":f.get(p.editLabel),"data-ai-kit-edit-button":!0,children:g(Lo,{size:14})})]}),e.citations&&e.citations.length>0&&G(Je,{className:"ai-citations",children:[g(Ie,{fw:"bold",size:"sm",mb:"xs",children:f.get(p.referencesLabel)}),g(Ba,{spacing:"xs",size:"sm",children:e.citations.map((i,T)=>{let y=i.sourceUrl||i.url,E=i.title||y||`${f.get(p.referenceLabel)} #${T+1}`;return G(Ba.Item,{children:[y?g(vo,{href:y,target:"_blank",rel:"noreferrer",children:E}):g(Ie,{children:E}),i.snippet?g(Ie,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},T)})})]}),e.role==="assistant"&&G(Pe,{className:"ai-feedback",gap:"xs",children:[g(Ye,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>Fn(e.id,"accepted"),"aria-label":f.get(p.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),g(Ye,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>Fn(e.id,"rejected"),"aria-label":f.get(p.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),ar&&g(Pe,{justify:"flex-start",className:"ai-chat-row assistant status",children:G(Je,{className:"ai-chat-bubble typing",children:[Un?g(Ie,{size:"sm",c:"dimmed",children:g("em",{children:Un})}):null,G("div",{className:"typing-indicator",children:[g("span",{}),g("span",{}),g("span",{})]})]})})]}),rr&&g(Pe,{className:"ai-status-line",children:g(Ie,{className:"ai-status-text",children:g("em",{children:or})})}),G(Je,{className:"ai-box ai-box-open",children:[G(Ct,{opened:be,onClose:Hn,centered:!0,title:f.get("Reset conversation"),style:{position:"fixed"},left:0,children:[g(Ie,{size:"sm",children:f.get("Are you sure you want to reset the conversation?")}),G(Pe,{justify:"flex-end",mt:"md",children:[g(Ye,{variant:"default",onClick:Hn,"data-ai-kit-no-button":!0,children:f.get("No")}),g(Ye,{color:"var(--ai-kit-color-danger, red)",onClick:Za,disabled:!tt&&!oe,"data-ai-kit-yes-button":!0,children:f.get("Yes")})]})]}),g(Pe,{children:g(So,{className:"ai-message",ref:D,placeholder:qa,value:K,onChange:e=>{Ce(e.target.value),b&&se()},onKeyDown:Qa,rows:3,disabled:ie||!!b})}),Mn&&ie&&G(Je,{gap:"xs",mt:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:g("em",{children:f.get("Recording...")})}),g("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:g("div",{style:{width:`${ot}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Mn&&b&&!ie&&G(Je,{gap:"xs",mt:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:G("em",{children:[f.get("Audio recorded")," (",Math.round(b.duration),"s)"]})}),g("audio",{className:"ai-kit-audio-player",controls:!0,src:b.objectUrl})]}),G(Pe,{className:"ai-actions",justify:"space-between",w:"100%",children:[g(Pe,{justify:"flex-start",children:g(Ye,{variant:"light",leftSection:g(Do,{size:18}),onClick:$a,disabled:!tt&&!oe,"data-ai-kit-reset-button":!0,children:f.get(p.resetLabel)})}),G(Pe,{justify:"flex-end",children:[Mn&&g(Ua,{children:b?g(Ye,{variant:"outline",leftSection:g(Eo,{size:18}),onClick:se,disabled:oe,title:f.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:f.get("Clear")}):g(Ye,{variant:"outline",leftSection:g(zo,{size:18}),onClick:ie?At:pe,disabled:oe,title:ie?f.get("Stop recording"):f.get("Record audio"),color:ie?"red":void 0,"data-ai-kit-microphone-button":!0,children:ie?f.get("Stop"):f.get("Record")})}),re>0&&G(Ua,{children:[g(Ye,{variant:"outline",leftSection:g(xo,{size:18}),onClick:()=>A.current?.click(),disabled:x.length>=re||oe||ie||!!b,title:f.get(p.addImageLabel),"data-ai-kit-add-image-button":!0,children:f.get(p.addLabel)}),g(To,{ref:A,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Ja})]}),g(Ye,{leftSection:sr,variant:"filled",onClick:lr,disabled:!oe&&!pn,"data-ai-kit-send-button":!0,children:ir})]})]}),Kn.length>0&&g(Pe,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Kn.map(({url:e,title:l},m)=>g("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":l||f.get("View image"),onClick:()=>hn(e,l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),hn(e,l))},children:g(Ye,{variant:"white",onClick:i=>{i.stopPropagation(),Va(m)},"aria-label":f.get(p.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:f.get(p.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},x[m]?.id??m))})]})]})}),g(Ct,{opened:!!ye,onClose:_a,centered:!0,size:"auto",title:ye?.title||f.get("Image preview"),children:ye&&g("img",{src:ye.url,alt:ye.title||f.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},Vo=Rt(Jo,{showOpenButton:!0,variation:"modal"});import{Alert as _o,Anchor as Na,Button as $t,Divider as ja,Group as Gt,Loader as $o,Modal as xt,Paper as Ga,Progress as Zo,Stack as Lt,Text as at,TextInput as Qo,Title as Xo}from"@mantine/core";import{AiKitDocSearchIcon as ei,sendSearchMessage as ti}from"@smart-cloud/ai-kit-core";import{I18n as de}from"aws-amplify/utils";import{useCallback as Ht,useEffect as mn,useMemo as rt,useRef as Mt,useState as Zt}from"react";import ni from"react-markdown";import ai from"rehype-raw";import ri from"remark-gfm";import{IconSearch as Ha}from"@tabler/icons-react";import{IconMicrophone as oi,IconMicrophoneOff as ii}from"@tabler/icons-react";import{Fragment as Qt,jsx as z,jsxs as ze}from"react/jsx-runtime";de.putVocabularies(wt);var Wa=!1;function si(t){let r=t?.citations?.docs??[],c=t?.citations?.chunks??[],s=new Map;for(let a of r)s.set(a.docId,{doc:a,chunks:[]});for(let a of c){let d=s.get(a.docId);d?d.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}var li=t=>{let{autoRun:r=!0,context:c,title:s,searchButtonIcon:a,showSearchButtonTitle:d=!0,showSearchButtonIcon:w=!0,showSources:B=!0,topK:$=10,getSearchText:Z,variation:L,rootElement:Q,colorMode:Ke,language:_,onClose:R,onClickDoc:u,showOpenButton:S=!1,openButtonTitle:ke,openButtonIcon:Ue,showOpenButtonTitle:q=!0,showOpenButtonIcon:ce=!0}=t,[p,C]=Zt(""),[K,Ce]=Zt(!S),[x,we]=Zt(!1),[b,X]=Zt(null),[ie,Ze]=Zt(0),ot=Mt(null),je=Mt([]),We=Mt(null),Fe=Mt(null),xe=Mt(null),De=Mt(null),P=1440*60*1e3,{busy:I,error:ge,statusEvent:Ve,result:ee,run:be,cancel:kt,reset:Te}=Kt(),Oe=Mt(!1),_e=ee?.sessionId,Qe=ee?.citations?.docs??[],te=ee?.citations?.chunks??[],Xe=ee?.citations?.anchors??[],M=ee?.result??"",it=rt(()=>{if(w)return a?.trim()?z("img",{src:a,alt:"",style:{width:18,height:18,objectFit:"contain"}}):z(Ha,{size:18})},[a,w]),ye=rt(()=>(_&&de.setLanguage(_||"en"),de.get(s||"Search with AI-Kit")),[_]),bt=Ht(A=>z(Ha,{className:A,size:18}),[]),Ge=rt(()=>Ve?de.get("Searching\u2026"):null,[_,Ve]),Ee=rt(()=>p||Z,[p,Z]),me=rt(()=>{if(I)return!1;let A=typeof Ee=="function"?Ee():Ee;return!!(A&&A.trim().length>0||b)},[Ee,I,b]),Wt=Ht(async()=>{try{C("");let A=await navigator.mediaDevices.getUserMedia({audio:!0}),D=new MediaRecorder(A,{mimeType:"audio/webm"}),H=new AudioContext,Ae=H.createMediaStreamSource(A),U=H.createAnalyser();U.fftSize=2048,U.smoothingTimeConstant=.8,Ae.connect(U),We.current=H,Fe.current=U;let ne=new Uint8Array(U.fftSize),se=()=>{if(!Fe.current)return;Fe.current.getByteTimeDomainData(ne);let pe=0;for(let o=0;o<ne.length;o++){let k=(ne[o]-128)/128;pe+=k*k}let At=Math.sqrt(pe/ne.length),ut=Math.min(100,At*200);Ze(ut),xe.current=requestAnimationFrame(se)};se(),je.current=[],D.ondataavailable=pe=>{pe.data.size>0&&je.current.push(pe.data)},D.onstop=()=>{let pe=new Blob(je.current,{type:"audio/webm"});X(pe),A.getTracks().forEach(At=>At.stop()),xe.current&&(cancelAnimationFrame(xe.current),xe.current=null),We.current&&(We.current.close(),We.current=null),Fe.current=null,Ze(0)},ot.current=D,D.start(),we(!0)}catch(A){console.error("Failed to start recording:",A)}},[]),J=Ht(()=>{ot.current&&x&&(ot.current.stop(),we(!1))},[x]),yt=Ht(()=>{X(null),je.current=[],Ze(0),De.current=null},[]);mn(()=>()=>{xe.current&&cancelAnimationFrame(xe.current),We.current&&We.current.close()},[]);let st=Ht(async()=>{let A;if(!b){if(A=typeof Ee=="function"?Ee():Ee,!A)return;C(A)}console.log("Starting search with query:",A,"and audio:",b);let D=Date.now(),H=b&&De.current?.blob===b&&D-De.current.uploadTimestamp<P;b&&!H?(De.current={blob:b,uploadTimestamp:D},console.log("Audio cache updated for new recording")):H&&console.log("Reusing cached audio (no re-upload needed within",Math.round((P-(D-De.current.uploadTimestamp))/1e3),"seconds)"),Te(),await be(async({signal:Ae,onStatus:U})=>await ti({sessionId:_e,...A&&{query:A},...b&&{audio:b},topK:$},{signal:Ae,onStatus:U,context:c}))},[c,Ee,b,be,Te,$,_e]),He=Ht(async()=>{Ce(!1),Te(),Oe.current=!1,S||R()},[R,Te,Oe,S]);mn(()=>{!r||!me||I||Oe.current||(Oe.current=!0,queueMicrotask(()=>{st()}))},[I,Oe,me,r,st]),mn(()=>{me||(Oe.current=!0)},[me]);let Se=rt(()=>si(ee),[ee]),v=rt(()=>{let A=new Map;return Qe.forEach((D,H)=>{D?.docId&&A.set(D.docId,H+1)}),A},[Qe]),lt=rt(()=>{let A=new Map;return te.forEach(D=>{D?.chunkId&&D?.docId&&A.set(D.chunkId,D.docId)}),A},[te]),Le=rt(()=>{if(!M)return"";if(!Xe.length||v.size===0)return M;let A=[...Xe].filter(Ae=>Array.isArray(Ae?.chunkIds)&&Ae?.span?.end!==void 0).sort((Ae,U)=>{let ne=Ae.span?.end??0,se=U.span?.end??0;return ne-se}),D=0,H=[];for(let Ae of A){let U=Ae.span?.end;if(typeof U!="number"||U<D)continue;let ne=Array.from(new Set((Ae.chunkIds??[]).map(pe=>pe?lt.get(pe):void 0).map(pe=>pe?v.get(pe):void 0).filter(pe=>typeof pe=="number")));if(!ne.length)continue;let se=Math.min(U,M.length);H.push(M.slice(D,se)),H.push(`<sup>${ne.join(",")}</sup>`),D=se}return H.push(M.slice(D)),H.join("")},[Xe,M]),et=L==="modal"?xt.Root:Gt,Pt=L==="modal"?xt.Content:Gt,Dt=L==="modal"?xt.Body:Gt;return mn(()=>{if(!(L!=="modal"||!K))return document.body.style.overflow="hidden",document.body.onkeydown=A=>{A.key==="Escape"&&(A.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,L]),ze(Qt,{children:[S&&z($t,{leftSection:ce&&(Ue?z("span",{dangerouslySetInnerHTML:{__html:Ue}}):bt()),className:q?"doc-search-open-button":"doc-search-open-button-no-title",variant:"filled",disabled:K,onClick:()=>Ce(!0),"data-ai-kit-open-button":!0,children:q&&de.get(ke||ye)}),K&&ze(et,{opened:!0,className:"doc-search-root",onClose:He,padding:"md",gap:"md",size:"xl",portalProps:L==="modal"?{target:Q,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ke,"data-ai-kit-variation":L,children:[L==="modal"&&z(xt.Overlay,{}),ze(Pt,{w:"100%",style:{left:0},children:[L==="modal"&&ze(xt.Header,{style:{zIndex:1e3},children:[z(ei,{className:"doc-search-title-icon"}),z(xt.Title,{children:de.get(ye)}),z(xt.CloseButton,{})]}),z(Dt,{w:"100%",style:{zIndex:1001},children:z(Ut,{enabled:L!=="modal",working:I,variation:L,children:z(Ga,{shadow:"sm",radius:"md",p:"md",children:ze(Lt,{gap:"sm",children:[L!=="modal"&&z(Xo,{order:4,style:{margin:0},children:de.get(ye)}),ze(Gt,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[z(Qo,{style:{flex:1},value:p,onChange:A=>{C(A.currentTarget.value),b&&yt()},placeholder:b?de.get("Audio recorded"):de.get("Search the documentation\u2026"),disabled:I||x||!!b,onKeyDown:A=>{A.key==="Enter"&&me&&(A.preventDefault(),st())}}),Wa&&z(Qt,{children:b?z($t,{variant:"outline",size:"sm",color:"red",onClick:yt,disabled:I,title:de.get("Clear audio"),children:z(ii,{size:18})}):z($t,{variant:x?"filled":"outline",size:"sm",color:x?"red":"gray",onClick:x?J:Wt,disabled:I,title:x?de.get("Stop recording"):de.get("Record audio"),style:x?{transform:`scale(${1+ie/300})`,transition:"transform 0.1s ease-out"}:void 0,children:z(oi,{size:18})})}),z($t,{variant:"filled",size:"sm",leftSection:it,onClick:()=>{st()},disabled:!me,className:d?"doc-search-button":"doc-search-button-no-title",children:d?de.get("Search"):null}),I?z($t,{variant:"outline",size:"sm",onClick:kt,children:de.get("Stop")}):null]}),Wa&&ze(Qt,{children:[x&&ze(Lt,{gap:"xs",children:[ze(at,{size:"xs",c:"dimmed",children:[de.get("Recording...")," \u{1F3A4}"]}),z(Zo,{value:ie,size:"sm",color:"red",animated:!0,striped:!0})]}),b&&!x&&ze(Lt,{gap:"xs",children:[z(at,{size:"xs",c:"dimmed",children:de.get("Recorded audio:")}),z("audio",{controls:!0,src:URL.createObjectURL(b),className:"ai-kit-audio-player"})]})]}),ge?z(_o,{color:"red",title:de.get("Error"),children:ge}):null,I&&Ge&&z(Ut,{enabled:L==="modal",working:!0,variation:L,children:ze(Gt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[z($o,{size:"sm"}),z(at,{size:"sm",c:"dimmed",children:Ge})]})}),ee?.result?ze(Qt,{children:[z(ja,{}),ze(Lt,{gap:"xs","data-doc-search-result":!0,children:[z(at,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:de.get("AI Summary")}),z(ni,{remarkPlugins:[ri],rehypePlugins:[ai],"data-doc-search-result-content":!0,children:Le||M})]})]}):null,B&&(ee?.citations?.docs?.length||ee?.citations?.chunks?.length)?ze(Qt,{children:[z(ja,{}),ze(Lt,{gap:"sm","data-doc-search-sources":!0,children:[z(at,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:de.get("Sources")}),Se.map(({doc:A})=>{let D=A.sourceUrl?.trim()||void 0,H=A.docId?v.get(A.docId):void 0,Ae=A.title?.trim()||A.docId,U=ze(at,{fw:600,style:{display:"inline"},children:[H?`${H}. `:"",Ae]});return z(Ga,{withBorder:!0,radius:"md",p:"sm",children:z(Lt,{gap:"xs",children:z(Gt,{justify:"space-between",align:"flex-start",children:ze(Lt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[D?z(Na,{href:D,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:ne=>{u&&(ne.preventDefault(),u?.(A))},"data-doc-search-source-title":!0,children:U}):U,z(Na,{href:D,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:ne=>{u&&(ne.preventDefault(),u?.(A))},"data-doc-search-source-url":!0,children:A.sourceUrl}),A.author?z(at,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:A.author}):null,A.description?z(at,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:A.description}):null]})})})},A.docId)})]})]}):null,!I&&!ge&&!ee?.result?z(at,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:de.get("Enter a search query to start.")}):null,z(nn,{variation:L})]})})})})]})]})]})},ui=Rt(li);export{Vo as AiChatbot,po as AiFeature,Dn as DEFAULT_CHATBOT_LABELS,ui as DocSearch,ka as isBackendConfigured,wn as markdownToHtml,Tt as readDefaultOutputLanguage,Yt as stripCodeFence,wt as translations,Kt as useAiRun,Rt as withAiKitShell};
31
+ Follow these additional instructions: ${be}`:"")},{role:"user",content:"What can you see on this image according to the optional knowledge base and shared context?"}].filter(Boolean),Y=await v.run(async({signal:V,onStatus:re})=>(await Ca({messages:N,images:[ee],outputLanguage:"en",responseConstraint:lo},{signal:V,onStatus:re,context:S,modeOverride:o,onDeviceTimeoutOverride:a})).result);if(!Y){I("");return}let ae=(M&&M!=="auto"?M:null)||Tt(),j=Yt(Y).trim();try{X("Translating result...");let V=await v.run(async({signal:re})=>await co(j,ae,{signal:re,context:S,modeOverride:o,onDeviceTimeoutOverride:a,silent:!0}));I(V)}catch(V){I(j),console.warn("AI Kit: failed to parse SEO JSON",V)}break}}}catch(k){De(k instanceof Error?k.message:n.get("An unknown error occurred."))}X(void 0)}},[K,v,be,ye,M,ge,Ge,S,u,me,_e,Se,we]),et=pt(async()=>{await Le("backend-only")},[Le]),Pt=pt(o=>{switch(u){case"proofread":return h(no,{className:o});case"translate":return h(ao,{className:o});case"summarize":return h(io,{className:o});case"rewrite":case"write":return h(ro,{className:o});case"generateImageMetadata":case"generatePostMetadata":return h(oo,{className:o});default:return h(Vr,{mode:u,className:o})}},[u]),Dt=pt(()=>{switch(u){case"proofread":return v.lastSource?n.get("Proofread again"):n.get("Proofread");case"translate":return v.lastSource?n.get("Translate again"):n.get("Translate");case"rewrite":return v.lastSource?n.get("Rewrite again"):n.get("Rewrite");case"summarize":return v.lastSource?n.get("Summarize again"):n.get("Summarize");default:return v.lastSource?n.get("Regenerate"):n.get("Generate")}},[K,v.lastSource,u]),A=pt(()=>{switch(u){case"proofread":return n.get("Proofread on Backend");case"translate":return n.get("Translate on Backend");case"rewrite":return n.get("Rewrite on Backend");case"summarize":return n.get("Summarize on Backend");default:return n.get("Regenerate on Backend")}},[K,u]),D=pt(async()=>{Ze(!1),I(null),De(null),J.current=!1,v.reset(),B||ce()},[ce,J,v,B]),H=pt(async()=>{v.busy&&v.cancel()},[v.busy]);ln(()=>{!ie||!c||!Se||v.busy||P||J.current||(J.current=!0,queueMicrotask(()=>{Le(ke)}))},[v.busy,J,ie,Se,c,P,Le,ke]),ln(()=>{we&&u!=="proofread"&&(Se||(je(!0),J.current=!0))},[we,Se,u]),ln(()=>{let o=!0;return(async()=>{try{await Xr();let k=await ka();o&&Fe(k)}catch(k){console.error(k),o&&Fe(!1)}})(),()=>{o=!1}},[]);let Ae=Vt(()=>{let o=[];if(u==="translate"){let k=sn.find(N=>N.value===_e)?.label;o.push(n.get("Input language")+": "+(k?n.get(k):"auto"))}if(M&&x?.outputLanguage){let k=sn.find(N=>N.value===M)?.label;o.push(n.get("Output language")+": "+(k?n.get(k):M))}return u==="summarize"&&me&&x?.type&&o.push(n.get("Type")+": "+n.get(me)),(u==="write"||u==="rewrite")&&Ge&&x?.tone&&o.push(n.get("Tone")+": "+n.get(Ge)),(u==="write"||u==="rewrite"||u==="summarize")&&ye&&x?.length&&o.push(n.get("Length")+": "+n.get(ye)),be?.trim()&&x?.instructions&&o.push(n.get("Instructions")+": \u2713"),o.length?o.join(" \u2022 "):n.get("No overrides")},[K,u,_e,M,me,Ge,ye,be]),U={label:{fontSize:11,opacity:.85},description:{fontSize:11,opacity:.65,marginTop:2},input:{fontSize:12}},ne=d==="modal"?zt.Root:ct,se=d==="modal"?zt.Content:ct,pe=d==="modal"?zt.Body:ct,At=R==="collapse"?Wr:ht,ut=R==="horizontal"?ct:ht;return ln(()=>{if(!(d!=="modal"||!ie))return document.body.style.overflow="hidden",document.body.onkeydown=o=>{o.key==="Escape"&&(o.preventDefault(),D())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[D,d]),he(_t,{children:[B&&h(It,{leftSection:Z&&(Q?h("span",{dangerouslySetInnerHTML:{__html:Q}}):Pt()),className:$?"ai-feature-open-button":"ai-feature-open-button-no-title",variant:"filled",disabled:ie,onClick:()=>Ze(!0),"data-ai-kit-open-button":!0,children:$&&n.get(L||yt)}),ie&&he(ne,{opened:!0,className:"ai-feature-root",onClose:D,padding:"md",gap:"md",size:"md",portalProps:d==="modal"?{target:Ce,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ue,"data-ai-kit-variation":d,children:[d==="modal"&&h(zt.Overlay,{}),he(se,{w:"100%",style:{left:0},children:[d==="modal"&&he(zt.Header,{style:{zIndex:1e3},children:[Pt("ai-feature-title-icon"),h(zt.Title,{children:n.get(yt)}),h(zt.CloseButton,{})]}),h(pe,{w:"100%",style:{zIndex:1001},children:he(Ut,{enabled:d!=="modal",working:v.busy,variation:d,children:[he(ht,{gap:"sm",mb:"sm",p:"sm",children:[xe&&h(Sn,{color:"red",children:n.get(xe)}),we&&u!=="proofread"&&he(Yr,{withBorder:!0,p:"sm",mt:"md",className:"ai-feature-options","data-options-display":R,children:[he(ct,{justify:"space-between",align:"center",className:"ai-feature-options-summary",onClick:R==="collapse"?()=>je(o=>!o):void 0,children:[R==="collapse"&&he(ht,{gap:0,children:[h(za,{size:"sm",fw:600,style:{lineHeight:1.1},children:n.get("Options")}),h(za,{size:"xs",c:"dimmed",style:{marginTop:2},children:Ae})]}),R==="collapse"&&h(It,{variant:"subtle",size:"xs",style:{minWidth:"fit-content"},onClick:o=>{o.stopPropagation(),je(k=>!k)},children:ot?n.get("Hide"):n.get("Show")})]}),he(At,{in:ot,children:[R==="collapse"&&h(Fr,{my:"sm"}),he(ut,{gap:"xs",justify:"space-between",children:[u==="write"&&x?.text&&h(mt,{label:n.get("The topic or subject for the AI to write about."),disabled:R!=="horizontal",position:"top",children:h(gt,{size:"xs",className:"ai-feature-option",styles:U,disabled:v.busy,label:n.get("Topic"),description:R!=="horizontal"?n.get("The topic or subject for the AI to write about."):void 0,value:ge||"",onChange:o=>{let k=o.target.value;Ve(k),C?.({text:k})}})}),(u==="write"||u==="rewrite"||u==="generateImageMetadata"||u==="generatePostMetadata")&&x?.instructions&&h(mt,{label:n.get("Additional instructions to guide the AI."),disabled:R!=="horizontal",position:"top",children:h(gt,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Instructions"),description:R!=="horizontal"?n.get("Additional instructions to guide the AI."):void 0,value:be||"",onChange:o=>{let k=o.target.value;kt(k),C?.({instructions:k})}})}),u==="translate"&&h(mt,{label:n.get("The language of the input text."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",styles:U,className:"ai-feature-option",label:n.get("Input language"),description:R!=="horizontal"?n.get("The language of the input text."):void 0,data:[{value:"auto",label:n.get("Auto-detect")},...sn.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:_e||"auto",onChange:o=>{let k=o;Qe(k),Oe(void 0),C?.({inputLanguage:k})}})}),x?.outputLanguage&&h(mt,{label:n.get("The language AI-Kit should use for generated text by default (when applicable)."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",styles:U,className:"ai-feature-option",label:n.get("Output language"),description:R!=="horizontal"?n.get("The language AI-Kit should use for generated text by default (when applicable)."):void 0,data:[...[u==="rewrite"?{value:"auto",label:n.get("Auto-detect")}:void 0].filter(Boolean),...sn.map(o=>({value:o.value,label:n.get(o.label)})).sort((o,k)=>o.label.localeCompare(k.label))],value:M||Ma.settings.defaultOutputLanguage||(u==="rewrite"?"auto":""),onChange:o=>{let k=o;it(k),Oe(void 0),C?.({outputLanguage:k})}})}),u==="summarize"&&x?.type&&h(mt,{label:n.get("The summary style to generate."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Type"),description:R!=="horizontal"?n.get("The summary style to generate."):void 0,data:[{value:"headline",label:n.get("Headline")},{value:"key-points",label:n.get("Key Points")},{value:"teaser",label:n.get("Teaser")},{value:"tldr",label:n.get("TL;DR")}],value:me||"key-points",onChange:o=>{let k=o;Wt(k),C?.({type:k})}})}),(u==="write"||u==="rewrite")&&x?.tone&&h(mt,{label:n.get("The tone or style for the AI to use."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Tone"),description:R!=="horizontal"?n.get("The tone or style for the AI to use."):void 0,data:u==="write"?[{value:"neutral",label:n.get("Neutral")},{value:"formal",label:n.get("Formal")},{value:"casual",label:n.get("Casual")}]:[{value:"as-is",label:n.get("As-Is")},{value:"more-formal",label:n.get("More formal")},{value:"more-casual",label:n.get("More casual")}],value:Ge||(u==="write"?"neutral":"as-is"),onChange:o=>{let k=o;Ee(k),C?.({tone:k})}})}),(u==="write"||u==="rewrite"||u==="summarize")&&x?.length&&h(mt,{label:n.get("The target output length."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Length"),description:R!=="horizontal"?n.get("The target output length."):void 0,data:u==="write"||u==="summarize"?[{value:"short",label:n.get("Short")},{value:"medium",label:n.get("Medium")},{value:"long",label:n.get("Long")}]:[{value:"as-is",label:n.get("As-Is")},{value:"shorter",label:n.get("Shorter")},{value:"longer",label:n.get("Longer")}],value:ye||(u==="rewrite"?"as-is":"short"),onChange:o=>{let k=o;bt(k),C?.({length:k})}})}),u==="summarize"||u==="write"||u==="rewrite"&&x?.outputFormat&&h(mt,{label:n.get("The format for the generated output."),disabled:R!=="horizontal",position:"top",children:h(Ot,{disabled:v.busy,size:"xs",className:"ai-feature-option",styles:U,label:n.get("Output format"),description:R!=="horizontal"?n.get("The format for the generated output."):void 0,data:[{value:"plain-text",label:n.get("Plain Text")},{value:"markdown",label:n.get("Markdown")},{value:"html",label:n.get("HTML")}],value:te||"markdown",onChange:o=>{let k=o;Xe(k),C?.({outputFormat:k})}})})]})]})]}),v.busy&&lt&&h(Ut,{enabled:d==="modal",working:!0,variation:d,children:he(ct,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[h(qr,{size:"sm"}),h(Rn.Label,{className:"ai-feature-status-text",children:lt})]})}),P&&he(ht,{mt:"md",children:[u==="proofread"&&(P.corrections.length===0?h(Sn,{color:"green",children:n.get("No issues found. Your text looks great!")}):he(_t,{children:[h("p",{style:{marginTop:0,opacity:.85},children:n.get("Hover highlights to see explanations.")}),h(Ia,{original:ge,corrections:P.corrections}),P.correctedInput?he(_t,{children:[h("h4",{style:{marginTop:16,marginBottom:8},children:n.get("Corrected")}),h(ct,{c:"pre",className:"ai-feature-generated-content",children:P.correctedInput})]}):null]})),u==="generateImageMetadata"&&he(_t,{children:[h(gt,{readOnly:!s,label:n.get("Alt Text"),description:n.get("The alt text for the image."),value:P.alt_text||"",onChange:o=>I({...P,alt_text:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the image."),value:P.title||"",onChange:o=>I({...P,title:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Caption"),description:n.get("The caption for the image."),value:P.caption||"",onChange:o=>I({...P,caption:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Description"),description:n.get("The description for the image."),value:P.description||"",onChange:o=>I({...P,description:o.target.value})})]}),u==="generatePostMetadata"&&he(_t,{children:[h(gt,{readOnly:!s,label:n.get("Title"),description:n.get("The title for the post."),value:P.title||"",onChange:o=>I({...P,title:o.target.value})}),h(gt,{readOnly:!s,label:n.get("Excerpt"),description:n.get("The excerpt for the post."),value:P.excerpt||"",onChange:o=>I({...P,excerpt:o.target.value})})]}),u!=="proofread"&&u!=="generateImageMetadata"&&u!=="generatePostMetadata"&&typeof P=="string"&&h(Pa,{value:P,editable:!!s,onChange:o=>{I(o)}})]}),P===""&&h(Pa,{value:P,editable:!1})]}),he(ct,{className:"ai-kit-actions",gap:"sm",mb:"sm",p:"sm",children:[v.busy&&h(It,{variant:"outline",size:"sm",onClick:H,"data-ai-kit-cancel-button":!0,children:n.get("Cancel")}),!v.busy&&h(It,{variant:"filled",size:"sm",disabled:!Se,onClick:()=>Le(),"data-ai-kit-generate-button":!0,children:Dt()}),!v.busy&&v.lastSource==="on-device"&&We&&Ke&&h(It,{variant:"filled",size:"sm",disabled:!Se,onClick:et,"data-ai-kit-regenerate-on-backend-button":!0,children:A()}),!v.busy&&p&&h(It,{variant:"outline",size:"sm",disabled:!P||u==="proofread"&&P.corrections.length===0,onClick:async()=>{p(te==="html"?await wn(P):P),D()},"data-ai-kit-accept-button":!0,children:n.get(_)}),h(It,{variant:"default",size:"sm",onClick:D,"data-ai-kit-close-button":!0,children:n.get("Close")})]}),h(nn,{variation:d})]})})]})]})]})};function Pa(t){let{value:r,editable:c,onChange:s}=t;return c?he(ht,{p:0,gap:"sm",children:[h(Rn.Label,{children:n.get("Generated content")}),h(Jr,{value:r,onChange:a=>s?.(a.currentTarget.value),autosize:!0,minRows:2,maxRows:12,p:0,className:"ai-feature-generated-content ai-feature-editor"}),h(Rn.Label,{children:n.get("Preview")}),h(ht,{className:"ai-feature-generated-content ai-feature-preview",children:h(xa,{remarkPlugins:[La],children:r})})]}):h(ht,{className:"ai-feature-generated-content",children:r?h(xa,{remarkPlugins:[La],children:r}):h(Sn,{color:"yellow",children:n.get("No content generated.")})})}var po=Rt(mo);import{ActionIcon as Ea,Anchor as vo,Box as wo,Button as Ye,Group as Pe,Input as To,List as Ba,Modal as Ct,Stack as Je,Text as Ie,Textarea as So}from"@mantine/core";import{IconMaximize as Ro,IconMessage as Io,IconMicrophone as zo,IconMinimize as Co,IconPaperclip as xo,IconPencil as Lo,IconPlayerStop as Mo,IconSend as Po,IconTrash as Do,IconX as Eo}from"@tabler/icons-react";import{getStoreSelect as Bo,sendChatMessage as Ko,sendFeedbackMessage as Uo}from"@smart-cloud/ai-kit-core";import{useSelect as Oo}from"@wordpress/data";import{I18n as f}from"aws-amplify/utils";import{useCallback as F,useEffect as le,useMemo as fe,useRef as ve,useState as ue}from"react";import No from"react-markdown";import jo from"remark-gfm";var ho="ai-kit-chatbot-attachments",$e="attachments";var In=null;function fo(){return typeof window<"u"&&typeof window.indexedDB<"u"}async function un(){if(!fo())return null;In||(In=new Promise(t=>{try{let r=window.indexedDB.open(ho,1);r.onerror=()=>t(null),r.onblocked=()=>t(null),r.onupgradeneeded=()=>{let c=r.result;c.objectStoreNames.contains($e)||c.createObjectStore($e,{keyPath:"id"})},r.onsuccess=()=>t(r.result)}catch(r){console.warn("[AiChatbot] IndexedDB is not available",r),t(null)}}));try{return await In}catch(t){return console.warn("[AiChatbot] Failed to open attachment store",t),null}}async function zn(t,r){let c=await un();return c?new Promise((s,a)=>{try{let d=c.transaction($e,t),w=d.objectStore($e),B=r(w);d.oncomplete=()=>s(B),d.onerror=()=>a(d.error),d.onabort=()=>a(d.error)}catch(d){a(d)}}).catch(s=>(console.warn("[AiChatbot] Attachment store transaction failed",s),null)):null}async function Cn(t,r,c){await Ao();let s={id:t,blob:r,name:c.name,type:c.type,size:c.size,createdAt:Date.now()};return await zn("readwrite",d=>(d.put(s),t))}async function xn(t){let r=await un();return r?new Promise((c,s)=>{try{let a=r.transaction($e,"readonly"),d=a.objectStore($e).get(t);d.onsuccess=()=>{let w=d.result;c(w??null)},d.onerror=()=>s(d.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(c=>(console.warn("[AiChatbot] Failed to load attachment",c),null)):null}async function ko(t){await zn("readwrite",r=>{r.delete(t)})}async function dn(){await zn("readwrite",t=>{t.clear()})}async function Ln(t){let r=await un();r&&await new Promise((c,s)=>{try{let a=r.transaction($e,"readwrite"),d=a.objectStore($e),w=d.getAllKeys();w.onsuccess=()=>{let B=w.result;for(let $ of B){let Z=String($);t.has(Z)||d.delete($)}},w.onerror=()=>s(w.error),a.oncomplete=()=>c(),a.onerror=()=>s(a.error),a.onabort=()=>s(a.error)}catch(a){s(a)}}).catch(c=>{console.warn("[AiChatbot] Failed to cleanup attachments",c)})}var bo=50*1024*1024;async function yo(){let t=await un();return t?new Promise((r,c)=>{try{let s=t.transaction($e,"readonly"),a=s.objectStore($e).getAll();a.onsuccess=()=>{let d=a.result||[];r(d)},a.onerror=()=>c(a.error),s.onerror=()=>c(s.error),s.onabort=()=>c(s.error)}catch(s){c(s)}}).catch(r=>(console.warn("[AiChatbot] Failed to get all attachments",r),[])):[]}async function Ao(){let t=await yo();if(t.length===0)return;let r=t.sort((d,w)=>d.createdAt-w.createdAt),c=r.reduce((d,w)=>d+w.size,0),s=[],a=0;for(;c>bo&&a<r.length;){let d=r[a];d&&(s.push(d.id),c-=d.size),a++}for(let d of s)await ko(d);s.length>0&&console.log(`[AiChatbot] Deleted ${s.length} old attachment(s) to enforce storage quota`)}import{Fragment as Ua,jsx as g,jsxs as G}from"react/jsx-runtime";f.putVocabularies(wt);var cn=1440*60*1e3,Mn=!1,Go=1,Ho="localstorage",Nt=`ai-kit-chatbot-history-v1:${typeof window<"u"?window.location.hostname:"unknown"}`,Dn={modalTitle:"AI Assistant",userLabel:"User",assistantLabel:"Assistant",assistantThinkingLabel:"Assistant is thinking...",askMeLabel:"Ask me",sendLabel:"Send",cancelLabel:"Cancel",resetLabel:"Reset",confirmLabel:"Confirm",clickAgainToConfirmLabel:"Click again to confirm",notSentLabel:"Not sent",editLabel:"Edit",readyLabel:"Ready.",readyEmptyLabel:"I'm ready to assist you.",addLabel:"Add",addImageLabel:"Add image",removeImageLabel:"Remove image",closeChatLabel:"Close chat",maximizeLabel:"Maximize",restoreSizeLabel:"Restore size",referencesLabel:"References",referenceLabel:"Reference",acceptResponseLabel:"Accept response",rejectResponseLabel:"Reject response",placeholder:"Ask anything\u2026",emptyResponseLabel:"Empty response",unexpectedErrorLabel:"Unexpected error"};function ft(t){return`${t}-${Math.random().toString(36).slice(2)}-${Date.now().toString(36)}`}var Wo=4,Fo=5*1024*1024,qo=t=>{let r=(t?.name||"").toString(),c=(t?.code||"").toString(),s=(t?.message||"").toString();return r==="AbortError"||c==="ABORT_ERR"||/abort|aborted|cancel/i.test(s)},Yo=(t,r)=>{if(!t)return null;let c=t.step,s=f.get((t.message??"").trim()),a=typeof t.progress=="number"?t.progress:null,d=a==null?null:Math.round(a*100);switch(c){case"decide":return s||f.get("Checking capabilities...");case"on-device:init":return s||f.get("Initializing on-device AI...");case"on-device:download":return d==null?s||f.get("Downloading model..."):s||`${f.get("Downloading model...")} ${d}%`;case"on-device:ready":return s||f.get("On-device model ready...");case"on-device:run":return s||f.get("Running on-device...");case"backend:request":case"backend:waiting":case"backend:response":return f.get(r.assistantThinkingLabel??Dn.assistantThinkingLabel);case"done":return s||f.get("Done.");case"error":return s||f.get("An error occurred.");default:return s||null}};function Pn(t){if(typeof window>"u")return null;try{return t==="localstorage"?window.localStorage:t==="sessionstorage"?window.sessionStorage:null}catch{return null}}var jt=t=>{if(typeof window>"u"||typeof URL>"u"||typeof URL.createObjectURL!="function")return null;try{return URL.createObjectURL(t)}catch{return null}},gn=t=>{if(t&&!(typeof window>"u")&&!(typeof URL>"u"||typeof URL.revokeObjectURL!="function"))try{URL.revokeObjectURL(t)}catch{}},Oa=t=>{!t||t.length===0||t.forEach(r=>gn(r.objectUrl))},Ka=t=>{t.forEach(r=>Oa(r.attachments))},Jo=t=>{let{rootElement:r,store:c,previewMode:s,title:a,openButtonTitle:d,openButtonIcon:w,showOpenButtonTitle:B=!0,showOpenButtonIcon:$=!0,colorMode:Z,language:L,onClose:Q,context:Ke,placeholder:_,maxImages:R,maxImageBytes:u,historyStorage:S=Ho,emptyHistoryAfterDays:ke=Go,labels:Ue,openButtonIconLayout:q="top",openButtonPosition:ce="bottom-right"}=t,p=fe(()=>({...Dn,...Ue||{}}),[Ue]),C=Kt(),[K,Ce]=ue(""),[x,we]=ue([]),[b,X]=ue(null),[ie,Ze]=ue(!1),[ot,je]=ue(0),We=ve(null),Fe=ve([]),xe=ve(null),De=ve(null),P=ve(null),[I,ge]=ue([]),[Ve,ee]=ue(null),[be,kt]=ue(!1),[Te,Oe]=ue(!1),[_e,Qe]=ue(!1),[te,Xe]=ue(!1),[M,it]=ue(!0),[ye,bt]=ue(null),[Ge,Ee]=ue(!1),[me,Wt]=ue(null),[J,yt]=ue(null),[st,He]=ue(!1),[Se,v]=ue(null),lt=ve(Se);le(()=>{lt.current=Se},[Se]);let Le=ve(null),et=ve(!1),[Pt,Dt]=ue(null),A=ve(null),D=ve(null),H=ve(null),Ae=ve(null),U=F(e=>{e.forEach(l=>gn(l.objectUrl))},[]),ne=F(()=>{U(ae.current),we([]),A.current&&(A.current.value="")},[U]),se=F(()=>{j.current&&gn(j.current.objectUrl),X(null),Fe.current=[],je(0)},[]),pe=F(async()=>{try{Ce(""),se();let e=await navigator.mediaDevices.getUserMedia({audio:!0}),l=new MediaRecorder(e,{mimeType:"audio/webm"}),m=new AudioContext,i=m.createMediaStreamSource(e),T=m.createAnalyser();T.fftSize=2048,T.smoothingTimeConstant=.8,i.connect(T),xe.current=m,De.current=T;let y=new Uint8Array(T.fftSize),E=()=>{if(!De.current)return;De.current.getByteTimeDomainData(y);let W=0;for(let Ne=0;Ne<y.length;Ne++){let vt=(y[Ne]-128)/128;W+=vt*vt}let Re=Math.sqrt(W/y.length),Be=Math.min(100,Re*200);je(Be),P.current=requestAnimationFrame(E)};E(),Fe.current=[];let O=Date.now();l.ondataavailable=W=>{W.data.size>0&&Fe.current.push(W.data)},l.onstop=()=>{let W=new Blob(Fe.current,{type:"audio/webm"}),Re=(Date.now()-O)/1e3,Be=jt(W);Be&&X({id:ft("composer-audio"),blob:W,objectUrl:Be,duration:Re}),e.getTracks().forEach(Ne=>Ne.stop()),P.current&&(cancelAnimationFrame(P.current),P.current=null),xe.current&&(xe.current.close(),xe.current=null),De.current=null,je(0)},We.current=l,l.start(),Ze(!0)}catch(e){console.error("Failed to start recording:",e)}},[se]),At=F(()=>{We.current&&ie&&(We.current.stop(),Ze(!1))},[ie]);le(()=>()=>{P.current&&cancelAnimationFrame(P.current),xe.current&&xe.current.close(),se()},[se]);let[ut,o]=ue(null),k=ve(K),N=ve(I),Y=ve(ut),ae=ve(x),j=ve(b);le(()=>{k.current=K},[K]),le(()=>{ae.current=x},[x]),le(()=>{j.current=b},[b]),le(()=>{N.current=I},[I]),le(()=>{Y.current=ut},[ut]),le(()=>{L&&f.setLanguage(L||"en")},[L]);let V=Oo(()=>Bo(c).isShowChatbotPreview()),re=fe(()=>Math.max(0,R??Wo),[R]),qe=fe(()=>Math.max(0,u??Fo),[u]),tt=I.length>0,oe=fe(()=>C.busy&&Se==="chat",[C.busy,Se]),pn=fe(()=>oe?!1:K.trim().length>0||b!==null,[K,oe,b]),Et=fe(()=>{let e=d||p.askMeLabel;return f.get(e)},[d,p.askMeLabel,L]),Fa=fe(()=>{let e=a||p.modalTitle;return f.get(e)},[a,p.modalTitle,L]),qa=fe(()=>{let e=_||p.placeholder;return f.get(e)},[_,p.placeholder,L]),En=fe(()=>{let e="ai-docs-ask",l=`ai-open-btn--${ce}`;return`${e} ${l}`},[ce]),Xt=F(()=>{let e=Ae.current;if(e)try{let l=window.innerHeight||document.documentElement.clientHeight,m=360,i=1e3,T=Math.floor(l*.8),y=Math.max(m,Math.min(T,i));e.style.height=`${y}px`}catch{}},[]),Ft=F(()=>{let e=J;e&&window.setTimeout(()=>{try{e.scrollTop=e.scrollHeight}catch{}},50)},[J]),Bn=F(()=>{Xe(!1),Te&&Oe(!1),Qe(!1),Q?.()},[Te,Q]);le(()=>{if(te)return Xt(),window.addEventListener("resize",Xt),()=>window.removeEventListener("resize",Xt)},[te,Xt]),le(()=>{if(!(!te||!Te))return document.body.style.overflow="hidden",()=>{document.body.style.overflow=""}},[te,Te,Bn]);let Kn=fe(()=>x.map(e=>({id:e.id,url:e.objectUrl,title:e.file.name})),[x]);le(()=>{tt||it(!0)},[tt]),le(()=>()=>{U(ae.current)},[U]),le(()=>{let e=J;if(!e)return;let l=()=>{let m=e.scrollHeight-(e.scrollTop+e.clientHeight);it(m<20)};return e.addEventListener("scroll",l),()=>{e.removeEventListener("scroll",l)}},[te,J]),le(()=>{if(!M)return;let e=J;e&&e.scrollHeight>e.clientHeight&&(e.scrollTop=e.scrollHeight)},[I,C.busy,M,J]),le(()=>{te||bt(null)},[te]);let Un=fe(()=>C.busy?Yo(C.statusEvent,p)||f.get("Working\u2026"):null,[C.busy,C.statusEvent,L,p]),Ya=fe(()=>{for(let e=I.length-1;e>=0;e--){let l=I[e];if(l.role==="user"&&l.clientStatus==="canceled")return l.id}return null},[I]),qt=F(e=>{ge(l=>{let m=[...l].map((y,E)=>({m:y,i:E})).reverse().find(y=>y.m.role==="user"&&y.m.clientStatus==="pending")?.i;if(m==null)return l;let i=l.slice(),T=i[m];return i[m]={...T,clientStatus:e??void 0},i})},[ge]),en=F(()=>{if(!(!C.busy||lt.current!=="chat")){et.current=!0;try{C.cancel()}catch{}qt("canceled"),v(null),ee(null),Ft()}},[C,qt,Ft]),Ja=F(e=>{let l=ae.current,m=Array.from(e.target.files||[]),i=Math.max(0,re-l.length);if(i===0){e.currentTarget.value="";return}let T=[];for(let y of m){if(T.length>=i)break;let E=/image\/(jpeg|png|gif|webp)/i.test(y.type),O=y.size<=qe,W=[...l,...T].some(Be=>Be.file.name===y.name&&Be.file.size===y.size&&Be.file.lastModified===y.lastModified);if(!E||!O||W)continue;let Re=jt(y);Re&&T.push({id:ft("composer-image"),file:y,objectUrl:Re})}T.length&&we(y=>[...y,...T]),e.currentTarget.value=""},[re,qe]),Va=F(e=>{we(l=>{if(e<0||e>=l.length)return l;let m=l[e];return m&&gn(m.objectUrl),l.filter((i,T)=>T!==e)})},[]),dt=ve(null);le(()=>{if(Ve)return dt.current&&(window.clearTimeout(dt.current),dt.current=null),dt.current=window.setTimeout(()=>{ee(null),dt.current=null},6e3),()=>{dt.current&&(window.clearTimeout(dt.current),dt.current=null)}},[Ve]);let On=F(async(e,l)=>{let m=S!=="nostorage",i=[];if(e.length>0){let T=await Promise.all(e.map(async y=>{let E=ft("attachment-image"),O;if(m)try{O=await Cn(E,y.file,{name:y.file.name,type:y.file.type,size:y.file.size})??void 0}catch(Re){console.warn("[AiChatbot] Failed to persist image",Re)}let W=jt(y.file);return{id:E,name:y.file.name,type:y.file.type||"application/octet-stream",size:y.file.size,blobId:O,objectUrl:W??void 0,blob:y.file,mediaType:"image"}}));i.push(...T.filter(Boolean))}if(l){let T=ft("attachment-audio"),y;if(m)try{y=await Cn(T,l.blob,{name:`audio-${Date.now()}.webm`,type:l.blob.type,size:l.blob.size})??void 0}catch(O){console.warn("[AiChatbot] Failed to persist audio",O)}let E=jt(l.blob);i.push({id:T,name:`audio-${Date.now()}.webm`,type:l.blob.type||"audio/webm",size:l.blob.size,blobId:y,objectUrl:E??void 0,blob:l.blob,duration:l.duration,mediaType:"audio"})}return i},[S]),Nn=F(async e=>{let l=[];for(let m of e){let i;if(m.attachments&&m.attachments.length>0){i=[];for(let T of m.attachments){let y;if(T.blobId)try{y=(await xn(T.blobId))?.blob??void 0}catch(O){console.warn("[AiChatbot] Failed to hydrate attachment",O)}if(!y)continue;let E=y?jt(y):null;i.push({...T,objectUrl:E??void 0,blob:y??void 0})}}l.push({...m,attachments:i})}return l},[]),jn=F(async e=>{if(!e||e.length===0){ne();return}let l=[];for(let m of e){let i=m.blob;if(!i&&m.blobId)try{i=(await xn(m.blobId))?.blob??void 0}catch(E){console.warn("[AiChatbot] Failed to reload attachment",E)}if(!i)continue;let T=i instanceof File?i:new File([i],m.name||"attachment",{type:m.type||i.type||"application/octet-stream"}),y=jt(T);if(y&&(l.push({id:ft("composer-image"),file:T,objectUrl:y}),l.length>=re))break}if(l.length===0){ne();return}we(m=>(U(m),l)),A.current&&(A.current.value="")},[ne,U,re]),hn=F((e,l)=>{e&&bt({url:e,title:l})},[]),_a=F(()=>{bt(null)},[]),Gn=F(()=>{Ka(N.current),ne(),se(),ge([]),ee(null),H.current=null,o(null),it(!0),kt(!1);let e=Pn(S);if(e)try{e.removeItem(Nt)}catch{}dn()},[ne,se,S]),$a=F(()=>{kt(!0)},[]),Za=F(()=>{C.busy&&lt.current==="chat"&&en(),Gn()},[C.busy,en,Gn]),Hn=F(()=>{kt(!1)},[]),Wn=F(async(e,l)=>{if(!C.busy)try{let m=H.current&&Date.now()-H.current.storedAt<ke*cn?H.current.id:void 0;if(!m)return;v("feedback"),ee(null),await C.run(async({signal:i,onStatus:T})=>(await Uo({sessionId:m,feedbackMessageId:e,feedbackType:l},{signal:i,onStatus:T,context:Ke}),null)),ee(null)}catch(m){let i=m?.message?.trim()||f.get("An error occurred.");ee(i),console.error("Failed to send feedback",m)}finally{v(m=>m==="feedback"?null:m)}},[C,L]),Fn=F((e,l)=>{ge(m=>m.map(i=>i.id!==e||i.role!=="assistant"?i:i.feedback===l?{...i,feedback:void 0}:{...i,feedback:l})),Wn(e,l)},[Wn]),tn=F(async()=>{let e=k.current.trim(),l=j.current;if(!e&&!l||C.busy)return;et.current=!1,ee(null),v("chat");let m=[...ae.current],i=await On(m,l),T=ft("user"),y=Date.now(),E={id:T,role:"user",content:e||(l?"[Audio message]":""),createdAt:y,clientStatus:"pending",attachments:i.length?i:void 0};Ce(""),ne(),se(),ge(O=>[...O,E]),te||Xe(!0),Ft();try{let O=H.current&&Date.now()-H.current.storedAt<ke*cn?H.current.id:void 0,W=await C.run(async({signal:Be,onStatus:Ne})=>await Ko({sessionId:O,message:e||void 0,audio:l?.blob,images:m.map(ur=>ur.file)},{signal:Be,onStatus:Ne,context:Ke}));if(et.current){qt("canceled");return}if(!W)throw new Error(f.get(C.error??p.emptyResponseLabel));W.sessionId&&(H.current={id:W.sessionId,storedAt:Date.now()});let Re={id:W.metadata?.messageId||ft("assistant"),role:"assistant",content:W.result||"",citations:W.citations,createdAt:Date.now()};ge(Be=>[...Be.map(vt=>vt.id===T?{...vt,clientStatus:void 0}:vt),Re]),o(y)}catch(O){if(console.error("Error during ask()",O),et.current||qo(O)){qt("canceled");return}let W=O?.message?.trim()||f.get(p.unexpectedErrorLabel);ge(Re=>[...Re.map(Ne=>Ne.id===T?{...Ne,clientStatus:void 0}:Ne),{id:ft("assistant-error"),role:"assistant",content:`\u26A0\uFE0F ${W}`,createdAt:Date.now()}]),o(y)}finally{v(O=>O==="chat"?null:O),et.current=!1,D.current&&D.current.focus(),Ft()}},[C,On,ne,se,te,Ft,qt,p.emptyResponseLabel,p.unexpectedErrorLabel,L]),Qa=F(e=>{e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),pn&&tn())},[tn,pn]),Xa=F(()=>{Xe(!0)},[]);le(()=>()=>{Le.current!=null&&(cancelAnimationFrame(Le.current),Le.current=null)},[]);let er=F(()=>{Oe(e=>{let l=!e;return Le.current!=null&&(cancelAnimationFrame(Le.current),Le.current=null),l?(Qe(!0),requestAnimationFrame(()=>{Le.current=requestAnimationFrame(()=>{Qe(!1),Le.current=null})})):Qe(!1),l})},[]),tr=F(e=>{Ce(e.content),(async()=>(await jn(e.attachments),ge(l=>l.filter(m=>m.id!==e.id)),Oa(e.attachments),queueMicrotask(()=>D.current?.focus())))()},[jn]),qn=fe(()=>$?w?g("img",{src:w,className:"ai-open-btn-icon",alt:f.get(p.askMeLabel||Et)}):g(Io,{size:18}):null,[$,w,p,Et,L]),nr=fe(()=>{let e=qn,l=B?g(Ie,{inherit:!0,children:Et}):null;if(!$&&!l)return null;if(!$)return l;if(!B)return e;switch(q){case"top":return G(Je,{gap:4,align:"center",children:[e,l]});case"bottom":return G(Je,{gap:4,align:"center",children:[l,e]});case"right":return G(Pe,{gap:6,align:"center",children:[l,e]});default:return G(Pe,{gap:6,align:"center",children:[e,l]})}},[qn,$,B,Et,q]),ar=fe(()=>oe,[oe]),rr=fe(()=>!oe,[oe]),or=fe(()=>Ve||(tt?f.get(p.readyLabel):f.get(p.readyEmptyLabel)),[Ve,tt,p.readyLabel,p.readyEmptyLabel,L]),ir=fe(()=>oe?f.get(p.cancelLabel):f.get(p.sendLabel),[oe,p.cancelLabel,p.sendLabel,L]),sr=fe(()=>oe?g(Mo,{size:18}):g(Po,{size:18}),[oe]),lr=F(()=>{if(oe){en();return}tn()},[oe,en,tn]);return le(()=>{if(!te||!me||!J)return;let e=()=>{let O=window.getComputedStyle(J).overflowY,W=O==="auto"||O==="scroll",Re=Math.ceil(J.scrollHeight),Be=Math.floor(J.clientHeight),Ne=Re>Be;return W&&Ne},l=!1,m=E=>{if(!e())return;E.preventDefault();let O=J.scrollHeight-J.clientHeight;J.scrollTop=Math.max(0,Math.min(O,J.scrollTop+E.deltaY))},i=()=>{let E=e();He(E),E!==l&&(l=E,l?me.addEventListener("wheel",m,{passive:!1}):me.removeEventListener("wheel",m))};i();let T=new ResizeObserver(i);T.observe(J);let y=new MutationObserver(i);return y.observe(J,{childList:!0,subtree:!0,characterData:!0}),window.addEventListener("resize",i),()=>{l&&me.removeEventListener("wheel",m),T.disconnect(),y.disconnect(),window.removeEventListener("resize",i)}},[te,me,J]),le(()=>{let e=!1,l=Pn(S);if(!l){S==="nostorage"&&dn(),Ee(!0);return}return(async()=>{try{let m=l.getItem(Nt);if(!m){Ee(!0);return}let i=JSON.parse(m),T=typeof i?.lastUserSentAt=="number"?i.lastUserSentAt:null;if(!T||Date.now()-T>ke*cn){l.removeItem(Nt),await dn(),Ee(!0);return}let E=(Array.isArray(i.messages)?i.messages:[]).map(W=>W?.role==="user"&&W.clientStatus==="pending"?{...W,clientStatus:"canceled"}:W),O=await Nn(E);if(e){Ka(O);return}ge(O),o(T),i.session&&i.session.id&&(H.current=i.session)}catch(m){console.warn("[AiChatbot] Failed to load history",m);try{l.removeItem(Nt)}catch{}}finally{e||Ee(!0)}})(),()=>{e=!0}},[S,ke,Nn]),le(()=>{if(!Ge)return;let e=Pn(S);if(!e)return;let l=Y.current;if(!l)return;if(Date.now()-l>ke*cn){try{e.removeItem(Nt)}catch{}Ln(new Set);return}let m=I.map(({attachments:y,...E})=>({...E,attachments:y?.map(({objectUrl:O,blob:W,...Re})=>Re)})),i={version:1,lastUserSentAt:l,session:H.current,messages:m};try{e.setItem(Nt,JSON.stringify(i))}catch{}let T=new Set;m.forEach(y=>{y.attachments?.forEach(E=>{E.blobId&&T.add(E.blobId)})}),Ln(T)},[Ge,I,ut,S,ke]),s&&!V||!s&&V?null:G(Pe,{className:En,children:[!te&&g(Ye,{variant:"filled",className:B?"ai-launcher-button ai-launcher-text":"ai-launcher-button",onClick:Xa,"aria-label":Et,title:Et,"data-ai-kit-open-button":!0,children:nr}),te&&g(Ct.Root,{ref:Ae,opened:te,lockScroll:!1,trapFocus:!1,closeOnEscape:!0,onClose:Bn,className:En+" ai-chat-container"+(Te?" maximized":"")+(Te&&_e?" ai-max-enter":""),portalProps:{target:r,reuseTargetNode:!0},"data-ai-kit-theme":Z,"data-ai-kit-variation":"modal",children:G("div",{className:"ai-chat-container-internal",ref:Wt,children:[G(Ct.Header,{className:"ai-chat-header-bar",children:[g(Ct.Title,{className:"ai-chat-title",children:Fa}),G(Pe,{gap:"4px",align:"center",justify:"center",children:[typeof window<"u"&&window.innerWidth>600&&g(Ea,{variant:"subtle",c:"var(--ai-kit-chat-icon-color, var(--ai-kit-color-text))",onClick:er,title:Te?f.get(p.restoreSizeLabel):f.get(p.maximizeLabel),"aria-label":Te?f.get(p.restoreSizeLabel):f.get(p.maximizeLabel),"data-ai-kit-maximize-button":!0,children:Te?g(Co,{size:16}):g(Ro,{size:16})}),g(Ct.CloseButton,{"aria-label":f.get(p.closeChatLabel)})]})]}),G(Ct.Body,{className:"ai-chat-scroll",ref:yt,"data-scrollable":st?"true":"false",children:[I.map(e=>{let l=e.role==="user",m=l&&e.clientStatus==="canceled"&&e.id===Ya;return g(Pe,{justify:l?"flex-end":"flex-start",className:"ai-chat-row "+e.role,onMouseEnter:()=>Dt(e.id),onMouseLeave:()=>Dt(i=>i===e.id?null:i),children:G(Je,{gap:4,w:"100%",style:{alignItems:l?"flex-end":"flex-start"},children:[G(Je,{className:"ai-chat-bubble",children:[G(Ie,{className:"ai-chat-header",children:[g(Ie,{fw:"bolder",size:"xs",style:{whiteSpace:"nowrap"},children:l?f.get(p.userLabel):f.get(p.assistantLabel)}),"\xA0",g(Ie,{size:"xs",style:{whiteSpace:"nowrap"},children:new Date(e.createdAt).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),e.role==="assistant"?g(No,{remarkPlugins:[jo],children:e.content}):g(Ie,{size:"sm",miw:"100px",children:e.content})]}),e.attachments&&e.attachments.length>0&&G(Je,{gap:"xs",style:{maxWidth:"min(400px, 100%)"},children:[e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).length>0&&g(Pe,{className:"ai-thumbs ai-message-thumbs",gap:"xs",children:e.attachments.filter(i=>i.mediaType==="image"||!i.mediaType&&i.type.startsWith("image/")).map(i=>g("button",{type:"button",className:"thumb",style:{backgroundImage:i.objectUrl?`url(${i.objectUrl})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat"},onClick:()=>hn(i.objectUrl,i.name),disabled:!i.objectUrl,title:i.name||f.get("View image"),"aria-label":i.name||f.get("View image"),children:!i.objectUrl&&g(Ie,{size:"xs",c:"dimmed",children:f.get("Image no longer available")})},i.id))}),e.attachments.filter(i=>i.mediaType==="audio"||!i.mediaType&&i.type.startsWith("audio/")).map(i=>g(wo,{p:"sm",style:{backgroundColor:"var(--ai-kit-chat-surface-subtle)",borderRadius:"var(--ai-kit-radius-sm)",border:"1px solid var(--ai-kit-chat-border-color)"},children:i.objectUrl?G(Je,{gap:"xs",children:[g("audio",{className:"ai-kit-audio-player",controls:!0,src:i.objectUrl,preload:"metadata"}),i.duration&&G(Ie,{size:"xs",c:"dimmed",style:{textAlign:"right"},children:[Math.round(i.duration),"s"]})]}):g(Ie,{size:"xs",c:"dimmed",children:f.get("Audio no longer available")})},i.id))]}),m&&G(Pe,{justify:"flex-end",gap:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:g("em",{children:f.get(p.notSentLabel)})}),Pt===e.id&&g(Ea,{size:"sm",variant:"subtle",onClick:()=>tr(e),title:f.get(p.editLabel),"aria-label":f.get(p.editLabel),"data-ai-kit-edit-button":!0,children:g(Lo,{size:14})})]}),e.citations&&e.citations.length>0&&G(Je,{className:"ai-citations",children:[g(Ie,{fw:"bold",size:"sm",mb:"xs",children:f.get(p.referencesLabel)}),g(Ba,{spacing:"xs",size:"sm",children:e.citations.map((i,T)=>{let y=i.sourceUrl||i.url,E=i.title||y||`${f.get(p.referenceLabel)} #${T+1}`;return G(Ba.Item,{children:[y?g(vo,{href:y,target:"_blank",rel:"noreferrer",children:E}):g(Ie,{children:E}),i.snippet?g(Ie,{size:"xs",c:"dimmed",mt:4,children:i.snippet}):null]},T)})})]}),e.role==="assistant"&&G(Pe,{className:"ai-feedback",gap:"xs",children:[g(Ye,{className:e.feedback==="accepted"?"active":void 0,onClick:()=>Fn(e.id,"accepted"),"aria-label":f.get(p.acceptResponseLabel),disabled:C.busy,"data-ai-kit-feedback-accept-button":!0,children:"\u{1F44D}"}),g(Ye,{type:"button",className:e.feedback==="rejected"?"active":void 0,onClick:()=>Fn(e.id,"rejected"),"aria-label":f.get(p.rejectResponseLabel),disabled:C.busy,"data-ai-kit-feedback-reject-button":!0,children:"\u{1F44E}"})]})]})},e.id)}),ar&&g(Pe,{justify:"flex-start",className:"ai-chat-row assistant status",children:G(Je,{className:"ai-chat-bubble typing",children:[Un?g(Ie,{size:"sm",c:"dimmed",children:g("em",{children:Un})}):null,G("div",{className:"typing-indicator",children:[g("span",{}),g("span",{}),g("span",{})]})]})})]}),rr&&g(Pe,{className:"ai-status-line",children:g(Ie,{className:"ai-status-text",children:g("em",{children:or})})}),G(Je,{className:"ai-box ai-box-open",children:[G(Ct,{opened:be,onClose:Hn,centered:!0,title:f.get("Reset conversation"),style:{position:"fixed"},left:0,children:[g(Ie,{size:"sm",children:f.get("Are you sure you want to reset the conversation?")}),G(Pe,{justify:"flex-end",mt:"md",children:[g(Ye,{variant:"default",onClick:Hn,"data-ai-kit-no-button":!0,children:f.get("No")}),g(Ye,{color:"var(--ai-kit-color-danger, red)",onClick:Za,disabled:!tt&&!oe,"data-ai-kit-yes-button":!0,children:f.get("Yes")})]})]}),g(Pe,{children:g(So,{className:"ai-message",ref:D,placeholder:qa,value:K,onChange:e=>{Ce(e.target.value),b&&se()},onKeyDown:Qa,rows:3,disabled:ie||!!b})}),Mn&&ie&&G(Je,{gap:"xs",mt:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:g("em",{children:f.get("Recording...")})}),g("div",{style:{width:"100%",height:"4px",backgroundColor:"var(--mantine-color-gray-3)",borderRadius:"2px",overflow:"hidden"},children:g("div",{style:{width:`${ot}%`,height:"100%",backgroundColor:"var(--mantine-color-red-6)",transition:"width 0.1s ease"}})})]}),Mn&&b&&!ie&&G(Je,{gap:"xs",mt:"xs",children:[g(Ie,{size:"xs",c:"dimmed",children:G("em",{children:[f.get("Audio recorded")," (",Math.round(b.duration),"s)"]})}),g("audio",{className:"ai-kit-audio-player",controls:!0,src:b.objectUrl})]}),G(Pe,{className:"ai-actions",justify:"space-between",w:"100%",children:[g(Pe,{justify:"flex-start",children:g(Ye,{variant:"light",leftSection:g(Do,{size:18}),onClick:$a,disabled:!tt&&!oe,"data-ai-kit-reset-button":!0,children:f.get(p.resetLabel)})}),G(Pe,{justify:"flex-end",children:[Mn&&g(Ua,{children:b?g(Ye,{variant:"outline",leftSection:g(Eo,{size:18}),onClick:se,disabled:oe,title:f.get("Clear audio"),"data-ai-kit-clear-audio-button":!0,children:f.get("Clear")}):g(Ye,{variant:"outline",leftSection:g(zo,{size:18}),onClick:ie?At:pe,disabled:oe,title:ie?f.get("Stop recording"):f.get("Record audio"),color:ie?"red":void 0,"data-ai-kit-microphone-button":!0,children:ie?f.get("Stop"):f.get("Record")})}),re>0&&G(Ua,{children:[g(Ye,{variant:"outline",leftSection:g(xo,{size:18}),onClick:()=>A.current?.click(),disabled:x.length>=re||oe||ie||!!b,title:f.get(p.addImageLabel),"data-ai-kit-add-image-button":!0,children:f.get(p.addLabel)}),g(To,{ref:A,type:"file",accept:"image/png,image/jpeg,image/gif,image/webp",style:{display:"none"},multiple:!0,onChange:Ja})]}),g(Ye,{leftSection:sr,variant:"filled",onClick:lr,disabled:!oe&&!pn,"data-ai-kit-send-button":!0,children:ir})]})]}),Kn.length>0&&g(Pe,{className:"ai-thumbs",mt:"xs",gap:"xs",children:Kn.map(({url:e,title:l},m)=>g("div",{role:"button",tabIndex:0,className:"thumb",style:{backgroundImage:e?`url(${e})`:void 0,backgroundSize:"cover",backgroundPosition:"center",backgroundRepeat:"no-repeat",overflow:"visible"},"aria-label":l||f.get("View image"),onClick:()=>hn(e,l),onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),hn(e,l))},children:g(Ye,{variant:"white",onClick:i=>{i.stopPropagation(),Va(m)},"aria-label":f.get(p.removeImageLabel),mt:"-xs",mr:"-xs",size:"xs",p:0,className:"remove-image-button",title:f.get(p.removeImageLabel),"data-ai-kit-remove-image-button":!0,children:"X"})},x[m]?.id??m))})]})]})}),g(Ct,{opened:!!ye,onClose:_a,centered:!0,size:"auto",title:ye?.title||f.get("Image preview"),children:ye&&g("img",{src:ye.url,alt:ye.title||f.get("Image preview"),style:{maxWidth:"100%",maxHeight:"70vh"}})})]})},Vo=Rt(Jo,{showOpenButton:!0,variation:"modal"});import{Alert as _o,Anchor as Na,Button as $t,Divider as ja,Group as Gt,Loader as $o,Modal as xt,Paper as Ga,Progress as Zo,Stack as Lt,Text as at,TextInput as Qo,Title as Xo}from"@mantine/core";import{AiKitDocSearchIcon as ei,sendSearchMessage as ti}from"@smart-cloud/ai-kit-core";import{I18n as de}from"aws-amplify/utils";import{useCallback as Ht,useEffect as mn,useMemo as rt,useRef as Mt,useState as Zt}from"react";import ni from"react-markdown";import ai from"rehype-raw";import ri from"remark-gfm";import{IconSearch as Ha}from"@tabler/icons-react";import{IconMicrophone as oi,IconMicrophoneOff as ii}from"@tabler/icons-react";import{Fragment as Qt,jsx as z,jsxs as ze}from"react/jsx-runtime";de.putVocabularies(wt);var Wa=!1;function si(t){let r=t?.citations?.docs??[],c=t?.citations?.chunks??[],s=new Map;for(let a of r)s.set(a.docId,{doc:a,chunks:[]});for(let a of c){let d=s.get(a.docId);d?d.chunks.push(a):s.set(a.docId,{doc:{docId:a.docId},chunks:[a]})}return Array.from(s.values())}var li=t=>{let{autoRun:r=!0,context:c,title:s,searchButtonIcon:a,showSearchButtonTitle:d=!0,showSearchButtonIcon:w=!0,showSources:B=!0,topK:$=10,getSearchText:Z,variation:L,rootElement:Q,colorMode:Ke,language:_,onClose:R,onClickDoc:u,showOpenButton:S=!1,openButtonTitle:ke,openButtonIcon:Ue,showOpenButtonTitle:q=!0,showOpenButtonIcon:ce=!0}=t,[p,C]=Zt(""),[K,Ce]=Zt(!S),[x,we]=Zt(!1),[b,X]=Zt(null),[ie,Ze]=Zt(0),ot=Mt(null),je=Mt([]),We=Mt(null),Fe=Mt(null),xe=Mt(null),De=Mt(null),P=1440*60*1e3,{busy:I,error:ge,statusEvent:Ve,result:ee,run:be,cancel:kt,reset:Te}=Kt(),Oe=Mt(!1),_e=ee?.sessionId,Qe=ee?.citations?.docs??[],te=ee?.citations?.chunks??[],Xe=ee?.citations?.anchors??[],M=ee?.result??"",it=rt(()=>{if(w)return a?.trim()?z("img",{src:a,alt:"",style:{width:18,height:18,objectFit:"contain"}}):z(Ha,{size:18})},[a,w]),ye=rt(()=>(_&&de.setLanguage(_||"en"),de.get(s||"Search with AI-Kit")),[_]),bt=Ht(A=>z(Ha,{className:A,size:18}),[]),Ge=rt(()=>Ve?de.get("Searching\u2026"):null,[_,Ve]),Ee=rt(()=>p||Z,[p,Z]),me=rt(()=>{if(I)return!1;let A=typeof Ee=="function"?Ee():Ee;return!!(A&&A.trim().length>0||b)},[Ee,I,b]),Wt=Ht(async()=>{try{C("");let A=await navigator.mediaDevices.getUserMedia({audio:!0}),D=new MediaRecorder(A,{mimeType:"audio/webm"}),H=new AudioContext,Ae=H.createMediaStreamSource(A),U=H.createAnalyser();U.fftSize=2048,U.smoothingTimeConstant=.8,Ae.connect(U),We.current=H,Fe.current=U;let ne=new Uint8Array(U.fftSize),se=()=>{if(!Fe.current)return;Fe.current.getByteTimeDomainData(ne);let pe=0;for(let o=0;o<ne.length;o++){let k=(ne[o]-128)/128;pe+=k*k}let At=Math.sqrt(pe/ne.length),ut=Math.min(100,At*200);Ze(ut),xe.current=requestAnimationFrame(se)};se(),je.current=[],D.ondataavailable=pe=>{pe.data.size>0&&je.current.push(pe.data)},D.onstop=()=>{let pe=new Blob(je.current,{type:"audio/webm"});X(pe),A.getTracks().forEach(At=>At.stop()),xe.current&&(cancelAnimationFrame(xe.current),xe.current=null),We.current&&(We.current.close(),We.current=null),Fe.current=null,Ze(0)},ot.current=D,D.start(),we(!0)}catch(A){console.error("Failed to start recording:",A)}},[]),J=Ht(()=>{ot.current&&x&&(ot.current.stop(),we(!1))},[x]),yt=Ht(()=>{X(null),je.current=[],Ze(0),De.current=null},[]);mn(()=>()=>{xe.current&&cancelAnimationFrame(xe.current),We.current&&We.current.close()},[]);let st=Ht(async()=>{let A;if(!b){if(A=typeof Ee=="function"?Ee():Ee,!A)return;C(A)}console.log("Starting search with query:",A,"and audio:",b);let D=Date.now(),H=b&&De.current?.blob===b&&D-De.current.uploadTimestamp<P;b&&!H?(De.current={blob:b,uploadTimestamp:D},console.log("Audio cache updated for new recording")):H&&console.log("Reusing cached audio (no re-upload needed within",Math.round((P-(D-De.current.uploadTimestamp))/1e3),"seconds)"),Te(),await be(async({signal:Ae,onStatus:U})=>await ti({sessionId:_e,...A&&{query:A},...b&&{audio:b},topK:$},{signal:Ae,onStatus:U,context:c}))},[c,Ee,b,be,Te,$,_e]),He=Ht(async()=>{Ce(!1),Te(),Oe.current=!1,S||R()},[R,Te,Oe,S]);mn(()=>{!r||!me||I||Oe.current||(Oe.current=!0,queueMicrotask(()=>{st()}))},[I,Oe,me,r,st]),mn(()=>{me||(Oe.current=!0)},[me]);let Se=rt(()=>si(ee),[ee]),v=rt(()=>{let A=new Map;return Qe.forEach((D,H)=>{D?.docId&&A.set(D.docId,H+1)}),A},[Qe]),lt=rt(()=>{let A=new Map;return te.forEach(D=>{D?.chunkId&&D?.docId&&A.set(D.chunkId,D.docId)}),A},[te]),Le=rt(()=>{if(!M)return"";if(!Xe.length||v.size===0)return M;let A=[...Xe].filter(Ae=>Array.isArray(Ae?.chunkIds)&&Ae?.span?.end!==void 0).sort((Ae,U)=>{let ne=Ae.span?.end??0,se=U.span?.end??0;return ne-se}),D=0,H=[];for(let Ae of A){let U=Ae.span?.end;if(typeof U!="number"||U<D)continue;let ne=Array.from(new Set((Ae.chunkIds??[]).map(pe=>pe?lt.get(pe):void 0).map(pe=>pe?v.get(pe):void 0).filter(pe=>typeof pe=="number")));if(!ne.length)continue;let se=Math.min(U,M.length);H.push(M.slice(D,se)),H.push(`<sup>${ne.join(",")}</sup>`),D=se}return H.push(M.slice(D)),H.join("")},[Xe,M]),et=L==="modal"?xt.Root:Gt,Pt=L==="modal"?xt.Content:Gt,Dt=L==="modal"?xt.Body:Gt;return mn(()=>{if(!(L!=="modal"||!K))return document.body.style.overflow="hidden",document.body.onkeydown=A=>{A.key==="Escape"&&(A.preventDefault(),He())},()=>{document.body.style.overflow="",document.body.onkeydown=null}},[He,L]),ze(Qt,{children:[S&&z($t,{leftSection:ce&&(Ue?z("span",{dangerouslySetInnerHTML:{__html:Ue}}):bt()),className:q?"doc-search-button":"doc-search-button-no-title",variant:"filled",disabled:K,onClick:()=>Ce(!0),"data-ai-kit-open-button":!0,children:q&&de.get(ke||ye)}),K&&ze(et,{opened:!0,className:"doc-search-root",onClose:He,padding:"md",gap:"md",size:"xl",portalProps:L==="modal"?{target:Q,reuseTargetNode:!0}:void 0,"data-ai-kit-theme":Ke,"data-ai-kit-variation":L,children:[L==="modal"&&z(xt.Overlay,{}),ze(Pt,{w:"100%",style:{left:0},children:[L==="modal"&&ze(xt.Header,{style:{zIndex:1e3},children:[z(ei,{className:"doc-search-title-icon"}),z(xt.Title,{children:de.get(ye)}),z(xt.CloseButton,{})]}),z(Dt,{w:"100%",style:{zIndex:1001},children:z(Ut,{enabled:L!=="modal",working:I,variation:L,children:z(Ga,{shadow:"sm",radius:"md",p:"md",children:ze(Lt,{gap:"sm",children:[L!=="modal"&&z(Xo,{order:4,style:{margin:0},children:de.get(ye)}),ze(Gt,{gap:"sm",align:"flex-end",wrap:"nowrap",children:[z(Qo,{style:{flex:1},value:p,onChange:A=>{C(A.currentTarget.value),b&&yt()},placeholder:b?de.get("Audio recorded"):de.get("Search the documentation\u2026"),disabled:I||x||!!b,onKeyDown:A=>{A.key==="Enter"&&me&&(A.preventDefault(),st())}}),Wa&&z(Qt,{children:b?z($t,{variant:"outline",size:"sm",color:"red",onClick:yt,disabled:I,title:de.get("Clear audio"),children:z(ii,{size:18})}):z($t,{variant:x?"filled":"outline",size:"sm",color:x?"red":"gray",onClick:x?J:Wt,disabled:I,title:x?de.get("Stop recording"):de.get("Record audio"),style:x?{transform:`scale(${1+ie/300})`,transition:"transform 0.1s ease-out"}:void 0,children:z(oi,{size:18})})}),z($t,{variant:"filled",size:"sm",leftSection:it,onClick:()=>{st()},disabled:!me,className:d?"doc-search-button":"doc-search-button-no-title",children:d?de.get("Search"):null}),I?z($t,{variant:"outline",size:"sm",onClick:kt,children:de.get("Stop")}):null]}),Wa&&ze(Qt,{children:[x&&ze(Lt,{gap:"xs",children:[ze(at,{size:"xs",c:"dimmed",children:[de.get("Recording...")," \u{1F3A4}"]}),z(Zo,{value:ie,size:"sm",color:"red",animated:!0,striped:!0})]}),b&&!x&&ze(Lt,{gap:"xs",children:[z(at,{size:"xs",c:"dimmed",children:de.get("Recorded audio:")}),z("audio",{controls:!0,src:URL.createObjectURL(b),className:"ai-kit-audio-player"})]})]}),ge?z(_o,{color:"red",title:de.get("Error"),children:ge}):null,I&&Ge&&z(Ut,{enabled:L==="modal",working:!0,variation:L,children:ze(Gt,{justify:"center",align:"center",gap:"sm",m:"sm",pr:"lg",children:[z($o,{size:"sm"}),z(at,{size:"sm",c:"dimmed",children:Ge})]})}),ee?.result?ze(Qt,{children:[z(ja,{}),ze(Lt,{gap:"xs","data-doc-search-result":!0,children:[z(at,{size:"sm",c:"dimmed","data-doc-search-result-title":!0,children:de.get("AI Summary")}),z(ni,{remarkPlugins:[ri],rehypePlugins:[ai],"data-doc-search-result-content":!0,children:Le||M})]})]}):null,B&&(ee?.citations?.docs?.length||ee?.citations?.chunks?.length)?ze(Qt,{children:[z(ja,{}),ze(Lt,{gap:"sm","data-doc-search-sources":!0,children:[z(at,{size:"sm",c:"dimmed","data-doc-search-sources-title":!0,children:de.get("Sources")}),Se.map(({doc:A})=>{let D=A.sourceUrl?.trim()||void 0,H=A.docId?v.get(A.docId):void 0,Ae=A.title?.trim()||A.docId,U=ze(at,{fw:600,style:{display:"inline"},children:[H?`${H}. `:"",Ae]});return z(Ga,{withBorder:!0,radius:"md",p:"sm",children:z(Lt,{gap:"xs",children:z(Gt,{justify:"space-between",align:"flex-start",children:ze(Lt,{gap:2,style:{flex:1},"data-doc-search-source":!0,children:[D?z(Na,{href:D,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:ne=>{u&&(ne.preventDefault(),u?.(A))},"data-doc-search-source-title":!0,children:U}):U,z(Na,{href:D,target:"_blank",rel:"noreferrer",style:{textDecoration:"none"},onClick:ne=>{u&&(ne.preventDefault(),u?.(A))},"data-doc-search-source-url":!0,children:A.sourceUrl}),A.author?z(at,{size:"xs",c:"dimmed","data-doc-search-source-author":!0,children:A.author}):null,A.description?z(at,{size:"sm",c:"dimmed",fs:"italic","data-doc-search-source-description":!0,children:A.description}):null]})})})},A.docId)})]})]}):null,!I&&!ge&&!ee?.result?z(at,{size:"sm",c:"dimmed","data-doc-search-no-results":!0,children:de.get("Enter a search query to start.")}):null,z(nn,{variation:L})]})})})})]})]})]})},ui=Rt(li);export{Vo as AiChatbot,po as AiFeature,Dn as DEFAULT_CHATBOT_LABELS,ui as DocSearch,ka as isBackendConfigured,wn as markdownToHtml,Tt as readDefaultOutputLanguage,Yt as stripCodeFence,wt as translations,Kt as useAiRun,Rt as withAiKitShell};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@smart-cloud/ai-kit-ui",
3
- "version": "1.3.4",
3
+ "version": "1.3.5",
4
4
  "type": "module",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -459,8 +459,8 @@ const DocSearchBase: FC<Props> = (props) => {
459
459
  }
460
460
  className={
461
461
  showOpenButtonTitle
462
- ? "doc-search-open-button"
463
- : "doc-search-open-button-no-title"
462
+ ? "doc-search-button"
463
+ : "doc-search-button-no-title"
464
464
  }
465
465
  variant={"filled"}
466
466
  disabled={featureOpen}