@akropolys/kiku 2.2.7 → 2.2.8
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/embed/{chunk-NMSSMVCV.js → chunk-KGBXPSPU.js} +1 -1
- package/dist/embed/embed.js +2 -2
- package/dist/embed/lazy-5HGOS5YA.js +37 -0
- package/dist/embed/meta.json +1 -1
- package/dist/index.js +6 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/lazy-6WK6YN3R.mjs +39 -0
- package/dist/lazy-6WK6YN3R.mjs.map +1 -0
- package/package.json +2 -2
- package/dist/embed/lazy-N6PCCAZX.js +0 -37
- package/dist/lazy-DRTULDRZ.mjs +0 -39
- package/dist/lazy-DRTULDRZ.mjs.map +0 -1
|
@@ -9,7 +9,7 @@ var En=Object.create;var gt=Object.defineProperty;var Rn=Object.getOwnPropertyDe
|
|
|
9
9
|
|
|
10
10
|
`),L=i.lastIndexOf(`\r
|
|
11
11
|
\r
|
|
12
|
-
`),M=Math.max(_,L);if(M===-1)continue;let k=M===L?4:2;y=i.slice(0,M+k),i=i.slice(M+k)}let A=Un(y);for(let{event:_,data:L}of A){if(this.aborted)return;if(_==="meta"){try{let k=JSON.parse(L);this.emit("meta",k)}catch{}continue}if(_==="entity_ref"){try{let k=JSON.parse(L);this.emit("entity_ref",k)}catch{}continue}if(_==="live_ref"){try{let k=JSON.parse(L);k&&typeof k.key=="string"&&k.key&&this.emit("live_ref",k)}catch{}continue}if(_==="knowledge_images"){try{let k=JSON.parse(L);Array.isArray(k?.refs)&&k.refs.length>0&&this.emit("knowledge_images",k.refs)}catch{}continue}if(_==="stale_notice"){try{let k=JSON.parse(L);Array.isArray(k?.items)&&k.items.length>0&&this.emit("stale_notice",k.items)}catch{}continue}if(_==="thinking"){try{let{text:k}=JSON.parse(L);k&&this.emit("thinking",k)}catch{}continue}if(_==="status"){try{let k=JSON.parse(L);this.emit("status",k)}catch{}continue}if(_==="viz"){try{let k=JSON.parse(L);this.emit("viz",k)}catch{}continue}if(_==="done"){u=!0;break}if(_==="error"){let k="Stream error",N;try{let j=JSON.parse(L);k=j.error??k,N=j.code}catch{k=L}let F=new Error(k);throw N&&(F.code=N),F}if(_)continue;let M=L;a+=M,this.emit("token",M)}if(u)break}this.aborted||(e=!0,n=a)}finally{try{s.cancel().catch(()=>{})}catch{}this.abortController.abort()}}catch(r){this.aborted||this.emit("error",r)}e&&!this.aborted&&this.emit("done",n)}};var kt=new Set;function St(t){let e,n,r=typeof location<"u"?location.href:"",s=typeof history<"u"?history.pushState.bind(history):null,o=typeof history<"u"?history.replaceState.bind(history):null,i=()=>{if(typeof window>"u"||typeof document>"u")return;let A=location.href;if(kt.has(A))return;kt.add(A);let _=document.querySelector("main")??document.querySelector("article")??document.querySelector('[role="main"]')??document.querySelector("#content")??document.querySelector(".entry-content")??document.querySelector("#main")??document.body;if(!_)return;let L=_.cloneNode(!0);["nav","header","footer","script","style","noscript","iframe",'[role="navigation"]','[role="banner"]','[role="contentinfo"]','[aria-hidden="true"]',"template",".hidden",'[style*="display:none"]','[style*="display: none"]'].forEach(j=>{L.querySelectorAll(j).forEach(Oe=>Oe.remove())});let k=L.textContent?.replace(/\s+/g," ").trim()??"";if(!k||k.length<50)return;let N=12e4,F=k.length>N?k.slice(0,N):k;t.queueContentIngest({url:A,title:document.title,text:F,capturedAt:Date.now()})},a=()=>{clearTimeout(e),e=setTimeout(()=>{clearTimeout(n),i()},1e3)},u=()=>{clearTimeout(n),n=setTimeout(()=>{clearTimeout(e),i()},4e3)},c=null,h=()=>{typeof window>"u"||typeof document>"u"||typeof MutationObserver>"u"||(c=new MutationObserver(()=>{a()}),c.observe(document.body,{childList:!0,subtree:!0}))},b=()=>{typeof location>"u"||location.href!==r&&(r=location.href,a(),u())};typeof window<"u"&&(window.addEventListener("popstate",b),history&&s&&(history.pushState=(...A)=>{s(...A),b()}),history&&o&&(history.replaceState=(...A)=>{o(...A),b()}),"requestIdleCallback"in window?requestIdleCallback(()=>{i(),h()},{timeout:3e3}):setTimeout(()=>{i(),h()},1e3));let y=()=>{c&&c.disconnect(),clearTimeout(e),clearTimeout(n),typeof window<"u"&&(window.removeEventListener("popstate",b),history&&s&&(history.pushState=s),history&&o&&(history.replaceState=o))};return t.contentIndexerCleanup=y,y}function re(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(re).join(",")+"]":"{"+Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${re(t[r])}`).join(",")+"}"}function ie(t){if(t==="NEXT_PUBLIC_AKROPOLYS_SITE_ID")try{return process.env.NEXT_PUBLIC_AKROPOLYS_SITE_ID}catch{}if(t==="NEXT_PUBLIC_AKROPOLYS_API_URL")try{return process.env.NEXT_PUBLIC_AKROPOLYS_API_URL}catch{}if(t==="NEXT_PUBLIC_AKROPOLYS_API_TOKEN")try{return process.env.NEXT_PUBLIC_AKROPOLYS_API_TOKEN||process.env.NEXT_PUBLIC_AKROPOLYS_API_KEY}catch{}try{let e=import.meta.env;if(e){if(t==="NEXT_PUBLIC_AKROPOLYS_SITE_ID")return e.NEXT_PUBLIC_AKROPOLYS_SITE_ID||e.VITE_AKROPOLYS_SITE_ID;if(t==="NEXT_PUBLIC_AKROPOLYS_API_URL")return e.NEXT_PUBLIC_AKROPOLYS_API_URL||e.VITE_AKROPOLYS_API_URL;if(t==="NEXT_PUBLIC_AKROPOLYS_API_TOKEN")return e.NEXT_PUBLIC_AKROPOLYS_API_TOKEN||e.VITE_AKROPOLYS_API_TOKEN}}catch{}if(typeof globalThis<"u"){let e=globalThis;if(e.process&&e.process.env){let n=e.process.env[t];if(n!==void 0)return n}}}function wt(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let t=new Error("Aborted");return t.name="AbortError",t}function we(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function On(t,e){let n=[];for(let r of e){let s=t[r];s==null||s===""||typeof s=="object"||n.push({label:r.replace(/[_-]+/g," "),value:String(s)})}return n}function He(t,e=[]){let n=["title","name","label","headline","subject","job_title","listing_title","common_name"],r="";if(!r){for(let a of n)if(typeof t[a]=="string"&&t[a].trim()!==""){r=t[a];break}}r||(r=Object.values(t).find(u=>typeof u=="string"&&u.length>=2&&u.length<=80&&!u.startsWith("http://")&&!u.startsWith("https://"))||"Untitled");let s=["image","images","thumbnail","photo","cover","featured_image"],o;if(!o)for(let a of s){let u=t[a];if(typeof u=="string"&&u.startsWith("http")){o=u;break}else if(Array.isArray(u)&&typeof u[0]=="string"&&u[0].startsWith("http")){o=u[0];break}}let i=ue(t.images,o);return{title:r,image:o||i[0]?.url,images:i,details:On(t,e)}}var $=class ${constructor(e){this.entities={query:async(e,n)=>{let r=n?.signal;if(r?.aborted)throw wt();let s=this.chat(e.q);return new Promise((o,i)=>{let a=()=>{s.destroy(),u(()=>i(wt()))},u=c=>{r?.removeEventListener("abort",a),c()};r?.addEventListener("abort",a,{once:!0}),s.on("token",c=>{n?.onToken?.(c)}),s.on("error",c=>u(()=>i(c))),s.on("done",()=>u(()=>o()))})}};this.allowance=(e,n)=>this.api.allowance(e,n);this.ingestQueue=[];this.ingestTimer=null;this.ingestedUrls=new Map;this.onlineHandler=null;this.sessionId="";this.deviceId="";this.kikuPub=null;this.kikuKey=null;this.shopperName=null;this.contextProviders=[];this.isFlushing=!1;this.retryCount=0;this.contentQueue=[];this.contentIngestTimer=null;this.isContentFlushing=!1;this.contentRetryCount=0;this.contentIndexerCleanup=null;this.lastIngestedItem=null;this.shopperLanguage=null;this.entityLanguageMode=null;let n=e.siteId||ie("NEXT_PUBLIC_AKROPOLYS_SITE_ID")||"",r=e.apiUrl||ie("NEXT_PUBLIC_AKROPOLYS_API_URL")||$.DEFAULT_API_URL,s=e.apiToken||ie("NEXT_PUBLIC_AKROPOLYS_API_TOKEN")||"";this.voiceUrl=e.voiceUrl||ie("NEXT_PUBLIC_AKROPOLYS_VOICE_URL")||$.DEFAULT_VOICE_URL,n||console.error("[Akropolys] Missing siteId \u2014 pass <AkropolysProvider siteId=\u2026> or set NEXT_PUBLIC_AKROPOLYS_SITE_ID."),s||console.error("[Akropolys] Missing apiToken \u2014 pass <AkropolysProvider apiToken=\u2026> or set NEXT_PUBLIC_AKROPOLYS_API_TOKEN."),this.shopperId=e.shopperId,this.userProof=e.userProof,this.authLoading=e.authLoading,this.onAction=e.onAction,this.onAddToCart=e.onAddToCart,this.getCart=e.getCart,this.onError=e.onError,e.kikuKey&&(this.kikuKey=e.kikuKey),this.initSession(),this.initDevice(),this.initKikuKey(),this.initShopperName(),this.initShopperLanguage(),this.initEntityLanguageMode(),this.loadIngestedCache(),this.api=new ke(r,n,s,()=>this.getShopperId(),()=>this.sessionId,()=>this.deviceId,()=>this.kikuPub??void 0,()=>this.shopperName??void 0,()=>{try{return this.getCart?.()}catch{return}},()=>this.shopperLanguage??void 0,()=>this.entityLanguageMode??void 0,()=>this.kikuKey??void 0),this.api.userProof=e.userProof,Te(this),typeof window<"u"&&(this.onlineHandler=()=>{console.debug("[Akropolys] Connectivity restored, flushing queued ingestions."),this.flushQueue(),this.flushContentQueue()},window.addEventListener("online",this.onlineHandler)),e.indexContent&&St(this)}get apiUrl(){return this.api.apiUrl}loadIngestedCache(){if(!(typeof window>"u"))try{let e=localStorage.getItem($.INGEST_CACHE_KEY);if(!e)return;let{ts:n,urlFingerprints:r}=JSON.parse(e);if(Date.now()-n>$.INGEST_CACHE_TTL){localStorage.removeItem($.INGEST_CACHE_KEY);return}this.ingestedUrls=new Map(r)}catch{}}saveIngestedCache(){if(!(typeof window>"u"))try{localStorage.setItem($.INGEST_CACHE_KEY,JSON.stringify({ts:Date.now(),urlFingerprints:Array.from(this.ingestedUrls.entries())}))}catch{}}registerContextProvider(e){return this.contextProviders.push(e),()=>{this.contextProviders=this.contextProviders.filter(n=>n!==e)}}async getCurrentContextAsync(e){let n=this.getCurrentContext();if(this.contextProviders.length===0)return n??{};let r=await Promise.all(this.contextProviders.map(i=>Promise.race([i(e),new Promise((a,u)=>setTimeout(()=>u(new Error("timeout")),3e3))]).catch(a=>(console.warn("[Akropolys] Live context provider failed:",a?.message??a),{})))),s=Object.assign({},...r),o=n??{};return{...o,raw:{...o.raw??{},...s}}}getCurrentContext(){if(typeof window>"u")return null;let e={url:window.location.href,title:document.title,raw:{}};if(this.lastIngestedItem){let n=this.lastIngestedItem.url;if(n)try{let r=new URL(n,window.location.origin);r.pathname===window.location.pathname&&(e.raw=this.lastIngestedItem,e.url=r.href,(this.lastIngestedItem.name||this.lastIngestedItem.title)&&(e.title=this.lastIngestedItem.name||this.lastIngestedItem.title))}catch{if(window.location.href.endsWith(n)||n.endsWith(window.location.pathname)){e.raw=this.lastIngestedItem;try{e.url=new URL(n,window.location.origin).href}catch{e.url=n}(this.lastIngestedItem.name||this.lastIngestedItem.title)&&(e.title=this.lastIngestedItem.name||this.lastIngestedItem.title)}}}return e}chat(e,n=[],r,s,o){let i=new AbortController,a=performance.now(),u=[],c=A=>u.push(`${A}=${Math.round(performance.now()-a)}ms`),h=this.getCurrentContextAsync(i.signal).then(A=>(c("context"),this.api.chatStream(e,n,i.signal,A,r,s,o))).then(A=>(c("headers"),A)),b=new Se(h,i),y=!1;return b.on("token",()=>{y||(y=!0,c("first_text"))}),b.on("done",()=>{c("done"),console.info(`[kiku timing] ${u.join(" ")}`)}),b.on("meta",A=>{A&&typeof A.language=="string"&&A.language&&this.setShopperLanguage(A.language)}),b}reRegister(){Te(this),typeof window<"u"&&!this.onlineHandler&&(this.onlineHandler=()=>{this.flushQueue(),this.flushContentQueue()},window.addEventListener("online",this.onlineHandler))}updateConfig(e){e.apiUrl&&(this.api.apiUrl=e.apiUrl),e.siteId&&(this.api.siteId=e.siteId),e.apiToken&&(this.api.apiToken=e.apiToken),e.voiceUrl!==void 0&&(this.voiceUrl=e.voiceUrl)}setUserProof(e){this.userProof=e,this.api.userProof=e}getUserProof(){return this.userProof}setShopperId(e){this.shopperId=e,this.authLoading||(this.flushQueue(),this.flushContentQueue())}setAuthLoading(e){let n=this.authLoading;this.authLoading=e,n&&!e&&(this.flushQueue(),this.flushContentQueue())}getShopperId(){return this.shopperId||"guest_"+this.sessionId}getSessionId(){return this.sessionId}initSession(){if(typeof window<"u"&&window.sessionStorage)try{let e=window.sessionStorage.getItem("akropolys_session_id");e||(e=we(),window.sessionStorage.setItem("akropolys_session_id",e)),this.sessionId=e;return}catch{}this.sessionId=we()}initDevice(){if(typeof window>"u"){this.deviceId=we();return}try{let e=localStorage.getItem("akropolys_device_id");e||(e=we(),localStorage.setItem("akropolys_device_id",e)),this.deviceId=e}catch{this.deviceId=we()}}getDeviceId(){return this.deviceId}async mintKikuKey(){let e=await this.api.mintKikuKey();return e.secret&&this.setKikuKey(e.secret),e.publicId&&this.setKikuPub(e.publicId),e}initKikuKey(){if(!(typeof window>"u"))try{if(!this.kikuKey){let s=localStorage.getItem("akropolys_kiku_key")||localStorage.getItem("kiku_key")||sessionStorage.getItem("akropolys_kiku_key");s&&(this.kikuKey=s)}let e=sessionStorage.getItem("akropolys_kiku_pub")||sessionStorage.getItem("kiku_pub");if(e){this.kikuPub=e;return}let n=localStorage.getItem("akropolys_kiku_pub")||localStorage.getItem("kiku_pub")||localStorage.getItem("kiku_id");if(n){this.kikuPub=n;return}let r=document.cookie.match(/(?:^|;\s*)(?:akropolys_kiku_pub|kiku_pub|kiku_id)=([^;]+)/);if(r){this.kikuPub=decodeURIComponent(r[1]);return}}catch{}}getKikuPub(){return this.kikuPub??void 0}getKikuKey(){return this.kikuKey??void 0}setKikuKey(e){if(this.kikuKey=e,!(typeof window>"u"))try{e?(localStorage.setItem("akropolys_kiku_key",e),sessionStorage.setItem("akropolys_kiku_key",e)):(localStorage.removeItem("akropolys_kiku_key"),sessionStorage.removeItem("akropolys_kiku_key"))}catch{}}initShopperName(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_shopper_name");e&&(this.shopperName=e)}catch{}}getShopperName(){return this.shopperName??void 0}setShopperName(e){let n=(e||"").trim().slice(0,40);if(n&&(this.shopperName=n,!(typeof window>"u")))try{localStorage.setItem("akropolys_shopper_name",n)}catch{}}clearShopperName(){if(this.shopperName=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_shopper_name")}catch{}}initShopperLanguage(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_shopper_language");e&&(this.shopperLanguage=e)}catch{}}getShopperLanguage(){return this.shopperLanguage??void 0}setShopperLanguage(e){let n=(e||"").trim().slice(0,40);if(n&&(this.shopperLanguage=n,!(typeof window>"u")))try{localStorage.setItem("akropolys_shopper_language",n)}catch{}}clearShopperLanguage(){if(this.shopperLanguage=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_shopper_language")}catch{}}initEntityLanguageMode(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_entity_language");(e==="original"||e==="translated")&&(this.entityLanguageMode=e)}catch{}}getEntityLanguageMode(){return this.entityLanguageMode??void 0}setEntityLanguageMode(e){if(!(e!=="original"&&e!=="translated")&&(this.entityLanguageMode=e,!(typeof window>"u")))try{localStorage.setItem("akropolys_entity_language",e)}catch{}}clearEntityLanguageMode(){if(this.entityLanguageMode=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_entity_language")}catch{}}getEntityPreview(e){return this.api.entityPreview(e)}storeScene(e){return this.api.storeScene(e)}baseFont(){return this.api.baseFont()}synthesizeSpeech(e,n,r,s){return this.api.synthesizeSpeech(e,n,r??this.getShopperLanguage(),s)}getCachedUIStrings(e,n){if(typeof window>"u"||!e)return null;let r=$.hashStrings(n),s=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_${e.toLowerCase().trim()}_${r}`;try{let o=localStorage.getItem(s);if(o){let i=JSON.parse(o);if(i?.strings&&Object.keys(i.strings).length>0)return{strings:i.strings,complete:!0,dir:i.dir==="rtl"?"rtl":"ltr",bcp47:typeof i.bcp47=="string"?i.bcp47:"",font:i.font?.family&&i.font?.faces?.length?i.font:null}}}catch{}return null}async getUIStrings(e,n){let r=$.hashStrings(n),s=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_${e.toLowerCase().trim()}_${r}`,o=this.getCachedUIStrings(e,n);if(o)return o;let i={strings:{},complete:!1,dir:"ltr",bcp47:"",font:null};if(typeof window<"u")try{let c=localStorage.getItem(s);if(c){let h=JSON.parse(c);if(h?.strings&&Object.keys(h.strings).length>0)return{strings:h.strings,complete:!0,dir:h.dir==="rtl"?"rtl":"ltr",bcp47:typeof h.bcp47=="string"?h.bcp47:"",font:h.font?.family&&h.font?.faces?.length?h.font:null};localStorage.removeItem(s)}}catch{}let a=await this.api.uiStrings(e,n);if(a?.complete||(a=await this.api.uiStrings(e,n)),!a?.complete||Object.keys(a.strings).length===0)return i;let u=a.strings;if(typeof window<"u")try{let c="akropolys_ui_strings_",h=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_`;for(let b=localStorage.length-1;b>=0;b--){let y=localStorage.key(b);y&&y.startsWith(c)&&!y.startsWith(h)&&localStorage.removeItem(y)}localStorage.setItem(s,JSON.stringify({strings:u,dir:a.dir,bcp47:a.bcp47,font:a.font}))}catch{}return a}static hashStrings(e){let n=Object.keys(e).sort().map(s=>`${s}${e[s]}`).join(""),r=5381;for(let s=0;s<n.length;s++)r=(r*33^n.charCodeAt(s))>>>0;return r.toString(36)}setKikuPub(e){let n=(e||"").trim();if(n&&(this.kikuPub=n,!(typeof window>"u"))){try{sessionStorage.setItem("akropolys_kiku_pub",n)}catch{}try{localStorage.setItem("akropolys_kiku_pub",n)}catch{}try{document.cookie=`akropolys_kiku_pub=${encodeURIComponent(n)};path=/;max-age=31536000;SameSite=Lax`}catch{}}}hasKikuKey(){return!!this.kikuPub}clearKikuKey(){if(this.kikuPub=null,!(typeof window>"u")){try{sessionStorage.removeItem("akropolys_kiku_pub")}catch{}try{sessionStorage.removeItem("kiku_pub")}catch{}try{localStorage.removeItem("akropolys_kiku_pub")}catch{}try{localStorage.removeItem("kiku_pub")}catch{}try{localStorage.removeItem("kiku_id")}catch{}try{localStorage.removeItem("akropolys_kiku_key")}catch{}try{document.cookie="akropolys_kiku_pub=;path=/;max-age=0"}catch{}}}destroy(){this.contextProviders=[],typeof window<"u"&&this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.ingestTimer&&(clearTimeout(this.ingestTimer),this.ingestTimer=null),this.contentIngestTimer&&(clearTimeout(this.contentIngestTimer),this.contentIngestTimer=null),this.contentIndexerCleanup&&(this.contentIndexerCleanup(),this.contentIndexerCleanup=null),bt()===this&&Te(null)}async queueIngest(e){return this.ingest(e)}async queueIngestBatch(e){return this.ingestMany(e)}async ingest(e){this.lastIngestedItem=e;let n=e.envelope?.entity||e,r=n.id??n.productId??n.slug??n.url??n.name??"",s=n.url||(typeof window<"u"?window.location.href:"");if(!r&&!s){console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");return}let o=re(e);if(s){if(this.ingestedUrls.get(s)===o)return;this.ingestedUrls.set(s,o),this.saveIngestedCache()}this.ingestQueue.push(e),this.scheduleFlush()}async ingestMany(e){e.length>0&&(this.lastIngestedItem=e[e.length-1]);let n=!1;e.forEach(r=>{let s=r.envelope?.entity||r,o=s.id??s.productId??s.slug??s.url??s.name??"",i=s.url||(typeof window<"u"?window.location.href:"");if(!o&&!i){console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");return}let a=re(r);if(i){if(this.ingestedUrls.get(i)===a)return;this.ingestedUrls.set(i,a),n=!0}this.ingestQueue.push(r)}),n&&this.saveIngestedCache(),this.ingestQueue.length>0&&this.scheduleFlush()}scheduleFlush(){this.ingestTimer||this.isFlushing||(this.ingestTimer=setTimeout(()=>{this.flushQueue()},300))}async flushQueue(){if(this.isFlushing)return;if(this.isFlushing=!0,this.ingestTimer&&(clearTimeout(this.ingestTimer),this.ingestTimer=null),this.authLoading){console.debug("[Akropolys] Authentication is loading. Deferring ingestion flush."),this.isFlushing=!1;return}if(typeof navigator<"u"&&!navigator.onLine){console.warn("[Akropolys] Browser offline. Postponing ingestion."),this.isFlushing=!1;return}let e=50;try{for(;this.ingestQueue.length>0;){let n=this.ingestQueue.slice(0,e);try{await this.api.ingestBatch(n),this.ingestQueue.splice(0,n.length),this.retryCount=0}catch(r){let s=r.status||500,o=r.message||"Unknown network error";if(this.onError)try{this.onError({status:s,message:o})}catch(i){console.error("[Akropolys] Error inside onError callback:",i)}if(s>=400&&s<500&&s!==429){console.error("[Akropolys] Ingestion discarded due to client error:",o),this.ingestQueue.splice(0,n.length);continue}else{console.warn("[Akropolys] Ingestion temporarily failed. Retrying later.",o),this.scheduleFlushWithBackoff();break}}}}finally{this.isFlushing=!1}}scheduleFlushWithBackoff(){if(this.ingestTimer)return;let e=1e3,n=Math.random()*1e3,r=Math.min(e*Math.pow(2,this.retryCount),3e4)+n;this.retryCount++,this.ingestTimer=setTimeout(()=>{this.flushQueue()},r)}async queueContentIngest(e){this.contentQueue.push(e),this.scheduleContentFlush()}scheduleContentFlush(){this.contentIngestTimer||this.isContentFlushing||(this.contentIngestTimer=setTimeout(()=>{this.flushContentQueue()},300))}async flushContentQueue(){if(this.isContentFlushing)return;if(this.isContentFlushing=!0,this.contentIngestTimer&&(clearTimeout(this.contentIngestTimer),this.contentIngestTimer=null),this.authLoading){console.debug("[Akropolys] Authentication is loading. Deferring content ingestion flush."),this.isContentFlushing=!1;return}if(typeof navigator<"u"&&!navigator.onLine){console.warn("[Akropolys] Browser offline. Postponing content ingestion."),this.isContentFlushing=!1;return}let e=50;try{for(;this.contentQueue.length>0;){let n=this.contentQueue.slice(0,e);try{await this.api.ingestContentBatch(n),this.contentQueue.splice(0,n.length),this.contentRetryCount=0}catch(r){let s=r.status||500,o=r.message||"Unknown network error";if(this.onError)try{this.onError({status:s,message:o})}catch(i){console.error("[Akropolys] Error inside onError callback:",i)}if(s>=400&&s<500&&s!==429){console.error("[Akropolys] Content ingestion discarded due to client error:",o),this.contentQueue.splice(0,n.length);continue}else{console.warn("[Akropolys] Content ingestion temporarily failed. Retrying later.",o),this.scheduleContentFlushWithBackoff();break}}}}finally{this.isContentFlushing=!1}}scheduleContentFlushWithBackoff(){if(this.contentIngestTimer)return;let e=1e3,n=Math.random()*1e3,r=Math.min(e*Math.pow(2,this.contentRetryCount),3e4)+n;this.contentRetryCount++,this.contentIngestTimer=setTimeout(()=>{this.flushContentQueue()},r)}};$.INGEST_CACHE_KEY="akropolys_ingested_v3",$.INGEST_CACHE_TTL=1440*60*1e3,$.DEFAULT_API_URL="https://api.akropolys.cloud/v1",$.DEFAULT_VOICE_URL="https://voice.akropolys.cloud",$.CHROME_STRINGS_CACHE_VERSION=5;var Ie=$,It="__akropolys_client__";function bt(){return globalThis[It]??null}function Te(t){globalThis[It]=t}function G(){let t=bt();if(!t){let e=ie("NEXT_PUBLIC_AKROPOLYS_SITE_ID"),n=ie("NEXT_PUBLIC_AKROPOLYS_API_URL"),r=ie("NEXT_PUBLIC_AKROPOLYS_API_TOKEN");if(e&&r)t=new Ie({siteId:e,apiUrl:n,apiToken:r}),Te(t);else throw new Error("[Akropolys] Call initAkropolys() or set NEXT_PUBLIC_AKROPOLYS_* environment variables before using the client.")}return t}var de=D(V());var Zn=D(je()),Kt=(0,de.createContext)(null);function se(){let t=(0,de.useContext)(Kt);return t||G()}var tr=D(V());var Le=D(V());var Dt=D(V());var Vt=D(V());var Ht=D(V());var g=D(V());var Ge=new Map,We=new Set,jt=3e4,qt=1200;function be(t,e,n=Date.now()){if(!t||!e||typeof e!="object")return;let r=Ge.get(t);if(r&&r.at>n)return;let s={...r?.changedAt??{}},o=!r;for(let i of Object.keys(e))(!r||r.fields[i]!==e[i])&&(s[i]=n,o=!0);for(let i of Object.keys(s))i in e||delete s[i];if(!(!o&&r&&r.at===n)){Ge.set(t,{key:t,fields:e,at:n,changedAt:s});for(let i of We)try{i(t)}catch(a){console.error("[Akropolys] live value listener failed:",a)}}}function Bt(t){return Ge.get(t)}function zt(t){return We.add(t),()=>{We.delete(t)}}function sr(t,e=Date.now()){return!!t&&e-t.at>=jt}function ir(t,e,n=Date.now()){let r=t?.changedAt[e];return r!==void 0&&n-r<qt}function or(t){let e=Math.max(0,Math.round(t/1e3));if(e<60)return`${e}s ago`;let n=Math.round(e/60);if(n<60)return`${n}m ago`;let r=Math.round(n/60);return r<24?`${r}h ago`:`${Math.round(r/24)}d ago`}function ar(t){if(t==null||t==="")return"\u2014";let e=String(t).trim();if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(e)){let r=new Date(e);if(!isNaN(r.getTime()))return r.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}let n=Number(e);return!isNaN(n)&&/^-?\d+(\.\d+)?$/.test(e)?Math.abs(n)>=1e6?`${(n/1e6).toFixed(2)}M`:Math.abs(n)>=1e3?n.toLocaleString(void 0,{maximumFractionDigits:2}):n.toString():e}function ur(t){return t.slice(t.lastIndexOf(".")+1).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/^./,n=>n.toUpperCase())}var Ue=D(V());function Ze(){let t=se(),[e,n]=(0,Ue.useState)(()=>t?.api.cardFields??[]);return(0,Ue.useEffect)(()=>{if(!t)return;let r=!0;return t.api.widgetSettings().then(s=>{r&&n(s.cardFields)}),()=>{r=!1}},[t]),e}function et(t,e,n,r,s,o,i){let a=[...t],u=i?.images?.length?i.images:void 0,c=i?.live;return(e||u)&&a.push({role:"user",content:e,spoken:!0,live:c,audioUrl:s,images:u}),(n||i?.visualization)&&a.push({role:"assistant",content:n,spoken:!0,live:c,thoughtForSeconds:r&&r>0?Math.round(r*10)/10:void 0,audioUrl:o,visualization:i?.visualization}),a}var cr="Continue your previous answer exactly where it stopped. Do not repeat anything already written \u2014 just carry on from the last character.";function Yt(t,e){return t.map(n=>{let r=He(n.fields||n,e);return{...n,name:n.name||r.title,image:n.image||r.image||ue(n.images,void 0,n.url)[0]?.url,images:ue(n.images??n.fields?.images??r.images,n.image||r.image,n.url),details:r.details}})}function lr(t={}){let e=se(),n=Ze(),[r,s]=(0,g.useState)(t.initialMessages??[]),[o,i]=(0,g.useState)([]),[a,u]=(0,g.useState)([]),[c,h]=(0,g.useState)(!1),[b,y]=(0,g.useState)(!1),[A,_]=(0,g.useState)(!1),[L,M]=(0,g.useState)(!1),[k,N]=(0,g.useState)(null),[F,j]=(0,g.useState)(null),[Oe,Me]=(0,g.useState)(null),[dn,Ne]=(0,g.useState)(null),[gn,pn]=(0,g.useState)(null),W=(0,g.useRef)(null),Z=(0,g.useRef)(null),[hn,Ce]=(0,g.useState)(null),ge=(0,g.useRef)([]),it=(0,g.useRef)(!1),ot=(0,g.useRef)(!1);it.current=c,ot.current=b;let q=(0,g.useRef)(""),X=(0,g.useRef)(0),ee=(0,g.useRef)(null),te=(0,g.useRef)(!1),B=(0,g.useCallback)(()=>{ee.current!=null&&(cancelAnimationFrame(ee.current),ee.current=null)},[]),at=(0,g.useRef)(t.onToken),ut=(0,g.useRef)(t.onMeta),ct=(0,g.useRef)(t.onDone),Ae=(0,g.useRef)(t.onError),[Q,pe]=(0,g.useState)(()=>e?.api.conversation?.id??null),he=(0,g.useRef)(0),[$e,me]=(0,g.useState)(null),Fe=(0,g.useRef)({id:Q,upTo:e?.api.conversation?.cursor??0,shown:0,auto:!0}),[lt,mn]=(0,g.useState)([]),[yn,ft]=(0,g.useState)(0),J=(0,g.useCallback)(async()=>{if(!e)return[];let f=await e.api.myRequests().catch(()=>[]);return mn(f),f},[e]),_e=(0,g.useCallback)(()=>{e?.api.forgetConversation(),Fe.current={id:null,upTo:0,shown:0,auto:!1},pe(null),me(null),J()},[e,J]),vn=(0,g.useCallback)(async f=>{if(!e)return;let m=await e.api.resumeRequest(f);m!==null&&(W.current?.destroy(),B(),te.current=!0,Z.current=null,Ce(null),h(!1),y(!1),s([]),Fe.current={id:f,upTo:m,shown:0,auto:!1},me(null),pe(f),ft(v=>v+1))},[e,B]);(0,g.useEffect)(()=>{J()},[J]);let kn=(0,g.useCallback)(()=>{e?.api.leaveConversation(),pe(null),me(null),setTimeout(J,600)},[e,J]);(0,g.useEffect)(()=>{if(!e||!Q)return;let f=new AbortController,m=null,v=Fe.current,E=0,I=!1,x=()=>v.id===Q&&v.shown<v.upTo,U=S=>{if(!f.signal.aborted){if(S.type==="message"&&S.message){if(e.api.seenConversationMessage(S.message.id),x()){if(S.message.id<=v.shown)return;v.shown=S.message.id;let{role:C,text:d}=S.message,p=new Date(S.message.at).getTime();if(S.message.kind==="joined"&&s(P=>[...P,{role:"assistant",content:"",statusStage:"team_joined"}]),C==="visitor"&&d&&s(P=>[...P,{role:"user",content:d}]),C==="human"){let P=E?Math.max(1,Math.round((p-E)/1e3)):void 0;s(ae=>[...ae,{role:"assistant",content:d,human:!0,repliedSeconds:P}])}C==="visitor"&&(E=p,he.current=Math.max(he.current,p)),!x()&&C==="visitor"&&(m==="waiting"||m==="human")&&s(P=>[...P,{role:"assistant",content:"",statusStage:"with_team"}]);return}if(S.message.kind==="joined"){s(C=>[...C,{role:"assistant",content:"",statusStage:"team_joined"}]);return}if(S.message.role==="system"&&(m==="kiku"||m==="closed")){let C=m==="kiku"?"back_with_kiku":"team_closed";s(d=>[...d,{role:"assistant",content:"",statusStage:C}]),I=!0,f.abort();return}if(S.message.role!=="human")return;let R=he.current?Math.max(1,Math.round((new Date(S.message.at).getTime()-he.current)/1e3)):void 0,l=S.message.text;s(C=>[...C,{role:"assistant",content:l,human:!0,repliedSeconds:R&&R>0?R:void 0}]);return}S.type==="status"&&S.status&&(m!==null&&m!==S.status&&J(),m=S.status,me(S.status))}};return(async()=>{if(v.auto&&v.id===Q){let R=await e.api.conversationState().catch(()=>null);if(f.signal.aborted)return;if(v.auto=!1,R&&R.status!=="waiting"&&R.status!=="human"&&R.unread===0){_e();return}}let S=3e3;for(;!f.signal.aborted;){let R=await e.api.conversationEvents(U,f.signal,x()?v.shown:void 0).catch(()=>0);if(I||R===200&&(m==="kiku"||m==="closed"))return;if(R===404){e.api.forgetConversation(),pe(null);return}S=R===200?3e3:Math.min(S*2,6e4),await new Promise(l=>setTimeout(l,S))}})(),()=>f.abort()},[e,Q,yn,J,_e]),(0,g.useEffect)(()=>{at.current=t.onToken,ut.current=t.onMeta,ct.current=t.onDone,Ae.current=t.onError},[t.onToken,t.onMeta,t.onDone,t.onError]),(0,g.useEffect)(()=>()=>{W.current?.destroy(),B()},[B]);let Ke=(0,g.useCallback)(()=>{if(ee.current!=null)return;let f=()=>{let m=q.current;if(m.length>X.current){X.current=m.length;let v=m;s(E=>{let I=[...E];return I.length>0&&I[I.length-1].role==="assistant"&&(I[I.length-1]={...I[I.length-1],content:v}),I})}X.current<q.current.length||!te.current?ee.current=requestAnimationFrame(f):(ee.current=null,y(!1))};ee.current=requestAnimationFrame(f)},[]),oe=(0,g.useRef)(new Set),ne=(0,g.useRef)(new Set);(0,g.useEffect)(()=>()=>{oe.current.clear(),ne.current.forEach(f=>clearTimeout(f)),ne.current.clear()},[]);let Sn=(0,g.useCallback)(f=>{if(!f||oe.current.has(f))return;oe.current.add(f);let m=Date.now()+600*1e3,v=4e3,E=U=>{oe.current.delete(f),s(S=>{let R=[...S];for(let l=R.length-1;l>=0;l--)if(R[l].role==="assistant"){R[l]={...R[l],visualizing:!1,...U};break}return R})},I=async()=>{if(!oe.current.has(f))return;if(Date.now()>m){E({});return}let U=await e.api?.getVideoStatus?.(f);if(U?.status==="SUCCESS"&&U.videoUrl){let R=U.videoUrl;R.startsWith("/")&&e?.apiUrl&&(R=`${e.apiUrl.replace(/\/+$/,"")}${R}`),E({visualization:R,visualizationType:"video"});return}if(U?.status==="FAILED"){E({});return}v=Math.min(v*1.4,2e4);let S=setTimeout(()=>{ne.current.delete(S),I()},v);ne.current.add(S)},x=setTimeout(()=>{ne.current.delete(x),I()},v);ne.current.add(x)},[e]),ye=(0,g.useCallback)((f,m,v)=>{let E=m,I=null,x=[],U=Date.now(),S=m;m&&(q.current=v,X.current=v.length,te.current=!1);let R=()=>{E?m&&(h(!1),y(!0),Ke()):(h(!1),y(!0),q.current="",X.current=0,te.current=!1,E=!0,Ke())};f.on("meta",l=>{I=l,i(l.sources??[]),l.intent&&Ne(l.intent),Array.isArray(l.allowedActions)&&pn(l.allowedActions),l.action&&Me(l.action),l.action?.kikuKey&&e&&(e.setKikuKey(l.action.kikuKey),l.action.kikuPub&&e.setKikuPub(l.action.kikuPub)),l.action?.type==="request_human"&&l.action.conversationId&&e&&(e.api.openConversation(l.action.conversationId,l.action.conversationToken),pe(e.api.conversation?.id??null),ft(C=>C+1),me("waiting"),J()),ut.current?.(l)}),f.on("status",l=>{l?.message&&(R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,statusMessage:l.message,statusStage:l.stage}),d}))}),f.on("entity_ref",l=>{l?.id&&(x.includes(l.id)||x.push(l.id),u(C=>C.includes(l.id)?C:[...C,l.id]))}),f.on("knowledge_images",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,knowledgeImages:l}),d})}),f.on("stale_notice",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,staleNotices:l}),d})}),f.on("live_ref",l=>{l?.fields&&typeof l.fields=="object"&&be(l.key,l.fields,typeof l.at=="number"?l.at:void 0),R(),s(C=>{let d=[...C],p=d[d.length-1];if(p?.role==="assistant"){let P=p.liveKeys??[];P.includes(l.key)||(d[d.length-1]={...p,liveKeys:[...P,l.key]})}return d})}),f.on("thinking",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,thinking:p.thinking?p.thinking+`
|
|
12
|
+
`),M=Math.max(_,L);if(M===-1)continue;let k=M===L?4:2;y=i.slice(0,M+k),i=i.slice(M+k)}let A=Un(y);for(let{event:_,data:L}of A){if(this.aborted)return;if(_==="meta"){try{let k=JSON.parse(L);this.emit("meta",k)}catch{}continue}if(_==="entity_ref"){try{let k=JSON.parse(L);this.emit("entity_ref",k)}catch{}continue}if(_==="live_ref"){try{let k=JSON.parse(L);k&&typeof k.key=="string"&&k.key&&this.emit("live_ref",k)}catch{}continue}if(_==="knowledge_images"){try{let k=JSON.parse(L);Array.isArray(k?.refs)&&k.refs.length>0&&this.emit("knowledge_images",k.refs)}catch{}continue}if(_==="stale_notice"){try{let k=JSON.parse(L);Array.isArray(k?.items)&&k.items.length>0&&this.emit("stale_notice",k.items)}catch{}continue}if(_==="thinking"){try{let{text:k}=JSON.parse(L);k&&this.emit("thinking",k)}catch{}continue}if(_==="status"){try{let k=JSON.parse(L);this.emit("status",k)}catch{}continue}if(_==="viz"){try{let k=JSON.parse(L);this.emit("viz",k)}catch{}continue}if(_==="done"){u=!0;break}if(_==="error"){let k="Stream error",N;try{let j=JSON.parse(L);k=j.error??k,N=j.code}catch{k=L}let F=new Error(k);throw N&&(F.code=N),F}if(_)continue;let M=L;a+=M,this.emit("token",M)}if(u)break}this.aborted||(e=!0,n=a)}finally{try{s.cancel().catch(()=>{})}catch{}this.abortController.abort()}}catch(r){this.aborted||this.emit("error",r)}e&&!this.aborted&&this.emit("done",n)}};var kt=new Set;function St(t){let e,n,r=typeof location<"u"?location.href:"",s=typeof history<"u"?history.pushState.bind(history):null,o=typeof history<"u"?history.replaceState.bind(history):null,i=()=>{if(typeof window>"u"||typeof document>"u")return;let A=location.href;if(kt.has(A))return;kt.add(A);let _=document.querySelector("main")??document.querySelector("article")??document.querySelector('[role="main"]')??document.querySelector("#content")??document.querySelector(".entry-content")??document.querySelector("#main")??document.body;if(!_)return;let L=_.cloneNode(!0);["nav","header","footer","script","style","noscript","iframe",'[role="navigation"]','[role="banner"]','[role="contentinfo"]','[aria-hidden="true"]',"template",".hidden",'[style*="display:none"]','[style*="display: none"]'].forEach(j=>{L.querySelectorAll(j).forEach(Oe=>Oe.remove())});let k=L.textContent?.replace(/\s+/g," ").trim()??"";if(!k||k.length<50)return;let N=12e4,F=k.length>N?k.slice(0,N):k;t.queueContentIngest({url:A,title:document.title,text:F,capturedAt:Date.now()})},a=()=>{clearTimeout(e),e=setTimeout(()=>{clearTimeout(n),i()},1e3)},u=()=>{clearTimeout(n),n=setTimeout(()=>{clearTimeout(e),i()},4e3)},c=null,h=()=>{typeof window>"u"||typeof document>"u"||typeof MutationObserver>"u"||(c=new MutationObserver(()=>{a()}),c.observe(document.body,{childList:!0,subtree:!0}))},b=()=>{typeof location>"u"||location.href!==r&&(r=location.href,a(),u())};typeof window<"u"&&(window.addEventListener("popstate",b),history&&s&&(history.pushState=(...A)=>{s(...A),b()}),history&&o&&(history.replaceState=(...A)=>{o(...A),b()}),"requestIdleCallback"in window?requestIdleCallback(()=>{i(),h()},{timeout:3e3}):setTimeout(()=>{i(),h()},1e3));let y=()=>{c&&c.disconnect(),clearTimeout(e),clearTimeout(n),typeof window<"u"&&(window.removeEventListener("popstate",b),history&&s&&(history.pushState=s),history&&o&&(history.replaceState=o))};return t.contentIndexerCleanup=y,y}function re(t){return t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(re).join(",")+"]":"{"+Object.keys(t).sort().map(r=>`${JSON.stringify(r)}:${re(t[r])}`).join(",")+"}"}function ie(t){if(t==="NEXT_PUBLIC_AKROPOLYS_SITE_ID")try{return process.env.NEXT_PUBLIC_AKROPOLYS_SITE_ID}catch{}if(t==="NEXT_PUBLIC_AKROPOLYS_API_URL")try{return process.env.NEXT_PUBLIC_AKROPOLYS_API_URL}catch{}if(t==="NEXT_PUBLIC_AKROPOLYS_API_TOKEN")try{return process.env.NEXT_PUBLIC_AKROPOLYS_API_TOKEN||process.env.NEXT_PUBLIC_AKROPOLYS_API_KEY}catch{}try{let e=import.meta.env;if(e){if(t==="NEXT_PUBLIC_AKROPOLYS_SITE_ID")return e.NEXT_PUBLIC_AKROPOLYS_SITE_ID||e.VITE_AKROPOLYS_SITE_ID;if(t==="NEXT_PUBLIC_AKROPOLYS_API_URL")return e.NEXT_PUBLIC_AKROPOLYS_API_URL||e.VITE_AKROPOLYS_API_URL;if(t==="NEXT_PUBLIC_AKROPOLYS_API_TOKEN")return e.NEXT_PUBLIC_AKROPOLYS_API_TOKEN||e.VITE_AKROPOLYS_API_TOKEN}}catch{}if(typeof globalThis<"u"){let e=globalThis;if(e.process&&e.process.env){let n=e.process.env[t];if(n!==void 0)return n}}}function wt(){if(typeof DOMException<"u")return new DOMException("Aborted","AbortError");let t=new Error("Aborted");return t.name="AbortError",t}function we(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function On(t,e){let n=[];for(let r of e){let s=t[r];s==null||s===""||typeof s=="object"||n.push({label:r.replace(/[_-]+/g," "),value:String(s)})}return n}function He(t,e=[]){let n=["title","name","label","headline","subject","job_title","listing_title","common_name"],r="";if(!r){for(let a of n)if(typeof t[a]=="string"&&t[a].trim()!==""){r=t[a];break}}r||(r=Object.values(t).find(u=>typeof u=="string"&&u.length>=2&&u.length<=80&&!u.startsWith("http://")&&!u.startsWith("https://"))||"Untitled");let s=["image","images","thumbnail","photo","cover","featured_image"],o;if(!o)for(let a of s){let u=t[a];if(typeof u=="string"&&u.startsWith("http")){o=u;break}else if(Array.isArray(u)&&typeof u[0]=="string"&&u[0].startsWith("http")){o=u[0];break}}let i=ue(t.images,o);return{title:r,image:o||i[0]?.url,images:i,details:On(t,e)}}var $=class ${constructor(e){this.entities={query:async(e,n)=>{let r=n?.signal;if(r?.aborted)throw wt();let s=this.chat(e.q);return new Promise((o,i)=>{let a=()=>{s.destroy(),u(()=>i(wt()))},u=c=>{r?.removeEventListener("abort",a),c()};r?.addEventListener("abort",a,{once:!0}),s.on("token",c=>{n?.onToken?.(c)}),s.on("error",c=>u(()=>i(c))),s.on("done",()=>u(()=>o()))})}};this.allowance=(e,n)=>this.api.allowance(e,n);this.ingestQueue=[];this.ingestTimer=null;this.ingestedUrls=new Map;this.onlineHandler=null;this.sessionId="";this.deviceId="";this.kikuPub=null;this.kikuKey=null;this.shopperName=null;this.contextProviders=[];this.isFlushing=!1;this.retryCount=0;this.contentQueue=[];this.contentIngestTimer=null;this.isContentFlushing=!1;this.contentRetryCount=0;this.contentIndexerCleanup=null;this.lastIngestedItem=null;this.shopperLanguage=null;this.entityLanguageMode=null;let n=e.siteId||ie("NEXT_PUBLIC_AKROPOLYS_SITE_ID")||"",r=e.apiUrl||ie("NEXT_PUBLIC_AKROPOLYS_API_URL")||$.DEFAULT_API_URL,s=e.apiToken||ie("NEXT_PUBLIC_AKROPOLYS_API_TOKEN")||"";this.voiceUrl=e.voiceUrl||ie("NEXT_PUBLIC_AKROPOLYS_VOICE_URL")||$.DEFAULT_VOICE_URL,n||console.error("[Akropolys] Missing siteId \u2014 pass <AkropolysProvider siteId=\u2026> or set NEXT_PUBLIC_AKROPOLYS_SITE_ID."),s||console.error("[Akropolys] Missing apiToken \u2014 pass <AkropolysProvider apiToken=\u2026> or set NEXT_PUBLIC_AKROPOLYS_API_TOKEN."),this.shopperId=e.shopperId,this.userProof=e.userProof,this.authLoading=e.authLoading,this.onAction=e.onAction,this.onAddToCart=e.onAddToCart,this.getCart=e.getCart,this.onError=e.onError,e.kikuKey&&(this.kikuKey=e.kikuKey),this.initSession(),this.initDevice(),this.initKikuKey(),this.initShopperName(),this.initShopperLanguage(),this.initEntityLanguageMode(),this.loadIngestedCache(),this.api=new ke(r,n,s,()=>this.getShopperId(),()=>this.sessionId,()=>this.deviceId,()=>this.kikuPub??void 0,()=>this.shopperName??void 0,()=>{try{return this.getCart?.()}catch{return}},()=>this.shopperLanguage??void 0,()=>this.entityLanguageMode??void 0,()=>this.kikuKey??void 0),this.api.userProof=e.userProof,Te(this),typeof window<"u"&&(this.onlineHandler=()=>{console.debug("[Akropolys] Connectivity restored, flushing queued ingestions."),this.flushQueue(),this.flushContentQueue()},window.addEventListener("online",this.onlineHandler)),e.indexContent&&St(this)}get apiUrl(){return this.api.apiUrl}loadIngestedCache(){if(!(typeof window>"u"))try{let e=localStorage.getItem($.INGEST_CACHE_KEY);if(!e)return;let{ts:n,urlFingerprints:r}=JSON.parse(e);if(Date.now()-n>$.INGEST_CACHE_TTL){localStorage.removeItem($.INGEST_CACHE_KEY);return}this.ingestedUrls=new Map(r)}catch{}}saveIngestedCache(){if(!(typeof window>"u"))try{localStorage.setItem($.INGEST_CACHE_KEY,JSON.stringify({ts:Date.now(),urlFingerprints:Array.from(this.ingestedUrls.entries())}))}catch{}}registerContextProvider(e){return this.contextProviders.push(e),()=>{this.contextProviders=this.contextProviders.filter(n=>n!==e)}}async getCurrentContextAsync(e){let n=this.getCurrentContext();if(this.contextProviders.length===0)return n??{};let r=await Promise.all(this.contextProviders.map(i=>Promise.race([i(e),new Promise((a,u)=>setTimeout(()=>u(new Error("timeout")),3e3))]).catch(a=>(console.warn("[Akropolys] Live context provider failed:",a?.message??a),{})))),s=Object.assign({},...r),o=n??{};return{...o,raw:{...o.raw??{},...s}}}getCurrentContext(){if(typeof window>"u")return null;let e={url:window.location.href,title:document.title,raw:{}};if(this.lastIngestedItem){let n=this.lastIngestedItem.url;if(n)try{let r=new URL(n,window.location.origin);r.pathname===window.location.pathname&&(e.raw=this.lastIngestedItem,e.url=r.href,(this.lastIngestedItem.name||this.lastIngestedItem.title)&&(e.title=this.lastIngestedItem.name||this.lastIngestedItem.title))}catch{if(window.location.href.endsWith(n)||n.endsWith(window.location.pathname)){e.raw=this.lastIngestedItem;try{e.url=new URL(n,window.location.origin).href}catch{e.url=n}(this.lastIngestedItem.name||this.lastIngestedItem.title)&&(e.title=this.lastIngestedItem.name||this.lastIngestedItem.title)}}}return e}chat(e,n=[],r,s,o){let i=new AbortController,a=performance.now(),u=[],c=A=>u.push(`${A}=${Math.round(performance.now()-a)}ms`),h=this.getCurrentContextAsync(i.signal).then(A=>(c("context"),this.api.chatStream(e,n,i.signal,A,r,s,o))).then(A=>(c("headers"),A)),b=new Se(h,i),y=!1;return b.on("token",()=>{y||(y=!0,c("first_text"))}),b.on("done",()=>{c("done"),console.info(`[kiku timing] ${u.join(" ")}`)}),b.on("meta",A=>{A&&typeof A.language=="string"&&A.language&&this.setShopperLanguage(A.language)}),b}reRegister(){Te(this),typeof window<"u"&&!this.onlineHandler&&(this.onlineHandler=()=>{this.flushQueue(),this.flushContentQueue()},window.addEventListener("online",this.onlineHandler))}updateConfig(e){e.apiUrl&&(this.api.apiUrl=e.apiUrl),e.siteId&&(this.api.siteId=e.siteId),e.apiToken&&(this.api.apiToken=e.apiToken),e.voiceUrl!==void 0&&(this.voiceUrl=e.voiceUrl)}setUserProof(e){this.userProof=e,this.api.userProof=e}getUserProof(){return this.userProof}setShopperId(e){this.shopperId=e,this.authLoading||(this.flushQueue(),this.flushContentQueue())}setAuthLoading(e){let n=this.authLoading;this.authLoading=e,n&&!e&&(this.flushQueue(),this.flushContentQueue())}getShopperId(){return this.shopperId||"guest_"+this.sessionId}getSessionId(){return this.sessionId}initSession(){if(typeof window<"u"&&window.sessionStorage)try{let e=window.sessionStorage.getItem("akropolys_session_id");e||(e=we(),window.sessionStorage.setItem("akropolys_session_id",e)),this.sessionId=e;return}catch{}this.sessionId=we()}initDevice(){if(typeof window>"u"){this.deviceId=we();return}try{let e=localStorage.getItem("akropolys_device_id");e||(e=we(),localStorage.setItem("akropolys_device_id",e)),this.deviceId=e}catch{this.deviceId=we()}}getDeviceId(){return this.deviceId}async mintKikuKey(){let e=await this.api.mintKikuKey();return e.secret&&this.setKikuKey(e.secret),e.publicId&&this.setKikuPub(e.publicId),e}initKikuKey(){if(!(typeof window>"u"))try{if(!this.kikuKey){let s=localStorage.getItem("akropolys_kiku_key")||localStorage.getItem("kiku_key")||sessionStorage.getItem("akropolys_kiku_key");s&&(this.kikuKey=s)}let e=sessionStorage.getItem("akropolys_kiku_pub")||sessionStorage.getItem("kiku_pub");if(e){this.kikuPub=e;return}let n=localStorage.getItem("akropolys_kiku_pub")||localStorage.getItem("kiku_pub")||localStorage.getItem("kiku_id");if(n){this.kikuPub=n;return}let r=document.cookie.match(/(?:^|;\s*)(?:akropolys_kiku_pub|kiku_pub|kiku_id)=([^;]+)/);if(r){this.kikuPub=decodeURIComponent(r[1]);return}}catch{}}getKikuPub(){return this.kikuPub??void 0}getKikuKey(){return this.kikuKey??void 0}setKikuKey(e){if(this.kikuKey=e,!(typeof window>"u"))try{e?(localStorage.setItem("akropolys_kiku_key",e),sessionStorage.setItem("akropolys_kiku_key",e)):(localStorage.removeItem("akropolys_kiku_key"),sessionStorage.removeItem("akropolys_kiku_key"))}catch{}}initShopperName(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_shopper_name");e&&(this.shopperName=e)}catch{}}getShopperName(){return this.shopperName??void 0}setShopperName(e){let n=(e||"").trim().slice(0,40);if(n&&(this.shopperName=n,!(typeof window>"u")))try{localStorage.setItem("akropolys_shopper_name",n)}catch{}}clearShopperName(){if(this.shopperName=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_shopper_name")}catch{}}initShopperLanguage(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_shopper_language");e&&(this.shopperLanguage=e)}catch{}}getShopperLanguage(){return this.shopperLanguage??void 0}setShopperLanguage(e){let n=(e||"").trim().slice(0,40);if(n&&(this.shopperLanguage=n,!(typeof window>"u")))try{localStorage.setItem("akropolys_shopper_language",n)}catch{}}clearShopperLanguage(){if(this.shopperLanguage=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_shopper_language")}catch{}}initEntityLanguageMode(){if(!(typeof window>"u"))try{let e=localStorage.getItem("akropolys_entity_language");(e==="original"||e==="translated")&&(this.entityLanguageMode=e)}catch{}}getEntityLanguageMode(){return this.entityLanguageMode??void 0}setEntityLanguageMode(e){if(!(e!=="original"&&e!=="translated")&&(this.entityLanguageMode=e,!(typeof window>"u")))try{localStorage.setItem("akropolys_entity_language",e)}catch{}}clearEntityLanguageMode(){if(this.entityLanguageMode=null,!(typeof window>"u"))try{localStorage.removeItem("akropolys_entity_language")}catch{}}getEntityPreview(e){return this.api.entityPreview(e)}storeScene(e){return this.api.storeScene(e)}baseFont(){return this.api.baseFont()}synthesizeSpeech(e,n,r,s){return this.api.synthesizeSpeech(e,n,r??this.getShopperLanguage(),s)}getCachedUIStrings(e,n){if(typeof window>"u"||!e)return null;let r=$.hashStrings(n),s=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_${e.toLowerCase().trim()}_${r}`;try{let o=localStorage.getItem(s);if(o){let i=JSON.parse(o);if(i?.strings&&Object.keys(i.strings).length>0)return{strings:i.strings,complete:!0,dir:i.dir==="rtl"?"rtl":"ltr",bcp47:typeof i.bcp47=="string"?i.bcp47:"",font:i.font?.family&&i.font?.faces?.length?i.font:null}}}catch{}return null}async getUIStrings(e,n){let r=$.hashStrings(n),s=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_${e.toLowerCase().trim()}_${r}`,o=this.getCachedUIStrings(e,n);if(o)return o;let i={strings:{},complete:!1,dir:"ltr",bcp47:"",font:null};if(typeof window<"u")try{let c=localStorage.getItem(s);if(c){let h=JSON.parse(c);if(h?.strings&&Object.keys(h.strings).length>0)return{strings:h.strings,complete:!0,dir:h.dir==="rtl"?"rtl":"ltr",bcp47:typeof h.bcp47=="string"?h.bcp47:"",font:h.font?.family&&h.font?.faces?.length?h.font:null};localStorage.removeItem(s)}}catch{}let a=await this.api.uiStrings(e,n);if(a?.complete||(a=await this.api.uiStrings(e,n)),!a?.complete||Object.keys(a.strings).length===0)return i;let u=a.strings;if(typeof window<"u")try{let c="akropolys_ui_strings_",h=`akropolys_ui_strings_v${$.CHROME_STRINGS_CACHE_VERSION}_`;for(let b=localStorage.length-1;b>=0;b--){let y=localStorage.key(b);y&&y.startsWith(c)&&!y.startsWith(h)&&localStorage.removeItem(y)}localStorage.setItem(s,JSON.stringify({strings:u,dir:a.dir,bcp47:a.bcp47,font:a.font}))}catch{}return a}static hashStrings(e){let n=Object.keys(e).sort().map(s=>`${s}${e[s]}`).join(""),r=5381;for(let s=0;s<n.length;s++)r=(r*33^n.charCodeAt(s))>>>0;return r.toString(36)}setKikuPub(e){let n=(e||"").trim();if(n&&(this.kikuPub=n,!(typeof window>"u"))){try{sessionStorage.setItem("akropolys_kiku_pub",n)}catch{}try{localStorage.setItem("akropolys_kiku_pub",n)}catch{}try{document.cookie=`akropolys_kiku_pub=${encodeURIComponent(n)};path=/;max-age=31536000;SameSite=Lax`}catch{}}}hasKikuKey(){return!!this.kikuPub}clearKikuKey(){if(this.kikuPub=null,!(typeof window>"u")){try{sessionStorage.removeItem("akropolys_kiku_pub")}catch{}try{sessionStorage.removeItem("kiku_pub")}catch{}try{localStorage.removeItem("akropolys_kiku_pub")}catch{}try{localStorage.removeItem("kiku_pub")}catch{}try{localStorage.removeItem("kiku_id")}catch{}try{localStorage.removeItem("akropolys_kiku_key")}catch{}try{document.cookie="akropolys_kiku_pub=;path=/;max-age=0"}catch{}}}destroy(){this.contextProviders=[],typeof window<"u"&&this.onlineHandler&&(window.removeEventListener("online",this.onlineHandler),this.onlineHandler=null),this.ingestTimer&&(clearTimeout(this.ingestTimer),this.ingestTimer=null),this.contentIngestTimer&&(clearTimeout(this.contentIngestTimer),this.contentIngestTimer=null),this.contentIndexerCleanup&&(this.contentIndexerCleanup(),this.contentIndexerCleanup=null),bt()===this&&Te(null)}async queueIngest(e){return this.ingest(e)}async queueIngestBatch(e){return this.ingestMany(e)}async ingest(e){this.lastIngestedItem=e;let n=e.envelope?.entity||e,r=n.id??n.productId??n.slug??n.url??n.name??"",s=n.url||(typeof window<"u"?window.location.href:"");if(!r&&!s){console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");return}let o=re(e);if(s){if(this.ingestedUrls.get(s)===o)return;this.ingestedUrls.set(s,o),this.saveIngestedCache()}this.ingestQueue.push(e),this.scheduleFlush()}async ingestMany(e){e.length>0&&(this.lastIngestedItem=e[e.length-1]);let n=!1;e.forEach(r=>{let s=r.envelope?.entity||r,o=s.id??s.productId??s.slug??s.url??s.name??"",i=s.url||(typeof window<"u"?window.location.href:"");if(!o&&!i){console.warn("[Akropolys] Ingestion warning: Item is missing both a stable identifier and a URL. Skipping.");return}let a=re(r);if(i){if(this.ingestedUrls.get(i)===a)return;this.ingestedUrls.set(i,a),n=!0}this.ingestQueue.push(r)}),n&&this.saveIngestedCache(),this.ingestQueue.length>0&&this.scheduleFlush()}scheduleFlush(){this.ingestTimer||this.isFlushing||(this.ingestTimer=setTimeout(()=>{this.flushQueue()},300))}async flushQueue(){if(this.isFlushing)return;if(this.isFlushing=!0,this.ingestTimer&&(clearTimeout(this.ingestTimer),this.ingestTimer=null),this.authLoading){console.debug("[Akropolys] Authentication is loading. Deferring ingestion flush."),this.isFlushing=!1;return}if(typeof navigator<"u"&&!navigator.onLine){console.warn("[Akropolys] Browser offline. Postponing ingestion."),this.isFlushing=!1;return}let e=50;try{for(;this.ingestQueue.length>0;){let n=this.ingestQueue.slice(0,e);try{await this.api.ingestBatch(n),this.ingestQueue.splice(0,n.length),this.retryCount=0}catch(r){let s=r.status||500,o=r.message||"Unknown network error";if(this.onError)try{this.onError({status:s,message:o})}catch(i){console.error("[Akropolys] Error inside onError callback:",i)}if(s>=400&&s<500&&s!==429){console.error("[Akropolys] Ingestion discarded due to client error:",o),this.ingestQueue.splice(0,n.length);continue}else{console.warn("[Akropolys] Ingestion temporarily failed. Retrying later.",o),this.scheduleFlushWithBackoff();break}}}}finally{this.isFlushing=!1}}scheduleFlushWithBackoff(){if(this.ingestTimer)return;let e=1e3,n=Math.random()*1e3,r=Math.min(e*Math.pow(2,this.retryCount),3e4)+n;this.retryCount++,this.ingestTimer=setTimeout(()=>{this.flushQueue()},r)}async queueContentIngest(e){this.contentQueue.push(e),this.scheduleContentFlush()}scheduleContentFlush(){this.contentIngestTimer||this.isContentFlushing||(this.contentIngestTimer=setTimeout(()=>{this.flushContentQueue()},300))}async flushContentQueue(){if(this.isContentFlushing)return;if(this.isContentFlushing=!0,this.contentIngestTimer&&(clearTimeout(this.contentIngestTimer),this.contentIngestTimer=null),this.authLoading){console.debug("[Akropolys] Authentication is loading. Deferring content ingestion flush."),this.isContentFlushing=!1;return}if(typeof navigator<"u"&&!navigator.onLine){console.warn("[Akropolys] Browser offline. Postponing content ingestion."),this.isContentFlushing=!1;return}let e=50;try{for(;this.contentQueue.length>0;){let n=this.contentQueue.slice(0,e);try{await this.api.ingestContentBatch(n),this.contentQueue.splice(0,n.length),this.contentRetryCount=0}catch(r){let s=r.status||500,o=r.message||"Unknown network error";if(this.onError)try{this.onError({status:s,message:o})}catch(i){console.error("[Akropolys] Error inside onError callback:",i)}if(s>=400&&s<500&&s!==429){console.error("[Akropolys] Content ingestion discarded due to client error:",o),this.contentQueue.splice(0,n.length);continue}else{console.warn("[Akropolys] Content ingestion temporarily failed. Retrying later.",o),this.scheduleContentFlushWithBackoff();break}}}}finally{this.isContentFlushing=!1}}scheduleContentFlushWithBackoff(){if(this.contentIngestTimer)return;let e=1e3,n=Math.random()*1e3,r=Math.min(e*Math.pow(2,this.contentRetryCount),3e4)+n;this.contentRetryCount++,this.contentIngestTimer=setTimeout(()=>{this.flushContentQueue()},r)}};$.INGEST_CACHE_KEY="akropolys_ingested_v3",$.INGEST_CACHE_TTL=1440*60*1e3,$.DEFAULT_API_URL="https://api.akropolys.cloud/v1",$.DEFAULT_VOICE_URL="https://voice.akropolys.cloud",$.CHROME_STRINGS_CACHE_VERSION=6;var Ie=$,It="__akropolys_client__";function bt(){return globalThis[It]??null}function Te(t){globalThis[It]=t}function G(){let t=bt();if(!t){let e=ie("NEXT_PUBLIC_AKROPOLYS_SITE_ID"),n=ie("NEXT_PUBLIC_AKROPOLYS_API_URL"),r=ie("NEXT_PUBLIC_AKROPOLYS_API_TOKEN");if(e&&r)t=new Ie({siteId:e,apiUrl:n,apiToken:r}),Te(t);else throw new Error("[Akropolys] Call initAkropolys() or set NEXT_PUBLIC_AKROPOLYS_* environment variables before using the client.")}return t}var de=D(V());var Zn=D(je()),Kt=(0,de.createContext)(null);function se(){let t=(0,de.useContext)(Kt);return t||G()}var tr=D(V());var Le=D(V());var Dt=D(V());var Vt=D(V());var Ht=D(V());var g=D(V());var Ge=new Map,We=new Set,jt=3e4,qt=1200;function be(t,e,n=Date.now()){if(!t||!e||typeof e!="object")return;let r=Ge.get(t);if(r&&r.at>n)return;let s={...r?.changedAt??{}},o=!r;for(let i of Object.keys(e))(!r||r.fields[i]!==e[i])&&(s[i]=n,o=!0);for(let i of Object.keys(s))i in e||delete s[i];if(!(!o&&r&&r.at===n)){Ge.set(t,{key:t,fields:e,at:n,changedAt:s});for(let i of We)try{i(t)}catch(a){console.error("[Akropolys] live value listener failed:",a)}}}function Bt(t){return Ge.get(t)}function zt(t){return We.add(t),()=>{We.delete(t)}}function sr(t,e=Date.now()){return!!t&&e-t.at>=jt}function ir(t,e,n=Date.now()){let r=t?.changedAt[e];return r!==void 0&&n-r<qt}function or(t){let e=Math.max(0,Math.round(t/1e3));if(e<60)return`${e}s ago`;let n=Math.round(e/60);if(n<60)return`${n}m ago`;let r=Math.round(n/60);return r<24?`${r}h ago`:`${Math.round(r/24)}d ago`}function ar(t){if(t==null||t==="")return"\u2014";let e=String(t).trim();if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(e)){let r=new Date(e);if(!isNaN(r.getTime()))return r.toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}let n=Number(e);return!isNaN(n)&&/^-?\d+(\.\d+)?$/.test(e)?Math.abs(n)>=1e6?`${(n/1e6).toFixed(2)}M`:Math.abs(n)>=1e3?n.toLocaleString(void 0,{maximumFractionDigits:2}):n.toString():e}function ur(t){return t.slice(t.lastIndexOf(".")+1).replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/^./,n=>n.toUpperCase())}var Ue=D(V());function Ze(){let t=se(),[e,n]=(0,Ue.useState)(()=>t?.api.cardFields??[]);return(0,Ue.useEffect)(()=>{if(!t)return;let r=!0;return t.api.widgetSettings().then(s=>{r&&n(s.cardFields)}),()=>{r=!1}},[t]),e}function et(t,e,n,r,s,o,i){let a=[...t],u=i?.images?.length?i.images:void 0,c=i?.live;return(e||u)&&a.push({role:"user",content:e,spoken:!0,live:c,audioUrl:s,images:u}),(n||i?.visualization)&&a.push({role:"assistant",content:n,spoken:!0,live:c,thoughtForSeconds:r&&r>0?Math.round(r*10)/10:void 0,audioUrl:o,visualization:i?.visualization}),a}var cr="Continue your previous answer exactly where it stopped. Do not repeat anything already written \u2014 just carry on from the last character.";function Yt(t,e){return t.map(n=>{let r=He(n.fields||n,e);return{...n,name:n.name||r.title,image:n.image||r.image||ue(n.images,void 0,n.url)[0]?.url,images:ue(n.images??n.fields?.images??r.images,n.image||r.image,n.url),details:r.details}})}function lr(t={}){let e=se(),n=Ze(),[r,s]=(0,g.useState)(t.initialMessages??[]),[o,i]=(0,g.useState)([]),[a,u]=(0,g.useState)([]),[c,h]=(0,g.useState)(!1),[b,y]=(0,g.useState)(!1),[A,_]=(0,g.useState)(!1),[L,M]=(0,g.useState)(!1),[k,N]=(0,g.useState)(null),[F,j]=(0,g.useState)(null),[Oe,Me]=(0,g.useState)(null),[dn,Ne]=(0,g.useState)(null),[gn,pn]=(0,g.useState)(null),W=(0,g.useRef)(null),Z=(0,g.useRef)(null),[hn,Ce]=(0,g.useState)(null),ge=(0,g.useRef)([]),it=(0,g.useRef)(!1),ot=(0,g.useRef)(!1);it.current=c,ot.current=b;let q=(0,g.useRef)(""),X=(0,g.useRef)(0),ee=(0,g.useRef)(null),te=(0,g.useRef)(!1),B=(0,g.useCallback)(()=>{ee.current!=null&&(cancelAnimationFrame(ee.current),ee.current=null)},[]),at=(0,g.useRef)(t.onToken),ut=(0,g.useRef)(t.onMeta),ct=(0,g.useRef)(t.onDone),Ae=(0,g.useRef)(t.onError),[Q,pe]=(0,g.useState)(()=>e?.api.conversation?.id??null),he=(0,g.useRef)(0),[$e,me]=(0,g.useState)(null),Fe=(0,g.useRef)({id:Q,upTo:e?.api.conversation?.cursor??0,shown:0,auto:!0}),[lt,mn]=(0,g.useState)([]),[yn,ft]=(0,g.useState)(0),J=(0,g.useCallback)(async()=>{if(!e)return[];let f=await e.api.myRequests().catch(()=>[]);return mn(f),f},[e]),_e=(0,g.useCallback)(()=>{e?.api.forgetConversation(),Fe.current={id:null,upTo:0,shown:0,auto:!1},pe(null),me(null),J()},[e,J]),vn=(0,g.useCallback)(async f=>{if(!e)return;let m=await e.api.resumeRequest(f);m!==null&&(W.current?.destroy(),B(),te.current=!0,Z.current=null,Ce(null),h(!1),y(!1),s([]),Fe.current={id:f,upTo:m,shown:0,auto:!1},me(null),pe(f),ft(v=>v+1))},[e,B]);(0,g.useEffect)(()=>{J()},[J]);let kn=(0,g.useCallback)(()=>{e?.api.leaveConversation(),pe(null),me(null),setTimeout(J,600)},[e,J]);(0,g.useEffect)(()=>{if(!e||!Q)return;let f=new AbortController,m=null,v=Fe.current,E=0,I=!1,x=()=>v.id===Q&&v.shown<v.upTo,U=S=>{if(!f.signal.aborted){if(S.type==="message"&&S.message){if(e.api.seenConversationMessage(S.message.id),x()){if(S.message.id<=v.shown)return;v.shown=S.message.id;let{role:C,text:d}=S.message,p=new Date(S.message.at).getTime();if(S.message.kind==="joined"&&s(P=>[...P,{role:"assistant",content:"",statusStage:"team_joined"}]),C==="visitor"&&d&&s(P=>[...P,{role:"user",content:d}]),C==="human"){let P=E?Math.max(1,Math.round((p-E)/1e3)):void 0;s(ae=>[...ae,{role:"assistant",content:d,human:!0,repliedSeconds:P}])}C==="visitor"&&(E=p,he.current=Math.max(he.current,p)),!x()&&C==="visitor"&&(m==="waiting"||m==="human")&&s(P=>[...P,{role:"assistant",content:"",statusStage:"with_team"}]);return}if(S.message.kind==="joined"){s(C=>[...C,{role:"assistant",content:"",statusStage:"team_joined"}]);return}if(S.message.role==="system"&&(m==="kiku"||m==="closed")){let C=m==="kiku"?"back_with_kiku":"team_closed";s(d=>[...d,{role:"assistant",content:"",statusStage:C}]),I=!0,f.abort();return}if(S.message.role!=="human")return;let R=he.current?Math.max(1,Math.round((new Date(S.message.at).getTime()-he.current)/1e3)):void 0,l=S.message.text;s(C=>[...C,{role:"assistant",content:l,human:!0,repliedSeconds:R&&R>0?R:void 0}]);return}S.type==="status"&&S.status&&(m!==null&&m!==S.status&&J(),m=S.status,me(S.status))}};return(async()=>{if(v.auto&&v.id===Q){let R=await e.api.conversationState().catch(()=>null);if(f.signal.aborted)return;if(v.auto=!1,R&&R.status!=="waiting"&&R.status!=="human"&&R.unread===0){_e();return}}let S=3e3;for(;!f.signal.aborted;){let R=await e.api.conversationEvents(U,f.signal,x()?v.shown:void 0).catch(()=>0);if(I||R===200&&(m==="kiku"||m==="closed"))return;if(R===404){e.api.forgetConversation(),pe(null);return}S=R===200?3e3:Math.min(S*2,6e4),await new Promise(l=>setTimeout(l,S))}})(),()=>f.abort()},[e,Q,yn,J,_e]),(0,g.useEffect)(()=>{at.current=t.onToken,ut.current=t.onMeta,ct.current=t.onDone,Ae.current=t.onError},[t.onToken,t.onMeta,t.onDone,t.onError]),(0,g.useEffect)(()=>()=>{W.current?.destroy(),B()},[B]);let Ke=(0,g.useCallback)(()=>{if(ee.current!=null)return;let f=()=>{let m=q.current;if(m.length>X.current){X.current=m.length;let v=m;s(E=>{let I=[...E];return I.length>0&&I[I.length-1].role==="assistant"&&(I[I.length-1]={...I[I.length-1],content:v}),I})}X.current<q.current.length||!te.current?ee.current=requestAnimationFrame(f):(ee.current=null,y(!1))};ee.current=requestAnimationFrame(f)},[]),oe=(0,g.useRef)(new Set),ne=(0,g.useRef)(new Set);(0,g.useEffect)(()=>()=>{oe.current.clear(),ne.current.forEach(f=>clearTimeout(f)),ne.current.clear()},[]);let Sn=(0,g.useCallback)(f=>{if(!f||oe.current.has(f))return;oe.current.add(f);let m=Date.now()+600*1e3,v=4e3,E=U=>{oe.current.delete(f),s(S=>{let R=[...S];for(let l=R.length-1;l>=0;l--)if(R[l].role==="assistant"){R[l]={...R[l],visualizing:!1,...U};break}return R})},I=async()=>{if(!oe.current.has(f))return;if(Date.now()>m){E({});return}let U=await e.api?.getVideoStatus?.(f);if(U?.status==="SUCCESS"&&U.videoUrl){let R=U.videoUrl;R.startsWith("/")&&e?.apiUrl&&(R=`${e.apiUrl.replace(/\/+$/,"")}${R}`),E({visualization:R,visualizationType:"video"});return}if(U?.status==="FAILED"){E({});return}v=Math.min(v*1.4,2e4);let S=setTimeout(()=>{ne.current.delete(S),I()},v);ne.current.add(S)},x=setTimeout(()=>{ne.current.delete(x),I()},v);ne.current.add(x)},[e]),ye=(0,g.useCallback)((f,m,v)=>{let E=m,I=null,x=[],U=Date.now(),S=m;m&&(q.current=v,X.current=v.length,te.current=!1);let R=()=>{E?m&&(h(!1),y(!0),Ke()):(h(!1),y(!0),q.current="",X.current=0,te.current=!1,E=!0,Ke())};f.on("meta",l=>{I=l,i(l.sources??[]),l.intent&&Ne(l.intent),Array.isArray(l.allowedActions)&&pn(l.allowedActions),l.action&&Me(l.action),l.action?.kikuKey&&e&&(e.setKikuKey(l.action.kikuKey),l.action.kikuPub&&e.setKikuPub(l.action.kikuPub)),l.action?.type==="request_human"&&l.action.conversationId&&e&&(e.api.openConversation(l.action.conversationId,l.action.conversationToken),pe(e.api.conversation?.id??null),ft(C=>C+1),me("waiting"),J()),ut.current?.(l)}),f.on("status",l=>{l?.message&&(R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,statusMessage:l.message,statusStage:l.stage}),d}))}),f.on("entity_ref",l=>{l?.id&&(x.includes(l.id)||x.push(l.id),u(C=>C.includes(l.id)?C:[...C,l.id]))}),f.on("knowledge_images",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,knowledgeImages:l}),d})}),f.on("stale_notice",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,staleNotices:l}),d})}),f.on("live_ref",l=>{l?.fields&&typeof l.fields=="object"&&be(l.key,l.fields,typeof l.at=="number"?l.at:void 0),R(),s(C=>{let d=[...C],p=d[d.length-1];if(p?.role==="assistant"){let P=p.liveKeys??[];P.includes(l.key)||(d[d.length-1]={...p,liveKeys:[...P,l.key]})}return d})}),f.on("thinking",l=>{R(),s(C=>{let d=[...C],p=d[d.length-1];return p?.role==="assistant"&&(d[d.length-1]={...p,thinking:p.thinking?p.thinking+`
|
|
13
13
|
`+l:l}),d})}),f.on("token",l=>{if(R(),!S){S=!0;let C=Math.max(1,Math.round((Date.now()-U)/1e3));s(d=>{let p=[...d],P=p[p.length-1];return P?.role==="assistant"&&(p[p.length-1]={...P,thoughtForSeconds:C}),p})}q.current+=l,at.current?.(l)}),f.on("viz",l=>{if(l.status==="generating"||l.status==="generating_video"){R(),s(C=>{let d=[...C];return d.length>0&&d[d.length-1].role==="assistant"&&(d[d.length-1]={...d[d.length-1],visualizing:!0,visualizationType:l.status==="generating_video"?"video":"image",visualizingText:l.status==="generating_video"?"Generating video\u2026":"Visualizing\u2026"}),d});return}if(l.status==="pending"){Sn(l.jobId);return}R(),s(C=>{let d=[...C];if(d.length>0&&d[d.length-1].role==="assistant"){let p=l.status==="done"?l.url:void 0;p&&p.startsWith("/")&&e?.apiUrl&&(p=`${e.apiUrl.replace(/\/+$/,"")}${p}`);let P=l.status==="done"?l.mediaType||(p?.includes("/videos/")?"video":"image"):void 0;d[d.length-1]={...d[d.length-1],visualizing:!1,...l.status==="done"&&p?{visualization:p,visualizationType:P}:{}}}return d})}),f.on("done",l=>{h(!1),te.current=!0,ee.current==null&&y(!1),s(p=>{let P=[...p];if(P.length>0&&P[P.length-1].role==="assistant"){let ae=I?.sources??[];P[P.length-1]={...P[P.length-1],sources:Yt(ae,e?.api.cardFields??[]),referencedIds:x,intent:I?.intent}}return P});let C=I?.action,d=["search","capture","capture_all","delete","view_history","request_kiku_key","visualize","open_memory"];if(C?.type&&!d.includes(C.type)){let p=(I?.sources??[]).filter(dt=>dt?.id&&x.includes(dt.id)),P={...C,items:p};window.dispatchEvent(new CustomEvent("akropolys:action",{detail:P})),e.onAction?.(P);let ae=String(C.type).replace(/[^a-z]/gi,"").toLowerCase();(ae==="addtocart"||ae==="cart")&&e.onAddToCart&&p.length>0&&e.onAddToCart(p)}ct.current?.(l)}),f.on("error",l=>{te.current=!0,B(),h(!1),y(!1);let C=q.current;m||E&&C?(X.current=C.length,s(d=>{let p=[...d];return p.length>0&&p[p.length-1].role==="assistant"&&(p[p.length-1]={...p[p.length-1],content:C}),p}),M(!0)):(N(l.message),j(l.code??null),s(d=>{let p=d;return p.length>0&&p[p.length-1].role==="assistant"&&!p[p.length-1].content&&(p=p.slice(0,-1)),p})),Ae.current?.(l)})},[e,Ke,B]),Ee=(0,g.useCallback)((f,m,v,E,I)=>{s(x=>[...x,{role:"assistant",content:"",thinking:""}]),h(!0),y(!0),_(!1),M(!1),N(null),j(null),u([]),Me(null),Ne(null),q.current="",X.current=0;try{let x=e.chat(m,f,v,E,I);W.current=x,ye(x,!1,"")}catch(x){h(!1),y(!1),N(x?.message??"Chat request failed"),s(U=>U.slice(0,-1)),Ae.current?.(x)}},[e,ye]),wn=(0,g.useCallback)(async(f,m,v,E,I)=>{if(!f.trim())return;he.current=Date.now();let x={role:"user",content:m??f,images:v?.filter(S=>S.type==="image").map(S=>S.preview||S.data)};if(c||b){if(Z.current)return;Z.current={query:f,displayQuery:m,attachments:v,forcedIntent:E,captureTargets:I},Ce({...x,queued:!0});return}s(S=>[...S,x]);let U=r.map(S=>({role:S.role,content:S.content}));Ee(U,f,v,E,I)},[r,c,b,Ee]);(0,g.useEffect)(()=>{if(c||b)return;let f=r;if(ge.current.length>0){let E=ge.current;ge.current=[];for(let I of E)f=et(f,I.heard,I.said,I.duration,I.userAudioUrl,I.assistantAudioUrl,I.media);s(I=>{let x=I;for(let U of E)x=et(x,U.heard,U.said,U.duration,U.userAudioUrl,U.assistantAudioUrl,U.media);return x})}if(!Z.current)return;let m=Z.current;Z.current=null,Ce(null);let v=f.map(E=>({role:E.role,content:E.content}));s(E=>[...E,{role:"user",content:m.displayQuery??m.query,images:m.attachments?.filter(I=>I.type==="image").map(I=>I.preview||I.data)}]),Ee(v,m.query,m.attachments,m.forcedIntent,m.captureTargets)},[c,b,r,Ee]);let In=(0,g.useCallback)(()=>{if(c||b)return;let f=r[r.length-1];if(f){W.current?.destroy(),_(!1),M(!1),h(!0),N(null),j(null);try{if(f.role==="assistant"){let m=r.map(E=>({role:E.role,content:E.content})),v=e.chat(cr,m);W.current=v,ye(v,!0,f.content||"")}else{let m=r.slice(0,-1).map(E=>({role:E.role,content:E.content})),v=e.chat(f.content,m);W.current=v,ye(v,!1,"")}}catch(m){h(!1),N(m?.message??"Chat request failed"),Ae.current?.(m)}}},[e,r,c,b,ye]),bn=(0,g.useCallback)(()=>{W.current?.destroy(),B(),te.current=!0,q.current="",X.current=0,Z.current=null,ge.current=[],oe.current.clear(),ne.current.forEach(f=>clearTimeout(f)),ne.current.clear(),Ce(null),s([]),i([]),u([]),y(!1),_(!1),M(!1),N(null),j(null),h(!1),Me(null),Ne(null),_e()},[_e,B]),De=(0,g.useCallback)(()=>{if(W.current?.destroy(),B(),te.current=!0,h(!1),y(!1),q.current){let f=q.current;X.current=f.length,s(m=>{let v=[...m];return v.length>0&&v[v.length-1].role==="assistant"&&(v[v.length-1]={...v[v.length-1],content:f}),v})}_(!0),s(f=>f.map(m=>m.visualizing?{...m,visualizing:!1}:m))},[B]),Cn=(0,g.useCallback)(()=>{Z.current&&De()},[De]),An=(0,g.useCallback)((f,m,v,E,I,x)=>{let U=f.trim(),S=m.trim();if(!(!U&&!S&&!x?.images?.length&&!x?.visualization)){if(it.current||ot.current){ge.current.push({heard:U,said:S,duration:v,userAudioUrl:E,assistantAudioUrl:I,media:x});return}s(R=>et(R,U,S,v,E,I,x))}},[]),_n=(0,g.useMemo)(()=>Yt(o,n),[o,n]);return{messages:r,sources:_n,referencedIds:a,loading:c,streaming:b,error:k,errorCode:F,lastAction:Oe,lastIntent:dn,allowedActions:gn,send:wn,queuedMessage:hn,sendQueuedNow:Cn,appendSpokenExchange:An,stop:De,stopped:A,interrupted:L,continueGenerating:In,reset:bn,humanPending:!!Q&&($e==="waiting"||$e==="human"),leaveHuman:kn,requests:lt.length>0||!Q?lt:[{id:Q,status:$e??"waiting",summary:""}],activeRequestId:Q,openRequest:vn}}var Xt=D(V());var Jt=D(V());function Qt(t={}){if(typeof window>"u"||typeof WebSocket>"u")return()=>{};let e=t.client??G(),{apiUrl:n,siteId:r,apiToken:s}=e.api??{};if(!n||!r||!s)return t.onError?.(new Error("subscribeLiveStream: client is not configured \u2014 is this inside <AkropolysProvider>?")),()=>{};let o=!1,i=null,a=0,u=null,c=n.replace(/^http/,"ws"),h=new URLSearchParams({site_id:r});t.keys?.length&&h.set("keys",t.keys.join(","));function b(){o||(i=new WebSocket(`${c}/live/stream?${h}`,[`akropolys.token.${s}`]),i.onopen=()=>{a=0},i.onmessage=y=>{let A;try{A=JSON.parse(y.data)}catch{return}if(Array.isArray(A.records))for(let _ of A.records)!_?.key||!_.fields||be(_.key,_.fields,_.at)},i.onerror=()=>{t.onError?.(new Error("live stream socket error"))},i.onclose=()=>{if(o)return;let y=Math.min(15e3,1e3*2**a++);u=setTimeout(b,y)})}return b(),()=>{o=!0,u&&clearTimeout(u),i?.close()}}var Gt=D(V());var tt=D(V());function oi(t){if(typeof t=="string")return{themeAttr:t,vars:void 0};if(!t)return{themeAttr:void 0,vars:void 0};let e={};return t.primaryColor&&(e["--hsk-primary"]=t.primaryColor),t.backgroundColor&&(e["--hsk-bg"]=t.backgroundColor,e["--hsk-chat-bg"]=t.backgroundColor),t.textColor&&(e["--hsk-text"]=t.textColor,e["--hsk-chat-text"]=t.textColor),t.fontFamily&&(e["--hsk-font"]=t.fontFamily),t.fontSize&&(e["--hsk-font-size"]=t.fontSize),t.mobileFontSize&&(e["--hsk-mobile-font-size"]=t.mobileFontSize),t.borderRadius&&(e["--hsk-border-radius"]=t.borderRadius),{themeAttr:void 0,vars:e}}var dr="coffee",gr=["light","dark","mahogany","blush","coffee","midnight"];function Wt(t){return typeof t=="string"&&gr.includes(t)}function ui(t){if(Wt(t))return t;try{let e=typeof window<"u"?localStorage.getItem("akropolys_theme"):null;if(Wt(e))return e}catch{}return dr}var Zt="hsk-sounds",T=null,Y=null;function en(){try{return localStorage.getItem(Zt)!=="off"}catch{return!0}}function li(t){try{localStorage.setItem(Zt,t?"on":"off")}catch{}t&&tn()}function tn(){if(typeof window>"u")return;try{let e=navigator.audioSession;e&&e.type!=="playback"&&(e.type="playback")}catch{}if(T){T.state==="suspended"&&T.resume().catch(()=>{});return}let t=window.AudioContext||window.webkitAudioContext;if(t)try{T=new t({latencyHint:"interactive"}),Y=T.createGain(),Y.gain.value=.28,Y.connect(T.destination);let e=T.createBuffer(1,1,T.sampleRate),n=T.createBufferSource();n.buffer=e,n.connect(T.destination),n.start(0),T.resume().catch(()=>{})}catch{T=null}}function z(t,e,n,r,s){if(!T||!Y)return;let o=T.createOscillator();o.type="sine",o.frequency.setValueAtTime(e,t),o.frequency.exponentialRampToValueAtTime(Math.max(40,e*n),t+r);let i=T.createBiquadFilter();i.type="lowpass",i.Q.value=.9,i.frequency.setValueAtTime(Math.min(18e3,e*7),t),i.frequency.exponentialRampToValueAtTime(Math.max(80,e*1.5),t+r);let a=T.createGain();a.gain.setValueAtTime(1e-4,t),a.gain.exponentialRampToValueAtTime(s,t+.006),a.gain.exponentialRampToValueAtTime(1e-4,t+r),o.connect(i),i.connect(a),a.connect(Y),o.start(t),o.stop(t+r+.02)}function nn(t,e){if(!T||!Y)return;let n=Math.floor(T.sampleRate*.03),r=T.createBuffer(1,n,T.sampleRate),s=r.getChannelData(0);for(let u=0;u<n;u++)s[u]=(Math.random()*2-1)*Math.pow(1-u/n,3);let o=T.createBufferSource();o.buffer=r;let i=T.createBiquadFilter();i.type="bandpass",i.frequency.value=2600,i.Q.value=5;let a=T.createGain();a.gain.value=e,o.connect(i),i.connect(a),a.connect(Y),o.start(t)}function fi(){return en()?T?T.state:"unsupported":"off"}function pr(t){!T||!Y||(z(t,587.33,.985,.16,.38),z(t+.048,739.99,.985,.18,.42),z(t+.096,880,.985,.28,.46),z(t+.105,1174.66,.985,.22,.22),nn(t+.096,.16))}function hr(t){!T||!Y||z(t,659.25,.97,.09,.26)}function di(t,e=!1){if(!e&&!en()||(tn(),!T||!Y||T.state==="closed"))return;T.state==="suspended"&&T.resume().catch(()=>{});let n=T.currentTime+.01;switch(t){case"connect":pr(n);break;case"heard":hr(n);break;case"reply":z(n,440,.94,.13,.5),z(n+.09,660,.94,.16,.42);break;case"interrupt":z(n,520,.62,.17,.4);break;case"send":z(n,300,1.16,.1,.22);break;case"pin":nn(n,.35),z(n+.02,880,.97,.07,.22);break}}function rn(t){var e,n,r="";if(typeof t=="string"||typeof t=="number")r+=t;else if(typeof t=="object")if(Array.isArray(t)){var s=t.length;for(e=0;e<s;e++)t[e]&&(n=rn(t[e]))&&(r&&(r+=" "),r+=n)}else for(n in t)t[n]&&(r&&(r+=" "),r+=n);return r}function sn(){for(var t,e,n=0,r="",s=arguments.length;n<s;n++)(t=arguments[n])&&(e=rn(t))&&(r&&(r+=" "),r+=e);return r}function mi(...t){return sn(t)}var nt=D(V()),H=new Map;function rt(t,e="hsk-font"){let n=5381;for(let r=0;r<t.length;r++)n=(n<<5)+n+t.charCodeAt(r)>>>0;return`${e}-${n.toString(36)}`}function mr(t){let e=t.split("?")[0].split("#")[0].split(".").pop()?.toLowerCase();return e==="woff2"?"woff2":e==="woff"?"woff":e==="otf"?"opentype":e==="ttf"?"truetype":""}function st(t){let e=t.trim();return!e||/["'()\\\s]/.test(e)||/^(javascript|vbscript):/i.test(e)?null:e}var an=t=>/["\\{}<>;\n\r]/.test(t)?"":t.trim(),yr=/^[Uu]\+[0-9A-Fa-f?]{1,6}(-[0-9A-Fa-f]{1,6})?$/,on=t=>{let e=t.split(",").map(n=>n.trim()).filter(Boolean);return e.length===0||!e.every(n=>yr.test(n))?"":e.join(", ")},un=t=>/^\d{3}( \d{3})?$/.test(t)?t:"400";function vr(t,e){(0,nt.useEffect)(()=>{if(!t||!e||typeof document>"u")return;let n=rt(t);if(H.set(t,(H.get(t)??0)+1),!document.getElementById(n)){let r=document.createElement("style");r.id=n,r.textContent=e,document.head.appendChild(r)}return()=>{let r=(H.get(t)??1)-1;if(r>0){H.set(t,r);return}H.delete(t),document.getElementById(n)?.remove()}},[t,e])}function cn(t){let e=an(t.family);return e?t.faces.map(n=>{let r=st(n.url);return r?`@font-face{font-family:"${e}";font-style:normal;font-weight:${un(n.weight)};font-display:swap;src:url(${r}) format("woff2");`+(on(n.unicodeRange)?`unicode-range:${on(n.unicodeRange)};`:"")+"}":""}).join(""):""}function vi(t){let e=t?.faces??[],n=t&&e.length?cn(t):"";vr(n?`script|${t.family}|${e.map(r=>r.url).join("|")}`:"",n)}async function ki(t,e=0){if(typeof document>"u"||!("fonts"in document))return;let n=cn(t);if(!n)return;let r=`script|${t.family}|${t.faces.map(o=>o.url).join("|")}`;H.set(r,(H.get(r)??0)+1);let s=rt(r);if(!document.getElementById(s)){let o=document.createElement("style");o.id=s,o.textContent=n,document.head.appendChild(o)}if(e>0){let o=document.fonts,i=t.family.replace(/^['"]|['"]$/g,""),a=Array.from(o||[]).filter(c=>c.family.replace(/^['"]|['"]$/g,"")===i),u=a.length>0?a.map(c=>c.load().catch(()=>{})):t.faces.map(c=>{let h=st(c.url);if(!h)return Promise.resolve();try{return new window.FontFace(i,`url(${h})`,{weight:un(c.weight),style:"normal"}).load().then(y=>{document.fonts?.add(y)}).catch(()=>{})}catch{return Promise.resolve()}});await Promise.race([Promise.all(u),new Promise(c=>setTimeout(c,e))])}}var ln=["400","500","600","700"];function fn(t,e){let n=Array.from(new Set(Array.from(Object.values(e).join("")))).join(""),r=t.map(s=>`"${s.replace(/^['"]|['"]$/g,"")}"`).join(", ");return{text:n,stack:r}}function Si(t,e){let n=typeof document<"u"?document.fonts:null,{text:r,stack:s}=fn(t,e);if(!n?.check||!r||!s)return!0;try{return ln.every(o=>n.check(`${o} 16px ${s}`,r))}catch{return!0}}async function wi(t,e,n){let r=typeof document<"u"?document.fonts:null;if(!r?.load)return;let{text:s,stack:o}=fn(t,e);!s||!o||await Promise.race([Promise.all(ln.map(i=>r.load(`${i} 16px ${o}`,s).catch(()=>{}))),new Promise(i=>setTimeout(i,n))])}function Ii(t){let e=typeof t=="object"&&t?t:void 0,n=an(e?.fontFamily?.split(",")[0].trim().replace(/^['"]|['"]$/g,"")??""),r=typeof e?.fontUrl=="string"?{normal:e.fontUrl}:e?.fontUrl??{},s=r.normal??"",o=r.bold??"",i=r.variable??"";(0,nt.useEffect)(()=>{if(!n||!s&&!o&&!i)return;let a=i?[["100 900",i]]:[["400",s],["700",o]],u=[];for(let[y,A]of a){if(!A)continue;let _=st(A);if(!_)continue;let L=mr(_);u.push(`@font-face{font-family:"${n}";font-style:normal;font-weight:${y};font-display:swap;src:url(${_})${L?` format("${L}")`:""};}`)}if(u.length===0)return;let c=u.join(""),h=`${n}|${s}|${o}|${i}`,b=rt(h,"hsk-host-font");if(H.set(h,(H.get(h)??0)+1),!document.getElementById(b)){let y=document.createElement("style");y.id=b,y.textContent=c,document.head.appendChild(y)}return()=>{let y=(H.get(h)??1)-1;if(y>0){H.set(h,y);return}H.delete(h),document.getElementById(b)?.remove()}},[n,s,o,i])}export{Re as a,D as b,V as c,ue as d,He as e,Ie as f,je as g,Kt as h,se as i,qt as j,Bt as k,zt as l,sr as m,ir as n,or as o,ar as p,ur as q,Ze as r,lr as s,Qt as t,oi as u,ui as v,en as w,li as x,tn as y,fi as z,di as A,mi as B,vi as C,ki as D,Si as E,wi as F,Ii as G};
|
|
14
14
|
/*! Bundled license information:
|
|
15
15
|
|