1/* AUTO-GENERATED by tools/build-js-bundles.mjs â do not edit by hand. */ 2/* Entry: JS/bundle-entries/beamo-core.ts */ 3globalThis.Beamo = globalThis.Beamo || {}; 4"use strict";(()=>{var oa=Object.freeze,od=Object.defineProperty;var xs=(e,t)=>oa(od(e,"raw",{value:oa(t||e.slice())}));var Xe={endpoints:{search:"/PHP/api_request.php",searchStatus:"/PHP/search_status.php",publicStatus:"/PHP/status.php",instant:"/PHP/instant.php",location:"/PHP/location.php",searchAnalyticsInsights:"/PHP/search_analytics_insights.php",suggest:"/PHP/suggest.php",chat:"/PHP/chat.php",chatSync:"/PHP/chatsync.php",chatImport:"/PHP/chatimport.php",chatSeed:"/PHP/chatseed.php",chatRestore:"/PHP/chatrestore.php",summary:"/PHP/summary.php",urlAsk:"/PHP/url_ask.php",research:"/PHP/research.php",translate:"/PHP/translate.php",tts:"/PHP/tts.php",languageTools:"/PHP/language_tools.php",calcAssist:"/PHP/calc_assist.php",elementAsk:"/PHP/element_ask.php",anagram:"/PHP/anagram.php",holidays:"/PHP/holidays.php",earthquakes:"/PHP/earthquakes.php",countryStats:"/PHP/country_stats.php",tides:"/PHP/tides.php",hurricanes:"/PHP/hurricanes.php",packageLookup:"/PHP/package.php",recipe:"/PHP/recipe.php",entity:"/PHP/entity.php",xkcd:"/PHP/xkcd.php",apod:"/PHP/apod.php",onthisday:"/PHP/onthisday.php",sports:"/PHP/sports.php",stocks:"/PHP/stocks.php",topCompanies:"/PHP/topcompanies.php",watches:"/PHP/watches.php",emailMfa:"/PHP/email_mfa.php",overviewGate:"/PHP/overview_gate.php",layoutGate:"/PHP/layout_gate.php",overviewMedia:"/PHP/overview_media.php",deleteChat:"/PHP/deletechat.php",cancelChat:"/PHP/chatcancel.php",feedbackReport:"/PHP/feedback_report.php",feedbackIntent:"/PHP/feedback_intent.php",overviewFeedback:"/PHP/overview_feedback.php",audienceBeacon:"/PHP/audience_beacon.php",instantAnalytics:"/PHP/instant_analytics.php"},pages:{home:"/",results:"/results",account:"/account",settings:"/settings",accountVerify:"/account-verify",accountReset:"/account-reset",yourData:"/your-data",calculator:"/calculator"},storageKeys:{lastSearchType:"lastSearchType",searchHistory:"beamo-search-history",searchFilters:"beamo-search-filters",apiData:"apiData",assistantResponsePrefix:"response-",layoutGatePrefix:"layout-gate-v4-",overviewMediaPrefix:"overview-media-",overviewFeedback:"beamo-overview-feedback",homeChatLayout:"beamoHomeChatLayout",chatAutoSendSearch:"beamoChatAutoSendSearch",chatIncludeSearchPrefix:"beamoChatIncludeSearch:",chatCiteOnly:"beamo-chat-cite-only",savedSearches:"beamo-saved-searches",sitePreferences:"beamo-site-preferences",weatherUnits:"beamo-weather-units",uiLocale:"beamo-ui-locale",aiPreset:"beamo-ai-preset",aiPresetAuto:"beamo-ai-preset-auto",usageSearchCount:"beamo-usage-search-count",upsellAccountLastShown:"beamo-upsell-account-last-shown",upsellProLastShown:"beamo-upsell-pro-last-shown",deepReasoningProvider:"beamo-deep-reasoning-provider",deepOverview:"beamo-deep-overview",customInstructions:"beamo-custom-instructions",searchOnlyMode:"beamo-search-only-mode",aiFeatures:"beamo-ai-features",alwaysShowResults:"beamo-always-show-results",searchUpstreamDismissUntil:"beamo-search-upstream-dismiss-until",aiUpstreamDismissUntil:"beamo-ai-upstream-dismiss-until",syncRecentHistory:"beamo-accounts-sync-recent-history",syncLocalDirty:"beamo-sync-local-dirty",syncLocalErase:"beamo-sync-local-erase",syncLocalOwner:"beamo-sync-local-owner",supabaseSession:"beamo-supabase-session",accountPlan:"beamo-account-plan",legalConsent:"beamo-legal-consent"},messages:{chatConnectionError:"Sorry, there was an error connecting to the server. Please try again.",chatPartialSaved:"This reply may be incomplete. It was saved to your chat history \u2014 you can retry for a full answer."},timeouts:{chatDeleteMs:5e3,chatMs:6e4,chatAutoRetryBaseMs:1500,fetchDefaultMs:8e3,suggestMs:5e3,suggestDebounceMs:200,speculativeSearchDebounceMs:450,summaryMs:3e4,summaryAuthMs:1500,urlAskMs:45e3,researchMs:18e4,researchIdleMs:45e3,researchStatusMs:8e3,layoutGateMs:2500,overviewMediaMs:2e3,accountAuthMs:12e3,accountSyncMs:12e3,definitionMs:5e3,weatherMs:8e3,weatherAlertsMs:3500,instantMs:8e3,sportsMs:8e3,stocksMs:8e3,topCompaniesMs:8e3,wat
4chesMs:8e3,conversionMs:6e3,geocodeMs:6e3,thesaurusMs:6e3,sunMs:8e3,airQualityMs:8e3,translateMs:12e3,languageToolsMs:14e3,calcAssistMs:25e3,elementAskMs:25e3,anagramMs:8e3,holidaysMs:8e3,onthisdayMs:8e3},limits:{searchHistoryMax:12,searchHistorySuggestMax:6,suggestMinChars:2,suggestMax:8,suggestPanelMax:10,savedSearchesMax:50,savedSearchesProMax:500,searchHistoryProMax:100,accountPasswordMin:8},extension:{productionOrigin:"https://beamosearch.com",chromeExtensionId:"ghfpmfejffpjebfokeikjimnommbpaon",chromeWebStoreUrl:"https://chromewebstore.google.com/detail/beamo-search/ghfpmfejffpjebfokeikjimnommbpaon"},external:{dictionaryApi:"https://api.dictionaryapi.dev/api/v2/entries/en/",openMeteoGeocoding:"https://geocoding-api.open-meteo.com/v1/search",nominatimSearch:"https://nominatim.openstreetmap.org/search",mapboxGeocoding:"https://api.mapbox.com/geocoding/v5/mapbox.places",mapboxSearchBox:"https://api.mapbox.com/search/searchbox/v1/forward",openMeteoForecast:"https://api.open-meteo.com/v1/forecast",openMeteoAirQuality:"https://air-quality-api.open-meteo.com/v1/air-quality",weatherGovApi:"https://api.weather.gov",frankfurterApi:"https://api.frankfurter.dev/v1/latest",exchangeRateApi:"https://open.er-api.com/v6/latest",datamuseApi:"https://api.datamuse.com/words",wiktionaryApi:"https://en.wiktionary.org/w/api.php",osrmRoute:"https://router.project-osrm.org/route/v1"}};function aa(e){e.config=Xe}function oe(e=globalThis.Beamo){let t=e?.config&&typeof e.config=="object"?e.config:{};return{...Xe,...t,endpoints:{...Xe.endpoints,...t.endpoints},pages:{...Xe.pages,...t.pages},storageKeys:{...Xe.storageKeys,...t.storageKeys},messages:{...Xe.messages,...t.messages},timeouts:{...Xe.timeouts,...t.timeouts},limits:{...Xe.limits,...t.limits},external:{...Xe.external,...t.external},extension:{...Xe.extension,...t.extension}}}function ia(e){let t=e.process;return e===globalThis&&typeof t?.versions?.node=="string"}function Rs(e=globalThis){if(ia(e))return null;try{return e?.sessionStorage||null}catch{return null}}function Ps(e=globalThis){if(ia(e))return null;try{return e?.localStorage||null}catch{return null}}function te(e,t,n=null){try{return Ps(e)?.getItem(t)??n}catch{return n}}function ie(e,t,n){try{let r=Ps(e);return r?(r.setItem(t,n),!0):!1}catch{return!1}}function ca(e,t){try{Ps(e)?.removeItem(t)}catch{}}function Je(e,t,n=null){try{return Rs(e)?.getItem(t)??n}catch{return n}}function Qe(e,t,n){try{let r=Rs(e);return r?(r.setItem(t,n),!0):!1}catch{return!1}}function la(e,t){try{Rs(e)?.removeItem(t)}catch{}}var ad=30,id=100;function ua(e=globalThis.Beamo){let t=Number(e?.chatHistoryLimit);return Number.isFinite(t)&&t>0?t:cd(e)?id:ad}function cd(e){let t=e?.accounts;return typeof t?.getState=="function"?t.getState().signedIn===!0:t?.isSignedIn?.()===!0}function da({variant:e="panel"}={}){return e==="panel"?"Ask a follow-up about your search, or switch to general chat below. Clear chat anytime to reset the session.":"Ask a question, explore your search, or get a quick summary. Clear chat resets this session."}function fa(e,t=80){let n=String(e??"").trim().replace(/\s+/g," ");return n?n.length<=t?n:"".concat(n.slice(0,Math.max(1,t-1)),"\u2026"):""}function ma({searchTerm:e="",messages:t=[],serverTitle:n="",fallbackTitle:r="Chat with Beamo"}={}){let s=String(n??"").trim();if(s)return s;let o=fa(e);if(o)return o;if(Array.isArray(t)){for(let a of t)if(a?.role==="user"&&String(a.content??"").trim())return fa(a.content)||r}return r}async function pr(e,t){let n=String(t??"").trim();if(!n)return!1;try{if(e.navigator?.clipboard?.writeText)return await e.navigator.clipboard.writeText(n),!0}catch{}let r=e.document;if(!r?.body)return!1;let s=r.createElement("textarea");s.value=n,s.setAttribute("readonly",""),s.style.position="fixed",s.style.left="-9999px",r.body.appendChild(s),s.select();let o=!1;try{o=r.execCommand("copy")}catch{o=!1}return s.remove(),o}var ld=/^[A-Za-z0-9_-]{8,64}$/,ha=new Set(["rate_limited","upstream_quota_exhausted","upstream_circuit_open"]);function an(e){if(!e||typeof e!="object")return"";let t=e.request_id;if(typeof t!="string")return"";let n=t.trim();return ld.test(n)?n:""}function Oe(e){let t=Number(e);return!Number.isFinite(t)||t<=0?0:Math.min(Math.max(1,Math.ceil(t)),86400)}function pa(e){if(e==null)return 0;let t=String(e).trim();if(t==="")return 0;let n=Number(t);if(Number.isFinite(n)&&n>0)return Oe(n);let r=Date.parse(t);return Number.isFinite(r)?Oe((r-Date.now())/1e3):0}function gr(e,t=0){if(!e||typeof e!="object")return Oe(t);let n=Oe(e.retry_after);return n>0?n:Oe(t)}function _t(e){return ha.has(String(e||"").trim())}function Ze(e,t){if(!e||typeof e!="object")return null;let n=e;if(n.status==="error"&&n.error&&typeof n.error=="object"){let r=n.error,s=typeof r.message=="string"&&r.message.trim()!==""?r.message.trim():typeof n.message=="string"&&n.message.trim()!==""?n.message.trim():"Request failed.",o=typeof r.code=="string"&&r.code.trim()!==""?r.code.trim():"request_failed",a=Number.isFinite(Number(r.http_status))?Number(r.http_status):void 0,i=r.details&&typeof r.details=="object"?r.details:{},c=gr(i);return{message:s,code:o,httpStatus:a,requestId:an(i),details:i,retryAfterSeconds:c,isThrottled:_t(o)&&c>0}}if(typeof n.error=="string"&&n.error.trim()!==""){let r=n.details&&typeof n.details=="object"?n.details:{},s="request_failed",o=gr(r);return{message:n.error.trim(),code:s,requestId:an(r),details:r,retryAfterSeconds:o,isThrottled:!1}}if(n.error&&typeof n.error=="object"){let r=n.error;if(typeof r.message=="string"&&r.message.trim()!==""){let s=r.details&&typeof r.details=="object"?r.details:{},o=typeof r.code=="string"&&r.code.trim()!==""?r.code.trim():"request_failed",a=gr(s);return{message:r.message.trim(),code:o,httpStatus:Number.isFinite(Number(r.http_status))?Number(r.http_status):void 0,requestId:an(s),details:s,retryAfterSeconds:a,isThrottled:_t(o)&&a>0}}}return null}function cn(e,t=null){let n=Ze(e);if(!n)return null;let r=t?.headers?.get?pa(t.headers.get("Retry-After")):0,s=Math.max(n.retryAfterSeconds,r);return{...n,retryAfterSeconds:s,isThrottled:_t(n.code)&&s>0}}function yr(e,t=null,n="Request failed."){let r=cn(e,t),s=r?.message||(e&&typeof e=="object"&&typeof e.message=="string"?e.message.trim():"")||n,o=new Error(s);return o.userFacing=!0,o.code=r?.code||"request_failed",o.requestId=r?.requestId||(t?.headers?.get?.("x-request-id")||"").trim(),o.retryAfterSeconds=r?.retryAfterSeconds||0,o.isThrottled=!!r?.isThrottled,o.httpStatus=r?.httpStatus??(t?.status||void 0),o}function ud(e){return typeof e=="string"?{requestId:e.trim(),retryAfterSeconds:0,errorCode:""}:e&&typeof e=="object"?{requestId:String(e.requestId??"").trim(),retryAfterSeconds:Oe(e.retryAfterSeconds),errorCode:String(e.errorCode??e.code??"").trim()}:{requestId:"",retryAfterSeconds:0,errorCode:""}}function Is(e,t="Retry",n=globalThis){let r=Oe(e),s=n?.Beamo?.i18n?.t,o=typeof s=="function"?s("errors.retry"):t;return r<=0?o:typeof s=="function"?r===1?s("errors.tryAgainOneSecond"):s("errors.tryAgainSeconds",{seconds:r}):r===1?"Try again in 1 second":"Try again in ".concat(r," seconds")}function ln(e,t="Request failed."){let n=Ze(e);if(n)return n.message;if(e&&typeof e=="object"&&typeof e.message=="string"){let r=e.message.trim();if(r!=="")return r}return t}function Ct(e){let t=Ze(e);if(t?.requestId)return t.requestId;if(!e||typeof e!="object")return"";let n=e;return an(n.details)||an(n.error&&typeof n.error=="object"?n.error.details:null)||(typeof n.request_id=="string"?an({request_id:n.request_id}):"")}function br(e,t,n,r={}){let s=String(e||"request_failed").trim()||"request_failed",o=String(t||"Request failed.").trim()||"Request failed.",a=Number.isFinite(Number(n))?Number(n):500,i=r&&typeof r=="object"?{...r}:{};return{status:"error",message:o,error:{code:s,message:o,http_status:a,...Object.keys(i).length>0?{details:i}:{}}}}function ga(e){e.THROTTLED_API_ERROR_CODES=ha,e.parseApiErrorPayload=Ze,e.parseApiErrorFromResponse=cn,e.createApiError=yr,e.normalizeRetryAfterSeconds=Oe,e.parseRetryAfterHeader=pa,e.retryAfterSecondsFromDetails=gr,e.isThrottledApiErrorC
4ode=_t,e.normalizeRetryMeta=ud,e.formatRetryCountdownLabel=Is,e.errorMessageFromPayload=ln,e.requestIdFromPayload=Ct,e.buildApiErrorEnvelope=br}var ya=10,dd=2e3;async function ba(e,t={},n=oe(e.Beamo)){let r=e.fetch;if(typeof r!="function")return{ok:!1,error:"Feedback is unavailable in this browser."};let s=String(t.message??"").trim();if(s.length<ya)return{ok:!1,error:"Please enter at least ".concat(ya," characters.")};let o=n?.endpoints?.feedbackReport||"/PHP/feedback_report.php",a={source:String(t.source??"").slice(0,80),message:s.slice(0,dd),search_term:String(t.searchTerm??t.search_term??"").slice(0,200),api_type:String(t.apiType??t.api_type??"").slice(0,20),overview_rating:String(t.overviewRating??t.overview_rating??"").slice(0,8),chat_turn_id:String(t.chatTurnId??t.chat_turn_id??"").slice(0,64),page_url:String(t.pageUrl??t.page_url??"").slice(0,480),zero_results:t.zeroResults===!0,_hp:""};if(!a.source)return{ok:!1,error:"Missing feedback context."};let i;try{i=await r(o,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)})}catch{return{ok:!1,error:"Network error. Please try again."}}let c=await i.text(),l=null;try{l=c?JSON.parse(c):null}catch{l=null}return i.ok&&l?.recorded===!0?{ok:!0}:{ok:!1,error:Ze(l,i.status)?.message||"Could not send your report. Please try again."}}function wa(e,t={},n=oe(e.Beamo)){let r=e.fetch;if(typeof r!="function")return;let s=String(t.source??"").trim().slice(0,80);if(!s)return;let o=n?.endpoints?.feedbackIntent||"/PHP/feedback_intent.php",a={source:s,search_term:String(t.searchTerm??t.search_term??"").slice(0,200),api_type:String(t.apiType??t.api_type??"").slice(0,20),zero_results:t.zeroResults===!0};try{r(o,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),keepalive:!0}).catch(()=>{})}catch{}}function Sa(e,t=480){let n=String(e?.location?.href??"").trim();return n?n.slice(0,t):""}function ka(e){let t=new URLSearchParams(String(e?.location?.search??""));return(t.get("searchTerm")||t.get("q")||"").trim()}var it=null;function fd(e){return!!(e&&typeof e.showModal=="function"&&typeof e.close=="function")}function va(e){let t=e.document?.getElementById("beamo-feedback-dialog")??null;return fd(t)?t:null}function _a(e){return e.document?.getElementById("beamo-feedback-form")??null}function md(e,t=""){return e==="wrong_summary"?t==="down"?"overview_thumbs_down":"overview_report":e==="chat_report"?"chat_report":"settings"}function wr(e,t,{isError:n=!1}={}){let r=e?.querySelector("#beamo-feedback-status");if(r){if(!t){r.hidden=!0,r.textContent="",r.classList.remove("is-error","is-success");return}r.hidden=!1,r.textContent=t,r.classList.toggle("is-error",n),r.classList.toggle("is-success",!n)}}function Ns(e){if(!e)return;e.reset(),wr(e,"");let t=e.querySelector(".beamo-feedback-dialog__submit");t instanceof HTMLButtonElement&&(t.disabled=!1)}function Ca(e=globalThis,t={}){let n=va(e),r=_a(e);if(!n||!r)return!1;let s=String(t.kind??"general"),o=String(t.overviewRating??t.rating??"").trim(),a=String(t.source??"").trim()||md(s,o),i=String(t.searchTerm??ka(e)).trim(),c=String(t.apiType??new URLSearchParams(e.location?.search||"").get("type")??"web").trim(),l=String(t.chatTurnId??t.turnId??"").trim();it={source:a,searchTerm:i,apiType:c,overviewRating:o==="up"||o==="down"?o:"",chatTurnId:l,zeroResults:t.zeroResults===!0},wa(e,{source:a,searchTerm:i,apiType:c,zeroResults:t.zeroResults===!0}),Ns(r),typeof n.showModal=="function"&&n.showModal();let m=r.querySelector("#beamo-feedback-message");return m instanceof HTMLTextAreaElement&&m.focus(),!0}function Aa(e=globalThis){let t=va(e),n=_a(e);if(!(!t||!n)&&t.dataset.beamoFeedbackFormBound!=="true"){t.dataset.beamoFeedbackFormBound="true";for(let r of n.querySelectorAll("[data-beamo-feedback-close]"))r.addEventListener("click",()=>{t.open&&t.close()});n.addEventListener("submit",r=>{if(r.preventDefault(),!it)return;let s=n.querySelector("#beamo-feedback-message"),o=s instanceof HTMLTextAreaElement?s.value:"",a=n.querySelector(".beamo-feedback-dialog__submit");a instanceof HTMLButtonElement&&(a.disabled=!0),wr(n,"Sending\u2026"),(async()=>{let i=await ba(e,{source:it.source,message:o,searchTerm:it.searchTerm,apiType:it.apiType,overviewRating:it.overviewRating,chatTurnId:it.chatTurnId,pageUrl:Sa(e),zeroResults:it.zeroResults});if(i.ok){wr(n,"Thanks \u2014 your report was sent.",{isError:!1}),e.setTimeout(()=>{t.close(),Ns(n)},1200);return}wr(n,i.error||"Could not send your report.",{isError:!0}),a instanceof HTMLButtonElement&&(a.disabled=!1)})()}),t.addEventListener("close",()=>{Ns(n),it=null})}}function hd(e){if(!e)return"";let t=e.cloneNode(!0);for(let n of[".chat-message-actions",".chat-partial-notice",".retry-action"])for(let r of t.querySelectorAll(n))r.remove();return t.textContent.replace(/\s+/g," ").trim()}function pd(e,t){let n=t.CSS;return n&&typeof n.escape=="function"?n.escape(e):e.replace(/["\\]/g,"\\$&")}
4function gd(e,t,n=globalThis){if(!e||!t)return"";let r=null;try{r=e.querySelector('.user-msg-text[data-turn-id="'.concat(pd(t,n),'"]'))}catch{return""}return r?.textContent?.trim()||""}function yd(e=globalThis){let t=e.document?.getElementById("chat-interface");return!!(t?.classList.contains("chat-panel")||t?.classList.contains("chat-home"))}function Hn({beamo:e=globalThis.Beamo,global:t=globalThis,messageElement:n,chatContainer:r,chatInput:s,turnId:o="",userMessage:a="",searchTerm:i="",onRegenerate:c}={}){if(!n||!yd(t))return null;n.querySelector(".chat-message-actions")?.remove();let l=o||n.dataset.turnId||"",m=a||gd(r,l,t);if(!l||!m||typeof c!="function")return null;let u=document.createElement("div");u.className="chat-message-actions",u.setAttribute("role","toolbar"),u.setAttribute("aria-label","Message actions");function d({action:A,label:S,icon:_,isLink:w=!1,href:f=""}){if(w){let T=document.createElement("a");T.className="chat-message-actions__btn",T.href=f,T.target="_blank",T.rel="noopener noreferrer",T.setAttribute("data-chat-action",A),T.setAttribute("aria-label",S),typeof e.createIcon=="function"&&T.appendChild(e.createIcon(_,"beamo-icon"));let x=document.createElement("span");return x.className="chat-message-actions__label",x.textContent=S,T.appendChild(x),T}let g=document.createElement("button");g.type="button",g.className="chat-message-actions__btn",g.setAttribute("data-chat-action",A),g.setAttribute("aria-label",S),typeof e.createIcon=="function"&&g.appendChild(e.createIcon(_,"beamo-icon"));let C=document.createElement("span");return C.className="chat-message-actions__label",C.textContent=S,g.appendChild(C),g}let h=d({action:"copy",label:"Copy",icon:"copy"}),p=d({action:"regenerate",label:"Regenerate",icon:"refresh"}),b=d({action:"deeper",label:"More depth",icon:"sparkles"}),v=d({action:"report",label:"Report",icon:"external"});v.addEventListener("click",()=>{Ca(t,{kind:"chat_report",searchTerm:i,chatTurnId:l,apiType:"chat"})}),u.append(h,p,b,v),n.appendChild(u),e.icons?.mount?.(u);let E=null;return h.addEventListener("click",()=>{(async()=>{let A=hd(n);!A||!await pr(t,A)||(h.classList.add("is-success"),h.querySelector(".chat-message-actions__label").textContent="Copied",E&&t.clearTimeout(E),E=t.setTimeout(()=>{h.classList.remove("is-success"),h.querySelector(".chat-message-actions__label").textContent="Copy",E=null},2e3))})()}),p.addEventListener("click",()=>{t.document.getElementById("chat-interface")?.getAttribute("aria-busy")!=="true"&&c({mode:"regenerate",turnId:l,userMessage:m,messageElement:n,chatContainer:r,chatInput:s})}),b.addEventListener("click",()=>{t.document.getElementById("chat-interface")?.getAttribute("aria-busy")!=="true"&&c({mode:"deeper",turnId:l,userMessage:m,messageElement:n,chatContainer:r,chatInput:s})}),u}var wd=Object.freeze(["q","type","offset","country","lang","hl","safesearch","freshness","strictQuery"]),Ea=Object.freeze(["token"]),Sd=Object.freeze({q:["query","search"],type:["tab","result_type"],offset:["page_offset"],country:["region"],lang:["search_lang","language"],hl:["ui_lang","uiLang","locale"],strictQuery:["strict_query"],token:["verify_token","reset_token"]}),$y=Object.freeze({home:{path:"/",keys:[],notes:"Omnibox submit navigates to results with q."},results:{path:"/results",keys:wd,notes:"Primary search surface; use buildResultsPath() for parity."},"account-verify":{path:"/account-verify",keys:Ea,notes:"Email verification link; canonical param token."},"account-reset":{path:"/account-reset",keys:Ea,notes:"Password reset link; canonical param token."}});function Ta(e){if(e instanceof URLSearchParams)return new URLSearchParams(e);if(typeof e=="string"){let n=e.startsWith("?")?e.slice(1):e;return new URLSearchParams(n)}let t=new URLSearchParams;for(let[n,r]of Object.entries(e||{}))if(r!=null){if(Array.isArray(r)){let s=r.find(o=>o!=null&&String(o).trim()!=="");s!=null&&t.set(n,String(s));continue}t.set(n,String(r))}return t}function Sr(e,t){let n=(e.get(t)||"").trim();if(n)return n;for(let r of Sd[t]||[]){let s=(e.get(r)||"").trim();if(s)return s}return""}var kd="beamo:site-preferences-change",vd=200,_d=100,Cd=2160*60*60*1e3,Ad=new Set(["pin","boost","block","none"]);function xa(e){return e?.storageKeys?.sitePreferences||"beamo-site-preferences"}function Ed(e){let t=String(e??"").trim().toLowerCase();return Ad.has(t)?t:""}function Td(e){let t=String(e??"").trim().toLowerCase();if(!t||t.length>500)return"";t.startsWith("//")&&(t="https:".concat(t)),t.includes("://")||(t="https://".concat(t));let n="";try{n=new URL(t).hostname}catch{return""}return n=n.replace(/\.+$/,"").replace(/^www\./,""),!n||n.length>253||!n.includes(".")||!/^[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?(\.[a-z0-9_]([a-z0-9_-]*[a-z0-9_])?)+$/.test(n)?"":n}function Ra(e){let t=Td(e?.domain);if(!t)return null;let n=Ed(e?.action);return n?{domain:t,action:n,ts:Number(e?.ts)||0}:null}function Pa(e,t){let n=te(e,xa(t),"");if(!n)return[];try{let r=JSON.parse(n);if(!Array.isArray(r))return[];let s=new Set,o=[];for(let a of r){let i=Ra(a);i&&!s.has(i.domain)&&(s.add(i.domain),o.push(i))}return o}catch{return[]}}
4function xd(e,t,n){ie(e,xa(t),JSON.stringify(n))}function Ia(e,t){return Pa(e,t)}function kr(e,t,n){let r=Ls(Array.isArray(n)?n:[],[]),s=JSON.stringify(Pa(e,t));return xd(e,t,r),JSON.stringify(r)!==s&&Pd(e),r}function Ls(e,t,{maxActive:n=vd,maxTombstones:r=_d,now:s=Date.now()}={}){let o=new Map;for(let l of[...t||[],...e||[]]){let m=Ra(l);if(!m)continue;let u=o.get(m.domain);(!u||m.ts>=u.ts)&&o.set(m.domain,m)}let a=[...o.values()].sort((l,m)=>m.ts-l.ts||l.domain.localeCompare(m.domain)),i=a.filter(l=>l.action!=="none").slice(0,n),c=a.filter(l=>l.action==="none"&&s-l.ts<Cd).slice(0,r);return[...i,...c].sort((l,m)=>m.ts-l.ts||l.domain.localeCompare(m.domain))}function Rd(e){let t=e.Beamo||(e.Beamo={});return t.__sitePreferenceListeners||(t.__sitePreferenceListeners=new Set),t.__sitePreferenceListeners}function Pd(e){let t=e;for(let n of Rd(t))try{n()}catch{}try{t.dispatchEvent?.(new CustomEvent(kd))}catch{}}function F(e){return typeof e=="string"?e:typeof e=="number"?String(e):""}function At(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Na(e){let t=e??null,n=F(t?.name).trim();if(!t||!n)return null;let r=[];if(Array.isArray(t.linescores))for(let o of t.linescores){let a=F(o).trim();a!==""&&r.push(a)}let s=F(t.color).trim();return{id:F(t.id),abbreviation:F(t.abbreviation),name:n,shortName:F(t.shortName)||n,logo:F(t.logo),color:/^#[0-9a-fA-F]{6}$/.test(s)?s.toLowerCase():"",score:F(t.score),winner:t.winner===!0,record:F(t.record),linescores:r,hits:At(t.hits),errors:At(t.errors)}}function Id(e){let t=e??null;if(!t)return null;let n={balls:At(t.balls),strikes:At(t.strikes),outs:At(t.outs),onFirst:t.onFirst===!0,onSecond:t.onSecond===!0,onThird:t.onThird===!0,isRedZone:t.isRedZone===!0,downDistance:F(t.downDistance),possession:F(t.possession),lastPlay:F(t.lastPlay)};return n.balls!==null||n.strikes!==null||n.outs!==null||n.onFirst||n.onSecond||n.onThird||n.downDistance!==""||n.possession!==""||n.lastPlay!==""?n:null}function Nd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=n??null,s=F(r?.player).trim();!r||s===""||t.push({team:F(r.team),player:s,clock:F(r.clock),kind:r.kind==="own-goal"||r.kind==="penalty"?r.kind:"goal"})}return t}function Ld(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=F(n).trim();r!==""&&!t.includes(r)&&t.push(r)}return t.slice(0,4)}function Md(e){let t=e??null;if(!t)return null;let n=F(t.line).trim(),r=F(t.overUnder).trim();return n===""&&r===""?null:{line:n,overUnder:r}}function Bd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=n??null,s=F(r?.athlete).trim(),o=F(r?.value).trim();if(!r||s===""||o==="")continue;let a=r.side==="home"||r.side==="away"?r.side:"";if(t.push({label:F(r.label),athlete:s,value:o,side:a}),t.length>=3)break}return t}function Od(e){let t=e??null;if(!t)return null;let n=At(t.home),r=At(t.away);if(n===null||r===null)return null;let s=o=>Math.max(0,Math.min(100,Math.round(o)));return{home:s(n),away:s(r)}}function Oa(e){let t=e??null;if(!t)return null;let n=Na(t.home),r=Na(t.away),s=F(t.date).trim();if(!n||!r||!s)return null;let o=t.state==="in"||t.state==="post"?t.state:"pre";return{id:F(t.id),date:s,state:o,completed:t.completed===!0||o==="post",status:F(t.status),detail:F(t.detail),clock:F(t.clock),period:Number.isFinite(Number(t.period))?Number(t.period):0,note:F(t.note),venue:F(t.venue),venueCity:F(t.venueCity),broadcast:F(t.broadcast),broadcasts:Ld(t.broadcasts),link:F(t.link),home:n,away:r,situation:Id(t.situation),scorers:Nd(t.scorers),odds:Md(t.odds),leaders:Bd(t.leaders),attendance:At(t.attendance),winProbability:Od(t.winProbability)}}function Dd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=n??null;if(!r||!Array.isArray(r.rows))continue;let s=[];for(let o of r.rows){let a=o??null,i=a?.team??null,c=F(i?.name).trim();if(!a||!c)continue;let l={},m=a.stats??null;for(let[u,d]of Object.entries(m??{}))l[u]=F(d);s.push({rank:Number.isFinite(Number(a.rank))?Number(a.rank):0,team:{id:F(i?.id),name:c,shortName:F(i?.shortName)||c,abbreviation:F(i?.abbreviation),logo:F(i?.logo)},stats:l})}s.length>0&&t.push({name:F(r.name),soccer:r.soccer===!0,rows:s})}return t}function Hd(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let r=n??null;if(!r||!Array.isArray(r.rows))continue;let s=[];for(let a of r.rows){let i=a??null,c=F(i?.athlete).trim(),l=F(i?.value).trim();!i||!c||!l||s.push({rank:Number.isFinite(Number(i.rank))&&Number(i.rank)>0?Number(i.rank):s.length+1,athlete:c,team:F(i.team),value:l})}let o=F(r.label).trim()||F(r.key).trim();s.length>0&&o&&t.push({key:F(r.key),label:o,abbreviation:F(r.abbreviation),rows:s})}return t}function Da(e){return e==="in"||e==="post"?e:"pre"}function La(e){let t=e??null,n=F(t?.name).trim();return!t||!n?null:{id:F(t.id),name:n,shortName:F(t.shortName)||n,date:F(t.date),state:Da(t.state),status:F(t.status),venue:F(t.venue),broadcast:F(t.broadcast),link:F(t.link)}}function Ma(e){let t=e??null,n=F(t?.name).trim();return!t||!n?null:{name:n,winner:t.winner===!0,score:F(t.score)}}function $d(e){let t=e??null;if(!t)return null;let n=Ma(t.a),r=Ma(t.b);return!n||!r?null:{round:F(t.round),note:F(t.note),state:Da(t.state),status:F(t.status),date:F(t.date),a:n,b:r,link:F(t.link)}}function Fd(e){let t=e??null,n=F(t?.name).trim();return!t||!n?null:{pos:Number.isFinite(Number(t.pos))?Number(t.pos):0,name:n,detail:F(t.detail),score:F(t.score),winner:t.winner===!0}}function qd(e,t){let n=La(e.event);if(!n)return null;let r=e.format==="leaderboard"?"leaderboard":"matches",s=[];if(Array.isArray(e.leaderboard))for(let l of e.leaderboard){let m=Fd(l);m&&s.push(m)}let o=[];if(Array.isArray(e.matches))for(let l of e.matches){let m=$d(l);m&&o.push(m)}if(!(r==="leaderboard"?s.length>0:o.length>0)&&n.state!=="post")return null;let i=[];
4if(Array.isArray(e.others))for(let l of e.others){let m=La(l);m&&i.push(m)}let c=e.league??null;return{show:!0,kind:"event",asOf:F(e.asOf),poll:Number.isFinite(Number(e.poll))?Math.max(0,Number(e.poll)):0,league:{key:F(c?.key),name:t,fullName:F(c?.fullName)||t,sport:F(c?.sport)},team:null,series:null,standings:[],tabs:["results"],games:[],teams:[],format:r,event:n,leaderboard:s,matches:o,others:i,scoreUnit:F(e.scoreUnit)}}function Ms(e){let t=F(e).trim();return t.startsWith("https://")?t:""}function Ba(e){let t=e??null,n=F(t?.label).trim(),r=F(t?.value).trim();return!t||n===""||r===""?null:{label:n,name:F(t.name).trim(),value:r}}function Ud(e){let t=e??null;if(!t)return null;let n=Array.isArray(t.rows)?t.rows.map(Ba).filter(s=>s!==null):[];if(n.length===0)return null;let r=Array.isArray(t.headline)?t.headline.map(Ba).filter(s=>s!==null).slice(0,4):[];return{splitLabel:F(t.splitLabel).trim(),headline:r,rows:n}}function jd(e,t,n){let r=e.player??null,s=F(r?.name).trim();if(!r||s==="")return null;let o=r.team??null,a=Number(r.age),i={id:F(r.id),sport:F(r.sport),leagueSlug:F(r.leagueSlug),name:s,position:F(r.position).trim(),jersey:F(r.jersey).trim(),headshot:Ms(r.headshot),status:F(r.status).trim().toLowerCase(),age:r.age!==null&&r.age!==void 0&&Number.isFinite(a)?Math.round(a):null,height:F(r.height).trim(),weight:F(r.weight).trim(),country:F(r.country).trim(),team:{id:F(o?.id),name:F(o?.name).trim(),abbreviation:F(o?.abbreviation).trim(),logo:Ms(o?.logo)},link:Ms(r.link),stats:Ud(r.stats),nextGame:Oa(r.nextGame)};return{show:!0,kind:"player",asOf:F(e.asOf),poll:Number.isFinite(Number(e.poll))?Math.max(0,Number(e.poll)):0,league:{key:F(t?.key),name:n,fullName:F(t?.fullName)||n,sport:F(t?.sport)||i.sport},team:null,series:null,standings:[],tabs:["matches"],games:[],teams:[],player:i}}function Bs(e){let t=e??null;if(!t||t.show!==!0)return null;let n=t.league??null,r=F(n?.name).trim();if(!r&&t.kind!=="player")return null;if(t.kind==="event")return qd(t,r);if(t.kind==="player")return jd(t,n,r);let s=t.kind==="team"||t.kind==="schedule"||t.kind==="standings"||t.kind==="leaders"?t.kind:"league",o=[];if(Array.isArray(t.games))for(let p of t.games){let b=Oa(p);b&&o.push(b)}let a=Dd(t.standings),i=Hd(t.leaders);if(o.length===0&&(s!=="standings"||a.length===0)&&(s!=="leaders"||i.length===0))return null;let c=null,l=t.team??null;l&&F(l.name).trim()&&(c={id:F(l.id),abbreviation:F(l.abbreviation),name:F(l.name),shortName:F(l.shortName)||F(l.name),logo:F(l.logo),record:F(l.record),homeRecord:F(l.homeRecord),awayRecord:F(l.awayRecord),streak:F(l.streak),last10:F(l.last10),form:Array.isArray(l.form)?l.form.map(p=>F(p).toUpperCase()).filter(p=>p==="W"||p==="L"||p==="D"):[],standing:F(l.standing)});let m=null,u=t.series??null;u&&F(u.summary).trim()&&(m={summary:F(u.summary),game:Number.isFinite(Number(u.game))?Number(u.game):0,of:Number.isFinite(Number(u.of))?Number(u.of):0,note:F(u.note)});let d=[];if(Array.isArray(t.tabs))for(let p of t.tabs)(p==="matches"||p==="schedule"||p==="standings"||p==="leaders")&&d.push(p);let h=[];if(Array.isArray(t.teams))for(let p of t.teams){let b=p??null,v=F(b?.name).trim(),E=F(b?.id).trim();!b||!v||!E||h.push({league:F(b.league),id:E,name:v,shortName:F(b.shortName)||v,abbreviation:F(b.abbreviation),logo:F(b.logo)})}return{show:!0,kind:s,asOf:F(t.asOf),poll:Number.isFinite(Number(t.poll))?Math.max(0,Number(t.poll)):0,league:{key:F(n?.key),name:r,fullName:F(n?.fullName)||r,sport:F(n?.sport)},team:c,series:m,standings:a,leaders:i,tabs:d.length>0?d:["matches"],games:o,teams:h}}async function zd(e,t,n,r={}){let s=String(n??"").trim();if(!s)return{payload:null,transient:!1};let o=oe(e),a=o.endpoints.sports||"/PHP/sports.php",i=r.timeoutMs??o.timeouts.sportsMs??8e3,c=r.view&&r.view!=="matches"?"&view=".concat(r.view):"",l=r.team&&r.team.league&&r.team.id?"&league=".concat(encodeURIComponent(r.team.league),"&team=").concat(encodeURIComponent(r.team.id)):"";try{let m={cache:"no-store"};r.signal&&(m.signal=r.signal);let u=await e.fetchWithTimeout("".concat(a,"?q=").concat(encodeURIComponent(s)).concat(c).concat(l),m,i);return u?.ok?{payload:Bs(await u.json()),transient:!1}:{payload:null,transient:!0}}catch{return{payload:null,transient:!0}}}async function Os(e,t,n,r={}){return(await zd(e,t,n,r)).payload}function vr(e,t=""){let n=new Date(e);if(Number.isNaN(n.getTime()))return"";try{return new Intl.DateTimeFormat(t||void 0,{hour:"numeric",minute:"2-digit"}).format(n)}catch{return""}}function Ha(e,t=""){return e.state==="in"?e.status||e.clock||"":e.state==="post"?e.status||"Final":vr(e.date,t)||e.status}function Ds(e){return e.games.some(t=>t.state==="in")}function $a(e,t=""){let n=new Date(e);if(Number.isNaN(n.getTime()))return"";try{return new Intl.DateTimeFormat(t||void 0,{weekday:"short",month:"short",day:"numeric"}).format(n)}catch{return n.toDateString()}}var Zy=300*1e3;
4function Wd(e,{beamo:t,safeHostname:n}={}){let r=[];for(let s=0;s<e.length;s+=1){let o=e[s],a=t?.safeHttpUrl?.(o?.url)||"";a&&r.push({href:a,title:String(o?.title||"").trim()||n?.(a)||"Source",description:String(o?.description||"").trim(),host:n?.(a)||"",sourceIndex:s+1})}return r}function Fa(e,t,{beamo:n,safeHostname:r,headingId:s="assistant-sources-label",headingText:o="Sources"}={}){if(!e)return!1;let a=Wd(t,{beamo:n,safeHostname:r});if(a.length===0)return!1;let i=t.length,c=document.createElement("p");c.className="ai-overview__sources-heading",c.id=s,c.textContent=o,e.appendChild(c);let l=document.createElement("ol");return l.className="ai-overview__sources-list",l.setAttribute("aria-labelledby",s),a.forEach(m=>{let u=document.createElement("li");u.className="ai-overview__sources-item",u.setAttribute("data-source-index",String(m.sourceIndex));let d=document.createElement("a");d.className="ai-overview__source-chip",d.setAttribute("data-source-index",String(m.sourceIndex)),d.href=m.href,d.target="_blank",d.rel="noopener noreferrer",d.setAttribute("data-preview-title",m.title),d.setAttribute("data-preview-host",m.host),d.setAttribute("data-preview-desc",m.description),m.host&&d.setAttribute("data-preview-favicon","https://www.google.com/s2/favicons?domain=".concat(encodeURIComponent(m.host),"&sz=64")),d.title=m.description?"".concat(m.title," \u2014 ").concat(m.description):m.title;let h=document.createElement("span");h.className="ai-overview__source-index",h.textContent=String(m.sourceIndex),h.setAttribute("aria-hidden","true"),d.appendChild(h);let p=document.createElement("span");p.className="ai-overview__source-text";let b=document.createElement("span");if(b.className="ai-overview__source-title",b.textContent=m.title,p.appendChild(b),m.host){let v=document.createElement("span");v.className="ai-overview__source-host",v.textContent=m.host,p.appendChild(v)}d.appendChild(p),u.appendChild(d),l.appendChild(u)}),e.appendChild(l),i}var $n=/\[\s*(\d{1,2}(?:\s*,\s*\d{1,2})*)\s*\]/g;function Gd(e,t,n){if(n<1||n>t||!e||typeof e.querySelectorAll!="function")return null;let r=e.querySelectorAll('[data-source-index="'.concat(n,'"]'));for(let s of r)if(s?.classList?.contains?.("ai-overview__source-chip"))return s;return null}function Kd(e,t,n){let r=e.createElement("a");r.className="ai-overview__citation",r.textContent=String(t),r.setAttribute("role","link"),r.setAttribute("tabindex","0"),r.setAttribute("aria-label","Jump to source ".concat(t)),r.dataset.citation=String(t);let s=n.getAttribute?.("href")||n.href||"";return s&&(r.setAttribute("href",s),r.setAttribute("target","_blank"),r.setAttribute("rel","noopener noreferrer")),r}function Vd(e,t,n,r){let s=String(t?.textContent??"");if(!s||!s.includes("[")||($n.lastIndex=0,!$n.test(s)))return;let o=e.createDocumentFragment(),a=0,i=!1;$n.lastIndex=0;let c=$n.exec(s);for(;c;){let m=c[1].split(",").map(d=>Number.parseInt(d.trim(),10)).filter(d=>Number.isFinite(d)),u=m.map(d=>({index:d,chip:Gd(r,n,d)})).filter(d=>!!d.chip);if(m.length>0&&u.length===m.length){c.index>a&&o.appendChild(e.createTextNode(s.slice(a,c.index)));let d=e.createElement("span");d.className="ai-overview__citations";for(let{index:h,chip:p}of u)d.appendChild(Kd(e,h,p));o.appendChild(d),a=c.index+c[0].length,i=!0}c=$n.exec(s)}if(!i)return;a<s.length&&o.appendChild(e.createTextNode(s.slice(a)));let l=t.parentNode;l&&typeof l.insertBefore=="function"&&(l.insertBefore(o,t),typeof t.remove=="function"&&t.remove())}function Yd(e){let t=e?.childNodes;return t&&typeof t.length=="number"?Array.from(t):Array.isArray(e?.children)?[...e.children]:[]}function Xd(e){return e?.nodeType===3||e?.tagName==="#text"||e?.nodeName==="#text"}function Jd(e){let t=e?.tagName||e?.nodeName||"";return t==="A"||t==="a"||e?.classList?.contains?.("ai-overview__citation")}function Qd(e){let t=[],n=r=>{for(let s of Yd(r))if(Xd(s))t.push(s);else{if(Jd(s))continue;n(s)}};return n(e),t}function qa(e,t,n,{sourcesRoot:r}={}){if(!t||!Number.isFinite(n)||n<=0)return;let s=e?.document;if(!s||typeof s.createDocumentFragment!="function")return;let o=r??s.getElementById?.("assistant-sources")??null;if(o)try{let a=Qd(t);for(let i of a)Vd(s,i,n,o)}catch{}}function Zd(e=globalThis){let t=e.document?.getElementById("chat-interface");return!!(t?.classList.contains("chat-panel")||t?.classList.contains("chat-home"))}function Fn({beamo:e=globalThis.Beamo,global:t=globalThis,host:n,sources:r=[],safeHostname:s,turnId:o=""}={}){if(!n||!Zd(t))return null;n.querySelector(".chat-message-sources")?.remove();let a=document.createElement("div");
4a.className="chat-message-sources";let i=o?"chat-sources-".concat(o):"chat-sources-".concat(Date.now()),c=Fa(a,r,{beamo:e,safeHostname:s,headingId:i,headingText:"Sources"});if(!c)return null;let l=n.querySelector(".chat-message-actions");l&&l.parentNode===n?n.insertBefore(a,l):n.appendChild(a);let m=n.querySelector(".ai-msg-text");return m&&qa(t,m,typeof c=="number"?c:0,{sourcesRoot:a}),e?.icons?.mount?.(a),a}function Ua(e){let t=e.filter(s=>s.state==="post"),n=e.filter(s=>s.state==="in"),r=e.filter(s=>s.state==="pre");return[...t.slice(-2),...n,...r.slice(0,2)]}function ja({beamo:e,global:t,host:n,pack:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=Bs(r);if(!a||a.games.length===0||n.querySelector(".chat-sports-card"))return null;let i=(r??{}).refresh??{};function c(w,f={}){return e.i18n?.t?.(w,f)||w}function l(){return o.documentElement?.lang||""}function m(w,f){if(w.logo&&w.logo.startsWith("https://")){let C=o.createElement("img");return C.className="chat-sports-card__logo",C.src=w.logo,C.alt="",C.loading="lazy",C.width=f,C.height=f,C}let g=o.createElement("span");return g.className="chat-sports-card__logo chat-sports-card__logo--fallback",g.setAttribute("aria-hidden","true"),g.textContent=(w.abbreviation||w.shortName||"?").slice(0,3).toUpperCase(),g}function u(w,f){w.classList.remove(f),w.offsetWidth,w.classList.add(f)}function d(w){return w.state==="pre"?vr(w.date,l())||w.status:Ha(w,l())}function h(w){let f=o.createElement("li");f.className="chat-sports-card__game",f.dataset.gameId=w.id,f.dataset.state=w.state;let g=o.createElement("span");g.className="chat-sports-card__date",g.textContent=$a(w.date,l()),f.appendChild(g);let C=o.createElement("span");C.className="chat-sports-card__matchup",["away","home"].forEach((N,B)=>{let I=w[N];if(B===1){let P=o.createElement("span");P.className="chat-sports-card__sep",P.setAttribute("aria-hidden","true"),P.textContent="\u2013",C.appendChild(P)}let y=o.createElement("span");y.className="chat-sports-card__team",w.state==="post"&&I.winner&&y.classList.add("chat-sports-card__team--winner"),y.appendChild(m(I,18));let k=o.createElement("span");if(k.className="chat-sports-card__team-name",k.textContent=I.abbreviation||I.shortName,k.title=I.name,y.appendChild(k),w.state!=="pre"&&I.score!==""){let P=o.createElement("span");P.className="chat-sports-card__game-score",P.dataset.side=N,P.textContent=I.score,y.appendChild(P)}C.appendChild(y)}),f.appendChild(C);let T=o.createElement("span");if(T.className="chat-sports-card__status",w.state==="in"){let N=o.createElement("span");N.className="chat-sports-card__live-dot",N.setAttribute("aria-hidden","true"),T.appendChild(N);let B=o.createElement("span");B.className="sr-only",B.textContent=c("sportsPack.live"),T.appendChild(B)}let x=o.createElement("span");return x.className="chat-sports-card__status-text",x.textContent=d(w),T.appendChild(x),f.appendChild(T),f}function p(w,f){w.replaceChildren(),w.dataset.live=Ds(f)?"true":"false";let g=o.createElement("span");g.className="chat-sports-card__head";let C=f.team??null;C&&g.appendChild(m(C,24));let T=o.createElement("span");T.className="chat-sports-card__title",T.textContent=C?C.name:f.league.name,g.appendChild(T);let x=C?[f.league.name,C.record,C.standing].filter(Boolean):[f.league.fullName],N=o.createElement("span");if(N.className="chat-sports-card__facts",N.textContent=x.join(" \xB7 "),g.appendChild(N),Ds(f)){let R=o.createElement("span");R.className="chat-sports-card__live-badge";let D=o.createElement("span");D.className="chat-sports-card__live-dot",D.setAttribute("aria-hidden","true"),R.appendChild(D),R.appendChild(o.createTextNode(c("sportsPack.live"))),g.appendChild(R)}if(w.appendChild(g),f.series){let R=[f.series.note,f.series.game>0&&f.series.of>0?c("sportsPack.gameOf",{game:f.series.game,of:f.series.of}):"",f.series.summary].filter(Boolean),D=o.createElement("span");D.className="chat-sports-card__series",D.textContent=Array.from(new Set(R)).join(" \xB7 "),w.appendChild(D)}let B=o.createElement("ol");B.className="chat-sports-card__games";for(let R of Ua(f.games))B.appendChild(h(R));w.appendChild(B);let I=o.createElement("span");
4I.className="chat-sports-card__foot";let y=o.createElement("span");y.className="chat-sports-card__attribution",y.textContent=c("sportsPack.attribution"),I.appendChild(y);let k=o.createElement("span");k.className="chat-sports-card__updated",k.hidden=!0,I.appendChild(k);let P=C?C.name:f.league.name;if(P){let R=o.createElement("a");R.className="chat-sports-card__link",R.href="/results?q=".concat(encodeURIComponent(P),"&type=web"),R.textContent=c("sportsPack.allScores"),I.appendChild(R)}w.appendChild(I)}function b(w,f){let g=Ua(f.games),C=w.querySelectorAll(".chat-sports-card__game");if(C.length!==g.length)return!1;let T=new Map(g.map(N=>[N.id,N])),x=!1;return C.forEach(N=>{let B=T.get(N.dataset.gameId||"");if(!B){x=!0;return}if(N.dataset.state!==B.state){x=!0;return}let I=N.querySelector(".chat-sports-card__status-text"),y=d(B);I&&I.textContent!==y&&(I.textContent=y,u(I,"chat-sports-card__status-text--changed")),["away","home"].forEach(k=>{let P=N.querySelector('.chat-sports-card__game-score[data-side="'.concat(k,'"]')),R=B[k].score;P&&R!==""&&P.textContent!==R&&(P.textContent=R,u(P,"chat-sports-card__game-score--changed"))})}),!x}function v(w){let f=w.querySelector(".chat-sports-card__updated");if(f){let g=vr(new Date().toISOString(),l());f.textContent=g?" \xB7 ".concat(c("sportsPack.updatedAt",{time:g})):"",f.hidden=!g}}async function E(){return i.league&&i.team?Os(e,e.config,a.team?.name||a.league.name,{team:{league:i.league,id:i.team}}):i.q?Os(e,e.config,i.q):null}function A(w,f){f<=0||!i.q&&!(i.league&&i.team)||t.setTimeout(()=>{(async()=>{if(!w.isConnected)return;if(o.visibilityState==="hidden"){A(w,f);return}let g=await E();if(w.isConnected){if(!g){A(w,f);return}b(w,g)||p(w,g),v(w),A(w,g.poll)}})()},Math.max(10,f)*1e3)}let S=o.createElement("div");S.className="chat-sports-card";let _=a?.team?.name||a?.league?.name||"";return S.setAttribute("role","group"),S.setAttribute("aria-label",_?"".concat(_," live scores"):"Live scores"),p(S,a),s&&s.parentNode===n?n.insertBefore(S,s):n.appendChild(S),A(S,a.poll),S}function Hs(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function qn(e,t){let n=Math.abs(e).toFixed(t),[r,s]=n.split("."),o=r.replace(/\B(?=(\d{3})+(?!\d))/g,","),a=e<0&&Number(n)!==0?"\u2212":"";return s?"".concat(a).concat(o,".").concat(s):"".concat(a).concat(o)}function ef(e,t,n){let r=Math.abs(e)>0&&Math.abs(e)<1?4:2;if(n==="index")return qn(e,r);if(n==="currency")return"".concat(qn(e,Math.abs(e)<1?4:2)," ").concat(t);let s=qn(e,r);return t==="USD"?"$".concat(s):"".concat(s," ").concat(t)}function za(e,t){return Number(e.toFixed(t))>0?"+".concat(qn(e,t)):qn(e,t)}var tf={index:"Index",crypto:"Crypto",future:"Futures",etf:"ETF",currency:"FX rate"},nf={open:"Market open",pre:"Pre-market",post:"After hours",closed:"Market closed"};function Wa({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=typeof a.symbol=="string"?a.symbol.trim():"",c=Hs(a.price);if(!i||c===null||n.querySelector(".chat-stock-card"))return null;let l=Hs(a.change),m=Hs(a.changePercent),u=typeof a.currency=="string"&&a.currency.trim()||"USD",d=typeof a.kind=="string"&&a.kind||(a.isCrypto?"crypto":"equity"),h=d==="crypto"||a.isCrypto===!0,p=l===null||l===0?"flat":l>0?"up":"down",b=o.createElement("div");b.className="chat-stock-card",b.dataset.direction=p,b.setAttribute("role","group"),b.setAttribute("aria-label","".concat(i," ").concat(h?"price":"market quote"));let v=o.createElement("div");v.className="chat-stock-card__head";let E=o.createElement("span");E.className="chat-stock-card__symbol",E.textContent=i,v.appendChild(E);let A=typeof a.name=="string"?a.name.trim():"";if(A&&A.toUpperCase()!==i.toUpperCase()){let B=o.createElement("span");B.className="chat-stock-card__name",B.textContent=A,v.appendChild(B)}let S=h?"24/7":nf[String(a.marketState??"")]||"";if(S){let B=o.createElement("span");B.className="chat-stock-card__state chat-stock-card__state--".concat(h?"crypto":String(a.marketState??"closed")),B.textContent=S,v.appendChild(B)}b.appendChild(v);let _=o.createElement("div");
4_.className="chat-stock-card__quote";let w=o.createElement("span");if(w.className="chat-stock-card__price",w.textContent=ef(c,u,d),_.appendChild(w),l!==null||m!==null){let B=o.createElement("span");B.className="chat-stock-card__change";let I=p==="up"?"\u25B2":p==="down"?"\u25BC":"\u2192",y=[];l!==null&&y.push(za(l,Math.abs(c)<1?4:2)),m!==null&&y.push("(".concat(za(m,2),"%)")),B.textContent="".concat(I," ").concat(y.join(" ")).trim();let k=p==="up"?"up":p==="down"?"down":"unchanged";B.setAttribute("aria-label","".concat(k," ").concat(y.join(" "))),_.appendChild(B)}b.appendChild(_);let f=o.createElement("div");f.className="chat-stock-card__foot";let g=typeof a.exchange=="string"?a.exchange.trim():"",C=[];d==="equity"||d==="etf"?(g&&C.push(g),d==="etf"&&C.push("ETF"),C.push(u)):(C.push(tf[d]||g),d!=="index"&&C.push(u));let T=C.filter((B,I)=>B&&C.indexOf(B)===I),x=o.createElement("span");x.className="chat-stock-card__meta",x.textContent=T.join(" \xB7 "),f.appendChild(x);let N=o.createElement("a");return N.className="chat-stock-card__link",N.href="/results?q=".concat(encodeURIComponent(i),"&type=web"),N.textContent="View full chart",f.appendChild(N),b.appendChild(f),s&&s.parentNode===n?n.insertBefore(b,s):n.appendChild(b),e.icons?.mount?.(b),b}function ze(e){return typeof e=="string"?e.trim():""}function Ga({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=ze(a.title),c=ze(a.primary?.value);if(!i||!c||n.querySelector(".chat-macro-card"))return null;let l=o.createElement("div");l.className="chat-macro-card",l.setAttribute("role","group"),l.setAttribute("aria-label","".concat(i," \u2014 economic data"));let m=o.createElement("div");m.className="chat-macro-card__head";let u=o.createElement("span");u.className="chat-macro-card__title",u.textContent=i,m.appendChild(u),l.appendChild(m);let d=o.createElement("div");d.className="chat-macro-card__primary";let h=o.createElement("span");h.className="chat-macro-card__value",h.textContent=c,d.appendChild(h);let p=[ze(a.primary?.label),ze(a.primary?.date)].filter(Boolean);if(p.length){let S=o.createElement("span");S.className="chat-macro-card__label",S.textContent=p.join(" \xB7 "),d.appendChild(S)}l.appendChild(d);let v=(Array.isArray(a.metrics)?a.metrics:[]).filter(S=>S&&typeof S=="object"&&ze(S.label)&&ze(S.value)).slice(0,4);if(v.length){let S=o.createElement("ul");S.className="chat-macro-card__metrics",S.setAttribute("aria-label","Supporting metrics");for(let _ of v){let w=o.createElement("li");w.className="chat-macro-card__metric";let f=o.createElement("span");f.className="chat-macro-card__metric-label",f.textContent=ze(_.label);let g=o.createElement("span");g.className="chat-macro-card__metric-value",g.textContent=ze(_.value),w.appendChild(f),w.appendChild(g),S.appendChild(w)}l.appendChild(S)}let E=ze(a.attribution),A=ze(a.link?.url);if(E||/^https?:\/\//i.test(A)){let S=o.createElement("div");if(S.className="chat-macro-card__foot",E){let _=o.createElement("span");_.className="chat-macro-card__attribution",_.textContent=E,S.appendChild(_)}if(/^https?:\/\//i.test(A)){let _=o.createElement("a");_.className="chat-macro-card__link",_.href=A,_.target="_blank",_.rel="noopener noreferrer",_.textContent=ze(a.link?.label)||"Source",S.appendChild(_)}l.appendChild(S)}return s&&s.parentNode===n?n.insertBefore(l,s):n.appendChild(l),e.icons?.mount?.(l),l}function ct(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function et(e){return typeof e=="string"?e.trim():""}function rf(e,t){let n=et(e?.displayDate);if(n)return"".concat(t," (").concat(n.replace(/,\s*\d{4}$/,""),")");let r=et(e?.weekday),s=et(e?.date);return r&&s?"".concat(t," (").concat(r,", ").concat(s,")"):r?"".concat(t," (").concat(r,")"):s?"".concat(t," (").concat(s,")"):t}function Ka({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=et(a.place),c=ct(a.current?.temp);if(!i||c===null||n.querySelector(".chat-weather-card"))return null;let l=et(a.tempUnit)||"\xB0",m=et(a.windUnit)||"mph",u=o.createElement("div");u.className="chat-weather-card",u.setAttribute("role","group"),u.setAttribute("aria-label","Weather for ".concat(i));let d=o.createElement("div");
4d.className="chat-weather-card__head";let h=o.createElement("span");h.className="chat-weather-card__place",h.textContent=i,d.appendChild(h);let p=et(a.region);if(p){let y=o.createElement("span");y.className="chat-weather-card__region",y.textContent=p,d.appendChild(y)}u.appendChild(d);let b=o.createElement("div");b.className="chat-weather-card__current";let v=et(a.current?.icon);if(v){let y=o.createElement("span");y.className="chat-weather-card__icon",y.setAttribute("aria-hidden","true"),y.textContent=v,b.appendChild(y)}let E=o.createElement("span");E.className="chat-weather-card__temp",E.textContent="".concat(Math.round(c)).concat(l),b.appendChild(E);let A=o.createElement("span");A.className="chat-weather-card__cond";let S=et(a.current?.label);if(S){let y=o.createElement("span");y.className="chat-weather-card__label",y.textContent=S,A.appendChild(y)}let _=ct(a.current?.feelsLike);if(_!==null){let y=o.createElement("span");y.className="chat-weather-card__feels",y.textContent="Feels like ".concat(Math.round(_)).concat(l),A.appendChild(y)}A.childNodes.length&&b.appendChild(A),u.appendChild(b);let w=[],f=a.today??null,g=ct(f?.high),C=ct(f?.low);g!==null&&C!==null&&w.push("H ".concat(Math.round(g),"\xB0 \xB7 L ").concat(Math.round(C),"\xB0"));let T=ct(a.current?.humidity);T!==null&&w.push("Humidity ".concat(Math.round(T),"%"));let x=ct(a.current?.wind);if(x!==null&&w.push("Wind ".concat(Math.round(x)," ").concat(m)),w.length){let y=o.createElement("div");y.className="chat-weather-card__stats",y.textContent=w.join(" \xB7 "),u.appendChild(y)}let N=a.tomorrow??null,B=ct(N?.high),I=ct(N?.low);if(B!==null&&I!==null){let y=o.createElement("div");y.className="chat-weather-card__tomorrow";let k=ct(N?.precipProbability),P=[et(N?.icon),rf(N,"Tomorrow"),"H ".concat(Math.round(B),"\xB0 \xB7 L ").concat(Math.round(I),"\xB0"),k!==null&&k>0?"".concat(Math.round(k),"% precip"):""].filter(Boolean);y.textContent=P.join(" \xB7 "),u.appendChild(y)}return s&&s.parentNode===n?n.insertBefore(u,s):n.appendChild(u),e.icons?.mount?.(u),u}function _r(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Et(e){return typeof e=="string"?e.trim():""}function Va({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=Et(a.place),c=_r(a.aqi);if(!i||c===null||n.querySelector(".chat-aqi-card"))return null;let l=Math.max(0,Math.min(5,_r(a.band)??0)),m=o.createElement("div");m.className="chat-aqi-card",m.dataset.band=String(l),m.setAttribute("role","group"),m.setAttribute("aria-label","Air quality for ".concat(i));let u=o.createElement("div");u.className="chat-aqi-card__head";let d=o.createElement("span");d.className="chat-aqi-card__place",d.textContent=i,u.appendChild(d);let h=Et(a.region);if(h){let f=o.createElement("span");f.className="chat-aqi-card__region",f.textContent=h,u.appendChild(f)}m.appendChild(u);let p=o.createElement("div");p.className="chat-aqi-card__main";let b=o.createElement("span");b.className="chat-aqi-card__value",b.textContent=String(Math.round(c)),p.appendChild(b);let v=o.createElement("span");v.className="chat-aqi-card__cat";let E=Et(a.category);if(E){let f=o.createElement("span");f.className="chat-aqi-card__category",f.textContent=E,v.appendChild(f)}let A=Et(a.scale);if(A){let f=o.createElement("span");f.className="chat-aqi-card__scale",f.textContent=A,v.appendChild(f)}v.childNodes.length&&p.appendChild(v),m.appendChild(p);let S=Et(a.note);if(S){let f=o.createElement("div");f.className="chat-aqi-card__note",f.textContent=S,m.appendChild(f)}let w=(Array.isArray(a.pollutants)?a.pollutants:[]).filter(f=>f&&typeof f=="object"&&Et(f.label)&&_r(f.value)!==null).slice(0,4);if(w.length){let f=o.createElement("ul");f.className="chat-aqi-card__pollutants";for(let g of w){let C=o.createElement("li");C.className="chat-aqi-card__pollutant";let T=o.createElement("span");T.className="chat-aqi-card__pollutant-label",T.textContent=Et(g.label);let x=o.createElement("span");x.className="chat-aqi-card__pollutant-value";let N=Et(g.unit);x.textContent="".concat(_r(g.value)).concat(N?" ".concat(N):""),C.appendChild(T),C.appendChild(x),f.appendChild(C)}m.appendChild(f)}return s&&s.parentNode===n?n.insertBefore(m,s):n.appendChild(m),e.icons?.mount?.(m),m}function Un(e=globalThis){try{let t=String(e?.document?.documentElement?.lang||"").trim();if(t)return t;let n=String(e?.navigator?.language||"").trim();if(n)return n}catch{}return"en-US"}function $s(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function jn(e){return typeof e=="string"?e.trim():""}
4function Ya(e){return e.toLocaleString(Un(),{minimumFractionDigits:0,maximumFractionDigits:2})}function sf(e){let t=e>=1?4:6;return e.toLocaleString(Un(),{minimumFractionDigits:2,maximumFractionDigits:t})}function of(e){let t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return e;let[,n,r,s]=t,a=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][Number(r)-1];return a?"".concat(a," ").concat(Number(s),", ").concat(n):e}function Xa({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=jn(a.fromCode).toUpperCase(),c=jn(a.toCode).toUpperCase(),l=$s(a.amount),m=$s(a.converted),u=$s(a.rate);if(!i||!c||l===null||m===null||u===null||n.querySelector(".chat-currency-card"))return null;let d=o.createElement("div");d.className="chat-currency-card",d.setAttribute("role","group"),d.setAttribute("aria-label","".concat(i," to ").concat(c," exchange rate"));let h=jn(a.fromName)||i,p=jn(a.toName)||c,b=o.createElement("div");b.className="chat-currency-card__head",b.textContent="".concat(h," \u2192 ").concat(p),d.appendChild(b);let v=o.createElement("div");v.className="chat-currency-card__main";let E=o.createElement("span");E.className="chat-currency-card__from",E.textContent="".concat(Ya(l)," ").concat(i);let A=o.createElement("span");A.className="chat-currency-card__eq",A.textContent="=",A.setAttribute("aria-hidden","true");let S=o.createElement("span");S.className="chat-currency-card__to",S.textContent="".concat(Ya(m)," ").concat(c),v.appendChild(E),v.appendChild(A),v.appendChild(S),d.appendChild(v);let _=o.createElement("div");_.className="chat-currency-card__rate",_.textContent="1 ".concat(i," = ").concat(sf(u)," ").concat(c),d.appendChild(_);let w=of(jn(a.date)),f=o.createElement("div");return f.className="chat-currency-card__meta",f.textContent=w?"European Central Bank \xB7 ".concat(w):"European Central Bank",d.appendChild(f),s&&s.parentNode===n?n.insertBefore(d,s):n.appendChild(d),e.icons?.mount?.(d),d}function Cr(e){return typeof e=="string"?e.trim():""}function af(e){return typeof e!="number"||!Number.isFinite(e)?"":e.toLocaleString(Un(),{maximumSignificantDigits:7})}function Ja(e,t){return Cr(e)||af(t)}function Qa({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=Cr(a.fromLabel),c=Cr(a.toLabel),l=Ja(a.valueText,a.value),m=Ja(a.resultText,a.result);if(!i||!c||!l||!m||n.querySelector(".chat-unit-convert-card"))return null;let u=o.createElement("div");u.className="chat-unit-convert-card",u.setAttribute("role","group"),u.setAttribute("aria-label","".concat(l," ").concat(i," to ").concat(m," ").concat(c));let d=Cr(a.categoryLabel),h=o.createElement("div");h.className="chat-unit-convert-card__head",h.textContent=d?"".concat(d," \xB7 Unit converter"):"Unit converter",u.appendChild(h);let p=o.createElement("div");p.className="chat-unit-convert-card__body";let b=o.createElement("div");b.className="chat-unit-convert-card__from",b.textContent="".concat(l," ").concat(i),p.appendChild(b);let v=o.createElement("div");v.className="chat-unit-convert-card__to";let E=o.createElement("span");E.className="chat-unit-convert-card__eq",E.textContent="=",E.setAttribute("aria-hidden","true");let A=o.createElement("span");return A.className="chat-unit-convert-card__to-value",A.textContent="".concat(m," ").concat(c),v.appendChild(E),v.appendChild(A),p.appendChild(v),u.appendChild(p),s&&s.parentNode===n?n.insertBefore(u,s):n.appendChild(u),e.icons?.mount?.(u),u}function Ht(e){return typeof e=="string"?e.trim():""}function Za({beamo:e,global:t,host:n,data:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=r??{},i=(Array.isArray(a.places)?a.places:[]).filter(p=>p&&typeof p=="object"&&Ht(p.name)).slice(0,5);if(i.length===0||n.querySelector(".chat-local-card"))return null;let c=o.createElement("div");c.className="chat-local-card";let l=o.createElement("div");l.className="chat-local-card__head";let m=Ht(a.category),u=Ht(a.area);l.textContent=[m,u].filter(Boolean).join(" \xB7 ")||"Places nearby",c.setAttribute("role","group"),c.setAttribute("aria-label","Local places: ".concat([m,u].filter(
4Boolean).join(" in ")||"nearby")),c.appendChild(l);let d=o.createElement("ol");d.className="chat-local-card__list",i.forEach((p,b)=>{let v=o.createElement("li");v.className="chat-local-card__item";let E=o.createElement("span");E.className="chat-local-card__pin",E.setAttribute("aria-hidden","true"),E.textContent=String(b+1),v.appendChild(E);let A=o.createElement("div");A.className="chat-local-card__body";let S=o.createElement("span");S.className="chat-local-card__name",S.textContent=Ht(p.name),A.appendChild(S);let _=[Ht(p.category),Ht(p.address)].filter(Boolean);if(_.length){let w=o.createElement("span");w.className="chat-local-card__meta",w.textContent=_.join(" \xB7 "),A.appendChild(w)}v.appendChild(A),d.appendChild(v)}),c.appendChild(d);let h=Ht(a.query)||[m,u].filter(Boolean).join(" ");if(h){let p=o.createElement("div");p.className="chat-local-card__foot";let b=o.createElement("a");b.className="chat-local-card__map-link",b.href="/results?q=".concat(encodeURIComponent(h),"&type=maps"),b.textContent="View on map",p.appendChild(b),c.appendChild(p)}return s&&s.parentNode===n?n.insertBefore(c,s):n.appendChild(c),e.icons?.mount?.(c),c}var cf=/^(?:https?:|mailto:|tel:|\/(?!\/)|#)/i,lf=/(?:url\s*\(|expression\s*\(|@import|behavior\s*:|-moz-binding|javascript\s*:|vbscript\s*:|data\s*:)/i,uf=/[<>{}\\]/,df=/^[a-z0-9\s.,%#()+\-*/_]+$/i,ff=/^--[a-z0-9_-]{1,80}$/i,mf=0,hf=new Set(["A","ABBR","ARTICLE","ASIDE","B","BLOCKQUOTE","BR","BUTTON","CANVAS","CAPTION","CIRCLE","CITE","CLIPPATH","CODE","COL","COLGROUP","DATA","DD","DEL","DETAILS","DFN","DIV","DL","DT","EM","FIELDSET","DEFS","ELLIPSE","FIGCAPTION","FIGURE","FILTER","FOOTER","FORM","G","H2","H3","H4","H5","HEADER","HR","I","IMG","INPUT","KBD","LABEL","LEGEND","LI","LINE","LINEARGRADIENT","MARK","MASK","METER","NAV","OL","OPTION","OUTPUT","P","PATH","PATTERN","POLYGON","POLYLINE","PRE","PROGRESS","Q","RADIALGRADIENT","RECT","S","SAMP","SECTION","SELECT","SMALL","SPAN","STOP","STRONG","SUB","SUMMARY","SUP","SVG","TABLE","TBODY","TD","TEXT","TFOOT","TH","THEAD","TIME","TR","TSPAN","UL"]),pf=new Set(["aria-atomic","aria-busy","aria-current","aria-disabled","aria-expanded","aria-haspopup","aria-hidden","aria-label","aria-live","aria-pressed","aria-selected","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","class","data-action","data-chat-card","data-direction","data-forecast-kind","data-index","data-instant-type","data-kind","data-provider","data-state","data-status","data-tool","data-type","data-value","disabled","hidden","role","title"]),gf=new Set(["autocomplete","checked","inputmode","max","maxlength","min","minlength","multiple","name","pattern","placeholder","readonly","selected","step","type","value"]),yf=new Set(["clip-path","cx","cy","d","fill","fill-opacity","filter","focusable","height","href","mask","marker-end","marker-mid","marker-start","offset","opacity","points","preserveaspectratio","r","rx","ry","shape-rendering","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-opacity","stroke-width","transform","viewbox","width","x","x1","x2","xlink:href","xmlns","y","y1","y2"]),bf=new Set(["SVG","PATH","G","LINE","POLYGON","POLYLINE","RECT","TEXT","TSPAN","CIRCLE","ELLIPSE","DEFS","LINEARGRADIENT","RADIALGRADIENT","STOP","CLIPPATH","MASK","PATTERN","FILTER"]),ei=new Set(["LINEARGRADIENT","RADIALGRADIENT","CLIPPATH","MASK","PATTERN","FILTER"]),wf=new Set(["fill","stroke","clip-path","mask","filter","marker-start","marker-mid","marker-end"]),Sf=new Set(["align-items","aspect-ratio","background","background-color","border","border-color","border-radius","bottom","box-shadow","color","display","fill","fill-opacity","flex","flex-basis","flex-direction","flex-grow","flex-shrink","font-family","font-size","font-variant-numeric","font-weight","gap","grid-column","grid-row","grid-template-columns","height","justify-content","left","letter-spacing","line-height","margin","margin-bottom","margin-left","margin-right","margin-top","max-height","max-width","min-height","min-width","opacity","order","right","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-opacity","stroke-width","text-align","text-anchor","top","transform","transform-origin","transition","width"]);function ti(e){return Array.from(e.attributes||[]).map(t=>Array.isArray(t)?{name:String(t[0]??""),value:String(t[1]??"")}:{name:String(t?.name??""),value:String(t?.value??"")}).filter(t=>t.name!=="")}function kf(e){return String(e??"").trim().replace(/[^\w:.-]+/g,"-").slice(0,96)||"instant"}
4function Fs(e){return e.nodeType===1||typeof e.tagName=="string"&&e.tagName!=="#text"}function vf(e){let t=e.trim();return t===""||cf.test(t)}function _f(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Cf(e){let t=e.trim();return t!==""&&t.length<=220&&!lf.test(t)&&!uf.test(t)&&df.test(t)}function Af(e){let t=e.split(";").map(r=>r.trim()).filter(Boolean),n=[];for(let r of t){let s=r.indexOf(":");if(s<=0)continue;let o=r.slice(0,s).trim().toLowerCase(),a=r.slice(s+1).trim();(ff.test(o)||Sf.has(o))&&Cf(a)&&n.push("".concat(o,": ").concat(a))}return n.join("; ")}function Ef(e){let t=e.trim();return t===""||!/url\s*\(/i.test(t)?!0:/^url\(\s*#[A-Za-z][\w:.-]{0,120}\s*\)$/i.test(t)}function Tf(e){let t=new Map,n="chat-snap-".concat(mf+=1),r=[],s=a=>{for(let i of Array.from(a.children||[]))Fs(i)&&(r.push(i),s(i))};s(e),r.filter(a=>ei.has(a.tagName.toUpperCase())&&a.hasAttribute("id")&&!!a.closest("svg")).forEach((a,i)=>{let c=String(a.getAttribute("id")||"").trim();if(!c||t.has(c))return;let l=c.replace(/[^\w:.-]+/g,"-").slice(0,64)||"id-".concat(i),m="".concat(n,"-").concat(i,"-").concat(l);t.set(c,m),a.setAttribute("id",m)}),t.size!==0&&r.forEach(a=>{for(let i of ti(a)){let c=i.value;for(let[l,m]of t){let u=_f(l);c=c.replace(new RegExp("url\\(\\s*#".concat(u,"\\s*\\)"),"g"),"url(#".concat(m,")")).replace(new RegExp("^#".concat(u,"$"),"g"),"#".concat(m))}c!==i.value&&a.setAttribute(i.name,c)}})}function xf(e){let t=e.parentNode;if(!t){e.remove();return}for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}function Rf(e){let t=e.tagName.toUpperCase();for(let n of ti(e)){let r=n.name.toLowerCase(),s=n.value||"";if(r==="style"){let m=Af(s);m?e.setAttribute(n.name,m):e.removeAttribute(n.name);continue}if(r==="id"){ei.has(t)&&e.closest?.("svg")&&/^chat-snap-\d+-\d+-[A-Za-z0-9_.:-]+$/.test(s)||e.removeAttribute(n.name);continue}let o=r.startsWith("aria-"),a=r.startsWith("data-"),i=gf.has(r)&&["BUTTON","INPUT","OPTION","SELECT"].includes(t),c=yf.has(r)&&bf.has(t);if(!(pf.has(r)||o||a||i||c||t==="A"&&["href","rel","target"].includes(r)||t==="IMG"&&["alt","decoding","height","loading","referrerpolicy","src","width"].includes(r))||r.startsWith("on")||r==="data-original-id"){e.removeAttribute(n.name);continue}if((r==="href"||r==="src")&&!vf(s)){e.removeAttribute(n.name);continue}if(c&&wf.has(r)&&!Ef(s)){e.removeAttribute(n.name);continue}r==="target"&&s==="_blank"&&e.setAttribute("rel","noopener noreferrer")}}function Pf(e){Tf(e);let t=[e];for(let n=0;n<t.length;n+=1){let r=t[n];for(let s of Array.from(r.children||[]))Fs(s)&&t.push(s)}for(let n=t.length-1;n>=0;n-=1){let r=t[n],s=r.tagName.toUpperCase();if(!hf.has(s)){xf(r);continue}Rf(r)}return["[for]","[aria-controls]","[aria-describedby]","[aria-labelledby]"].forEach(n=>{e.querySelectorAll(n).forEach(r=>{r.removeAttribute("for"),r.removeAttribute("aria-controls"),r.removeAttribute("aria-describedby"),r.removeAttribute("aria-labelledby")})}),e.querySelectorAll("[aria-live]").forEach(n=>{n.removeAttribute("aria-live")}),e.textContent?.trim()?e:null}function ni(e){if(!e||typeof e!="object"||!Array.isArray(e.parts))return null;let t=[],n=0;for(let r of e.parts){if(t.length>=8||!r||typeof r!="object")continue;let s=String(r.html??"").trim();!s||s.length>24e3||n+s.length>72e3||(n+=s.length,t.push({sourceId:kf(r.sourceId),html:s}))}return t.length>0?{parts:t}:null}function zn(e){return ni(e.instantSnapshot)}function ri({global:e,host:t,snapshot:n,before:r=null}){if(!t||t.querySelector("[data-chat-instant-snapshot]"))return null;let s=ni(n);if(!s)return null;let o=e.document,a=o.createElement("div");a.className="chat-instant-snapshot",a.dataset.chatInstantSnapshot="1",a.dataset.sourceId=s.parts.map(c=>c.sourceId).join(" "),a.setAttribute("role","group"),a.setAttribute("aria-label","Instant answer from this search");for(let c of s.parts){let l=o.createElement("template");l.innerHTML=c.html;let m=l.content||l,u=m.childNodes&&m.childNodes.length>0?m.childNodes:m.children,d=Array.from(u||[]).filter(Fs);for(let h of d){let p=Pf(h);p&&(p.classList.add("chat-instant-snapshot__content"),a.appendChild(p))}}if(!a.textContent?.trim())return null;let i=r&&r.parentNode===t?r:t.querySelector(".chat-message-sources, .chat-message-actions");return i&&i.parentNode===t?t.insertBefore(a,i):t.appendChild(a),a}var Re=e=>!!e&&typeof e=="object",O=e=>typeof e=="string"?e.trim():typeof e=="number"&&Number.isFinite(e)?String(e):"",be=e=>Array.isArray(e)?e.filter(Re):[],Ar=e=>
4Array.isArray(e)?e.map(O).filter(Boolean):[],De=e=>Re(e)&&!!e.__instantUnavailable,$t=e=>be(e).map(t=>({label:O(t.label),href:O(t.url)})).filter(t=>t.label&&/^https?:\/\//i.test(t.href)),If=e=>{if(!Re(e)||De(e))return null;let t=O(e.sourceText),n=O(e.identifiedLanguage)||O(e.detectedSource),r=O(e.kind)==="language",s=r?n:O(e.translation);if(!t||!s)return null;let o=O(e.sourceLanguage)||n||"auto",a=O(e.targetLanguage)||"English",i=be(e.examples).map(m=>"".concat(O(m.source)," \u2014 ").concat(O(m.target))).filter(m=>m.length>3),c=[...be(e.toneVariants),...be(e.genderVariants)].map(m=>"".concat(O(m.label),": ").concat(O(m.text))).filter(m=>m.length>2),l=Ar(e.alternatives);return{icon:"\u{1F310}",title:t,subtitle:r?"Language identification":"".concat(o," \u2192 ").concat(a),primary:s,facts:[O(e.romanization)||null,O(e.backTranslation)?"\u21A9 ".concat(O(e.backTranslation)):null,l.length?"alt: ".concat(l.join(", ")):null],lines:[...i,...c],note:O(e.attribution)||"Translated by Beamo AI"}},Nf=e=>{if(!Re(e)||De(e))return null;let t=O(e.word);if(!t)return null;let n=be(e.meanings),r=c=>{let l=be(c.definitions);return l.length?O(l[0].text):""},s=n[0],o=s?[O(s.partOfSpeech)?"(".concat(O(s.partOfSpeech),")"):"",r(s)].filter(Boolean).join(" "):"",a=n.slice(0,4).map(c=>{let l=O(c.partOfSpeech),m=r(c);return m?l?"".concat(l,": ").concat(m):m:null}),i=Ar(e.homophones);return{icon:"\u{1F4D6}",title:t,subtitle:O(e.phonetic)||void 0,primary:o||void 0,facts:[typeof e.syllableCount=="number"?"".concat(e.syllableCount," syllables"):null,O(e.origin)?"Origin: ".concat(O(e.origin)):null,i.length?"Homophones: ".concat(i.join(", ")):null],lines:a,note:O(e.attribution)||"Results from Dictionary API"}},Lf=e=>{if(!Re(e)||De(e))return null;let t=Ar(e.words);if(t.length===0)return null;let n=O(e.term),r=O(e.kind)||"results";return{icon:"\u{1F524}",title:n||r,subtitle:{synonyms:"Synonyms",antonyms:"Antonyms",rhymes:"Rhymes",nearrhymes:"Near rhymes",alliteration:"Alliteration",wordle:"Wordle matches",crossword:"Crossword matches",spelling:"Matching words"}[r]||r,primary:t.slice(0,6).join(", "),lines:t,note:O(e.attribution)||"Word data from Datamuse"}},Mf=e=>{if(!Re(e)||De(e))return null;let t=be(e.metrics);if(!t.length)return null;let n=t[0],r=s=>O(s.value)?"".concat(O(s.label)?"".concat(O(s.label),": "):"").concat(O(s.value)):null;return{icon:"\u{1F52D}",title:O(e.title)||"Astronomy",subtitle:O(e.placeLabel)||void 0,primary:r(n)||void 0,facts:t.slice(1,4).map(r),links:$t(e.links),note:O(e.source)||void 0}},Bf=e=>{if(!Re(e)||De(e))return null;let t=O(e.sunrise),n=O(e.sunset);if(!t&&!n)return null;let r=Re(e.moon)?e.moon:null,s=r&&O(r.label)?"".concat(O(r.icon)?"".concat(O(r.icon)," "):"").concat(O(r.label)).trim():null;return{icon:"\u{1F305}",title:O(e.placeLabel)||"Sun times",subtitle:O(e.targetLabel)||void 0,primary:t?"Sunrise ".concat(t):"Sunset ".concat(n),facts:[t&&n?"Sunset ".concat(n):null,O(e.dayLength)?"Day length ".concat(O(e.dayLength)):null,s],note:O(e.attribution)||void 0}},Of=e=>{if(!Re(e)||De(e))return null;let t=O(e.time);if(!t)return null;let n=O(e.timezone);return{icon:"\u{1F550}",title:O(e.placeLabel)||"Local time",primary:t,facts:[O(e.date)||null,n?"Time zone ".concat(n):null],note:O(e.ianaTimeZone)||void 0}},Df=e=>{if(!Re(e)||De(e))return null;let t=O(e.scopeLabel)||O(e.state);if(!t)return null;let n=be(e.diseases).map(s=>[O(s.label),O(s.category)].filter(Boolean).join(": ")).filter(Boolean),r=O(e.asOf);return{icon:"\u{1F9A0}",title:"".concat(t," respiratory illness"),subtitle:O(e.summary)||void 0,primary:O(e.status)||void 0,facts:n,lines:r?["As of ".concat(r)]:void 0,links:$t(e.links),note:O(e.attribution)||void 0}},Hf=e=>{if(!Re(e)||De(e))return null;let t=O(e.title);if(!t)return null;let r=(be(e.items).length?be(e.items):be(e.events)).slice(0,4).map(s=>[O(s.title)||O(s.label)||O(s.name),O(s.detail)||O(s.summary)||O(s.magnitude)||O(s.place)].filter(Boolean).join(" \xB7 ")||null);return{icon:"\u{1F4CA}",title:t,subtitle:O(e.summary)||void 0,primary:O(e.status)||O(e.providerStatus)||void 0,facts:[O(e.updated)||O(e.asOf)||null,r.filter(Boolean).length?null:O(e.note)||null],lines:r,links:$t(e.links),note:O(e.attribution)||O(e.source)||void 0}},$f=e=>{if(!Re(e)||De(e))return null;let t=O(e.trackingNumber);if(!t)return null;
4let n=[O(e.lastLocation),O(e.lastUpdate)].filter(Boolean).join(" \xB7 "),r=O(e.estimatedDelivery);return{icon:"\u{1F4E6}",title:O(e.carrier)||"Package",subtitle:t,primary:O(e.status)||void 0,facts:[O(e.confidenceLabel)||null,O(e.lastEvent)||null,n||null,r?"Est. delivery ".concat(r):null],links:[...$t(e.links),...$t(e.alternateLinks)],note:O(e.attribution)||void 0}},Ff=e=>{if(!Re(e)||De(e))return null;let t=O(e.flight);if(!t)return null;let n=O(e.departureIata),r=O(e.arrivalIata),s=n&&r?"".concat(n," \u2192 ").concat(r):O(e.route)||[O(e.departureAirport),O(e.arrivalAirport)].filter(Boolean).join(" \u2192 "),o=O(e.mode)==="live",a=O(e.departureScheduled),i=O(e.arrivalScheduled);return{icon:"\u2708\uFE0F",title:t,subtitle:o?s||void 0:O(e.summary)||void 0,primary:O(e.status)||void 0,facts:[O(e.airline)||null,o&&s||null,a?"Departs ".concat(a):null,i?"Arrives ".concat(i):null,O(e.aircraft)||null],links:$t(e.links),note:O(e.attribution)||void 0}},qf=e=>{if(!Re(e)||De(e))return null;let t=O(e.title);if(!t)return null;let n=be(e.rows).slice(0,3).map(o=>{let a=[O(o.origin),O(o.destination)].filter(Boolean).join("\u2192"),i=O(o.gate)?"Gate ".concat(O(o.gate)):"";return[O(o.flight),a,O(o.status),O(o.delay),i].filter(Boolean).join(" \xB7 ")||null}),r=O(e.airport)||O(e.route),s=Ar(e.alertControls).join(", ");return{icon:"\u{1F6EB}",title:t,subtitle:O(e.summary)||void 0,primary:O(e.providerStatus)||void 0,facts:[r||null,O(e.boardMode)||null,s||null],lines:n,links:$t(e.links),note:O(e.source)||void 0}},Uf=e=>{if(!Re(e)||De(e))return null;let t=O(e.ip);if(!t)return null;let n=[O(e.city),O(e.region),O(e.country)].filter(Boolean).join(", ");return{icon:"\u{1F310}",title:"Your IP address",primary:t,facts:[n||null,O(e.isp)||null],note:O(e.attribution)||void 0}},jf=e=>{if(!Re(e)||De(e))return null;let t=O(e.kind);if(!t)return null;let n=O(e.translation)||O(e.revised)||O(e.explanation)||(O(e.cefr)?"CEFR ".concat(O(e.cefr)):""),r=be(e.forms).map(l=>"".concat(O(l.label),": ").concat(O(l.value))).filter(l=>l.length>2);if(!n&&!r.length&&!be(e.conjugations).length&&!be(e.declensions).length)return null;let s=O(e.term)||O(e.text),o=[...be(e.variants),...be(e.falseFriends),...be(e.changes)].map(l=>"".concat(O(l.label),": ").concat(O(l.text))).filter(l=>l.length>2),a=be(e.examples).map(l=>"".concat(O(l.source)," \u2014 ").concat(O(l.target))).filter(l=>l.length>3),i={bilingual:"Bilingual dictionary",rewrite:"Rewrite",learning:"Language learning"},c=O(e.rewriteMode)||O(e.learningMode);return{icon:"\u{1F6E0}\uFE0F",title:s||t,subtitle:[i[t]||t,c].filter(Boolean).join(" \xB7 "),primary:s&&n?"".concat(s," \u2192 ").concat(n):n||void 0,facts:[O(e.literal)?"literal: ".concat(O(e.literal)):null,O(e.partOfSpeech)||null,O(e.register)||null,O(e.gender)||null,O(e.difficulty)||null],lines:[...r,...o,...a],note:O(e.attribution)||"Language help by Beamo AI"}},qs={translation:If,definition:Nf,thesaurus:Lf,astronomy:Mf,sun:Bf,timezone:Of,illness:Df,officialdata:Hf,tracking:$f,flight:Ff,airportops:qf,ip:Uf,languagetools:jf};var Tt=e=>typeof e=="string"?e.trim():"";function zf(e){let t=Tt(e);return/^(?:https?:|mailto:)/i.test(t)?t:""}function si(e,t){return(e||[]).map(n=>Tt(n)).filter(Boolean).slice(0,t)}function Wf(e,t,n){let r=e.document;if(!r||!n)return null;let s=Tt(n.title);if(!s)return null;let o=si(n.facts,5),a=si(n.lines,6),i=(n.links||[]).map(b=>({label:Tt(b?.label),href:zf(b?.href)})).filter(b=>b.label&&b.href).slice(0,4),c=r.createElement("div");c.className="chat-instant-card chat-instant-card--".concat(t),c.setAttribute("role","group"),c.setAttribute("aria-label",s);let l=r.createElement("div");l.className="chat-instant-card__head";let m=Tt(n.icon);if(m){let b=r.createElement("span");b.className="chat-instant-card__icon",b.setAttribute("aria-hidden","true"),b.textContent=m,l.appendChild(b)}let u=r.createElement("span");u.className="chat-instant-card__title",u.textContent=s,l.appendChild(u);let d=Tt(n.subtitle);if(d){let b=r.createElement("span");b.className="chat-instant-card__subtitle",b.textContent=d,l.appendChild(b)}c.appendChild(l);let h=Tt(n.primary);if(h){let b=r.createElement("div");
4b.className="chat-instant-card__primary",b.textContent=h,c.appendChild(b)}if(o.length){let b=r.createElement("div");b.className="chat-instant-card__facts",b.textContent=o.join(" \xB7 "),c.appendChild(b)}if(a.length){let b=r.createElement("ul");b.className="chat-instant-card__lines";for(let v of a){let E=r.createElement("li");E.textContent=v,b.appendChild(E)}c.appendChild(b)}if(i.length){let b=r.createElement("div");b.className="chat-instant-card__links";for(let v of i){let E=r.createElement("a");E.className="chat-instant-card__link",E.href=v.href,E.target="_blank",E.rel="noopener noreferrer",E.textContent=v.label,b.appendChild(E)}c.appendChild(b)}let p=Tt(n.note);if(p){let b=r.createElement("div");b.className="chat-instant-card__note",b.textContent=p,c.appendChild(b)}return!h&&!o.length&&!a.length&&!i.length?null:c}var oi=Object.keys(qs);function ai({beamo:e,global:t,host:n,kind:r,data:s,before:o=null}){if(!n||n.querySelector("[data-chat-card]"))return null;let a=qs[r];if(!a)return null;let i=null;try{i=a(s)}catch{i=null}let c=Wf(t,r,i);if(!c)return null;let l=o??n.querySelector(".chat-message-sources");return l&&l.parentNode===n?n.insertBefore(c,l):n.appendChild(c),e.icons?.mount?.(c),c}var Gf=new Set(oi),ii={sports:{icon:"\u{1F3C6}",verb:"Checked live scores"},finance:{icon:"\u{1F4C8}",verb:"Checked live market data"},macro:{icon:"\u{1F4CA}",verb:"Checked live economic data"},weather:{icon:"\u{1F324}\uFE0F",verb:"Checked the weather"},aqi:{icon:"\u{1F4A8}",verb:"Checked the air quality"},currency:{icon:"\u{1F4B1}",verb:"Checked the exchange rate"},convert:{icon:"\u{1F4D0}",verb:"Converted units"},local:{icon:"\u{1F4CD}",verb:"Found local places"},web:{icon:"\u{1F50E}",verb:"Searched the web for"}},Kf=new Set(["sports","finance","macro","weather","aqi","currency","convert","local"]);function Us({beamo:e,global:t,host:n,activity:r,before:s=null}){let o=t.document;if(!n||!o)return null;let a=typeof r?.query=="string"?r.query.trim():"";if(!a||n.querySelector(".chat-search-activity"))return null;let i=Kf.has(r?.kind??"")?r.kind:"web",c=ii[i]??ii.web,l=i==="web",m=o.createElement("p");m.className="chat-search-activity",m.setAttribute("aria-label","".concat(c.verb,": ").concat(a));let u=o.createElement("span");u.className="chat-search-activity-icon",u.setAttribute("aria-hidden","true"),u.textContent=c.icon;let d=o.createElement("span");d.textContent=l?" ".concat(c.verb,' "').concat(a,'"'):" ".concat(c.verb," \xB7 ").concat(a),m.appendChild(u),m.appendChild(d);let h=s&&s.parentNode===n?s:n.querySelector(".chat-message-sources");return h&&h.parentNode===n?n.insertBefore(m,h):n.appendChild(m),m}function js({beamo:e,global:t,host:n,card:r,before:s=null}){if(!n||!r||typeof r!="object"||n.querySelector("[data-chat-card]"))return null;let o=s??n.querySelector(".chat-message-sources"),a=null;switch(r.kind){case"sports":a=ja({beamo:e,global:t,host:n,pack:r.data,before:o});break;case"stocks":a=Wa({beamo:e,global:t,host:n,data:r.data,before:o});break;case"macro":a=Ga({beamo:e,global:t,host:n,data:r.data,before:o});break;case"weather":a=Ka({beamo:e,global:t,host:n,data:r.data,before:o});break;case"aqi":a=Va({beamo:e,global:t,host:n,data:r.data,before:o});break;case"currency":a=Xa({beamo:e,global:t,host:n,data:r.data,before:o});break;case"unit-convert":a=Qa({beamo:e,global:t,host:n,data:r.data,before:o});break;case"local":a=Za({beamo:e,global:t,host:n,data:r.data,before:o});break;default:if(Gf.has(r.kind)){a=ai({beamo:e,global:t,host:n,kind:r.kind,data:r.data,before:o});break}return null}return a&&a.setAttribute("data-chat-card",r.kind),a}function ci({beamo:e,global:t,host:n,message:r}){if(!n||!e)return;let s=r.searchActivity;s&&typeof s=="object"&&typeof s.query=="string"&&s.query&&Us({beamo:e,global:t,host:n,activity:s});let o=r.card,a=zn(r);!(a&&ri({global:t,host:n,snapshot:a}))&&o&&typeof o=="object"&&typeof o.kind=="string"&&js({beamo:e,global:t,host:n,card:o})}function li({variant:e="panel",parent:t,onClearChat:n,t:r=s=>s}={}){if(!t||e!=="panel")return{refresh(){}};let s=document.createElement("div");s.className="chat-composer-context";let o=document.createElement("button");
4return o.type="button",o.className="chat-composer-scope__clear",o.textContent=r("chat.scope.clearChat"),o.setAttribute("aria-label",r("chat.scope.clearChatAria")),o.addEventListener("click",()=>n?.()),s.appendChild(o),t.insertBefore(s,t.firstChild),{refresh(){}}}function Vf(e){return e.replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/(?:\*\*|__)(.*?)(?:\*\*|__)/g,"$1").replace(/~~(.*?)~~/g,"$1").replace(/^\s{0,3}#{1,6}\s+/gm,"").replace(/^\s{0,3}>\s?/gm,"").replace(/^\s{0,3}(?:[-*+]|\d+\.)\s+/gm,"")}function ui(e,t=220){let n=Vf(String(e??"")).replace(/\s+/g," ").trim();return n?n.length<=t?n:"".concat(n.slice(0,Math.max(0,t-1)),"\u2026"):""}function Er({id:e,parent:t,className:n="sr-only",label:r=""}={}){if(!t)return null;let s=document.createElement("div");return e&&(s.id=e),s.className=n,s.setAttribute("role","status"),s.setAttribute("aria-live","polite"),s.setAttribute("aria-atomic","true"),r&&s.setAttribute("aria-label",r),t.appendChild(s),s}function Tr(e){e&&(e.textContent="",e.setAttribute("aria-live","off"))}function xr(e,t){e&&(e.setAttribute("aria-busy",t?"true":"false"),e.setAttribute("aria-live","off"))}function zs(e,t,{prefix:n="",assertive:r=!1}={}){if(!e)return;let s=ui(t,r?400:220);if(!s){Tr(e);return}let o=n?"".concat(n,": ").concat(s):s;e.setAttribute("aria-live",r?"assertive":"polite"),e.textContent=o}function Wn(e,t,{prefix:n=""}={}){zs(e,t,{prefix:n,assertive:!1})}function Yf(e,t,{prefix:n=""}={}){zs(e,t,{prefix:n,assertive:!0})}function di(e){e.plainTextForAnnouncement=ui,e.announceStreamStatus=zs,e.announceStreamComplete=Wn,e.announceStreamError=Yf,e.clearStreamAnnouncement=Tr,e.setStreamRegionBusy=xr}var Xf=/^[A-Za-z0-9_-]{8,64}$/;function Jf(e){return Ct(e)}function Gs(e){if(typeof e!="string")return"";let t=e.trim();return Xf.test(t)?t:""}function Ws(e){let t=Gs(e);return t?t.length>8?t.slice(0,8):t:""}function Gn(e,t,{document:n=globalThis.document}={}){let r=Gs(t);if(!e||!r)return null;let s=n.createElement("div");s.className="support-request-id",s.setAttribute("role","group"),s.setAttribute("aria-label","Support reference");let o=n.createElement("span");o.className="support-request-id__label",o.textContent="Error ref: ";let a=n.createElement("code");a.className="support-request-id__value",a.textContent=Ws(r),a.title=r;let i=n.createElement("button");return i.type="button",i.className="support-request-id__copy",i.textContent="Copy",i.setAttribute("aria-label","Copy support ID ".concat(Ws(r))),i.addEventListener("click",async c=>{c.preventDefault();try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(r);else{let l=n.createElement("textarea");l.value=r,l.setAttribute("readonly",""),l.style.position="absolute",l.style.left="-9999px",n.body.appendChild(l),l.select(),n.execCommand("copy"),l.remove()}i.textContent="Copied",globalThis.setTimeout(()=>{i.textContent="Copy"},2e3)}catch{i.textContent="Copy failed",globalThis.setTimeout(()=>{i.textContent="Copy"},2e3)}}),s.append(o,a,i),e.appendChild(s),s}function fi(e){e.requestIdFromPayload=Jf,e.normalizeRequestId=Gs,e.formatSupportIdLabel=Ws,e.appendSupportRequestId=Gn}function Qf({retryAfterSeconds:e,errorCode:t}){let n=Oe(e);return n<=0?!1:t&&_t(t)?!0:n>0}function Zf(e=globalThis){return typeof e?.setInterval=="function"?e:typeof globalThis?.setInterval=="function"?globalThis:e}function mi(e,{global:t=globalThis,retryAfterSeconds:n,label:r="Retry",onRetry:s,ariaLabel:o="Retry request"}={}){if(!e||typeof s!="function")return()=>{};let a=Zf(t),i=Oe(n);if(i<=0)return e.disabled=!1,e.textContent=r,e.setAttribute("aria-label",o),()=>{};let c=()=>{e.textContent=Is(i,r),e.setAttribute("aria-label","".concat(o," (").concat(i," second").concat(i===1?"":"s"," remaining)"))};c(),e.disabled=!0,e.classList.add("retry-action--countdown");let l=a.setInterval(()=>{if(i-=1,i<=0){a.clearInterval(l),e.disabled=!1,e.textContent=r,e.setAttribute("aria-label",o),e.classList.remove("retry-action--countdown"),e.addEventListener("click",u=>{u.preventDefault(),e.disabled=!0,s()},{once:!0});return}c()},1e3),m=l;return typeof m.unref=="function"&&m.unref(),()=>{a.clearInterval(l)}}function hi({document:e=globalThis.document,global:t=globalThis,retryAfterSeconds:n=0,errorCode:r="",label:s="Retry",ariaLabel:o="Retry request",onRetry:a}={}){if(typeof a!="function")return null;let i=e.createElement("button");return i.type="button",i.className="retry-action",Qf({retryAfterSeconds:n,errorCode:r})?(mi(i,{global:t,retryAfterSeconds:n,label:s,onRetry:a,ariaLabel:o}),i):(i.textContent=s,i.setAttribute("aria-label",o),i.addEventListener("click",c=>{c.preventDefault(),i.disabled=!0,a()}),i)}function Ks(e,t={}){let{retryAfterSeconds:n=0,errorCode:r="",requestId:s="",label:o="Retry",ariaLabel:a="Retry request",onRetry:i}=t,c=hi({retryAfterSeconds:n,errorCode:r,label:o,ariaLabel:a,onRetry:i});return c&&e?.appendChild(c),s&&Gn(e,s),c}function pi(e){e.startRetryCountdown=mi,e.createRetryAfterButton=hi,e.append
4RetryAfterAction=Ks}function Kn(e){e&&(e.textContent="")}function Rr(e,t){e?.setAttribute("aria-busy",t?"true":"false")}function gi({ariaLabel:e="Retry request",label:t="Retry",onRetry:n}={}){if(typeof n!="function")return null;let r=document.createElement("button");return r.type="button",r.className="retry-action",r.textContent=t,r.setAttribute("aria-label",e),r.addEventListener("click",s=>{s.preventDefault(),r.disabled=!0,n()}),r}function Pr(e,t={}){let n=Oe(t.retryAfterSeconds),r=String(t.errorCode??t.code??"").trim();if(typeof t.onRetry=="function"&&n>0&&_t(r))return Ks(e,{...t,retryAfterSeconds:n,errorCode:r});let s=gi(t);return s&&e?.appendChild(s),t?.requestId&&Gn(e,t.requestId),s}function yi(e){e.clearElement=Kn,e.setElementBusy=Rr,e.createRetryAction=gi,e.appendRetryAction=Pr}var em=["Summarize my search","Explain this simply","What should I ask next?"];function Nr(e){return e?.querySelector(".chat-message-list")||e}function Vs(e){let t=e?.querySelector(".chat-empty-state");if(!t)return;let n=Nr(e),r=!!(n.querySelector(".user-msg-element")||n.querySelector(".ai-msg-element"));t.hidden=r}function wi(e,t=80){if(!e)return!0;let n=Number(e.scrollHeight),r=Number(e.scrollTop),s=Number(e.clientHeight);return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(s)?!0:n-r-s<=t}var Si=140,tm=64;function Xs(e){if(!e)return 0;let t=(Number(e.scrollHeight)||0)-(Number(e.scrollTop)||0)-(Number(e.clientHeight)||0),r=Nr(e)?.querySelectorAll?.(".user-msg-element, .ai-msg-element"),s=r&&r.length?r[r.length-1]:null;if(!s||typeof s.getBoundingClientRect!="function"||typeof e.getBoundingClientRect!="function")return t;let a=(s.dataset?.turnSpacer&&s.firstElementChild?s.firstElementChild:s).getBoundingClientRect(),i=e.getBoundingClientRect();return!Number.isFinite(a?.bottom)||!Number.isFinite(i?.bottom)?t:a.bottom-i.bottom}function Ft(e,{smooth:t=!1,force:n=!1}={}){if(!e)return;if(n){let s=Number(e.scrollHeight);Number.isFinite(s)&&(t&&typeof e.scrollTo=="function"?e.scrollTo({top:s,behavior:"smooth"}):e.scrollTop=s),un(e);return}let r=Xs(e);if(r>Si){un(e);return}r>0&&Number.isFinite(Number(e.scrollTop))&&(e.scrollTop=(Number(e.scrollTop)||0)+r),un(e)}function un(e){let n=(e?.closest?.("#chat-interface")||e)?.querySelector(".chat-scroll-pill");if(!n)return;let r=Xs(e);n.hidden?r>Si&&(n.hidden=!1):r<=tm&&(n.hidden=!0)}function nm(e,t,n){if(!e)return;let r=e.closest?.("#chat-interface");if(!(!!r?.classList?.contains?.("chat-panel")||!!r?.classList?.contains?.("chat-home-max"))||!t){Ft(e,{force:!0});return}e.querySelectorAll(".ai-msg-element[data-turn-spacer]").forEach(i=>{i.style.minHeight="",delete i.dataset.turnSpacer});let o=Number(e.clientHeight)||0;if(n&&o>0){let i=Number(t.offsetHeight)||0,c=Math.max(180,o-i+100);n.style.minHeight="".concat(c,"px"),n.dataset.turnSpacer="1"}let a=Math.max(0,(Number(t.offsetTop)||0)-12);typeof e.scrollTo=="function"?e.scrollTo({top:a,behavior:"auto"}):e.scrollTop=a,un(e)}function rm(e,t){let n=()=>un(e);e.addEventListener("scroll",n,{passive:!0}),t.addEventListener("click",()=>{let r=Xs(e);r>0&&Number.isFinite(Number(e.scrollTop))?e.scrollTop=(Number(e.scrollTop)||0)+r+12:Ft(e,{force:!0}),t.hidden=!0}),un(e)}function Js(e,t,n){xr(e,n),Rr(t,n),n&&Tr(Qs(e))}function Qs(e){return(e?.closest("#chat-interface")||e?.parentElement)?.querySelector("#chat-stream-announcer")||null}function sm(e,t,n){xr(e,!1),Rr(t,!1),Wn(Qs(e),n,{prefix:"Beamo replied"})}function ki(e,t,{markdown:n=!0}={}){if(!e)return;let r=n&&e.classList.contains("ai-msg-text"),s=globalThis.Beamo?.markdown;if(r&&s&&typeof s.renderToFragment=="function"){e.replaceChildren(s.renderToFragment(t));return}e.textContent=t}function vi(e,t,n,{turnId:r=""}={}){let s=t==="user-msg-text",o=document.createElement("div");o.className=s?"user-msg-element":"ai-msg-element",o.setAttribute("aria-label",s?"Your message":"Beamo response"),o.setAttribute("role","article"),r&&(o.dataset.turnId=r);let a=document.createElement("div");return a.className=t,ki(a,n),r&&(a.dataset.turnId=r),s?a.setAttribute("aria-live","off"):(a.setAttribute("aria-atomic","false"),a.setAttribute("aria-live","off"),a.setAttribute("aria-busy",n?"false":"true")),o.appendChild(a),Nr(e).appendChild(o),Vs(e),Ft(e,{force:s}),a}function om(e){e&&(e.value="",e.style.height="")}function Ys(e){e&&(e.style.height="auto",e.style.height="".concat(e.scrollHeight,"px"))}function am(e){return e==="overlay"?"chat-overlay":e==="home"?"chat-home chat-home-max":"
4chat-panel"}function Ir(e,t,n){let r=document.createElement("button");r.type="button",r.className="chat-layout-toggle",r.setAttribute("aria-label",t),r.setAttribute("title",t),r.dataset.layoutAction=n;let s=n==="minimize"?"minimize":n==="maximize"?"expand":"close";return typeof e.createIcon=="function"?r.appendChild(e.createIcon(s,"beamo-icon")):r.textContent=n==="minimize"?"\u2212":n==="maximize"?"\u2922":"\xD7",r}function bi(e,{showSubtitle:t=!1,showLayoutControls:n=!1,onNewChat:r,onExportChat:s,onHistory:o,variant:a="panel",searchTerm:i="",threadTitle:c="Chat with Beamo"}){let l=document.createElement("div");l.className="chat-toolbar chat-home-toolbar";let m=document.createElement("div");m.className="chat-home-toolbar__brand",typeof e.createIcon=="function"&&m.appendChild(e.createIcon("sparkles","beamo-icon"));let u=document.createElement("div");u.className="chat-home-toolbar__copy";let d=document.createElement("p");d.className="chat-home-toolbar__title",d.textContent=c;let h=document.createElement("p");h.className="chat-home-toolbar__subtitle",h.hidden=a!=="panel"&&!t,(a==="panel"||t)&&(h.classList.add("chat-home-toolbar__subtitle--visible"),h.textContent=a==="panel"?"Search context defaults to your current query":"Ask questions, brainstorm, or get help with your search"),u.appendChild(d),u.appendChild(h),m.appendChild(u);let p=document.createElement("div");p.className="chat-home-toolbar__actions";let b=null,v=null,E=null,A=null,S=null,_=null,w=[],f=ua(e);if(o){E=document.createElement("button"),E.type="button",E.className="chat-history-button",E.setAttribute("aria-label","Show chat history"),E.setAttribute("title","Chat history"),E.setAttribute("aria-haspopup","dialog"),typeof e.createIcon=="function"&&E.appendChild(e.createIcon("history","beamo-icon"));let g=document.createElement("span");g.className="chat-history-button__label",g.textContent="History",E.appendChild(g),w.push(E)}if(s){v=document.createElement("button"),v.type="button",v.className="chat-export-button",v.setAttribute("aria-label","Export chat thread"),v.setAttribute("title","Export chat"),typeof e.createIcon=="function"&&v.appendChild(e.createIcon("copy","beamo-icon"));let g=document.createElement("span");g.className="chat-export-button__label",g.textContent="Export",v.appendChild(g),w.push(v)}if(r){b=document.createElement("button"),b.type="button",b.className="chat-clear-button",a==="panel"&&b.classList.add("chat-clear-button--prominent"),b.setAttribute("aria-label","Clear chat history for this session (removes up to ".concat(f," stored messages)")),b.setAttribute("title","Clear chat"),typeof e.createIcon=="function"&&b.appendChild(e.createIcon("trash","beamo-icon"));let g=document.createElement("span");g.className="chat-clear-button__label",g.textContent="Clear chat",b.appendChild(g),w.push(b)}return n?(A=Ir(e,"Minimize chat","minimize"),S=Ir(e,"Maximize chat","maximize"),S.hidden=!0,_=Ir(e,"Close chat","close"),w.push(A,S,_)):a==="panel"&&(_=Ir(e,"Close chat","close"),w.push(_)),w.forEach(g=>{g&&p.appendChild(g)}),l.appendChild(m),l.appendChild(p),{toolbar:l,titleElement:d,subtitleElement:h,newChatButton:b,exportButton:v,historyButton:E,minimizeButton:A,maximizeButton:S,closeButton:_}}function im(e,{ariaLabel:t="",labelledBy:n="",role:r="region",variant:s="panel",parent:o=document.body,searchTerm:a="",onSend:i,onClose:c,onLayoutToggle:l,onStop:m,onNewChat:u,onExportChat:d,onHistory:h,scopeContext:p=null,initialThreadTitle:b="",autoFocus:v=!0}={}){let E=b||ma({searchTerm:a,fallbackTitle:"Chat with Beamo"}),A=document.createElement("div");A.id="chat-interface",A.className=am(s),A.setAttribute("role",r),A.setAttribute("aria-busy","false"),n?A.setAttribute("aria-labelledby",n):t&&A.setAttribute("aria-label",t),o.appendChild(A);let S=null,_=null,w=null,f=null,g=null,C=null;if(s==="home"){let ne=bi(e,{showSubtitle:!0,showLayoutControls:!0,onNewChat:u,onExportChat:d,onHistory:h,variant:s,searchTerm:a,threadTitle:E});C=ne.titleElement,w=ne.newChatButton,f=ne.historyButton,S=ne.minimizeButton,_=ne.maximizeButton,g=ne.closeButton,A.appendChild(ne.toolbar)}else if(s==="panel"){let ne=bi(e,{showSubtitle:!1,showLayoutControls:!1,onNewChat:u,onExportChat:d,variant:s,searchTerm:a,threadTitle:E});w=ne.newChatButton,g=ne.closeButton,C=ne.titleElement,A.appendChild(ne.toolbar)}let T=document.createElement("div");
4T.className="chat-sync-banner",T.hidden=!0,T.setAttribute("role","status"),T.setAttribute("aria-live","polite"),A.appendChild(T);let x=document.createElement("div");x.id="chatContainer",x.setAttribute("aria-atomic","false"),x.setAttribute("aria-busy","false"),x.setAttribute("aria-label","Chat messages"),x.setAttribute("aria-live","off"),x.setAttribute("role","log"),Er({id:"chat-stream-announcer",parent:A,label:"Chat response status"});let N=document.createElement("div");N.className="chat-message-list",N.setAttribute("role","presentation"),x.appendChild(N);let B=document.createElement("div");B.className="chat-empty-state",B.setAttribute("aria-hidden","true");let I=document.createElement("div");I.className="chat-empty-state__icon",typeof e.createIcon=="function"&&I.appendChild(e.createIcon("chat","beamo-icon"));let y=document.createElement("p");y.className="chat-empty-state__title",y.textContent="What can I help with?";let k=document.createElement("p");k.className="chat-empty-state__hint",k.textContent=da({variant:s});let P=document.createElement("div");P.className="chat-empty-state__chips",P.setAttribute("role","group"),P.setAttribute("aria-label","Suggested prompts"),B.appendChild(I),B.appendChild(y),B.appendChild(k),B.appendChild(P),x.appendChild(B);let R=document.createElement("button");R.type="button",R.className="chat-scroll-pill",R.hidden=!0,R.setAttribute("aria-label","Jump to latest messages"),typeof e.createIcon=="function"&&R.appendChild(e.createIcon("chevronDown","beamo-icon"));let D=document.createElement("span");D.className="chat-scroll-pill__label",D.textContent="Jump to latest",R.appendChild(D),A.appendChild(x);let L=null;(s==="panel"||s==="home")&&(L=document.createElement("aside"),L.className="chat-panel__sidebar",L.setAttribute("aria-label","Sources for this conversation"),L.hidden=!0,A.appendChild(L));let $=document.createElement("div");$.className="chat-composer-wrap",$.appendChild(R),rm(x,R);let G=document.createElement("div");G.className="chat-composer",$.appendChild(G);let J=document.createElement("p");J.className="chat-composer-hint",J.textContent="Enter to send \xB7 Shift+Enter for new line",$.appendChild(J);let X=document.createElement("p");X.className="chat-composer-disclaimer",X.textContent="Beamo can make mistakes \u2014 double-check important answers.",$.appendChild(X),A.appendChild($);let W=document.createElement("div");W.className="chat-composer__actions";let V=document.createElement("textarea");V.id="chat-input",V.maxLength=2e4,V.placeholder="Ask anything",V.setAttribute("aria-controls","chatContainer"),V.setAttribute("aria-label","Chat message"),V.setAttribute("aria-multiline","true");let j=document.createElement("button");if(j.type="button",j.className="enter-button-style",j.setAttribute("aria-label","Send chat message"),j.disabled=!0,typeof e.createIcon=="function")j.appendChild(e.createIcon("arrow","beamo-icon chat-icon"));else{let ne=document.createElement("img");ne.src="/images/arrow.webp",ne.alt="",ne.className="chat-icon",j.appendChild(ne)}let ee=document.createElement("button");ee.type="button",ee.className="chat-stop-button",ee.setAttribute("aria-label","Stop generating"),ee.hidden=!0,typeof e.createIcon=="function"?ee.appendChild(e.createIcon("stop","beamo-icon")):ee.textContent="\u25A0",s!=="home"&&s!=="panel"&&(g=document.createElement("button"),g.type="button",g.className="close-button-style",g.setAttribute("aria-label","Close chat"),typeof e.createIcon=="function"?g.appendChild(e.createIcon("close","beamo-icon")):g.textContent="\xD7"),W.appendChild(ee),W.appendChild(j),g&&s!=="home"&&s!=="panel"&&W.appendChild(g),G.appendChild(V),G.appendChild(W);let Ee=null;if(p&&s==="panel"&&!w)Ee=li({variant:s,parent:$,t:p.t,onClearChat:()=>u?.({chatContainer:x,chatInput:V,chatInterface:A})});else if(u&&!w){let ne=document.createElement("p");ne.className="chat-composer-scope";let ce=document.createElement("button");ce.type="button",ce.className="chat-composer-scope__clear",ce.textContent="Clear chat",ce.setAttribute("aria-label","Clear chat history for this session"),ce.addEventListener("click",()=>u?.({chatContainer:x,chatInput:V,chatInterface:A})),ne.appendChild(ce),$.appendChild(ne)}let Y=!1;function se(){j.disabled=Y||!V.value.trim()}function ae(ne){Y=!!ne,A.setAttribute("aria-busy",Y?"true":"false"),ee.hidden=!Y,j.hidden=Y,se()}let Me=()=>{j.disabled||i?.({chatContainer:x,chatInput:V,chatInterface:A})};for(let ne of em){let ce=document.createElement("button");
4ce.type="button",ce.className="chat-empty-state__chip",ce.textContent=ne,ce.addEventListener("click",()=>{V.value=ne,Ys(V),se(),V.focus()}),P.appendChild(ce)}V.addEventListener("input",()=>{Ys(V),se()}),V.addEventListener("keydown",ne=>{ne.key==="Enter"&&!ne.shiftKey&&(ne.preventDefault(),Me())}),j.addEventListener("click",Me),ee.addEventListener("click",()=>m?.({chatContainer:x,chatInput:V,chatInterface:A})),g&&s!=="home"&&g.addEventListener("click",()=>c?.({chatContainer:x,chatInput:V,chatInterface:A})),w?.addEventListener("click",()=>u?.({chatContainer:x,chatInput:V,chatInterface:A})),A.querySelector(".chat-export-button")?.addEventListener("click",()=>d?.({chatContainer:x,chatInput:V,chatInterface:A})),f?.addEventListener("click",()=>h?.({chatContainer:x,chatInput:V,chatInterface:A}));let Te=s==="home"?{minimizeButton:S,maximizeButton:_,updateLayoutButtons(ne){let ce=ne==="max";S&&(S.hidden=!ce),_&&(_.hidden=ce)}}:null;return s==="home"&&Te&&(S.addEventListener("click",()=>c?.({action:"minimize",chatContainer:x,chatInput:V,chatInterface:A})),_.addEventListener("click",()=>l?.()),g?.addEventListener("click",()=>c?.({action:"close",chatContainer:x,chatInput:V,chatInterface:A})),Te.updateLayoutButtons("max")),v&&setTimeout(()=>V.focus(),100),{chatContainer:x,chatInput:V,chatInterface:A,syncBanner:T,sourcesSidebar:L,closeButton:g,historyButton:f,inputContainer:G,sendButton:j,stopButton:ee,layoutControls:Te,setStreamingBusy:ae,refreshSearchContextUi:()=>Ee?.refresh?.(),setThreadTitle(ne){if(!C)return;let ce=String(ne??"").trim()||"Chat with Beamo";C.textContent=ce,A.setAttribute("aria-label",ce)}}}function cm(e,t){if(!e)return!1;let n=Array.from(e.children||[]).filter(s=>s?.classList&&(s.classList.contains("user-msg-element")||s.classList.contains("ai-msg-element"))),r=t.filter(s=>s&&typeof s=="object"&&typeof s.content=="string");if(r.length===0||n.length<r.length)return!1;if(n.length>r.length){for(let s=r.length;s<n.length;s+=1)if(!n[s].dataset.chatLocalTurn)return!1}for(let s=0;s<r.length;s+=1){let o=r[s],a=n[s],i=o.role==="user"?"user":"ai",c=a.classList.contains("user-msg-element")?"user":"ai";if(i!==c)return!1;let l=i==="ai"?".ai-msg-text":".user-msg-text",m=a.querySelector(l),u=typeof o.turnId=="string"?o.turnId:"",d=a.dataset.turnId||m?.dataset?.turnId||"";if(u!==d)return!1;if(i==="ai"&&o.content.trim()){if(!m||!m.textContent||!m.textContent.trim())return!1;let h=a;if(o.searchActivity&&!h.querySelector(".chat-search-activity")||o.card&&!h.querySelector("[data-chat-card]")&&!zn(o)||zn(o)&&!h.querySelector("[data-chat-instant-snapshot]"))return!1}}return!0}function Zs(e,t,n={}){let{onRegenerateMessage:r=null,getSearchTermForActions:s=null,getGroundingSourcesForHistory:o=null,safeHostname:a,beamoNamespace:i=globalThis.Beamo,global:c=globalThis}=n,l=typeof o=="function"?o():[];if(!e)return;let m=Nr(e);if(cm(m,t)){Vs(e);return}let u=wi(e);e.classList.add("chat-rehydrating");try{for(let b of[".user-msg-element",".ai-msg-element"])for(let v of m.querySelectorAll(b))v.remove();let d=new Map,h=c.document?.getElementById("chat-input")||null,p=typeof s=="function"?s():"";for(let b of t){if(!b||typeof b!="object"||typeof b.content!="string")continue;let v=typeof b.turnId=="string"?b.turnId:"",E=b.role==="user"?"user-msg-text":"ai-msg-text",A=vi(e,E,b.content,{turnId:v});if(b.role==="user"&&v){d.set(v,b.content);continue}if(b.role==="assistant"&&v&&b.content.trim()){if(typeof r=="function"){let _=d.get(v)||"";_&&Hn({beamo:i,global:c,messageElement:A,chatContainer:e,chatInput:h,turnId:v,userMessage:_,searchTerm:p,onRegenerate:r})}ci({beamo:i,global:c,host:A.closest?.(".ai-msg-element")||A.parentElement,message:b});let S=Array.isArray(b.sources)&&b.sources.length>0?b.sources:l;Array.isArray(S)&&S.length>0&&Fn({beamo:i,global:c,host:A.closest?.(".ai-msg-element")||A.parentElement,sources:S,safeHostname:a,turnId:v})}}}finally{e.classList.remove("chat-rehydrating")}Vs(e),Ft(e,{force:u})}function lm({messageElement:e,chatContainer:t,message:n,onRetry:r,requestId:s="",retryAfterSeconds:o=0,errorCode:a=""}){if(!e)return;e.querySelector(".chat-partial-notice")?.remove();let i=document.createElement("div");
4i.className="chat-partial-notice",i.setAttribute("role","status");let c=document.createElement("p");c.className="chat-partial-notice__text",c.textContent=n,i.appendChild(c),Pr(i,{ariaLabel:"Retry for a complete answer",label:"Retry",onRetry:r,requestId:s,retryAfterSeconds:o,errorCode:a}),e.appendChild(i),Js(t,e,!1),Ft(t)}function um({messageElement:e,chatContainer:t,message:n,onRetry:r,requestId:s="",retryAfterSeconds:o=0,errorCode:a=""}){Kn(e);let i=document.createElement("span");i.textContent=n,e.appendChild(i),Pr(e,{ariaLabel:"Retry chat message",label:"Retry",onRetry:r,requestId:s,retryAfterSeconds:o,errorCode:a});let c=e.closest(".ai-msg-element")||e.parentElement;c&&(c.dataset.chatLocalTurn="1");let l=e.dataset?.turnId||c?.dataset?.turnId||"";if(l&&t){let m=t.querySelector(".chat-message-list")||t;for(let u of Array.from(m.children||[]))u?.classList?.contains("user-msg-element")&&u.dataset?.turnId===l&&(u.dataset.chatLocalTurn="1")}Js(t,e,!1),Ft(t)}function _i(e){e.mountChatMessageActions=t=>Hn({beamo:e,...t}),e.mountChatMessageSources=t=>Fn({beamo:e,...t}),e.setChatBusy=Js,e.announceChatStreamComplete=sm,e.getChatStreamAnnouncer=Qs,e.setMessageContent=ki,e.appendChatMessage=vi,e.renderChatHistory=Zs,e.resetChatInput=om,e.autosizeChatInput=Ys,e.isChatNearBottom=wi,e.scrollChatToBottom=Ft,e.scrollChatTurnIntoView=nm,e.createChatInterface=t=>im(e,t),e.showChatRetry=um,e.showChatPartialNotice=lm}function dm(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.max(1,Math.round(t)):0}function fm(e){return new Promise(t=>{globalThis.setTimeout(()=>t({}),e)})}function mm(e,t,n){let r=dm(t);return r?Promise.race([e,fm(r)]).catch(()=>n):e}function hm(e,t={}){let n=e?.__supabaseClient;if(!n||typeof n.getSession!="function")return{};if(typeof n.isConfigured=="function"&&!n.isConfigured())return{};let r=(async()=>{try{let o=(await n.getSession())?.access_token;return typeof o=="string"&&o?{Authorization:"Bearer ".concat(o)}:{}}catch{return{}}})();return mm(r,t.timeoutMs||0,{})}async function Ie(e,t={}){let n=hm(e,t);return n instanceof Promise,n}var pm=new Set(["web","sports","finance","macro","weather","aqi","currency","convert","local"]);function gm(e){return typeof e=="string"&&pm.has(e)?e:"web"}function Ci(e){let t=e.replace(/^data:\s*/,"").trim();if(!t||t==="[DONE]")return{done:!0,content:""};let n=JSON.parse(t);if(n===null||typeof n!="object")return{done:!1,content:""};let r=Ze(n);if(r)return{done:!0,content:r.message,error:!0,code:r.code,requestId:r.requestId,retryAfterSeconds:r.retryAfterSeconds,isThrottled:r.isThrottled};if(n.error)return{done:!0,content:ln(n,"Request failed."),error:!0,requestId:Ct(n)};if(typeof n.warning=="string"&&n.warning.trim()!=="")return{done:!1,content:"",warning:n.warning.trim()};if(Array.isArray(n.sources))return{done:!1,content:"",sources:n.sources};if(n.overviewMeta&&typeof n.overviewMeta=="object")return{done:!1,content:"",overviewMeta:n.overviewMeta};if(n.searchActivity&&typeof n.searchActivity.query=="string")return{done:!1,content:"",searchActivity:{query:n.searchActivity.query,kind:gm(n.searchActivity.kind)}};if(n.sportsPack&&typeof n.sportsPack=="object")return{done:!1,content:"",sportsPack:n.sportsPack};if(n.chatCard&&typeof n.chatCard=="object"&&typeof n.chatCard.kind=="string")return{done:!1,content:"",chatCard:{kind:n.chatCard.kind,data:n.chatCard.data}};if(n.research&&typeof n.research=="object"&&typeof n.research.phase=="string")return{done:!1,content:"",research:{phase:n.research.phase,...Array.isArray(n.research.queries)?{queries:n.research.queries.filter(o=>typeof o=="string")}:{},...Number.isFinite(n.research.sourceCount)?{sourceCount:Number(n.research.sourceCount)}:{},...Number.isFinite(n.research.remaining)?{remaining:Number(n.research.remaining)}:{},...Number.isFinite(n.research.limit)?{limit:Number(n.research.limit)}:{},...typeof n.research.tier=="string"?{tier:n.research.tier}:{},...typeof n.research.pro=="boolean"?{pro:n.research.pro}:{}}};let s=n.choices?.[0];return{done:!!(s?.finish_reason||n.finished),content:s?.delta?.content||s?.message?.content||n.content||"",replace:!!n.replace}}function Lr(e){return e.split(/\r?\n/).filter(t=>t.startsWith("data:")).map(t=>t.slice(5).replace(/^\s/,"")).join("\n")}function Vn(e,t=null){let n=Ct(t);if(n)return n;let r=e?.headers?.get?.("x-request-id");return typeof r=="string"?r.trim():""}async function Ai(e){let t=e.headers.get("content-type")||"",n=await e.text(),r="Request failed with HTTP ".concat(e.status,".");if(t.includes("application/json"))try{let s=JSON.parse(n),o=cn(s,e);return{message:o?.message||ln(s,r),requestId:Vn(e,s),code:o?.code||"request_failed",retryAfterSeconds:o?.retryAfterSeconds||0,isThrottled:!!o?.isThrottled}}catch{return{message:r,requestId:Vn(e,null),code:"request_failed",retryAfterSeconds:0,isThrottled:!1}}if(t.includes("text/event-stream"))for(let s of n.split(/\r?\n\r?\n/)){let o=Lr(s).trim();if(!(!o||o==="[DONE]"))try{let a=Ci("data: ".concat(o));return{message:a.content||r,requestId:a.requestId||Vn(e,null),code:a.code||"request_failed",retryAfterSeconds:a.retryAfterSeconds||0,isThrottled:!!a.isThrottled}}catch{return{message:o,requestId:Vn(e,null),code:"request_failed",retryAfterSeconds:0,isThrottled:!1}}}return{message:n.trim()||r,requestId:Vn(e,null),code:"request_failed",retryAfterSeconds:0,isThrottled:!1}}async function ym(e){return(await Ai(e)).message}function bm(e,t,n={}){let r=new AbortController,s=!1,o={onmessage:null,onerror:null,close(){s=!0,r.abort()}},a=n&&typeof n.headers=="object"&&n.headers?n.headers:{};return(async()=>{try{let i=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json",...a},body:JSON.stringify(t),signal:r.signal});if(!i.ok){let{message:d,requestId:h,code:p,retryAfterSeconds:b}=await Ai(i),v=br(p,d,i.status,{...h?{request_id:h}:{},...b>0?{retry_after:b}:{}});o.onmessage?.({data:JSON.stringify(v)}),o.onmessage?.({data:"[DONE]"});return}let c=i.body?.getReader();
4if(!c){(await i.text()).split(/\r?\n\r?\n/).forEach(h=>{let p=Lr(h);p&&o.onmessage?.({data:p})}),o.onmessage?.({data:"[DONE]"});return}let l=new TextDecoder,m="";for(;;){let{value:d,done:h}=await c.read();if(h)break;m+=l.decode(d,{stream:!0});let p=m.split(/\r?\n\r?\n/);m=p.pop()||"",p.forEach(b=>{let v=Lr(b);v&&o.onmessage?.({data:v})})}m+=l.decode();let u=Lr(m);u&&o.onmessage?.({data:u}),o.onmessage?.({data:"[DONE]"})}catch(i){!s&&i?.name!=="AbortError"&&o.onerror?.(i)}})(),o}async function dn(e,t={},n=8e3){let r=new AbortController,s=globalThis.setTimeout(()=>r.abort(),n),o=t.signal,a=()=>r.abort(o.reason);o?.aborted?r.abort(o.reason):o?.addEventListener("abort",a,{once:!0});try{return await fetch(e,{...t,signal:r.signal})}finally{globalThis.clearTimeout(s),o?.removeEventListener("abort",a)}}async function wm(e,t){try{let n=String(t??"").trim();if(!n)return!1;let r=e.config?.endpoints||{},s=e.config?.timeouts||{},o=await Ie(e),a=await dn(r.cancelChat||"/PHP/chatcancel.php",{method:"POST",headers:{...o,"Content-Type":"application/json"},body:JSON.stringify({turnId:n})},s.chatDeleteMs||5e3);return!!(a&&typeof a.ok=="boolean"&&a.ok)}catch{return!1}}async function Sm(e){let t=e.config?.endpoints||{},n=e.config?.timeouts||{},r=await Ie(e),s=await dn(t.deleteChat||"/PHP/deletechat.php",{method:"POST",headers:r},n.chatDeleteMs||5e3);if(s&&typeof s.ok=="boolean"&&!s.ok){let o=await ym(s);throw new Error(o)}return s}function Ei(e){e.parseStreamPayload=Ci,e.parseApiErrorPayload=Ze,e.parseApiErrorFromResponse=cn,e.createApiError=yr,e.errorMessageFromPayload=ln,e.requestIdFromPayload=Ct,e.buildApiErrorEnvelope=br,e.streamSsePost=bm,e.fetchWithTimeout=dn,e.deleteChatSession=()=>Sm(e),e.cancelChatTurn=t=>wm(e,t)}function fn(e){return te(globalThis,e,null)}function Br(e,t){ie(globalThis,e,t)}function mn(e){ca(globalThis,e)}function hn(e,t){let n=String(e??"").trim(),r=String(t??"").trim();if(!n||!r)return null;let s=Number(n),o=Number(r);return!Number.isFinite(s)||!Number.isFinite(o)||s===0&&o===0||s<-90||s>90||o<-180||o>180?null:{latitude:n,longitude:r}}function to(e){if(!e||typeof e!="object")return null;let t=e.latitude,n=e.longitude;if((t==null||n==null||t===""||n==="")&&typeof e.loc=="string"){let[s,o]=e.loc.split(",");t=s,n=o}let r=hn(t,n);return r?{...e,...r}:null}function Ti(){return{latitude:"0",longitude:"0"}}function eo(){mn("ipData"),mn("ipDataTimestamp")}function xi(){let e=Number(fn("ipDataTimestamp")||0);return e>0&&Date.now()-e<3600*1e3}function km(){let e=fn("latitude"),t=fn("longitude");if(!e&&!t)return null;let n=hn(e,t);return n||(mn("latitude"),mn("longitude"),null)}function no({allowLegacyCoordinates:e=!1}={}){if(e){let n=km();if(n)return n}let t=fn("ipData");if(!t||!xi())return null;try{let n=to(JSON.parse(t));if(n?.latitude&&n?.longitude)return n}catch{return eo(),null}return eo(),null}async function Ri(){let e=globalThis.Beamo?.config?.endpoints?.location||"/PHP/location.php",t=await dn(e,{headers:{Accept:"application/json"}},5e3);if(!t.ok)throw new Error("Location request failed with HTTP ".concat(t.status,"."));let n=to(await t.json());if(!n)throw new Error("Location response did not include usable coordinates.");return Br("ipData",JSON.stringify(n)),Br("ipDataTimestamp",String(Date.now())),n}async function vm(){let e=globalThis.Beamo?.config?.endpoints?.location||"/PHP/location.php",t=await dn(e,{headers:{Accept:"application/json"}},5e3);if(!t.ok)throw new Error("Location request failed with HTTP ".concat(t.status,"."));let n=await t.json();if(!n||typeof n!="object")throw new Error("Location response was not usable.");return n}var Mr=null;async function Or({allowLegacyCoordinates:e=!1,fallbackOnError:t=!1}={}){let n=no({allowLegacyCoordinates:e});if(n)return n;try{let r=Mr;if(!r){let s=Ri();Mr=s;let o=()=>{Mr===s&&(Mr=null)};s.then(o,o),r=s}return await r}catch(r){if(!t)throw r;return Ti()}}var _m=1800*1e3;function Pi(){mn("geoPosition"),mn("geoPositionTimestamp")}function Cm(e,t,n){let r=hn(e,t);if(!r)return null;
4let s={...r,accuracy:Number.isFinite(n)?n:null,source:"browser"};return Br("geoPosition",JSON.stringify(s)),Br("geoPositionTimestamp",String(Date.now())),s}function ro(){let e=fn("geoPosition"),t=Number(fn("geoPositionTimestamp")||0);if(!e||!(t>0)||Date.now()-t>=_m)return null;try{let n=JSON.parse(e),r=hn(n?.latitude,n?.longitude);if(r)return{...n,...r,source:"browser"}}catch{Pi()}return null}async function Ii(){let e=globalThis.navigator;if(!e||!("geolocation"in e)||!e.geolocation)return"unsupported";try{let t=e.permissions;if(t?.query){let n=await t.query({name:"geolocation"});if(n?.state==="granted"||n?.state==="denied"||n?.state==="prompt")return n.state}}catch{}return"prompt"}function Am({timeout:e=8e3,maximumAge:t=300*1e3}={}){return new Promise((n,r)=>{let s=globalThis.navigator?.geolocation;if(!s?.getCurrentPosition){r(new Error("Geolocation is not available."));return}s.getCurrentPosition(o=>{let{latitude:a,longitude:i,accuracy:c}=o.coords,l=Cm(a,i,c);l?n(l):r(new Error("Geolocation returned unusable coordinates."))},o=>r(o instanceof Error?o:new Error("Geolocation request failed.")),{enableHighAccuracy:!1,timeout:e,maximumAge:t})})}var Yn=null;function Ni(e={}){let t=e.timeout===void 0&&e.maximumAge===void 0;if(t&&Yn)return Yn;let n=Am(e);if(t){Yn=n;let r=()=>{Yn===n&&(Yn=null)};n.then(r,r)}return n}function Em(){let e=ro();if(e)return e;let t=no({allowLegacyCoordinates:!0});return t?{...t,source:"ip"}:null}async function Tm({allowPrompt:e=!1,fallbackToIp:t=!0}={}){let n=ro();if(n)return n;let r=await Ii();if(r==="granted"||r==="prompt"&&e)try{return await Ni()}catch{}if(t)try{let s=await Or({allowLegacyCoordinates:!0,fallbackOnError:!0});if(s&&hn(s.latitude,s.longitude))return{...s,source:"ip"}}catch{}return null}function Li(e){e.normalizeLocation=hn,e.normalizeIpData=to,e.fallbackLocation=Ti,e.clearCachedIpData=eo,e.isCachedIpDataFresh=xi,e.cachedIpLocation=no,e.fetchIpLocation=Ri,e.fetchRawIpData=vm,e.getLocationData=Or,e.cachedBrowserPosition=ro,e.clearBrowserPosition=Pi,e.geolocationPermissionState=Ii,e.requestBrowserPosition=Ni,e.cachedPreciseLocation=Em,e.getPreciseLocation=Tm}function pn(e){let t=String(e??"").trim();if(!t)return"";try{let n=t.startsWith("//")?new URL("https:".concat(t)):new URL(t);return n.protocol==="http:"||n.protocol==="https:"?n.href:""}catch{return""}}var xm=new Set(["com","org","net","edu","gov","mil","int","io","co","ai","app","dev","info","biz","me","tv","us","uk","ca","de","fr","jp","cn","au","in","nl","ru","br","es","it","ch","se","no","eu"]);function Mi(e){let t=String(e??"").trim();if(/^https?:\/\//i.test(t))return!!pn(t);if(t.includes("@")||!/^(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d{1,5})?(?:[/?#][^\s]*)?$/i.test(t)||!pn("https://".concat(t)))return!1;if(!/[/?#:]/.test(t)){let n=t.toLowerCase().split(".").pop()??"";if(!xm.has(n))return!1}return!0}function Rm(e){let t=String(e??"").trim();if(!t||!Mi(t))return"";let n=/^https?:\/\//i.test(t)?t:"https://".concat(t);return pn(n)}function Pm(e){let t=String(e??"").trim();return/^data:image\/(?:png|jpe?g|gif|webp);base64,[a-z0-9+/=]+$/i.test(t)?t:pn(t)}function Bi(e){e.url={safeHttpUrl:pn,isUrlQuery:Mi,coerceHttpUrl:Rm},e.safeHttpUrl=pn,e.safeImageUrl=Pm}var Hr=Object.freeze({country:"us",lang:"en",safesearch:"moderate",freshness:""}),Dr=Object.freeze({countries:[{value:"us",label:"United States"},{value:"gb",label:"United Kingdom"},{value:"ca",label:"Canada"},{value:"au",label:"Australia"},{value:"de",label:"Germany"},{value:"fr",label:"France"},{value:"es",label:"Spain"},{value:"it",label:"Italy"},{value:"nl",label:"Netherlands"},{value:"be",label:"Belgium"},{value:"at",label:"Austria"},{value:"ch",label:"Switzerland"},{value:"se",label:"Sweden"},{value:"no",label:"Norway"},{value:"dk",label:"Denmark"},{value:"fi",label:"Finland"},{value:"ie",label:"Ireland"},{value:"pt",label:"Portugal"},{value:"pl",label:"Poland"},{value:"cz",label:"Czechia"},{value:"gr",label:"Greece"},{value:"hu",label:"Hungary"},{value:"ro",label:"Romania"},{value:"jp",label:"Japan"},{value:"kr",label:"South Korea"},{value:"in",label:"India"},{value:"id",label:"Indonesia"},{value:"my",label:"Malaysia"},{value:"th",label:"Thailand"},{value:"sg",label:"Singapore"},{value:"nz",label:"New Zealand"},{value:"za",label:"South Africa"},{value:"ae",label:"United Arab Emirates"},{value:"sa",label:"Saudi Arabia"},{value:"il",label:"Israel"},{value:"tr",label:"Turkey"},{value:"mx",label:"Mexico"},{value:"br",label:"Brazil"},{value:"ar",label:"Argentina"},{value:"cl",label:"Chile"},{value:"co",label:"Colombia"},{value:"all",label:"All regions"}],languages:[{value:"en",label:"English"},{value:"es",label:"Spanish"},{value:"fr",label:"French"},{value:"de",label:"German"},{value:"it",label:"Italian"},{value:"pt",label:"Portuguese"},{value:"nl",label:"Dutch"},{value:"pl",label:"Polish"},{value:"sv",label:"Swedish"},{value:"da",label:"Danish"},{value:"no",label:"Norwegian"},{value:"fi",label:"Finnish"},{value:"cs",label:"Czech"},{value:"hu",label:"Hungarian"},{value:"ro",label:"Romanian"},{value:"ja",label:"Japanese"},{value:"ko",label:"Korean"},{value:"zh",label:"Chinese"},{value:"ar",label:"Arabic"},{value:"he",label:"Hebrew"},{value:"tr",label:"Turkish"},{value:"ru",label:"Russian"},{value:"hi",label:"Hindi"},{value:"id",label:"Indonesian"},{value:"ms",label:"Malay"},{value:"vi",label:"Vietnamese"},{value:"th",label:"Thai"},{value:"uk",label:"Ukrainian"},{value:"el",label:"Greek"}],freshness:[{value:"",label:"Any time"},{value:"pd",label:"Past day"},{value:"pw",label:"Past week"},{value:"pm",label:"Past month"},{value:"py",label:"Past year"}],safesearch:[{value:"moderate",label:"Moderate"}
4,{value:"strict",label:"Strict"},{value:"off",label:"Off"}]}),$r={countries:new Set(Dr.countries.map(e=>e.value)),languages:new Set(Dr.languages.map(e=>e.value)),freshness:new Set(Dr.freshness.map(e=>e.value)),safesearch:new Set(Dr.safesearch.map(e=>e.value))};function Im(e){let t=String(e??"").trim().toLowerCase();return $r.countries.has(t)?t:Hr.country}function Nm(e){let t=String(e??"").trim().toLowerCase();return $r.languages.has(t)?t:Hr.lang}function Lm(e){let t=String(e??"").trim().toLowerCase();return t==="any"?"":$r.freshness.has(t)?t:Hr.freshness}function Mm(e){let t=String(e??"").trim().toLowerCase();return $r.safesearch.has(t)?t:Hr.safesearch}function lt(e={}){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{country:Im(t.country),lang:Nm(t.lang??t.search_lang),freshness:Lm(t.freshness),safesearch:Mm(t.safesearch)}}var Fr=new WeakMap;function Bm(e,t,n){!t||n==null||(Fr.has(e)||Fr.set(e,new Map),Fr.get(e).set(t,{cachedAt:Date.now(),data:n}))}function Om(e,t,n=300*1e3){let r=Fr.get(e);if(!r)return null;let s=r.get(t);if(r.delete(t),!s)return null;let o=Number(s.cachedAt);return!Number.isFinite(o)||Date.now()-o>n?null:s.data??null}function Oi(e,t=globalThis){!e||typeof e!="object"||(e.storeSpeculativeSearchPayload=(n,r)=>{Bm(t,n,r)},e.takeSpeculativeSearchPayload=(n,r)=>Om(t,n,r))}function Dm(e=globalThis.Beamo||{}){let t=e;return aa(t),Bi(t),Li(t),yi(t),ga(t),pi(t),Ei(t),fi(t),di(t),_i(t),Oi(t,globalThis),globalThis.Beamo=t,t}Dm();var Di={settings:{button:"Settings",groupAppearance:"Appearance",groupAiAssistant:"AI assistant",groupSearch:"Search",groupChat:"Chat",groupPrivacyHistory:"Privacy & history",groupApp:"App",groupHelpLegal:"Help & legal",theme:"Theme",themeLight:"Light",themeDark:"Dark",themeSystem:"System",uiLanguage:"Interface language",uiLangEn:"English",uiLangDe:"Deutsch",uiLangEs:"Espa\xF1ol",uiLangFr:"Fran\xE7ais",uiLangPt:"Portugu\xEAs",uiLangZh:"\u4E2D\u6587",uiLangHi:"\u0939\u093F\u0928\u094D\u0926\u0940",uiLangJa:"\u65E5\u672C\u8A9E",uiLangBn:"\u09AC\u09BE\u0982\u09B2\u09BE",uiLangRu:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439",temperature:"Temperature",tempAuto:"Auto (Local)",tempFahrenheit:"Fahrenheit (\xB0F)",tempCelsius:"Celsius (\xB0C)",installApp:"Install app",addToHomeScreen:"Add to Home Screen",addToHomeScreenHelp:"Add to Home Screen instructions",appEmpty:"Beamo is ready to install from your browser\u2019s menu when available.",chatAutoSend:"Send search when opening Chat",chatAutoSendHint:"Uses your toolbar query once per search (optional).",searchOnly:"Disable AI",searchOnlyHint:"Turn off every AI feature in Beamo Search. Expand below to choose individual features.",aiFeaturesChoose:"Choose which AI features are on",aiFeaturesGroupAria:"Individual AI features",alwaysShowResults:"Always show search results",alwaysShowResultsHint:"Show web results even for instant answers that normally hide them.",aiFeatureOverviewLabel:"AI Overviews",aiFeatureOverviewHint:"The AI summary at the top of search results.",aiFeatureChatLabel:"AI Chat",aiFeatureChatHint:"Ask follow-up questions about a search in the Chat tab.",aiFeaturePeriodicAskLabel:"Periodic table AI",aiFeaturePeriodicAskHint:"\u201CAsk Beamo\u201D about an element in the periodic table.",aiFeatureCalcAssistLabel:"Calculator assistant",aiFeatureCalcAssistHint:"Solve word problems with the calculator\u2019s AI helper.",aiFeatureTranslateLabel:"AI translation",aiFeatureTranslateHint:"The interactive translation answer and widget.",aiFeatureLanguageToolsLabel:"Language tools",aiFeatureLanguageToolsHint:"Grammar, rewriting, and bilingual language helpers.",aiFeatureUrlAskLabel:"Ask about a URL",aiFeatureUrlAskHint:"Summarize or ask questions about a web page (Beamo Search Pro).",terms:"Terms of Service",privacy:"Privacy Policy",feedback:"Send feedback",travel:"Travel",blog:"Blog",support:"Support",setDefault:"Set as default search engine",faq:"FAQ",products:"Our Products",filtersGroup:"Search filters",clearHistory:"Clear search history",clearHistoryHour:"Last hour",clearHistoryWeek:"Last week",clearHistoryMonth:"Last month",clearHistoryYear:"Last year",clearHistoryAll:"All time",aiAnswers:"AI answers",aiPresetFaster:"Fast",aiPresetMedium:"Medium",aiPresetDeeper:"Deep",aiDeepProviderLabel:"Deep reasoning model",aiDeepProviderHint:"Beamo Search Pro \xB7 powers your Deep answers.",aiDeepOverviewTitle:"Deep answers in search",aiDeepOverviewHint:"Beamo Search Pro \xB7 also use your Deep model for the search AI Overview, not just Chat. On by default for Pro \u2014 turn it off here if you prefer faster overviews.",customInstru
4ctionsLabel:"Custom AI instructions",customInstructionsPlaceholder:"e.g. Always be concise, show your sources, and explain at an expert level.",customInstructionsHint:"Beamo Search Pro \xB7 saved and applied to every AI overview and chat answer.",watchesTitle:"Search watches",watchesHint:"Beamo Search Pro \xB7 we re-run these for you and email you when the results meaningfully change (a new top result or breaking news), judged by AI.",watchesAdd:"Add watch",watchesAddPlaceholder:"Search to monitor (e.g. \u201COpenAI news\u201D)",watchesAddAria:"Search to monitor",watchesEmpty:"You aren\u2019t watching any searches yet.",watchesRemove:"Remove",watchesActive:"Active",watchesPaused:"Paused",watchesNoChangeYet:"No changes yet",watchesAdded:"Now watching \u201C{query}\u201D.",watchesDuplicate:"You\u2019re already watching that search.",watchesLimit:"You can watch up to {limit} searches.",watchesError:"Something went wrong. Please try again.",watchesProRequired:"Search watches are a Beamo Search Pro feature."},feedbackForm:{title:"Report an issue",hint:"Describe what went wrong. Do not paste passwords, API keys, or full chat transcripts.",messageLabel:"Your message",messagePlaceholder:"What happened? What did you expect instead?",submit:"Send report",cancel:"Cancel"},consent:{title:"Before you start",message:"By using Beamo Search you agree to our Terms and Privacy Policy.",noteGdpr:"You're in a region with strong privacy laws (GDPR). We use only first-party storage for the site and privacy-safe analytics \u2014 no ads or cross-site tracking \u2014 and you can review, export, or delete your data anytime.",noteCcpa:"California: we don't sell or share your personal information, and you can review or delete your data anytime.",noteGeneral:"We keep it simple \u2014 search, AI features, and first-party product analytics only, no ad tracking \u2014 and you stay in control of your data.",privacy:"Privacy Policy",terms:"Terms",agree:"Agree & continue",dismiss:"Dismiss"},home:{searchPlaceholder:"Type a question or search term\u2026",title:"What do you want to know?"},discovery:{accountUpsell:{title:"Get more from Beamo Search \u2014 free",ariaLabel:"Create a free Beamo account",itemAnswers:"Smarter Medium-tier AI answers on every search.",itemResearch:"Research mode: cited deep-dive reports, 10 runs a month.",itemSync:"Your settings, chats, and preferences synced across devices.",cta:"Create a free account",dismiss:"Not now"},proUpsell:{title:"Do more with Beamo Search Pro",ariaLabel:"Upgrade to Beamo Search Pro",itemDeep:"Deep-tier answers on our most capable model, never downgraded.",itemResearch:"20 research runs a month with more advanced reports.",itemPerks:"Custom AI instructions, search watches, and Ask-about-a-URL.",cta:"Upgrade to Pro",dismiss:"Not now"}},toolbar:{search:"Search",searchPlaceholder:"Search",share:"Share",copyLink:"Copy link",shareSearchAria:"Share link to this search",copySearchAria:"Copy link to this search",watch:"Watch",watching:"Watching",watchSearchAria:"Watch this search for changes",research:"Research",researchAria:"Run deep research on this search",saveSearch:"Save",saveSearchAria:"Save this search to your account",goSearch:"Search",resultsFor:"Results for {query}"},tabs:{all:"All",chat:"Chat",images:"Images",news:"News",videos:"Videos",maps:"Maps",travel:"Travel",travelAria:"Search flights on Kiwi.com (opens in new tab)"},filters:{group:"Search filters",region:"Region",language:"Language",time:"Time",safeSearch:"Safe search",activePrefix:"Region",activeLanguage:"Language",activeTime:"Time",activeSafeSearch:"Safe search"},empty:{activeFilters:"Active filters: {list}",tryNext:"Try next:",noResultsTitle:"No {type} results for this search",noResultsLead:"We could not find any {type} results. Adjust your query or try a different view.",noResultsLeadRestrictive:"No web results matched your current filters. Broadening region, language, or time range often helps.",noResultsLeadStrict:"No web results with strict spelling. You can search the original wording or try another tab.",thinTitle:"Only {count} on Web",thinLead:"This search returned few web matches. Related topics or another tab may surface more.",thinLeadRelated:"These related searches may help.",typeWeb:"web",typeImages:"images",typeNews:"news",typeVideos:"videos",typeChat:"chat",countOne:"1 result",countMany:"{count} results",actionDisableStrict:"Search without spelling correction",actionResetFilters:"Reset filters to defaults",actionRetryWithoutFilters:"Retry without filters",actionTryImages:"Try Images",actionTryNews:"Try News",actionTryVideos:"Try Videos",actionTryWeb:"Try Web results",actionEditSearch:"Edit search query",actionsLabel:"Suggested next steps",relatedSearches:"Related searches",spellcheckTitle:"Try the suggested spelling",spellcheckLead:"Brave found results for \u201C{altered}\u201D. You searched for \u201C{original}\u201D with exact spelling.",spellcheckActionsLabel:"Spelling options",actionUseSpellcheck:"Search for \u201C{query}\u201D",actionSearchOriginalStrict:"Keep \u201C{query}\u201D (exact spelling)",noResultsLeadLooseWeb:"Turning off exact spelling finds about {count} web results. Use the buttons above or try another tab."},mapsPanel:{emptyQuery:"Enter a place or address to see it on the map.",loading:"Loading map\u2026",notFound:"We could not find a map location for \u201C{term}\u201D. Try a city, address, or landmark.",tilesFailed:"Map tiles could not be loaded. Try again or use Open in OpenStreetMap below.",loaded:"Map loaded for {label}.",loadedGeneric:"Map loaded.",directions:"Directions",details:"Details",website:"Website",call:"Call",openNow:"Open",closedNow:"Closed",placesFor:"Places for \u201C{term}\u201D",mapAriaLabel:"Interactive map of places for {term}. Use arrow keys to pan, plus and minus to zoom.",loadedPlaces:"{count} places found for {term}. Map loaded."},aiService:{unavailableTitle:"AI summaries aren't available right now",quotaTitle:"AI is maxed out for today",busyTitle:"AI is a bit busy right now",degradedTitle:"AI may be slower than usual",defaultMessage:"Your web results loaded fine. You can keep searching or give the AI overview another try.",quotaMessage:"We've hit today's limit for AI summaries. You can still search normally \u2014 AI will be back tomorrow.",busyMessage:"AI hit a few errors and needs a moment to recover. Search still works \u2014 try again shortly.",degradedMessage:"AI summaries might take a bit longer than usual or need a retry. Search still works.",tryLaterMessage:"AI is a bit overloaded right now. Try again in a moment.",unavailableMessage:"AI summaries and chat are down for now, but you can still search the web.",timeoutMessage:"The AI summary took too long. Try again and it should be faster.",retryOverview:"Retry AI overview",retryOverviewAria:"Retry AI overview",searchOnlyOn:"Search-only mode on",searchOnlyOff:"Continue without AI",statusLink:"Service status",dismiss:"Dismiss"},aiErrors:{dailyLimit:"We've hit today's limit for AI. You can still search \u2014 AI will be back tomorrow.",busy:"AI is a bit busy right now. Search still works \u2014 try again in a moment.",rateLimited:"You've sent a lot of AI requests. Wait a moment and try again."},searchUpstream:{degradedTitle:"Search may be a little slow",circuitTitle:"Search is catching up",staleTitle:"Showing saved results",majorTitle:"Search isn't loading right now",degradedMessage:"Results might be a bit slower than usual. Try refreshing if something looks off.",majorMessage:"Search isn't loading right now. Results saved on this device may still appear.",staleMessage:"The
4se results were saved from an earlier search while we catch up.",deviceCacheMessage:"Showing results saved on this device \u2014 live search isn't available at the moment.",statusLink:"Service status",dismiss:"Dismiss",retryAria:"Retry search"},errors:{requestFailed:"Something went wrong. Please try again.",loadResults:"We couldn't load results. Please try again.",retry:"Retry",tryAgainOneSecond:"Try again in 1 second",tryAgainSeconds:"Try again in {seconds} seconds",rateLimited:"You've made a lot of requests. Wait a moment and try again.",upstreamQuota:"Search isn't available at the moment. Give it a minute and try again.",circuitOpen:"Search is recovering and will be back shortly. Please try again in a moment.",originForbidden:"This request was blocked for security reasons.",invalidRequest:"This request couldn't be processed. Please try again."},chat:{connectionError:"Sorry, there was an error connecting to the server. Please try again.",stopped:"Previous response stopped.",partialSaved:"This reply may be incomplete. It was saved to your chat history \u2014 you can retry for a full answer.",scope:{contextLabel:"Search context",clearChat:"Clear chat",clearChatAria:"Clear chat history for this session",useThisSearch:"This search (default)",generalChat:"General chat",citeOnlyLabel:"Only cite numbered search results",citeOnlyHint:"Cite-only mode is on \u2014 answers stay within your result snippets and overview.",searchContextOn:"Search context on",searchContextOff:"Search context off"}},share:{copied:"Copied!",copyFailed:"Copy failed",linkCopied:"Link copied",shared:"Shared",searchLinkCopiedAria:"Search link copied to clipboard",searchLinkSharedAria:"Search link shared"},mobile:{appShellAria:"Beamo Search mobile app",brandAlt:"Beamo Search",themeToggleAria:"Switch to dark theme",themeToggleTitle:"Dark mode",searchLabel:"Search or enter address",searchPlaceholder:"Search or enter address",searchSubmit:"Search",shortcutGridAria:"Search categories",shortcutAll:"All",shortcutImages:"Images",shortcutNews:"News",shortcutVideos:"Videos",shortcutChat:"Chat",browserSurfaceAria:"Browser view",frameTitle:"Beamo browser view",offline:{banner:"You're offline. Cached Beamo pages in the viewer below may still work. Reconnect for new searches or external sites.",bannerCached:"You're offline. Showing cached Beamo results below. Reconnect to refresh or run a new search.",bannerCachedOnline:"You're online. The viewer below is showing cached search results saved on this device.",status:"Offline \u2014 reconnect for new searches and external sites.",statusCached:"Offline \u2014 showing cached Beamo results below.",statusCachedOnline:"Showing cached search results saved on this device.",statusBackOnline:"Back online.",blockExternal:"You're offline. External sites need a connection.",blockNavigation:"You're offline. Reconnect to open this page.",reload:"Reloading cached page\u2026",prefetchToggleOff:"Save searches for offline: Off",prefetchToggleOn:"Save searches for offline: On",prefetchUnavailable:"Saving searches for offline requires the production Beamo site (not a local dev server).",prefetchDialogTitle:"Save recent searches for offline?",prefetchDialogLead:"When enabled, Beamo may load your recent searches in the background while you are online so they stay available if you lose connection.",prefetchConfirm:"Enable",prefetchCancel:"Not now",prefetchDisable:"Turn off",prefetchProgress:"Updating offline copies\u2026",prefetchDone:"Offline copies updated."},nav:{back:"Back",backAria:"Back",forward:"Forward",forwardAria:"Forward",home:"Home",homeAria:"Home",reload:"Reload",reloadAria:"Reload",go:"Go",goAria:"Go"},status:{ready:"Ready",loading:"Loading\u2026",reloading:"Reloading\u2026",loaded:"Loaded. Use full screen if a site blocks embedded viewing.",addQuery:"Add a search query to open results.",lockBlocked:"Unlock the app to continue."},openFullscreen:"Open full screen",biometric:{lockToggleOn:"App lock: On",lockToggleOff:"App lock: Off",settingsAria:"App lock options",idleLabel:"Auto-lock after inactivity",idleOff:"Off",idle1m:"1 minute",idle5m:"5 minutes",idle15m:"15 minutes",idle30m:"30 minutes",lockOnLeaveLabel:"Lock when leaving the app",lockOnLeaveHint:"Shows the lock screen when you switch away (recommended for privacy).",promptO
4nResumeLabel:"Require unlock when returning",promptOnResumeHint:"Prompts Face ID, fingerprint, or device PIN when you open the app again.",title:"Unlock Beamo Search",lead:"Use Face ID or fingerprint to continue. App lock does not sign you out or clear site cookies in search.",leadDeviceCredential:"Use your device PIN, pattern, or password to continue. App lock does not sign you out or clear site cookies in search.",hintSignedIn:"Your Beamo account stays signed in inside search after unlock (session cookies are not cleared).",hintSignedOut:"Sign in from search settings after unlock if you use a Beamo account.",unlock:"Unlock with biometrics",unlockDevice:"Unlock with device PIN",authReason:"Unlock Beamo Search",authCancel:"Cancel",iosFallbackTitle:"Use passcode",androidTitle:"Unlock Beamo Search",androidSubtitle:"Use biometrics or your device PIN",unavailableAlert:"App lock needs Face ID, fingerprint, or a device PIN, pattern, or password. Set one in system settings, then try again."}},nav:{home:"Home",chat:"Chat"},mapsPack:{title:"Places",openMaps:"Open Maps",mapAriaLabel:"Map of places for {term}",nearYou:"near you"},sportsPack:{title:"Sports",live:"Live",today:"Today",yesterday:"Yesterday",tomorrow:"Tomorrow",attribution:"Scores via ESPN",matches:"Matches",schedule:"Schedule",standings:"Standings",leaders:"Leaders",vs:"vs",win:"W",loss:"L",draw:"D",home:"Home",away:"Away",streak:"Streak",last10:"Last 10",gameOf:"Game {game} of {of}",updatedAt:"Updated {time}",outsOne:"{count} out",outsOther:"{count} outs",allScores:"All scores",age:"Age {age}",injured:"Injured",nextGame:"Next",noStats:"Season stats aren't available right now.",playerProfile:"Full profile on ESPN"},richAnswer:{actionsGroup:"Answer actions",copy:"Copy",copied:"Copied",copyAria:"Copy this answer to the clipboard",copyTitle:"Copy this answer",share:"Share",shareAria:"Share this answer",shareTitle:"Share this answer",save:"Save",saved:"Saved",saveAria:"Save this answer to your saved instant answers",saveTitle:"Save this answer",prefs:"Prefs",prefsAria:"Card preferences",watch:"Watch",watching:"Watching",watchAria:"Watch this search for updates",watchSaved:"This instant-answer search is saved in Search watches.",watchLimit:"You have reached your watch limit.",watchError:"Could not save this watch. Please try again.",working:"\u2026",watchUpdates:"Watch updates",watchTrackingSaved:"This tracking search is saved in Search watches.",watchTrackingError:"Could not save this tracking watch. Please try again.",alertControls:"Alert controls",alertNote:"Saved watches use these domain-specific signals when the provider can supply them.",prefsHeading:"Card preferences",savePrefs:"Save preferences",prefDefaultWeatherLocation:"Default weather location",prefPreferredUnits:"Preferred units",prefUnitAuto:"Auto",prefUnitFahrenheit:"Fahrenheit",prefUnitCelsius:"Celsius",prefPreferredLanguage:"Preferred language",prefPreferredLanguagePlaceholder:"e.g. Spanish",prefHomeLanguage:"Home language",prefHomeLanguagePlaceholder:"e.g. English",prefHomeCity:"Home city",prefHomeCityPlaceholder:"e.g. Austin, TX",prefFinanceSymbols:"Favorite symbols",prefFinanceSymbolsPlaceholder:"e.g. AAPL, MSFT",prefHomeAirport:"Home airport",prefHomeAirportPlaceholder:"e.g. JFK",prefAlertThreshold:"Alert threshold",prefAlertThresholdPlaceholder:"e.g. 15",prefFavoriteTeams:"Favorite teams",prefFavoriteTeamsPlaceholder:"e.g. Lakers, Yankees",unavailableTitle:"Data temporarily unavailable",notFoundTitle:"Couldn't find that place",sourceQuality:"Source quality",sourceLabel:"Source",statusLabel:"Status",stateLabel:"State",whyLabel:"Why this showed",statusNotFound:"Not found",statusUnavailable:"Temporarily unavailable",stateNoMatch:"no match",stateDegraded:"degraded",dataProvider:"the data provider",retryAnswerAria:"Retry {kind} answer",whyNotFound:"Matched the {kind} instant-answer intent for \u201C{query}\u201D, but that place could not be located.",whyUnavailable:"Matched the {kind} instant-answer intent for \u201C{query}\u201D, but the provider could not be reached."},accounts:{signedOutIntro:"Optional Beamo account \u2014 sync saved searches, recent history, chat, and preferences across your devices.",comingSoonTitle:"Beamo accounts are coming soon",comingSoonBody:"Sign-in isn't available just yet. Soon you'll be able to create a free Beamo account to sync your saved searches, recent history, chat threads, and preferences across every device.",comingSoonNote:"Check back soon \u2014 your Beamo experience will follow you everywhere you search.",syncBenefitsHeading:"What syncs with your account",syncBenefitSaved:"Saved searches you pin from results",syncBenefitRecent:"Recent search history (when enabled in settings)",syncBenefitChat:"Chat conversation on this device",syncBenefitPrefs:"Theme, search f
4ilters, and other preferences",syncBenefitsSignedIn:"Sync is on for saved searches, recent history, chat, and preferences on this device.",signInGoogle:"Continue with Google",signInApple:"Continue with Apple",orDivider:"or",signInTitle:"Welcome back",signInSubtitle:"Sign in to sync your searches, history, and settings across devices.",createAccountTitle:"Create your account",createAccountSubtitle:"One free account keeps everything in sync across your devices.",signInSubmit:"Sign in",createAccountSubmit:"Create account",signInSwitchPrompt:"New to Beamo?",signInSwitchAction:"Create account",createSwitchPrompt:"Already have an account?",createSwitchAction:"Sign in",forgotPassword:"Forgot password?",otpToggle:"Email me a sign-in code instead",otpToggleBack:"Use a password instead",otpSendButton:"Email me a code",otpSentPrefix:"Enter the code we sent to ",otpCodeLabel:"Sign-in code",otpCodeHint:"Check your inbox \u2014 the code expires shortly. You can also tap the link in the email.",otpVerifyButton:"Sign in",otpResend:"Send a new code",manageHeading:"Email & password",changeEmailLabel:"Email address",changeEmailButton:"Update email",changeEmailNewLabel:"New email address",currentEmailPrefix:"Current: {email}. ",changeEmailHint:"We'll email both your current and new address to confirm the change.",changePasswordHeading:"Change password",changePasswordCurrentLabel:"Current password",changePasswordNewLabel:"New password",changePasswordConfirmLabel:"Confirm new password",changePasswordButton:"Update password",setPasswordHeading:"Add a password",setPasswordIntro:"You sign in with a connected account. Add a password so you can also sign in with your email.",setPasswordButton:"Email me a link to set a password",setPasswordSent:"Check your inbox for a link to set your password.",verifyBannerTitle:"Verify your email",verifyBannerBody:"We sent a link to your inbox. Open it on this device (or copy the link into this browser) to finish securing your account.",verifyBannerMobileHint:"Tip: if mail opened outside the Beamo app, return here after tapping the link.",resendVerification:"Resend verification email",conflictTitle:"Sync needs your attention",busyTitle:"Sync is busy",refreshPage:"Refresh page",trySyncAgain:"Try sync again",dismissSyncBanner:"Dismiss",verifyChecking:"Checking your verification link\u2026",verifyMissingToken:"Missing verification token. Open the link from your email.",verifySuccess:"Email verified successfully.",emailChangeSuccess:"Your email address change is confirmed on this side. If we asked you to confirm from your other inbox too, open that link to finish.",verifyContinueApp:"Continue in Beamo",verifyContinueWeb:"Back to Beamo Search",verifyOpenSettings:"Open settings",securityHeading:"Sign-in & security",passkeysHeading:"Passkeys",passkeysIntro:"Sign in with Face ID, Touch ID, or your device PIN \u2014 no password typing.",passkeysEmpty:"No passkeys yet. Add one on this device to sign in faster.",passkeysIosHint:"On iPhone, stay on this screen and approve the Face ID or Touch ID prompt when it appears.",passkeysEmbeddedHint:"Passkeys work best in Safari. If setup fail
4s in the app browser, open beamosearch.com in Safari, sign in, and add a passkey from Settings.",passkeyRegisterSuccess:"Passkey added. You can sign in with Face ID, Touch ID, or your device PIN on this device.",passkeySuccessDismiss:"Dismiss",passkeyRegistering:"Waiting for your device\u2026",sessionsHeading:"Active sessions",sessionsIntro:"These browsers and devices can access your signed-in account.",sessionsLoading:"Loading sessions\u2026",signOutEverywhere:"Sign out everywhere else",signOutEverywhereConfirm:"Sign out all other browsers and devices? They will need to sign in again. This device stays signed in.",signOutEverywhereSuccess:"Other sessions were signed out.",signOutEverywhereNone:"No other active sessions to sign out.",signOutHere:"Sign out on this device",revokeSession:"Revoke session",sessionCurrent:"This device",accountSettings:"Account settings",manageAccount:"Manage your account",yourDataPrivacy:"Your data & privacy",accountPageTitle:"Settings",settingsPageSubtitle:"Preferences, profile, security, billing, and your synced data.",searchSettingsPlaceholder:"Search settings",searchSettingsAria:"Search settings",searchSettingsClear:"Clear search",searchSettingsNoMatch:"No settings match your search.",sectionNavHeading:"On this page",sectionNavAria:"Jump to a settings section",proActiveBadge:"Beamo Search Pro active",proThanks:"Thanks for supporting Beamo \u2014 ads are off, the Deep AI tier is unlocked (and never downgraded), and you can ask Beamo about any link.",proRenews:"Renews {date}",proManage:"Manage subscription",proTagline:"Ad-free, the smartest AI Beamo offers, and 10\xD7 the memory \u2014 for less than a coffee a month.",proAnnual:"Annual",proMonthly:"Monthly",proSave:"Save {pct}%",proBillingCycleAria:"Billing cycle",proPerMonth:"/mo",proBilledYearly:"Billed yearly",proBilledMonthlySwitch:"Billed monthly \xB7 switch to annual anytime",proBilledMonthly:"Billed monthly",proBilledAnnualSave:"Billed {price} \u2014 save {amount} ({pct}%) vs monthly",proBilledAnnual:"Billed {price}",proUpgrade:"Upgrade to Pro",proOpeningCheckout:"Opening secure checkout\u2026",proCheckoutUnavailable:"Secure checkout is temporarily unavailable. Please try again.",proTrust:"Cancel anytime \xB7 Secure checkout by Stripe \xB7 Instant access",proBenefit1Title:"Deep AI answers",proBenefit1Body:"unlock Beamo\u2019s most thorough AI t
4ier \u2014 free tops out at Medium \u2014 and it powers your search AI Overview by default, not just Chat.",proBenefit2Title:"Priority AI, never downgraded",proBenefit2Body:"your Deep model keeps running even after the daily free pool is spent \u2014 Pro always gets the good model.",proBenefit3Title:"Ask about any link",proBenefit3Body:"paste a URL and Beamo reads the page, then summarizes it or answers your questions about it.",proBenefit4Title:"Pick your AI model",proBenefit4Body:"power your Deep answers with GPT or Claude, your choice.",proBenefit5Title:"Zero ads, ever",proBenefit5Body:"the affiliate Shop module never appears for Pro members.",proBenefit6Title:"10\xD7 more memory",proBenefit6Body:"keep up to 500 saved searches and 100 recent \u2014 synced everywhere.",msgCouldNotUpdateName:"Could not update your name.",msgVerificationSent:"Verification email sent.",msgCouldNotSendEmail:"Could not send email.",msgCouldNotExport:"Could not export your data.",msgChatHistoryDeleted:"Chat history deleted.",msgCouldNotDeleteChat:"Could not delete chat history.",msgCouldNotDeleteData:"Could not delete your data. Try again.",msgDownloadBlocked:"Your browser blocked the download. Try again.",passkeysRefresh:"Refresh passkeys",passkeysAdd:"Add passkey",passkeysCancelRequest:"Cancel passkey request",passkeysOpenInBrowser:"Open account security in browser",passkeyNameLabel:"Passkey name",mfaMethodLabel:"Verification method",mfaVerifyContinue:"Verify and continue",mfaFreshChallenge:"Start a fresh challenge",mfaSignOut:"Sign out",totpTitle:"Authenticator app (two-factor authentication)",totpEmpty:"No authenticator apps are set up.",totpActive:"Active",totpSetupIncomplete:"Setup incomplete",totpRemove:"Remove",totpCancelSetup:"Cancel setup",totpAdd:"Add an authenticator app",totpShowCode:"Show setup code",tabGeneral:"General",generalHeading:"Preferences",accountTabSignedOutBody:"Sign in to manage your profile, security, billing, and synced data. Your preferences on the General tab work without an account.",accountsUnavailableTitle:"Accounts aren't available",accountsUnavailableBody:"Optional Beamo accounts aren't enabled on this deployment yet. Your preferences on the General tab still work.",tabProfile:"Profile",tabSecurity:"Security",tabBilling:"Billing",tabData:"Data & privacy",billingProPlan:"You\u2019re on Beamo Search Pro.",billingFreePlan:"You\u2019re on the free plan.",billingUnavailableHint:"Beamo Search Pro upgrades aren\u2019t available on this deployment yet. Core search and AI answers are free.",profileHeading:"Profile",profileDisplayNameLabel:"Display name",profileDisplayNameHint:"The name shown across Beamo Search.",profileSaveName:"Save",profileEmailLabel:"Email address",profileSignInMethodsLabel:"Sign-in methods",profileMemberSince:"Member since",profileEmailUnverified:"Your email isn't verified yet.",profileSaved:"Profile updated.",signInToManage:"Sign in to manage your account",signInToManageBody:"Create a free Beamo account or sign in to access your profile, security, billing, and synced data.",dataHeading:"Your data",dataSyncedSummary:"These are synced to your account on this device.",dataSavedSearches:"Saved searches",dataRecentSearches:"Recent searches",dataChatMessages:"Chat messages",dataExport:"Export my data (JSON)",dataDeleteChat:"Delete chat history",dataEraseHeading:"Erase your data",dataEraseBody:"Permanently delete the searches, history, and chat Beamo has stored for you. Your account and sign-in stay \u2014 only your data is removed. This cannot be undone.",dataDeleteAll:"Delete all my data",dataDeleteAllConfirm:"Delete all of your saved searches, recent history, and chat from Beamo? Your account stays active. This cannot be undone.",dataDeleteAllDone:"All your data was deleted. Your account is still active.",dataDangerHeading:"Danger zone",dataDeleteAccount:"Delete account",dataDeleteAccountBody:"Permanently delete your Beamo account and all synced data. This cannot be undone.",dataDeleteAccountConfirm:"Delete your account and all synced data? This cannot be undone.",signIn:"Sign in",signOut:"Sign out",noSavedSearches:'No s
4aved searches yet. Use "Save" next to the search box on the results page.',removeSavedSearch:"Remove",buttonSignInAria:"Sign in or create an account",popoverAria:"Your Beamo account",syncErrorRetry:"Could not sync your account. Refresh the page, then try again.",createAccountError:"Could not create account.",confirmEmailFirst:"Check your inbox to confirm your email, then sign in.",deleteAccountError:"Could not delete your account.",verifyLinkExpired:"This verification link is invalid or has expired."},sitePrefs:{settingsTitle:"Site preferences",menuLabel:"Site options for {domain}",pin:"Pin to top",unpin:"Unpin from top",boost:"Boost this site",unboost:"Remove boost",block:"Block {domain}",unblock:"Unblock {domain}",signedOutPrompt:"Sign in to pin, boost, or block sites in your results \u2014 free with a Beamo account.",signInCta:"Sign in",badgePinned:"Pinned",badgeBoosted:"Boosted",badgeBlocked:"Blocked",hiddenOne:"1 result hidden by your site preferences",hiddenMany:"{count} results hidden by your site preferences",showHidden:"Show",hideHidden:"Hide",settingsHint:"Pin favorite sites to the top of your results, boost sites you trust, or block sites you never want to see. Preferences sync with your account.",settingsEmpty:"No site preferences yet. Add one above, or use the \u22EE control on any search result.",settingsSignedOut:"Sign in to your Beamo account (free) to pin, boost, or block sites in your search results.",settingsUnavailable:"Site preferences are unavailable on this server.",addPlaceholder:"example.com",addLabel:"Add a site",addActionLabel:"Preference for the new site",addButton:"Add",actionPin:"Pin to top",actionBoost:"Boost",actionBlock:"Block",rowActionLabel:"Preference for {domain}",removeButton:"Remove",removeLabel:"Remove preference for {domain}"},stocksPack:{title:"Stocks",marketOpen:"Market open",marketClosed:"Market closed",atClose:"At close",regularClose:"Last regular close",preMarket:"Pre-market",afterHours:"After hours",today:"today",open:"Open",high:"High",low:"Low",dayRange:"Day range",marketCap:"Mkt cap",peRatio:"P/E ratio",forwardPeRatio:"Forward P/E",epsTtm:"EPS (TTM)",epsForward:"Forward EPS",beta:"Beta",divYield:"Div yield",week52High:"52-wk high",week52Low:"52-wk low",week52Range:"52-wk range",volume:"Volume",averageVolume:"Avg volume",averageVolume10Day:"10-day avg vol",fiftyDayAverage:"50-day avg",twoHundredDayAverage:"200-day avg",sharesOutstanding:"Shares out",shortPercentOfFloat:"Short % float",shortRatio:"Days to cover",marketCapRank:"Cap rank",circulatingSupply:"Circ. supply",allTimeHigh:"All-time high",prevClose:"Prev close",compare:"Compare",attribution:"Data via Yahoo Finance \xB7 may be delayed",updatedAt:"Updated {time}",earnings:"Earnings",quarterlyFinancials:"Quarterly financials",news:"News",analysts:"Analysts",consensusStrongBuy:"Strong Buy",consensusBuy:"Buy",consensusHold:"Hold",consensusSell:"Sell",consensusStrongSell:"Strong Sell",analystCount:"{count} analysts",avgPriceTarget:"Avg target {target}",medianPriceTarget:"Median target {target}",priceTargetRange:"Target range {range}",priceTargetUpdated:"Target updated {date}",nextDividend:"Next dividend",latestDividend:"Latest dividend",dividendAmount:"Amount {amount}",exDividendDate:"Ex-date {date}",paymentDate:"Payment {date}",recordDate:"Record date {date}",declarationDate:"Declared {date}",epsBeat:"EPS beat",epsMiss:"EPS miss",epsActual:"EPS {actual}",epsActualVsEstimate:"EPS {actual} vs est. {estimate}",nextEarnings:"Next earnings \xB7 {date}",revenue:"Revenue",netIncome:"Net income",yoyChange:"{percent} YoY",options:"Options",maxPain:"Max pain",iv30:"IV (30d)",avgImpliedVolatility:"Avg IV",putCallOpenInterestRatio:"Put/call OI",putCallVolumeRatio:"Put/call vol",atmGreeks:"At-the-money Greeks",greekDelta:"\u0394",greekGamma:"\u0393",greekTheta:"\u0398",greekVega:"V",optionsVolumeLine:"Calls {calls} \xB7 Puts {puts}",activeOptions:"Active volume",optionCall:"Call",optionPut:"Put",optionContractSummary:"{side} {strike} \xB7 Vol {volume} \xB7 OI {openInterest}",optionActivityRatio:"{ratio}x OI",optionsAttribution:"Cboe delayed option quotes"}};var yn=["en","de","es","fr","pt","zh","hi","ja","bn","ru"],Ne="en",ao="beamo:ui-locale-changed",xt={en:Di}
4,so=new Map,$i={en:"settings.uiLangEn",de:"settings.uiLangDe",es:"settings.uiLangEs",fr:"settings.uiLangFr",pt:"settings.uiLangPt",zh:"settings.uiLangZh",hi:"settings.uiLangHi",ja:"settings.uiLangJa",bn:"settings.uiLangBn",ru:"settings.uiLangRu"},$m=[{locale:"de",prefixes:["de"]},{locale:"en",prefixes:["en"]},{locale:"es",prefixes:["es"]},{locale:"fr",prefixes:["fr"]},{locale:"pt",prefixes:["pt"]},{locale:"zh",prefixes:["zh"]},{locale:"hi",prefixes:["hi"]},{locale:"ja",prefixes:["ja"]},{locale:"bn",prefixes:["bn"]},{locale:"ru",prefixes:["ru"]}];function We(e){let t=String(e??"").trim().toLowerCase().replace(/_/g,"-");if(!t)return Ne;for(let{locale:n,prefixes:r}of $m)if(r.some(s=>t===s||t.startsWith("".concat(s,"-"))))return n;return Ne}function Fm(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qm(e,t){let n=We(e);return Fm(t)?(xt[n]=t,t):xt[Ne]}function Um(e,t){let n=We(t),r="locales/".concat(encodeURIComponent(n),".json"),s=String(e.location?.protocol||"").toLowerCase();if(s==="http:"||s==="https:")return"/".concat(r);try{return new URL("./".concat(r),e.location?.href||"./").toString()}catch{return"./".concat(r)}}async function jm(e,t=globalThis){let n=We(e);if(xt[n])return xt[n];if(n===Ne||typeof t.fetch!="function")return xt[Ne];let r=so.get(n);if(r)return r;let s=(async()=>{try{let o=await t.fetch(Um(t,n),{credentials:"same-origin"});if(!o.ok)throw new Error("Locale catalog request failed: ".concat(o.status));return qm(n,await o.json())}catch{return xt[Ne]}finally{so.delete(n)}})();return so.set(n,s),s}function qr(e){return e?.storageKeys?.uiLocale||"beamo-ui-locale"}function zm(e,t){let n=qr(t);return Je(e,n,"")||te(e,n,"")}function Jn(e=globalThis,t={}){if(typeof URLSearchParams<"u"){let r=String(e.location?.search||"").trim();if(r){let s=Sr(Ta(r),"hl");if(s)return We(s)}}let n=zm(e,t);return We(n||e.navigator?.language)}function gn(e,t,n){let r=We(n),s=qr(t);Qe(e,s,r),ie(e,s,r)}function Wm(e=globalThis){typeof e.dispatchEvent=="function"&&e.dispatchEvent(new CustomEvent(ao))}function Hi(e,t){let n=String(t??"").split("."),r=e;for(let s of n){if(!r||typeof r!="object"||!(s in r))return null;r=r[s]}return typeof r=="string"?r:null}function Gm(e,t={}){return String(e).replace(/\{(\w+)\}/g,(n,r)=>{let s=t[r];return s==null?"":String(s)})}function Xn(e,t={},n=Ne){let r=We(n),s=Hi(xt[r],e)??Hi(xt[Ne],e)??String(e);return Gm(s,t)}function Km(e,t=globalThis,n={}){let r=Jn(t,n);r!==Ne&&e.set("hl",r)}function Fi(e,t="Request failed.",n=Ne){let r=String(e?.code||"").trim();if(r){let s=Vm[r]||"",o=s?Xn("errors.".concat(s),{},n):"";if(s&&o!=="errors.".concat(s))return o}return String(e?.message||t).trim()||Xn("errors.requestFailed",{},n)}var Vm={rate_limited:"rateLimited",upstream_quota_exhausted:"upstreamQuota",upstream_circuit_open:"circuitOpen",origin_forbidden:"originForbidden",invalid_request:"invalidRequest"},Ym={rate_limited:"rateLimited",upstream_quota_exhausted:"dailyLimit",upstream_circuit_open:"busy"};function Xm(e,t="Request failed.",n=Ne){let r=String(e?.code||"").trim();if(r){let s=Ym[r]||"",o=s?Xn("aiErrors.".concat(s),{},n):"";if(s&&o!=="aiErrors.".concat(s))return o}return Fi(e,t,n)}function oo(e,t,n=Ne){if(!e)return;e.querySelectorAll("[data-beamo-i18n]").forEach(s=>{let o=s.getAttribute("data-beamo-i18n");if(!o)return;let a=t(o);a&&(s.textContent=a)}),e.querySelectorAll("[data-beamo-i18n-placeholder]").forEach(s=>{let o=s.getAttribute("data-beamo-i18n-placeholder");o&&s.setAttribute("placeholder",t(o))}),e.querySelectorAll("[data-beamo-i18n-aria]").forEach(s=>{let o=s.getAttribute("data-beamo-i18n-aria");o&&s.setAttribute("aria-label",t(o))}),e.querySelectorAll("[data-beamo-i18n-title]").forEach(s=>{let o=s.getAttribute("data-beamo-i18n-title");o&&s.setAttribute("title",t(o))});let r=e.documentElement;r&&r.setAttribute("lang",We(n))}function qi(e,t=globalThis,n={}){let r=Jn(t,n);(t.sessionStorage||t.localStorage)&&gn(t,n,r);function s(a=r,i=!1){let c=We(a);return jm(c,t).then(()=>(c!==r||(oo(t.document,o.t,r),i&&Wm(t)),r))}let o={get locale(){return r},supportedLocales:yn,ready:Promise.resolve(Ne),loadLocale(a=r){return s(a,!1)},t(a,i={}){return Xn(a,i,r)},setLocale(a){let i=We(a);return i===r||(r=i,gn(t,n,r),s(r,!0)),r},applyChrome(){oo(t.document,o.t,r)},appendUiLocaleToParams(a){Km(a,t,n)},localizeApiError(a,i){return Fi(a,i,r)},localizeAiApiError(a,i){return Xm(a,i,r)}};return o.ready=s(r,r!==Ne),e.i18n=o,t.document&&oo(t.document,o.t,r),o}function we(e=globalThis){let t=e?.Beamo?.i18n?.t;return typeof t=="function"?t:(n,r)=>Xn(n,r,Ne)}var bn="beamo-theme",Qn=["light","dark","system"];
4function Jm(e,t=globalThis){if(e.__themeAttached)return e.theme;let n=document.documentElement,r="system",s=null;function o(){return t.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function a(f){return Qn.includes(f)?f:"system"}function i(){try{let f=t.localStorage?.getItem(bn);return a(f)}catch{return"system"}}function c(f){return f==="dark"||f==="light"?f:o()}function l(f){let g=document.querySelector('meta[name="theme-color"]:not([media])')||document.getElementById("beamo-theme-color");g&&g.setAttribute("content",f==="dark"?"#0b1220":"#fafafa")}function m(f,g){document.querySelectorAll("[data-beamo-theme-toggle]").forEach(C=>{let T=f==="dark";C.setAttribute("aria-pressed",T?"true":"false");let x=T?"light":"dark",N=g==="system";C.setAttribute("aria-label",N?"Switch to ".concat(x," theme (currently following system)"):"Switch to ".concat(x," theme")),C.setAttribute("title",T?"Light mode":"Dark mode")})}function u(f){document.querySelectorAll("[data-beamo-logo]").forEach(g=>{let C=g.dataset.logoLight,T=g.dataset.logoDark;!C||!T||(g.src=f==="dark"?T:C)})}function d(){document.querySelectorAll("[data-beamo-theme-pref]").forEach(f=>{let C=f.getAttribute("data-beamo-theme-pref")===r;f.setAttribute("aria-checked",C?"true":"false"),f.classList.toggle("is-active",C)})}function h(f,{persist:g=!1}={}){r=a(f);let C=c(r);if(n.setAttribute("data-theme",C),n.setAttribute("data-theme-preference",r),n.style.colorScheme=C,l(C),g)try{t.localStorage?.setItem(bn,r)}catch{}m(C,r),u(C),d()}function p(){return r}function b(){return n.getAttribute("data-theme")==="dark"?"dark":"light"}function v(f){h(f,{persist:!0}),t.Beamo?.accounts?.schedulePushWithChat?.()}function E(){v(b()==="dark"?"light":"dark")}function A(){document.querySelectorAll("[data-beamo-theme-toggle]").forEach(f=>{f.dataset.beamoThemeBound!=="true"&&(f.dataset.beamoThemeBound="true",f.addEventListener("click",()=>{E()}))})}function S(){document.querySelectorAll("[data-beamo-theme-pref]").forEach(f=>{f.dataset.beamoThemePrefBound!=="true"&&(f.dataset.beamoThemePrefBound="true",f.addEventListener("click",g=>{g?.stopPropagation?.();let C=f.getAttribute("data-beamo-theme-pref");C&&v(C)}))}),d()}function _(){s=t.matchMedia("(prefers-color-scheme: dark)"),s.addEventListener("change",()=>{r==="system"&&h("system",{persist:!1})})}function w(){A(),S(),m(b(),r),l(b())}return h(i(),{persist:!1}),_(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",w):w(),e.__themeAttached=!0,e.theme={getTheme:b,getPreference:p,setPreference:v,setTheme:v,toggleTheme:E},e.theme}if(typeof document<"u"){let e=globalThis.Beamo||(globalThis.Beamo={});Jm(e,globalThis)}var Qm=new Set(["true","false","null","undefined","nil","None","True","False","NaN","Infinity","NULL","TRUE","FALSE"]),Wi=["abstract","as","async","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","final","finally","for","from","function","get","goto","if","implements","import","in","instanceof","interface","let","namespace","new","of","override","package","private","protected","public","readonly","return","set","static","super","switch","this","throw","try","type","typeof","var","void","while","with","yield"],io=["and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","match","case"],Ur=["if","then","else","elif","fi","for","in","do","done","while","until","case","esac","function","return","echo","export","local","read","set","unset","source","sudo","cd","exit","select","time","trap"],Zm=["select","from","where","insert","into","values","update","set","delete","create","table","alter","drop","join","inner","left","right","outer","full","on","group","by","order","having","limit","offset","as","and","or","not","in","is","between","like","distinct","union","all","index","primary","key","foreign","references","default","cascade","with","case","when","then","else","end","count","sum","avg","min","max","asc","desc","into"],Ui=["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],ji=["as","async","await","break","const","continue","crate","dyn","else","enum","extern","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","static","struct","super","trait","type","unsafe","use","where","while"],zi=["begin","break","case","class","def","do","else","elsif","end","ensure","for","if","in","module","next","nil","redo","rescue","retry","return","self","super","then","unless","until","when","while","yield","require","attr_accessor","puts"],eh=["abstract","and","array","as","break","case","catch","class","const","continue","default","do","echo","else","elseif","extends","final","finally","for","foreach","function","global","if","implements","include","instanceof","interface","namespace","new","or","print","private","protected","public","require","return","static","switch","throw","trait","try","use","var","while"];function Ae(e=[]){return{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"',"'","`"],keywords:new Set([...Wi,...e])}}var th={lineComment:["//","#"],blockComment:[["/*","*/"]],strings:['"',"'","`"],keywords:new Set([...Wi,...io])}
4,nh={js:Ae(),javascript:Ae(),jsx:Ae(),mjs:Ae(),ts:Ae(["declare","keyof","infer","asserts","satisfies"]),typescript:Ae(["declare","keyof","infer","asserts","satisfies"]),tsx:Ae(["declare","keyof","infer"]),java:Ae(["boolean","byte","char","double","float","int","long","short","synchronized","throws","transient","volatile","native","strictfp"]),c:Ae(["int","char","float","double","long","short","unsigned","signed","struct","union","sizeof","typedef"]),cpp:Ae(["int","char","float","double","long","short","unsigned","struct","union","sizeof","typedef","template","using","nullptr","constexpr","virtual"]),"c++":Ae(["int","char","float","double","template","using","nullptr","constexpr","virtual"]),csharp:Ae(["string","bool","int","using","using","foreach","override","sealed","struct","var","when"]),"c#":Ae(["string","bool","int","using","foreach","override","struct","var"]),cs:Ae(["string","bool","int","using","foreach","override","struct","var"]),swift:Ae(["func","guard","struct","protocol","extension","var","let","enum","init","self","nil"]),kotlin:Ae(["fun","val","var","when","object","companion","data","sealed","override","suspend"]),scala:Ae(["def","val","var","object","trait","match","case","sealed","implicit"]),go:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"',"`","'"],keywords:new Set(Ui)},golang:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"',"`","'"],keywords:new Set(Ui)},rust:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"'],keywords:new Set(ji)},rs:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"'],keywords:new Set(ji)},python:{lineComment:["#"],blockComment:[],strings:['"',"'"],tripleStrings:!0,keywords:new Set(io)},py:{lineComment:["#"],blockComment:[],strings:['"',"'"],tripleStrings:!0,keywords:new Set(io)},ruby:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(zi)},rb:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(zi)},php:{lineComment:["//","#"],blockComment:[["/*","*/"]],strings:['"',"'"],keywords:new Set(eh)},bash:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(Ur)},sh:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(Ur)},shell:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(Ur)},zsh:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set(Ur)},sql:{lineComment:["--"],blockComment:[["/*","*/"]],strings:["'",'"'],keywords:new Set(Zm),caseInsensitive:!0},json:{lineComment:[],blockComment:[],strings:['"'],keywords:new Set},jsonc:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"'],keywords:new Set},yaml:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set},yml:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set},toml:{lineComment:["#"],blockComment:[],strings:['"',"'"],keywords:new Set},ini:{lineComment:[";","#"],blockComment:[],strings:['"',"'"],keywords:new Set},css:{lineComment:[],blockComment:[["/*","*/"]],strings:['"',"'"],keywords:new Set},scss:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"',"'"],keywords:new Set(["@mixin","@include","@if","@else","@for","@each","@function"])},less:{lineComment:["//"],blockComment:[["/*","*/"]],strings:['"',"'"],keywords:new Set},html:{lineComment:[],blockComment:[["<!--","-->"]],strings:['"',"'"],keywords:new Set,markup:!0},xml:{lineComment:[],blockComment:[["<!--","-->"]],strings:['"',"'"],keywords:new Set,markup:!0},svg:{lineComment:[],blockComment:[["<!--","-->"]],strings:['"',"'"],keywords:new Set,markup:!0}};function co(e){return String(e||"").trim().toLowerCase().replace(/^language-/,"")}function rh(e){return nh[co(e)]||th}function sh(e){return/[A-Za-z_$@]/.test(e)}function oh(e){return/[A-Za-z0-9_$-]/.test(e)}function ah(e,t){let n=[],r=e.length,s=0,o=0,a=i=>{i>o&&n.push({type:"plain",value:e.slice(o,i)})};for(;s<r;){let i=!1;for(let[l,m]of t.blockComment)if(e.startsWith(l,s)){a(s);let u=e.indexOf(m,s+l.length);u=u===-1?r:u+m.length,n.push({type:"comment",value:e.slice(s,u)}),s=u,o=s,i=!0;break}if(i)continue;for(let l of t.lineComment)if(e.startsWith(l,s)){a(s);let m=e.indexOf("\n",s);m=m===-1?r:m,n.push({type:"comment",value:e.slice(s,m)}),s=m,o=s,i=!0;break}if(i)continue;let c=e[s];if(t.tripleStrings&&(e.startsWith('"""',s)||e.startsWith("'''",s))){a(s);let l=e.slice(s,s+3),m=e.indexOf(l,s+3);m=m===-1?r:m+3,n.push({type:"string",value:e.slice(s,m)}),s=m,o=s;continue}if(t.strings.includes(c)){a(s);let l=s+1;for(;l<r&&e[l]!==c&&e[l]!=="\n";)l+=e[l]==="\\"?2:1;l=e[l]===c?l+1:l,n.push({type:"string",value:e.slice(s,l)}),s=l,o=s;continue}if(t.markup&&c==="<"&&/[A-Za-z/!?]/.test(e[s+1]||"")){let l=/^<\/?[A-Za-z][\w:-]*/.exec(e.slice(s));if(l){a(s),n.push({type:"tag",value:l[0]}),s+=l[0].length,o=s;continue}}if(/[0-9]/.test(c)||c==="."&&/[0-9]/.test(e[s+1]||"")){let l=/^(?:0x[0-9a-fA-F]+|0b[01]+|\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(e.slice(s));if(l){a(s),n.push({type:"number",value:l[0]}),s+=l[0].length,o=s;continue}}if(sh(c)){let l=s+1;for(;l<r&&oh(e[l]);)l+=1;let m=e.slice(s,l);if(t.caseInsensitive?t.keywords.has(m.toLowerCase()):t.keywords.has(m))a(s),n.push({type:"keyword",value:m}),o=l;else if(Qm.has(m))a(s),n.push({type:"literal",value:m}),o=l;else{let d=l;for(;d<r&&(e[d]===" "||e[d]===" ");)d+=1;e[d]==="("&&!t.markup&&(a(s),n.push({type:"function",value:m}),o=l)}s=l;continue}s+=1}return a(r),n}function Gi(e,t,n){let r=e.createDocumentFragment(),s=rh(n),o;try{o=ah(t,s)}catch{return r.appendChild(e.createTextNode(t)),r}for(let a of o){if(a.type==="plain"){r.appendChild(e.createTextNode(a.value));continue}let i=e.createElement("span");i.className="tok-".concat(a.type),i.textContent=a.value,r.appendChild(i)}return r}function Ki(e,t=globalThis){function r(f){let g=e.url||{};
4return typeof g.safeHttpUrl=="function"?g.safeHttpUrl(f):""}let s=/^\s*[-*+â¢Â·â£âªâ¦]\s+/,o=/^\s*\d+[.)]\s+/,a=/^\s*(#{1,6})\s+/,i=/^\s*>\s?/,c=/<br\s*\/?>/i;function l(f){return s.test(f)}function m(f){return o.test(f)}function u(f,g){let C=/(\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|\[[^\]]+\]\((?:[^()]|\([^()]*\))*\)|<br\s*\/?>|https?:\/\/\S+)/gi,T=0,x=C.exec(g);for(;x;){x.index>T&&f.appendChild(document.createTextNode(g.slice(T,x.index)));let N=x[0];if(N.startsWith("**")){let B=document.createElement("strong");B.textContent=N.slice(2,-2),f.appendChild(B)}else if(N.startsWith("*")){let B=document.createElement("em");B.textContent=N.slice(1,-1),f.appendChild(B)}else if(N.startsWith("`")){let B=document.createElement("code");B.textContent=N.slice(1,-1),f.appendChild(B)}else if(N[0]==="<")f.appendChild(document.createElement("br"));else if(N.startsWith("[")){let B=/^\[([^\]]+)\]\(((?:[^()]|\([^()]*\))*)\)$/.exec(N);if(B){let I=r(B[2]);if(I){let y=document.createElement("a");y.setAttribute("href",I),y.setAttribute("rel","noopener noreferrer"),y.setAttribute("target","_blank"),y.textContent=B[1],f.appendChild(y)}else f.appendChild(document.createTextNode(B[1]))}}else if(N.startsWith("https://")||N.startsWith("http://")){let B=N.replace(/[.,;:!?)]+$/,""),I=r(B);if(I){let y=document.createElement("a");y.setAttribute("href",I),y.setAttribute("rel","noopener noreferrer"),y.setAttribute("target","_blank"),y.textContent=B,f.appendChild(y),B.length<N.length&&f.appendChild(document.createTextNode(N.slice(B.length)))}else f.appendChild(document.createTextNode(N))}T=C.lastIndex,x=C.exec(g)}T<g.length&&f.appendChild(document.createTextNode(g.slice(T)))}function d(f,g){let C=String(g).split(c).map(x=>x.trim()).filter(Boolean);if(C.length===0){u(f,g.trim());return}let T=C.filter(l).length;if(C.length>1&&T>=Math.ceil(C.length/2)){let x=document.createElement("ul");C.forEach(N=>{let B=document.createElement("li");u(B,N.replace(s,"")),x.appendChild(B)}),f.appendChild(x);return}C.forEach((x,N)=>{N>0&&f.appendChild(document.createElement("br")),u(f,x)})}function h(f){let g=f.trim();return g.startsWith("|")&&(g=g.slice(1)),g.endsWith("|")&&(g=g.slice(0,-1)),g.split("|").map(C=>C.trim())}function p(f){return/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)+\|?\s*$/.test(f)}function b(f,g,C){let T=document.createElement("div");T.className="md-table-wrap";let x=document.createElement("table"),N=document.createElement("thead"),B=document.createElement("tr");h(g).forEach(y=>{let k=document.createElement("th");d(k,y),B.appendChild(k)}),N.appendChild(B),x.appendChild(N);let I=document.createElement("tbody");C.forEach(y=>{if(!y.trim())return;let k=document.createElement("tr");h(y).forEach(P=>{let R=document.createElement("td");d(R,P),k.appendChild(R)}),I.appendChild(k)}),x.appendChild(I),T.appendChild(x),f.appendChild(T)}function v(f,g,C){let T=0;for(;T<g.length;){let x=g[T];if(!x.trim()){T+=1;continue}let N=a.exec(x);if(N){C.orderedNext=null;let y=Math.min(6,Math.max(1,N[1].length)),k=document.createElement("h".concat(y));u(k,x.replace(a,"").replace(/\s+#+\s*$/,"")),f.appendChild(k),T+=1;continue}if(l(x)){let y=document.createElement("ul");for(;T<g.length&&l(g[T]);){let k=document.createElement("li");u(k,g[T].replace(s,"")),y.appendChild(k),T+=1}f.appendChild(y);continue}if(m(x)){let y=document.createElement("ol"),k=/^\s*(\d+)[.)]\s+/.exec(x),P=k?parseInt(k[1],10):1,R=C.orderedNext!=null?C.orderedNext:Number.isFinite(P)&&P>0?P:1;R!==1&&y.setAttribute("start",String(R));let D=0;for(;T<g.length&&m(g[T]);){let L=document.createElement("li");u(L,g[T].replace(o,"")),y.appendChild(L),T+=1,D+=1}f.appendChild(y),C.orderedNext=R+D;continue}if(i.test(x)){C.orderedNext=null;let y=document.createElement("blockquote"),k=[];for(;T<g.length&&i.test(g[T]);)k.push(g[T].replace(i,"")),T+=1;u(y,k.join(" ")),f.appendChild(y);continue}C.orderedNext=null;let B=[];for(;T<g.length&&g[T].trim()&&!a.test(g[T])&&!l(g[T])&&!m(g[T])&&!i.test(g[T]);)B.push(g[T]),T+=1;let I=document.createElement("p");u(I,B.join(" ")),f.appendChild(I)}}function E(f,g,C){let T=document.createElement("div");T.className="beamo-code";let x=co(C);x&&T.setAttribute("data-lang",x);let N=document.createElement("div");N.className="beamo-code__head";let B=document.createElement("span");B.className="beamo-code__lang",B.textContent=x||"code",N.appendChild(B);let I=document.createElement("button");
4I.type="button",I.className="beamo-code__copy",I.setAttribute("data-beamo-copy","1"),I.setAttribute("aria-label","Copy code");let y=document.createElement("span");y.className="beamo-code__copy-label",y.textContent="Copy",I.appendChild(y),N.appendChild(I),T.appendChild(N);let k=document.createElement("pre");k.className="beamo-code__pre";let P=document.createElement("code");P.className=x?"beamo-code__code language-".concat(x):"beamo-code__code",P.appendChild(Gi(document,g,x)),k.appendChild(P),T.appendChild(k),f.appendChild(T)}function A(f,g,C){let T=g.trim();if(!T)return;let x=T.split("\n"),N=x.findIndex((B,I)=>I>0&&p(B)&&x[I-1].includes("|"));if(N>0){let B=N-1;B>0&&v(f,x.slice(0,B),C);let I=N+1;for(;I<x.length&&x[I].includes("|");)I+=1;C.orderedNext=null,b(f,x[B],x.slice(N+1,I)),I<x.length&&v(f,x.slice(I),C);return}v(f,x,C)}let S=/^(\s*)(```+|~~~+)[ \t]*([\w+#.-]*)[ \t]*$/;function _(f){let g=document.createDocumentFragment(),C=String(f??"").slice(0,5e4).replace(/\r\n/g,"\n");if(!C.trim())return g;let T={orderedNext:null},x=C.split("\n"),N=[],B=()=>{if(N.length===0)return;let y=N.join("\n");N=[],y.trim()&&y.split(/\n{2,}/).forEach(k=>A(g,k,T))},I=0;for(;I<x.length;){let y=S.exec(x[I]);if(y){B(),T.orderedNext=null;let k=y[2][0],P=y[3]||"",R=[];I+=1;let D=new RegExp("^\\s*".concat(k==="`"?"```+":"~~~+","\\s*$"));for(;I<x.length&&!D.test(x[I]);)R.push(x[I]),I+=1;I<x.length&&(I+=1),E(g,R.join("\n"),P);continue}N.push(x[I]),I+=1}return B(),g}e.markdown={renderToFragment:_};let w=t.document;w&&!w.__beamoCodeCopyBound&&typeof w.addEventListener=="function"&&(w.__beamoCodeCopyBound=!0,w.addEventListener("click",f=>{let C=f.target?.closest?.("[data-beamo-copy]");if(!C)return;let x=C.closest(".beamo-code")?.querySelector(".beamo-code__code")?.textContent??"";if(!x)return;let N=C.querySelector(".beamo-code__copy-label")||C;pr(t,x).then(B=>{if(!B)return;let I=N.textContent;N.textContent="Copied",C.classList.add("is-copied"),t.setTimeout?.(()=>{N.textContent=I||"Copy",C.classList.remove("is-copied")},1600)})}))}function Vi(e,t=globalThis){let n="http://www.w3.org/2000/svg",r={search:'<circle cx="11" cy="11" r="7" fill="none" stroke="currentColor" stroke-width="2"/><path d="M20 20l-3.5-3.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',history:'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M12 8v4l2.5 2.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',arrow:'<path d="M5 12h12M13 7l5 5-5 5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',chat:'<path d="M7 8h10M7 12h6M6 4h12a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H9l-4 3V6a2 2 0 0 1 2-2z" fill="none" stroke="currentColor" stroke-width="2" stroke-linejoin="round"/>',image:'<rect x="4" y="5" width="16" height="14" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="9" cy="10" r="1.5" fill="currentColor"/><path d="M4 16l4.5-4.5 3 3L16 10l4 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',news:'<path d="M6 5h12v14H6z" fill="none" stroke="currentColor" stroke-width="2"/><path d="M9 9h6M9 13h6M9 17h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',video:'<rect x="4" y="6" width="16" height="12" rx="2" fill="none" stroke="currentColor" stroke-width="2"/><path d="M11 10l4 2.5L11 15z" fill="currentColor"/>',map:'<path d="M12 21s6-4.35 6-10a6 6 0 1 0-12 0c0 5.65 6 10 6 10z" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="11" r="2" fill="currentColor"/>',travel:'<path d="M3 12h18M14 6l7 6-7 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M3 6v12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',sparkles:'<path d="M12 3l1.2 4.2L17 8l-3.8 1.2L12 13l-1.2-3.8L7 8l3.8-.8zM5 16l.7 2.3L8 19l-2.3.7L5 22l-.7-2.3L2 19l2.3-.7zM18 14l.9 3.1L22 18l-3.1.9L18 22l-.9-3.1L14 18l3.1-.9z" fill="currentColor"/>',globe:'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><path d="M3 12h18M12 3a14 14 0 0 1 0 18M12 3a14 14 0 0 0 0 18" fill="none" stroke="currentColor" stroke-width="2"/>
4',external:'<path d="M14 5h5v5M10 14L19 5M15 19H6a2 2 0 0 1-2-2V8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',info:'<circle cx="12" cy="12" r="9" fill="none" stroke="currentColor" stroke-width="2"/><circle cx="12" cy="8" r="1.15" fill="currentColor"/><path d="M12 11.25v5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',minimize:'<path d="M5 12h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',expand:'<path d="M4 8V4h4M20 8V4h-4M4 16v4h4M20 16v4h-4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',plus:'<path d="M12 5v14M5 12h14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',close:'<path d="M6 6l12 12M18 6L6 18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>',chevronDown:'<path d="M6 9l6 6 6-6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',chevronLeft:'<path d="M15 6l-6 6 6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',chevronRight:'<path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',stop:'<rect x="5.5" y="5.5" width="13" height="13" rx="1.5" fill="currentColor"/>',copy:'<rect x="8" y="8" width="11" height="13" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/><rect x="5" y="5" width="11" height="13" rx="1.5" fill="none" stroke="currentColor" stroke-width="2"/>',refresh:'<path d="M20 7v5h-5M4 17v-5h5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M6 10a6 6 0 0 1 10-3l2 2M18 14a6 6 0 0 1-10 3l-2-2" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',thumbUp:'<path d="M9 19h6M8 11V7.5A2.5 2.5 0 0 1 10.5 5H11a2 2 0 0 1 2 2v2h3.2a2 2 0 0 1 1.94 2.52l-1.2 4.8A2 2 0 0 1 15.06 18H9" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',thumbDown:'<path d="M9 5h6M16 13v3.5A2.5 2.5 0 0 1 13.5 19H13a2 2 0 0 1-2-2v-2H7.8a2 2 0 0 1-1.94-2.52l1.2-4.8A2 2 0 0 1 8.94 6H15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',archive:'<rect x="4" y="4" width="16" height="5" rx="1" fill="none" stroke="currentColor" stroke-width="2"/><path d="M6 9v9a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V9M10 13h4" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>',trash:'<path d="M5 7h14M10 7V5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v2M8 7l.6 11.1a2 2 0 0 0 2 1.9h2.8a2 2 0 0 0 2-1.9L16 7M10 11v5M14 11v5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>'};function s(c,l="beamo-icon"){let m=document.createElementNS(n,"svg");m.setAttribute("viewBox","0 0 24 24"),m.setAttribute("class",l),m.setAttribute("aria-hidden","true");let u=r[c]||"";if(u&&typeof t.DOMParser=="function"){let h=new t.DOMParser().parseFromString('<svg xmlns="'.concat(n,'">').concat(u,"</svg>"),"image/svg+xml").documentElement;for(let p of Array.from(h.childNodes))m.appendChild(document.importNode(p,!0))}return m}function o(c,l){c.querySelectorAll("[".concat(l,"]")).forEach(m=>{let u=m.getAttribute(l);
4if(!u||m.querySelector("svg"))return;let d=s(u,m.getAttribute("data-beamo-icon-class")||"beamo-icon"),h=m.getAttribute("data-beamo-icon-size");if(h&&d.classList.add(h),l==="data-quick-icon"){m.insertBefore(d,m.firstChild);return}m.appendChild(d)})}function a(c=document){o(c,"data-beamo-icon"),o(c,"data-quick-icon")}function i(){if(!(typeof document>"u")){if(document.readyState==="loading"){document.addEventListener("DOMContentLoaded",()=>a());return}a()}}e.icons={create:s,mount:a,markup:(c,l="beamo-icon")=>{let m=r[c];return m?'<svg class="'.concat(l,'" viewBox="0 0 24 24" aria-hidden="true">').concat(m,"</svg>"):""}},e.createIcon=s,e.iconMarkup=e.icons.markup,i()}function Rt(e=globalThis){let t=e.crypto;return t&&typeof t.randomUUID=="function"?t.randomUUID().replace(/-/g,""):"turn".concat(Date.now().toString(36)).concat(Math.random().toString(36).slice(2,11))}var ih="beamo-chat-sync",Yi="beamoChatRevision";function wn(e){return String(e??"").trim().replace(/\s+/g," ").slice(0,256).toLowerCase()}function ch(e){return Array.isArray(e?.messages)?e.messages:[]}function lh(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=Number(t.revision);return Number.isFinite(n)&&n>=0&&Array.isArray(t.messages)&&Array.isArray(t.inflight)}function uh(e){for(let t of e)if(t&&t.role==="user")return String(t.content||"");return""}function dh(e,t){let n=wn(t);if(!e||n==="")return!0;if(e.staleForSearch===!0)return!1;let r=ch(e);if(r.length===0)return!0;let s=String(e.origin||""),o=wn(e.originTerm);if(o!=="")return o===n;if(s==="chat")return!1;let a=wn(uh(r));if(a!=="")return a===n;let i=wn(e.threadTitle);return i!==""&&i===n}function fh(e){return{...e,messages:[],inflight:[],messageCount:0,origin:"",originTerm:"",staleForSearch:!0}}function mh(e,t=globalThis,{getHistoryRenderOptions:n=null,getDefaultSearchTerm:r=null,onStateApplied:s=null}={}){let o=null,a=null,i=Number(Je(t,Yi,"0")||0)||0,c="",l=0,m=0,u=0,d=new Set,h=null,p=null,b=null,v=!1;function E(){return typeof t.BroadcastChannel=="function"}function A(L){let $={...L,revision:i,at:Date.now()};try{b?.postMessage($)}catch{}try{t.localStorage?.setItem("beamo-chat-event",JSON.stringify($)),t.localStorage?.removeItem("beamo-chat-event")}catch{}}function S(L,$,{actionLabel:G="",onAction:J=null}={}){if(!a)return;if(!L){a.hidden=!0,a.replaceChildren();return}a.hidden=!1,a.dataset.mode=L,Kn(a);let X=document.createElement("p");if(X.className="chat-sync-banner__text",X.textContent=$,a.appendChild(X),G&&typeof J=="function"){let W=document.createElement("button");W.type="button",W.className="chat-sync-banner__action",W.textContent=G,W.addEventListener("click",J),a.appendChild(W)}}function _(){let L=[...d].filter(J=>J&&J!==c);if(L.length>0){S("inflight",L.length===1?"Another tab is waiting for a reply. You can keep chatting here; history will stay in sync.":"".concat(L.length," replies are in progress in other tabs."));return}let $=Number(e.chatHistoryLimit)||0,G=Number(e.chatMessageCount)||0;if($>0&&G>=Math.max(1,$-2)){S("history","Older messages roll off after ".concat($," turns").concat(e.chatSignedIn?" on your account":" in this session",". Export the thread or clear chat to start fresh."),{actionLabel:"Dismiss",onAction:()=>S(null)});return}S(null)}function w(L={}){if(wn(L.searchTerm)!==""||typeof r!="function")return L;let $=r();return wn($)!==""?{...L,searchTerm:$}:L}async function f(L={}){let $=w(L),G=e.config?.endpoints?.chatSync;if(!G||typeof t.fetch!="function")return null;let J=String($.searchTerm??"").trim(),X=J?"".concat(G).concat(G.includes("?")?"&":"?","searchTerm=").concat(encodeURIComponent(J)):G;
4try{let W=await Ie(e),V=await e.fetchWithTimeout(X,{method:"GET",headers:W},e.config?.timeouts?.fetchDefaultMs||8e3);if(!V.ok)return null;let j=await V.json().catch(()=>null);return lh(j)?j:null}catch{return null}}function g(L){let $=Number(L);!Number.isFinite($)||$<0||(i=$,Qe(t,Yi,String($)))}function C(L,{forceRender:$=!1}={}){if(!L||typeof L!="object")return;let G=Number(L.revision),J=Array.isArray(L.messages)?L.messages:[],X=Array.isArray(L.inflight)?L.inflight:[],W=Number(L.historyLimit);if(Number.isFinite(W)&&W>0&&(e.chatHistoryLimit=W,e.chatMessageCount=Number(L.messageCount)||J.length,e.chatSignedIn=!!L.signedIn),d=new Set(X.map(ee=>ee&&typeof ee.turnId=="string"?ee.turnId:"").filter(Boolean)),i>0&&(!Number.isFinite(G)||G<i)){_();return}let V=Number.isFinite(G)&&G!==i;g(Number.isFinite(G)?G:i);let j=!!c||!!o?.querySelector('.ai-msg-text[aria-busy="true"]');if(o&&!j&&($||V)){let ee=typeof n=="function"?n():{};Zs(o,J,ee),S(null)}else V&&o&&S("updated","Conversation updated in another tab.",{actionLabel:"Refresh view",onAction:()=>{T({forceRender:!0}).catch(()=>{})}});_(),h=L;try{s?.(L)}catch{}}async function T(L={}){let $=w(L),G=l,J=++u,X=await f($);return l!==G?X:X&&!dh(X,$.searchTerm)?fh(X):(X&&J<m||(X&&(m=J),C(X,$)),X)}function x(){return h}function N(){p!==null&&t.clearTimeout(p),p=t.setTimeout(()=>{p=null,T().catch(()=>{})},120)}function B(L){let $=L?.data;!$||typeof $!="object"||($.type==="turn_started"||$.type==="turn_completed"||$.type==="conversation_cleared")&&N()}function I(L){L.key!=="beamo-chat-event"||!L.newValue||N()}function y(){T().catch(()=>{})}function k(){t.document.visibilityState==="visible"&&T().catch(()=>{})}function P({chatContainer:L,banner:$}){o=L,a=$,_()}function R({initialRefresh:L=!0}={}){v||(v=!0,E()&&(b=new t.BroadcastChannel(ih),b.addEventListener("message",B)),typeof t.addEventListener=="function"&&(t.addEventListener("storage",I),t.addEventListener("focus",y)),typeof t.document?.addEventListener=="function"&&t.document.addEventListener("visibilitychange",k),L&&typeof t.fetch=="function"&&T().catch(()=>{}))}function D(){v=!1,p!==null&&(t.clearTimeout(p),p=null),b?.removeEventListener?.("message",B),b?.close(),b=null,typeof t.removeEventListener=="function"&&(t.removeEventListener("storage",I),t.removeEventListener("focus",y)),typeof t.document?.removeEventListener=="function"&&t.document.removeEventListener("visibilitychange",k),S(null)}return{attachUI:P,start:R,dispose:D,createTurnId:()=>Rt(t),setActiveTurn(L){c=L||"",c&&(l+=1),_()},clearActiveTurn(){c="",_()},notifyTurnStarted(L,$){l+=1,A({type:"turn_started",turnId:L,userMessage:$}),N()},notifyTurnCompleted(L){A({type:"turn_completed",turnId:L}),c="",N(),e.accounts?.schedulePushWithChat?.()},notifyConversationCleared(){l+=1,A({type:"conversation_cleared"}),g(0),d=new Set,S(null),e.accounts?.schedulePushWithChat?.()},refreshFromServer:T,applyServerState:C,fetchState:f,getLastServerState:x}}function Xi(e,t=globalThis){let n=e.chat&&typeof e.chat=="object"?e.chat:{};function r(s={}){let o=mh(e,t,s),a=o.dispose;return o.dispose=()=>{a(),e.chatSync===o&&(e.chatSync=null)},e.chatSync=o,o}e.chat={...n,createSyncManager:r}}var Zn="fast",Pt="medium",ut="deep",hh="premium";var ph={[Zn]:0,[Pt]:1,[ut]:2};function dt(e){return ph[Ge(e)]??0}function Ge(e){let t=String(e??"").trim().toLowerCase();return t===ut||t===hh?ut:t===Pt?Pt:Zn}function jr(e){return Ge(e)}function Ji(e=globalThis.Beamo){let t=oe(e).storageKeys?.aiPreset;return typeof t=="string"&&t?t:"beamo-ai-preset"}function tt(e=globalThis,t=e?.Beamo){return Ge(te(e,Ji(t),Zn))}function er(e,t,n=e?.Beamo){return ie(e,Ji(n),Ge(t))}function lo(e){switch(Ge(e)){case ut:return"Deep answers";case Pt:return"Medium answers";default:return"Fast answers"}}var gh=1500,yh=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;function tr(e){return typeof e!="string"?"":e.replace(/\r\n?/g,"\n").replace(yh,"").replace(/\n{3,}/g,"\n\n").trim().slice(0,gh)}function Qi(e=globalThis.Beamo){let t=oe(e).storageKeys?.customInstructions;return typeof t=="string"&&t?t:"beamo-custom-instructions"}function It(e=globalThis,t=e?.Beamo){return tr(te(e,Qi(t),""))}function uo(e,t,n=e?.Beamo){let r=tr(t);return ie(e,Qi(n),r),r}function zr(e){return tr(e)}var ec="openai",Zi="anthropic";function tc(e){return String(e??"").trim().toLowerCase()===Zi?Zi:ec}
4function nc(e=globalThis.Beamo){let t=oe(e).storageKeys?.deepReasoningProvider;return typeof t=="string"&&t?t:"beamo-deep-reasoning-provider"}function Sn(e=globalThis,t=e?.Beamo){return tc(te(e,nc(t),ec))}function rc(e,t,n=e?.Beamo){return ie(e,nc(n),tc(t))}var qt=["overview","chat","periodicAsk","calcAssist","translate","languageTools","urlAsk"],nr="beamo:ai-features-change",bh="beamo:search-only-mode-change";function sc(e){let t=oe(e).storageKeys?.aiFeatures;return typeof t=="string"&&t?t:"beamo-ai-features"}function oc(){let e={};for(let t of qt)e[t]=!0;return e}function kn(e=globalThis,t=e?.Beamo){let n=te(e,sc(t),""),r={};if(n)try{let o=JSON.parse(n);o&&typeof o=="object"&&(r=o)}catch{}let s=oc();if(r.features&&typeof r.features=="object")for(let o of qt)r.features[o]===!1&&(s[o]=!1);return{enabled:r.enabled!==!1,features:s}}function wh(e,t,n=e?.Beamo){let r={enabled:t.enabled!==!1,features:{...oc(),...t.features}};ie(e,sc(n),JSON.stringify(r));try{n?.accounts?.schedulePushWithChat?.()}catch{}for(let s of[nr,bh])try{e.dispatchEvent?.(new CustomEvent(s,{detail:{enabled:r.enabled,features:r.features}}))}catch{}}function fo(e,t=globalThis,n=t?.Beamo){let r=kn(t,n);return r.enabled&&r.features[e]!==!1}function ac(e,t,n,r=e?.Beamo){let s=kn(e,r);s.features[t]=!!n,wh(e,s,r)}var Sh="beamo:ai-unavailable";function rr(e,t={}){try{e.dispatchEvent?.(new CustomEvent(Sh,{detail:t}))}catch{}}function ic(e,t,n,r,s=e.ownerDocument){let o=[];(function c(l){let m=Array.from(l.childNodes||[]);for(let u of m)u.nodeType===3?(u.textContent||"").length>0&&o.push(u):u.nodeType===1&&c(u)})(e);let a=[];for(let c of o){let l=(c.textContent||"").split(/(\s+)/),m=s.createDocumentFragment();for(let u of l){if(!u)continue;if(/^\s+$/.test(u)){m.appendChild(s.createTextNode(u));continue}let d=s.createElement("span");d.className=r,d.textContent=u,a.push(d),m.appendChild(d)}c.parentNode?.replaceChild(m,c)}a.forEach((c,l)=>{l<t?c.classList.add("is-shown"):c.style.animationDelay="".concat(Math.round((l-t)*n),"ms")});let i=Math.max(0,a.length-t);return{total:a.length,revealMs:i*n}}function cc(e=globalThis){try{let t=typeof e.Intl?.DateTimeFormat=="function"?e.Intl:globalThis.Intl,n=t?.DateTimeFormat?.(),r=String(n?.resolvedOptions?.().timeZone||"").trim();return!r||r.length>80||!/^[A-Za-z][A-Za-z0-9_+\-/.]{0,79}$/.test(r)?"":(t.DateTimeFormat("en-US",{timeZone:r}).format(new Date),r)}catch{return""}}function Ch(e,t,n){return t?.code&&e?.i18n?.localizeAiApiError?e.i18n.localizeAiApiError({code:t.code,message:t.content||t.warning||n,retryAfterSeconds:t.retryAfterSeconds||0},n):t?.content||t?.warning||n}function lc(e,t=globalThis){function n(s={}){let o=null,a=null,i="",c=null,l=!1,m=new Map,u=null;function d(){return s.syncManager||null}function h(I){l=!!I,s.onStreamingChange?.(l),l?d()?.setActiveTurn(i):d()?.clearActiveTurn()}function p(){c!==null&&(t.clearTimeout(c),c=null)}function b(){u!==null&&(t.clearTimeout(u),u=null)}function v({stoppedByUser:I=!1}={}){p(),b();let y=i;if(o&&(o.close(),o=null),y&&typeof e.cancelChatTurn=="function")try{e.cancelChatTurn(y).catch(()=>{})}catch{}a&&(a.querySelector(".chat-reconnect-note")?(a.closest(".ai-msg-element")||a.parentElement)?.remove():I&&!a.textContent.trim()?a.parentNode?.remove():a.setAttribute("aria-busy","false"),a=null),i="",h(!1)}function E(I,y,k,P,R,D=i,L=""){let $=e.normalizeRetryMeta(L);e.showChatRetry({messageElement:I,chatContainer:y,message:R,requestId:$.requestId,retryAfterSeconds:$.retryAfterSeconds,errorCode:$.errorCode,onRetry:()=>{I.parentNode?.remove(),B({chatContainer:y,chatInput:k,retryMessage:P,clientTurnId:D||Rt(t),assistantMessage:s.getAssistantMessage?.()||"",locationOptions:s.locationOptions||{}})}})}function A(I,y,k,P,R,D=i,L=""){let $=e.normalizeRetryMeta(L);e.showChatPartialNotice({messageElement:I,chatContainer:y,message:R,requestId:$.requestId,retryAfterSeconds:$.retryAfterSeconds,errorCode:$.errorCode,onRetry:()=>{B({chatContainer:y,chatInput:k,retryMessage:P,clientTurnId:D||Rt(t),assistantMessage:s.getAssistantMessage?.()||"",locationOptions:s.locationOptions||{}})}})}let S=new Set(["","chat_unavailable","upstream_circuit_open","rate_limited"]),_=2,
4w=8e3;function f({aiMessage:I,chatContainer:y,chatInput:k,userMessage:P,turnId:R,errorCode:D="",retryAfterSeconds:L=0}){if(!R||!y||!k)return!1;let $=m.get(R)||0;if($>=_||!S.has(D))return!1;let G=Math.max(0,Number(L)||0)*1e3;if(G>w)return!1;let J=e.config?.timeouts?.chatAutoRetryBaseMs||1500,X=Math.max(G,J*($+1));m.set(R,$+1);let W=t.document.createElement("span");return W.className="chat-reconnect-note",W.textContent="Connection hiccup \u2014 retrying\u2026",I.replaceChildren(W),I.setAttribute("aria-busy","true"),e.setChatBusy(y,I,!0),a=I,i=R,h(!0),b(),u=t.setTimeout(()=>{u=null,(I.closest(".ai-msg-element")||I.parentElement)?.remove(),a=null,B({chatContainer:y,chatInput:k,retryMessage:P,clientTurnId:R,assistantMessage:s.getAssistantMessage?.()||"",locationOptions:s.locationOptions||{}})},X),!0}function g(I,y,{announceText:k=""}={}){p(),o&&(o.close(),o=null),a=null,e.setChatBusy(I,y,!1),k&&typeof e.announceChatStreamComplete=="function"&&e.announceChatStreamComplete(I,y,k),h(!1)}function C(I){I&&(d()?.notifyTurnCompleted(I),m.delete(I)),I===i&&(i="")}function T(I,y,k){if(!Array.isArray(k)||k.length===0)return;let P=I?.closest?.(".ai-msg-element")||I?.parentElement;Fn({beamo:e,global:t,host:P,sources:k,safeHostname:s.safeHostname,turnId:y})}function x(I,y,k,P,R){Hn({beamo:e,global:t,messageElement:I,chatContainer:P,chatInput:R,turnId:y,userMessage:k,searchTerm:s.getSearchTerm?.()||"",onRegenerate:D=>{N({...D,assistantMessage:s.getAssistantMessage?.()||"",locationOptions:s.locationOptions||{}})}})}async function N({chatContainer:I,chatInput:y,messageElement:k,turnId:P,userMessage:R,mode:D="regenerate",assistantMessage:L="",locationOptions:$={}}={}){!I||!y||!P||!R||(k?.closest(".ai-msg-element")?.remove(),await B({chatContainer:I,chatInput:y,retryMessage:R,clientTurnId:P,assistantMessage:L,locationOptions:$,responseMode:D,replaceLastAssistant:!0}))}async function B({chatContainer:I,chatInput:y,retryMessage:k="",clientTurnId:P="",assistantMessage:R="",locationOptions:D={},responseMode:L="",replaceLastAssistant:$=!1}={}){let G=e.config,J=k!=="",X=(J?k:y?.value||"").trim();if(!X||!I||!y)return;let W=P||Rt(t),V=null;J||(e.resetChatInput(y),V=e.appendChatMessage(I,"user-msg-text",X,{turnId:W})),p(),b(),o&&(o.close(),a&&!a.textContent.trim()?a.parentNode?.remove():a&&a.setAttribute("aria-busy","false"),o=null,a=null,h(!1));let j=e.appendChatMessage(I,"ai-msg-text","");j.dataset.turnId=W,a=j,i=W,s.onAssistantBubbleCreated?.({aiMessage:j,chatContainer:I??null,turnId:W,userMessage:X}),e.setChatBusy(I,j,!0),h(!0),V&&typeof e.scrollChatTurnIntoView=="function"&&e.scrollChatTurnIntoView(I??null,V.closest(".user-msg-element")||V.parentElement,j.closest(".ai-msg-element")||j.parentElement),d()?.notifyTurnStarted(W,X);let ee=e.fallbackLocation();try{ee=e.normalizeIpData(await e.getLocationData(D))||e.fallbackLocation()}catch{ee=e.fallbackLocation()}let Ee=s.getGroundingSources?.()||[],Y=typeof s.getSearchTermForPayload=="function"?String(s.getSearchTermForPayload()||"").trim():"",se=typeof s.getCiteOnlyResults=="function"?!!s.getCiteOnlyResults():!1,ae={userMessage:X,clientTurnId:W,latitude:ee?.latitude||"0",longitude:ee?.longitude||"0",aiPreset:jr(tt(t,e)),deepProvider:Sn(t,e)},Me=cc(t);Me&&(ae.timezone=Me),Y&&(ae.searchTerm=Y);let Ue=zr(It(t,e));Ue&&(ae.customInstructions=Ue),se&&(ae.citeOnlyResults="1"),R&&(ae.assistantMessage=R),Ee.length>0&&(ae.searchResults=JSON.stringify(Ee));let Te=s.getSearchContext?.();if(Te&&typeof Te=="object"&&Object.keys(Te).length>0)try{ae.searchContext=JSON.stringify(Te)}catch{}let ne=s.getInstantSnapshot?.();if(ne&&typeof ne=="object"&&Object.keys(ne).length>0)try{ae.instantSnapshot=JSON.stringify(ne)}catch{}else if(s.getInstantCard&&!J)try{let de=await s.getInstantCard(X);de&&typeof de=="object"&&typeof de.kind=="string"&&(ae.card=JSON.stringify(de))}catch{}J&&(ae.retryLastUserMessage="1"),$&&(ae.replaceLastAssistant="1"),L&&(ae.responseMode=L);let ce="",en=!1,wt=!1,Fe="",st=null,Ot=null,tn="",ot="web",Pn=null,In=null,Nn=await Ie(e),Be=e.streamSsePost(G.endpoints.chat,ae,{headers:Nn});if(i!==W){Be.close(),(j.closest(".ai-msg-element")||j.parentElement)?.remove();return}o=Be;let St="",xe=0,mr=0,kt=0,hr=0,Ln=0,nn=null;function Mn(){let de=t.performance;return de&&typeof de.now=="function"?de.now():Date.now()}function H(){try{return!!t.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches}catch{return!1}}let q=!H()&&typeof t.requestAnimationFrame=="function",z=q?260:45;function Z(){nn!==null&&(t.clearTimeout(nn),nn=null)}function le(){if(e.setMessageContent(j,St),q&&o===Be){St.length<Ln&&(kt=0);let de=kt===0,re=0;if(de){let On=j.textContent?j.textContent.trim().split(/\s+/).length:0,Dn=Math.max(1,On-kt);re=Math.min(28,480/Dn)}let{total:qe,revealMs:Bn}=ic(j,kt,re,"ai-msg-word",t.document);kt=qe,Ln=St.length,hr=Mn()+Bn+240}e.scrollChatToBottom(I??null)}function ge(){xe&&typeof t.cancelAnimationFrame=="function"&&(t.cancelAnimationFrame(xe),xe=0)}function Ce(){ge(),le()}function Dt(){xe||(typeof t.requestAnimationFrame=="function"?xe=t.requestAnimationFrame(rn):le())}function rn(){if(xe=0,o!==Be)return;let de=Mn();de-mr>
4=z?(mr=de,le()):Dt()}function sn(de){St=de,Dt()}function je(){if(Z(),o!==null&&o!==Be)return;if(j.isConnected===!1){ge();return}if(j.querySelector(".retry-action")||j.querySelector(".chat-reconnect-note")){ge();return}ge(),kt=0,Ln=0;let de=[...Array.from(j.querySelectorAll(".chat-message-actions")),...Array.from(j.querySelectorAll(".chat-partial-notice"))];e.setMessageContent(j,St);for(let re of de)j.appendChild(re);Ot&&Ot.length>0&&T(j,W,Ot),e.scrollChatToBottom(I??null)}function at(){if(Z(),!q){je();return}let de=Math.max(0,Math.min(1200,hr-Mn()));nn=t.setTimeout(je,de)}let Ts=G.timeouts?.chatMs||6e4;function vt(){p(),c=t.setTimeout(()=>{o===Be&&(c=null,Ce(),je(),Be.close(),o=null,a=null,h(!1),E(j,I??null,y??null,X,"The chat response timed out. Please try again.",W),C(W))},Ts)}vt();let ue=G.messages.chatConnectionError,on=G.messages.chatPartialSaved;Be.onmessage=de=>{if(o===Be){vt();try{let re=e.parseStreamPayload(de.data);if(re.searchActivity){tn=re.searchActivity.query||"",ot=re.searchActivity.kind||"web";return}if(re.sources){st=re.sources;return}if(re.sportsPack){Pn=re.sportsPack;return}if(re.chatCard&&typeof re.chatCard=="object"&&typeof re.chatCard.kind=="string"){In=re.chatCard;return}if(re.warning&&(wt=!0,Fe=re.warning),re.error){if(en=!0,Ce(),je(),g(I,j),ce.trim())A(j,I,y,X,re.content||Fe||on,W,{requestId:re.requestId||"",retryAfterSeconds:re.retryAfterSeconds||0,errorCode:re.code||""});else{if(f({aiMessage:j,chatContainer:I??null,chatInput:y??null,userMessage:X,turnId:W,errorCode:re.code||"",retryAfterSeconds:re.retryAfterSeconds||0}))return;let qe=Ch(e,re,ue);rr(t,{message:qe,scope:"chat",errorCode:re.code||"",retryAfterSeconds:re.retryAfterSeconds||0}),E(j,I,y,X,qe,W,{requestId:re.requestId||"",retryAfterSeconds:re.retryAfterSeconds||0,errorCode:re.code||""})}C(W);return}if(re.content&&(ce=re.replace?re.content:ce+re.content,sn(ce)),re.done){Ce(),at();let qe=!!ce.trim();if(g(I,j,{announceText:qe&&!en&&!wt?ce:""}),en)return;if(wt&&qe){A(j,I,y,X,Fe||on,W),s.onResponseComplete?.(ce),C(W),d()?.refreshFromServer().catch(()=>{});return}if(qe){if(tn){let Dn=j?.closest?.(".ai-msg-element")||j?.parentElement;Us({beamo:e,global:t,host:Dn,activity:{query:tn,kind:ot}})}let Bn=In??(Pn?{kind:"sports",data:Pn}:null);if(Bn){let Dn=j?.closest?.(".ai-msg-element")||j?.parentElement;js({beamo:e,global:t,host:Dn,card:Bn})}let On=st&&st.length>0?st:Ee;Ot=Array.isArray(On)?On:null,T(j,W,On),x(j,W,X,I,y),s.onResponseComplete?.(ce),C(W),d()?.refreshFromServer().catch(()=>{});return}je(),s.onResponseComplete?.(""),rr(t,{message:ue,scope:"chat"}),E(j,I,y,X,ue,W),C(W)}}catch{Ce(),at(),o===Be&&g(I,j),rr(t,{message:ue,scope:"chat"}),E(j,I,y,X,ue,W),C(W)}en&&(a=null,e.setChatBusy(I,j,!1),h(!1))}},Be.onerror=()=>{if(o===Be){if(Ce(),je(),g(I,j),ce.trim())A(j,I,y,X,Fe||on,W);else{if(f({aiMessage:j,chatContainer:I??null,chatInput:y??null,userMessage:X,turnId:W}))return;rr(t,{message:ue,scope:"chat"}),E(j,I,y,X,ue,W)}C(W)}}}return{cancel:v,send:B,regenerateReply:N,isStreaming:()=>l,getActiveStream:()=>o,getActiveTurnId:()=>i}}let r=e.chat&&typeof e.chat=="object"?e.chat:{};e.chat={...r,createClient:n,createTurnId:()=>Rt(t)}}var uc={pi:Math.PI,\u03C0:Math.PI,tau:Math.PI*2,e:Math.E};function Ah(e){if(!Number.isInteger(e)||e<0)return Number.NaN;if(e>170)return 1/0;let t=1;for(let n=2;n<=e;n+=1)t*=n;return t}function Eh(e){if(!Number.isInteger(e)||e<0||e>78)throw new Error("fibonacci");let t=0,n=1;for(let r=0;r<e;r+=1)[t,n]=[n,t+n];return t}function dc(e,t){let n=Math.abs(Math.round(e)),r=Math.abs(Math.round(t));for(;r;)[n,r]=[r,n%r];return n}function Th(e,t){let n=dc(e,t);return n===0?0:Math.abs(Math.round(e)*Math.round(t))/n}function xh(e,t){let n=Math.round(e),r=Math.round(t);if(n<0||r<0||r>n)throw new Error("domain");r=Math.min(r,n-r);let s=1;for(let o=0;o<r;o+=1)s=s*(n-o)/(o+1);return Math.round(s)}function Rh(e,t){let n=Math.round(e),r=Math.round(t);if(n<0||r<0||r>n)throw new Error("domain");let s=1;for(let o=0;o<r;o+=1)s*=n-o;return s}var Ph={mod:(e,t)=>e%t,gcd:dc,lcm:Th,ncr:xh,npr:Rh};function Ih(e){let t=String(e).replace(/Ã/g,"*").replace(/÷/g,"/").replace(/â/g,"-").replace(/â/g,"sqrt").replace(/Ï/g,"pi").replace(/\s+/g,""),n=[],r=0;for(;r<t.length;){let s=t[r];
4if(/[0-9.]/.test(s)){let o=r+1;for(;o<t.length&&/[0-9.]/.test(t[o]);)o+=1;if(o<t.length&&(t[o]==="e"||t[o]==="E")){let i=o+1;if(i<t.length&&(t[i]==="+"||t[i]==="-")&&(i+=1),i<t.length&&/[0-9]/.test(t[i])){for(i+=1;i<t.length&&/[0-9]/.test(t[i]);)i+=1;o=i}else if(i>=t.length||!/[a-z]/i.test(t[i]))throw new Error("number")}let a=Number(t.slice(r,o));if(!Number.isFinite(a))throw new Error("number");n.push({type:"num",value:a}),r=o;continue}if(/[a-z]/i.test(s)){let o=r+1;for(;o<t.length&&/[a-z0-9]/i.test(t[o]);)o+=1;n.push({type:"name",value:t.slice(r,o).toLowerCase()}),r=o;continue}if("+-*/^%()!,".includes(s)){n.push({type:"op",value:s}),r+=1;continue}throw new Error("unexpected: ".concat(s))}return n}function Nh(e,t,n){let r=0,s=!1,o=()=>e[r],a=()=>e[r++],i=f=>t?f*Math.PI/180:f,c=f=>t?f*180/Math.PI:f,l=f=>{let g=(f%360+360)%360;return g===0||g===180?0:g===90?1:g===270?-1:Math.sin(i(f))},m=f=>{let g=(f%360+360)%360;return g===90||g===270?0:g===0?1:g===180?-1:Math.cos(i(f))},u=f=>{let g=(f%180+180)%180;return g===0?0:g===90?1/0:Math.tan(i(f))},d={sin:f=>t?l(f):Math.sin(f),cos:f=>t?m(f):Math.cos(f),tan:f=>t?u(f):Math.tan(f),sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,asin:f=>c(Math.asin(f)),acos:f=>c(Math.acos(f)),atan:f=>c(Math.atan(f)),sqrt:Math.sqrt,cbrt:Math.cbrt,ln:Math.log,log:f=>Math.log10(f),log2:Math.log2,exp:Math.exp,abs:Math.abs,round:Math.round,floor:Math.floor,ceil:Math.ceil,fib:Eh};function h(f){let g=o();if(!g||g.type!=="op"||g.value!==f)throw new Error("expected ".concat(f));a()}function p(){let f=o();if(!f)throw new Error("unexpected end");if(f.type==="num")return a(),f.value;if(f.type==="op"&&f.value==="("){a();let g=w();return h(")"),g}if(f.type==="name"){if(a(),f.value==="ans")return n;if(f.value in uc)return uc[f.value];let g=d[f.value];if(g){h("(");let T=w();return h(")"),g(T)}let C=Ph[f.value];if(C){h("(");let T=w();h(",");let x=w();return h(")"),C(T,x)}throw new Error("unknown: ".concat(f.value))}throw new Error("unexpected token")}function b(){let f=p(),g=!1;for(;;){let C=o();if(C&&C.type==="op"&&C.value==="!")a(),f=Ah(f),g=!1;else if(C&&C.type==="op"&&C.value==="%")a(),f/=100,g=!0;else break}return s=g,f}function v(){let f=o();if(f&&f.type==="op"&&(f.value==="-"||f.value==="+")){a();let g=v();return f.value==="-"?-g:g}return E()}function E(){let f=b(),g=o();if(g&&g.type==="op"&&g.value==="^"){a();let C=A();return f**C}return f}function A(){let f=o();if(f&&f.type==="op"&&(f.value==="-"||f.value==="+")){a();let C=A();return f.value==="-"?-C:C}let g=E();for(;S(o());)g*=E();return g}function S(f){return!!f&&(f.type==="num"||f.type==="name"||f.type==="op"&&f.value==="(")}function _(){let f=v(),g=!1;for(;;){let C=o();if(C&&C.type==="op"&&(C.value==="*"||C.value==="/")){a();let T=v();f=C.value==="*"?f*T:f/T,g=!0}else if(S(C))f*=v(),g=!0;else break}return g&&(s=!1),f}function w(){let f=_();for(;;){let g=o();if(g&&g.type==="op"&&(g.value==="+"||g.value==="-")){a();let C=_();s?f=g.value==="+"?f+f*C:f-f*C:f=g.value==="+"?f+C:f-C}else break}return f}return{run(){let f=w();if(r!==e.length)throw new Error("trailing input");return f}}}function Lh(e){if(Number.isNaN(e))return"Undefined";if(e===1/0)return"Infinity";if(e===-1/0)return"-Infinity";if(Number.isInteger(e))return String(e);let t=Number(e.toPrecision(15));return String(t)}function fc(e,{degrees:t=!1,ans:n=0}={}){let r=Ih(e);if(r.length===0)throw new Error("empty");let s=Nh(r,t,Number.isFinite(n)?n:0).run();return Lh(s)}function mc({ttlMs:e,maxEntries:t=64,persistKey:n,global:r}){let s=new Map,o=new Map,a=r??globalThis;function i(){if(n)try{let u={};for(let[d,h]of s)u[d]=h;Qe(a,n,JSON.stringify(u))}catch{}}if(n)try{let u=Je(a,n,"");if(u){let d=JSON.parse(u),h=Date.now();for(let[p,b]of Object.entries(d))b&&typeof b=="object"&&typeof b.storedAt=="number"&&h-b.storedAt<=e&&s.size<t&&s.set(p,{value:b.value,storedAt:b.storedAt})}}catch{}function c(u){let d=s.get(u);if(d){if(Date.now()-d.storedAt>e){s.delete(u);return}return s.delete(u),s.set(u,d),d.value}}function l(u,d){if(!s.has(u)&&s.size>=t){let h=s.keys().next().value;h!==void 0&&s.delete(h)}s.set(u,{value:d,storedAt:Date.now()}),i()}async function m(u,d){let h=c(u);if(h!==void 0)return h;let p=o.get(u);if(p)return p;let b=(async()=>{try{let v=await d();return v!=null&&l(u,v),v}finally{o.delete(u)}})();return o.set(u,b),b}return{get:c,set:l,getOrFetch:m,clear(){s.clear(),o.clear(),n&&la(a,n)}}}var pc,hc=String.raw(pc||(pc=xs(["(?:jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)"]))),gc,Mh=new RegExp(String.raw(gc||
4(gc=xs(["s+(?:rights+now|now|currently|ats+thes+moment|overs+thes+weekend|days+afters+tomorrow|ins+d{1,2}s+days?|(?:on|for)s+",".?s+d{1,2}(?:st|nd|rd|th)?|",".?s+d{1,2}(?:st|nd|rd|th)?|(?:today|tonight|tomorrow|yesterday)(?:s+(?:morning|afternoon|evening|night|noon))?|thiss+(?:morning|afternoon|evening|weekend|week|month|year)|nexts+(?:week|month|weekend|year)|(?:ons+)?(?:(?:this|next)s+)?(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday)(?:s+(?:morning|afternoon|evening|night))?|morning|afternoon|evening|night|noon|midnight)$"],["\\s+(?:right\\s+now|now|currently|at\\s+the\\s+moment|over\\s+the\\s+weekend|day\\s+after\\s+tomorrow|in\\s+\\d{1,2}\\s+days?|(?:on|for)\\s+","\\.?\\s+\\d{1,2}(?:st|nd|rd|th)?|","\\.?\\s+\\d{1,2}(?:st|nd|rd|th)?|(?:today|tonight|tomorrow|yesterday)(?:\\s+(?:morning|afternoon|evening|night|noon))?|this\\s+(?:morning|afternoon|evening|weekend|week|month|year)|next\\s+(?:week|month|weekend|year)|(?:on\\s+)?(?:(?:this|next)\\s+)?(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday)(?:\\s+(?:morning|afternoon|evening|night))?|morning|afternoon|evening|night|noon|midnight)$"])),hc,hc),"i");function yc(e){let t=String(e??"").trim().replace(/^[\s,]+|[\s,?.!]+$/g,"").trim(),n="";for(;t&&t!==n;)n=t,t=t.replace(Mh,"").trim();return t}var Bh=/^(?:me|here|nearby|my\s+(?:location|area|city|town|place|position|region|spot|home|house|neighbou?rhood|surroundings?|locale|gps|zip(?:\s*code)?|postal\s*code)|current\s+(?:location|position|area|city|place|gps)|this\s+(?:location|area|city|place)|where\s+i(?:'?m|\s*am)(?:\s+at)?|(?:around|near)\s+me)$/i;function bc(e){return Bh.test(String(e??"").trim())}var Oh=new Set(["the","a","an","this","that","right","now","currently","moment","next","last","upcoming","coming","soon","soonest","sooner","later","after","before","in","nearest","today","tonight","tomorrow","yesterday","morning","mornings","afternoon","afternoons","evening","evenings","night","nights","noon","midnight","dawn","dusk","daytime","daybreak","day","days","week","weeks","weekend","weekends","weekday","weekdays","month","months","year","years","january","jan","february","feb","march","mar","april","apr","may","june","jun","july","jul","august","aug","september","sept","sep","october","oct","november","nov","december","dec","monday","tuesday","wednesday","thursday","friday","saturday","sunday"]);function wc(e){let t=String(e??"").toLowerCase().replace(/['â]s\b/g,"").replace(/\b(\d{1,2})(?:st|nd|rd|th)\b/g,"$1").split(/\s+/).filter(Boolean);return t.length>0&&t.every(n=>Oh.has(n)||/^\d{1,2}$/.test(n))}function mo(e){let t=yc(e);return bc(t)||wc(t)?"":t}var ik=mc({ttlMs:1440*60*1e3,maxEntries:128,persistKey:"beamo-geocode-cache-v1"});var Dh=/^(?:what|whats|what's|hows|how's|how|is|are|will|the|a|an|current|currently|today'?s?|todays|tonight'?s?|tomorrow'?s?|this|hourly|weekly|daily|monthly|10[\s-]?day|7[\s-]?day|five[\s-]?day|live|local|my|our|your|latest|upcoming|extended|weekend)\b/i;function Hh(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var $h=[{key:"temperature",phrases:["temperature","temp","current temperature","current temp","how hot","how cold"]},{key:"feelsLike",phrases:["feels like","feel like","real feel","apparent temperature"]},{key:"windChill",phrases:["wind chill factor","wind chill","windchill","wind-chill"]},{key:"heatIndex",phrases:["heat index","heatindex","heat-index"]},{key:"wind",phrases:["wind speed","windspeed","how windy","wind gusts","windy","gusts","wind"]},{key:"humidity",phrases:["humidity","how humid"]},{key:"dewPoint",phrases:["dew point","dewpoint"]},{key:"pressure",phrases:["barometric pressure","atmospheric pressure","air pressure","pressure"]},{key:"visibility",phrases:["visibility"]},{key:"cloudCover",phrases:["cloud cover","cloud coverage","cloudiness","how cloudy"]},{key:"uvIndex",phrases:["uv index","uvindex","uv-index","ultraviolet index","uv level","uv rays","uv"]}],Fh=/\s+(?:right\s+now|now|today|tonight|tomorrow|currently|current|at\s+the\s+moment|this\s+(?:morning|afternoon|evening|week|weekend)|over\s+the\s+weekend|forecast|outside|out\s+there|rn)\s*$/i;function qh(e){let t=e,n="";for(;t!==n;)n=t,t=t.replace(Fh,"").trim();return t}var Uh=$h.map(e=>({key:e.key,patterns:e.phrases.flatMap(t=>
4{let n=Hh(t),r=[{re:new RegExp("\\b".concat(n,"\\b[^]*?\\b(?:in|for|at|near|around|of)\\s+(.+)$"),"i"),leading:!1},{re:new RegExp("^(.+?)\\s+".concat(n,"\\s*$"),"i"),leading:!0}];return/^how\s/i.test(t)&&r.push({re:new RegExp("^".concat(n,"\\s+(?:is|was|are|s)\\s+(?:it\\s+)?(.+)$"),"i"),leading:!1}),r})}));function jh(e){let t=qh(String(e??"").trim());if(!t)return null;for(let n of Uh)for(let{re:r,leading:s}of n.patterns){let o=t.match(r);if(!o)continue;let a=mo(o[1]);if(!(!a||s&&Dh.test(a)))return{key:n.key,place:a}}return null}function Sc(e){return jh(e)!==null}var zh=/\bweather\s+(?:channel|underground|network|app|apps|widget|widgets|station|stations|balloon|balloons|vane|vanes|girl|man|woman|bug)\b|weather\.com|\bweatherbug\b|^\s*the\s+weather\s*$/i;function kc(e,t=globalThis){function n(o){let a=String(o??"").trim();return a?/\bweather\b/i.test(a)?!zh.test(a):Sc(a)?!0:/\b(?:forecast|temperature|radar)\s+(?:today|tomorrow|tonight|now|current|this weekend|weekend|this week|next week|in|near|for)\b/i.test(a)||/^(?:10[\s-]?day|ten[\s-]?day|7[\s-]?day|seven[\s-]?day|five[\s-]?day|extended|long[\s-]?range)\s+(?:weather\s+)?forecast\s+\S+/i.test(a)||/\S+\s+(?:10[\s-]?day|ten[\s-]?day|7[\s-]?day|seven[\s-]?day|five[\s-]?day|extended|long[\s-]?range)\s+(?:weather\s+)?forecast\b/i.test(a)||/\b(?:weather|forecast)\s+(?:radar|map)\b/i.test(a)||/\b(?:rain|precipitation|storm)\s+map\b/i.test(a)||/\b(?:compare|comparison)\b.*\b(?:weather|forecast|temperature|conditions)\b/i.test(a)||/\b(?:weather|forecast|temperature|conditions)\s+comparison\b/i.test(a)||/\b(?:weather|forecast|temperature|conditions)\b.*\b(?:vs\.?|versus)\b/i.test(a)||/\b.+\s+(?:vs\.?|versus)\s+.+\s+(?:weather|forecast|temperature|conditions)\b/i.test(a)||/\b(?:today|tomorrow|tonight|current|local)\s+(?:forecast|temperature)\b/i.test(a)||/\bwhat'?s\s+the\s+(?:forecast|temperature)\b/i.test(a)||/\b(?:is it going to|will it|chance of)\s+(?:rain|snow)\b/i.test(a)||/\b(?:rain|snow)\s+(?:today|tomorrow|tonight|forecast|report|prediction|chance|chances|this weekend|weekend)\b/i.test(a)||/\bis\s+it\s+(?:currently\s+|going\s+to\s+be\s+|gonna\s+be\s+|supposed\s+to\s+be\s+|getting\s+)?(?:sunny|cloudy|overcast|rainy|raining|snowy|snowing|stormy|foggy|hazy|gloomy|misty|drizzly|muggy|humid|breezy)\b/i.test(a)||/^(?:is\s+it\s+(?:currently\s+|going\s+to\s+be\s+|gonna\s+be\s+)?)?(?:sunny|cloudy|overcast|rainy|snowy|stormy|foggy|hazy|gloomy|misty|drizzly)\s+(?:in|near|for)\b/i.test(a)||/\b(?:sunny|cloudy|overcast|rainy|snowy|stormy|foggy)\s+(?:today|tonight|tomorrow|this\s+weekend|over\s+the\s+weekend|outside|out\s+there|right\s+now)\b/i.test(a)||/\b(?:snowfall|rainfall)\s+(?:in|for|near|at|today|tomorrow|tonight|yesterday|this\s+(?:week|weekend|month|year|winter|season)|so\s+far|total|totals|amount|average|annual|expected|forecast|map|data)\b/i.test(a)||/\b\w+\s+(?:snowfall|rainfall)\b/i.test(a)||/\bstorm\s+(?:today|tomorrow|tonight|forecast|report|prediction|warning|watch|this weekend|weekend)\b/i.test(a)||/\b(?:umbrella|jacket|coat|commute|drive|driving|running|run|beach|ski|snowboard|outdoor\s+event|picnic|hike|hiking|water\s+(?:my\s+)?plants?|fishing|fish)\b.*\b(?:weather|forecast|today|tomorrow|tonight|this weekend|weekend|in|near|for|needed|need|safe|good)\b/i.test(a)||/\b(?:best|better|good|ideal)\s+(?:day|time|weather|window|hour)\b.*\b(?:hike|hiking|run|running|jog|beach|ski|snowboard|outdoor|picnic|camping|patio|walk|water\s+(?:my\s+)?plants?|fish|fishing)\b/i.test(a)||/\b(?:do i need|should i bring|should i wear|should i water|is it good|is it safe|safe to drive)\b.*\b(?:umbrella|jacket|coat|commute|drive|driving|running|run|beach|ski|snowboard|outdoor|picnic|hike|hiking|plants?|fishing|fish)\b/i.test(a)||/\b(?:hotter|warmer|colder|cooler)\s+than\s+normal\b/i.test(a)||/\b(?:record\s+(?:high|low)|rainfall\s+deficit|rain\s+deficit|precipitation\s+deficit|snowpack|snow\s+pack|degree\s+days?|heating\s+degree|cooling\s+degree)\b/i.test(a):!1}function r(o){if(e.url&&typeof e.url.isUrlQuery=="function")return e.url.isUrlQuery(o);let a=o.trim();return/^https?:\/\//i.test(a)?!!e.safeHttpUrl(a):a.includes("@")?!1:/^(?:[a-z0-9-]+\.)+[a-z]{2,}(?::\d{1,5})?(?:[/?#][^\s]*)?$/i.test(a)&&!!e.safeHttpUrl("https://".concat(a))}function s(o){try{return fc(o)}catch{throw new Error("Invalid expression.")}}e.searchIntents={evaluateMathExpression:s,isUrlQuery:r,isWeatherRequest:n}}function vc(e,t=globalThis.document,{preventScroll:n=!1}={}){return!e||typeof e.focus!="function"?!1:(e.hasAttribute("tabindex")||e.setAttribute("tabindex","-1"),e.focus({preventScroll:n}),t?.activeElement?t.activeElement===e||typeof e.contains=="function"&&e.contains(t.activeElement):!0)}function _c(e=globalThis.document){let t=e.getElementById("main-content");
4if(t&&vc(t))return!0;let n=e.querySelector("main");return vc(n)}function Cc(e=globalThis){let t=e.document,n=t?.querySelector('.skip-link[href="#main-content"]');!n||n.dataset.beamoSkipBound==="true"||(n.dataset.beamoSkipBound="true",n.addEventListener("click",r=>{r.preventDefault(),_c(t)}))}var Wh="beamo:weather-units-changed";function Ac(e=globalThis){typeof e.dispatchEvent=="function"&&e.dispatchEvent(new CustomEvent(Wh))}var Gh="beamo-weather-units";function Ec(e){let t=String(e??"").trim().toLowerCase();return t==="fahrenheit"||t==="celsius"?t:"auto"}function Tc(e){return e?.storageKeys?.weatherUnits||Gh}function Wr(e,t){return Ec(te(e,Tc(t),"auto"))}function Gr(e,t,n){ie(e,Tc(t),Ec(n))}function xc(e=globalThis,t={}){let n=e.document?.getElementById("settings-weather-units");!n||n.dataset.beamoWeatherUnitsBound==="true"||(n.dataset.beamoWeatherUnitsBound="true",n.value=Wr(e,t),n.addEventListener("change",()=>{Gr(e,t,n.value),Ac(e)}))}var Kr="settings-ui-locale";function Kh(e,t){if(e.document.getElementById(Kr))return e.document.getElementById(Kr);let r=e.document?.getElementById("settings-weather-units")?.closest(".settings-group__body");if(!r)return null;let s=e.document.createElement("div");s.className="settings-ui-locale-item settings-field",s.setAttribute("role","presentation");let o=e.document.createElement("label");o.className="settings-ui-locale__label settings-field__label",o.setAttribute("for",Kr),o.setAttribute("data-beamo-i18n","settings.uiLanguage"),o.textContent="Interface language";let a=e.document.createElement("select");a.id=Kr,a.className="settings-field__select",a.setAttribute("data-beamo-i18n-aria","settings.uiLanguage");for(let i of yn){let c=e.document.createElement("option");c.value=i;let l=$i[i]||"settings.uiLangEn";c.setAttribute("data-beamo-i18n",l),c.textContent=i,a.appendChild(c)}return s.append(o,a),r.appendChild(s),a}function Rc(e=globalThis,t={}){if(!e.document?.getElementById)return;let n=Kh(e,t);!n||n.dataset.beamoUiLocaleBound==="true"||(n.dataset.beamoUiLocaleBound="true",n.value=Jn(e,t),e.Beamo?.i18n?.applyChrome?.(),n.addEventListener("change",()=>{let r=n.value;gn(e,t,r),e.Beamo?.i18n?.setLocale?.(r)}),e.addEventListener(ao,()=>{n.value=Jn(e,t),e.Beamo?.i18n?.applyChrome?.()}))}function Pc(e){let t=e?.accounts;try{return t?.getState?.()??{}}catch{return{}}}function ho(e=globalThis.Beamo){return!!Pc(e).signedIn}function Se(e=globalThis.Beamo){return!!Pc(e).isPro}function po(e=globalThis.Beamo){return Se(e)?ut:ho(e)?Pt:Zn}function Vh(e,t=globalThis.Beamo){return dt(e)<=dt(po(t))}function go(e,t=globalThis.Beamo){return Vh(e,t)?null:Ge(e)===ut?"pro":"account"}var Yh="beamo-ai-preset-auto";function yo(e=globalThis.Beamo){let t=oe(e).storageKeys?.aiPresetAuto;return typeof t=="string"&&t?t:Yh}function Ic(e,t=e?.Beamo){ie(e,yo(t),"explicit")}function Xh(e,t){try{let n=oe(t).storageKeys?.aiPreset||"beamo-ai-preset",r=e?.localStorage?.getItem?.(n);return typeof r=="string"&&r.trim()!==""}catch{return!1}}function Vr(e=globalThis,t=e?.Beamo){if(!ho(t))return null;let n=te(e,yo(t),"");if(n==="explicit")return null;let r=Se(t)?ut:Pt,s=Xh(e,t),o=tt(e,t);return s&&n===""||s&&dt(r)<=dt(o)?null:(er(e,r,t),ie(e,yo(t),"auto"),r)}function Nc(e=globalThis,t=e?.Beamo){Vr(e,t),typeof t?.accounts?.subscribe=="function"&&t.accounts.subscribe(()=>{Vr(e,t)})}var Jh=["stripe"];function vn(e,t){let n=typeof e?.querySelector=="function"?e.querySelector('meta[name="'.concat(t,'"]')):null;return!n||typeof n.getAttribute!="function"?"":String(n.getAttribute("content")||"").trim()}function ft(e){let t=String(e||"").trim();if(!t)return"";try{let n=new URL(t),r=["127.0.0.1","localhost","::1","[::1]"].includes(n.hostname);if(n.protocol==="https:"||n.protocol==="http:"&&r)return t}catch{return""}return""}function Lc(e){let t=String(e||"").trim().toLowerCase();return Jh.includes(t)?t:"stripe"}function Qh(e){if(!e||typeof e!="object")return null;let t=ft(e.checkoutUrl),n=ft(e.checkoutUrlAnnual)||"";return!t&&!n?null:{provider:Lc(e.provider),checkoutUrl:t,checkoutUrlAnnual:n,portalUrl:ft(e.portalUrl)||"",price:String(e.price||"").trim(),priceAnnual:String(e.priceAnnual||"").trim()}}function Mc(e=globalThis){let t=Qh(e?.Beamo?.billing);if(t)return t;let n=e?.document,r=ft(vn(n,"beamo-billing-checkout-url")),s=ft(vn(n,"beamo-billing-checkout-url-annual"))||"";return!r&&!s?null:{provider:Lc(vn(n,"beamo-billing-provider")),checkoutUrl:r,checkoutUrlAnnual:s,portalUrl:ft(vn(n,"beamo-billing-portal-url"))||"",price:vn(n,"beamo-billing-price"),priceAnnual:vn(n,"beamo-billing-price-annual")}}function Zh(e,{clientReferenceId:t="",email:n=""}={}){let r=ft(e?.checkoutUrl);if(!r)return"";let s;try{s=new URL(r)}catch{return""}let o=String(t||"").trim(),a=String(n||"").trim();return o&&s.searchParams.set("client_reference_id",o),a&&s.searchParams.set("prefilled_email",a),s.toString()}function ep(e,t){return e?t==="annual"?{provider:e.provider,checkoutUrl:ft(e.checkoutUrlAnnual)||""}:{provider:e.provider,checkoutUrl:ft(e.checkoutUrl)||""}:null}async function Bc(e,{plan:t="monthly",email:n="",global:r=globalThis}={}){let s=ep(e,t);if(!s?.checkoutUrl)return{ok:!1,status:0,url:"",error:"checkout_not_configured"};let o=r?.Beamo?.__supabaseClient;if(!o||typeof o.invokeFunction!="function")return{ok:!1,status:0,url:"",error:"checkout_signer_unavailable"};let a=await o.invokeFunction("billing-checkout",{body:{plan:t}}),i=a?.data&&typeof a.data=="object"?a.data:{},c=String(i.clientReferenceId??i.client_reference_id??"").trim();if(!a?.ok||!c)return{ok:!1,status:Number(a?.status)||0,url:"",error:String(i.error??"checkout_signing_failed")};let l=Zh(s,{clientReferenceId:c,email:String(i.email??n??"").trim()});return l?{ok:!0,status:Number(a.status)||200,url:l,error:""}:{ok:!1,status:0,url:"",error:"checkout_url_invalid"}}function Oc(e=globalThis){let t=e?.document;if(!t||typeof t.getElementById!="function")return;let n=t.getElementById("settings-ai-preset");if(!n)return;let r=e.Beamo,s=Array.from(n.querySelectorAll(".settings-ai-preset__option"));if(s.length===0)return;let o=we(e);function a(){let d=r?.accounts?.getState?.().account||null;return{userId:d?.userId||"",email:d?.email||""}}async function i(){let d=Mc(e);if(d){let E=a(),A=await Bc(d,{plan:"monthly",email:E.email,global:e});
4if(A.ok&&A.url&&typeof e.open=="function"){e.open(A.url,"_blank","noopener,noreferrer");return}}let h=r?.settingsPage;if(h&&typeof h.openTab=="function"){h.openTab("billing");return}let p=t.getElementById("settings-button");t.getElementById("settings-options")?.hidden&&p&&typeof p.click=="function"&&p.click();let v=t.querySelector?.(".settings-account__pro")||t.querySelector?.(".settings-account__pro-upgrade");v&&typeof v.scrollIntoView=="function"&&v.scrollIntoView({behavior:"smooth",block:"center"})}function c(){let d=t.getElementById("settings-button"),h=t.getElementById("settings-options");h&&!h.hidden&&d&&typeof d.click=="function"&&d.click();let p=t.getElementById("account-button");p&&typeof p.click=="function"&&p.click()}function l(){let d=po(r),h=Ge(tt(e,r));if(dt(h)>dt(d))h=d,er(e,h,r);else{let p=Vr(e,r);p&&(h=p)}return h}function m(){let d=l();try{t.documentElement?.setAttribute("data-ai-preset",d)}catch{}for(let h of s){let p=Ge(h.getAttribute("data-ai-preset")||""),b=go(p,r),v=b!==null,E=p===d,A=h.querySelector("[data-ai-preset-lock]");A&&(A.hidden=!v),h.setAttribute("aria-checked",E?"true":"false"),h.setAttribute("data-locked",v?"true":"false"),h.classList.toggle("settings-ai-preset__option--active",E),h.classList.toggle("settings-ai-preset__option--locked",v);let S=!!t.getElementById("settings-options");h.setAttribute("tabindex",S?"-1":E?"0":"-1");let _=lo(p),w=b==="pro"?" (Beamo Search Pro \u2014 upgrade to use)":b==="account"?" (sign in to use)":"";h.setAttribute("aria-label","".concat(_).concat(w))}n.setAttribute("aria-label","AI answer style: ".concat(lo(d)))}async function u(d){let h=Ge(d),p=go(h,r);if(p==="pro"){await i();return}if(p==="account"){c();return}er(e,h,r),Ic(e,r),m()}for(let d of s)d.addEventListener("click",h=>{h?.preventDefault?.(),u(d.getAttribute("data-ai-preset")||"")}),d.addEventListener("keydown",h=>{let p=h.key;(p===" "||p==="Enter")&&(h.preventDefault?.(),u(d.getAttribute("data-ai-preset")||""))});m(),typeof r?.accounts?.subscribe=="function"&&r.accounts.subscribe(()=>m())}function Dc(e=globalThis){let t=e.document,n=t?.getElementById("settings-ai-deep-provider-item"),r=t?.getElementById("settings-ai-deep-provider");if(!n||!r||r.dataset.beamoDeepProviderBound==="true")return;r.dataset.beamoDeepProviderBound="true";let s=e.Beamo,o=()=>{r.value=Sn(e,s)},a=()=>{n.hidden=!Se(s)};o(),a(),r.addEventListener("change",()=>{rc(e,r.value,s),o(),s?.accounts?.schedulePushWithChat?.({source:"deep-provider"})}),typeof s?.accounts?.subscribe=="function"&&s.accounts.subscribe(()=>{a(),o()})}function Hc(e=globalThis.Beamo){let t=oe(e).storageKeys?.deepOverview;return typeof t=="string"&&t?t:"beamo-deep-overview"}function $c(e=globalThis,t=e?.Beamo){let n=String(te(e,Hc(t),"")??"").trim().toLowerCase();return["1","true","on","yes"].includes(n)?"on":n==="off"?"off":"unset"}function Fc(e=globalThis,t=e?.Beamo){let n=$c(e,t);return n==="on"?!0:n==="off"?!1:Se(t)}function qc(e,t,n=e?.Beamo){return ie(e,Hc(n),t?"on":"off")}function Uc(e=globalThis,t=e?.Beamo){let n=$c(e,t);return n==="unset"?void 0:n}function jc(e=globalThis){let t=e.document,n=t?.getElementById("settings-ai-deep-overview-item"),r=t?.getElementById("settings-ai-deep-overview");if(!n||!r||r.dataset.beamoDeepOverviewBound==="true")return;r.dataset.beamoDeepOverviewBound="true";let s=e.Beamo,o=()=>{r.checked=Fc(e,s),r.setAttribute("aria-checked",r.checked?"true":"false")},a=()=>{n.hidden=!Se(s)};o(),a(),r.addEventListener("change",()=>{qc(e,r.checked,s),o(),s?.accounts?.schedulePushWithChat?.({source:"deep-overview"})}),typeof s?.accounts?.subscribe=="function"&&s.accounts.subscribe(()=>{a(),o()})}function zc(e=globalThis){let t=e.document,n=t?.getElementById("settings-custom-instructions-item"),r=t?.getElementById("settings-custom-instructions");
4if(!n||!r||r.dataset.beamoCustomInstructionsBound==="true")return;r.dataset.beamoCustomInstructionsBound="true";let s=e.Beamo,o=()=>{r.value=It(e,s)},a=()=>{n.hidden=!Se(s)};o(),a();let i=null,c=()=>{i&&e.clearTimeout(i),i=e.setTimeout(()=>{i=null,s?.accounts?.schedulePushWithChat?.({source:"custom-instructions"})},800)};r.addEventListener("input",()=>{uo(e,r.value,s),c()}),r.addEventListener("blur",()=>{i&&(e.clearTimeout(i),i=null),r.value=uo(e,r.value,s),s?.accounts?.schedulePushWithChat?.({source:"custom-instructions"})}),typeof s?.accounts?.subscribe=="function"&&s.accounts.subscribe(()=>{a(),t?.activeElement!==r&&o()})}var tp={overview:{label:"aiFeatureOverviewLabel",hint:"aiFeatureOverviewHint"},chat:{label:"aiFeatureChatLabel",hint:"aiFeatureChatHint"},periodicAsk:{label:"aiFeaturePeriodicAskLabel",hint:"aiFeaturePeriodicAskHint"},calcAssist:{label:"aiFeatureCalcAssistLabel",hint:"aiFeatureCalcAssistHint"},translate:{label:"aiFeatureTranslateLabel",hint:"aiFeatureTranslateHint"},languageTools:{label:"aiFeatureLanguageToolsLabel",hint:"aiFeatureLanguageToolsHint"},urlAsk:{label:"aiFeatureUrlAskLabel",hint:"aiFeatureUrlAskHint"}};function np(e,t){e.checked=t,e.setAttribute("aria-checked",t?"true":"false")}function Wc(e=globalThis){let t=e.document,n=t?.getElementById("settings-ai-features-list");if(!n)return;let r=e.Beamo,s=new Map,o=we(e);if(n.childElementCount===0)for(let i of qt){let c=tp[i],l=t.createElement("div");l.className="settings-field settings-ai-feature",l.setAttribute("role","presentation");let m=t.createElement("label");m.className="settings-switch";let u="settings-ai-feature-".concat(i);m.setAttribute("for",u);let d=t.createElement("span");d.className="settings-switch__text";let h=t.createElement("span");h.className="settings-switch__title",h.setAttribute("data-beamo-i18n","settings.".concat(c.label)),h.textContent=o("settings.".concat(c.label));let p=t.createElement("span");p.className="settings-switch__hint",p.setAttribute("data-beamo-i18n","settings.".concat(c.hint)),p.textContent=o("settings.".concat(c.hint)),d.append(h,p);let b=t.createElement("input");b.type="checkbox",b.id=u,b.className="settings-switch__input";let v=t.createElement("span");v.className="settings-switch__track",v.setAttribute("aria-hidden","true"),m.append(d,b,v),l.append(m),n.append(l),s.set(i,b),b.addEventListener("change",()=>{ac(e,i,b.checked,r),b.setAttribute("aria-checked",b.checked?"true":"false")})}else for(let i of qt){let c=t.getElementById("settings-ai-feature-".concat(i));c&&s.set(i,c)}function a(){let i=kn(e,r);for(let[c,l]of s)np(l,i.features[c]!==!1),l.closest(".settings-ai-feature")?.classList.toggle("settings-ai-feature--muted",!i.enabled)}e.addEventListener?.(nr,a),e.addEventListener?.("beamo:preferences-sync",a),a()}var bo="beamo:always-show-results-change";function Gc(e){let t=oe(e).storageKeys?.alwaysShowResults;return typeof t=="string"&&t?t:"beamo-always-show-results"}function rp(e=globalThis){try{if(e.matchMedia?.("(max-width: 768px)")?.matches)return!0;let t=e.matchMedia?.("(pointer: coarse)")?.matches===!0,n=Number(e.innerWidth)||1024;return t&&n<900}catch{return!1}}function sp(e=globalThis,t=e?.Beamo){let n=String(te(e,Gc(t),"")??"");return n==="on"||n==="off"?n:"auto"}function Kc(e=globalThis,t=e?.Beamo){let n=sp(e,t);return n==="on"?!0:n==="off"?!1:rp(e)}function Vc(e,t,n=e?.Beamo){ie(e,Gc(n),t==="on"||t==="off"?t:"");try{n?.accounts?.schedulePushWithChat?.()}catch{}try{e.dispatchEvent?.(new CustomEvent(bo,{detail:{setting:t}}))}catch{}}function Yc(e=globalThis){let t=e.document?.getElementById("settings-always-show-results");if(!t)return;let n=e.Beamo,r=()=>{let s=Kc(e,n);t.checked=s,t.setAttribute("aria-checked",s?"true":"false")};r(),t.addEventListener("change",()=>{Vc(e,t.checked?"on":"off",n),t.setAttribute("aria-checked",t.checked?"true":"false")}),e.addEventListener?.(bo,r),e.addEventListener?.("beamo:preferences-sync",r)}function op(e=globalThis){let t=e.document?.body;if(!t?.classList)return;let n=kn(e,e.Beamo);t.classList.toggle("beamo-search-only-mode",!n.enabled);for(let r of qt){let s=!n.enabled||n.features[r]===!1;t.classList.toggle("beamo-ai-off-".concat(ap(r)),s)}}function ap(e){return e.replace(/[A-Z]/g,t=>"-".concat(t.toLowerCase()))}function Xc(e=globalThis){let t=()=>op(e);e.document?.body?t():e.document?.addEventListener?.("DOMContentLoaded",t,{once:!0}),e.addEventListener?.(nr,t),e.addEventListener?.("beamo:preferences-sync",t)}function mt(e){return typeof e=="string"?e:""}function ip(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}
4function Jc(e){let t=e??null,n=mt(t?.id).trim(),r=mt(t?.query).trim();return!n||!r?null:{id:n,query:r,type:t?.type==="news"?"news":"web",filters:ip(t?.filters),label:mt(t?.label),enabled:t?.enabled!==!1,cadence:mt(t?.cadence)||"daily",lastCheckedAt:mt(t?.last_checked_at),lastChangeSummary:mt(t?.last_change_summary),lastChangeHeadline:mt(t?.last_change_headline),lastChangedAt:mt(t?.last_changed_at),createdAt:mt(t?.created_at)}}function cp(e,t){return oe(e).endpoints.watches||"/PHP/watches.php"}async function Yr(e,t,n){let s=oe(e).timeouts?.watchesMs??8e3,a={...await Ie(e)},i={method:n.method,headers:a};n.method==="POST"&&(a["Content-Type"]="application/json",i.body=JSON.stringify(n.body??{}));try{let c=await e.fetchWithTimeout(cp(e,t),i,s),l=null;try{l=await c.json()}catch{l=null}return{ok:!!c?.ok,status:c?.status??0,data:l}}catch{return{ok:!1,status:0,data:null}}}async function Qc(e,t){let{status:n,data:r}=await Yr(e,t,{method:"GET"}),o=(Array.isArray(r?.watches)?r.watches:[]).map(Jc).filter(a=>a!==null);return{enabled:r?.enabled!==!1&&n!==403,proRequired:n===403,limit:typeof r?.limit=="number"?r.limit:10,watches:o}}async function Xr(e,t,n,r={}){let{ok:s,status:o,data:a}=await Yr(e,t,{method:"POST",body:{action:"add",query:n,type:r.type||"web",label:r.label||"",filters:r.filters||{}}});return{ok:s,status:o,watch:Jc(a?.watch),duplicate:a?.duplicate===!0,proRequired:o===403,limitReached:o===409}}async function Zc(e,t,n){let{ok:r}=await Yr(e,t,{method:"POST",body:{action:"remove",id:n}});return r}async function el(e,t,n,r){let{ok:s}=await Yr(e,t,{method:"POST",body:{action:"setEnabled",id:n,value:r?"1":"0"}});return s}function tl(e=globalThis){let t=e?.document;if(!t||typeof t.getElementById!="function")return;let n=t.getElementById("settings-group-watches-section"),r=t.getElementById("settings-watches-item"),s=t.getElementById("settings-watches-list"),o=t.getElementById("settings-watches-empty"),a=t.getElementById("settings-watches-add-form"),i=t.getElementById("settings-watches-add-input"),c=t.getElementById("settings-watches-status");if(!n||!r||!s||!a||!i||a.dataset.beamoWatchesBound==="true")return;a.dataset.beamoWatchesBound="true";let l=e.Beamo,m=we(e),u=(A,S,_)=>{let w=m(A,_);return w&&w!==A?w:S},d=!1,h=10;function p(A,S=!1){c&&(c.textContent=A,c.hidden=A==="",c.classList.toggle("settings-watches__status--error",S&&A!==""))}function b(A){s.replaceChildren(),o&&(o.hidden=A.length>0);for(let S of A){let _=t.createElement("li");_.className="settings-watches__row",_.dataset.watchId=S.id;let w=t.createElement("div");w.className="settings-watches__row-main";let f=t.createElement("span");f.className="settings-watches__query",f.textContent=S.query,w.appendChild(f);let C=S.lastChangeHeadline||S.lastChangeSummary||(S.lastCheckedAt?u("settings.watchesNoChangeYet","No changes yet"):"");if(C){let B=t.createElement("span");B.className="settings-watches__meta",B.textContent=C,w.appendChild(B)}_.appendChild(w);let T=t.createElement("div");T.className="settings-watches__row-controls";let x=t.createElement("button");x.type="button",x.className="settings-watches__toggle",x.setAttribute("aria-pressed",S.enabled?"true":"false"),x.dataset.enabled=S.enabled?"true":"false",x.textContent=S.enabled?u("settings.watchesActive","Active"):u("settings.watchesPaused","Paused"),x.addEventListener("click",()=>{let B=x.dataset.enabled!=="true";x.disabled=!0,el(l,l?.config,S.id,B).then(I=>{x.disabled=!1,I?(x.dataset.enabled=B?"true":"false",x.setAttribute("aria-pressed",B?"true":"false"),x.textContent=B?u("settings.watchesActive","Active"):u("settings.watchesPaused","Paused")):p(u("settings.watchesError","Something went wrong. Please try again."),!0)})}),T.appendChild(x);let N=t.createElement("button");N.type="button",N.className="settings-watches__remove",N.setAttribute("aria-label","".concat(u("settings.watchesRemove","Remove"),": ").concat(S.query)),N.textContent=u("settings.watchesRemove","Remove"),N.addEventListener("click",()=>{N.disabled=!0,Zc(l,l?.config,S.id).then(B=>{B?(_.remove(),s.children.length===0&&o&&(o.hidden=!1)):(N.disabled=!1,p(u("settings.watchesError","S
4omething went wrong. Please try again."),!0))})}),T.appendChild(N),_.appendChild(T),s.appendChild(_)}}async function v(){if(!l)return;let A=await Qc(l,l.config);if(A.proRequired||!A.enabled){n.hidden=!0;return}h=A.limit||10,d=!0,b(A.watches)}function E(){let A=Se(l);n.hidden=!A,A&&!d&&v()}a.addEventListener("submit",A=>{A.preventDefault();let S=i.value.trim();if(!S)return;p("");let _=t.getElementById("settings-watches-add-btn");_&&(_.disabled=!0),Xr(l,l?.config,S).then(w=>{if(_&&(_.disabled=!1),w.proRequired){p(u("settings.watchesProRequired","Search watches are a Beamo Search Pro feature."),!0);return}if(w.limitReached){p(u("settings.watchesLimit","You can watch up to ".concat(h," searches."),{limit:h}),!0);return}if(!w.ok&&!w.duplicate){p(u("settings.watchesError","Something went wrong. Please try again."),!0);return}i.value="",w.duplicate?p(u("settings.watchesDuplicate","You\u2019re already watching that search.")):p(u("settings.watchesAdded","Now watching \u201C".concat(S,"\u201D."),{query:S})),v()})}),E(),typeof l?.accounts?.subscribe=="function"&&l.accounts.subscribe(()=>E())}function nl(e=globalThis){let t=e?.document,n=t?.getElementById("watch-search-button");if(!t||!n||n.dataset.beamoWatchBound==="true")return;let r=n;r.dataset.beamoWatchBound="true";let s=e.Beamo,o=we(e),a=(h,p,b)=>{let v=o(h,b);return v&&v!==h?v:p},i=()=>a("toolbar.watch",r.dataset.defaultLabel||"Watch"),c=()=>a("toolbar.watching",r.dataset.watchingLabel||"Watching");function l(){let p=(t.getElementById("search-term")?.value||"").trim();if(p)return p;try{return(new URL(e.location?.href||"").searchParams.get("q")||"").trim()}catch{return""}}function m(){r.disabled=!1,r.dataset.state="",r.textContent=i(),r.removeAttribute("title"),r.setAttribute("aria-label",a("toolbar.watchSearchAria","Watch this search for changes"))}function u(){let h=Se(s);r.hidden=!h,h&&r.dataset.state!=="watching"&&m()}r.addEventListener("click",()=>{let h=l();!h||!s||r.dataset.state==="watching"||(r.disabled=!0,r.textContent="\u2026",Xr(s,s.config,h).then(p=>{if(p.ok||p.duplicate){r.dataset.state="watching",r.textContent=c(),r.title=a("settings.watchesAdded","Now watching \u201C".concat(h,"\u201D."),{query:h}),r.disabled=!0;return}r.disabled=!1,r.textContent=i(),p.limitReached?r.title=a("settings.watchesLimit","You have reached your watch limit.",{limit:10}):p.proRequired?r.title=a("settings.watchesProRequired","Search watches are a Beamo Search Pro feature."):r.title=a("settings.watchesError","Something went wrong. Please try again.")}))}),t.getElementById("search-term")?.addEventListener("input",()=>{r.dataset.state==="watching"&&m()}),u(),typeof s?.accounts?.subscribe=="function"&&s.accounts.subscribe(()=>u())}function rl(e=globalThis){let t=e.document,n=t?.getElementById("url-ask-overlay"),r=t?.getElementById("url-ask-launch");if(!t||!n||n.dataset.beamoUrlAskBound==="true")return;n.dataset.beamoUrlAskBound="true";let s=e.Beamo,o=oe(s),a=o.endpoints?.urlAsk||"/PHP/url_ask.php",i=Number(o.timeouts?.urlAskMs)||45e3,c=t.getElementById("url-ask-form"),l=t.getElementById("url-ask-url"),m=t.getElementById("url-ask-question"),u=t.getElementById("url-ask-submit"),d=t.getElementById("url-ask-status"),h=t.getElementById("url-ask-result"),p=t.getElementById("url-ask-source"),b=t.getElementById("url-ask-answer"),v=Er({id:"url-ask-announcer",parent:h??n}),E=null,A=null,S=null,_=0,w=(y,k="info")=>{d&&(d.textContent=y,d.hidden=y==="",d.dataset.tone=k)},f=y=>{if(!b)return;let k=s?.markdown;k&&typeof k.renderToFragment=="function"?b.replaceChildren(k.renderToFragment(y)):b.textContent=y},g=()=>{if(S&&(clearTimeout(S),S=null),A){try{A.close()}catch{}A=null}},C=y=>{u&&(u.disabled=y,u.setAttribute("aria-busy",y?"true":"false")),n.setAttribute("aria-busy",y?"true":"false")},T=()=>{E=t.activeElement||r,n.hidden=!1,t.body?.classList.add("url-ask-open"),e.setTimeout(()=>l?.focus(),0)},x=()=>{_+=1,g(),n.hidden=!0,t.body?.classList.remove("url-ask-open"),C(!1),E&&typeof E.focus=="function"&&E.focus()},N=()=>{let y=new Set(["a","button","input","textarea","select","[tabindex]"].flatMap(R=>[...n.querySelectorAll(R)])),k=[],P=R=>{for(let D of[...R.children])y.has(D)&&k.push(D),P(D)};return P(n),k.filter(R=>!R.hidden&&!R.closest("[hidden]")&&!R.disabled&&R.getAttribute("tabindex")!=="-1"&&(R.tagName!=="A"||R.hasAttribute("href")))},B=async(y,k)=>{g();let P=++_;C(!0),w("Reading the page\u2026"),h&&(h.hidden=!0),f(""),p&&(p.textContent="",p.removeAttribute("href"));let R="",D=!1,L={};try{L=await Ie(s)}catch{L={}}if(P!==_)return;let $=s?.streamSsePost,G=s?.parseStreamPayload;if(typeof $!="function"||typeof G!="function"){C(!1),w("Beamo could not start the request. Refresh and try again.","error");return}let J=jr(tt(e,s)),X=zr(It(e,s)),W={url:y,question:k,tier:J};
4X&&(W.customInstructions=X);let V=$(a,W,{headers:L});A=V,S=e.setTimeout(()=>{P===_&&(g(),C(!1),R||w("That took too long to respond. Try again.","error"))},i),V.onmessage=j=>{if(P!==_)return;let ee;try{ee=G(j.data)}catch{return}if(ee.sources&&Array.isArray(ee.sources)&&ee.sources.length>0){let Ee=ee.sources[0],Y=String(Ee?.url??""),se=s?.safeHttpUrl?s.safeHttpUrl(Y):Y;se&&p&&(p.href=se,p.textContent=String(Ee?.title||se));return}if(ee.error){D=!0,g(),C(!1),w(ee.content||"Beamo couldn\u2019t read that page. Try a different link.","error");return}ee.content&&(R=ee.replace?ee.content:R+ee.content,h&&(h.hidden=!1),w(""),f(R)),ee.done&&(g(),C(!1),!R&&!D?w("Beamo didn\u2019t return an answer for that page. Try again.","error"):R&&Wn(v,R))},V.onerror=()=>{P===_&&(g(),C(!1),R||w("There was a problem connecting. Please try again.","error"))}};c?.addEventListener("submit",y=>{y.preventDefault();let k=String(l?.value??"").trim(),P=String(m?.value??"").trim();if(!fo("urlAsk",e,s)){w("\u201CAsk about a URL\u201D is turned off in your settings.","error");return}if(!k){w("Paste a link first.","error"),l?.focus();return}let R=/^https?:\/\//i.test(k)?k:"https://".concat(k);if(!(s?.safeHttpUrl?s.safeHttpUrl(R):R)){w("That doesn\u2019t look like a valid web link.","error"),l?.focus();return}B(k,P)}),r?.addEventListener("click",()=>{!Se(s)||!fo("urlAsk",e,s)||T()}),t.getElementById("url-ask-close")?.addEventListener("click",()=>x()),n.querySelectorAll("[data-url-ask-dismiss]").forEach(y=>{y.addEventListener("click",()=>x())}),t.addEventListener("keydown",y=>{if(!n.hidden){if(y.key==="Escape"){x();return}if(y.key==="Tab"){let k=N();if(k.length===0){y.preventDefault();return}let P=k[0],R=k[k.length-1];y.shiftKey&&t.activeElement===P?(y.preventDefault(),R.focus()):!y.shiftKey&&t.activeElement===R?(y.preventDefault(),P.focus()):n.contains(t.activeElement)||(y.preventDefault(),(y.shiftKey?R:P).focus())}}});let I=()=>{r&&(r.hidden=!Se(s)),!Se(s)&&!n.hidden&&x()};I(),typeof s?.accounts?.subscribe=="function"&&s.accounts.subscribe(()=>I())}async function lp(e,t){if(!e.navigator?.serviceWorker)return!1;try{let n=await e.navigator.serviceWorker.ready,r=n.active||n.waiting||n.installing;return r?.postMessage(t),!!r}catch{return!1}}async function up(e){await lp(e,{type:"BEAMO_CLEAR_SEARCH_CACHE"})}function sl(e=globalThis){if(!e.navigator?.serviceWorker)return;e.navigator.serviceWorker.addEventListener("message",n=>{let r=n.data;if(!r||r.type!=="BEAMO_OFFLINE_CACHE_CLEARED")return;let s=e.Beamo;s?.results?.setCachedApiData&&s.results.setCachedApiData({}),s?.results?.hideOfflineResultsNotice?.()});let t=e.Beamo?.accounts;if(t&&typeof t.subscribe=="function"){let n=t.getState?.().signedIn===!0;t.subscribe(r=>{n&&!r.signedIn&&up(e),n=r.signedIn===!0})}}var dp="beamo-search",Ke=Object.freeze({PWA_IFRAME_STATE:"pwa-iframe-state",PWA_IFRAME_ACCOUNT:"pwa-iframe-account",PWA_IFRAME_ACCOUNT_VERIFIED:"pwa-iframe-account-verified",PWA_IFRAME_HOME:"pwa-iframe-home",PWA_IFRAME_NAVIGATE:"pwa-iframe-navigate"}),Rv=Object.freeze(Object.values(Ke)),Pv=Object.freeze({[Ke.PWA_IFRAME_STATE]:{required:["offline"],optional:["cachedResults"],booleans:["offline","cachedResults"]},[Ke.PWA_IFRAME_ACCOUNT]:{required:["enabled","signedIn"],booleans:["enabled","signedIn"]},[Ke.PWA_IFRAME_ACCOUNT_VERIFIED]:{required:[]},[Ke.PWA_IFRAME_HOME]:{required:[]},[Ke.PWA_IFRAME_NAVIGATE]:{required:["url"],strings:["url"],httpUrls:["url"]}});function ol(e){return{source:dp,...e}}function wo(e){let t=e.parent;return!!(t&&t!==e)}function Jr(e,t){let n=e.parent;if(!(!n||n===e))try{n.postMessage(ol(t),"*")}catch{}}function al(e){if(!e.navigator?.serviceWorker)return;let t=()=>{e.navigator.serviceWorker.register("/sw.js",{scope:"/",updateViaCache:"none"}).catch(()=>{})};e.document?.readyState==="complete"?t():e.addEventListener("load",t,{once:!0}),fp(e),sl(e)}function fp(e){let t=e.document;if(!t?.body)return;let n=t.getElementById("beamo-pwa-offline");n||(n=t.createElement("div"),n.id="beamo-pwa-offline",n.className="beamo-pwa-offline",n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.hidden=!0,n.textContent="You're offline. Cached pages on this device may still work. Reconnect for new searches.",t.body.appendChild(n));let r=()=>{let s=e.navigator.onLine===!1;n.hidden=!s;let o=t.getElementById("offline-results-notice"),a=!!(o&&!o.hidden);Jr(e,{type:Ke.PWA_IFRAME_STATE,offline:s,cachedResults:a})};r(),e.addEventListener("online",r),e.addEventListener("offline",r)}function mp(e=globalThis){let t=String(e.navigator?.userAgent??"");return/iPad|iPhone|iPod/.test(t)?!0:(e.navigator?.platform??"")==="MacIntel"&&Number(e.navigator?.maxTouchPoints)>1}function il(e=globalThis){let t=String(e.navigator?.userAgent??"");return/CriOS|FxiOS|EdgiOS|OPiOS/.test(t)}function cl(e=globalThis){return mp(e)&&!So(e)}function So(e=globalThis){return e.matchMedia?.("(display-mode: standalone)")?.matches?!0:e.navigator?.standalone===!0}function ll(e){let t=e.Beamo||(e.Beamo={});t.pwa=t.pwa||{};let n=e.document,r=n?.getElementById("pwa-install-button"),s=n?.getElementById("pwa-install-item"),o=n?.getElementById("pwa-ios-install-button"),a=n?.getElementById("pwa-ios-install-item"),i=n?.getElementById("pwa-ios-install-help");if(!r||!s||So(e))return;let c=null,l=()=>{s.hidden=!0},m=()=>{s.hidden=!1,a&&(a.hidden=!0,ko(o,i,!1))},u=()=>{a&&(a.hidden=!0,ko(o,i,!1))},d=()=>{!a||!o||(a.hidden=!1,i&&(i.innerHTML=hp(e)))};cl(e)&&(t.pwa.installable=!0,d()),e.addEventListener("beforeinstallprompt",h=>{h.preventDefault(),c=h,t.pwa.installable=!0,u(),m()}),e.addEventListener("appinstalled",()=>{c=null,t.pwa.installable=!0,l()}),r.addEventListener("click",async()=>
4{if(c){await c.prompt();try{await c.userChoice}catch{}c=null,l()}}),o?.addEventListener("click",()=>{let h=o.getAttribute("aria-expanded")==="true";ko(o,i,!h)})}function hp(e){return il(e)?'<p class="pwa-ios-install-help__lead">Install Beamo from Safari:</p><ol><li>Open <strong>beamosearch.com</strong> in <strong>Safari</strong>.</li><li>Tap <strong>Share</strong> <span class="pwa-ios-install-help__glyph" aria-hidden="true">\u25A1\u2191</span>.</li><li>Tap <strong>Add to Home Screen</strong>, then <strong>Add</strong>.</li></ol>':'<p class="pwa-ios-install-help__lead">Install Beamo on your home screen:</p><ol><li>Tap <strong>Share</strong> <span class="pwa-ios-install-help__glyph" aria-hidden="true">\u25A1\u2191</span> in Safari\u2019s toolbar.</li><li>Tap <strong>Add to Home Screen</strong>.</li><li>Tap <strong>Add</strong> in the top corner.</li></ol>'}function ko(e,t,n){!e||!t||(e.setAttribute("aria-expanded",n?"true":"false"),t.hidden=!n)}var pp=new Set(["active","on_trial","trialing","past_due","cancelled","paused"]);function ul(e,t=Date.now()){if(!e||typeof e!="object"||String(e.plan||"").toLowerCase()!=="pro")return!1;let n=String(e.status||"").toLowerCase();if(n&&!pp.has(n))return!1;let r=e.current_period_end;if(r!=null&&r!==""){let s=typeof r=="number"?r:Date.parse(String(r));if(Number.isFinite(s)&&s<t)return!1}return!0}function dl(e=globalThis.Beamo){return!!e?.accounts?.getState?.()?.isPro}function fl(e,t){let n=e?.limits||{},r=Number(n.savedSearchesMax)||50,s=Number(n.searchHistoryMax)||12;return t?{savedSearchesMax:Math.max(r,Number(n.savedSearchesProMax)||500),searchHistoryMax:Math.max(s,Number(n.searchHistoryProMax)||100)}:{savedSearchesMax:r,searchHistoryMax:s}}function vo(e,t){let n=e?.Beamo,r=dl(n),s=Number(t?.limits?.savedSearchesMax)||50;if(!r)return s;let o=Number(t?.limits?.savedSearchesProMax)||Number(n?.config?.limits?.savedSearchesProMax)||500;return Math.max(s,o)}function ml(e,t){let n=e?.Beamo,r=dl(n),s=Number(t?.limits?.searchHistoryMax)||12;if(!r)return s;let o=Number(t?.limits?.searchHistoryProMax)||Number(n?.config?.limits?.searchHistoryProMax)||100;return Math.max(s,o)}var gp=100,yp=2160*60*60*1e3;function hl(e){return e?.storageKeys?.savedSearches||"beamo-saved-searches"}function _o(e){return String(e??"").trim().replace(/\s+/g," ")}function Co(e,t){let n=te(e,hl(t),"");if(!n)return[];try{let r=JSON.parse(n);return Array.isArray(r)?r.map(s=>{if(!s||typeof s!="object")return null;let o=_o(s.q);if(!o)return null;let a=String(s.label??"").trim().slice(0,120);return{q:o,label:a,ts:Number(s.ts)||0,...s.deleted===!0?{deleted:!0}:{}}}).filter(Boolean):[]}catch{return[]}}function pl(e,t){return Co(e,t).filter(n=>n.deleted!==!0)}function gl(e,t,n=Date.now()){let r=e.filter(o=>o.deleted!==!0).slice(0,t),s=e.filter(o=>o.deleted===!0&&n-o.ts<yp).slice(0,gp);return[...r,...s]}function yl(e,t,n){ie(e,hl(t),JSON.stringify(n))}function bl(e,t){return pl(e,t)}function wl(e,t){return Co(e,t)}function Sl(e,t,n){let r=_o(n);if(!r)return pl(e,t);let s=Date.now(),o=Co(e,t).filter(i=>i.q.toLowerCase()!==r.toLowerCase());o.unshift({q:r,label:"",ts:s,deleted:!0});let a=gl(o,vo(e,t),s);return yl(e,t,a),a.filter(i=>i.deleted!==!0)}function Qr(e,t,n){let r=vo(e,t),s=(Array.isArray(n)?n:[]).map(a=>{let i=_o(a?.q);return i?{q:i,label:String(a?.label??"").trim().slice(0,120),ts:Number(a?.ts)||0,...a?.deleted===!0?{deleted:!0}:{}}:null}).filter(Boolean),o=gl(s,r);return yl(e,t,o),o.filter(a=>a.deleted!==!0)}var bp=12,wp=100,Sp=2160*60*60*1e3;function kl(e){return e?.storageKeys?.searchHistory||"beamo-search-history"}function kp(e){return e?.storageKeys?.syncRecentHistory||"beamo-accounts-sync-recent-history"}function Ao(e){return String(e??"").trim().replace(/\s+/g," ")}function vp(e,t){let n=te(e,kl(t),"");if(!n)return[];try{let r=JSON.parse(n);return Array.isArray(r)?r.map(s=>{if(typeof s=="string"){let a=Ao(s);return a?{q:a,ts:0}:null}if(!s||typeof s!="object")return null;let o=Ao(s.q);return o?{q:o,ts:Number(s.ts)||0,...s.deleted===!0?{deleted:!0}:{}}:null}).filter(Boolean):[]}catch{return[]}}function _p(e,t,n=Date.now()){let r=e.filter(o=>o.deleted!==!0).slice(0,t),s=e.filter(o=>o.deleted===!0&&n-o.ts<Sp).slice(0,wp);return[...r,...s]}
4function Cp(e,t,n){ie(e,kl(t),JSON.stringify(n))}function vl(e,t){return te(e,kp(t),"1")!=="0"}function _l(e,t){return vp(e,t)}function Zr(e,t,n){let r=ml(e,t)||bp,s=[];for(let o of n||[]){let a=Ao(o?.q);a&&s.push({q:a,ts:Number(o?.ts)||0,...o?.deleted===!0?{deleted:!0}:{}})}Cp(e,t,_p(s,r))}var Ap="beamo:preferences-sync";function Cl(e){let t=e.Beamo||(e.Beamo={});return t.__preferenceSyncListeners||(t.__preferenceSyncListeners=new Set),t.__preferenceSyncListeners}function Al(e,t){if(!t||typeof t!="object")return;let n={detail:{preferences:t}};for(let r of Cl(e))try{r(n)}catch{}try{e.dispatchEvent?.(new CustomEvent(Ap,n))}catch{}}function El(e,t){if(typeof t!="function")return()=>{};let n=Cl(e);return n.add(t),()=>{n.delete(t)}}function ht(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function fe(e,t){return String(e??"").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g,"").replace(/\s+/g," ").trim().slice(0,t)}function Ep(e){let t=fe(e,500);return/^https?:\/\//i.test(t)?t:""}function Tp(e){try{return JSON.stringify(e).length}catch{return 1/0}}function xp(e){let t={...e},n=["faq","resultDigest","spellcheck","place","query","infobox","instant"];for(;Object.keys(t).length>0;){if(Tp(t)<=5e3)return t;let r=n.find(s=>Object.prototype.hasOwnProperty.call(t,s));if(!r)break;delete t[r]}return null}function es(e){if(!ht(e))return null;let t={};if(ht(e.query)){let n={},r=fe(e.query.text,240),s=fe(e.query.questionType,40),o=fe(e.query.freshness,40);if(r&&(n.text=r),s&&(n.questionType=s),o&&(n.freshness=o),Array.isArray(e.query.signals)){let a=e.query.signals.map(i=>fe(i,40)).filter(Boolean).slice(0,5);a.length>
40&&(n.signals=[...new Set(a)])}if(Array.isArray(e.query.temporalTerms)){let a=e.query.temporalTerms.map(i=>fe(i,40)).filter(Boolean).slice(0,5);a.length>0&&(n.temporalTerms=[...new Set(a)])}Object.keys(n).length>0&&(t.query=n)}if(ht(e.infobox)){let n={},r=fe(e.infobox.title,200),s=fe(e.infobox.subtitle,200),o=fe(e.infobox.description,600),a=Ep(e.infobox.url);if(r&&(n.title=r),s&&(n.subtitle=s),o&&(n.description=o),a&&(n.url=a),Array.isArray(e.infobox.attributes)){let i=e.infobox.attributes.filter(ht).slice(0,6).map(c=>({label:fe(c.label,60),value:fe(c.value,200)})).filter(c=>c.label&&c.value);i.length>0&&(n.attributes=i)}(n.title||n.description)&&(t.infobox=n)}if(ht(e.spellcheck)){let n=fe(e.spellcheck.original,200),r=fe(e.spellcheck.altered,200);n&&r&&n!==r&&(t.spellcheck={original:n,altered:r})}if(ht(e.instant)){let n=fe(e.instant.summary,400);if(n){let r=fe(e.instant.type,40),s=r?{type:r,summary:n}:{summary:n},o={place:120,targetLabel:40,targetWeekday:40,timezone:80,localWeekday:40,tomorrowWeekday:40};for(let[a,i]of Object.entries(o)){let c=fe(e.instant[a],i);c&&(s[a]=c)}for(let a of["targetDate","localDate","tomorrowDate"]){let i=fe(e.instant[a],40);/^\d{4}-\d{2}-\d{2}$/.test(i)&&(s[a]=i)}t.instant=s}}if(Array.isArray(e.faq)){let n=e.faq.filter(ht).slice(0,4).map(r=>({question:fe(r.question,200),answer:fe(r.answer,500)})).filter(r=>r.question&&r.answer);n.length>0&&(t.faq=n)}if(ht(e.place)){let n={},r={city:120,region:120,country:120,localTime:120,timezone:80,localDate:120,localWeekday:120,tomorrowDate:120,tomorrowWeekday:120};for(let[s,o]of Object.entries(r)){let a=fe(e.place[s],o);a&&(n[s]=a)}Object.keys(n).length>0&&(t.place=n)}if(Array.isArray(e.resultDigest)){let n=e.resultDigest.filter(ht).slice(0,3).map(r=>({title:fe(r.title,160),source:fe(r.source,100),age:fe(r.age,40),snippet:fe(r.snippet,260)})).filter(r=>r.title||r.snippet);n.length>0&&(t.resultDigest=n)}return Object.keys(t).length===0?null:xp(t)}var Eo="beamo-chat-threads",Tl="beamo-chat-active-thread",xl="beamo:chat-threads-sync",_n=60,Rp=80,Pp=100,Ip=2e4,Np=8,Lp=new Set(["sports","stocks","macro","weather","aqi","currency","unit-convert","local","translation","definition","thesaurus","astronomy","sun","timezone","illness","officialdata","tracking","flight","airportops","ip","languagetools"]),Mp=12e3,Bp=8,Op=24e3,Dp=72e3;function Hp(e){if(!e||typeof e!="object")return null;let t=String(e.query??"").trim().slice(0,120);if(!t)return null;let n=e.kind;return{query:t,kind:n==="sports"||n==="finance"||n==="macro"||n==="weather"||n==="aqi"||n==="currency"||n==="convert"||n==="local"?n:"web"}}function $p(e){if(!e||typeof e!="object")return null;let t=String(e.kind??""),n=e.data;if(!Lp.has(t)||!n||typeof n!="object")return null;let r="";try{r=JSON.stringify(n)}catch{return null}return!r||r.length>Mp?null:{kind:t,data:n}}function Fp(e){if(!e||typeof e!="object"||!Array.isArray(e.parts))return null;let t=[],n=0;for(let r of e.parts){if(t.length>=Bp||!r||typeof r!="object")continue;let s=String(r.html??"").trim();!s||s.length>Op||n+s.length>Dp||(n+=s.length,t.push({sourceId:String(r.sourceId??"instant").trim().replace(/[^\w:.-]+/g,"-").slice(0,96)||"instant",html:s}))}return t.length>0?{parts:t}:null}function qp(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(t.length>=Pp)break;let r=n?.role,s=n?.content;if(r!=="user"&&r!=="assistant"||typeof s!="string"||!s.trim())continue;let o={role:r,content:s.slice(0,Ip)},a=n.turnId;typeof a=="string"&&a&&(o.turnId=a);let i=n.sources;if(r==="assistant"&&Array.isArray(i)&&i.length>0&&(o.sources=i.slice(0,Np).filter(c=>c&&typeof c=="object").map(c=>({title:String(c.title??"").slice(0,200),url:String(c.url??"").slice(0,600),description:String(c.description??"").slice(0,200)})).filter(c=>/^https?:\/\//i.test(c.url))),r==="assistant"){let c=Hp(n.searchActivity);c&&(o.searchActivity=c);let l=$p(n.card);l&&(o.card=l);let m=Fp(n.instantSnapshot);m&&(o.instantSnapshot=m);let u=es(n.searchContext);u&&(o.searchContext=u)}t.push(o)}return t}function Rl(e){if(!e||typeof e!="object")return null;let t=e,n=typeof t.id=="string"?t.id.trim():"";if(!n)return null;let r=Number(t.createdAt)>0?Number(t.createdAt):0,s=Number(t.updatedAt)>0?Number(t.updatedAt):0;if(t.deleted===!0)return{id:n,title:"",origin:"",messages:[],createdAt:r,updatedAt:s,archived:!1,deleted:!0}
4;let o=qp(t.messages);return o.length===0?null:{id:n,title:(typeof t.title=="string"?t.title.trim():"").slice(0,120),origin:t.origin==="search"||t.origin==="chat"?t.origin:"",messages:o,createdAt:r,updatedAt:s,archived:!!t.archived}}function Pl(e=globalThis){let t=te(e,Eo,"");if(!t)return[];try{let n=JSON.parse(t);return Array.isArray(n)?n.map(Rl).filter(r=>r!==null):[]}catch{return[]}}function Up(e,t){let n=To(t),r=0;for(;r<3;){if(ie(e,Eo,JSON.stringify(n)))return!0;if(n.length<=1)return!1;n=Cn(n).slice(0,Math.ceil(n.length/2)),r+=1}return!1}function Cn(e){return[...e].sort((t,n)=>(n.updatedAt||0)-(t.updatedAt||0))}function jp(e){if(e.length<=_n)return e;let t=Cn(e),n=t.slice(0,_n),r=t.slice(_n).filter(o=>o.archived),s=[...n,...r];if(s.length>_n){let o=s.filter(i=>i.archived),a=s.filter(i=>!i.archived);s=Cn([...a,...Cn(o).slice(0,Math.max(0,_n-a.length))]).slice(0,_n)}return s}function To(e){let t=jp(e.filter(r=>!r.deleted)),n=Cn(e.filter(r=>r.deleted)).slice(0,Rp);return[...t,...n]}function zp(e=globalThis){return te(e,Tl,"")||""}function Il(e=globalThis){try{e.localStorage?.removeItem(Tl)}catch{}}var Wp=40,Gp=7e5;function Nl(e=globalThis){let t=To(Pl(e)),n=Cn(t.filter(a=>!a.deleted)),r=t.filter(a=>a.deleted),s=[],o=0;for(let a of n){if(s.length>=Wp)break;let i=JSON.stringify(a).length;if(s.length>0&&o+i>Gp)break;s.push(a),o+=i}return[...s,...r]}function ts(e,t){let n=new Map,r=Array.isArray(e)?e:[],s=Array.isArray(t)?t:[];for(let o of[...s,...r]){let a=Rl(o);if(!a)continue;let i=n.get(a.id);(!i||(a.updatedAt||0)>=(i.updatedAt||0))&&n.set(a.id,a)}return To([...n.values()])}function Ll(e=globalThis){Il(e),ie(e,Eo,"[]")}function Ml(e,t){let n=ts(Pl(e),t),r=zp(e);return r&&n.some(s=>s.id===r&&s.deleted)&&Il(e),Up(e,n)}var Fl=2,Kp=/^[a-zA-Z0-9][a-zA-Z0-9_-]{7,63}$/,Vp=8,Yp=12e3,Xp=new Set(["sports","stocks","macro","weather","aqi","currency","unit-convert","local","translation","definition","thesaurus","astronomy","sun","timezone","illness","officialdata","tracking","flight","airportops","ip","languagetools"]),Jp=new Set(["sports","finance","macro","weather","aqi","currency","convert","local"]),Qp=new Set(["web","images","news","videos","maps"]),Zp=new Map([["image","images"]]);function Po(e){return typeof e=="string"&&Kp.test(e)}function ql(e){let t=String(e?.role??""),n=String(e?.turnId??"").trim();return n&&Po(n)?"".concat(t,":turn:").concat(n):"".concat(t,":").concat(e?.content??"")}function ns(e,t){return typeof e=="string"?e.trim().slice(0,t):""}function rs(e){return e!==null&&typeof e=="object"}function eg(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(t.length>=Vp)break;if(!rs(n))continue;let r=ns(n.url,600);/^https?:\/\//i.test(r)&&t.push({title:ns(n.title,200),url:r,description:ns(n.description,200)})}return t}function tg(e){if(!rs(e))return null;let t=ns(e.query,120);if(!t)return null;let n=typeof e.kind=="string"&&Jp.has(e.kind)?e.kind:"web";return{query:t,kind:n}}function ng(e){return rs(e)?Array.isArray(e)?e.length>0:Object.keys(e).length>0:!1}function rg(e){if(!rs(e))return null;let t=typeof e.kind=="string"?e.kind:"",n=e.data;if(!Xp.has(t)||!ng(n))return null;try{let r=JSON.stringify(n);if(!r||r.length>Yp)return null}catch{return null}return{kind:t,data:n}}function Ul(e){return e?.storageKeys?.lastSearchType||"lastSearchType"}function Ro(e,t="web"){let n=String(e??"").trim().toLowerCase(),r=Zp.get(n)||n;return Qp.has(r)?r:t}function sg(e,t){let n=Ul(t),r=Ro(Je(e,n,""),"");return r||Ro(te(e,n,"web"),"web")}function og(e,t,n){let r=Ro(n,"");if(!r)return;let s=Ul(t);ie(e,s,r),Qe(e,s,r)}function xo(e){let t=Math.max(0,Number(e?.revision)||0),n=Array.isArray(e?.messages)?e.messages.filter(r=>
4r&&(r.role==="user"||r.role==="assistant")&&typeof r.content=="string").map(r=>{let s={role:r.role,content:r.content},o=String(r.turnId??"").trim();if(o&&Po(o)&&(s.turnId=o),s.role==="assistant"){let a=eg(r.sources);a.length>0&&(s.sources=a);let i=tg(r.searchActivity);i&&(s.searchActivity=i);let c=rg(r.card);c&&(s.card=c);let l=es(r.searchContext);l&&(s.searchContext=l)}return s}):[];return{revision:t,messages:n}}function ag(e,t){if(e.role!=="assistant"||t.role!=="assistant"||e.content!==t.content)return e;let n={...e};for(let r of["turnId","sources","searchActivity","card","searchContext"])Object.prototype.hasOwnProperty.call(t,r)&&(n[r]=t[r]);return n}function Bl(e){let t=new Map;return e.forEach((n,r)=>{t.set(ql(n),r)}),t}function ig(e,t){let n=String(t.turnId??"").trim();if(!n||!Po(n))return e.length;if(t.role==="assistant"){let r=e.findIndex(s=>s.role==="user"&&s.turnId===n);if(r>=0)return r+1}if(t.role==="user"){let r=e.findIndex(s=>s.role==="assistant"&&s.turnId===n);if(r>=0)return r}return e.length}function Ol(e,t){let n=xo(e),r=xo(t);if(n.messages.length===0)return r;if(r.messages.length===0)return n;let s=n.revision,o=r.revision,a=o>=s?r:n,i=o>=s?n:r,c=[...a.messages],l=Bl(c);for(let m of i.messages){let u=ql(m),d=l.get(u);if(d!==void 0){c[d]=ag(c[d],m);continue}let h=ig(c,m);c.splice(h,0,m),l=Bl(c)}return xo({revision:Math.max(s,o),messages:c})}function cg(e,t,n){let r=lt(e||{}),s=lt(t||{});return n?lt({...r,...s}):lt({...s,...r})}function Dl(e,t){try{let n=te(e,t,"");return n?JSON.parse(n):null}catch{return null}}function jl(e){if(!e||typeof e!="object")return null;let t=e;if(t.agreed!==!0||!(Number(t.version)>0))return null;let n=String(t.region??"general");return{version:Number(t.version)||0,agreed:!0,region:n==="gdpr"||n==="ccpa"?n:"general",method:typeof t.method=="string"?t.method:void 0,agreedAt:Number(t.agreedAt)||0}}function Io(e,t){let n=Qn.includes(te(e,bn,"system"))?te(e,bn,"system"):"system",r={};try{let E=te(e,t?.storageKeys?.searchFilters||"beamo-search-filters","");r=E?lt(JSON.parse(E)):lt({})}catch{r=lt({})}let s=sg(e,t),o=vl(e,t),a=Wr(e,t),i=String(te(e,qr(t),"")??""),c=yn.includes(i)?i:"",l=t?.storageKeys?.chatAutoSendSearch||"beamoChatAutoSendSearch",m=t?.storageKeys?.chatCiteOnly||"beamo-chat-cite-only",u=["1","true"].includes(String(te(e,l,"")??"")),d=["1","true"].includes(String(te(e,m,"")??"")),h=jl(Dl(e,t?.storageKeys?.legalConsent||"beamo-legal-consent")),p=Dl(e,t?.storageKeys?.aiFeatures||"beamo-ai-features"),b=String(te(e,t?.storageKeys?.alwaysShowResults||"beamo-always-show-results","")??""),v=["on","off"].includes(b)?b:"";return{version:Fl,revision:0,updated_at:0,saved_searches:wl(e,t),recent_searches:o?_l(e,t):[],site_prefs:Ia(e,t),chat_threads:Nl(e),preferences:{theme:n,searchFilters:r,lastSearchType:s,aiPreset:tt(e,{config:t}),deepProvider:Sn(e,{config:t}),deepOverview:Uc(e,{config:t}),customInstructions:It(e,{config:t}),syncRecentHistory:o,weatherUnits:a,uiLocale:c,chatAutoSendSearch:u,chatCiteOnly:d,aiFeatures:p,alwaysShowResults:v,legalConsent:h},chat:{revision:0,messages:[]}}}function Hl(e,t,n=50){let r=new Map;for(let o of[...t||[],...e||[]]){let a=String(o?.q??"").trim();if(!a)continue;let i=a.toLowerCase(),c=r.get(i),l={q:a,label:String(o?.label??"").trim(),ts:Number(o?.ts)||0,...o?.deleted===!0?{deleted:!0}:{}};(!c||l.ts>=c.ts)&&r.set(i,l)}let s=[...r.values()].sort((o,a)=>a.ts-o.ts||o.q.localeCompare(a.q));return[...s.filter(o=>o.deleted!==!0).slice(0,n),...s.filter(o=>o.deleted===!0).slice(0,100)]}function $l(e,t,n=12){let r=new Map;for(let o of[...t||[],...e||[]]){let a=String(o?.q??"").trim();if(!a)continue;let i=a.toLowerCase(),c=r.get(i),l={q:a,ts:Number(o?.ts)||0,...o?.deleted===!0?{deleted:!0}:{}};(!c||l.ts>=c.ts)&&r.set(i,l)}let s=[...r.values()].sort((o,a)=>a.ts-o.ts||o.q.localeCompare(a.q));return[...s.filter(o=>o.deleted!==!0).slice(0,n),...s.filter(o=>o.deleted===!0).slice(0,100)]}function zl(e,t,n,{beamo:r}={}){if(!n||typeof n!="object")return;if(Array.isArray(n.saved_searches)&&Qr(e,t,n.saved_searches),Array.isArray(n.site_prefs)&&kr(e,t,n.site_prefs),Array.isArray(n.chat_threads)){Ml(e,n.chat_threads);try{e.dispatchEvent?.(new CustomEvent(xl))}catch{}}let s=n.preferences,o=s?.syncRecentHistory!==!1;if(Array.isArray(n.recent_searches)&&o&&Zr(e,t,n.recent_searches),s&&typeof s=="object"){let a=String(s.theme??"");if(Qn.includes(a)&&r?.theme?.setPreference)r.theme.setPreference(a,{persist:!0});else if(Qn.includes(a))try{e.localStorage?.setItem(bn,a)}catch{}if(s.searchFilters&&typeof s.searchFilters=="object")try{e.localStorage?.setItem(t?.storageKeys?.searchFilters||"beamo-search-filters",JSON.stringify(lt(s.searchFilters)))}catch{}og(e,t,s.lastSearchType);let i=String(s.aiPreset??"");if(i==="fast"||i==="medium"||i==="deep"||i==="premium")try{e.localStorage?.setItem(t?.storageKeys?.aiPreset||"beamo-ai-preset",i)}catch{}let c=String(s.deepProvider??"").toLowerCase();if(c==="openai"||c==="anthropic")try{e.localStorage?.setItem(t?.storageKeys?.deepReasoningProvider||"beamo-deep-reasoning-provider",c)}catch{}let l=s.deepOverview;if(l==="on"||l===!0||l==="1")try{e.localStorage?.setItem(t?.storageKeys?.deepOverview||"beamo-deep-overview","on")}catch{}else if(l==="off")try{e.localStorage?.setItem(t?.storageKeys?.deepOverview||"beamo-deep-overview","off")}catch{}
4if(typeof s.customInstructions=="string")try{e.localStorage?.setItem(t?.storageKeys?.customInstructions||"beamo-custom-instructions",tr(s.customInstructions))}catch{}let m=String(s.weatherUnits??"");(m==="auto"||m==="fahrenheit"||m==="celsius")&&Gr(e,t,m);let u=String(s.uiLocale??"");if(yn.includes(u)&&gn(e,t,u),typeof s.chatAutoSendSearch=="boolean")try{e.localStorage?.setItem(t?.storageKeys?.chatAutoSendSearch||"beamoChatAutoSendSearch",s.chatAutoSendSearch?"1":"0")}catch{}if(typeof s.chatCiteOnly=="boolean")try{e.localStorage?.setItem(t?.storageKeys?.chatCiteOnly||"beamo-chat-cite-only",s.chatCiteOnly?"1":"0")}catch{}if(s.aiFeatures&&typeof s.aiFeatures=="object")try{e.localStorage?.setItem(t?.storageKeys?.aiFeatures||"beamo-ai-features",JSON.stringify(s.aiFeatures))}catch{}if(s.alwaysShowResults==="on"||s.alwaysShowResults==="off")try{e.localStorage?.setItem(t?.storageKeys?.alwaysShowResults||"beamo-always-show-results",s.alwaysShowResults)}catch{}let d=jl(s.legalConsent);if(d)try{e.localStorage?.setItem(t?.storageKeys?.legalConsent||"beamo-legal-consent",JSON.stringify(d))}catch{}try{e.localStorage?.setItem(t?.storageKeys?.syncRecentHistory||"beamo-accounts-sync-recent-history",o?"1":"0")}catch{}Al(e,s)}}function ss(e,t,n=50,r=12,{preferLocalPreferences:s=!1,preferLocalData:o=!1,preferLocalChat:a=!1}={}){let i=e&&typeof e=="object"?e:{},c=t&&typeof t=="object"?t:{},l=Number(i.revision)||0,m=Number(c.revision)||0,u=!s&&m>=l,d=u?{...i.preferences||{},...c.preferences||{}}:{...c.preferences||{},...i.preferences||{}};d.searchFilters=cg(i.preferences?.searchFilters,c.preferences?.searchFilters,u);let h=d.syncRecentHistory!==!1,p=o||a?Ol(i.chat,null):Ol(i.chat,c.chat);return{version:Fl,revision:Math.max(l,m),updated_at:Math.max(Number(i.updated_at)||0,Number(c.updated_at)||0),saved_searches:o?Hl(i.saved_searches,[],n):Hl(i.saved_searches,c.saved_searches,n),recent_searches:h?o?$l(i.recent_searches,[],r):$l(i.recent_searches,c.recent_searches,r):[],site_prefs:Ls(Array.isArray(i.site_prefs)?i.site_prefs:[],Array.isArray(c.site_prefs)?c.site_prefs:[]),chat_threads:o?ts(i.chat_threads,[]):ts(i.chat_threads,c.chat_threads),preferences:d,chat:p||{revision:0,messages:[]}}}var Lo=["google","apple"],lg={google:"google",apple:"apple"};function os(e,t){let n=typeof e?.querySelector=="function"?e.querySelector('meta[name="'.concat(t,'"]')):null;return!n||typeof n.getAttribute!="function"?"":String(n.getAttribute("content")||"").trim()}function No(e){let t=String(e||"").split(",").map(n=>lg[n.trim().toLowerCase()]).filter(n=>Lo.includes(n));return[...new Set(t)]}function as(e){return String(e||"").replace(/\/+$/,"")}function ug(e){if(!e||typeof e!="object")return null;let t=as(e.url),n=String(e.anonKey||"").trim();if(!t||!n)return null;let r=Array.isArray(e.providers)?No(e.providers.join(",")):No("google,apple");return{url:t,anonKey:n,providers:r.length>0?r:[...Lo],functionsUrl:as(e.functionsUrl)||"".concat(t,"/functions/v1")}}function An(e=globalThis){let t=ug(e?.Beamo?.supabase);if(t)return t;let n=e?.document,r=as(os(n,"beamo-supabase-url")),s=os(n,"beamo-supabase-anon-key");if(!r||!s)return null;let o=No(os(n,"beamo-supabase-providers")||"google,apple"),a=as(os(n,"beamo-supabase-functions-url"))||"".concat(r,"/functions/v1");return{url:r,anonKey:s,providers:o.length>0?o:[...Lo],functionsUrl:a}}function Ut(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}var is="2.105.0";var jt=30*1e3,cs=3,ls=cs*jt,Wl="http://localhost:9999",Gl="supabase.auth.token";var Kl={"X-Client-Info":"gotrue-js/".concat(is)};var sr="X-Supabase-Api-Version",Mo={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Vl=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Yl=600*1e3;var Nt=class extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};function U(e){return typeof e=="object"&&e!==null&&"__isAuthError"in e}var us=class extends Nt{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}};function Xl(e){return U(e)&&e.name==="AuthApiError"}var Pe=class extends Nt{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}},Ve=class extends Nt{constructor(t,n,r,s){super(t,r,s),this.name=n,this.status=r}},pe=class extends Ve{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}};function ir(e){return U(e)&&e.name==="AuthSessionMissingError"}var pt=class extends Ve{constructor(){super("Auth session or user missing","AuthInvalidToken
4ResponseError",500,void 0)}},zt=class extends Ve{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}},Wt=class extends Ve{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function Jl(e){return U(e)&&e.name==="AuthImplicitGrantRedirectError"}var or=class extends Ve{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},ds=class extends Ve{constructor(){super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.","AuthPKCECodeVerifierMissingError",400,"pkce_code_verifier_not_found")}};var En=class extends Ve{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}};function fs(e){return U(e)&&e.name==="AuthRetryableFetchError"}var ar=class extends Ve{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};var Gt=class extends Ve{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}};var ms="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),Ql=" \n\r=".split(""),dg=(()=>{let e=new Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<Ql.length;t+=1)e[Ql[t].charCodeAt(0)]=-2;for(let t=0;t<ms.length;t+=1)e[ms[t].charCodeAt(0)]=t;return e})();function Zl(e,t,n){if(e!==null)for(t.queue=t.queue<<8|e,t.queuedBits+=8;t.queuedBits>=6;){let r=t.queue>>t.queuedBits-6&63;n(ms[r]),t.queuedBits-=6}else if(t.queuedBits>0)for(t.queue=t.queue<<6-t.queuedBits,t.queuedBits=6;t.queuedBits>=6;){let r=t.queue>>t.queuedBits-6&63;n(ms[r]),t.queuedBits-=6}}function eu(e,t,n){let r=dg[e];if(r>-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error('Invalid Base64-URL character "'.concat(String.fromCharCode(e),'"'))}}function Bo(e){let t=[],n=a=>{t.push(String.fromCodePoint(a))},r={utf8seq:0,codepoint:0},s={queue:0,queuedBits:0},o=a=>{hg(a,r,n)};for(let a=0;a<e.length;a+=1)eu(e.charCodeAt(a),s,o);return t.join("")}function fg(e,t){if(e<=127){t(e);return}else if(e<=2047){t(192|e>>6),t(128|e&63);return}else if(e<=65535){t(224|e>>12),t(128|e>>6&63),t(128|e&63);return}else if(e<=1114111){t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);return}throw new Error("Unrecognized Unicode codepoint: ".concat(e.toString(16)))}function mg(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){let s=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|s)+65536,n+=1}fg(r,t)}}function hg(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let r=1;r<6;r+=1)if((e>>7-r&1)===0){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(e<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|e&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function Lt(e){let t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};for(let s=0;s<e.length;s+=1)eu(e.charCodeAt(s),n,r);return new Uint8Array(t)}function tu(e){let t=[];return mg(e,n=>t.push(n)),new Uint8Array(t)}function gt(e){let t=[],n={queue:0,queuedBits:0},r=s=>{t.push(s)};return e.forEach(s=>Zl(s,n,r)),Zl(null,n,r),t.join("")}function nu(e){return Math.round(Date.now()/1e3)+e}function ru(){return Symbol("auth-callback")}var ke=()=>typeof globalThis<"u"&&typeof document<"u",Kt={tested:!1,writable:!1},hs=()=>{if(!ke())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Kt.tested)return Kt.writable;let e="lswt-".concat(Math.random()).concat(Math.random());try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),Kt.tested=!0,Kt.writable=!0}catch{Kt.tested=!0,Kt.writable=!1}return Kt.writable};function su(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEac
4h((s,o)=>{t[o]=s})}catch{}return n.searchParams.forEach((r,s)=>{t[s]=r}),t}var ps=e=>e?(...t)=>e(...t):(...t)=>fetch(...t),ou=e=>typeof e=="object"&&e!==null&&"status"in e&&"ok"in e&&"json"in e&&typeof e.json=="function",Vt=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},Mt=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},_e=async(e,t)=>{await e.removeItem(t)},cr=class e{constructor(){this.promise=new e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}};cr.promiseConstructor=Promise;function lr(e){let t=e.split(".");if(t.length!==3)throw new Gt("Invalid JWT structure");for(let r=0;r<t.length;r++)if(!Vl.test(t[r]))throw new Gt("JWT not in base64url format");return{header:JSON.parse(Bo(t[0])),payload:JSON.parse(Bo(t[1])),signature:Lt(t[2]),raw:{header:t[0],payload:t[1]}}}async function au(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function iu(e,t){return new Promise((r,s)=>{(async()=>{for(let o=0;o<1/0;o++)try{let a=await e(o);if(!t(o,null,a)){r(a);return}}catch(a){if(!t(o,a)){s(a);return}}})()})}function pg(e){return("0"+e.toString(16)).substr(-2)}function gg(){let t=new Uint32Array(56);if(typeof crypto>"u"){let n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length,s="";for(let o=0;o<56;o++)s+=n.charAt(Math.floor(Math.random()*r));return s}return crypto.getRandomValues(t),Array.from(t,pg).join("")}async function yg(e){let n=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",n),s=new Uint8Array(r);return Array.from(s).map(o=>String.fromCharCode(o)).join("")}async function bg(e){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e;let n=await yg(e);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function Yt(e,t,n=!1){let r=gg(),s=r;n&&(s+="/recovery"),await Vt(e,"".concat(t,"-code-verifier"),s);let o=await bg(r);return[o,r===o?"plain":"s256"]}var wg=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function cu(e){let t=e.headers.get(sr);if(!t||!t.match(wg))return null;try{return new Date("".concat(t,"T00:00:00.0Z"))}catch{return null}}function lu(e){if(!e)throw new Error("Missing exp claim");let t=Math.floor(Date.now()/1e3);if(e<=t)throw new Error("JWT has expired")}function uu(e){switch(e){case"RS256":return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case"ES256":return{name:"ECDSA",namedCurve:"P-256",hash:{name:"SHA-256"}};default:throw new Error("Invalid alg claim")}}var Sg=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function nt(e){if(!Sg.test(e))throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not")}function He(e){if(!e.passkey)throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor).")}function gs(){let e={};return new Proxy(e,{get:(t,n)=>{if(n==="__isUserNotAvailableProxy")return!0;if(typeof n=="symbol"){let r=n.toString();if(r==="Symbol(Symbol.toPrimitive)"||r==="Symbol(Symbol.toStringTag)"||r==="Symbol(util.inspect.custom)")return}throw new Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "'.concat(n,'" property of the session object is not supported. Please use getUser() instead.'))},set:(t,n)=>{throw new Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "'.concat(n,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))},deleteProperty:(t,n)=>{throw new Error('@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "'.concat(n,'" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.'))}})}function du(e,t){return new Proxy(e,{get:(n,r,s)=>{if(r==="__isInsecureUserWarningProxy")return!0;
4if(typeof r=="symbol"){let o=r.toString();if(o==="Symbol(Symbol.toPrimitive)"||o==="Symbol(Symbol.toStringTag)"||o==="Symbol(util.inspect.custom)"||o==="Symbol(nodejs.util.inspect.custom)")return Reflect.get(n,r,s)}return!t.value&&typeof r=="string"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),t.value=!0),Reflect.get(n,r,s)}})}function Oo(e){return JSON.parse(JSON.stringify(e))}var Xt=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),kg=[502,503,504,520,521,522,523,524,530];async function fu(e){var t;if(!ou(e))throw new En(Xt(e),0);if(kg.includes(e.status))throw new En(Xt(e),e.status);let n;try{n=await e.json()}catch(o){throw new Pe(Xt(o),o)}let r,s=cu(e);if(s&&s.getTime()>=Mo["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new ar(Xt(n),e.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new pe}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((o,a)=>o&&typeof a=="string",!0))throw new ar(Xt(n),e.status,n.weak_password.reasons);throw new us(Xt(n),e.status||500,r)}var vg=(e,t,n,r)=>{let s={method:e,headers:t?.headers||{}};return e==="GET"?s:(s.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t?.headers),s.body=JSON.stringify(r),Object.assign(Object.assign({},s),n))};async function K(e,t,n,r){var s;let o=Object.assign({},r?.headers);o[sr]||(o[sr]=Mo["2024-01-01"].name),r?.jwt&&(o.Authorization="Bearer ".concat(r.jwt));let a=(s=r?.query)!==null&&s!==void 0?s:{};r?.redirectTo&&(a.redirect_to=r.redirectTo);let i=Object.keys(a).length?"?"+new URLSearchParams(a).toString():"",c=await _g(e,t,n+i,{headers:o,noResolveJson:r?.noResolveJson},{},r?.body);return r?.xform?r?.xform(c):{data:Object.assign({},c),error:null}}async function _g(e,t,n,r,s,o){let a=vg(t,r,s,o),i;try{i=await e(n,Object.assign({},a))}catch(c){throw console.error(c),new En(Xt(c),0)}if(i.ok||await fu(i),r?.noResolveJson)return i;try{return await i.json()}catch(c){await fu(c)}}function $e(e){var t;let n=null;Cg(e)&&(n=Object.assign({},e),e.expires_at||(n.expires_at=nu(e.expires_in)));let r=(t=e.user)!==null&&t!==void 0?t:e;return{data:{session:n,user:r},error:null}}function Do(e){let t=$e(e);return!t.error&&e.weak_password&&typeof e.weak_password=="object"&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message=="string"&&e.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=e.weak_password),t}function rt(e){var t;return{data:{user:(t=e.user)!==null&&t!==void 0?t:e},error:null}}function mu(e){return{data:e,error:null}}function hu(e){let{action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:o}=e,a=Ut(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),i={action_link:t,email_otp:n,hashed_token:r,redirect_to:s,verification_type:o},c=Object.assign({},a);return{data:{properties:i,user:c},error:null}}function Ho(e){return e}function Cg(e){return e.access_token&&e.refresh_token&&e.expires_in}var ys=["global","local","others"];var Jt=class{constructor({url:t="",headers:n={},fetch:r,experimental:s}){this.url=t,this.headers=n,this.fetch=ps(r),this.experimental=s??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(t,n=ys[0]){if(ys.indexOf(n)<0)throw new Error("@supabase/auth-js: Parameter scope must be one of ".concat(ys.join(", ")));try{return await K(this.fetch,"POST","".concat(this.url,"/logout?scope=").concat(n),{headers:this.headers,jwt:t,noResolveJson:!0}),{data:null,error:null}}catch(r){if(U(r))return{data:null,error:r};throw r}}async inviteUserByEmail(t,n={}){try{return await K(this.fetch,"POST","".concat(this.url,"/invite"),{body:{email:t,data:n.data},headers:this.headers,redirectTo:n.redirectTo,xform:rt})}catch(r){if(U(r))return{data:{user:null},error:r};throw r}}async generateLink(t){try{let{options:n}=t,r=Ut(t,["options"]),s=Object.assign(Object.assign({},r),n);return"newEmail"in r&&(s.new_email=r?.newEmail,delete s.newEmail),await K(this.fetch,"POST","".concat(this.url,"/admin/generate_link"),{body:s,headers:this.headers,xform:hu,redirectTo:n?.redirectTo})}catch(n){if(U(n))return{data:{properties:null,user:null},error:n};throw n}}async createUser(t){try{return await K(this.fetch,"POST","".concat(this.url,"/admin/users"),{body:t,headers:this.headers,xform:rt})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async listUsers(t){var n,r,s,o,a,i,c;try{let l={nextPage:null,lastPage:0,total:0},m=await K(this.fetch,"GET","".concat(this.url,"/admin/users"),{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t?.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(o=(s=t?.perPage)===null||s===void 0?void 0:s.toString())!==null&&o!==void 0?o:""},xform:Ho});if(m.error)throw m.error;let u=await m.json(),d=(a=m.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(c=(i=m.headers.get("link"))===null||i===void 0?void 0:i.split(","))!==null&&c!==void 0?c:[];return h.length>
40&&(h.forEach(p=>{let b=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(p.split(";")[1].split("=")[1]);l["".concat(v,"Page")]=b}),l.total=parseInt(d)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(U(l))return{data:{users:[]},error:l};throw l}}async getUserById(t){nt(t);try{return await K(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(t),{headers:this.headers,xform:rt})}catch(n){if(U(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){nt(t);try{return await K(this.fetch,"PUT","".concat(this.url,"/admin/users/").concat(t),{body:n,headers:this.headers,xform:rt})}catch(r){if(U(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){nt(t);try{return await K(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(t),{headers:this.headers,body:{should_soft_delete:n},xform:rt})}catch(r){if(U(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){nt(t.userId);try{let{data:n,error:r}=await K(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(t.userId,"/factors"),{headers:this.headers,xform:s=>({data:{factors:s},error:null})});return{data:n,error:r}}catch(n){if(U(n))return{data:null,error:n};throw n}}async _deleteFactor(t){nt(t.userId),nt(t.id);try{return{data:await K(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(t.userId,"/factors/").concat(t.id),{headers:this.headers}),error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}async _listOAuthClients(t){var n,r,s,o,a,i,c;try{let l={nextPage:null,lastPage:0,total:0},m=await K(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients"),{headers:this.headers,noResolveJson:!0,query:{page:(r=(n=t?.page)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:"",per_page:(o=(s=t?.perPage)===null||s===void 0?void 0:s.toString())!==null&&o!==void 0?o:""},xform:Ho});if(m.error)throw m.error;let u=await m.json(),d=(a=m.headers.get("x-total-count"))!==null&&a!==void 0?a:0,h=(c=(i=m.headers.get("link"))===null||i===void 0?void 0:i.split(","))!==null&&c!==void 0?c:[];return h.length>0&&(h.forEach(p=>{let b=parseInt(p.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(p.split(";")[1].split("=")[1]);l["".concat(v,"Page")]=b}),l.total=parseInt(d)),{data:Object.assign(Object.assign({},u),l),error:null}}catch(l){if(U(l))return{data:{clients:[]},error:l};throw l}}async _createOAuthClient(t){try{return await K(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients"),{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _getOAuthClient(t){try{return await K(this.fetch,"GET","".concat(this.url,"/admin/oauth/clients/").concat(t),{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _updateOAuthClient(t,n){try{return await K(this.fetch,"PUT","".concat(this.url,"/admin/oauth/clients/").concat(t),{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(U(r))return{data:null,error:r};throw r}}async _deleteOAuthClient(t){try{return await K(this.fetch,"DELETE","".concat(this.url,"/admin/oauth/clients/").concat(t),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}async _regenerateOAuthClientSecret(t){try{return await K(this.fetch,"POST","".concat(this.url,"/admin/oauth/clients/").concat(t,"/regenerate_secret"),{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _listCustomProviders(t){try{let n={};return t?.type&&(n.type=t.type),await K(this.fetch,"GET","".concat(this.url,"/admin/custom-providers"),{headers:this.headers,query:n,xform:r=>{var s;return{data:{providers:(s=r?.providers)!==null&&s!==void 0?s:[]},error:null}}})}catch(n){if(U(n))return{data:{providers:[]},error:n};throw n}}async _createCustomProvider(t){try{return await K(this.fetch,"POST","".concat(this.url,"/admin/custom-providers"),{body:t,headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _getCustomProvider(t){try{return await K(this.fetch,"GET","".concat(this.url,"/admin/custom-providers/").concat(t),{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _updateCustomProvider(t,n){try{return await K(this.fetch,"PUT","".concat(this.url,"/admin/custom-providers/").concat(t),{body:n,headers:this.headers,xform:r=>({data:r,error:null})})}catch(r){if(U(r))return{data:null,error:r};throw r}}async _deleteCustomProvider(t){try{return await K(this.fetch,"DELET
4E","".concat(this.url,"/admin/custom-providers/").concat(t),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}async _adminListPasskeys(t){He(this.experimental),nt(t.userId);try{return await K(this.fetch,"GET","".concat(this.url,"/admin/users/").concat(t.userId,"/passkeys"),{headers:this.headers,xform:n=>({data:n,error:null})})}catch(n){if(U(n))return{data:null,error:n};throw n}}async _adminDeletePasskey(t){He(this.experimental),nt(t.userId),nt(t.passkeyId);try{return await K(this.fetch,"DELETE","".concat(this.url,"/admin/users/").concat(t.userId,"/passkeys/").concat(t.passkeyId),{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(n){if(U(n))return{data:null,error:n};throw n}}};function $o(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}var Ye={debug:!!(globalThis&&hs()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")},ur=class extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}},dr=class extends ur{};
4async function Fo(e,t,n){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let r=new globalThis.AbortController,s;t>0&&(s=setTimeout(()=>{r.abort(),Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t)),await Promise.resolve();try{return await globalThis.navigator.locks.request(e,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async o=>{if(o){clearTimeout(s),Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,o.name);try{return await n()}finally{Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,o.name)}}else{if(t===0)throw Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new dr('Acquiring an exclusive Navigator LockManager lock "'.concat(e,'" immediately failed'));if(Ye.debug)try{let a=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(a,null," "))}catch(a){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",a)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),clearTimeout(s),await n()}})}catch(o){if(t>0&&clearTimeout(s),o?.name==="AbortError"&&t>0){if(r.signal.aborted)return Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock",e),console.warn('@supabase/gotrue-js: Lock "'.concat(e,'" was not released within ').concat(t,"ms. ")+"This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover."),await Promise.resolve().then(()=>globalThis.navigator.locks.request(e,{mode:"exclusive",steal:!0},async a=>{if(a){Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: recovered (stolen)",e,a.name);try{return await n()}finally{Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: released (stolen)",e,a.name)}}else return console.warn("@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true"),await n()}));throw Ye.debug&&console.log("@supabase/gotrue-js: navigatorLock: lock was stolen by another request",e),new dr
4('Lock "'.concat(e,'" was released because another request stole it'))}throw o}}function pu(){if(typeof globalThis!="object")try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<"u"&&(self.globalThis=self)}}function qo(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw new Error('@supabase/auth-js: Address "'.concat(e,'" is invalid.'));return e.toLowerCase()}function gu(e){return parseInt(e,16)}function yu(e){let t=new TextEncoder().encode(e);return"0x"+Array.from(t,r=>r.toString(16).padStart(2,"0")).join("")}function bu(e){var t;let{chainId:n,domain:r,expirationTime:s,issuedAt:o=new Date,nonce:a,notBefore:i,requestId:c,resources:l,scheme:m,uri:u,version:d}=e;{if(!Number.isInteger(n))throw new Error('@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: '.concat(n));if(!r)throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.');if(a&&a.length<8)throw new Error('@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: '.concat(a));if(!u)throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.');if(d!=="1")throw new Error("@supabase/auth-js: Invalid SIWE message field \"version\". Version must be '1'. Provided value: ".concat(d));if(!((t=e.statement)===null||t===void 0)&&t.includes("\n"))throw new Error("@supabase/auth-js: Invalid SIWE message field \"statement\". Statement must not include '\\n'. Provided value: ".concat(e.statement))}let h=qo(e.address),p=m?"".concat(m,"://").concat(r):r,b=e.statement?"".concat(e.statement,"\n"):"",v="".concat(p," wants you to sign in with your Ethereum account:\n").concat(h,"\n\n").concat(b),E="URI: ".concat(u,"\nVersion: ").concat(d,"\nChain ID: ").concat(n).concat(a?"\nNonce: ".concat(a):"","\nIssued At: ").concat(o.toISOString());if(s&&(E+="\nExpiration Time: ".concat(s.toISOString())),i&&(E+="\nNot Before: ".concat(i.toISOString())),c&&(E+="\nRequest ID: ".concat(c)),l){let A="\nResources:";for(let S of l){if(!S||typeof S!="string")throw new Error('@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: '.concat(S));A+="\n- ".concat(S)}E+=A}return"".concat(v,"\n").concat(E)}var me=class extends Error{constructor({message:t,code:n,cause:r,name:s}){var o;super(t,{cause:r}),this.__isWebAuthnError=!0,this.name=(o=s??(r instanceof Error?r.name:void 0))!==null&&o!==void 0?o:"Unknown Error",this.code=n}},Qt=class extends me{constructor(t,n){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:n,message:t}),this.name="WebAuthnUnknownError",this.originalError=n}};function wu({error:e,options:t}){var n,r,s;let{publicKey:o}=t;if(!o)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new me({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(((n=o.authenticatorSelection)===null||n===void 0?void 0:n.requireResidentKey)===!0)return new me({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&((r=o.authenticatorSelection)===null||r===void 0?void 0:r.userVerification)==="required")return new me({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(((s=o.authenticatorSelection)===null||s===void 0?void 0:s.userVerification)==="required")return new me({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new me({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new me({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return o.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new me({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new me({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let a=globalThis.location.hostname;if(Uo(a)){if(o.rp.id!==a)return new me({message:'The RP ID "'.concat(o.rp.id,'" is invali
4d for this domain'),code:"ERROR_INVALID_RP_ID",cause:e})}else return new me({message:"".concat(globalThis.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(o.user.id.byteLength<1||o.user.id.byteLength>64)return new me({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new me({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new me({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}function Su({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new me({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new me({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let r=globalThis.location.hostname;if(Uo(r)){if(n.rpId!==r)return new me({message:'The RP ID "'.concat(n.rpId,'" is invalid for this domain'),code:"ERROR_INVALID_RP_ID",cause:e})}else return new me({message:"".concat(globalThis.location.hostname," is an invalid domain"),code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new me({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return new me({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e})}var jo=class{createNewAbortSignal(){if(this.controller){let n=new Error("Cancelling existing WebAuthn API call for new one");n.name="AbortError",this.controller.abort(n)}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},Ss=new jo;function zo(e){if(!e)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:t,user:n,excludeCredentials:r}=e,s=Ut(e,["challenge","user","excludeCredentials"]),o=Lt(t).buffer,a=Object.assign(Object.assign({},n),{id:Lt(n.id).buffer}),i=Object.assign(Object.assign({},s),{challenge:o,user:a});if(r&&r.length>0){i.excludeCredentials=new Array(r.length);for(let c=0;c<r.length;c++){let l=r[c];i.excludeCredentials[c]=Object.assign(Object.assign({},l),{id:Lt(l.id).buffer,type:l.type||"public-key",transports:l.transports})}}return i}function Wo(e){if(!e)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:t,allowCredentials:n}=e,r=Ut(e,["challenge","allowCredentials"]),s=Lt(t).buffer,o=Object.assign(Object.assign({},r),{challenge:s});if(n&&n.length>0){o.allowCredentials=new Array(n.length);for(let a=0;a<n.length;a++){let i=n[a];o.allowCredentials[a]=Object.assign(Object.assign({},i),{id:Lt(i.id).buffer,type:i.type||"public-key",transports:i.transports})}}return o}function Go(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();let n=e;return{id:e.id,rawId:e.id,response:{attestationObject:gt(new Uint8Array(e.response.attestationObject)),clientDataJSON:gt(new Uint8Array(e.response.clientDataJSON))},type:"public-key",clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function Ko(e){var t;if("toJSON"in e&&typeof e.toJSON=="function")return e.toJSON();let n=e,r=e.getClientExtensionResults(),s=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:gt(new Uint8Array(s.authenticatorData)),clientDataJSON:gt(ne
4w Uint8Array(s.clientDataJSON)),signature:gt(new Uint8Array(s.signature)),userHandle:s.userHandle?gt(new Uint8Array(s.userHandle)):void 0},type:"public-key",clientExtensionResults:r,authenticatorAttachment:(t=n.authenticatorAttachment)!==null&&t!==void 0?t:void 0}}function Uo(e){return e==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function fr(){var e,t;return!!(ke()&&"PublicKeyCredential"in globalThis&&globalThis.PublicKeyCredential&&"credentials"in navigator&&typeof((e=navigator?.credentials)===null||e===void 0?void 0:e.create)=="function"&&typeof((t=navigator?.credentials)===null||t===void 0?void 0:t.get)=="function")}async function Vo(e){try{let t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",t)}:{data:null,error:new Qt("Empty credential response",t)}}catch(t){return{data:null,error:wu({error:t,options:e})}}}async function Yo(e){try{let t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new Qt("Browser returned unexpected credential type",t)}:{data:null,error:new Qt("Empty credential response",t)}}catch(t){return{data:null,error:Su({error:t,options:e})}}}var Ag={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},Eg={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function bs(...e){let t=s=>s!==null&&typeof s=="object"&&!Array.isArray(s),n=s=>s instanceof ArrayBuffer||ArrayBuffer.isView(s),r={};for(let s of e)if(s)for(let o in s){let a=s[o];if(a!==void 0)if(Array.isArray(a))r[o]=a;else if(n(a))r[o]=a;else if(t(a)){let i=r[o];t(i)?r[o]=bs(i,a):r[o]=bs(a)}else r[o]=a}return r}function Tg(e,t){return bs(Ag,e,t||{})}function xg(e,t){return bs(Eg,e,t||{})}var ws=class{constructor(t){this.client=t,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(t){return this.client.mfa.enroll(Object.assign(Object.assign({},t),{factorType:"webauthn"}))}async _challenge({factorId:t,webauthn:n,friendlyName:r,signal:s},o){var a;try{let{data:i,error:c}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!i)return{data:null,error:c};let l=s??Ss.createNewAbortSignal();if(i.webauthn.type==="create"){let{user:m}=i.webauthn.credential_options.publicKey;if(!m.name){let u=r;if(u)m.name="".concat(m.id,":").concat(u);else{let h=(await this.client.getUser()).data.user,p=((a=h?.user_metadata)===null||a===void 0?void 0:a.name)||h?.email||h?.id||"User";m.name="".concat(m.id,":").concat(p)}}m.displayName||(m.displayName=m.name)}switch(i.webauthn.type){case"create":{let m=Tg(i.webauthn.credential_options.publicKey,o?.create),{data:u,error:d}=await Vo({publicKey:m,signal:l});return u?{data:{factorId:t,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}case"request":{let m=xg(i.webauthn.credential_options.publicKey,o?.request),{data:u,error:d}=await Yo(Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:m,signal:l}));return u?{data:{factorId:t,challengeId:i.id,webauthn:{type:i.webauthn.type,credential_response:u}},error:null}:{data:null,error:d}}}}catch(i){return U(i)?{data:null,error:i}:{data:null,error:new Pe("Unexpected error in challenge",i)}}}async _verify({challengeId:t,factorId:n,webauthn:r}){return this.client.mfa.verify({factorId:n,challengeId:t,webauthn:r})}async _authenticate({factorId:t,webauthn:{rpId:n=typeof globalThis<"u"?globalThis.location.hostname:void 0,rpOrigins:r=typeof globalThis<"u"?[globalThis.location.origin]:void 0,signal:s}={}},o){if(!n)return{data:null,error:new Nt("rpId is required for WebAuthn authentication")};try{if(!fr())return{data:null,error:new Pe("Browser does not support WebAuthn",null)};let{data:a,error:i}=await this.challenge({factorId:t,webauthn:{rpId:n,rpOrigins:r},signal:s},{request:o});if(!a)return{data:null,error:i};let{webauthn:c}=a;return this._verify({factorId:t,challengeId:a.challengeId,webauthn:{type:c.type,rpId:n,rpOrigins:r,credential_response:c.credential_response}})}catch(a){return U(a)?{data:null,error:a}:{data:null,error:new Pe("Unexpected error in authenticate",a)}}}async _register({friendlyName:t,webauthn:{rpId:n=typeof globalThis<"u"?globalThis.location.hostname:void 0,rpOrigins:r=typeof globalThis<"u"?[globalThis.location.origin]:void 0,signal:s}={}},o){if(!n)return{data:null,error:new Nt("rpId is required for WebAuthn registration")};try{if(!fr())return{data:null,error:new Pe("Browser does not support WebAuthn",null)};let{data:a,error:i}=await this._enroll({friendlyName:t});if(!a)return await this.client.mfa.listFactors().then(m=>{var u;return(u=m.data)===null||u===void 0?void 0:u.all.find(d=>d.factor_type==="webauthn"&&d.friendly_name===t&&d.status!=="unverified")}).then(m=>m?this.client.mfa.unenroll({factorId:m?.id}):void 0),{data:null,error:i};let{data:c,error:l}=await this._challenge({factorId:a.id,friendlyName:a.friendly_name,webauthn:{rpId:n,rpOrigins:r},signal:s},{create:o});return c?this._verify({factorId:a.id,challengeId:c.challengeId,webauthn:{rpId:n,rpOrigins:r,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(a){return U(a)?{data:null,error:a}:{data:null,error:new Pe("Unexpected error in register",a)}}}};pu();var Rg={url:Wl,storageKey:Gl,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Kl,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}};async function ku(e,t,n){return await n()}var Tn={},ks=class e{get jwks(){var t,n;return(n=(t=Tn[this.storageKey])===null||t===void 0?void 0:t.jwks)!==null&&n!==void 0?n:{keys:[]}}set jwks(t){Tn[this.storageKey]=Object.assign(Object.assign({},Tn[this.storageKey]),{jwks:t})}get jwks_cached_at(){var t,n;return(n=(t=Tn[this.storageKey])===null||t===void 0?void 0:t.cachedAt)!==null&&n!==void 0?n:Number.MIN_SAFE_INTEGER}set jwks_cached_at(t){Tn[this.storageKey]=Object.assign(Object.assign({},Tn[this.storageKey]),{cachedAt:t})}constructor(t){var n,r,s,o;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let a=Object.assign(Object.assign({},Rg),t);if(this.storageKey=a.storageKey,this.instanceID=(n=e.nextInstanceID[this.storageKey])!==null&&n!==void 0?n:0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!a.debug,typeof a.debug=="function"&&(this.logger=a.debug),this.instanceID>0&&ke()){let i="".concat(this._logPrefix()," Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");console.warn(i),this.logDebugMessages&&console.trace(i)}if(this.persistSession=a.persistSession,this.autoRefreshToken=a.autoRefreshToken,this.experimental=(r=a.experimental)!==null&&r!==void 0?r:{},this.admin=new Jt({url:a.url,headers:a.headers,fetch:a.fetch,experimental:this.experimental}),this.url=a.url,this.headers=a.headers,this.fetch=ps(a.fetch),this.lock=a.lock||ku,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,this.throwOnError=a.throwOnError,this.lockAcquireTimeout=a.lockAcquireTimeout,a.lock?this.lock=a.lock:this.persistSession&&ke()&&(!((s=globalThis?.navigator)===null||s===void 0)&&s.locks)?this.lock=Fo:this.lock=ku,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new ws(this)}
4,this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(a.storage?this.storage=a.storage:hs()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=$o(this.memoryStorage)),a.userStorage&&(this.userStorage=a.userStorage)):(this.memoryStorage={},this.storage=$o(this.memoryStorage)),ke()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(o=this.broadcastChannel)===null||o===void 0||o.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i);try{await this._notifyAllSubscribers(i.data.event,i.data.session,!1)}catch(c){this._debug("#broadcastChannel","error",c)}})}a.skipAutoInitialize||this.initialize().catch(i=>{this._debug("#initialize()","error",i)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(t){if(this.throwOnError&&t&&t.error)throw t.error;return t}_logPrefix(){return"GoTrueClient@"+"".concat(this.storageKey,":").concat(this.instanceID," (").concat(is,") ").concat(new Date().toISOString())}_debug(...t){return this.logDebugMessages&&this.logger(this._logPrefix(),...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{let n={},r="none";if(ke()&&(n=su(globalThis.location.href),this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce")),ke()&&this.detectSessionInUrl&&r!=="none"){let{data:s,error:o}=await this._getSessionFromURL(n,r);if(o){if(this._debug("#_initialize()","error detecting session from URL",o),Jl(o)){let c=(t=o.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:o}}return{error:o}}let{session:a,redirectType:i}=s;return this._debug("#_initialize()","detected session in URL",a,"redirect type",i),await this._saveSession(a),setTimeout(async()=>{i==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",a):await this._notifyAllSubscribers("SIGNED_IN",a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return U(n)?this._returnResult({error:n}):this._returnResult({error:new Pe("Unexpected error during initialization",n)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,s;try{let o=await K(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{data:(r=(n=t?.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(s=t?.options)===null||s===void 0?void 0:s.captchaToken}},xform:$e}),{data:a,error:i}=o;if(i||!a)return this._returnResult({data:{user:null,session:null},error:i});let c=a.session,l=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(o){if(U(o))return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signUp(t){var n,r,s;try{let o;if("email"in t){let{email:m,password:u,options:d}=t,h=null,p=null;this.flowType==="pkce"&&([h,p]=await Yt(this.storage,this.storageKey)),o=await K(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,redirectTo:d?.emailRedirectTo,body:{email:m,password:u,data:(n=d?.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:d?.captchaToken},code_challenge:h,code_challenge_method:p},xform:$e})}else if("phone"in t){let{phone:m,password:u,options:d}=t;o=await K(this.fetch,"POST","".concat(this.url,"/signup"),{headers:this.headers,body:{phone:m,password:u,data:(r=d?.data)!==null&&r!==void 0?r:{},channel:(s=d?.channel)!==null&&s!==void 0?s:"sms",gotrue_meta_security:{captcha_token:d?.captchaToken}},xform:$e})}else throw new zt("You must provide either an email or phone number and a password");let{data:a,error:i}=o;if(i||!a)return await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),this._returnResult({data:{user:null,session:null},error:i});let c=a.session,l=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(o){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(o)
4)return this._returnResult({data:{user:null,session:null},error:o});throw o}}async signInWithPassword(t){try{let n;if("email"in t){let{email:o,password:a,options:i}=t;n=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{email:o,password:a,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Do})}else if("phone"in t){let{phone:o,password:a,options:i}=t;n=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=password"),{headers:this.headers,body:{phone:o,password:a,gotrue_meta_security:{captcha_token:i?.captchaToken}},xform:Do})}else throw new zt("You must provide either an email or phone number and a password");let{data:r,error:s}=n;if(s)return this._returnResult({data:{user:null,session:null},error:s});if(!r||!r.session||!r.user){let o=new pt;return this._returnResult({data:{user:null,session:null},error:o})}return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),this._returnResult({data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:s})}catch(n){if(U(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOAuth(t){var n,r,s,o;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(s=t.options)===null||s===void 0?void 0:s.queryParams,skipBrowserRedirect:(o=t.options)===null||o===void 0?void 0:o.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(t))}async signInWithWeb3(t){let{chain:n}=t;switch(n){case"ethereum":return await this.signInWithEthereum(t);case"solana":return await this.signInWithSolana(t);default:throw new Error('@supabase/auth-js: Unsupported chain "'.concat(n,'"'))}}async signInWithEthereum(t){var n,r,s,o,a,i,c,l,m,u,d;let h,p;if("message"in t)h=t.message,p=t.signature;else{let{chain:b,wallet:v,statement:E,options:A}=t,S;if(ke())if(typeof v=="object")S=v;else{let T=globalThis;if("ethereum"in T&&typeof T.ethereum=="object"&&"request"in T.ethereum&&typeof T.ethereum.request=="function")S=T.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof v!="object"||!A?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");S=v}let _=new URL((n=A?.url)!==null&&n!==void 0?n:globalThis.location.href),w=await S.request({method:"eth_requestAccounts"}).then(T=>T).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!w||w.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");let f=qo(w[0]),g=(r=A?.signInWithEthereum)===null||r===void 0?void 0:r.chainId;if(!g){let T=await S.request({method:"eth_chainId"});g=gu(T)}let C={domain:_.host,address:f,statement:E,uri:_.href,version:"1",chainId:g,nonce:(s=A?.signInWithEthereum)===null||s===void 0?void 0:s.nonce,issuedAt:(a=(o=A?.signInWithEthereum)===null||o===void 0?void 0:o.issuedAt)!==null&&a!==void 0?a:new Date,expirationTime:(i=A?.signInWithEthereum)===null||i===void 0?void 0:i.expirationTime,notBefore:(c=A?.signInWithEthereum)===null||c===void 0?void 0:c.notBefore,requestId:(l=A?.signInWithEthereum)===null||l===void 0?void 0:l.requestId,resources:(m=A?.signInWithEthereum)===null||m===void 0?void 0:m.resources};h=bu(C),p=await S.request({method:"personal_sign",params:[yu(h),f]})}try{let{data:b,error:v}=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"ethereum",message:h,signature:p},!((u=t.options)===null||u===void 0)&&u.captchaToken?{gotrue_meta_security:{captcha_token:(d=t.options)===null||d===void 0?void 0:d.captchaToken}}:null),xform:$e});if(v)throw v;if(!b||!b.session||!b.user){let E=new pt;return this._returnResult({data:{user:null,session:null},error:E})}return b.session&&(await this._saveSession(b.session),await this._notifyAllSubscribers("SIGNED_IN",b.session)),this._returnResult({data:Object.assign({},b),error:v})}catch(b){if(U(b))return this._returnResult({data:{user:null,session:null},error:b});throw b}}async signInWithSolana(t){var n,r,s,o,a,i,c,l,m,u,d,h;let p,b;if("message"in t)p=t.message,b=t.signature;else{let{chain:v,wallet:E,statement:A,options:S}=t,_;if(ke())if(typeof E=="object")_=E;else{let f=globalThis;if("solana"in f&&typeof f.solana=="object"&&("signIn"in f.solana&&typeof f.solana.signIn=="function"||"signMessage"in f.solana&&typeof f.solana.signMessage=="function"))_=f.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof E!="object"||!S?.url)throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");_=E}let w=new URL((n=S?.url)!==null&&n!==void 0?n:globalThis.location.href);if("signIn"in _&&_.signIn){let f=await _.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},S?.signInWithSolana),{version:"1",domain:w.host,uri:w.href}),A?{statement:A}:null)),g;if(Array.isArray(f)&&f[0]&&typeof f[0]=="object")g=f[0];else if(f&&typeof f=="object"&&"signedMessage"in f&&"signature"in f)g=f;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in g&&"signature"in g&&(typeof g.signedMessage=="string"||g.signedMessage instanceof Uint8Array)&&g.signature instanceof Uint8Array)p=typeof g.signedMessage=="string"?g.signedMessage:new TextDecoder().decode(g.signedMessage),b=g.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in _)||typeof _.signMessage!="function"||!("publicKey"in _)||typeof _!="object"||!_.publicKey||!("toBase58"in _.publicKey)||typeof _.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");p=["".concat(w.host," wants you to sign in with your Solana account:"),_.publicKey.toBase58(),...A?["",A,""]:[""],"Version: 1","URI: ".concat(w.href),"Issued At: ".concat((s=(r=S?.signInWithSolana)===null||r===void 0?void 0:r.issuedAt)!==null&&s!==void 0?s:new Date().toISOString()),...!((o=S?.signInWithSolana)===null||o===void 0)&&o.notBefore?["Not Before: ".concat(S.signInWithSolana.notBefore)]:[],...!((a=S?.signInWithSolana)===null||a===void 0)&&a.expirationTime?["Expiration Time: ".concat(S.signInWithSolana.expirationTime)]:[],...!((i=S?.signInWithSolana)===null||i===void 0)&&i.chainId?["Chain ID: ".concat(S.signInWithSolana.chainId)]:[],...!((c=S?.signInWithSolana)===null||c===void 0)&&c.nonce?["Nonce: ".concat(S.signInWithSolana.nonce)]:[],...!((l=S?.signInWithSolana)===null||l===void 0)&&l.requestId?["Request ID: ".concat(S.signInWithSolana.requestId)]:[],...!((u=(m=S?.signInWithSolana)===null||m===void 0?void 0:m.resources)===null||u===void 0)&&u.length?["Resources",...S.signInWithSolana.resources.map(g=>"- ".concat(g))]:[]].join("\n");let f=await _.signMessage(new TextEncoder().encode(p),"utf8");if(!f||!(f instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");b=f}}try{let{data:v,error:E}=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=web3"),{headers:this.headers,body:Object.assign({chain:"solana",message:p,signature:gt(b)},!((d=t.options)===null||d===void 0)&&d.captchaToken?{gotrue_meta_security:{captcha_token:(h=t.options)===null||h===void 0?void 0:h.captchaToken}}:null),xform:$e});if(E)throw E;if(!v||!v.session||!v.user){let A=new pt;return this._returnResult({data:{user:null,session:null},error:A})}return v.session&&(await this._saveSession(v.session),await this._notifyAllSubscribers("SIGNED_IN",v.session)),this._returnResult({data:Object.assign({},v),error:E})}catch(v){if(U(v))return this._returnResult({data:{user:null,session:null},error:v});throw v}}async _exchangeCodeForSession(t){let n=await Mt(this.storage,"".concat(this.storageKey,"-code-verifier")),[r,s]=(n??"").split("/");try{if(!r&&this.flowType==="pkce")throw new ds;let{data:o,error:a}=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=pkce"),{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:$e});if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),a)throw a;if(!o||!o.session||!o.user){let i=new pt;return this._returnResult({data:{user:null,session:null,redirectType:null},error:i})}return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(s==="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",o.session)),this._returnResult({data:Object.assign(Object.assign({},o),{redirectType:s??null}),error:a})}catch(o){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(o)
4)return this._returnResult({data:{user:null,session:null,redirectType:null},error:o});throw o}}async signInWithIdToken(t){try{let{options:n,provider:r,token:s,access_token:o,nonce:a}=t,i=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,body:{provider:r,id_token:s,access_token:o,nonce:a,gotrue_meta_security:{captcha_token:n?.captchaToken}},xform:$e}),{data:c,error:l}=i;if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let m=new pt;return this._returnResult({data:{user:null,session:null},error:m})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),this._returnResult({data:c,error:l})}catch(n){if(U(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async signInWithOtp(t){var n,r,s,o,a;try{if("email"in t){let{email:i,options:c}=t,l=null,m=null;this.flowType==="pkce"&&([l,m]=await Yt(this.storage,this.storageKey));let{error:u}=await K(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{email:i,data:(n=c?.data)!==null&&n!==void 0?n:{},create_user:(r=c?.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},code_challenge:l,code_challenge_method:m},redirectTo:c?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:u})}if("phone"in t){let{phone:i,options:c}=t,{data:l,error:m}=await K(this.fetch,"POST","".concat(this.url,"/otp"),{headers:this.headers,body:{phone:i,data:(s=c?.data)!==null&&s!==void 0?s:{},create_user:(o=c?.shouldCreateUser)!==null&&o!==void 0?o:!0,gotrue_meta_security:{captcha_token:c?.captchaToken},channel:(a=c?.channel)!==null&&a!==void 0?a:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:l?.message_id},error:m})}throw new zt("You must provide either an email or phone number.")}catch(i){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(i))return this._returnResult({data:{user:null,session:null},error:i});throw i}}async verifyOtp(t){var n,r;try{let s,o;"options"in t&&(s=(n=t.options)===null||n===void 0?void 0:n.redirectTo,o=(r=t.options)===null||r===void 0?void 0:r.captchaToken);let{data:a,error:i}=await K(this.fetch,"POST","".concat(this.url,"/verify"),{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:o}}),redirectTo:s,xform:$e});if(i)throw i;if(!a)throw new Error("An error occurred on token verification.");let c=a.session,l=a.user;return c?.access_token&&(await this._saveSession(c),await this._notifyAllSubscribers(t.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",c)),this._returnResult({data:{user:l,session:c},error:null})}catch(s){if(U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}}async signInWithSSO(t){var n,r,s,o,a;try{let i=null,c=null;this.flowType==="pkce"&&([i,c]=await Yt(this.storage,this.storageKey));let l=await K(this.fetch,"POST","".concat(this.url,"/sso"),{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((s=t?.options)===null||s===void 0)&&s.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:c}),headers:this.headers,xform:mu});return!((o=l.data)===null||o===void 0)&&o.url&&ke()&&!(!((a=t.options)===null||a===void 0)&&a.skipBrowserRedirect)&&globalThis.location.assign(l.data.url),this._returnResult(l)}catch(i){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(i))return this._returnResult({data:null,error:i});throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new pe;let{error:s}=await K(this.fetch,"GET","".concat(this.url,"/reauthenticate"),{headers:this.headers,jwt:n.access_token});return this._returnResult({data:{user:null,session:null},error:s})})}catch(t){if(U(t))return this._returnResult({data:{user:null,session:null},error:t});throw t}}async resend(t){try{let n="".concat(this.url,"/resend");if("email"in t){let{email:r,type:s,options:o}=t,{error:a}=await K(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:s,gotrue_meta_security:{captcha_token:o?.captchaToken}},redirectTo:o?.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:a})}else if("phone"in t){let{phone:r,type:s,options:o}=t,{data:a,error:i}=await K(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:s,gotrue_meta_security:{captcha_token:o?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:a?.message_id},error:i})}throw new zt("You must provide either an email or phone number and a type")}catch(n){if(U(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){let r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),s=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await s}catch{}})()),s}return await this.lock("lock:".concat(this.storageKey),t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){let s=[...this.pendingInLock];await Promise.all(s),this.pendingInLock.splice(0,s.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{let n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null,n=await Mt(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not val
4id"),await this._removeSession())),!t)return{data:{session:null},error:null};let r=t.expires_at?t.expires_at*1e3-Date.now()<ls:!1;if(this._debug("#__loadSession()","session has".concat(r?"":" not"," expired"),"expires_at",t.expires_at),!r){if(this.userStorage){let a=await Mt(this.userStorage,this.storageKey+"-user");a?.user?t.user=a.user:t.user=gs()}if(this.storage.isServer&&t.user&&!t.user.__isUserNotAvailableProxy){let a={value:this.suppressGetSessionWarning};t.user=du(t.user,a),a.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:t},error:null}}let{data:s,error:o}=await this._callRefreshToken(t.refresh_token);return o?this._returnResult({data:{session:null},error:o}):this._returnResult({data:{session:s},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser(t){if(t)return await this._getUser(t);await this.initializePromise;let n=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return n.data.user&&(this.suppressGetSessionWarning=!0),n}async _getUser(t){try{return t?await K(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:t,xform:rt}):await this._useSession(async n=>{var r,s,o;let{data:a,error:i}=n;if(i)throw i;return!(!((r=a.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new pe}:await K(this.fetch,"GET","".concat(this.url,"/user"),{headers:this.headers,jwt:(o=(s=a.session)===null||s===void 0?void 0:s.access_token)!==null&&o!==void 0?o:void 0,xform:rt})})}catch(n){if(U(n))return ir(n)&&(await this._removeSession(),await _e(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({data:{user:null},error:n});throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{let{data:s,error:o}=r;if(o)throw o;if(!s.session)throw new pe;let a=s.session,i=null,c=null;this.flowType==="pkce"&&t.email!=null&&([i,c]=await Yt(this.storage,this.storageKey));let{data:l,error:m}=await K(this.fetch,"PUT","".concat(this.url,"/user"),{headers:this.headers,redirectTo:n?.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:i,code_challenge_method:c}),jwt:a.access_token,xform:rt});if(m)throw m;return a.user=l.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),this._returnResult({data:{user:a.user},error:null})})}catch(r){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(r))return this._returnResult({data:{user:null},error:r});throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new pe;let n=Date.now()/1e3,r=n,s=!0,o=null,{payload:a}=lr(t.access_token);if(a.exp&&(r=a.exp,s=r<=n),s){let{data:i,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});if(!i)return{data:{user:null,session:null},error:null};o=i}else{let{data:i,error:c}=await this._getUser(t.access_token);if(c)return this._returnResult({data:{user:null,session:null},error:c});o={access_token:t.access_token,refresh_token:t.refresh_token,user:i.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(o),await this._notifyAllSubscribers("SIGNED_IN",o)}return this._returnResult({data:{user:o.user,session:o},error:null})}catch(n){if(U(n))return this._returnResult({data:{session:null,user:null},error:n});throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){let{data:a,error:i}=n;if(i)throw i;t=(r=a.session)!==null&&r!==void 0?r:void 0}if(!t?.refresh_token)throw new pe;let{data:s,error:o}=await this._callRefreshToken(t.refresh_token);return o?this._returnResult({data:{user:null,session:null},error:o}):s?this._returnResult({data:{user:s.user,session:s},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(n){if(U(n))return this._returnResult({data:{user:null,session:null},error:n});throw n}}async _getSessionFromURL(t,n){var r;try{if(!ke())throw new Wt("No browser detected.");
4if(t.error||t.error_description||t.error_code)throw new Wt(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new or("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new Wt("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new or("No code detected.");let{data:S,error:_}=await this._exchangeCodeForSession(t.code);if(_)throw _;let w=new URL(globalThis.location.href);return w.searchParams.delete("code"),globalThis.history.replaceState(globalThis.history.state,"",w.toString()),{data:{session:S.session,redirectType:(r=S.redirectType)!==null&&r!==void 0?r:null},error:null}}let{provider_token:s,provider_refresh_token:o,access_token:a,refresh_token:i,expires_in:c,expires_at:l,token_type:m}=t;if(!a||!c||!i||!m)throw new Wt("No session defined in URL");let u=Math.round(Date.now()/1e3),d=parseInt(c),h=u+d;l&&(h=parseInt(l));let p=h-u;p*1e3<=jt&&console.warn("@supabase/gotrue-js: Session as retrieved from URL expires in ".concat(p,"s, should have been closer to ").concat(d,"s"));let b=h-d;u-b>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",b,h,u):u-b<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",b,h,u);let{data:v,error:E}=await this._getUser(a);if(E)throw E;let A={provider_token:s,provider_refresh_token:o,access_token:a,expires_in:d,expires_at:h,refresh_token:i,token_type:m,user:v.user};return globalThis.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:A,redirectType:t.type},error:null})}catch(s){if(U(s))return this._returnResult({data:{session:null,redirectType:null},error:s});throw s}}_isImplicitGrantCallback(t){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(globalThis.location.href),t):!!(t.access_token||t.error_description)}async _isPKCECallback(t){let n=await Mt(this.storage,"".concat(this.storageKey,"-code-verifier"));return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;let{data:s,error:o}=n;if(o&&!ir(o))return this._returnResult({error:o});let a=(r=s.session)===null||r===void 0?void 0:r.access_token;if(a){let{error:i}=await this.admin.signOut(a,t);if(i&&!(Xl(i)&&(i.status===404||i.status===401||i.status===403)||ir(i)))return this._returnResult({error:i})}return t!=="others"&&(await this._removeSession(),await _e(this.storage,"".concat(this.storageKey,"-code-verifier"))),this._returnResult({error:null})})}onAuthStateChange(t){let n=ru(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,s;try{let{data:{session:o},error:a}=n;if(a)throw a;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",o)),this._debug("INITIAL_SESSION","callback id",t,"session",o)}catch(o){await((s=this.stateChangeEmitters.get(t))===null||s===void 0?void 0:s.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",o),ir(o)?console.warn(o):console.error(o)}})}async resetPasswordForEmail(t,n={}){let r=null,s=null;this.flowType==="pkce"&&([r,s]=await Yt(this.storage,this.storageKey,!0));try{return await K(this.fetch,"POST","".concat(this.url,"/recover"),{body:{email:t,code_challenge:r,code_challenge_method:s,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(o){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(o)
4)return this._returnResult({data:null,error:o});throw o}}async getUserIdentities(){var t;try{let{data:n,error:r}=await this.getUser();if(r)throw r;return this._returnResult({data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async linkIdentity(t){return"token"in t?this.linkIdentityIdToken(t):this.linkIdentityOAuth(t)}async linkIdentityOAuth(t){var n;try{let{data:r,error:s}=await this._useSession(async o=>{var a,i,c,l,m;let{data:u,error:d}=o;if(d)throw d;let h=await this._getUrlForProvider("".concat(this.url,"/user/identities/authorize"),t.provider,{redirectTo:(a=t.options)===null||a===void 0?void 0:a.redirectTo,scopes:(i=t.options)===null||i===void 0?void 0:i.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await K(this.fetch,"GET",h,{headers:this.headers,jwt:(m=(l=u.session)===null||l===void 0?void 0:l.access_token)!==null&&m!==void 0?m:void 0})});if(s)throw s;return ke()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&globalThis.location.assign(r?.url),this._returnResult({data:{provider:t.provider,url:r?.url},error:null})}catch(r){if(U(r))return this._returnResult({data:{provider:t.provider,url:null},error:r});throw r}}async linkIdentityIdToken(t){return await this._useSession(async n=>{var r;try{let{error:s,data:{session:o}}=n;if(s)throw s;let{options:a,provider:i,token:c,access_token:l,nonce:m}=t,u=await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=id_token"),{headers:this.headers,jwt:(r=o?.access_token)!==null&&r!==void 0?r:void 0,body:{provider:i,id_token:c,access_token:l,nonce:m,link_identity:!0,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:$e}),{data:d,error:h}=u;return h?this._returnResult({data:{user:null,session:null},error:h}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new pt}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers("USER_UPDATED",d.session)),this._returnResult({data:d,error:h}))}catch(s){if(await _e(this.storage,"".concat(this.storageKey,"-code-verifier")),U(s))return this._returnResult({data:{user:null,session:null},error:s});throw s}})}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,s;let{data:o,error:a}=n;if(a)throw a;return await K(this.fetch,"DELETE","".concat(this.url,"/user/identities/").concat(t.identity_id),{headers:this.headers,jwt:(s=(r=o.session)===null||r===void 0?void 0:r.access_token)!==null&&s!==void 0?s:void 0})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _refreshAccessToken(t){let n="#_refreshAccessToken(".concat(t.substring(0,5),"...)");this._debug(n,"begin");try{let r=Date.now();return await iu(async s=>(s>0&&await au(200*Math.pow(2,s-1)),this._debug(n,"refreshing attempt",s),await K(this.fetch,"POST","".concat(this.url,"/token?grant_type=refresh_token"),{body:{refresh_token:t},headers:this.headers,xform:$e})),(s,o)=>{let a=200*Math.pow(2,s);return o&&fs(o)&&Date.now()+a-r<jt})}catch(r){if(this._debug(n,"error",r),U(r))return this._returnResult({data:{session:null,user:null},error:r});throw r}finally{this._debug(n,"end")}}_isValidSession(t){return typeof t=="object"&&t!==null&&"access_token"in t&&"refresh_token"in t&&"expires_at"in t}async _handleProviderSignIn(t,n){let r=await this._getUrlForProvider("".concat(this.url,"/authorize"),t,{redirectTo:n.redirectTo,scopes:n.scopes,queryParams:n.queryParams});return this._debug("#_handleProviderSignIn()","provider",t,"options",n,"url",r),ke()&&!n.skipBrowserRedirect&&globalThis.location.assign(r),{data:{provider:t,url:r},error:null}}async _recoverAndRefresh(){var t,n;let r="#_recoverAndRefresh()";this._debug(r,"begin");try{let s=await Mt(this.storage,this.storageKey);if(s&&this.userStorage){let a=await Mt(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!a&&(a={user:s.user},await Vt(this.userStorage,this.storageKey+"-user",a)),s.user=(t=a?.user)!==null&&t!==void 0?t:gs()}else if(s&&!s.user&&!s.user){let a=await Mt(this.storage,this.storageKey+"-user");a&&a?.user?(s.user=a.user,await _e(this.storage,this.storageKey+"-user"),await Vt(this.storage,this.storageKey,s)):s.user=gs()}if(this._debug(r,"session from storage",s),!this._isValidSession(s)){this._debug(r,"session is not val
4id"),s!==null&&await this._removeSession();return}let o=((n=s.expires_at)!==null&&n!==void 0?n:1/0)*1e3-Date.now()<ls;if(this._debug(r,"session has".concat(o?"":" not"," expired with margin of ").concat(ls,"s")),o){if(this.autoRefreshToken&&s.refresh_token){let{error:a}=await this._callRefreshToken(s.refresh_token);a&&(console.error(a),fs(a)||(this._debug(r,"refresh failed with a non-retryable error, removing the session",a),await this._removeSession()))}}else if(s.user&&s.user.__isUserNotAvailableProxy===!0)try{let{data:a,error:i}=await this._getUser(s.access_token);!i&&a?.user?(s.user=a.user,await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)):this._debug(r,"could not get user data, skipping SIGNED_IN notification")}catch(a){console.error("Error getting user data:",a),this._debug(r,"error getting user data, skipping SIGNED_IN notification",a)}else await this._notifyAllSubscribers("SIGNED_IN",s)}catch(s){this._debug(r,"error",s),console.error(s);return}finally{this._debug(r,"end")}}async _callRefreshToken(t){var n,r;if(!t)throw new pe;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let s="#_callRefreshToken(".concat(t.substring(0,5),"...)");this._debug(s,"begin");try{this.refreshingDeferred=new cr;let{data:o,error:a}=await this._refreshAccessToken(t);if(a)throw a;if(!o.session)throw new pe;await this._saveSession(o.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",o.session);let i={data:o.session,error:null};return this.refreshingDeferred.resolve(i),i}catch(o){if(this._debug(s,"error",o),U(o)){let a={data:null,error:o};return fs(o)||await this._removeSession(),(n=this.refreshingDeferred)===null||n===void 0||n.resolve(a),a}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(o),o}finally{this.refreshingDeferred=null,this._debug(s,"end")}}async _notifyAllSubscribers(t,n,r=!0){let s="#_notifyAllSubscribers(".concat(t,")");this._debug(s,"begin",n,"broadcast = ".concat(r));try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:t,session:n});let o=[],a=Array.from(this.stateChangeEmitters.values()).map(async i=>{try{await i.callback(t,n)}catch(c){o.push(c)}});if(await Promise.all(a),o.length>0){for(let i=0;i<o.length;i+=1)console.error(o[i]);throw o[0]}}finally{this._debug(s,"end")}}async _saveSession(t){this._debug("#_saveSession()",t),this.suppressGetSessionWarning=!0,await _e(this.storage,"".concat(this.storageKey,"-code-verifier"));let n=Object.assign({},t),r=n.user&&n.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!r&&n.user&&await Vt(this.userStorage,this.storageKey+"-user",{user:n.user});let s=Object.assign({},n);delete s.user;let o=Oo(s);await Vt(this.storage,this.storageKey,o)}else{let s=Oo(n);await Vt(this.storage,this.storageKey,s)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await _e(this.storage,this.storageKey),await _e(this.storage,this.storageKey+"-code-verifier"),await _e(this.storage,this.storageKey+"-user"),this.userStorage&&await _e(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let t=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{t&&ke()&&globalThis?.removeEventListener&&globalThis.removeEventListener("visibilitychange",t)}catch(n){console.error("removing visibilitychange callback failed",n)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let t=setInterval(()=>this._autoRefreshTokenTick(),jt);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t);let n=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=n,n&&typeof n=="object"&&typeof n.unref=="function"?n.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(n)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t);let n=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,n&&clearTimeout(n)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let t=Date.now();try{return await this._useSession(async n=>{let{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}let s=Math.floor((r.expires_at*1e3-t)/jt);this._debug("#_autoRefreshTokenTick()","access token expires in ".concat(s," ticks, a tick lasts ").concat(jt,"ms, refresh threshold is ").concat(cs," ticks")),s<=cs&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof ur)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!ke()||!globalThis?.addEventListener)return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(t){this._debug("#visibilityChangedCallback","error",t)}},globalThis?.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){let n="#_onVisibilityChanged(".concat(t,")");this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>
4{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){let s=["provider=".concat(encodeURIComponent(n))];if(r?.redirectTo&&s.push("redirect_to=".concat(encodeURIComponent(r.redirectTo))),r?.scopes&&s.push("scopes=".concat(encodeURIComponent(r.scopes))),this.flowType==="pkce"){let[o,a]=await Yt(this.storage,this.storageKey),i=new URLSearchParams({code_challenge:"".concat(encodeURIComponent(o)),code_challenge_method:"".concat(encodeURIComponent(a))});s.push(i.toString())}if(r?.queryParams){let o=new URLSearchParams(r.queryParams);s.push(o.toString())}return r?.skipBrowserRedirect&&s.push("skip_http_redirect=".concat(r.skipBrowserRedirect)),"".concat(t,"?").concat(s.join("&"))}async _unenroll(t){try{return await this._useSession(async n=>{var r;let{data:s,error:o}=n;return o?this._returnResult({data:null,error:o}):await K(this.fetch,"DELETE","".concat(this.url,"/factors/").concat(t.factorId),{headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,s;let{data:o,error:a}=n;if(a)return this._returnResult({data:null,error:a});let i=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:t.factorType==="totp"?{issuer:t.issuer}:{}),{data:c,error:l}=await K(this.fetch,"POST","".concat(this.url,"/factors"),{body:i,headers:this.headers,jwt:(r=o?.session)===null||r===void 0?void 0:r.access_token});return l?this._returnResult({data:null,error:l}):(t.factorType==="totp"&&c.type==="totp"&&(!((s=c?.totp)===null||s===void 0)&&s.qr_code)&&(c.totp.qr_code="data:image/svg+xml;utf-8,".concat(c.totp.qr_code)),this._returnResult({data:c,error:null}))})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _verify(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;let{data:s,error:o}=n;if(o)return this._returnResult({data:null,error:o});let a=Object.assign({challenge_id:t.challengeId},"webauthn"in t?{webauthn:Object.assign(Object.assign({},t.webauthn),{credential_response:t.webauthn.type==="create"?Go(t.webauthn.credential_response):Ko(t.webauthn.credential_response)})}:{code:t.code}),{data:i,error:c}=await K(this.fetch,"POST","".concat(this.url,"/factors/").concat(t.factorId,"/verify"),{body:a,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});return c?this._returnResult({data:null,error:c}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+i.expires_in},i)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",i),this._returnResult({data:i,error:c}))})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}})}async _challenge(t){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async n=>{var r;let{data:s,error:o}=n;if(o)return this._returnResult({data:null,error:o});let a=await K(this.fetch,"POST","".concat(this.url,"/factors/").concat(t.factorId,"/challenge"),{body:t,headers:this.headers,jwt:(r=s?.session)===null||r===void 0?void 0:r.access_token});if(a.error)return a;let{data:i}=a;if(i.type!=="webauthn")return{data:i,error:null};switch(i.webauthn.type){case"create":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:zo(i.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},i),{webauthn:Object.assign(Object.assign({},i.webauthn),{credential_options:Object.assign(Object.assign({},i.webauthn.credential_options),{publicKey:Wo(i.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}})}async _challengeAndVerify(t){let{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?this._returnResult({data:null,error:r}):await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){var t;let{data:{user:n},error:r}=await this.getUser();if(r)return{data:null,error:r};let s={all:[],phone:[],totp:[],webauthn:[]};for(let o of(t=n?.factors)!==null&&t!==void 0?t:[])s.all.push(o),o.status==="verified"&&s[o.factor_type].push(o);return{data:s,error:null}}async _getAuthenticatorAssuranceLevel(t){var n,r,s,o;if(t)try{let{payload:h}=lr(t),p=null;h.aal&&(p=h.aal);let b=p,{data:{user:v},error:E}=await this.getUser(t);if(E)return this._returnResult({data:null,error:E});((r=(n=v?.factors)===null||n===void 0?void 0:n.filter(_=>_.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(b="aal2");let S=h.amr||[];return{data:{currentLevel:p,nextLevel:b,currentAuthenticationMethods:S},error:null}}catch(h){if(U(h))return this._returnResult({data:null,error:h});throw h}let{data:{session:a},error:i}
4=await this.getSession();if(i)return this._returnResult({data:null,error:i});if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:c}=lr(a.access_token),l=null;c.aal&&(l=c.aal);let m=l;((o=(s=a.user.factors)===null||s===void 0?void 0:s.filter(h=>h.status==="verified"))!==null&&o!==void 0?o:[]).length>0&&(m="aal2");let d=c.amr||[];return{data:{currentLevel:l,nextLevel:m,currentAuthenticationMethods:d},error:null}}async _getAuthorizationDetails(t){try{return await this._useSession(async n=>{let{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?await K(this.fetch,"GET","".concat(this.url,"/oauth/authorizations/").concat(t),{headers:this.headers,jwt:r.access_token,xform:o=>({data:o,error:null})}):this._returnResult({data:null,error:new pe})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _approveAuthorization(t,n){try{return await this._useSession(async r=>{let{data:{session:s},error:o}=r;if(o)return this._returnResult({data:null,error:o});if(!s)return this._returnResult({data:null,error:new pe});let a=await K(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(t,"/consent"),{headers:this.headers,jwt:s.access_token,body:{action:"approve"},xform:i=>({data:i,error:null})});return a.data&&a.data.redirect_url&&ke()&&!n?.skipBrowserRedirect&&globalThis.location.assign(a.data.redirect_url),a})}catch(r){if(U(r))return this._returnResult({data:null,error:r});throw r}}async _denyAuthorization(t,n){try{return await this._useSession(async r=>{let{data:{session:s},error:o}=r;if(o)return this._returnResult({data:null,error:o});if(!s)return this._returnResult({data:null,error:new pe});let a=await K(this.fetch,"POST","".concat(this.url,"/oauth/authorizations/").concat(t,"/consent"),{headers:this.headers,jwt:s.access_token,body:{action:"deny"},xform:i=>({data:i,error:null})});return a.data&&a.data.redirect_url&&ke()&&!n?.skipBrowserRedirect&&globalThis.location.assign(a.data.redirect_url),a})}catch(r){if(U(r))return this._returnResult({data:null,error:r});throw r}}async _listOAuthGrants(){try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;return r?this._returnResult({data:null,error:r}):n?await K(this.fetch,"GET","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:n.access_token,xform:s=>({data:s,error:null})}):this._returnResult({data:null,error:new pe})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _revokeOAuthGrant(t){try{return await this._useSession(async n=>{let{data:{session:r},error:s}=n;return s?this._returnResult({data:null,error:s}):r?(await K(this.fetch,"DELETE","".concat(this.url,"/user/oauth/grants"),{headers:this.headers,jwt:r.access_token,query:{client_id:t.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new pe})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(i=>i.kid===t);if(r)return r;let s=Date.now();if(r=this.jwks.keys.find(i=>i.kid===t),r&&this.jwks_cached_at+Yl>s)return r;let{data:o,error:a}=await K(this.fetch,"GET","".concat(this.url,"/.well-known/jwks.json"),{headers:this.headers});if(a)throw a;return!o.keys||o.keys.length===0||(this.jwks=o,this.jwks_cached_at=s,r=o.keys.find(i=>i.kid===t),!r)?null:r}async getClaims(t,n={}){try{let r=t;if(!r){let{data:h,error:p}
4=await this.getSession();if(p||!h.session)return this._returnResult({data:null,error:p});r=h.session.access_token}let{header:s,payload:o,signature:a,raw:{header:i,payload:c}}=lr(r);n?.allowExpired||lu(o.exp);let l=!s.alg||s.alg.startsWith("HS")||!s.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(s.kid,n?.keys?{keys:n.keys}:n?.jwks);if(!l){let{error:h}=await this.getUser(r);if(h)throw h;return{data:{claims:o,header:s,signature:a},error:null}}let m=uu(s.alg),u=await crypto.subtle.importKey("jwk",l,m,!0,["verify"]);if(!await crypto.subtle.verify(m,u,a,tu("".concat(i,".").concat(c))))throw new Gt("Invalid JWT signature");return{data:{claims:o,header:s,signature:a},error:null}}catch(r){if(U(r))return this._returnResult({data:null,error:r});throw r}}async signInWithPasskey(t){var n,r,s;He(this.experimental);try{if(!fr())return this._returnResult({data:null,error:new Pe("Browser does not support WebAuthn",null)});let{data:o,error:a}=await this._startPasskeyAuthentication({options:{captchaToken:(n=t?.options)===null||n===void 0?void 0:n.captchaToken}});if(a||!o)return this._returnResult({data:null,error:a});let i=Wo(o.options),c=(s=(r=t?.options)===null||r===void 0?void 0:r.signal)!==null&&s!==void 0?s:Ss.createNewAbortSignal(),{data:l,error:m}=await Yo({publicKey:i,signal:c});if(m||!l)return this._returnResult({data:null,error:m??new Pe("WebAuthn ceremony failed",null)});let u=Ko(l);return this._verifyPasskeyAuthentication({challengeId:o.challenge_id,credential:u})}catch(o){if(U(o))return this._returnResult({data:null,error:o});throw o}}async registerPasskey(t){var n,r;He(this.experimental);try{if(!fr())return this._returnResult({data:null,error:new Pe("Browser does not support WebAuthn",null)});let{data:s,error:o}=await this._startPasskeyRegistration();if(o||!s)return this._returnResult({data:null,error:o});let a=zo(s.options),i=(r=(n=t?.options)===null||n===void 0?void 0:n.signal)!==null&&r!==void 0?r:Ss.createNewAbortSignal(),{data:c,error:l}=await Vo({publicKey:a,signal:i});if(l||!c)return this._returnResult({data:null,error:l??new Pe("WebAuthn ceremony failed",null)});let m=Go(c);return this._verifyPasskeyRegistration({challengeId:s.challenge_id,credential:m})}catch(s){if(U(s))return this._returnResult({data:null,error:s});throw s}}async _startPasskeyRegistration(){He(this.experimental);try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new pe});let{data:s,error:o}=await K(this.fetch,"POST","".concat(this.url,"/passkeys/registration/options"),{headers:this.headers,jwt:n.access_token,body:{}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:s,error:null})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _verifyPasskeyRegistration(t){He(this.experimental);try{return await this._useSession(async n=>{let{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new pe});let{data:o,error:a}=await K(this.fetch,"POST","".concat(this.url,"/passkeys/registration/verify"),{headers:this.headers,jwt:r.access_token,body:{challenge_id:t.challengeId,credential:t.credential}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:o,error:null})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _startPasskeyAuthentication(t){var n;He(this.experimental);try{let{data:r,error:s}=await K(this.fetch,"POST","".concat(this.url,"/passkeys/authentication/options"),{headers:this.headers,body:{gotrue_meta_security:{captcha_token:(n=t?.options)===null||n===void 0?void 0:n.captchaToken}}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:r,error:null})}catch(r){if(U(r))return this._returnResult({data:null,error:r});throw r}}async _verifyPasskeyAuthentication(t){He(this.experimental);try{let{data:n,error:r}=await K(this.fetch,"POST","".concat(this.url,"/passkeys/authentication/verify"),{headers:this.headers,body:{challenge_id:t.challengeId,credential:t.credential},xform:$e});return r?this._returnResult({data:null,error:r}):(n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers("SIGNED_IN",n.session)),this._returnResult({data:n,error:null}))}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _listPasskeys(){He(this.experimental);try{return await this._useSession(async t=>{let{data:{session:n},error:r}=t;if(r)return this._returnResult({data:null,error:r});if(!n)return this._returnResult({data:null,error:new pe});let{data:s,error:o}=await K(this.fetch,"GET","".concat(this.url,"/passkeys"),{headers:this.headers,jwt:n.access_token,xform:a=>({data:a,error:null})});return o?this._returnResult({data:null,error:o}):this._returnResult({data:s,error:null})})}catch(t){if(U(t))return this._returnResult({data:null,error:t});throw t}}async _updatePasskey(t){He(this.experimental);try{return await this._useSession(async n=>{let{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new pe});let{data:o,error:a}=await K(this.fetch,"PATCH","".concat(this.url,"/passkeys/").concat(t.passkeyId),{headers:this.headers,jwt:r.access_token,body:{friendly_name:t.friendlyName}});return a?this._returnResult({data:null,error:a}):this._returnResult({data:o,error:null})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}async _deletePasskey(t){He(this.experimental);try{return await this._useSession(async n=>{let{data:{session:r},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!r)return this._returnResult({data:null,error:new pe});let{error:o}
4=await K(this.fetch,"DELETE","".concat(this.url,"/passkeys/").concat(t.passkeyId),{headers:this.headers,jwt:r.access_token,noResolveJson:!0});return o?this._returnResult({data:null,error:o}):this._returnResult({data:null,error:null})})}catch(n){if(U(n))return this._returnResult({data:null,error:n});throw n}}};ks.nextInstanceID={};var vs=ks;function Pg(e,t){let n=e&&typeof e=="object"?e:{};return String(n.code||n.error_code||n.name||t).trim().toLowerCase()}function Ig(e){let t=e&&typeof e=="object"?e:{},n=t.cause&&typeof t.cause=="object"?t.cause:{};return[t.code,t.error_code,t.name,t.message,n.code,n.error_code,n.name,n.message].map(r=>String(r||"").trim().toLowerCase()).filter(Boolean).join(" ")}function ve(e){let t=e&&typeof e=="object"?e:{},n=Number(t.status||t.statusCode||0);return Number.isFinite(n)&&n>0?n:503}function ye(e,t){let n=Pg(e,t),r="".concat(n," ").concat(Ig(e));return/error_ceremony_aborted|aborterror|\babort\b|\bcancelled\b/.test(r)?{code:"cancelled",message:"The passkey request was cancelled. You can try again."}:/notallowederror/.test(r)?{code:"passkey_not_completed",message:"Your device did not complete the passkey request. It may have timed out, been dismissed, or been blocked by browser settings."}:/too_many_passkeys/.test(r)?{code:"passkey_limit_reached",message:"This account has reached its passkey limit. Remove an unused passkey before adding another."}:/webauthn_credential_not_found/.test(r)?{code:"passkey_not_found",message:"That passkey is no longer registered. Refresh your passkey list and try again."}:/webauthn_challenge_expired|webauthn_challenge_not_found|mfa_challenge_expired|challenge_expired/.test(r)?{code:"challenge_expired",message:"That challenge expired. Start a fresh challenge and try again."}:/webauthn_verification_failed|mfa_verification_failed|mfa_verification_rejected/.test(r)?{code:"passkey_verification_failed",message:"Your passkey could not be verified. Try again or use another sign-in method."}:/error_invalid_domain|error_invalid_rp_id|securityerror/.test(r)?{code:"passkey_configuration_error",message:"Passkeys are temporarily unavailable because this site is not configured correctly. Use another sign-in method."}:/error_authenticator_missing_discoverable_credential_support|error_authenticator_missing_user_verification_support|error_authenticator_no_supported_pubkeycredparams_alg|notsupportederror|constrainterror/.test(r)?{code:"passkey_authenticator_unsupported",message:"This authenticator cannot create or use the required passkey. Try another device, password manager, or security key."}:/email_not_confirmed|phone_not_confirmed/.test(r)?{code:"account_not_confirmed",message:"Confirm your account email or phone before using a passkey."}:/user_banned/.test(r)?{code:"account_unavailable",message:"This account cannot sign in. Contact support if you think this is a mistake."}:/user_sso_managed|anonymous/.test(r)?{code:"passkey_account_unsupported",message:"Passkeys cannot be added to this account type. Use its existing sign-in provider."}:/reauthentication_needed|reauthentication_not_valid|insufficient_aal/.test(r)?{code:"reauthentication_required",message:"Sign in again and complete any required verification before changing passkeys."}:/too_many_enrolled_mfa_factors/.test(r)?{code:"mfa_setup_incomplete",message:"Finish or cancel an incomplete authenticator setup before adding another one."}:/mfa_verified_factor_exists/.test(r)?{code:"mfa_already_enabled",message:"Two-factor authentication is already active. Use or manage your existing authenticator."}:/webauthn_credential_exists|duplicate|already|factor_name_conflict|authenticator_previously_registered|invalidstate|conflict/.test(r)?{code:"duplicate",message:"That authenticator is already registered."}:/passkey_disabled|disabled|experimental|not.?enabled|not.?available/.test(r)?{code:"passkey_disabled",message:"Passkeys are not available on this server. Use another sign-in method."}:/network|fetch|timeout|offline/.test(r)?{code:"network_error",message:"Could not reach account security. Check your connection and try again."}:{code:n,message:t}}function Bt(){return{ok:!1,status:401,error:{code:"not_authenticated",message:"Sign in again to continue."}}}function vu(){return{ok:!1,status:422,error:{code:"passkey_unsupported",message:"Passkeys are not supported by this browser. Use another sign-in method."}}}function Xo(){return{ok:!1,status:503,error:{code:"passkey_management_unavailable",message:"Passkey management is temporarily unavailable. Try again later."}}}function Ng(e=globalThis){try{return!!(e.parent&&e.parent!==e)}catch{return!0}}function Lg(e=globalThis){let t=e.navigator?.credentials;return!!(!Ng(e)&&e.isSecureContext===!0&&e.PublicKeyCredential&&typeof t?.create=="function"&&typeof t?.get=="function")}function _u(e){let t=null,n="";function r(){let S=e.config();return S?(t||(t=(e.createClient||(w=>({auth:new vs({url:"".concat(w.url.replace(/\/+$/,""),"/auth/v1"),headers:{Authorization:"Bearer ".concat(w.anonKey),apikey:w.anonKey},persistSession:!1,autoRefreshToken:!1,fetch:e.fetch,detectSessionInUrl:!1,experimental:{passkey:!0}})})))(S)),t):null}async function s(){let S=r();if(!S)return{instance:null,session:null};let _=await e.getSession();if(!_?.access_token||!_.refresh_token)return{instance:S,session:null};if(_.access_token!==n){let{error:w}=await S.auth.setSession({access_token:_.access_token,refresh_token:_.refresh_token});if(w)return{instance:S,session:null};n=_.access_token}return{instance:S,session:_}}function o(S){let _=S&&typeof S=="object"?S:{},w=_.session&&typeof _.session=="object"?_.session:_;return w.access_token&&w.refresh_token?(n=String(w.access_token),e.adoptSession(w)):null}async function a(){let{instance:S,session:_}=await s();
4if(!S||!_)return{ok:!1,factors:[],verifiedFactors:[],currentLevel:null,nextLevel:null,required:!0,error:{code:"mfa_state_unavailable",message:"Could not verify your two-factor security status. Try again before accessing account data."}};try{let[w,f]=await Promise.all([S.auth.mfa.listFactors(),S.auth.mfa.getAuthenticatorAssuranceLevel()]);if(w.error||f.error){let N=w.error||f.error;return{ok:!1,factors:[],verifiedFactors:[],currentLevel:null,nextLevel:null,required:!0,error:ye(N,"Could not verify your two-factor security status. Try again before accessing account data.")}}let g=(w.data?.all||[]).filter(N=>N.factor_type==="totp"),C=g.filter(N=>N.status==="verified"),T=f.data?.currentLevel||null,x=f.data?.nextLevel||null;return{ok:!0,factors:g,verifiedFactors:C,currentLevel:T,nextLevel:x,required:C.length>0&&T!=="aal2"}}catch(w){return{ok:!1,factors:[],verifiedFactors:[],currentLevel:null,nextLevel:null,required:!0,error:ye(w,"Could not verify your two-factor security status. Try again before accessing account data.")}}}async function i(S){let{instance:_,session:w}=await s();if(!_||!w)return Bt();try{let{data:f,error:g}=await _.auth.mfa.enroll({factorType:"totp",friendlyName:S.trim().slice(0,120)||"Authenticator app"});return g||!f?.id||!f.totp?.secret?{ok:!1,status:ve(g),error:ye(g,"Could not start two-factor setup. Try again.")}:{ok:!0,status:200,data:{factor:{id:f.id,friendly_name:f.friendly_name,factor_type:"totp",status:"unverified"},qrCode:f.totp.qr_code,secret:f.totp.secret,uri:f.totp.uri}}}catch(f){return{ok:!1,status:ve(f),error:ye(f,"Could not start two-factor setup. Try again.")}}}async function c(S){let{instance:_,session:w}=await s();if(!_||!w)return Bt();try{let{data:f,error:g}=await _.auth.mfa.challenge({factorId:S});return g||!f?.id?{ok:!1,status:ve(g),error:ye(g,"Could not start a two-factor challenge. Try again.")}:{ok:!0,status:200,data:{id:f.id}}}catch(f){return{ok:!1,status:ve(f),error:ye(f,"Could not start a two-factor challenge. Try again.")}}}async function l(S,_,w){let{instance:f,session:g}=await s();if(!f||!g)return Bt();try{let{data:C,error:T}=await f.auth.mfa.verify({factorId:S,challengeId:_,code:w});return T||!C?.access_token?{ok:!1,status:ve(T),error:ye(T,"That code was not accepted. Check it and try a fresh challenge.")}:(o(C),{ok:!0,status:200})}catch(C){return{ok:!1,status:ve(C),error:ye(C,"That code was not accepted. Check it and try a fresh challenge.")}}}async function m(S,_=!1){let w=await a();if(!w.ok)return{ok:!1,status:503,error:w.error};let f=w.factors.find(T=>T.id===S);if(!f)return{ok:!1,status:404,error:{code:"factor_not_found",message:"That authenticator is no longer available. Refresh the list."}};if(f.status==="verified"){if(w.currentLevel!=="aal2")return{ok:!1,status:403,error:{code:"mfa_aal2_required",message:"Complete two-factor verification before changing your authenticators."}};if(w.verifiedFactors.length===1&&!_)return{ok:!1,status:409,error:{code:"mfa_disable_confirmation_required",message:"Confirm that you want to disable two-factor authentication before removing your final authenticator."}}}let{instance:g,session:C}=await s();if(!g||!C)return Bt();try{let{error:T}=await g.auth.mfa.unenroll({factorId:S});return T?{ok:!1,status:ve(T),error:ye(T,"Could not remove that authenticator. Try again.")}:{ok:!0,status:200}}catch(T){return{ok:!1,status:ve(T),error:ye(T,"Could not remove that authenticator. Try again.")}}}function u(){let S=r();return!!(S&&S.auth.passkey&&typeof S.auth.passkey.list=="function"&&typeof S.auth.passkey.update=="function"&&typeof S.auth.passkey.delete=="function")}function d(){let S=r();return!!(S&&Lg(e.global)&&typeof S.auth.signInWithPasskey=="function"&&typeof S.auth.registerPasskey=="function")}function h(S){if(!Array.isArray(S))return[];let _=new Set,w=[];for(let f of S){let g=f&&typeof f=="object"?f:null,C=String(g?.id||"").trim();if(!C||_.has(C))continue;_.add(C);let T=String(g?.friendly_name||"").trim().replace(/\s+/g," ").slice(0,120),x=String(g?.created_at||"").trim(),N=String(g?.last_used_at||"").trim();w.push({id:C,...T?{friendly_name:T}:{},...x?{created_at:x}:{}
4,...N?{last_used_at:N}:{}})}return w}async function p(S,_=()=>!0){let w=r();if(!d()||!w)return vu();try{let{data:f,error:g}=await w.auth.signInWithPasskey({options:{signal:S}});return g||!f?.session?{ok:!1,status:ve(g),error:ye(g,"Could not sign in with a passkey. Use another sign-in method.")}:S?.aborted||!_()?{ok:!1,status:409,error:{code:"passkey_superseded",message:"A newer sign-in request replaced this passkey request."}}:(o(f),{ok:!0,status:200})}catch(f){return{ok:!1,status:ve(f),error:ye(f,"Could not sign in with a passkey. Use another sign-in method.")}}}async function b(S){if(!d())return vu();let{instance:_,session:w}=await s();if(!_||!w)return Bt();try{let{data:f,error:g}=await _.auth.registerPasskey({options:{signal:S}});return g||!f?.id?{ok:!1,status:ve(g),error:ye(g,"Could not add a passkey. Try again or use another authenticator.")}:{ok:!0,status:200,data:h([f])[0]}}catch(f){return{ok:!1,status:ve(f),error:ye(f,"Could not add a passkey. Try again or use another authenticator.")}}}async function v(){if(!u())return Xo();let{instance:S,session:_}=await s();if(!S||!_)return Bt();try{let{data:w,error:f}=await S.auth.passkey.list();return f?{ok:!1,status:ve(f),error:ye(f,"Could not load passkeys. Try again.")}:{ok:!0,status:200,data:h(w)}}catch(w){return{ok:!1,status:ve(w),error:ye(w,"Could not load passkeys. Try again.")}}}async function E(S,_){if(!u())return Xo();let w=String(S||"").trim(),f=String(_||"").trim().replace(/\s+/g," ").slice(0,120);if(!w||!f)return{ok:!1,status:400,error:{code:"passkey_name_required",message:"Enter a name for this passkey."}};let{instance:g,session:C}=await s();if(!g||!C)return Bt();try{let{error:T}=await g.auth.passkey.update({passkeyId:w,friendlyName:f});return T?{ok:!1,status:ve(T),error:ye(T,"Could not rename that passkey. Try again.")}:{ok:!0,status:200}}catch(T){return{ok:!1,status:ve(T),error:ye(T,"Could not rename that passkey. Try again.")}}}async function A(S,_){if(!u())return Xo();let w=String(S||"").trim();if(!w)return{ok:!1,status:400,error:{code:"passkey_not_found",message:"That passkey could not be identified. Refresh the list and try again."}};if(!_)return{ok:!1,status:409,error:{code:"passkey_recovery_required",message:"Add and verify an independent recovery sign-in method before removing passkeys."}};let{instance:f,session:g}=await s();if(!f||!g)return Bt();try{let[C,T]=await Promise.all([f.auth.passkey.list(),f.auth.mfa.getAuthenticatorAssuranceLevel()]);if(C.error)return{ok:!1,status:ve(C.error),error:ye(C.error,"Could not verify that passkey. Refresh and try again.")};if(T.error||!T.data?.currentLevel||!T.data?.nextLevel)return{ok:!1,status:503,error:{code:"passkey_aal_unavailable",message:"Could not verify your security level. Try again before removing a passkey."}};if(T.data.nextLevel==="aal2"&&T.data.currentLevel!=="aal2")return{ok:!1,status:403,error:{code:"passkey_aal2_required",message:"Complete two-factor verification before removing a passkey."}};if(!h(C.data).some(N=>N.id===w))return{ok:!1,status:404,error:{code:"passkey_not_found",message:"That passkey is no longer registered. Refresh the list and try again."}};let{error:x}=await f.auth.passkey.delete({passkeyId:w});return x?{ok:!1,status:ve(x),error:ye(x,"Could not remove that passkey. Refresh and try again.")}:{ok:!0,status:200}}catch(C){return{ok:!1,status:ve(C),error:ye(C,"Could not remove that passkey. Refresh and try again.")}}}return{getMfaState:a,enrollTotp:i,challengeTotp:c,verifyTotp:l,unenrollTotp:m,passkeyAvailable:d,passkeyManagementAvailable:u,signInWithPasskey:p,registerPasskey:b,listPasskeys:v,renamePasskey:E,deletePasskey:A}}var Mg=60,Bg=12e3,Og=12e3,Jo="beamo_auth_state",Qo="beamo-auth-redirect-intents",Dg=1800,Cu=8;function _s(){return Math.floor(Date.now()/1e3)}function Au(e){return e?.config?.storageKeys?.supabaseSession||"beamo-supabase-session"}function Hg(e){let t=e?.user_metadata||{};return String(t.display_name||t.full_name||t.name||"").trim()}function $g(e){return(Array.isArray(e?.identities)?e.identities:[]).map(n=>String(n?.provider||"")).filter(Boolean)}function Eu(e,t=globalThis){let n=()=>An(t),r=null,s=null,o=0;function a(){return o+=1,o}
4function i(){try{let y=t.localStorage?.getItem(Qo),k=y?JSON.parse(y):[];if(!Array.isArray(k))return[];let P=_s();return k.filter(R=>typeof R?.state=="string"&&R.state.length>=32&&typeof R?.kind=="string"&&Number(R?.expiresAt)>=P).slice(-Cu)}catch{return[]}}function c(y){try{let k=t.localStorage;return k?(k.setItem(Qo,JSON.stringify(y.slice(-Cu))),k.getItem(Qo)!==null):!1}catch{return!1}}function l(){let y=new Uint8Array(32),k=t.crypto||globalThis.crypto;return k?.getRandomValues?(k.getRandomValues(y),Array.from(y,P=>P.toString(16).padStart(2,"0")).join("")):""}function m(y,k){let P=l();if(!P)return null;let R;try{let L=String(t.location?.origin||t.location?.href||"");R=L?new URL(k,L):new URL(k)}catch{return null}R.searchParams.set(Jo,P);let D=i();return D.push({state:P,kind:String(y||"auth").slice(0,32),expiresAt:_s()+Dg}),c(D)?R.toString():null}function u(y){switch(y){case"signup":return"signup";case"recovery":return"recovery";case"email_change":return"email_change";case"magiclink":return"email";case"":return"oauth";default:return""}}function d(y,k){let P=i(),R=P.find(L=>L.state===y&&(L.kind===k||k==="oauth"&&L.kind.startsWith("oauth:"))),D=P.filter(L=>L.state!==y);return R?c(D):!1}function h(){return{ok:!1,status:503,error:{code:"auth_storage_unavailable",message:"Secure sign-in could not start in this browser. Enable site storage and try again."}}}function p(){return e?.config?.timeouts?.accountAuthMs||Bg}function b(){return e?.config?.timeouts?.accountSyncMs||Og}async function v(y,k,P){try{if(typeof e?.fetchWithTimeout=="function")return await e.fetchWithTimeout(y,k,P);if(typeof t.fetch!="function")throw new Error("fetch_unavailable");let R=typeof t.AbortController=="function"?new t.AbortController:null,D=R?t.setTimeout(()=>R.abort(),P):null;try{return await t.fetch(y,R?{...k,signal:R.signal}:k)}finally{D&&t.clearTimeout(D)}}catch(R){if(typeof t.Response=="function"){let D=R?.name==="AbortError"?"request_timeout":"network_error",L=D==="request_timeout"?"The request timed out. Check your connection and try again.":"Could not reach your account. Check your connection and try again.";return new t.Response(JSON.stringify({error:{code:D,message:L},message:L,msg:L}),{status:503,headers:{"Content-Type":"application/json"}})}throw R}}function E(){try{let y=t.localStorage?.getItem(Au(e));if(!y)return null;let k=JSON.parse(y);return!k?.access_token||!k?.refresh_token||!k?.user?.id?null:k}catch{return null}}function A(y){try{let k=Au(e);if(!y){t.localStorage?.removeItem(k);return}t.localStorage?.setItem(k,JSON.stringify(y))}catch{}}function S(y,k){return!!(y&&k&&y.access_token===k.access_token&&y.refresh_token===k.refresh_token)}function _(y,k=null){if(!y?.access_token)return null;let P=Number(y.expires_at)||_s()+(Number(y.expires_in)||3600);return{access_token:y.access_token,refresh_token:y.refresh_token||"",token_type:y.token_type||"bearer",expires_at:P,user:y.user||k||null}}function w(y){let k=_(y,y?.user||null);return k&&A(k),k}function f(y={}){let k=n();return{apikey:k.anonKey,Authorization:"Bearer ".concat(k.anonKey),...y}}function g(y,k={}){return{apikey:n().anonKey,Authorization:"Bearer ".concat(y),...k}}async function C(y){let k=n();if(!k)return null;try{let P=await v("".concat(k.url,"/auth/v1/user"),{method:"GET",headers:g(y)},p());return P.ok?await P.json().catch(()=>null):null}catch{return null}}async function T(y){let k=n();if(!k||!y?.refresh_token)return A(null),null;try{let P=await v("".concat(k.url,"/auth/v1/token?grant_type=refresh_token"),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({refresh_token:y.refresh_token})},p());if(!P.ok){let $=E();return S($,y)?P.status===408||P.status===429||P.status>=500?y:(A(null),null):$}let R=await P.json().catch(()=>null),D=_(R,y.user),L=E();return S(L,y)?D?(A(D),D):(A(null),null):L}catch{let P=E();return S(P,y)?y:P}}async function x(){let y=E();return y?(y.expires_at||0)-_s()>Mg?y:(r||(r=T(y).finally(()=>{r=null})),r):null}function N(){return s||(s=_u({config:n,global:t,getSession:x,adoptSession:w,fetch:(y,k)=>v(String(y),k,p())})),s}async function B(){return(await x())?.access_token||null}function I(y,k,P="auth_error"){let R=String(y?.error_code||y?.code||y?.error||"").trim()||P,D=Array.isArray(y?.weak_password?.reasons)?y.weak_password.reasons:[];if(R==="weak_password"||D.length>
40){let J="Choose a stronger password.";return D.includes("pwned")?J="This password has appeared in a known data breach. Please choose a different one.":D.includes("length")?J="This password is too short. Use a longer one.":D.includes("characters")&&(J="Password must include at least one letter and one number."),{code:"weak_password",message:J}}let L={invalid_grant:"Invalid email or password.",invalid_credentials:"Invalid email or password.",email_exists:"An account with this email already exists. Try signing in instead.",user_already_exists:"An account with this email already exists. Try signing in instead.",email_not_confirmed:"Confirm your email first \u2014 check your inbox for the link we sent.",same_password:"Your new password must be different from your current one.",otp_expired:"That code has expired. Request a new one.",otp_disabled:"Email codes are not enabled for this account.",over_email_send_rate_limit:"Too many emails sent. Wait a minute, then try again.",email_address_invalid:"Enter a valid email address.",reauthentication_needed:"For your security, sign in again before making this change."},$=R==="invalid_grant"?"invalid_credentials":R,G=String(L[R]||y?.error_description||y?.msg||y?.message||(k===400?"Invalid email or password.":"Something went wrong. Please try again."));return{code:$,message:G}}return{isConfigured(){return n()!==null},config(){return n()},async getSession(){return x()},adoptSession:w,async getMfaState(){return N().getMfaState()},async enrollTotp(y){return N().enrollTotp(y)},async challengeTotp(y){return N().challengeTotp(y)},async verifyTotp(y,k,P){return N().verifyTotp(y,k,P)},async unenrollTotp(y,k=!1){return N().unenrollTotp(y,k)},async getEmailMfaState(){let y=await x();if(!y)return{ok:!1,status:401,data:null};let k=n(),P=await v("".concat(k.url,"/rest/v1/rpc/beamo_email_mfa_status"),{method:"POST",headers:g(y.access_token,{"Content-Type":"application/json",Accept:"application/json"}),body:"{}"},b()),R=await P.json().catch(()=>null);return{ok:P.ok,status:P.status,data:R}},async emailMfaRequest(y,k={}){let P=await x();if(!P)return{ok:!1,status:401,data:{error:{code:"signed_out",message:"Sign in again to continue."}}};let R=e?.config?.endpoints?.emailMfa||"/PHP/email_mfa.php",D=await v(R,{method:"POST",headers:{Authorization:"Bearer ".concat(P.access_token),"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({action:y,...k})},p()),L=await D.json().catch(()=>null);return{ok:D.ok,status:D.status,data:L}},async refreshAuthSession(){let y=E();if(!y)return{ok:!1,status:401,session:null};let k=await T(y);return{ok:!!k,status:k?200:401,session:k}},passkeysSupported(){return N().passkeyAvailable()},passkeyManagementSupported(){return N().passkeyManagementAvailable()},async signInWithPasskey(y){let k=a();return N().signInWithPasskey(y,()=>k===o)},async registerPasskey(y){return N().registerPasskey(y)},async listPasskeys(){return N().listPasskeys()},async renamePasskey(y,k){return N().renamePasskey(y,k)},async deletePasskey(y,k){return N().deletePasskey(y,k)},async getUser(){return(await x())?.user||null},peekUser(){return E()?.user||null},async signUp({email:y,password:k,displayName:P="",redirectTo:R}={}){let D=a(),L=n(),$=R?m("signup",R):"";if(R&&!$)return h();let G=$?"?redirect_to=".concat(encodeURIComponent($)):"",J={email:y,password:k},X=String(P||"").trim();X&&(J.data={display_name:X,full_name:X});let W=await v("".concat(L.url,"/auth/v1/signup").concat(G),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify(J)},p()),V=await W.json().catch(()=>null);if(!W.ok)return{ok:!1,status:W.status,error:I(V,W.status,"signup_failed")};let j=V?.access_token?V:V?.session?.access_token?V.session:null;if(j?.access_token){if(D!==o)return{ok:!1,status:409,error:{code:"auth_superseded",message:"A newer sign-in request replaced this request."}};let ee=_(j,V?.user||j.user);return A(ee),{ok:!0,status:W.status,session:ee,user:ee?.user||null}}return{ok:!0,status:W.status,session:null,user:V?.user||V||null}},async signInWithPassword({email:y,password:k}={}){let P=a(),R=n(),D=await v("".concat(R.url,"/auth/v1/token?grant_type=password"),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({email:y,password:k})},p()),L=await D.json().catch(()=>null);if(!D.ok||!L?.access_token)return{ok:!1,status:D.status,error:I(L,D.status,"invalid_credentials")};if(P!==o)return{ok:!1,status:409,error:{code:"auth_superseded",message:"A newer sign-in request replaced this request."}};let $=_(L,L.user);return A($),{ok:!0,status:D.status,session:$}},oauthSignInUrl(y,k){let P=n();if(!P)return"#";let R=new URLSearchParams({provider:y});if(k){let D=m("oauth:".concat(y),k);if(!D)return"#";R.set("redirect_to",D)}return"".concat(P.url,"/auth/v1/authorize?").concat(R.toString())},async signOut({scope:y="local"}={}){let k=n(),P=E();if(y!=="others"&&A(null),!P?.access_token)return{ok:!0};try{let R=await v("".concat(k.url,"/auth/v1/logout?scope=").concat(encodeURIComponent(y)),{method:"POST",headers:g(P.access_token)},p());if(!R.ok)return y==="local"?{ok:!0}:{ok:!1,status:R.status}}catch{return y==="local"?{ok:!0}:{ok:!1,status:0}}return{ok:!0}},async resetPasswordForEmail(y,{redirectTo:k}={}){let P=n(),R=k?m("recovery",k):"";if(k&&!R)return h();let D=R?"?redirect_to=".concat(encodeURIComponent(R)):"",L=await v("".concat(P.url,"/auth/v1/recover").concat(D),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({email:y})},p());return{ok:L.ok,status:L.status}},async resendVerification(y,{redirectTo:k}={}){let P=n(),R=k?m("signup",k):"";if(k&&!R)return h();let D=R?"?redirect_to=".concat(encodeURIComponent(R)):"",L=await v("".concat(P.url,"/auth/v1/resend").concat(D),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({type:"signup",email:y})},p()),$=L.ok?null:await L.json().catch(()=>null);
4return{ok:L.ok,status:L.status,error:L.ok?null:I($,L.status)}},async updatePassword(y){let k=await B();if(!k)return{ok:!1,status:401,error:{code:"not_authenticated",message:"Your reset link has expired. Request a new one."}};let P=n(),R=await v("".concat(P.url,"/auth/v1/user"),{method:"PUT",headers:g(k,{"Content-Type":"application/json"}),body:JSON.stringify({password:y})},p()),D=await R.json().catch(()=>null);if(!R.ok)return{ok:!1,status:R.status,error:I(D,R.status,"password_update_failed")};let L=E();return L&&D?.id&&(L.user=D,A(L)),{ok:!0,status:R.status,user:D}},async updateEmail(y,{redirectTo:k}={}){let P=await B();if(!P)return{ok:!1,status:401,error:{code:"not_authenticated",message:"Sign in again to change your email."}};let R=n(),D=k?m("email_change",k):"";if(k&&!D)return h();let L=D?"?redirect_to=".concat(encodeURIComponent(D)):"",$=await v("".concat(R.url,"/auth/v1/user").concat(L),{method:"PUT",headers:g(P,{"Content-Type":"application/json"}),body:JSON.stringify({email:y})},p()),G=await $.json().catch(()=>null);if(!$.ok)return{ok:!1,status:$.status,error:I(G,$.status,"email_update_failed")};let J=E();return J&&G?.id&&(J.user=G,A(J)),{ok:!0,status:$.status,user:G}},async updateDisplayName(y){let k=await B();if(!k)return{ok:!1,status:401,error:{code:"not_authenticated",message:"Sign in again to update your profile."}};let P=n(),R=String(y||"").trim(),D=await v("".concat(P.url,"/auth/v1/user"),{method:"PUT",headers:g(k,{"Content-Type":"application/json"}),body:JSON.stringify({data:{display_name:R,full_name:R}})},p()),L=await D.json().catch(()=>null);if(!D.ok)return{ok:!1,status:D.status,error:I(L,D.status,"profile_update_failed")};let $=E();return $&&L?.id&&($.user=L,A($)),{ok:!0,status:D.status,user:L}},async signInWithOtp(y,{redirectTo:k,shouldCreateUser:P=!1}={}){a();let R=n(),D=k?m("email",k):"";if(k&&!D)return h();let L=D?"?redirect_to=".concat(encodeURIComponent(D)):"",$=await v("".concat(R.url,"/auth/v1/otp").concat(L),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({email:y,create_user:P})},p());if(!$.ok){let G=await $.json().catch(()=>null);return{ok:!1,status:$.status,error:I(G,$.status,"otp_send_failed")}}return{ok:!0,status:$.status}},async verifyOtp({email:y,token:k,type:P="email"}={}){let R=a(),D=n(),L=await v("".concat(D.url,"/auth/v1/verify"),{method:"POST",headers:f({"Content-Type":"application/json"}),body:JSON.stringify({email:y,token:k,type:P})},p()),$=await L.json().catch(()=>null);if(!L.ok||!$?.access_token)return{ok:!1,status:L.status,error:I($,L.status,"otp_invalid")};if(R!==o)return{ok:!1,status:409,error:{code:"auth_superseded",message:"A newer sign-in request replaced this request."}};let G=_($,$.user);return A(G),{ok:!0,status:L.status,session:G}},async handleRedirectCallback(){let y=String(t.location?.hash||"").replace(/^#/,"");if(!y)return{handled:!1};let k;try{k=new URLSearchParams(y)}catch{return{handled:!1}}let P=()=>{try{let{pathname:X="",search:W=""}=t.location||{},V=new URLSearchParams(String(W||"").replace(/^\?/,""));V.delete(Jo);let j=V.toString();t.history?.replaceState?.({},"","".concat(X).concat(j?"?".concat(j):""))}catch{}};if(k.get("error")||k.get("error_description")){let X=k.get("error_description")||k.get("error")||"oauth_error";return P(),{handled:!1,error:X,type:k.get("error_code")||"error"}}let R=k.get("access_token");if(!R)return{handled:!1};let D=new URLSearchParams(String(t.location?.search||"").replace(/^\?/,"")).get(Jo)||"",L=u(k.get("type")||"");if(!D||!L||!d(D,L))return P(),{handled:!1,error:"auth_callback_unbound"};a();let $=_({access_token:R,refresh_token:k.get("refresh_token")||"",token_type:k.get("token_type")||"bearer",expires_in:Number(k.get("expires_in"))||3600});if(!$)return P(),{handled:!1};A($);let G=await C($.access_token);G&&($.user=G,A($));let J=k.get("type")||"";return P(),{handled:!!$.user,type:J}},async selectSyncRow(){let y=await x();if(!y)return{ok:!1,status:401,row:null};let k=n(),P="".concat(k.url,"/rest/v1/account_sync?select=revision,document&user_id=eq.").concat(encodeURIComponent(y.user.id)),R=await v(P,{method:"GET",headers:g(y.access_token,{Accept:"application/json"})},b());if(!R.ok)return{ok:!1,status:R.status,row:null};let D=await R.json().catch(()=>[]);return{ok:!0,status:R.status,row:Array.isArray(D)&&D[0]?D[0]:null}},async patchSyncRow(y,k){let P=await x();if(!P)return{ok:!1,status:401,row:null};let R=n(),D="".concat(R.url,"/rest/v1/account_sync?user_id=eq.").concat(encodeURIComponent(P.user.id),"&revision=eq.").concat(encodeURIComponent(y)),L=await v(D,{method:"PATCH",headers:g(P.access_token,{"Content-Type":"application/json",Prefer:"return=representation"}),body:JSON.stringify({revision:Number(y)+1,document:k})},b());if(!L.ok)return{ok:!1,status:L.status,row:null};let $=await L.json().catch(()=>[]);return{ok:!0,status:L.status,row:Array.isArray($)&&$[0]?$[0]:null}},async selectSubscriptionRow(){let y=await x();if(!y)return{ok:!1,status:401,row:null};let k=n(),P="".concat(k.url,"/rest/v1/subscriptions?select=plan,status,current_period_end&user_id=eq.").concat(encodeURIComponent(y.user.id)),R=await v(P,{method:"GET",headers:g(y.access_token,{Accept:"application/json"})},b());if(!R.ok)return{ok:!1,status:R.status,row:null};let D=await R.json().catch(()=>[]);return{ok:!0,status:R.status,row:Array.isArray(D)&&D[0]?D[0]:null}},async insertSyncRow(y){let k=await x();if(!k)return{ok:!1,status:401,row:null};let P=n(),R=await v("".concat(P.url,"/rest/v1/account_sync"),{method:"POST",headers:g(k.access_token,{"Content-Type":"application/json",Prefer:"return=representation,resolution=merge-duplicates"}),body:JSON.stringify({user_id:k.user.id,revision:1,document:y})},b());if(!R.ok)return{ok:!1,status:R.status,row:null};let D=await R.json().catch(()=>[]);return{ok:!0,status:R.status,row:Array.isArray(D)&&D[0]?D[0]:null}},async invokeFunction(y,{body:k}={}){let P=await B();if(!P)return{ok:!1,status:401,data:null};let R=n(),D=await v("".concat(R.functionsUrl,"/").concat(y),{method:"POST",headers:g(P,{"Content-Type":"application/json"}),body:JSON.stringify(k||{})},p()),L=await D.json().catch(()=>null);return{ok:D.ok,status:D.status,data:L}},displayNameFromUser:Hg,providerFromUser:$g}}
4function Tu(e){let t=e&&typeof e=="object"?{...e}:{};return delete t.revision,t}function xn(e){return{...e?.document&&typeof e.document=="object"?e.document:{},revision:Number(e?.revision)||0}}function xu(e){return!!(e?.email_confirmed_at||e?.confirmed_at)}function Ru(e,t=globalThis){let n=()=>oe(e),r=e?.__supabaseClient instanceof Object?e.__supabaseClient:Eu(e,t);e&&!e.__supabaseClient&&(e.__supabaseClient=r);function s(u,d){let h=n().pages?.[u]||d,p=String(t.location?.origin||"").replace(/\/+$/,"");return p?"".concat(p).concat(h):h}function o(u){return{signedIn:!0,email:String(u?.email||""),displayName:r.displayNameFromUser(u)}}function a(u){let d=r.providerFromUser(u);return d.includes("email")&&xu(u)||d.includes("google")||d.includes("apple")}async function i(){if(typeof r.getMfaState!="function")return{ok:!0,required:!1,factors:[],verifiedFactors:[],currentLevel:"aal1",nextLevel:"aal1"};let u=await r.getMfaState();if(!u.ok||typeof r.getEmailMfaState!="function")return u;let d=await r.getEmailMfaState(),h=d?.data&&typeof d.data=="object"?d.data:null;if(!d?.ok||!h)return{...u,ok:!1,required:!0,error:{code:"email_mfa_state_unavailable",message:"Could not verify your email two-factor security status. Try again before accessing account data."}};let p={enabled:!!h.enabled,verified:!!h.verified,primaryEligible:!!h.primaryEligible},b=p.enabled?[{id:"email",friendly_name:"Email code",factor_type:"email",status:"verified"}]:[],v=[...u.factors,...b],E=[...u.verifiedFactors,...b],A=u.currentLevel==="aal2"||p.verified;return{...u,factors:v,verifiedFactors:E,required:E.length>0&&!A,email:p}}function c(u,d){let h=u?.data&&typeof u.data=="object"?u.data:{},p=h.error&&typeof h.error=="object"?h.error:{};return{code:String(p.code||"email_mfa_error"),message:String(p.message||h.message||d),details:p.details&&typeof p.details=="object"?p.details:{}}}async function l(){let u=await i();return u.ok&&!u.required?{ok:!0,mfa:u}:{ok:!1,status:403,mfa:u,error:{code:u.error?.code||"mfa_required",message:u.error?.message||"Complete tw
4o-factor verification before accessing account data."}}}async function m(){let u=await l();if(!u.ok)return{ok:!1,status:u.status};let d=await r.selectSyncRow();return d.ok&&d.row?{ok:!0,document:xn(d.row)}:d.ok?{ok:!0,document:{revision:0}}:{ok:!1,status:d.status||503}}return{supabase:r,async fetchStatus(){let u=An(t);if(!u)return{ok:!0,status:200,data:{enabled:!1,signedIn:!1}};let d=await r.getUser();if(!d)return{ok:!0,status:200,data:{enabled:!0,signedIn:!1,mailConfigured:!0,oauthProviders:u.providers,googleOAuthConfigured:u.providers.includes("google"),passkeysSupported:typeof r.passkeysSupported=="function"&&r.passkeysSupported(),passkeyManagementSupported:typeof r.passkeyManagementSupported=="function"&&r.passkeyManagementSupported(),syncRevision:0}};let h=r.providerFromUser(d),p=await i();return{ok:!0,status:200,data:{enabled:!0,signedIn:!0,userId:String(d.id||""),email:String(d.email||""),displayName:r.displayNameFromUser(d),emailVerified:xu(d),mailConfigured:!0,oauthProviders:u.providers,googleOAuthConfigured:u.providers.includes("google"),providers:h,hasPassword:h.includes("email"),passkeysSupported:typeof r.passkeysSupported=="function"&&r.passkeysSupported(),passkeyManagementSupported:typeof r.passkeyManagementSupported=="function"&&r.passkeyManagementSupported(),mfa:{checked:!!p.ok,required:!p.ok||!!p.required,currentLevel:p.currentLevel||null,nextLevel:p.nextLevel||null,factors:Array.isArray(p.factors)?p.factors:[],verifiedFactorCount:Array.isArray(p.verifiedFactors)?p.verifiedFactors.length:0,email:p.email||{enabled:!1,verified:!1,primaryEligible:!1},error:p.ok?null:p.error||{code:"mfa_state_unavailable",message:"Could not verify two-factor security status."}},syncRevision:0}}},async register({email:u,password:d,displayName:h=""}){let p=await r.signUp({email:u,password:d,displayName:h,redirectTo:s("accountVerify","/account-verify")});if(!p.ok)return{ok:!1,status:p.status,data:{error:p.error}};if(p.session?.user){let b=await i();return{ok:!0,status:p.status,data:{account:o(p.session.user),mfa:b}}}return{ok:!0,status:p.status,data:{account:{signedIn:!1},message:"Account created. Check your inbox for a confirmation link to finish signing in."}}},async login({email:u,password:d}){let h=await r.signInWithPassword({email:u,password:d});if(!h.ok)return{ok:!1,status:h.status,data:{error:h.error}};let p=await i();return{ok:!0,status:h.status,data:{account:o(h.session.user),mfa:p}}},async logout(){return await r.signOut({scope:"local"}),{ok:!0,status:200,data:{}}},async beginTotpEnrollment({friendlyName:u}){let d=await r.enrollTotp(String(u||""));return d.ok?{ok:!0,status:d.status,data:d.data}:{ok:!1,status:d.status,data:{error:d.error}}},async beginTotpChallenge({factorId:u}){let d=await r.challengeTotp(String(u||""));return d.ok?{ok:!0,status:d.status,data:d.data}:{ok:!1,status:d.status,data:{error:d.error}}},async verifyTotpChallenge({factorId:u,challengeId:d,code:h}){let p=await r.verifyTotp(String(u||""),String(d||""),String(h||""));return p.ok?{ok:!0,status:p.status,data:{}}:{ok:!1,status:p.status,data:{error:p.error}}},async cancelTotpEnrollment({factorId:u}){let d=await r.unenrollTotp(String(u||""),!1);return d.ok?{ok:!0,status:d.status,data:{}}:{ok:!1,status:d.status,data:{error:d.error}}},async removeTotpFactor({factorId:u,confirmDisable:d=!1}){let h=await r.unenrollTotp(String(u||""),!!d);return h.ok?{ok:!0,status:h.status,data:{}}:{ok:!1,status:h.status,data:{error:h.error}}},async beginEmailMfaEnrollment(){let u=await r.emailMfaRequest("enroll");return u.ok?{ok:!0,status:u.status,data:u.data}:{ok:!1,status:u.status,data:{error:c(u,"Could not send the enrollment code.")}}},async beginEmailMfaChallenge(){let u=await r.emailMfaRequest("challenge");return u.ok?{ok:!0,status:u.status,data:u.data}:{ok:!1,status:u.status,data:{error:c(u,"Could not send the verification code.")}}},async verifyEmailMfaChallenge({challengeId:u,code:d}){let h=await r.emailMfaRequest("verify",{challengeId:String(u||""),code:String(d||"")});if(!h.ok)return{ok:!1,status:h.status,data:{error:c(h,"That code was not accepted.")}};if(!(await r.refreshAuthSession()).ok)return{ok:!1,status:503,data:{error:{code:"session_refresh_failed",message:"The code was accepted, but your session could not be refreshed. Sign in again."}}};let b=await i();return!b.ok||!b.email?.verified?{ok:!1,status:503,data:{error:{code:"email_mfa_claim_missing",message:"Email verification could not be applied to this session. Try again."}}}:{ok:!0,status:h.status,data:h.data}},async disableEmailMfa(){let u=await r.emailMfaRequest("disable");return u.ok?(await r.refreshAuthSession(),{ok:!0,status:u.status,data:u.data}):{ok:!1,status:u.status,data:{error:c(u,"Could not disable email two-factor authentication.")}}},async signInWithPasskey({signal:u}={}){let d=await r.signInWithPasskey(u);if(!d.ok)return{ok:!1,status:d.status,data:{error:d.error}};let h=await r.getUser(),p=await i();return{ok:!0,status:d.status,data:{account:o(h),mfa:p}}},async listPasskeys(){let u=await r.listPasskeys();return u.ok?{ok:!0,status:u.status,data:{passkeys:u.data||[]}}:{ok:!1,status:u.status,data:{error:u.error}}},async registerPasskey({signal:u}={}){let d=await r.registerPasskey(u);return d.ok?{ok:!0,status:d.status,data:{passkey:d.data}}:{ok:!1,status:d.status,data:{error:d.error}}},async renamePasskey({passkeyId:u,friendlyName:d}){let h=await r.renamePasskey(String(u||""),String(d||""));return h.ok?{ok:!0,status:h.status,data:{}}:{ok:!1,status:h.status,data:{error:h.error}}},async deletePasskey({passkeyId:u}){let d=await r.getUser(),h=await r.deletePasskey(String(u||""),a(d));return h.ok?{ok:!0,status:h.status,data:{}}:{ok:!1,status:h.status,data:{error:h.error}}},async fetchPlan(){let u={plan:"free",status:"inactive",current_period_end:null,isPro:!1};if(!(await l()).ok||typeof r.selectSubscriptionRow!="function")return u;let h=await r.selectSubscriptionRow();if(!h.ok||!h.row)return u;let p=h.row,b=ul(p);return{plan:b||String(p.plan||"free").toLowerCase()==="pro"?"pro":"free",status:String(p.status||"inactive"),current_period_end:p.current_period_end??null,isPro:b}},async pullSync(){let u=await m();return u.ok?{ok:!0,status:200,data:{sync:u.document}}:{ok:!1,status:u.status,data:{error:{code:"mfa_required",message:"Complete tw
4o-factor verification before accessing synced data."}}}},async pushSync({baseRevision:u,document:d}){let h=await l();if(!h.ok)return{ok:!1,status:h.status,data:{error:h.error}};let p=Number(u)||0,b=await r.patchSyncRow(p,Tu(d));if(b.ok&&b.row)return{ok:!0,status:200,data:{sync:xn(b.row)}};if(!b.ok&&b.status!==200)return{ok:!1,status:b.status||503,data:{error:{code:"sync_busy",message:"Account sync is busy. Try again."}}};let v=await r.selectSyncRow();if(!v.ok)return{ok:!1,status:v.status||503,data:{error:{code:"sync_busy",message:"Account sync is busy. Try again."}}};if(!v.row){let E=await r.insertSyncRow(Tu(d));return E.ok&&E.row?{ok:!0,status:200,data:{sync:xn(E.row)}}:{ok:!1,status:E.status||503,data:{error:{code:"sync_busy",message:"Account sync is busy. Try again."}}}}return{ok:!1,status:409,data:{status:"conflict",sync:xn(v.row)}}},async requestVerificationEmail(){let u=await r.getUser();if(!u?.email)return{ok:!1,status:401,data:{error:{code:"not_authenticated",message:"Sign in first."}}};let d=await r.resendVerification(u.email,{redirectTo:s("accountVerify","/account-verify")});return d.ok?{ok:!0,status:200,data:{message:"Verification email sent. Check your inbox."}}:{ok:!1,status:d.status,data:{error:d.error}}},async requestPasswordReset({email:u}){return await r.resetPasswordForEmail(u,{redirectTo:s("accountReset","/account-reset")}),{ok:!0,status:200,data:{message:"If an account exists for that email, a reset link is on its way."}}},async resetPassword({password:u}){let d=await r.updatePassword(u);return d.ok?{ok:!0,status:200,data:{message:"Password updated. You can sign in now."}}:{ok:!1,status:d.status,data:{error:d.error}}},async changeEmail({email:u}){let d=await r.updateEmail(u,{redirectTo:s("accountVerify","/account-verify")});return d.ok?{ok:!0,status:200,data:{message:"Check both your current and new inbox \u2014 confirm from each link to finish the change."}}:{ok:!1,status:d.status,data:{error:d.error}}},async changePassword({currentPassword:u,newPassword:d}){let h=await r.getUser();if(!h?.email)return{ok:!1,status:401,data:{error:{code:"not_authenticated",message:"Sign in again to change your password."}}};let p=await r.signInWithPassword({email:h.email,password:u});if(!p.ok)return{ok:!1,status:p.status,data:{error:{code:"invalid_current_password",message:"Your current password is incorrect."}}};let b=await r.updatePassword(d);return b.ok?{ok:!0,status:200,data:{message:"Your password has been updated."}}:{ok:!1,status:b.status,data:{error:b.error}}},async updateDisplayName({displayName:u}){let d=await r.updateDisplayName(u);return d.ok?{ok:!0,status:200,data:{account:o(d.user),message:"Display name updated."}}:{ok:!1,status:d.status,data:{error:d.error}}},async requestEmailSignInCode({email:u}){let d=await r.signInWithOtp(u,{redirectTo:s("home","/"),shouldCreateUser:!1});return d.ok?{ok:!0,status:200,data:{message:"If an account exists for that email, a sign-in code is on its way."}}:{ok:!1,status:d.status,data:{error:d.error}}},async verifyEmailSignInCode({email:u,token:d}){let h=await r.verifyOtp({email:u,token:d,type:"email"});if(!h.ok||!h.session?.user)return{ok:!1,status:h.status,data:{error:h.error||{code:"otp_invalid",message:"That code is incorrect or expired."}}};let p=await i();return{ok:!0,status:h.status,data:{account:o(h.session.user),mfa:p}}},async fetchSessions(){return await r.getUser()?{ok:!0,status:200,data:{devices:[{id:"current",current:!0,label:"This device",lastSeenAt:Math.floor(Date.now()/1e3)}]}}:{ok:!1,status:401,data:{error:{code:"not_authenticated",message:"Sign in first."}}}},async revokeSession({deviceId:u,allOthers:d=!1}={}){if(d){let h=await r.signOut({scope:"others"});return h.ok?{ok:!0,status:200,data:{revoked:1}}:{ok:!1,status:h.status||503,data:{error:{code:"revoke_failed",message:"Could not sign out your other sessions. Try again."}}}}if(u==="current"){let h=await r.signOut({scope:"local"});return h.ok?{ok:!0,status:200,data:{signedOut:!0}}:{ok:!1,status:h.status||503,data:{error:{code:"revoke_failed",message:"Could not sign out this session. Try again."}}}}return{ok:!0,status:200,data:{}}},async fetchPrivacySummary(){let u=await r.getUser();if(!u)return{ok:!1,status:401,data:{error:{code:"not_authenticated",message:"Sign in first."}}};let d=await m();if(!d.ok)return{ok:!1,status:d.status,data:{error:{code:"sync_unavailable",message:"Could not load your account data. Try again."}}};let h=d.document,p=r.providerFromUser(u),b=typeof r.listPasskeys=="function"?await r.listPasskeys():null,v=b?.ok&&Array.isArray(b.data)?b.data.length:null;return{ok:!0,status:200,data:{account:{email:String(u.email||""),providers:p,hasGoogle:p.includes("google"),hasPassword:p.includes("email"),passkeyCount:v},stored:{savedSearches:Array.isArray(h.saved_searches)?h.saved_searches.filter(E=>!E?.deleted).length:0,recentSearches:Array.isArray(h.recent_searches)?h.recent_searches.filter(E=>!E?.deleted).length:0,chatMessages:Array.isArray(h.chat?.messages)?h.chat.messages.length:0}}}},async exportAccountData(){let u=await r.getUser();if(!u)return{ok:!1,status:401,data:{error:{code:"not_authenticated",message:"Sign in first."}}};let d=await m();if(!d.ok)return{ok:!1,status:d.status,data:{error:{code:"sync_unavailable",message:"Could not load your account data for export. Try again."}}};let h=d.document;return{ok:!0,status:200,data:{export:{exported_at:new Date().toISOString(),account:{id:u.id,email:u.email,display_name:r.displayNameFromUser(u),created_at:u.created_at,providers:r.providerFromUser(u)},sync:h}}}},async exportAccountChat(){let u=await m();if(!u.ok)return{ok:!1,status:u.status,data:{error:{code:"sync_unavailable",message:"Could not load your chat data for export. Try again."}}};let d=u.document;return{ok:!0,status:200,data:{export:{messages:Array.isArray(d.chat?.messages)?d.
4chat.messages:[]}}}},async deleteAccountChat(){let u=await l();if(!u.ok)return{ok:!1,status:u.status,data:{error:u.error}};let d=await r.selectSyncRow();if(!d.ok)return{ok:!1,status:d.status||503,data:{error:{code:"sync_busy",message:"Could not reach your account. Try again."}}};let h=d.row?xn(d.row):{revision:0},p={...h,chat:{revision:0,messages:[]}};return this.pushSync({baseRevision:h.revision||0,document:p})},async deleteAccountData(){let u=await l();if(!u.ok)return{ok:!1,status:u.status,data:{error:u.error}};let d=null;for(let h=0;h<4;h+=1){let p=await r.selectSyncRow();if(!p.ok)return{ok:!1,status:p.status||503,data:{error:{code:"sync_busy",message:"Could not reach your account. Try again."}}};let b=p.row?xn(p.row):{revision:0},v={...b,saved_searches:[],recent_searches:[],chat:{revision:0,messages:[]}},E=await this.pushSync({baseRevision:b.revision||0,document:v});if(E.ok||E.status!==409)return E;d={ok:!1,status:409,data:{error:{code:"sync_conflict",message:"Your data changed during deletion. Try again."}}}}return d??{ok:!1,status:409,data:{error:{code:"sync_conflict",message:"Your data changed during deletion. Try again."}}}},async deleteAccount(u){let d=await r.invokeFunction("delete-account",{});if(!d.ok){let h=d.status===404?"Account deletion is not available \u2014 the delete-account function is not deployed.":d.data?.detail||d.data?.error||"Could not delete your account. Try again.";return{ok:!1,status:d.status,data:{error:{code:"delete_failed",message:h}}}}return await r.signOut({scope:"local"}),{ok:!0,status:200,data:{deleted:!0}}},async handleOAuthRedirect(){return r.handleRedirectCallback()}}}var Fg="Your account data changed on another device. Refresh this page, then try again.",qg="Account sync is busy. Wait a moment, refresh the page, then try again.";function Rn(e){return e?.status===409&&(e?.data?.status==="conflict"||!!e?.data?.sync)}function Ug(e){return e?.status===503&&e?.data?.error?.code==="sync_busy"}function Zo(e){return Rn(e)?Fg:Ug(e)?qg:null}function Pu(e,t=globalThis){let n=Ru(e,t),r=()=>oe(e),s=()=>fl(r(),S),o=!1,a=!1,i=null,c=!1,l=!1,m=!1,u=[],d=[],h=!1,p=!1,b=!1,v={checked:!1,required:!0,currentLevel:null,nextLevel:null,factors:[],verifiedFactorCount:0,email:{enabled:!1,verified:!1,primaryEligible:!1},error:null},E=0,A="free",S=!1,_=null,w=null,f=Promise.resolve(),g=0,C=null,T=null,x=0,N=new Set,B=new Set,I=()=>r()?.storageKeys?.syncLocalDirty||"beamo-sync-local-dirty",y=()=>r()?.storageKeys?.syncLocalErase||"beamo-sync-local-erase",k=()=>r()?.storageKeys?.syncLocalOwner||"beamo-sync-local-owner";function P(){try{return Number(t.localStorage?.getItem(I()))||0}catch{return 0}}function R(){try{t.localStorage?.setItem(I(),String(Date.now()))}catch{}}function D(H){try{P()<=H&&t.localStorage?.removeItem(I())}catch{}}function L(){try{return Number(t.localStorage?.getItem(y()))||0}catch{return 0}}function $(){let H=Date.now();g=H,w&&(t.clearTimeout(w),w=null);try{t.localStorage?.setItem(y(),String(H))}catch{}return H}function G(H=Number.MAX_SAFE_INTEGER){return L()>0||g>0&&g>=H}function J(H=Number.MAX_SAFE_INTEGER){try{L()<=H&&t.localStorage?.removeItem(y())}catch{}}function X(){try{return String(t.localStorage?.getItem(k())||"").trim()}catch{return""}}function W(H){if(H)try{t.localStorage?.setItem(k(),H)}catch{}}function V(){try{Qr(t,r(),[]),Zr(t,r(),[]),kr(t,r(),[]),Ll(t)}catch{}}async function j(H){w&&(t.clearTimeout(w),w=null),V(),D(Date.now()),J(Date.now());let q=await st();return q.ok?(C=null,!0):(C={message:q.message||"Could not clear previous account data from this browser. Sign out and try again.",type:"busy",source:H},Ee(C),!1)}function ee(){Jr(t,{type:Ke.PWA_IFRAME_ACCOUNT,enabled:o,signedIn:a});for(let H of N)try{H({enabled:o,signedIn:a,account:i,emailVerified:c,mailConfigured:l,googleOAuthConfigured:m,oauthProviders:u,providers:d,hasPassword:h,passkeysSupported:p,passkeyManagementSupported:b,mfa:v,syncRevision:E,plan:A,isPro:S,subscription:_})}catch{}}function Ee(H){T=H;for(let q of B)try{q(T)}catch{}}function Y(){if(T){T=null;for(let H of B)try{H(null)}catch{}}}function se(H){o=!!H.enabled,a=!!H.signedIn,i=H.account??null,c=!!H.emailVerified,l=!!H.mailConfigured,m=!!H.googleOAuthConfigured,u=Array.isArray(H.oauthProviders)?H.oauthProviders:[],d=Array.isArray(H.providers)?H.providers:[],h=!!H.hasPassword,p=!!H.passkeysSupported,b=!!H.passkeyManagementSupported;
4let q=H.mfa&&typeof H.mfa=="object"?H.mfa:null;v={checked:!!q?.checked,required:!!q?.required,currentLevel:q?.currentLevel==="aal2"?"aal2":q?.currentLevel==="aal1"?"aal1":null,nextLevel:q?.nextLevel==="aal2"?"aal2":q?.nextLevel==="aal1"?"aal1":null,factors:Array.isArray(q?.factors)?q.factors.filter(z=>!!(z&&typeof z=="object")):[],verifiedFactorCount:Number(q?.verifiedFactorCount)||0,email:{enabled:!!q?.email?.enabled,verified:!!q?.email?.verified,primaryEligible:!!q?.email?.primaryEligible},error:q?.error&&typeof q.error=="object"?{code:String(q.error.code||"mfa_state_unavailable"),message:String(q.error.message||"Could not verify two-factor security status.")}:null},E=Number(H.syncRevision)||0,A=H.plan==="pro"?"pro":"free",S=!!H.isPro,_=H.subscription&&typeof H.subscription=="object"?{current_period_end:H.subscription.current_period_end??null}:null,ee()}function ae(){return a?String(i?.userId||""):""}function Me(H,q){return x===H&&(q===void 0||ae()===q)}function Ue(){return r().storageKeys?.accountPlan||"beamo-account-plan"}function Te(){try{let H=t.localStorage?.getItem(Ue());if(!H)return null;let q=JSON.parse(H);return!q||typeof q!="object"||typeof q.userId!="string"?null:q}catch{return null}}function ne(H,q){if(H)try{t.localStorage?.setItem(Ue(),JSON.stringify({userId:H,plan:q.plan==="pro"?"pro":"free",isPro:!!q.isPro,current_period_end:q.current_period_end??null}))}catch{}}function ce(){try{t.localStorage?.removeItem(Ue())}catch{}}function en(){let H=n.supabase;if(!H||typeof H.isConfigured!="function"||!H.isConfigured())return;o=!0,p=typeof H.passkeysSupported=="function"&&H.passkeysSupported(),b=typeof H.passkeyManagementSupported=="function"&&H.passkeyManagementSupported();let q=An(t);u=Array.isArray(q?.providers)?q.providers:[],m=u.includes("google"),l=!0;let z=typeof H.peekUser=="function"?H.peekUser():null;if(!z)return;a=!0;let Z=String(z.id||"");i={userId:Z,email:String(z.email||""),displayName:H.displayNameFromUser(z)},c=!!(z.email_confirmed_at||z.confirmed_at),d=H.providerFromUser(z),h=d.includes("email");let le=Te();le&&le.userId===Z&&(A=le.plan==="pro"?"pro":"free",S=!!le.isPro,_={current_period_end:le.current_period_end??null})}async function wt(){let H=++x,q=await n.fetchStatus();if(!Me(H))return{enabled:o,signedIn:a};let z=q.data;if(!q.ok||!z||typeof z!="object")return ce(),se({enabled:!1,signedIn:!1,account:null,emailVerified:!1,mailConfigured:!1,googleOAuthConfigured:!1,oauthProviders:[],passkeysSupported:!1,passkeyManagementSupported:!1,mfa:null,syncRevision:0,plan:"free",isPro:!1,subscription:null}),{enabled:!1,signedIn:!1};let Z={plan:"free",isPro:!1,current_period_end:null};if(z.signedIn&&!z.mfa?.required&&z.mfa?.checked&&typeof n.fetchPlan=="function")try{Z=await n.fetchPlan()}catch{Z={plan:"free",isPro:!1,current_period_end:null}}if(!Me(H))return{enabled:o,signedIn:a};let le=z.signedIn?String(z.userId||""):"";if(le){let ge=X();if(ge&&ge!==le){if(await j("account-switch"),!Me(H))return{enabled:o,signedIn:a};E=0}}return z.signedIn?(ne(le,Z),W(le)):ce(),se({enabled:!!z.enabled,signedIn:!!z.signedIn,account:z.signedIn?{userId:z.userId||"",email:z.email||"",displayName:z.displayName||""}:null,emailVerified:!!z.emailVerified,mailConfigured:!!z.mailConfigured,googleOAuthConfigured:!!z.googleOAuthConfigured,oauthProviders:Array.isArray(z.oauthProviders)?z.oauthProviders:[],providers:Array.isArray(z.providers)?z.providers:[],hasPassword:!!z.hasPassword,passkeysSupported:!!z.passkeysSupported,passkeyManagementSupported:!!z.passkeyManagementSupported,mfa:z.mfa||null,syncRevision:Number(z.syncRevision)||0,plan:Z.plan==="pro"?"pro":"free",isPro:!!Z.isPro,subscription:z.signedIn?{current_period_end:Z.current_period_end??null}:null}),{enabled:o,signedIn:a}}function Fe(){return{revision:0,messages:[]}}async function st(){try{if(typeof e?.deleteChatSession=="function")return await e.deleteChatSession(),{ok:!0};let H=r().endpoints?.deleteChat||"/PHP/deletechat.php",q=typeof e?.fetchWithTimeout=="function"?e.fetchWithTimeout:null,Z={method:"POST",credentials:"same-origin",headers:await Ie(e)},le=q?await q(H,Z,r().timeouts?.chatDeleteMs||5e3):typeof t.fetch=="function"?await t.fetch(H,Z):null;return!le||!le.ok?{ok:!1,message:"Could not clear this browser chat session."}:{ok:!0}
4}catch(H){return{ok:!1,message:H instanceof Error?H.message:"Could not clear this browser chat session."}}}function Ot(H){let q=H;return q.saved_searches=[],q.recent_searches=[],q.chat_threads=[],q.chat=Fe(),H}function tn(H,{erasePersonalData:q=!1}={}){let z=Io(t,r());return H&&typeof H=="object"&&(z.chat={revision:Number(H.revision)||0,messages:Array.isArray(H.messages)?H.messages:[]}),q&&Ot(z),z}async function ot(H,{refreshChat:q=!0}={}){if(!H||typeof H!="object")return;let z=G()?Ot({...H}):H;zl(t,r(),z,{beamo:e}),E=Number(z.revision)||E,q&&e.chatSync?.refreshFromServer&&await e.chatSync.refreshFromServer({forceRender:!0}),ee()}async function Pn(){if(!o||!a)return!1;let H=x,q=ae(),z=()=>Me(H,q),Z=await n.pullSync();return!z()||!Z.ok||!Z.data?.sync||(await ot(Z.data.sync,{refreshChat:!0}),!z())?!1:(await wt(),!0)}async function In({source:H}={}){if(!o||!a)return{ok:!1,skipped:!0};if(C)return Ee(C),{ok:!1,busy:!0,message:C.message};let q=x,z=ae(),Z=()=>Me(q,z),le=Date.now();if(G(le))return xe({source:H,chatState:Fe()});let ge=await n.pullSync();if(!Z())return{ok:!1,skipped:!0,stale:!0};let Ce=null;if(ge.ok&&ge.data?.sync){if(G(le))return xe({source:H,chatState:Fe()});let Dt=ge.data.sync,rn=await Nn();if(!Z())return{ok:!1,skipped:!0,stale:!0};let sn=tn(rn),je=s(),at=ss(sn,Dt,je.savedSearchesMax,je.searchHistoryMax,{preferLocalPreferences:P()>0});if(G(le))return xe({source:H,chatState:Fe()});if(Ce=at.chat??null,E=Number(Dt.revision)||E,await ot(at,{refreshChat:!1}),!Z())return{ok:!1,skipped:!0,stale:!0};if(await Be(Ce),!Z())return{ok:!1,skipped:!0,stale:!0};if(e.chatSync?.refreshFromServer&&(await e.chatSync.refreshFromServer({forceRender:!0}),!Z()))return{ok:!1,skipped:!0,stale:!0}}return Z()?xe({source:H,chatState:Ce??void 0}):{ok:!1,skipped:!0,stale:!0}}async function Nn(){let H=r().endpoints?.chatSync;if(!H||typeof t.fetch!="function")return{revision:0,messages:[]};try{let q=await Ie(e),z=await e.fetchWithTimeout(H,{method:"GET",headers:q},r().timeouts?.fetchDefaultMs||8e3);if(!z.ok)return{revision:0,messages:[]};let Z=await z.json();return{revision:Number(Z?.revision)||0,messages:Array.isArray(Z?.messages)?Z.messages:[]}}catch{return{revision:0,messages:[]}}}async function Be(H){let q=Array.isArray(H?.messages)?H.messages:[];if(q.length===0)return!1;let z=r().endpoints?.chatImport,Z=e?.fetchWithTimeout;if(!z||typeof Z!="function")return!1;try{let le=await Ie(e),ge=await Z(z,{method:"POST",credentials:"same-origin",headers:{...le,"Content-Type":"application/json"},body:JSON.stringify({chat:{revision:Number(H?.revision)||0,messages:q}})},r().timeouts?.fetchDefaultMs||8e3);return ge.ok?!!(await ge.json().catch(()=>null))?.imported:!1}catch{return!1}}function St(H,{source:q}={}){let z=Zo(H);if(!z)return null;let Z=Rn(H)?"conflict":"busy",le={message:z,type:Z,source:q};return Ee(le),le}async function xe({chatState:H,source:q,preferLocalChat:z=!1}={}){if(!o||!a)return{ok:!1,skipped:!0};if(C)return Ee(C),{ok:!1,busy:!0,message:C.message};let Z=x,le=ae(),ge=()=>Me(Z,le),Ce=()=>({ok:!1,skipped:!0,stale:!0}),Dt=Date.now(),rn=async()=>{if(!ge())return Ce();let sn=P(),je=L(),at=G(Dt),Ts=at?Fe():H||await Nn();if(!ge())return Ce();let vt=tn(Ts,{erasePersonalData:at});vt.revision=E;let ue=await n.pushSync({baseRevision:E,document:vt});if(!ge())return Ce();let on=!1;for(;Rn(ue)&&ue.data?.sync;){let re=s(),qe=ss(vt,ue.data.sync,re.savedSearchesMax,re.searchHistoryMax,{preferLocalPreferences:sn>0,preferLocalData:at,preferLocalChat:z});if(await ot(qe,{refreshChat:!1}),!ge())return Ce();if(E=Number(ue.data.sync.revision)||E,qe.revision=E,vt=qe,on)return{ok:!1,conflict:!0,message:St(ue,{source:q})?.message||null,result:ue};if(on=!0,ue=await n.pushSync({baseRevision:E,document:vt}),!ge())return Ce()}let de=Zo(ue);if(de){let re=St(ue,{source:q});return{ok:!1,conflict:Rn(ue),busy:!Rn(ue),message:re?.message||de,result:ue}}return ue.ok&&ue.data?.sync?(E=Number(ue.data.sync.revision)||E,await ot(ue.data.sync,{refreshChat:!0}),ge()?(Y(),D(sn),J(je),{ok:!0,result:ue}):Ce()):{ok:!1,result:ue}};return f=f.then(rn,rn),f}function mr({chatState:H,chatStateLoader:q,delayMs:z=1500,source:Z}={}){!o||!a||(w&&t.clearTimeout(w),R(),w=t.setTimeout(()=>{w=null,(async()=>{let le=H||(typeof q=="function"?await q():null);await xe({chatState:le,source:Z})})()},z))}async function kt(){x+=1,await j("logout"),ce();let H=await n.logout();return await wt(),H}async function hr(H){let q=await n.deleteAccount(H);if(!q.ok)return q;x+=1,w&&(t.clearTimeout(w),w=null),V(),D(Date.now()),J(Date.now());try{t.localStorage?.removeItem(k())}catch{}return ce(),await st(),se({enabled:o,signedIn:!1,account:null}),q}async function Ln(){let H=await st();return H.ok?xe({chatState:Fe(),source:"account-chat-delete",preferLocalChat:!0}):{ok:!1,status:503,data:{error:{code:"chat_session_clear_failed",message:H.message||"Could not clear this browser chat session."}}}}async function nn(){let H=$();V();let q=await st();if(!q.ok)return J(H),{ok:!1,status:503,data:{error:{code:"chat_session_clear_failed",message:q.message||"Could not clear this browser chat session."}}};let z=await n.deleteAccountData();if(!z.ok)return J(H),z;let Z=await xe({source:"account-data-erase",chatState:Fe()});return Z&&typeof Z=="object"&&Z.ok===!1&&Z.skipped!==!0?Z:(J(H),z)}async function Mn(H){if(await wt(),!a||C||v.required||!v.checked)return;if(!H?.sync){await In({source:"sign-in-no-sync"});return}let q=Io(t,r()),z=s(),Z=ss(q,H.sync,z.savedSearchesMax,z.searchHistoryMax);await ot(Z,{refreshChat:!0}),Y(),D(Date.now()),xe()}
4return en(),{getState:()=>({enabled:o,signedIn:a,account:i,emailVerified:c,mailConfigured:l,googleOAuthConfigured:m,oauthProviders:u,providers:d,hasPassword:h,passkeysSupported:p,passkeyManagementSupported:b,mfa:v,syncRevision:E,plan:A,isPro:S,subscription:_}),getSyncFailure:()=>T,subscribe(H){return N.add(H),()=>N.delete(H)},subscribeSyncFailure(H){if(B.add(H),T)try{H(T)}catch{}return()=>B.delete(H)},refreshStatus:wt,refreshFromServer:Pn,mergePullAndPush:In,schedulePush:mr,pushNow:xe,logout:kt,deleteAccountEverywhere:hr,deleteAccountChatEverywhere:Ln,eraseAccountDataEverywhere:nn,markDataEraseInProgress:$,clearDataEraseInProgress:J,applyRemoteSync:ot,signInWithPayload:Mn,clearSyncFailure:Y,client:n,fetchChatState:Nn}}var jg=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;function Zt(e){let t=String(e??"").trim();return t===""?"Enter your email address.":t.length>254?"Email address must be 254 characters or fewer.":jg.test(t)?null:"Enter a valid email address."}function ea(e,t=8,n=128){let r=String(e??"");return r===""?"Enter your password.":r.length<t?"Password must be at least ".concat(t," characters."):r.length>n?"Password must be ".concat(n," characters or fewer."):null}var Iu=/\p{L}/u,Nu=/\d/;function ta(e,t=8){let n=String(e??"");return[{id:"length",label:"At least ".concat(t," characters"),met:n.length>=t},{id:"letter",label:"At least one letter",met:Iu.test(n)},{id:"digit",label:"At least one number",met:Nu.test(n)}]}function zg(e,t=8,n=128){let r=String(e??"");return r===""?"Enter a password.":r.length>n?"Password must be ".concat(n," characters or fewer."):r.length<t?"Password must be at least ".concat(t," characters."):Iu.test(r)?Nu.test(r)?null:"Password must include at least one number.":"Password must include at least one letter."}function Wg(e,t=80){return String(e??"").trim().length>t?"Display name must be ".concat(t," characters or fewer."):null}function Lu({email:e,password:t},{minPassword:n=8,maxPassword:r=128}={}){let s={},o=Zt(e),a=ea(t,n,r);return o&&(s.email=o),a&&(s.password=a),s}function Mu({email:e,password:t,displayName:n},{minPassword:r=8,maxPassword:s=128,maxDisplayName:o=80}={}){let a={},i=Zt(e),c=zg(t,r,s),l=Wg(n,o);return i&&(a.email=i),c&&(a.password=c),l&&(a.displayName=l),a}function yt({id:e,label:t,input:n,hint:r="",optional:s=!1}){let o=document.createElement("div");o.className="settings-account__field";let a=document.createElement("label");a.className="settings-account__label",a.htmlFor=e,a.textContent=s?"".concat(t," (optional)"):t;let i=document.createElement("div");i.className="settings-account__control",n.id=e,n.classList.add("settings-account__input");let c=document.createElement("span");c.id="".concat(e,"-hint"),c.className="settings-account__hint",c.textContent=r,r||(c.hidden=!0);let l=document.createElement("span");return l.id="".concat(e,"-error"),l.className="settings-account__field-error",l.hidden=!0,l.setAttribute("role","alert"),n.setAttribute("aria-describedby",r?"".concat(e,"-hint ").concat(e,"-error"):"".concat(e,"-error")),i.append(n),o.append(a,i,c,l),{field:o,input:n,errorEl:l,hintEl:c}}function Bu(e,{minLength:t=8,id:n="password-requirements"}={}){let r=e.createElement("ul");r.className="settings-account__password-reqs",r.id=n,r.setAttribute("aria-label","Password requirements");let s=new Map;for(let a of ta("",t)){let i=e.createElement("li");i.className="settings-account__password-req",i.dataset.met="false";let c=e.createElement("span");c.className="settings-account__password-req-mark",c.setAttribute("aria-hidden","true");let l=e.createElement("span");l.className="settings-account__password-req-text",l.textContent=a.label,i.append(c,l),r.appendChild(i),s.set(a.id,{li:i,text:l})}function o(a){for(let i of ta(a,t)){let c=s.get(i.id);c&&(c.li.dataset.met=i.met?"true":"false",c.li.setAttribute("aria-label","".concat(i.label,": ").concat(i.met?"met":"not met")))}}return o(""),{el:r,update:o}}function Le(e,t,n){if(!(!e||!t)){if(n){e.textContent=n,e.hidden=!1,t.setAttribute("aria-invalid","true");return}e.textContent="",e.hidden=!0,t.removeAttribute("aria-invalid")}}function na(e,t,n){let r=()=>{Le(t,e,n(e.value))};return e.addEventListener("blur",r),e.addEventListener("input",()=>{e.getAttribute("aria-invalid")==="true"&&r()}),r}function ra(e,t){let n=null;for(let[r,s]of Object.entries(e)){let o=t[r]||null;Le(s.errorEl,s.input,o),o&&!n&&(n=s.input)}n?.focus()}function M(e){return we(globalThis)("accounts."+e)}var Q={get signedOutIntro(){return M("signedOutIntro")},get comingSoonTitle(){return M("comingSoonTitle")},get comingSoonBody(){return M("comingSoonBody")},get comingSoonNote(){return M("comingSoonNote")},get syncBenefitsHeading(){return M("syncBenefitsHeading")},get syncBenefitSaved(){return M("syncBenefitSaved")},get syncBenefitRecent(){return M("syncBenefitRecent")},get syncBenefitChat(){return M("syncBenefitChat")},get syncBenefitPrefs(){return M("syncBenefitPrefs")},get syncBenefitsSignedIn(){return M("syncBenefitsSignedIn")},get signInGoogle(){return M("signInGoogle")},get signInApple(){return M("signInApple")},get orDivider(){return M("orDivider")},get signInTitle(){return M("signInTitle")},get signInSubtitle(){return M("signInSubtitle")},get createAccountTitle(){return M("createAccountTitle")},get createAccountSubtitle(){return M("createAccountSubtitle")},get signInSubmit(){return M("signInSubmit")},get createAccountSubmit(){return M("createAccountSubmit")},get signInSwitchPrompt(){return M("signInSwitchPrompt")},get signInSwitchAction(){return M("signInSwitchAction")},get createSwitchPrompt(){return M("createSwitchPrompt")},get createSwitchAction(){return M("createSwitchAction")},get forgotPassword(){return M("forgotPassword")}
4,get otpToggle(){return M("otpToggle")},get otpToggleBack(){return M("otpToggleBack")},get otpSendButton(){return M("otpSendButton")},get otpSentPrefix(){return M("otpSentPrefix")},get otpCodeLabel(){return M("otpCodeLabel")},get otpCodeHint(){return M("otpCodeHint")},get otpVerifyButton(){return M("otpVerifyButton")},get otpResend(){return M("otpResend")},get manageHeading(){return M("manageHeading")},get changeEmailLabel(){return M("changeEmailLabel")},get changeEmailButton(){return M("changeEmailButton")},get changeEmailNewLabel(){return M("changeEmailNewLabel")},get changeEmailHint(){return M("changeEmailHint")},get changePasswordHeading(){return M("changePasswordHeading")},get changePasswordCurrentLabel(){return M("changePasswordCurrentLabel")},get changePasswordNewLabel(){return M("changePasswordNewLabel")},get changePasswordConfirmLabel(){return M("changePasswordConfirmLabel")},get changePasswordButton(){return M("changePasswordButton")},get setPasswordHeading(){return M("setPasswordHeading")},get setPasswordIntro(){return M("setPasswordIntro")},get setPasswordButton(){return M("setPasswordButton")},get setPasswordSent(){return M("setPasswordSent")},get verifyBannerTitle(){return M("verifyBannerTitle")},get verifyBannerBody(){return M("verifyBannerBody")},get verifyBannerMobileHint(){return M("verifyBannerMobileHint")},get resendVerification(){return M("resendVerification")},get conflictTitle(){return M("conflictTitle")},get busyTitle(){return M("busyTitle")},get refreshPage(){return M("refreshPage")},get trySyncAgain(){return M("trySyncAgain")},get dismissSyncBanner(){return M("dismissSyncBanner")},get verifyChecking(){return M("verifyChecking")},get verifyMissingToken(){return M("verifyMissingToken")},get verifySuccess(){return M("verifySuccess")},get emailChangeSuccess(){return M("emailChangeSuccess")},get verifyContinueApp(){return M("verifyContinueApp")},get verifyContinueWeb(){return M("verifyContinueWeb")},get verifyOpenSettings(){return M("verifyOpenSettings")},get securityHeading(){return M("securityHeading")},get passkeysHeading(){return M("passkeysHeading")},get passkeysIntro(){return M("passkeysIntro")},get passkeysEmpty(){return M("passkeysEmpty")},get passkeysIosHint(){return M("passkeysIosHint")},get passkeysEmbeddedHint(){return M("passkeysEmbeddedHint")},get passkeyRegisterSuccess(){return M("passkeyRegisterSuccess")},get passkeySuccessDismiss(){return M("passkeySuccessDismiss")},get passkeyRegistering(){return M("passkeyRegistering")},get sessionsHeading(){return M("sessionsHeading")},get sessionsIntro(){return M("sessionsIntro")},get sessionsLoading(){return M("sessionsLoading")},get signOutEverywhere(){return M("signOutEverywhere")},get signOutEverywhereConfirm(){return M("signOutEverywhereConfirm")},get signOutEverywhereSuccess(){return M("signOutEverywhereSuccess")},get signOutEverywhereNone(){return M("signOutEverywhereNone")},get signOutHere(){return M("signOutHere")},get revokeSession(){return M("revokeSession")},get sessionCurrent(){return M("sessionCurrent")},get accountSettings(){return M("accountSettings")},get manageAccount(){return M("manageAccount")},get yourDataPrivacy(){return M("yourDataPrivacy")},get accountPageTitle(){return M("accountPageTitle")},get settingsPageSubtitle(){return M("settingsPageSubtitle")},get searchSettingsPlaceholder(){return M("searchSettingsPlaceholder")},get searchSettingsAria(){return M("searchSettingsAria")},get searchSettingsClear(){return M("searchSettingsClear")},get searchSettingsNoMatch(){return M("searchSettingsNoMatch")},get sectionNavAria(){return M("sectionNavAria")},get sectionNavHeading(){return M("sectionNavHeading")},get msgCouldNotUpdateName(){return M("msgCouldNotUpdateName")},get msgVerificationSent(){return M("msgVerificationSent")},get msgCouldNotSendEmail(){return M("msgCouldNotSendEmail")},get msgCouldNotExport(){return M("msgCouldNotExport")},get msgChatHistoryDeleted(){return M("msgChatHistoryDeleted")},get msgCouldNotDeleteChat(){return M("msgCouldNotDeleteChat")},get msgCouldNotDeleteData(){return M("msgCouldNotDeleteData")},get msgDownloadBlocked(){return M("msgDownloadBlocked")},get passkeysRefresh(){return M("passkeysRefresh")},get passkeysAdd(){return M("passkeysAdd")},get passkeysCancelRequest(){return M("passkeysCancelRequest")},get passkeysOpenInBrowser(){return M("passkeysOpenInBrowser")},get passkeyNameLabel(){return M("passkeyNameLabel")},get mfaMethodLabel(){return M("mfaMethodLabel")},get mfaVerifyContinue(){return M("mfaVerifyContinue")}
4,get mfaFreshChallenge(){return M("mfaFreshChallenge")},get mfaSignOut(){return M("mfaSignOut")},get totpTitle(){return M("totpTitle")},get totpEmpty(){return M("totpEmpty")},get totpActive(){return M("totpActive")},get totpSetupIncomplete(){return M("totpSetupIncomplete")},get totpRemove(){return M("totpRemove")},get totpCancelSetup(){return M("totpCancelSetup")},get totpAdd(){return M("totpAdd")},get totpShowCode(){return M("totpShowCode")},get tabGeneral(){return M("tabGeneral")},get generalHeading(){return M("generalHeading")},get accountTabSignedOutBody(){return M("accountTabSignedOutBody")},get accountsUnavailableTitle(){return M("accountsUnavailableTitle")},get accountsUnavailableBody(){return M("accountsUnavailableBody")},get tabProfile(){return M("tabProfile")},get tabSecurity(){return M("tabSecurity")},get tabBilling(){return M("tabBilling")},get tabData(){return M("tabData")},get profileHeading(){return M("profileHeading")},get profileDisplayNameLabel(){return M("profileDisplayNameLabel")},get profileDisplayNameHint(){return M("profileDisplayNameHint")},get profileSaveName(){return M("profileSaveName")},get profileEmailLabel(){return M("profileEmailLabel")},get profileSignInMethodsLabel(){return M("profileSignInMethodsLabel")},get profileMemberSince(){return M("profileMemberSince")},get profileEmailUnverified(){return M("profileEmailUnverified")},get profileSaved(){return M("profileSaved")},get signInToManage(){return M("signInToManage")},get signInToManageBody(){return M("signInToManageBody")},get dataHeading(){return M("dataHeading")},get dataSyncedSummary(){return M("dataSyncedSummary")},get dataSavedSearches(){return M("dataSavedSearches")},get dataRecentSearches(){return M("dataRecentSearches")},get dataChatMessages(){return M("dataChatMessages")},get billingProPlan(){return M("billingProPlan")},get billingFreePlan(){return M("billingFreePlan")},get billingUnavailableHint(){return M("billingUnavailableHint")},get dataExport(){return M("dataExport")},get dataDeleteChat(){return M("dataDeleteChat")},get dataEraseHeading(){return M("dataEraseHeading")},get dataEraseBody(){return M("dataEraseBody")},get dataDeleteAll(){return M("dataDeleteAll")},get dataDeleteAllConfirm(){return M("dataDeleteAllConfirm")},get dataDeleteAllDone(){return M("dataDeleteAllDone")},get dataDangerHeading(){return M("dataDangerHeading")},get dataDeleteAccount(){return M("dataDeleteAccount")},get dataDeleteAccountBody(){return M("dataDeleteAccountBody")},get dataDeleteAccountConfirm(){return M("dataDeleteAccountConfirm")}};function Ou(e){return e?typeof e=="string"?{message:e,type:"conflict"}:{message:e.message||"",type:e.type==="busy"?"busy":"conflict"}:{message:"",type:"conflict"}}function Du(e){return e==="busy"?Q.busyTitle:Q.conflictTitle}function Hu(e,t){let{coordinator:n,getEmail:r,onBegin:s,onMessage:o,onSignedIn:a}=t,i=0,c=!1,l=e.createElement("div");l.className="settings-account__otp";let m=e.createElement("button");m.type="button",m.className="settings-account__link-button settings-account__otp-toggle",m.textContent=Q.otpToggle;let u=e.createElement("div");u.className="settings-account__otp-panel",u.hidden=!0;let d=e.createElement("input");d.type="email",d.name="otp-email",d.autocomplete="email",d.placeholder="[email protected]",d.inputMode="email";let h=yt({id:"settings-account-otp-email",label:Q.changeEmailLabel,input:d}),p=e.createElement("button");p.type="button",p.className="settings-account__primary settings-account__otp-send",p.textContent=Q.otpSendButton;let b=e.createElement("div");b.className="settings-account__otp-verify",b.hidden=!0;let v=e.createElement("p");v.className="settings-account__hint settings-account__otp-sent",v.setAttribute("role","status"),v.setAttribute("aria-live","polite");let E=e.createElement("input");E.type="text",E.name="otp-code",E.autocomplete="one-time-code",E.inputMode="numeric",E.setAttribute("pattern","[0-9]*"),E.maxLength=10,E.placeholder="123456";let A=yt({id:"settings-account-otp-code",label:Q.otpCodeLabel,input:E,hint:Q.otpCodeHint}),S=e.createElement("button");S.type="button",S.className="settings-account__primary settings-account__otp-confirm",S.textContent=Q.otpVerifyButton;let _=e.createElement("button");_.type="button",_.className="settings-account__link-button settings-account__otp-resend",_.textContent=Q.otpResend,b.append(v,A.field,S,_);let w=e.createElement("button");w.type="button",w.className="settings-account__link-button settings-account__otp-back",w.textContent=Q.otpToggleBack,u.append(h.field,p,b,w),l.append(m,u);function f(T){if(u.hidden=!T,m.hidden=T,T){let x=String(r()||"").trim();x&&!d.value&&(d.value=x),d.focus()}else b.hidden=!0,Le(A.errorEl,E,null)}function g(){i+=1,p.disabled=!1,_.disabled=!1,S.disabled=!1,f(!1)}m.addEventListener("click",()=>{s?.(),f(!0)}),w.addEventListener("click",()=>{g(),m.focus()});async function C(){s?.();let T=d.value.trim(),x=Zt(T);if(x){Le(h.errorEl,d,x),d.focus();return}Le(h.errorEl,d,null);let N=++i;p.disabled=!0,_.disabled=!0,o("");let B=await n.client.requestEmailSignInCode({email:T});if(!(c||N!==i)){if(p.disabled=!1,_.disabled=!1,!B.ok){o(B.data?.error?.message||"Could not send a sign-in code. Try again.",{isError:!0});return}v.textContent="".concat(Q.otpSentPrefix).concat(T,"."),b.hidden=!1,p.textContent=Q.otpResend,E.value="",E.focus()}}return p.addEventListener("click",C),_.addEventListener("click",C),S.addEventListener("click",async()=>{s?.();let T=d.value.trim(),x=E.value.trim();if(!x){Le(A.errorEl,E,"Enter the code from your email."),E.focus();return}Le(A.errorEl,E,null);let N=++i;S.disabled=!0,o("");let B=await n.client.verifyEmailSignInCode({email:T,token:x});if(!(c||N!==i)){if(S.disabled=!1,!B.ok){Le(A.errorEl,E,B.data?.error?.message||"That code is incorrect or expired.");return}await n.signInWithPayload(B.data),a()}}),{root:l,cancel:g,destroy(){c=!0,g()}}}var Gg={google:Q.signInGoogle,apple:Q.signInApple},Kg=["google","apple"];function Vg(e){let t=e.location||{},n=String(t.origin||"").replace(/\/+$/,""),r=String(t.pathname||"/"),s=String(t.search||"");return n?"".concat(n).concat(r).concat(s):"".concat(r).concat(s)}function $u(e,{coordinator:t,global:n}){let r=t.getState(),s=t.client?.supabase,o=Array.isArray(r.oauthProviders)?r.oauthProviders:[];if(!s||o.length===0)return null;let a=Kg.filter(m=>o.includes(m));if(a.length===0)return null;let i=e.createElement("div");i.className="settings-account__sign-in-methods";
4let c=Vg(n);for(let m of a){let u=e.createElement("a");u.href=s.oauthSignInUrl(m,c),u.className="settings-account__oauth settings-account__oauth--".concat(m),u.setAttribute("role","button");let d=e.createElement("span");d.className="settings-account__oauth-icon settings-account__oauth-icon--".concat(m),d.setAttribute("aria-hidden","true");let h=e.createElement("span");h.className="settings-account__oauth-label",h.textContent=Gg[m]||"Continue with ".concat(m),u.append(d,h),i.appendChild(u)}let l=e.createElement("p");return l.className="settings-account__or-divider",l.setAttribute("role","presentation"),l.textContent=Q.orDivider,{root:i,divider:l}}function Yg(e){return(Array.isArray(e?.factors)?e.factors:[]).filter(t=>["totp","email"].includes(String(t?.factor_type))&&t?.status==="verified"&&t.id)}function Fu(e,t){return e?.data?.error?.message||t}function Xg(e){return/^\d{6}$/.test(e.replace(/\s+/g,""))}function qu(e,t){let{coordinator:n,global:r}=t,s=e.ownerDocument||r.document,o=n.getState().mfa;e.replaceChildren();let a=s.createElement("section");a.className="settings-account__mfa-challenge",a.setAttribute("aria-labelledby","mfa-challenge-title");let i=s.createElement("h2");i.id="mfa-challenge-title",i.className="settings-account__title",i.textContent="Two-factor verification required";let c=s.createElement("p");c.className="settings-account__subtitle",c.textContent="Enter a code from a verified second factor before accessing your account data.";let l=s.createElement("p");if(l.className="settings-account__mfa-status",l.setAttribute("role","status"),l.setAttribute("aria-live","polite"),a.append(i,c,l),!o?.checked){l.textContent=o?.error?.message||"We could not verify your two-factor security status. Retry before continuing.";let w=s.createElement("button");return w.type="button",w.className="settings-account__secondary",w.textContent="Retry security check",w.addEventListener("click",async()=>{w.disabled=!0,await n.refreshStatus?.(),w.disabled=!1}),a.append(w,_()),e.append(a),w.focus(),{refresh(){}}}let m=Yg(o);if(m.length===0)return l.textContent="Your two-factor setup changed. Refresh the security check before continuing.",a.append(_()),e.append(a),{refresh(){}};let u=s.createElement("form");u.className="settings-account__form settings-account__mfa-form",u.noValidate=!0;let d=m[0];if(m.length>1){let w=s.createElement("label");w.className="settings-account__label",w.htmlFor="mfa-factor-select",w.textContent=Q.mfaMethodLabel;let f=s.createElement("select");f.id="mfa-factor-select",f.className="settings-account__input";for(let g of m){let C=s.createElement("option");C.value=String(g.id),C.textContent=g.factor_type==="email"?"Email code":String(g.friendly_name||"Authenticator app"),f.append(C)}f.addEventListener("change",()=>{d=m.find(g=>String(g.id)===f.value)||m[0],A()}),u.append(w,f)}let h=s.createElement("input");h.type="text",h.inputMode="numeric",h.autocomplete="one-time-code",h.maxLength=6,h.setAttribute("pattern","[0-9]{6}");let p=yt({id:"mfa-challenge-code",label:"Six-digit verification code",input:h,hint:"Use the newest code. If it expires, request a fresh challenge."}),b=s.createElement("button");b.type="submit",b.className="settings-account__primary",b.textContent=Q.mfaVerifyContinue;let v=s.createElement("button");v.type="button",v.className="settings-account__link-button",v.textContent=Q.mfaFreshChallenge,u.append(p.field,b,v),a.append(u,S()),e.append(a);let E="";async function A(){v.disabled=!0,b.disabled=!0;let w=d.factor_type==="email";if(w&&!o?.email?.primaryEligible){E="",v.disabled=!1,b.disabled=!0,l.textContent="An email sign-in code cannot also be your second factor. Sign out and use your password, Google, Apple, a Passkey, or an authenticator app.";return}l.textContent=w?"Sending a fresh email code\u2026":"Starting a fresh challenge\u2026";let f=w?await n.client.beginEmailMfaChallenge():await n.client.beginTotpChallenge({factorId:d.id});v.disabled=!1,b.disabled=!1;let g=String(f.data?.challengeId||f.data?.id||"");if(!f.ok||!g){E="",l.textContent=Fu(f,"Could not start a challenge. Try again."),v.focus();return}E=g,l.textContent=w?"Enter the code sent to ".concat(String(f.data?.maskedEmail||"your verified email"),"."):"Enter the current code from your authenticator app.",h.focus()}v.addEventListener("click",()=>{A()}),u.addEventListener("submit",async w=>{w.preventDefault();let f=h.value.replace(/\s+/g,"");if(!Xg(f)){Le(p.errorEl,h,"Enter a six-digit code."),h.focus();return}if(!E){Le(p.errorEl,h,"Start a fresh challenge first."),v.focus();return}Le(p.errorEl,h,null),b.disabled=!0,l.textContent="Verifying\u2026";let g=d.factor_type==="email"?await n.client.verifyEmailMfaChallenge({challengeId:E,code:f}):await n.client.verifyTotpChallenge({factorId:d.id,challengeId:E,code:f});if(b.disabled=!1,!g.ok){E="";let C=g.data?.error?.code==="challenge_expired";l.textContent=C?"That challenge expired. Start a fresh challenge and try again.":Fu(g,"That code was not accepted. Try a fresh challenge."),h.select?.(),h.focus();return}l.textContent="Two-factor verification complete.",await n.refreshStatus?.(),await n.mergePullAndPush?.({source:"mfa-verified"})});function S(){let w=s.createElement("div");w.className="settings-account__mfa-recovery";let f=s.createElement("p");return f.className="settings-account__hint",f.textContent=m.length>1?"Choose another verified method above if this one is unavailable.":d.factor_type==="email"?"Cannot access your email? Sign out and use another verified factor, or contact support for account recovery guidance.":"Lost your authenticator app? Do not bypass verification. Sign out and use another verified factor, or contact support for account recovery guidance.",w.append(f,_()),w}function _(){let w=s.createElement("button");return w.type="button",w.className="settings-account__link-button",w.textContent=Q.mfaSignOut,w.addEventListener("click",()=>{n.logout?.()}),w}return A(),{refresh(){}}}var Jg=["syncBenefitSaved","syncBenefitRecent","syncBenefitChat","syncBenefitPrefs"];function Uu(e,{compact:t=!1,signedIn:n=!1}={}){let r=e.createElement("div");if(r.className="settings-account__sync-benefits".concat(t?" settings-account__sync-benefits--compact":""),n){let o=e.createElement("p");o.className="settings-account__subtitle settings-account__sync-benefits-summary",o.textContent=Q.syncBenefitsSignedIn,r.appendChild(o)}else{let o=e.createElement("p");o.className="settings-account__heading settings-account__sync-benefits-heading",o.textContent=Q.syncBenefitsHeading,r.appendChild(o)}let s=e.createElement("ul");s.className="settings-account__sync-benefits-list";for(let o of Jg){let a=e.createElement("li");a.textContent=Q[o],s.appendChild(a)}return r.appendChild(s),r}function Cs(e,t,n){let r=e?.ownerDocument||t?.document,{message:s,type:o}=Ou(n);if(!e||!r||!s)return;let a=e.querySelector(".settings-account__sync-conflict");if(!a){a=r.createElement("div"),a.className="settings-account__sync-conflict settings-account__verify-banner",a.setAttribute("role","alert");let l=r.createElement("p");l.className="settings-account__sync-conflict-title",a.appendChild(l);let m=r.createElement("p");m.className="settings-account__sync-conflict-text",a.appendChild(m);let u=r.createElement("div");u.className="settings-account__sync-conflict-actions settings-account__verify-actions";let d=r.createElement("button");d.type="button",d.className="settings-account__primary",d.textContent=Q.refreshPage,d.addEventListener("click",()=>{t.location.reload()});let h=r.createElement("button");h.type="button",h.className="settings-account__secondary",h.textContent=Q.trySyncAgain,h.setAttribute("data-beamo-sync-retry","1");let p=r.createElement("button");p.type="button",p.className="settings-account__link-button",p.textContent=Q.dismissSyncBanner,p.setAttribute("data-beamo-sync-dismiss","1"),p.addEventListener("click",()=>{As(e),t.Beamo?.accounts?.clearSyncFailure?.()}),u.append(d,h,p),a.append(u),typeof e.prepend=="function"?e.prepend(a):e.f
4irstChild?e.insertBefore(a,e.firstChild):e.appendChild(a)}a.classList.toggle("settings-account__sync-conflict--busy",o==="busy"),a.classList.toggle("settings-account__sync-conflict--conflict",o!=="busy");let i=a.querySelector(".settings-account__sync-conflict-title");i&&(i.textContent=Du(o));let c=a.querySelector(".settings-account__sync-conflict-text");c&&(c.textContent=s),a.hidden=!1}function As(e){let t=e.querySelector(".settings-account__sync-conflict");t&&(t.hidden=!0)}function ju(e){return e?.message?{message:e.message,type:e.busy?"busy":"conflict"}:null}function he(e,t,{isError:n=!1}={}){let r=e.querySelector(".settings-account__message");if(r&&r.remove(),!t)return;let s=document.createElement("p");s.className="settings-account__message".concat(n?" settings-account__message--error":""),s.setAttribute("role",n?"alert":"status"),s.setAttribute("aria-live",n?"assertive":"polite"),s.textContent=t,e.prepend(s)}function zu({global:e,beamo:t,coordinator:n,host:r}){if(!r||!n)return()=>{};let s=oe(t),o=s.limits?.accountPasswordMin||8,a=128,i=80,c=()=>{},l=null,m=null;function u(){m?.abort(),m=null}function d(){let _=r.querySelector("[data-beamo-sync-retry]");!_||_.dataset.beamoSyncRetryBound==="1"||(_.dataset.beamoSyncRetryBound="1",_.addEventListener("click",async()=>{_.disabled=!0,he(r,"");try{let w=await n.mergePullAndPush({source:"settings-retry"});if(w.ok){As(r),c();return}let f=ju(w);if(f){Cs(r,e,f);return}he(r,we(globalThis)("accounts.syncErrorRetry"),{isError:!0})}catch{he(r,we(globalThis)("accounts.syncErrorRetry"),{isError:!0})}finally{_.disabled=!1}}))}function h(){r.replaceChildren(),he(r,"");let _="signin",w=document.createElement("div");w.className="settings-account__auth-header";let f=document.createElement("h2");f.className="settings-account__title";let g=document.createElement("p");if(g.className="settings-account__subtitle settings-account__auth-subtitle",w.append(f,g),r.appendChild(w),n.getState().passkeysSupported&&typeof n.client.signInWithPasskey=="function"){let Y=document.createElement("button");Y.type="button",Y.className="settings-account__oauth settings-account__passkey-sign-in",Y.textContent="Sign in with a Passkey",Y.setAttribute("aria-describedby","settings-passkey-note");let se=document.createElement("p");se.id="settings-passkey-note",se.className="settings-account__hint",se.textContent="Use Face ID, Touch ID, your device PIN, password manager, or a compatible security key.";let ae=document.createElement("button");ae.type="button",ae.className="settings-account__link-button settings-account__passkey-sign-in-cancel",ae.textContent="Cancel passkey request",ae.hidden=!0,ae.addEventListener("click",()=>{ae.disabled=!0,u(),Y.disabled=!1,ae.hidden=!0,he(r,"The passkey request was cancelled. You can try again.",{isError:!0}),Y.focus()}),Y.addEventListener("click",async()=>{l?.cancel(),u();let Me=e.AbortController||AbortController,Ue=new Me;m=Ue,Y.disabled=!0,ae.hidden=!1,ae.disabled=!1,he(r,"Waiting for your passkey\u2026");let Te;try{Te=await n.client.signInWithPasskey({signal:Ue.signal})}catch{Te={ok:!1,data:{error:{message:"Could not sign in with a Passkey. Use another sign-in method."}}}}if(m===Ue){if(m=null,Y.disabled=!1,ae.hidden=!0,ae.disabled=!1,!Te.ok){he(r,Te.data?.error?.message||"Could not sign in with a Passkey. Use another sign-in method.",{isError:!0}),Y.focus();return}await n.signInWithPayload(Te.data),E(),r.querySelector(".settings-account__manage-cta")?.focus()}}),r.append(Y,se,ae)}else if(wo(e)){let Y=document.createElement("p");Y.className="settings-account__hint settings-account__passkey-embedded-hint",Y.textContent="Passkeys are not available inside the Beamo app. Open Beamo Search in your browser to use a Passkey.",r.appendChild(Y)}let T=$u(document,{beamo:t,coordinator:n,global:e,onMessage:(Y,se)=>he(r,Y,se),onSignedIn:()=>E()});if(T){for(let Y of T.root.querySelectorAll("a"))Y.addEventListener("click",u);r.appendChild(T.root),r.appendChild(T.divider)}let x=document.createElement("form");x.className="settings-account__form",x.noValidate=!0;let N=document.createElement("input");N.type="email",N.name="email",N.autocomplete="username",N.placeholder="[email protected]",N.required=!0,N.inputMode="email";let B=document.createElement("input");B.type="password",B.name="password",B.autocomplete="current-password",B.placeholder="Password",B.minLength=o,B.maxLength=a,B.required=!0;let I=document.createElement("input");I.type="text",I.name="displayName",I.autocomplete="name",I.placeholder="Display name",I.maxLength=i;let y=yt({id:"settings-account-email",label:"Email",input:N}),k=yt({id:"settings-account-password",label:"Password",input:B}),P=yt({id:"settings-account-display-name",label:"Display name",input:I,optional:!0}),R={email:y,password:k,displayName:P};na(N,y.errorEl,Zt),na(B,k.errorEl,Y=>ea(Y,o,a));let D=Bu(document,{minLength:o,id:"settings-account-password-reqs"});B.addEventListener("input",()=>D.update(B.value));let L=document.createElement("button");L.type="submit",L.className="settings-account__primary",x.append(y.field,k.field,D.el,P.field,L),r.appendChild(x);let $=document.createElement("div");$.className="settings-account__auth-footer";let G=document.createElement("p");G.className="settings-account__mode-row";let J=document.createElement("span");J.className="settings-account__mode-prompt";let X=document.createElement("button");X.type="button",X.className="settings-account__secondary settings-account__mode-toggle",G.append(J,document.createTextNode(" "),X);let W=document.createElement("button");W.type="button",W.className="settings-account__link-button settings-account__forgot",W.textContent=Q.forgotPassword,W.addEventListener("click",async()=>{let Y=Zt(N.value);if(Y){Le(y.errorEl,N,Y),N.focus();return}W.disabled=!0,he(r,"");let se=await n.client.requestPasswordReset({email:N.value.trim()});if(W.disabled=!1,!se.ok){he(r,se.data?.error?.message||"Could not send reset email.",{isError:!0});return}he(r,se.data?.message||"If an account exists, a reset link was sent.")}),$.append(G,W),r.appendChild($);let V=Hu(document,{coordinator:n,getEmail:()=>N.value,onBegin:u,onMessage:(Y,se)=>he(r,Y,se),onSignedIn:()=>E()});l=V,r.appendChild(V.root);function j(){let Y=_==="create";f.textContent=Y?Q.createAccountTitle:Q.signInTitle,g.textContent=Y?Q.createAccountSubtitle:Q.signInSubtitle,L.textContent=Y?Q.createAccountSubmit:Q.signInSubmit,B.autocomplete=Y?"new-password":"current-password",D.el.hidden=!Y,P.field.hidden=!Y,W.hidden=Y,V.root.hidden=Y,J.textContent=Y?Q.createSwitchPrompt:Q.signInSwitchPrompt,X.textContent=Y?Q.createSwitchAction:Q.sign
4InSwitchAction}X.addEventListener("click",()=>{u(),V.cancel(),_=_==="create"?"signin":"create",he(r,""),j(),N.focus()}),j();async function ee(){u(),V.cancel();let Y=Lu({email:N.value,password:B.value},{minPassword:o,maxPassword:a});if(ra(R,Y),Object.keys(Y).length>0)return;L.disabled=!0,he(r,"");let se=await n.client.login({email:N.value.trim(),password:B.value});if(L.disabled=!1,!se.ok){let ae=se.data?.error?.code==="invalid_credentials"?se.data?.error?.message||"Could not sign in with that email and password.":se.data?.error?.message||se.data?.message||"Could not sign in.";he(r,ae,{isError:!0});return}await n.signInWithPayload(se.data),E()}async function Ee(){u(),V.cancel();let Y=Mu({email:N.value,password:B.value,displayName:I.value},{minPassword:o,maxPassword:a,maxDisplayName:i});if(ra(R,Y),Object.keys(Y).length>0)return;L.disabled=!0,he(r,"");let se=await n.client.register({email:N.value.trim(),password:B.value,displayName:I.value});if(L.disabled=!1,!se.ok){he(r,se.data?.error?.message||se.data?.message||we(globalThis)("accounts.createAccountError"),{isError:!0});return}if(!se.data?.account?.signedIn){he(r,se.data?.message||we(globalThis)("accounts.confirmEmailFirst"));return}await n.signInWithPayload(se.data),E()}x.addEventListener("submit",Y=>{Y.preventDefault(),_==="create"?Ee():ee()})}function p(){let _=r.querySelector(".settings-account__saved-list");if(!_)return;_.replaceChildren();let w=bl(e,s);if(w.length===0){let g=document.createElement("p");g.className="settings-account__empty",g.textContent=we(globalThis)("accounts.noSavedSearches"),_.appendChild(g);return}let f=document.createElement("ul");f.className="settings-account__saved-items";for(let g of w){let C=document.createElement("li"),T=document.createElement("a");T.href="/results?q=".concat(encodeURIComponent(g.q),"&type=web"),T.textContent=g.label||g.q,T.setAttribute("role","menuitem"),T.tabIndex=-1;let x=document.createElement("button");x.type="button",x.className="settings-account__remove",x.setAttribute("aria-label","".concat(we(globalThis)("accounts.removeSavedSearch")," ").concat(g.q)),x.textContent=we(globalThis)("accounts.removeSavedSearch"),x.addEventListener("click",async()=>{Sl(e,s,g.q);let N=await n.pushNow({source:"settings-saved-search"}),B=ju(N);B&&(Cs(r,e,B),d()),p()}),C.append(T,x),f.appendChild(C)}_.appendChild(f)}c=p;function b(_){if(r.replaceChildren(),he(r,""),_.mfa?.required||!_.mfa?.checked){qu(r,{coordinator:n,global:e,onMessage:(P,R)=>he(r,P,R)});return}if(_.mailConfigured&&!_.emailVerified){let P=document.createElement("div");P.className="settings-account__verify-banner settings-account__verify-banner--pending",P.setAttribute("role","status");let R=document.createElement("p");R.className="settings-account__verify-title",R.textContent=Q.verifyBannerTitle;let D=document.createElement("p");if(D.className="settings-account__verify-body",D.textContent=Q.verifyBannerBody,P.append(R,D),wo(e)){let G=document.createElement("p");G.className="settings-account__verify-hint",G.textContent=Q.verifyBannerMobileHint,P.appendChild(G)}let L=document.createElement("button");L.type="button",L.className="settings-account__secondary",L.textContent=Q.resendVerification,L.addEventListener("click",async()=>{L.disabled=!0;let G=await n.client.requestVerificationEmail();if(L.disabled=!1,!G.ok){he(r,G.data?.error?.message||"Could not send verification email.",{isError:!0});return}he(r,G.data?.message||"Verification email sent.")});let $=document.createElement("div");$.className="settings-account__verify-actions",$.appendChild(L),P.appendChild($),r.appendChild(P)}let w=String(_.account?.email||""),f=String(_.account?.displayName||""),g=document.createElement("div");g.className="settings-account__id";let C=document.createElement("span");C.className="settings-account__id-avatar",C.setAttribute("aria-hidden","true"),C.textContent=(f||w||"?").trim().charAt(0).toUpperCase()||"?";let T=document.createElement("div");T.className="settings-account__id-text";let x=document.createElement("p");if(x.className="settings-account__id-name",x.textContent=f||w||"Signed in",T.appendChild(x),w){let P=document.createElement("p");P.className="settings-account__id-email",P.textContent=w,T.appendChild(P)}let N=document.createElement("span");N.className="settings-account__plan-badge".concat(_.isPro?" settings-account__plan-badge--pro":""),N.textContent=_.isPro?"Pro":"Free",g.append(C,T,N),r.appendChild(g);let B=document.createElement("a");B.className="settings-account__primary settings-account__manage-cta",B.href=s.pages?.settings||s.pages?.account||"/settings",B.textContent=Q.accountSettings,r.appendChild(B);let I=document.createElement("div");I.className="settings-account__quick-links";let y=document.createElement("a");y.href=s.pages?.yourData||"/your-data",y.className="settings-account__link-button",y.textContent=Q.yourDataPrivacy;let k=document.createElement("button");k.type="button",k.className="settings-account__link-button settings-account__sign-out",k.textContent=we(globalThis)("accounts.signOut"),k.addEventListener("click",async()=>{k.disabled=!0,typeof n.logout=="function"?await n.logout():(await n.client.logout(),await n.refreshStatus()),k.disabled=!1,E()}),I.append(y,k),r.appendChild(I)}function v(){r.replaceChildren(),he(r,"");let _=document.createElement("p");_.className="settings-account__heading settings-account__coming-soon-title",_.textContent=Q.comingSoonTitle,r.appendChild(_);let w=document.createElement("p");w.className="settings-account__intro",w.textContent=Q.comingSoonBody,r.appendChild(w),r.appendChild(Uu(document));let f=document.createElement("p");f.className="settings-account__coming-soon-note",f.textContent=Q.comingSoonNote,r.appendChild(f)}function E(){l?.destroy(),l=null;let _=n.getState();if(r.closest("#settings-account-item")?.removeAttribute("hidden"),!_.enabled){u(),v();return}if(_.signedIn){u(),b(_);return}h()}let A=n.subscribe(()=>{E()}),S=n.subscribeSyncFailure?.(_=>{if(n.getState().signedIn){if(_?.message){Cs(r,e,_),d();return}As(r)}});return E(),()=>{u(),l?.destroy(),l=null,A(),S?.(),r.replaceChildren()}}
4function sa(e,t=globalThis){if(e.__accountsAttached)return e.accounts;let n=Pu(e,t);return e.accounts=n,e.__accountsAttached=!0,n}function Wu(e,t=globalThis){let n=sa(e,t);if(!n)return null;n.schedulePushWithChat=(o={})=>{n.schedulePush({...o,chatStateLoader:()=>n.fetchChatState()})};let r=t.document?.getElementById("settings-account-host"),s=null;return r&&(s=zu({global:t,beamo:e,coordinator:n,host:r})),(async()=>{try{await n.client.handleOAuthRedirect?.()}catch{}(await n.refreshStatus()).signedIn&&!n.getState().mfa?.required&&n.getState().mfa?.checked&&await n.mergePullAndPush({source:"accounts-init"})})(),{coordinator:n,dispose(){s?.()}}}function Gu(e=globalThis){let t=e.Beamo;if(!(!t||typeof t.fetchWithTimeout!="function")){if(e.document?.readyState==="loading"){e.document.addEventListener("DOMContentLoaded",()=>Wu(t,e),{once:!0});return}Wu(t,e)}}function Qg(e){let t=e.trim();if(!t)return"?";let n=Array.from(t)[0]??"";return n?n.toUpperCase():"?"}function Ku(e=globalThis){let t=e.document,r=e.Beamo?.accounts,s=t?.getElementById("header-account"),o=t?.getElementById("account-button"),a=t?.getElementById("account-label"),i=t?.getElementById("account-initial"),c=t?.getElementById("account-popover");if(!t||!s||!o||!a||!i||!c||!r||typeof r.getState!="function"||o.dataset&&o.dataset.accountControlBound==="1")return;o.dataset&&(o.dataset.accountControlBound="1");let l=s,m=o,u=a,d=i,h=c,p=r,b=!1;function v(){let S=p.getState?.()??{};if(l.hidden=!1,S.signedIn){let _=String(S.account?.displayName||S.account?.email||"Account");u.textContent=_,d.textContent=Qg(_),l.classList.add("header-account--signed-in"),l.classList.remove("header-account--signed-out","header-account--unconfigured"),m.setAttribute("aria-label","Account menu for ".concat(_));return}u.textContent="Sign in",d.textContent="",l.classList.add("header-account--signed-out"),l.classList.remove("header-account--signed-in"),l.classList.toggle("header-account--unconfigured",!S.enabled),m.setAttribute("aria-label",S.enabled?"Sign in or create an account":"Sign in to Beamo")}function E(){h.querySelector('a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus?.()}function A(S){b=S,h.hidden=!b,m.setAttribute("aria-expanded",b?"true":"false"),l.classList.toggle("header-account--open",b),b&&E()}m.addEventListener("click",S=>{S.stopPropagation(),A(!b)}),t.addEventListener("click",S=>{b&&!l.contains(S.target)&&A(!1)}),t.addEventListener("keydown",S=>{b&&S.key==="Escape"&&(S.preventDefault(),A(!1),m.focus?.())}),p.subscribe?.(()=>v()),v()}function Zg(e){if(!e||typeof e!="object")return!1;let t=e,n=t.tagName?.toLowerCase()||"";return n==="input"||n==="textarea"||n==="select"||t.isContentEditable?!0:!!t.closest?.('[contenteditable="true"]')}function Vu(e){return!!(e&&String(e.tagName||"").toLowerCase()==="input")}function ey(e,t={}){let n=t.resolveSearchInput||(()=>e.document?.getElementById("search-term"));function r(){let o=n();return Vu(o)?(o.focus({preventScroll:!1}),o.select?.(),!0):!1}function s(){e.__beamoSearchFocusShortcutAttached||(e.__beamoSearchFocusShortcutAttached=!0,e.document?.addEventListener("keydown",o=>{if(o.defaultPrevented||o.altKey)return;let a=String(o.key||""),i=a==="/"&&!o.ctrlKey&&!o.metaKey&&!o.shiftKey,c=(o.ctrlKey||o.metaKey)&&a.toLowerCase()==="k";!i&&!c||Zg(o.target)||Vu(n())&&(o.preventDefault(),r())}))}return{attach:s,focusPrimarySearch:r}}function Yu(e=globalThis,t={}){let n=ey(e,t);return n.attach(),n}var ed=2,ty=new Set(["AT","BE","BG","HR","CY","CZ","DK","EE","FI","FR","DE","GR","HU","IE","IT","LV","LT","LU","MT","NL","PL","PT","RO","SK","SI","ES","SE","IS","LI","NO"]);function ny(e,t){let n=String(e??"").trim().toUpperCase(),r=String(t??"").trim().toLowerCase();return ty.has(n)||n==="GB"||n==="CH"?"gdpr":n==="US"&&r==="california"?"ccpa":"general"}function td(e){return e?.storageKeys?.legalConsent||"beamo-legal-consent"}function nd(e){if(!e||typeof e!="object")return null;let t=e,n=String(t.region??"general");return{version:Number(t.version)||0,agreed:t.agreed===!0,region:n==="gdpr"||n==="ccpa"?n:"general",method:typeof t.method=="string"?t.method:void 0,agreedAt:Number(t.agreedAt)||0}}function Xu(e,t){let n=te(e,td(t),"");if(!n)return null;try{return nd(JSON.parse(n))}catch{return null}}function Ju(e){return!!e&&e.agreed===!0&&e.version>=ed}function Qu(e,t,n=Date.now()){return{version:ed,agreed:!0,region:e||"general",method:t||"agree",agreedAt:n}}function Zu(e,t,n){ie(e,td(t),JSON.stringify(n))}function rd(e=globalThis,t=e?.Beamo){let n=e.document,r=n?.getElementById?.("beamo-legal-consent");if(!r)return;let s=oe(t);if(Ju(Xu(e,s))){r.hidden=!0;return}let o=!1,a=null,i=null;function c(){r.hidden=!0,a?.(),i?.()}function l(u){if(o)return;o=!0;let d=r.getAttribute("data-legal-region")||"general";Zu(e,s,Qu(d,u)),c();try{t?.accounts?.schedulePushWithChat?.()}catch{}}r.hidden=!1,r.querySelector("[data-legal-consent-agree]")?.addEventListener("click",()=>l("agree")),r.querySelector("[data-legal-consent-dismiss]")?.addEventListener("click",()=>l("dismiss"));let m=()=>l("implied");n.addEventListener?.("submit",m,!0),i=()=>n.removeEventListener?.("submit",m,!0),a=El(e,u=>{let d=nd(u?.detail?.preferences?.legalConsent);Ju(d)&&(o=!0,c())}),ry(e,t,r).then(u=>{if(!o||u==="general")return;let d=Xu(e,s);if(d&&d.region==="general"){Zu(e,s,Qu(u,d.method,d.agreedAt));try{t?.accounts?.schedulePushWithChat?.()}catch{}}})}async function ry(e,t,n){let r="general";try{let o=await(t?.getLocationData??Or)({fallbackOnError:!0});r=ny(o?.country,o?.region)}catch{r="general"}n.setAttribute("data-legal-region",r);for(let s of n.querySelectorAll("[data-legal-region-note]"))s.hidden=s.getAttribute("data-legal-region-note")!==r;return r}function sy(e){return e?.endpoints?.audienceBeacon||"/PHP/audience_beacon.php"}function oy(e,t,n){try{let r=e.fetch;if(typeof r!="function")return;r(sy(t),{method:"POST",credentials:"same-origin",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}).catch(()=>{})}catch{}}function ay(e){let t=e.document;return!t||typeof t.querySelector!="function"?"":(t.querySelector('meta[name="beamo-analytics-page"]')?.content||"").trim()}function sd(e,t){let n=e.document;if(!n)return;let r=e;if(r.__beamoPageviewSent)return;let s=()=>
4{if(r.__beamoPageviewSent)return;let a=ay(e);a!==""&&(r.__beamoPageviewSent=!0,oy(e,t,{type:"pageview",page:a}))},o=()=>{let a=e.requestIdleCallback;typeof a=="function"?a(s,{timeout:4e3}):typeof e.setTimeout=="function"?e.setTimeout(s,1200):s()};n.readyState==="complete"||n.readyState==="interactive"?o():typeof e.addEventListener=="function"?e.addEventListener("DOMContentLoaded",o,{once:!0}):o()}var bt=globalThis.Beamo,Es=oe(bt);qi(bt,globalThis,Es);Yu(globalThis);sa(bt,globalThis);Ki(bt,globalThis);Vi(bt,globalThis);Xi(bt,globalThis);lc(bt,globalThis);kc(bt,globalThis);Cc(globalThis);xc(globalThis,Es);Rc(globalThis,Es);Oc(globalThis);Dc(globalThis);jc(globalThis);zc(globalThis);Wc(globalThis);Yc(globalThis);Xc(globalThis);tl(globalThis);nl(globalThis);rl(globalThis);al(globalThis);ll(globalThis);Gu(globalThis);Nc(globalThis);Ku(globalThis);Aa(globalThis);rd(globalThis,bt);sd(globalThis,Es);})();
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.