-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-c71c72d9.js
7 lines (7 loc) · 238 KB
/
index-c71c72d9.js
1
2
3
4
5
6
7
(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function t(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=t(i);fetch(i.href,s)}})();(function(){try{if(typeof document<"u"){var n=document.createElement("style");n.appendChild(document.createTextNode(":root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:light dark;color:#ffffffde;background-color:#242424;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}body{margin:0;min-width:320px;min-height:100vh;background-image:linear-gradient(45deg,hsl(240deg 100% 20%) 0%,hsl(289deg 100% 21%) 11%,hsl(315deg 100% 27%) 22%,hsl(329deg 100% 36%) 33%,hsl(337deg 100% 43%) 44%,hsl(357deg 91% 59%) 56%,hsl(17deg 100% 59%) 67%,hsl(34deg 100% 53%) 78%,hsl(45deg 100% 50%) 89%,hsl(55deg 100% 50%) 100%);overflow-y:hidden}h1{font-size:3.2em;line-height:1.1}@media (prefers-color-scheme: light){:root{color:#213547;background-color:#fff}a:hover{color:#747bff}button{background-color:transparent}}.station-card.svelte-vt3xxd{border-radius:8px;border:4px solid black;font-size:1em;font-weight:500;font-family:inherit;background-color:#f9f9f9;transition:border-color .25s;grid-template-rows:auto auto;padding-left:1rem;padding-right:1rem;padding-bottom:.5rem}main.svelte-vt3xxd{display:flex;flex-direction:column;place-items:center;height:100vh;overflow-y:auto}.stations-grid.svelte-vt3xxd{display:grid;grid-template-columns:repeat(auto-fit,minmax(20rem,1fr));gap:1rem;width:80%}.station-title.svelte-vt3xxd{font-size:1.5em;display:flex;justify-content:center;width:100%}.time.svelte-vt3xxd{padding-top:1rem;font-size:3.2rem;font-weight:700}.date.svelte-vt3xxd{padding-bottom:1.5rem}.train-title.svelte-vt3xxd{display:flex;flex-direction:row;gap:.5rem;align-items:center}.line-circles.svelte-vt3xxd{display:flex;flex-direction:row;min-width:2rem}.line-circle.svelte-vt3xxd{height:1rem;width:1rem;border-radius:.5rem}.arriving-now-chip.svelte-vt3xxd{border-radius:4px;padding:.2rem;border:1px solid #2d72d2;color:#fff;background-color:#2d72d2;text-justify:center;text-wrap:nowrap}.manual-refresh.svelte-vt3xxd{cursor:pointer;display:flex;align-items:center;gap:.5rem;transition:.5s;border:2px solid transparent;width:fit-content;border-radius:4px;padding:.2rem}.manual-refresh.svelte-vt3xxd:hover{border-color:#fff}@keyframes svelte-vt3xxd-rotation{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.spinner.svelte-vt3xxd{animation:svelte-vt3xxd-rotation .5s infinite linear}.refresh-row.svelte-vt3xxd{display:flex;flex-direction:row;align-items:center;gap:1rem}@media (prefers-color-scheme: dark){.station-card.svelte-vt3xxd{background-color:#242424;border-color:#ffffffde}}")),document.head.appendChild(n)}}catch(e){console.error("vite-plugin-css-injected-by-js",e)}})();var wo=Object.defineProperty,ko=(n,e,t)=>e in n?wo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ni=(n,e,t)=>(ko(n,typeof e!="symbol"?e+"":e,t),t);function So(n,e){for(var t=0;t<e.length;t++){const r=e[t];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in n)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(n,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))t(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const s of i.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&t(s)}).observe(document,{childList:!0,subtree:!0});function e(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function t(r){if(r.ep)return;r.ep=!0;const i=e(r);fetch(r.href,i)}})();function rt(){}function gs(n){return n()}function ri(){return Object.create(null)}function In(n){n.forEach(gs)}function vs(n){return typeof n=="function"}function To(n,e){return n!=n?e==e:n!==e||n&&typeof n=="object"||typeof n=="function"}function Eo(n){return Object.keys(n).length===0}function ii(n){return n??""}function C(n,e){n.appendChild(e)}function Ge(n,e,t){n.insertBefore(e,t||null)}function De(n){n.parentNode&&n.parentNode.removeChild(n)}function Ir(n,e){for(let t=0;t<n.length;t+=1)n[t]&&n[t].d(e)}function H(n){return document.createElement(n)}function Zt(n){return document.createElementNS("http://www.w3.org/2000/svg",n)}function We(n){return document.createTextNode(n)}function Se(){return We(" ")}function xo(n,e,t,r){return n.addEventListener(e,t,r),()=>n.removeEventListener(e,t,r)}function N(n,e,t){t==null?n.removeAttribute(e):n.getAttribute(e)!==t&&n.setAttribute(e,t)}function Po(n){return Array.from(n.childNodes)}function it(n,e){e=""+e,n.data!==e&&(n.data=e)}function si(n,e,t,r){t==null?n.style.removeProperty(e):n.style.setProperty(e,t,r?"important":"")}let zt;function Dt(n){zt=n}function Ro(){if(!zt)throw new Error("Function called outside component initialization");return zt}function Oo(n){Ro().$$.on_mount.push(n)}const dt=[],oi=[];let mt=[];const ai=[],$o=Promise.resolve();let tr=!1;function Io(){tr||(tr=!0,$o.then(_s))}function nr(n){mt.push(n)}const Mn=new Set;let ct=0;function _s(){if(ct!==0)return;const n=zt;do{try{for(;ct<dt.length;){const e=dt[ct];ct++,Dt(e),Co(e.$$)}}catch(e){throw dt.length=0,ct=0,e}for(Dt(null),dt.length=0,ct=0;oi.length;)oi.pop()();for(let e=0;e<mt.length;e+=1){const t=mt[e];Mn.has(t)||(Mn.add(t),t())}mt.length=0}while(dt.length);for(;ai.length;)ai.pop()();tr=!1,Mn.clear(),Dt(n)}function Co(n){if(n.fragment!==null){n.update(),In(n.before_update);const e=n.dirty;n.dirty=[-1],n.fragment&&n.fragment.p(n.ctx,e),n.after_update.forEach(nr)}}function Ao(n){const e=[],t=[];mt.forEach(r=>n.indexOf(r)===-1?e.push(r):t.push(r)),t.forEach(r=>r()),mt=e}const jo=new Set;function Fo(n,e){n&&n.i&&(jo.delete(n),n.i(e))}function Tt(n){return(n==null?void 0:n.length)!==void 0?n:Array.from(n)}function Lo(n,e,t){const{fragment:r,after_update:i}=n.$$;r&&r.m(e,t),nr(()=>{const s=n.$$.on_mount.map(gs).filter(vs);n.$$.on_destroy?n.$$.on_destroy.push(...s):In(s),n.$$.on_mount=[]}),i.forEach(nr)}function Do(n,e){const t=n.$$;t.fragment!==null&&(Ao(t.after_update),In(t.on_destroy),t.fragment&&t.fragment.d(e),t.on_destroy=t.fragment=null,t.ctx=[])}function No(n,e){n.$$.dirty[0]===-1&&(dt.push(n),Io(),n.$$.dirty.fill(0)),n.$$.dirty[e/31|0]|=1<<e%31}function qo(n,e,t,r,i,s,o,a=[-1]){const l=zt;Dt(n);const c=n.$$={fragment:null,ctx:[],props:s,update:rt,not_equal:i,bound:ri(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(e.context||(l?l.$$.context:[])),callbacks:ri(),dirty:a,skip_bound:!1,root:e.target||l.$$.root};o&&o(c.root);let u=!1;if(c.ctx=t?t(n,e.props||{},(h,d,...p)=>{const f=p.length?p[0]:d;return c.ctx&&i(c.ctx[h],c.ctx[h]=f)&&(!c.skip_bound&&c.bound[h]&&c.bound[h](f),u&&No(n,h)),d}):[],c.update(),u=!0,In(c.before_update),c.fragment=r?r(c.ctx):!1,e.target){if(e.hydrate){const h=Po(e.target);c.fragment&&c.fragment.l(h),h.forEach(De)}else c.fragment&&c.fragment.c();e.intro&&Fo(n.$$.fragment),Lo(n,e.target,e.anchor),_s()}Dt(l)}class Mo{constructor(){ni(this,"$$"),ni(this,"$$set")}$destroy(){Do(this,1),this.$destroy=rt}$on(e,t){if(!vs(t))return rt;const r=this.$$.callbacks[e]||(this.$$.callbacks[e]=[]);return r.push(t),()=>{const i=r.indexOf(t);i!==-1&&r.splice(i,1)}}$set(e){this.$$set&&!Eo(e)&&(this.$$.skip_bound=!0,this.$$set(e),this.$$.skip_bound=!1)}}const Uo="4";typeof window<"u"&&(window.__svelte||(window.__svelte={v:new Set})).v.add(Uo);const Bo="modulepreload",Ho=function(n){return"/"+n},li={},Cn=function(n,e,t){if(!e||e.length===0)return n();const r=document.getElementsByTagName("link");return Promise.all(e.map(i=>{if(i=Ho(i),i in li)return;li[i]=!0;const s=i.endsWith(".css"),o=s?'[rel="stylesheet"]':"";if(t)for(let l=r.length-1;l>=0;l--){const c=r[l];if(c.href===i&&(!s||c.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${i}"]${o}`))return;const a=document.createElement("link");if(a.rel=s?"stylesheet":Bo,s||(a.as="script",a.crossOrigin=""),a.href=i,document.head.appendChild(a),s)return new Promise((l,c)=>{a.addEventListener("load",l),a.addEventListener("error",()=>c(new Error(`Unable to preload CSS for ${i}`)))})})).then(()=>n()).catch(i=>{const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=i,window.dispatchEvent(s),!s.defaultPrevented)throw i})};var zo=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const Vo=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>zo(void 0,void 0,void 0,function*(){return yield(yield Cn(()=>Promise.resolve().then(()=>jn),void 0)).fetch(...t)}):e=fetch,(...t)=>e(...t)};class Cr extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class Jo extends Cr{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class Wo extends Cr{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class Go extends Cr{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}var Ko=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};class Qo{constructor(e,{headers:t={},customFetch:r}={}){this.url=e,this.headers=t,this.fetch=Vo(r)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var r;return Ko(this,void 0,void 0,function*(){try{const{headers:i,method:s,body:o}=t;let a={},l;o&&(i&&!Object.prototype.hasOwnProperty.call(i,"Content-Type")||!i)&&(typeof Blob<"u"&&o instanceof Blob||o instanceof ArrayBuffer?(a["Content-Type"]="application/octet-stream",l=o):typeof o=="string"?(a["Content-Type"]="text/plain",l=o):typeof FormData<"u"&&o instanceof FormData?l=o:(a["Content-Type"]="application/json",l=JSON.stringify(o)));const c=yield this.fetch(`${this.url}/${e}`,{method:s||"POST",headers:Object.assign(Object.assign(Object.assign({},a),this.headers),i),body:l}).catch(p=>{throw new Jo(p)}),u=c.headers.get("x-relay-error");if(u&&u==="true")throw new Wo(c);if(!c.ok)throw new Go(c);let h=((r=c.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),d;return h==="application/json"?d=yield c.json():h==="application/octet-stream"?d=yield c.blob():h==="multipart/form-data"?d=yield c.formData():d=yield c.text(),{data:d,error:null}}catch(i){return{data:null,error:i}}})}}var rr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ms(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var ir={exports:{}};(function(n,e){var t=function(){if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof rr<"u")return rr;throw new Error("unable to locate global object")},r=t();n.exports=e=r.fetch,r.fetch&&(e.default=r.fetch.bind(r)),e.Headers=r.Headers,e.Request=r.Request,e.Response=r.Response})(ir,ir.exports);var Yo=ir.exports;const Xo=ms(Yo);class Zo{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:typeof fetch>"u"?this.fetch=Xo:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let i=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async s=>{var o,a,l;let c=null,u=null,h=null,d=s.status,p=s.statusText;if(s.ok){if(this.method!=="HEAD"){const m=await s.text();m===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=m:u=JSON.parse(m))}const f=(o=this.headers.Prefer)===null||o===void 0?void 0:o.match(/count=(exact|planned|estimated)/),g=(a=s.headers.get("content-range"))===null||a===void 0?void 0:a.split("/");f&&g&&g.length>1&&(h=parseInt(g[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(c={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,d=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const f=await s.text();try{c=JSON.parse(f),Array.isArray(c)&&s.status===404&&(u=[],c=null,d=200,p="OK")}catch{s.status===404&&f===""?(d=204,p="No Content"):c={message:f}}if(c&&this.isMaybeSingle&&!((l=c==null?void 0:c.details)===null||l===void 0)&&l.includes("Results contain 0 rows")&&(c=null,d=200,p="OK"),c&&this.shouldThrowOnError)throw c}return{error:c,data:u,count:h,status:d,statusText:p}});return this.shouldThrowOnError||(i=i.catch(s=>{var o,a,l;return{error:{message:`${(o=s==null?void 0:s.name)!==null&&o!==void 0?o:"FetchError"}: ${s==null?void 0:s.message}`,details:`${(a=s==null?void 0:s.stack)!==null&&a!==void 0?a:""}`,hint:"",code:`${(l=s==null?void 0:s.code)!==null&&l!==void 0?l:""}`},data:null,count:null,status:0,statusText:""}})),i.then(e,t)}}class ea extends Zo{select(e){let t=!1;const r=(e??"*").split("").map(i=>/\s/.test(i)&&!t?"":(i==='"'&&(t=!t),i)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:i}={}){const s=i?`${i}.order`:"order",o=this.url.searchParams.get(s);return this.url.searchParams.set(s,`${o?`${o},`:""}${e}.${t?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t}={}){const r=typeof t>"u"?"limit":`${t}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:r}={}){const i=typeof r>"u"?"offset":`${r}.offset`,s=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(s,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:i=!1,wal:s=!1,format:o="text"}={}){const a=[e?"analyze":null,t?"verbose":null,r?"settings":null,i?"buffers":null,s?"wal":null].filter(Boolean).join("|"),l=this.headers.Accept;return this.headers.Accept=`application/vnd.pgrst.plan+${o}; for="${l}"; options=${a};`,o==="json"?this:this}rollback(){var e;return((e=this.headers.Prefer)!==null&&e!==void 0?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class ft extends ea{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){const r=t.map(i=>typeof i=="string"&&new RegExp("[,()]").test(i)?`"${i}"`:`${i}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t=="string"?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t=="string"?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:i}={}){let s="";i==="plain"?s="pl":i==="phrase"?s="ph":i==="websearch"&&(s="w");const o=r===void 0?"":`(${r})`;return this.url.searchParams.append(e,`${s}fts${o}.${t}`),this}match(e){return Object.entries(e).forEach(([t,r])=>{this.url.searchParams.append(t,`eq.${r}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t}={}){const r=t?`${t}.or`:"or";return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class ta{constructor(e,{headers:t={},schema:r,fetch:i}){this.url=e,this.headers=t,this.schema=r,this.fetch=i}select(e,{head:t=!1,count:r}={}){const i=t?"HEAD":"GET";let s=!1;const o=(e??"*").split("").map(a=>/\s/.test(a)&&!s?"":(a==='"'&&(s=!s),a)).join("");return this.url.searchParams.set("select",o),r&&(this.headers.Prefer=`count=${r}`),new ft({method:i,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){const i="POST",s=[];if(this.headers.Prefer&&s.push(this.headers.Prefer),t&&s.push(`count=${t}`),r||s.push("missing=default"),this.headers.Prefer=s.join(","),Array.isArray(e)){const o=e.reduce((a,l)=>a.concat(Object.keys(l)),[]);if(o.length>0){const a=[...new Set(o)].map(l=>`"${l}"`);this.url.searchParams.set("columns",a.join(","))}}return new ft({method:i,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:i,defaultToNull:s=!0}={}){const o="POST",a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(t!==void 0&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),i&&a.push(`count=${i}`),s||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){const l=e.reduce((c,u)=>c.concat(Object.keys(u)),[]);if(l.length>0){const c=[...new Set(l)].map(u=>`"${u}"`);this.url.searchParams.set("columns",c.join(","))}}return new ft({method:o,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){const r="PATCH",i=[];return this.headers.Prefer&&i.push(this.headers.Prefer),t&&i.push(`count=${t}`),this.headers.Prefer=i.join(","),new ft({method:r,url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){const t="DELETE",r=[];return e&&r.push(`count=${e}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new ft({method:t,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}const na="1.8.4",ra={"X-Client-Info":`postgrest-js/${na}`};class Ar{constructor(e,{headers:t={},schema:r,fetch:i}={}){this.url=e,this.headers=Object.assign(Object.assign({},ra),t),this.schemaName=r,this.fetch=i}from(e){const t=new URL(`${this.url}/${e}`);return new ta(t,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new Ar(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,count:i}={}){let s;const o=new URL(`${this.url}/rpc/${e}`);let a;r?(s="HEAD",Object.entries(t).forEach(([c,u])=>{o.searchParams.append(c,`${u}`)})):(s="POST",a=t);const l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new ft({method:s,url:o,headers:l,schema:this.schemaName,body:a,fetch:this.fetch,allowEmpty:!1})}}var Un,ci;function ia(){if(ci)return Un;ci=1;var n=function(){if(typeof self=="object"&&self)return self;if(typeof window=="object"&&window)return window;throw new Error("Unable to resolve global `this`")};return Un=function(){if(this)return this;if(typeof globalThis=="object"&&globalThis)return globalThis;try{Object.defineProperty(Object.prototype,"__global__",{get:function(){return this},configurable:!0})}catch{return n()}try{return __global__||n()}finally{delete Object.prototype.__global__}}(),Un}const sa="websocket",oa="Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.",aa=["websocket","websockets","socket","networking","comet","push","RFC-6455","realtime","server","client"],la="Brian McKelvey <[email protected]> (https://github.com/theturtle32)",ca=["Iñaki Baz Castillo <[email protected]> (http://dev.sipdoc.net)"],ua="1.0.34",ha={type:"git",url:"https://github.com/theturtle32/WebSocket-Node.git"},da="https://github.com/theturtle32/WebSocket-Node",fa={node:">=4.0.0"},pa={bufferutil:"^4.0.1",debug:"^2.2.0","es5-ext":"^0.10.50","typedarray-to-buffer":"^3.1.5","utf-8-validate":"^5.0.2",yaeti:"^0.0.6"},ga={"buffer-equal":"^1.0.0",gulp:"^4.0.2","gulp-jshint":"^2.0.4","jshint-stylish":"^2.2.1",jshint:"^2.0.0",tape:"^4.9.1"},va={verbose:!1},_a={test:"tape test/unit/*.js",gulp:"gulp"},ma="index",ya={lib:"./lib"},ba="lib/browser.js",wa="Apache-2.0",ka={name:sa,description:oa,keywords:aa,author:la,contributors:ca,version:ua,repository:ha,homepage:da,engines:fa,dependencies:pa,devDependencies:ga,config:va,scripts:_a,main:ma,directories:ya,browser:ba,license:wa};var Sa=ka.version,Xe;if(typeof globalThis=="object")Xe=globalThis;else try{Xe=ia()}catch{}finally{if(!Xe&&typeof window<"u"&&(Xe=window),!Xe)throw new Error("Could not determine global this")}var Vt=Xe.WebSocket||Xe.MozWebSocket,Ta=Sa;function ys(n,e){var t;return e?t=new Vt(n,e):t=new Vt(n),t}Vt&&["CONNECTING","OPEN","CLOSING","CLOSED"].forEach(function(n){Object.defineProperty(ys,n,{get:function(){return Vt[n]}})});var Ea={w3cwebsocket:Vt?ys:null,version:Ta};const xa="2.7.4",Pa={"X-Client-Info":`realtime-js/${xa}`},Ra="1.0.0",bs=1e4,Oa=1e3;var Nt;(function(n){n[n.connecting=0]="connecting",n[n.open=1]="open",n[n.closing=2]="closing",n[n.closed=3]="closed"})(Nt||(Nt={}));var _e;(function(n){n.closed="closed",n.errored="errored",n.joined="joined",n.joining="joining",n.leaving="leaving"})(_e||(_e={}));var xe;(function(n){n.close="phx_close",n.error="phx_error",n.join="phx_join",n.reply="phx_reply",n.leave="phx_leave",n.access_token="access_token"})(xe||(xe={}));var sr;(function(n){n.websocket="websocket"})(sr||(sr={}));var Ze;(function(n){n.Connecting="connecting",n.Open="open",n.Closing="closing",n.Closed="closed"})(Ze||(Ze={}));class ws{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class $a{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):t(typeof e=="string"?JSON.parse(e):{})}_binaryDecode(e){const t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){const i=t.getUint8(1),s=t.getUint8(2);let o=this.HEADER_LENGTH+2;const a=r.decode(e.slice(o,o+i));o=o+i;const l=r.decode(e.slice(o,o+s));o=o+s;const c=JSON.parse(r.decode(e.slice(o,e.byteLength)));return{ref:null,topic:a,event:l,payload:c}}}class Bn{constructor(e,t,r={},i=bs){this.channel=e,this.event=t,this.payload=r,this.timeout=i,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null,this.rateLimited=!1}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()})==="rate limited"&&(this.rateLimited=!0))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const e=t=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=t,this._matchReceive(t)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(r=>r.status===e).forEach(r=>r.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}var ui;(function(n){n.SYNC="sync",n.JOIN="join",n.LEAVE="leave"})(ui||(ui={}));class qt{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(t==null?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},i=>{const{onJoin:s,onLeave:o,onSync:a}=this.caller;this.joinRef=this.channel._joinRef(),this.state=qt.syncState(this.state,i,s,o),this.pendingDiffs.forEach(l=>{this.state=qt.syncDiff(this.state,l,s,o)}),this.pendingDiffs=[],a()}),this.channel._on(r.diff,{},i=>{const{onJoin:s,onLeave:o,onSync:a}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(i):(this.state=qt.syncDiff(this.state,i,s,o),a())}),this.onJoin((i,s,o)=>{this.channel._trigger("presence",{event:"join",key:i,currentPresences:s,newPresences:o})}),this.onLeave((i,s,o)=>{this.channel._trigger("presence",{event:"leave",key:i,currentPresences:s,leftPresences:o})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,i){const s=this.cloneDeep(e),o=this.transformState(t),a={},l={};return this.map(s,(c,u)=>{o[c]||(l[c]=u)}),this.map(o,(c,u)=>{const h=s[c];if(h){const d=u.map(m=>m.presence_ref),p=h.map(m=>m.presence_ref),f=u.filter(m=>p.indexOf(m.presence_ref)<0),g=h.filter(m=>d.indexOf(m.presence_ref)<0);f.length>0&&(a[c]=f),g.length>0&&(l[c]=g)}else a[c]=u}),this.syncDiff(s,{joins:a,leaves:l},r,i)}static syncDiff(e,t,r,i){const{joins:s,leaves:o}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),i||(i=()=>{}),this.map(s,(a,l)=>{var c;const u=(c=e[a])!==null&&c!==void 0?c:[];if(e[a]=this.cloneDeep(l),u.length>0){const h=e[a].map(p=>p.presence_ref),d=u.filter(p=>h.indexOf(p.presence_ref)<0);e[a].unshift(...d)}r(a,u,l)}),this.map(o,(a,l)=>{let c=e[a];if(!c)return;const u=l.map(h=>h.presence_ref);c=c.filter(h=>u.indexOf(h.presence_ref)<0),e[a]=c,i(a,c,l),c.length===0&&delete e[a]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return e=this.cloneDeep(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{const i=e[r];return"metas"in i?t[r]=i.metas.map(s=>(s.presence_ref=s.phx_ref,delete s.phx_ref,delete s.phx_ref_prev,s)):t[r]=i,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var U;(function(n){n.abstime="abstime",n.bool="bool",n.date="date",n.daterange="daterange",n.float4="float4",n.float8="float8",n.int2="int2",n.int4="int4",n.int4range="int4range",n.int8="int8",n.int8range="int8range",n.json="json",n.jsonb="jsonb",n.money="money",n.numeric="numeric",n.oid="oid",n.reltime="reltime",n.text="text",n.time="time",n.timestamp="timestamp",n.timestamptz="timestamptz",n.timetz="timetz",n.tsrange="tsrange",n.tstzrange="tstzrange"})(U||(U={}));const hi=(n,e,t={})=>{var r;const i=(r=t.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(e).reduce((s,o)=>(s[o]=Ia(o,n,e,i),s),{})},Ia=(n,e,t,r)=>{const i=e.find(a=>a.name===n),s=i==null?void 0:i.type,o=t[n];return s&&!r.includes(s)?ks(s,o):or(o)},ks=(n,e)=>{if(n.charAt(0)==="_"){const t=n.slice(1,n.length);return Fa(e,t)}switch(n){case U.bool:return Ca(e);case U.float4:case U.float8:case U.int2:case U.int4:case U.int8:case U.numeric:case U.oid:return Aa(e);case U.json:case U.jsonb:return ja(e);case U.timestamp:return La(e);case U.abstime:case U.date:case U.daterange:case U.int4range:case U.int8range:case U.money:case U.reltime:case U.text:case U.time:case U.timestamptz:case U.timetz:case U.tsrange:case U.tstzrange:return or(e);default:return or(e)}},or=n=>n,Ca=n=>{switch(n){case"t":return!0;case"f":return!1;default:return n}},Aa=n=>{if(typeof n=="string"){const e=parseFloat(n);if(!Number.isNaN(e))return e}return n},ja=n=>{if(typeof n=="string")try{return JSON.parse(n)}catch(e){return console.log(`JSON parse error: ${e}`),n}return n},Fa=(n,e)=>{if(typeof n!="string")return n;const t=n.length-1,r=n[t];if(n[0]==="{"&&r==="}"){let i;const s=n.slice(1,t);try{i=JSON.parse("["+s+"]")}catch{i=s?s.split(","):[]}return i.map(o=>ks(e,o))}return n},La=n=>typeof n=="string"?n.replace(" ","T"):n;var di=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})},fi;(function(n){n.ALL="*",n.INSERT="INSERT",n.UPDATE="UPDATE",n.DELETE="DELETE"})(fi||(fi={}));var pi;(function(n){n.BROADCAST="broadcast",n.PRESENCE="presence",n.POSTGRES_CHANGES="postgres_changes"})(pi||(pi={}));var gi;(function(n){n.SUBSCRIBED="SUBSCRIBED",n.TIMED_OUT="TIMED_OUT",n.CLOSED="CLOSED",n.CHANNEL_ERROR="CHANNEL_ERROR"})(gi||(gi={}));class jr{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=_e.closed,this.joinedOnce=!1,this.pushBuffer=[],this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new Bn(this,xe.join,this.params,this.timeout),this.rejoinTimer=new ws(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=_e.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(i=>i.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=_e.closed,this.socket._remove(this)}),this._onError(i=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,i),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=_e.errored,this.rejoinTimer.scheduleTimeout())}),this._on(xe.reply,{},(i,s)=>{this._trigger(this._replyEventName(s),i)}),this.presence=new qt(this)}subscribe(e,t=this.timeout){var r,i;if(this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:s,presence:o}}=this.params;this._onError(c=>e&&e("CHANNEL_ERROR",c)),this._onClose(()=>e&&e("CLOSED"));const a={},l={broadcast:s,presence:o,postgres_changes:(i=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(c=>c.filter))!==null&&i!==void 0?i:[]};this.socket.accessToken&&(a.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:l},a)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:c})=>{var u;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),c===void 0){e&&e("SUBSCRIBED");return}else{const h=this.bindings.postgres_changes,d=(u=h==null?void 0:h.length)!==null&&u!==void 0?u:0,p=[];for(let f=0;f<d;f++){const g=h[f],{filter:{event:m,schema:b,table:E,filter:T}}=g,S=c&&c[f];if(S&&S.event===m&&S.schema===b&&S.table===E&&S.filter===T)p.push(Object.assign(Object.assign({},g),{id:S.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",new Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=p,e&&e("SUBSCRIBED");return}}).receive("error",c=>{e&&e("CHANNEL_ERROR",new Error(JSON.stringify(Object.values(c).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}track(e,t={}){return di(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)})}untrack(e={}){return di(this,void 0,void 0,function*(){return yield this.send({type:"presence",event:"untrack"},e)})}on(e,t,r){return this._on(e,t,r)}send(e,t={}){return new Promise(r=>{var i,s,o;const a=this._push(e.type,e,t.timeout||this.timeout);a.rateLimited&&r("rate limited"),e.type==="broadcast"&&!(!((o=(s=(i=this.params)===null||i===void 0?void 0:i.config)===null||s===void 0?void 0:s.broadcast)===null||o===void 0)&&o.ack)&&r("ok"),a.receive("ok",()=>r("ok")),a.receive("timeout",()=>r("timed out"))})}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=_e.leaving;const t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(xe.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{const i=new Bn(this,xe.leave,{},e);i.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),i.send(),this._canPush()||i.trigger("ok",{})})}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let i=new Bn(this,e,t,r);return this._canPush()?i.send():(i.startTimeout(),this.pushBuffer.push(i)),i}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var i,s;const o=e.toLocaleLowerCase(),{close:a,error:l,leave:c,join:u}=xe;if(r&&[a,l,c,u].indexOf(o)>=0&&r!==this._joinRef())return;let h=this._onMessage(o,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(o)?(i=this.bindings.postgres_changes)===null||i===void 0||i.filter(d=>{var p,f,g;return((p=d.filter)===null||p===void 0?void 0:p.event)==="*"||((g=(f=d.filter)===null||f===void 0?void 0:f.event)===null||g===void 0?void 0:g.toLocaleLowerCase())===o}).map(d=>d.callback(h,r)):(s=this.bindings[o])===null||s===void 0||s.filter(d=>{var p,f,g,m,b,E;if(["broadcast","presence","postgres_changes"].includes(o))if("id"in d){const T=d.id,S=(p=d.filter)===null||p===void 0?void 0:p.event;return T&&((f=t.ids)===null||f===void 0?void 0:f.includes(T))&&(S==="*"||(S==null?void 0:S.toLocaleLowerCase())===((g=t.data)===null||g===void 0?void 0:g.type.toLocaleLowerCase()))}else{const T=(b=(m=d==null?void 0:d.filter)===null||m===void 0?void 0:m.event)===null||b===void 0?void 0:b.toLocaleLowerCase();return T==="*"||T===((E=t==null?void 0:t.event)===null||E===void 0?void 0:E.toLocaleLowerCase())}else return d.type.toLocaleLowerCase()===o}).map(d=>{if(typeof h=="object"&&"ids"in h){const p=h.data,{schema:f,table:g,commit_timestamp:m,type:b,errors:E}=p;h=Object.assign(Object.assign({},{schema:f,table:g,commit_timestamp:m,eventType:b,new:{},old:{},errors:E}),this._getPayloadRecords(p))}d.callback(h,r)})}_isClosed(){return this.state===_e.closed}_isJoined(){return this.state===_e.joined}_isJoining(){return this.state===_e.joining}_isLeaving(){return this.state===_e.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){const i=e.toLocaleLowerCase(),s={type:i,filter:t,callback:r};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this}_off(e,t){const r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(i=>{var s;return!(((s=i.type)===null||s===void 0?void 0:s.toLocaleLowerCase())===r&&jr.isEqual(i.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(const r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(xe.close,{},e)}_onError(e){this._on(xe.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=_e.joining,this.joinPush.resend(e))}_getPayloadRecords(e){const t={new:{},old:{}};return(e.type==="INSERT"||e.type==="UPDATE")&&(t.new=hi(e.columns,e.record)),(e.type==="UPDATE"||e.type==="DELETE")&&(t.old=hi(e.columns,e.old_record)),t}}var Hn=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const Da=()=>{};class Na{constructor(e,t){var r,i;this.accessToken=null,this.channels=[],this.endPoint="",this.headers=Pa,this.params={},this.timeout=bs,this.transport=Ea.w3cwebsocket,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Da,this.conn=null,this.sendBuffer=[],this.serializer=new $a,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.eventsPerSecondLimitMs=100,this.inThrottle=!1,this.endPoint=`${e}/${sr.websocket}`,t!=null&&t.params&&(this.params=t.params),t!=null&&t.headers&&(this.headers=Object.assign(Object.assign({},this.headers),t.headers)),t!=null&&t.timeout&&(this.timeout=t.timeout),t!=null&&t.logger&&(this.logger=t.logger),t!=null&&t.transport&&(this.transport=t.transport),t!=null&&t.heartbeatIntervalMs&&(this.heartbeatIntervalMs=t.heartbeatIntervalMs);const s=(r=t==null?void 0:t.params)===null||r===void 0?void 0:r.eventsPerSecond;s&&(this.eventsPerSecondLimitMs=Math.floor(1e3/s));const o=(i=t==null?void 0:t.params)===null||i===void 0?void 0:i.apikey;o&&(this.accessToken=o),this.reconnectAfterMs=t!=null&&t.reconnectAfterMs?t.reconnectAfterMs:a=>[1e3,2e3,5e3,1e4][a-1]||1e4,this.encode=t!=null&&t.encode?t.encode:(a,l)=>l(JSON.stringify(a)),this.decode=t!=null&&t.decode?t.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new ws(()=>Hn(this,void 0,void 0,function*(){this.disconnect(),this.connect()}),this.reconnectAfterMs)}connect(){this.conn||(this.conn=new this.transport(this._endPointURL(),[],null,this.headers),this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e)))}disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,t??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}removeChannel(e){return Hn(this,void 0,void 0,function*(){const t=yield e.unsubscribe();return this.channels.length===0&&this.disconnect(),t})}removeAllChannels(){return Hn(this,void 0,void 0,function*(){const e=yield Promise.all(this.channels.map(t=>t.unsubscribe()));return this.disconnect(),e})}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case Nt.connecting:return Ze.Connecting;case Nt.open:return Ze.Open;case Nt.closing:return Ze.Closing;default:return Ze.Closed}}isConnected(){return this.connectionState()===Ze.Open}channel(e,t={config:{}}){this.isConnected()||this.connect();const r=new jr(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){const{topic:t,event:r,payload:i,ref:s}=e;let o=()=>{this.encode(e,a=>{var l;(l=this.conn)===null||l===void 0||l.send(a)})};if(this.log("push",`${t} ${r} (${s})`,i),this.isConnected())if(["broadcast","presence","postgres_changes"].includes(r)){if(this._throttle(o)())return"rate limited"}else o();else this.sendBuffer.push(o)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(xe.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(r=>r.topic===e&&(r._isJoined()||r._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ra}))}_onConnMessage(e){this.decode(e.data,t=>{let{topic:r,event:i,payload:s,ref:o}=t;(o&&o===this.pendingHeartbeatRef||i===(s==null?void 0:s.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${s.status||""} ${r} ${i} ${o&&"("+o+")"||""}`,s),this.channels.filter(a=>a._isMember(r)).forEach(a=>a._trigger(i,s,o)),this.stateChangeCallbacks.message.forEach(a=>a(t))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(xe.error))}_appendParams(e,t){if(Object.keys(t).length===0)return e;const r=e.match(/\?/)?"&":"?",i=new URLSearchParams(t);return`${e}${r}${i}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),(e=this.conn)===null||e===void 0||e.close(Oa,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}_throttle(e,t=this.eventsPerSecondLimitMs){return()=>this.inThrottle?!0:(e(),t>0&&(this.inThrottle=!0,setTimeout(()=>{this.inThrottle=!1},t)),!1)}}class Fr extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function se(n){return typeof n=="object"&&n!==null&&"__isStorageError"in n}class qa extends Fr{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class vi extends Fr{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}var Ss=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const Ts=n=>{let e;return n?e=n:typeof fetch>"u"?e=(...t)=>Ss(void 0,void 0,void 0,function*(){return yield(yield Cn(()=>Promise.resolve().then(()=>jn),void 0)).fetch(...t)}):e=fetch,(...t)=>e(...t)},Ma=()=>Ss(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Cn(()=>Promise.resolve().then(()=>jn),void 0)).Response:Response});var Pt=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const zn=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),Ua=(n,e)=>Pt(void 0,void 0,void 0,function*(){const t=yield Ma();n instanceof t?n.json().then(r=>{e(new qa(zn(r),n.status||500))}).catch(r=>{e(new vi(zn(r),r))}):e(new vi(zn(n),n))}),Ba=(n,e,t,r)=>{const i={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};function An(n,e,t,r,i,s){return Pt(this,void 0,void 0,function*(){return new Promise((o,a)=>{n(t,Ba(e,r,i,s)).then(l=>{if(!l.ok)throw l;return r!=null&&r.noResolveJson?l:l.json()}).then(l=>o(l)).catch(l=>Ua(l,a))})})}function ar(n,e,t,r){return Pt(this,void 0,void 0,function*(){return An(n,"GET",e,t,r)})}function Be(n,e,t,r,i){return Pt(this,void 0,void 0,function*(){return An(n,"POST",e,r,i,t)})}function Ha(n,e,t,r,i){return Pt(this,void 0,void 0,function*(){return An(n,"PUT",e,r,i,t)})}function Es(n,e,t,r,i){return Pt(this,void 0,void 0,function*(){return An(n,"DELETE",e,r,i,t)})}var ke=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const za={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},_i={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class Va{constructor(e,t={},r,i){this.url=e,this.headers=t,this.bucketId=r,this.fetch=Ts(i)}uploadOrUpdate(e,t,r,i){return ke(this,void 0,void 0,function*(){try{let s;const o=Object.assign(Object.assign({},_i),i),a=Object.assign(Object.assign({},this.headers),e==="POST"&&{"x-upsert":String(o.upsert)});typeof Blob<"u"&&r instanceof Blob?(s=new FormData,s.append("cacheControl",o.cacheControl),s.append("",r)):typeof FormData<"u"&&r instanceof FormData?(s=r,s.append("cacheControl",o.cacheControl)):(s=r,a["cache-control"]=`max-age=${o.cacheControl}`,a["content-type"]=o.contentType);const l=this._removeEmptyFolders(t),c=this._getFinalPath(l),u=yield this.fetch(`${this.url}/object/${c}`,Object.assign({method:e,body:s,headers:a},o!=null&&o.duplex?{duplex:o.duplex}:{}));return u.ok?{data:{path:l},error:null}:{data:null,error:yield u.json()}}catch(s){if(se(s))return{data:null,error:s};throw s}})}upload(e,t,r){return ke(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,i){return ke(this,void 0,void 0,function*(){const s=this._removeEmptyFolders(e),o=this._getFinalPath(s),a=new URL(this.url+`/object/upload/sign/${o}`);a.searchParams.set("token",t);try{let l;const c=Object.assign({upsert:_i.upsert},i),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(c.upsert)});typeof Blob<"u"&&r instanceof Blob?(l=new FormData,l.append("cacheControl",c.cacheControl),l.append("",r)):typeof FormData<"u"&&r instanceof FormData?(l=r,l.append("cacheControl",c.cacheControl)):(l=r,u["cache-control"]=`max-age=${c.cacheControl}`,u["content-type"]=c.contentType);const h=yield this.fetch(a.toString(),{method:"PUT",body:l,headers:u});return h.ok?{data:{path:s},error:null}:{data:null,error:yield h.json()}}catch(l){if(se(l))return{data:null,error:l};throw l}})}createSignedUploadUrl(e){return ke(this,void 0,void 0,function*(){try{let t=this._getFinalPath(e);const r=yield Be(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),i=new URL(this.url+r.url),s=i.searchParams.get("token");if(!s)throw new Fr("No token returned by API");return{data:{signedUrl:i.toString(),path:e,token:s},error:null}}catch(t){if(se(t))return{data:null,error:t};throw t}})}update(e,t,r){return ke(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t){return ke(this,void 0,void 0,function*(){try{return{data:yield Be(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(r){if(se(r))return{data:null,error:r};throw r}})}copy(e,t){return ke(this,void 0,void 0,function*(){try{return{data:{path:(yield Be(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(r){if(se(r))return{data:null,error:r};throw r}})}createSignedUrl(e,t,r){return ke(this,void 0,void 0,function*(){try{let i=this._getFinalPath(e),s=yield Be(this.fetch,`${this.url}/object/sign/${i}`,Object.assign({expiresIn:t},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const o=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return s={signedUrl:encodeURI(`${this.url}${s.signedURL}${o}`)},{data:s,error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}})}createSignedUrls(e,t,r){return ke(this,void 0,void 0,function*(){try{const i=yield Be(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),s=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:i.map(o=>Object.assign(Object.assign({},o),{signedUrl:o.signedURL?encodeURI(`${this.url}${o.signedURL}${s}`):null})),error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}})}download(e,t){return ke(this,void 0,void 0,function*(){const r=typeof(t==null?void 0:t.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((t==null?void 0:t.transform)||{}),s=i?`?${i}`:"";try{const o=this._getFinalPath(e);return{data:yield(yield ar(this.fetch,`${this.url}/${r}/${o}${s}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(se(o))return{data:null,error:o};throw o}})}getPublicUrl(e,t){const r=this._getFinalPath(e),i=[],s=t!=null&&t.download?`download=${t.download===!0?"":t.download}`:"";s!==""&&i.push(s);const o=typeof(t==null?void 0:t.transform)<"u"?"render/image":"object",a=this.transformOptsToQueryString((t==null?void 0:t.transform)||{});a!==""&&i.push(a);let l=i.join("&");return l!==""&&(l=`?${l}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${r}${l}`)}}}remove(e){return ke(this,void 0,void 0,function*(){try{return{data:yield Es(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(t){if(se(t))return{data:null,error:t};throw t}})}list(e,t,r){return ke(this,void 0,void 0,function*(){try{const i=Object.assign(Object.assign(Object.assign({},za),t),{prefix:e||""});return{data:yield Be(this.fetch,`${this.url}/object/list/${this.bucketId}`,i,{headers:this.headers},r),error:null}}catch(i){if(se(i))return{data:null,error:i};throw i}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){const t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}const Ja="2.5.3",Wa={"X-Client-Info":`storage-js/${Ja}`};var ut=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};class Ga{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},Wa),t),this.fetch=Ts(r)}listBuckets(){return ut(this,void 0,void 0,function*(){try{return{data:yield ar(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(se(e))return{data:null,error:e};throw e}})}getBucket(e){return ut(this,void 0,void 0,function*(){try{return{data:yield ar(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(t){if(se(t))return{data:null,error:t};throw t}})}createBucket(e,t={public:!1}){return ut(this,void 0,void 0,function*(){try{return{data:yield Be(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(se(r))return{data:null,error:r};throw r}})}updateBucket(e,t){return ut(this,void 0,void 0,function*(){try{return{data:yield Ha(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(se(r))return{data:null,error:r};throw r}})}emptyBucket(e){return ut(this,void 0,void 0,function*(){try{return{data:yield Be(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(t){if(se(t))return{data:null,error:t};throw t}})}deleteBucket(e){return ut(this,void 0,void 0,function*(){try{return{data:yield Es(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(t){if(se(t))return{data:null,error:t};throw t}})}}class Ka extends Ga{constructor(e,t={},r){super(e,t,r)}from(e){return new Va(this.url,this.headers,e,this.fetch)}}const Qa="2.33.1",Ya={"X-Client-Info":`supabase-js/${Qa}`};var lr={exports:{}};(function(n,e){var t=typeof self<"u"?self:rr,r=function(){function s(){this.fetch=!1,this.DOMException=t.DOMException}return s.prototype=t,new s}();(function(s){(function(o){var a={searchParams:"URLSearchParams"in s,iterable:"Symbol"in s&&"iterator"in Symbol,blob:"FileReader"in s&&"Blob"in s&&function(){try{return new Blob,!0}catch{return!1}}(),formData:"FormData"in s,arrayBuffer:"ArrayBuffer"in s};function l(v){return v&&DataView.prototype.isPrototypeOf(v)}if(a.arrayBuffer)var c=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],u=ArrayBuffer.isView||function(v){return v&&c.indexOf(Object.prototype.toString.call(v))>-1};function h(v){if(typeof v!="string"&&(v=String(v)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(v))throw new TypeError("Invalid character in header field name");return v.toLowerCase()}function d(v){return typeof v!="string"&&(v=String(v)),v}function p(v){var y={next:function(){var $=v.shift();return{done:$===void 0,value:$}}};return a.iterable&&(y[Symbol.iterator]=function(){return y}),y}function f(v){this.map={},v instanceof f?v.forEach(function(y,$){this.append($,y)},this):Array.isArray(v)?v.forEach(function(y){this.append(y[0],y[1])},this):v&&Object.getOwnPropertyNames(v).forEach(function(y){this.append(y,v[y])},this)}f.prototype.append=function(v,y){v=h(v),y=d(y);var $=this.map[v];this.map[v]=$?$+", "+y:y},f.prototype.delete=function(v){delete this.map[h(v)]},f.prototype.get=function(v){return v=h(v),this.has(v)?this.map[v]:null},f.prototype.has=function(v){return this.map.hasOwnProperty(h(v))},f.prototype.set=function(v,y){this.map[h(v)]=d(y)},f.prototype.forEach=function(v,y){for(var $ in this.map)this.map.hasOwnProperty($)&&v.call(y,this.map[$],$,this)},f.prototype.keys=function(){var v=[];return this.forEach(function(y,$){v.push($)}),p(v)},f.prototype.values=function(){var v=[];return this.forEach(function(y){v.push(y)}),p(v)},f.prototype.entries=function(){var v=[];return this.forEach(function(y,$){v.push([$,y])}),p(v)},a.iterable&&(f.prototype[Symbol.iterator]=f.prototype.entries);function g(v){if(v.bodyUsed)return Promise.reject(new TypeError("Already read"));v.bodyUsed=!0}function m(v){return new Promise(function(y,$){v.onload=function(){y(v.result)},v.onerror=function(){$(v.error)}})}function b(v){var y=new FileReader,$=m(y);return y.readAsArrayBuffer(v),$}function E(v){var y=new FileReader,$=m(y);return y.readAsText(v),$}function T(v){for(var y=new Uint8Array(v),$=new Array(y.length),V=0;V<y.length;V++)$[V]=String.fromCharCode(y[V]);return $.join("")}function S(v){if(v.slice)return v.slice(0);var y=new Uint8Array(v.byteLength);return y.set(new Uint8Array(v)),y.buffer}function O(){return this.bodyUsed=!1,this._initBody=function(v){this._bodyInit=v,v?typeof v=="string"?this._bodyText=v:a.blob&&Blob.prototype.isPrototypeOf(v)?this._bodyBlob=v:a.formData&&FormData.prototype.isPrototypeOf(v)?this._bodyFormData=v:a.searchParams&&URLSearchParams.prototype.isPrototypeOf(v)?this._bodyText=v.toString():a.arrayBuffer&&a.blob&&l(v)?(this._bodyArrayBuffer=S(v.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(v)||u(v))?this._bodyArrayBuffer=S(v):this._bodyText=v=Object.prototype.toString.call(v):this._bodyText="",this.headers.get("content-type")||(typeof v=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):a.searchParams&&URLSearchParams.prototype.isPrototypeOf(v)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},a.blob&&(this.blob=function(){var v=g(this);if(v)return v;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?g(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(b)}),this.text=function(){var v=g(this);if(v)return v;if(this._bodyBlob)return E(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(T(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},a.formData&&(this.formData=function(){return this.text().then(Ee)}),this.json=function(){return this.text().then(JSON.parse)},this}var I=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];function q(v){var y=v.toUpperCase();return I.indexOf(y)>-1?y:v}function R(v,y){y=y||{};var $=y.body;if(v instanceof R){if(v.bodyUsed)throw new TypeError("Already read");this.url=v.url,this.credentials=v.credentials,y.headers||(this.headers=new f(v.headers)),this.method=v.method,this.mode=v.mode,this.signal=v.signal,!$&&v._bodyInit!=null&&($=v._bodyInit,v.bodyUsed=!0)}else this.url=String(v);if(this.credentials=y.credentials||this.credentials||"same-origin",(y.headers||!this.headers)&&(this.headers=new f(y.headers)),this.method=q(y.method||this.method||"GET"),this.mode=y.mode||this.mode||null,this.signal=y.signal||this.signal,this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&$)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody($)}R.prototype.clone=function(){return new R(this,{body:this._bodyInit})};function Ee(v){var y=new FormData;return v.trim().split("&").forEach(function($){if($){var V=$.split("="),B=V.shift().replace(/\+/g," "),A=V.join("=").replace(/\+/g," ");y.append(decodeURIComponent(B),decodeURIComponent(A))}}),y}function ie(v){var y=new f,$=v.replace(/\r?\n[\t ]+/g," ");return $.split(/\r?\n/).forEach(function(V){var B=V.split(":"),A=B.shift().trim();if(A){var pe=B.join(":").trim();y.append(A,pe)}}),y}O.call(R.prototype);function X(v,y){y||(y={}),this.type="default",this.status=y.status===void 0?200:y.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in y?y.statusText:"OK",this.headers=new f(y.headers),this.url=y.url||"",this._initBody(v)}O.call(X.prototype),X.prototype.clone=function(){return new X(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new f(this.headers),url:this.url})},X.error=function(){var v=new X(null,{status:0,statusText:""});return v.type="error",v};var ue=[301,302,303,307,308];X.redirect=function(v,y){if(ue.indexOf(y)===-1)throw new RangeError("Invalid status code");return new X(null,{status:y,headers:{location:v}})},o.DOMException=s.DOMException;try{new o.DOMException}catch{o.DOMException=function(v,y){this.message=v,this.name=y;var $=Error(v);this.stack=$.stack},o.DOMException.prototype=Object.create(Error.prototype),o.DOMException.prototype.constructor=o.DOMException}function fe(v,y){return new Promise(function($,V){var B=new R(v,y);if(B.signal&&B.signal.aborted)return V(new o.DOMException("Aborted","AbortError"));var A=new XMLHttpRequest;function pe(){A.abort()}A.onload=function(){var be={status:A.status,statusText:A.statusText,headers:ie(A.getAllResponseHeaders()||"")};be.url="responseURL"in A?A.responseURL:be.headers.get("X-Request-URL");var Y="response"in A?A.response:A.responseText;$(new X(Y,be))},A.onerror=function(){V(new TypeError("Network request failed"))},A.ontimeout=function(){V(new TypeError("Network request failed"))},A.onabort=function(){V(new o.DOMException("Aborted","AbortError"))},A.open(B.method,B.url,!0),B.credentials==="include"?A.withCredentials=!0:B.credentials==="omit"&&(A.withCredentials=!1),"responseType"in A&&a.blob&&(A.responseType="blob"),B.headers.forEach(function(be,Y){A.setRequestHeader(Y,be)}),B.signal&&(B.signal.addEventListener("abort",pe),A.onreadystatechange=function(){A.readyState===4&&B.signal.removeEventListener("abort",pe)}),A.send(typeof B._bodyInit>"u"?null:B._bodyInit)})}return fe.polyfill=!0,s.fetch||(s.fetch=fe,s.Headers=f,s.Request=R,s.Response=X),o.Headers=f,o.Request=R,o.Response=X,o.fetch=fe,Object.defineProperty(o,"__esModule",{value:!0}),o})({})})(r),r.fetch.ponyfill=!0,delete r.fetch.polyfill;var i=r;e=i.fetch,e.default=i.fetch,e.fetch=i.fetch,e.Headers=i.Headers,e.Request=i.Request,e.Response=i.Response,n.exports=e})(lr,lr.exports);var Lr=lr.exports;const xs=ms(Lr),jn=So({__proto__:null,default:xs},[Lr]);var Xa=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const Za=n=>{let e;return n?e=n:typeof fetch>"u"?e=xs:e=fetch,(...t)=>e(...t)},el=()=>typeof Headers>"u"?Lr.Headers:Headers,tl=(n,e,t)=>{const r=Za(t),i=el();return(s,o)=>Xa(void 0,void 0,void 0,function*(){var a;const l=(a=yield e())!==null&&a!==void 0?a:n;let c=new i(o==null?void 0:o.headers);return c.has("apikey")||c.set("apikey",n),c.has("Authorization")||c.set("Authorization",`Bearer ${l}`),r(s,Object.assign(Object.assign({},o),{headers:c}))})};function nl(n){return n.replace(/\/$/,"")}function rl(n,e){const{db:t,auth:r,realtime:i,global:s}=n,{db:o,auth:a,realtime:l,global:c}=e;return{db:Object.assign(Object.assign({},o),t),auth:Object.assign(Object.assign({},a),r),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},c),s)}}function il(n){return Math.round(Date.now()/1e3)+n}function sl(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(n){const e=Math.random()*16|0;return(n=="x"?e:e&3|8).toString(16)})}const Fe=()=>typeof document<"u",Ke={tested:!1,writable:!1},Mt=()=>{if(!Fe())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(Ke.tested)return Ke.writable;const n=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(n,n),globalThis.localStorage.removeItem(n),Ke.tested=!0,Ke.writable=!0}catch{Ke.tested=!0,Ke.writable=!1}return Ke.writable};function Vn(n){const e={},t=new URL(n);if(t.hash&&t.hash[0]==="#")try{new URLSearchParams(t.hash.substring(1)).forEach((r,i)=>{e[i]=r})}catch{}return t.searchParams.forEach((r,i)=>{e[i]=r}),e}const Ps=n=>{let e;return n?e=n:typeof fetch>"u"?e=async(...t)=>await(await Cn(()=>Promise.resolve().then(()=>jn),void 0)).fetch(...t):e=fetch,(...t)=>e(...t)},ol=n=>typeof n=="object"&&n!==null&&"status"in n&&"ok"in n&&"json"in n&&typeof n.json=="function",Ot=async(n,e,t)=>{await n.setItem(e,JSON.stringify(t))},en=async(n,e)=>{const t=await n.getItem(e);if(!t)return null;try{return JSON.parse(t)}catch{return t}},Jn=async(n,e)=>{await n.removeItem(e)};function al(n){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",r,i,s,o,a,l,c,u=0;for(n=n.replace("-","+").replace("_","/");u<n.length;)o=e.indexOf(n.charAt(u++)),a=e.indexOf(n.charAt(u++)),l=e.indexOf(n.charAt(u++)),c=e.indexOf(n.charAt(u++)),r=o<<2|a>>4,i=(a&15)<<4|l>>2,s=(l&3)<<6|c,t=t+String.fromCharCode(r),l!=64&&i!=0&&(t=t+String.fromCharCode(i)),c!=64&&s!=0&&(t=t+String.fromCharCode(s));return t}class Fn{constructor(){this.promise=new Fn.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}Fn.promiseConstructor=Promise;function mi(n){const e=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i,t=n.split(".");if(t.length!==3)throw new Error("JWT is not valid: not a JWT structure");if(!e.test(t[1]))throw new Error("JWT is not valid: payload is not in base64url format");const r=t[1];return JSON.parse(al(r))}async function ll(n){return await new Promise(e=>{setTimeout(()=>e(null),n)})}function cl(n,e){return new Promise((t,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{const s=await n(i);if(!e(i,null,s)){t(s);return}}catch(s){if(!e(i,s)){r(s);return}}})()})}function ul(n){return("0"+n.toString(16)).substr(-2)}function tn(){const n=new Uint32Array(56);if(typeof crypto>"u"){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length;let r="";for(let i=0;i<56;i++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(n),Array.from(n,ul).join("")}async function hl(n){const e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);return Array.from(r).map(i=>String.fromCharCode(i)).join("")}function dl(n){return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function nn(n){if(typeof crypto>"u")return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),n;const e=await hl(n);return dl(e)}class Dr extends Error{constructor(e,t){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t}}function F(n){return typeof n=="object"&&n!==null&&"__isAuthError"in n}class fl extends Dr{constructor(e,t){super(e,t),this.name="AuthApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}function pl(n){return F(n)&&n.name==="AuthApiError"}class Rs extends Dr{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class Rt extends Dr{constructor(e,t,r){super(e),this.name=t,this.status=r}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ht extends Rt{constructor(){super("Auth session missing!","AuthSessionMissingError",400)}}class Wn extends Rt{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500)}}class rn extends Rt{constructor(e){super(e,"AuthInvalidCredentialsError",400)}}class sn extends Rt{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class yi extends Rt{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class cr extends Rt{constructor(e,t){super(e,"AuthRetryableFetchError",t)}}function bi(n){return F(n)&&n.name==="AuthRetryableFetchError"}var gl=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t};const At=n=>n.msg||n.message||n.error_description||n.error||JSON.stringify(n),vl=[502,503,504];async function wi(n){if(!ol(n))throw new cr(At(n),0);if(vl.includes(n.status))throw new cr(At(n),n.status);let e;try{e=await n.json()}catch(t){throw new Rs(At(t),t)}throw new fl(At(e),n.status||500)}const _l=(n,e,t,r)=>{const i={method:n,headers:(e==null?void 0:e.headers)||{}};return n==="GET"?i:(i.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},e==null?void 0:e.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),t))};async function L(n,e,t,r){var i;const s=Object.assign({},r==null?void 0:r.headers);r!=null&&r.jwt&&(s.Authorization=`Bearer ${r.jwt}`);const o=(i=r==null?void 0:r.query)!==null&&i!==void 0?i:{};r!=null&&r.redirectTo&&(o.redirect_to=r.redirectTo);const a=Object.keys(o).length?"?"+new URLSearchParams(o).toString():"",l=await ml(n,e,t+a,{headers:s,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(l):{data:Object.assign({},l),error:null}}async function ml(n,e,t,r,i,s){const o=_l(e,r,i,s);let a;try{a=await n(t,o)}catch(l){throw console.error(l),new cr(At(l),0)}if(a.ok||await wi(a),r!=null&&r.noResolveJson)return a;try{return await a.json()}catch(l){await wi(l)}}function Me(n){var e;let t=null;kl(n)&&(t=Object.assign({},n),t.expires_at=il(n.expires_in));const r=(e=n.user)!==null&&e!==void 0?e:n;return{data:{session:t,user:r},error:null}}function Ve(n){var e;return{data:{user:(e=n.user)!==null&&e!==void 0?e:n},error:null}}function yl(n){return{data:n,error:null}}function bl(n){const{action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:s}=n,o=gl(n,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),a={action_link:e,email_otp:t,hashed_token:r,redirect_to:i,verification_type:s},l=Object.assign({},o);return{data:{properties:a,user:l},error:null}}function wl(n){return n}function kl(n){return n.access_token&&n.refresh_token&&n.expires_in}var Sl=globalThis&&globalThis.__rest||function(n,e){var t={};for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.indexOf(r)<0&&(t[r]=n[r]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(n);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(n,r[i])&&(t[r[i]]=n[r[i]]);return t};class Tl{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=Ps(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await L(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(r){if(F(r))return{data:null,error:r};throw r}}async inviteUserByEmail(e,t={}){try{return await L(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:Ve})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async generateLink(e){try{const{options:t}=e,r=Sl(e,["options"]),i=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(i.new_email=r==null?void 0:r.newEmail,delete i.newEmail),await L(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:i,headers:this.headers,xform:bl,redirectTo:t==null?void 0:t.redirectTo})}catch(t){if(F(t))return{data:{properties:null,user:null},error:t};throw t}}async createUser(e){try{return await L(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:Ve})}catch(t){if(F(t))return{data:{user:null},error:t};throw t}}async listUsers(e){var t,r,i,s,o,a,l;try{const c={nextPage:null,lastPage:0,total:0},u=await L(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(r=(t=e==null?void 0:e.page)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:"",per_page:(s=(i=e==null?void 0:e.perPage)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""},xform:wl});if(u.error)throw u.error;const h=await u.json(),d=(o=u.headers.get("x-total-count"))!==null&&o!==void 0?o:0,p=(l=(a=u.headers.get("link"))===null||a===void 0?void 0:a.split(","))!==null&&l!==void 0?l:[];return p.length>0&&(p.forEach(f=>{const g=parseInt(f.split(";")[0].split("=")[1].substring(0,1)),m=JSON.parse(f.split(";")[1].split("=")[1]);c[`${m}Page`]=g}),c.total=parseInt(d)),{data:Object.assign(Object.assign({},h),c),error:null}}catch(c){if(F(c))return{data:{users:[]},error:c};throw c}}async getUserById(e){try{return await L(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:Ve})}catch(t){if(F(t))return{data:{user:null},error:t};throw t}}async updateUserById(e,t){try{return await L(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:Ve})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async deleteUser(e,t=!1){try{return await L(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:Ve})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}async _listFactors(e){try{const{data:t,error:r}=await L(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:i=>({data:{factors:i},error:null})});return{data:t,error:r}}catch(t){if(F(t))return{data:null,error:t};throw t}}async _deleteFactor(e){try{return{data:await L(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(t){if(F(t))return{data:null,error:t};throw t}}}const Os="2.48.1",El="http://localhost:9999",xl="supabase.auth.token",Pl={"X-Client-Info":`gotrue-js/${Os}`},ki=10,Si={getItem:n=>Mt()?globalThis.localStorage.getItem(n):null,setItem:(n,e)=>{Mt()&&globalThis.localStorage.setItem(n,e)},removeItem:n=>{Mt()&&globalThis.localStorage.removeItem(n)}};function Rl(){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)}}Rl();const Ol={url:El,storageKey:xl,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Pl,flowType:"implicit",debug:!1},on=30*1e3,Ti=3;async function $l(n,e,t){return await t()}class Jt{constructor(e){var t;this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.instanceID=Jt.nextInstanceID,Jt.nextInstanceID+=1,this.instanceID>0&&Fe()&&console.warn("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.");const r=Object.assign(Object.assign({},Ol),e);if(this.logDebugMessages=r.debug,this.inMemorySession=null,this.storageKey=r.storageKey,this.autoRefreshToken=r.autoRefreshToken,this.persistSession=r.persistSession,this.storage=r.storage||Si,this.admin=new Tl({url:r.url,headers:r.headers,fetch:r.fetch}),this.url=r.url,this.headers=r.headers,this.fetch=Ps(r.fetch),this.lock=r.lock||$l,this.detectSessionInUrl=r.detectSessionInUrl,this.flowType=r.flowType,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)},this.persistSession&&this.storage===Si&&!Mt()&&console.warn(`No storage option exists to persist the session, which may result in unexpected behavior when using auth.
If you want to set persistSession to true, please provide a storage option or you may set persistSession to false to disable this warning.`),Fe()&&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)}(t=this.broadcastChannel)===null||t===void 0||t.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&console.log(`GoTrueClient@${this.instanceID} (${Os}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){try{const e=Fe()?await this._isPKCEFlow():!1;if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){const{data:t,error:r}=await this._getSessionFromURL(e);if(r)return this._debug("#_initialize()","error detecting session from URL",r),await this._removeSession(),{error:r};const{session:i,redirectType:s}=t;return this._debug("#_initialize()","detected session in URL",i,"redirect type",s),await this._saveSession(i),setTimeout(async()=>{s==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",i):await this._notifyAllSubscribers("SIGNED_IN",i)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return F(e)?{error:e}:{error:new Rs("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signUp(e){var t,r,i;try{await this._removeSession();let s;if("email"in e){const{email:u,password:h,options:d}=e;let p=null,f=null;if(this.flowType==="pkce"){const g=tn();await Ot(this.storage,`${this.storageKey}-code-verifier`,g),p=await nn(g),f=g===p?"plain":"s256"}s=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:d==null?void 0:d.emailRedirectTo,body:{email:u,password:h,data:(t=d==null?void 0:d.data)!==null&&t!==void 0?t:{},gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken},code_challenge:p,code_challenge_method:f},xform:Me})}else if("phone"in e){const{phone:u,password:h,options:d}=e;s=await L(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=d==null?void 0:d.data)!==null&&r!==void 0?r:{},channel:(i=d==null?void 0:d.channel)!==null&&i!==void 0?i:"sms",gotrue_meta_security:{captcha_token:d==null?void 0:d.captchaToken}},xform:Me})}else throw new rn("You must provide either an email or phone number and a password");const{data:o,error:a}=s;if(a||!o)return{data:{user:null,session:null},error:a};const l=o.session,c=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(s){if(F(s))return{data:{user:null,session:null},error:s};throw s}}async signInWithPassword(e){try{await this._removeSession();let t;if("email"in e){const{email:s,password:o,options:a}=e;t=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:s,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Me})}else if("phone"in e){const{phone:s,password:o,options:a}=e;t=await L(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:s,password:o,gotrue_meta_security:{captcha_token:a==null?void 0:a.captchaToken}},xform:Me})}else throw new rn("You must provide either an email or phone number and a password");const{data:r,error:i}=t;return i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Wn}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:{user:r.user,session:r.session},error:i})}catch(t){if(F(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOAuth(e){var t,r,i,s;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:(t=e.options)===null||t===void 0?void 0:t.redirectTo,scopes:(r=e.options)===null||r===void 0?void 0:r.scopes,queryParams:(i=e.options)===null||i===void 0?void 0:i.queryParams,skipBrowserRedirect:(s=e.options)===null||s===void 0?void 0:s.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){const t=await en(this.storage,`${this.storageKey}-code-verifier`),{data:r,error:i}=await L(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:t},xform:Me});return await Jn(this.storage,`${this.storageKey}-code-verifier`),i?{data:{user:null,session:null},error:i}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Wn}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:r,error:i})}async signInWithIdToken(e){await this._removeSession();try{const{options:t,provider:r,token:i,access_token:s,nonce:o}=e,a=await L(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:i,access_token:s,nonce:o,gotrue_meta_security:{captcha_token:t==null?void 0:t.captchaToken}},xform:Me}),{data:l,error:c}=a;return c?{data:{user:null,session:null},error:c}:!l||!l.session||!l.user?{data:{user:null,session:null},error:new Wn}:(l.session&&(await this._saveSession(l.session),await this._notifyAllSubscribers("SIGNED_IN",l.session)),{data:l,error:c})}catch(t){if(F(t))return{data:{user:null,session:null},error:t};throw t}}async signInWithOtp(e){var t,r,i,s,o;try{if(await this._removeSession(),"email"in e){const{email:a,options:l}=e;let c=null,u=null;if(this.flowType==="pkce"){const d=tn();await Ot(this.storage,`${this.storageKey}-code-verifier`,d),c=await nn(d),u=d===c?"plain":"s256"}const{error:h}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:a,data:(t=l==null?void 0:l.data)!==null&&t!==void 0?t:{},create_user:(r=l==null?void 0:l.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},code_challenge:c,code_challenge_method:u},redirectTo:l==null?void 0:l.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in e){const{phone:a,options:l}=e,{data:c,error:u}=await L(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:a,data:(i=l==null?void 0:l.data)!==null&&i!==void 0?i:{},create_user:(s=l==null?void 0:l.shouldCreateUser)!==null&&s!==void 0?s:!0,gotrue_meta_security:{captcha_token:l==null?void 0:l.captchaToken},channel:(o=l==null?void 0:l.channel)!==null&&o!==void 0?o:"sms"}});return{data:{user:null,session:null,messageId:c==null?void 0:c.message_id},error:u}}throw new rn("You must provide either an email or phone number.")}catch(a){if(F(a))return{data:{user:null,session:null},error:a};throw a}}async verifyOtp(e){var t,r;try{e.type!=="email_change"&&e.type!=="phone_change"&&await this._removeSession();let i,s;"options"in e&&(i=(t=e.options)===null||t===void 0?void 0:t.redirectTo,s=(r=e.options)===null||r===void 0?void 0:r.captchaToken);const{data:o,error:a}=await L(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:s}}),redirectTo:i,xform:Me});if(a)throw a;if(!o)throw new Error("An error occurred on token verification.");const l=o.session,c=o.user;return l!=null&&l.access_token&&(await this._saveSession(l),await this._notifyAllSubscribers("SIGNED_IN",l)),{data:{user:c,session:l},error:null}}catch(i){if(F(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithSSO(e){var t,r,i;try{return await this._removeSession(),await L(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:(r=(t=e.options)===null||t===void 0?void 0:t.redirectTo)!==null&&r!==void 0?r:void 0}),!((i=e==null?void 0:e.options)===null||i===void 0)&&i.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0}),headers:this.headers,xform:yl})}catch(s){if(F(s))return{data:null,error:s};throw s}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{const{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new ht;const{error:i}=await L(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:i}})}catch(e){if(F(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{e.type!="email_change"&&e.type!="phone_change"&&await this._removeSession();const t=`${this.url}/resend`;if("email"in e){const{email:r,type:i,options:s}=e,{error:o}=await L(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}},redirectTo:s==null?void 0:s.emailRedirectTo});return{data:{user:null,session:null},error:o}}else if("phone"in e){const{phone:r,type:i,options:s}=e,{data:o,error:a}=await L(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:i,gotrue_meta_security:{captcha_token:s==null?void 0:s.captchaToken}}});return{data:{user:null,session:null,messageId:o==null?void 0:o.message_id},error:a}}throw new rn("You must provide either an email or phone number and a type")}catch(t){if(F(t))return{data:{user:null,session:null},error:t};throw t}}async getSession(){return await this.initializePromise,this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_acquireLock","begin",e);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),i=(async()=>(await r,await t()))();return this.pendingInLock.push((async()=>{try{await i}catch{}})()),i}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=t();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const i=[...this.pendingInLock];await Promise.all(i),this.pendingInLock.splice(0,i.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(e){this._debug("#_useSession","begin");try{const t=await this.__loadSession();return await e(t)}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 e=null;if(this.persistSession){const s=await en(this.storage,this.storageKey);this._debug("#getSession()","session from storage",s),s!==null&&(this._isValidSession(s)?e=s:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession()))}else e=this.inMemorySession,this._debug("#getSession()","session from memory",e);if(!e)return{data:{session:null},error:null};const t=e.expires_at?e.expires_at<=Date.now()/1e3:!1;if(this._debug("#__loadSession()",`session has${t?"":" not"} expired`,"expires_at",e.expires_at),!t)return{data:{session:e},error:null};const{session:r,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{session:null},error:i}:{data:{session:r},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{return e?await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:Ve}):await this._useSession(async t=>{var r,i;const{data:s,error:o}=t;if(o)throw o;return await L(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(i=(r=s.session)===null||r===void 0?void 0:r.access_token)!==null&&i!==void 0?i:void 0,xform:Ve})})}catch(t){if(F(t))return{data:{user:null},error:t};throw t}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{const{data:i,error:s}=r;if(s)throw s;if(!i.session)throw new ht;const o=i.session,{data:a,error:l}=await L(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:t==null?void 0:t.emailRedirectTo,body:e,jwt:o.access_token,xform:Ve});if(l)throw l;return o.user=a.user,await this._saveSession(o),await this._notifyAllSubscribers("USER_UPDATED",o),{data:{user:o.user},error:null}})}catch(r){if(F(r))return{data:{user:null},error:r};throw r}}_decodeJWT(e){return mi(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new ht;const t=Date.now()/1e3;let r=t,i=!0,s=null;const o=mi(e.access_token);if(o.exp&&(r=o.exp,i=r<=t),i){const{session:a,error:l}=await this._callRefreshToken(e.refresh_token);if(l)return{data:{user:null,session:null},error:l};if(!a)return{data:{user:null,session:null},error:null};s=a}else{const{data:a,error:l}=await this._getUser(e.access_token);if(l)throw l;s={access_token:e.access_token,refresh_token:e.refresh_token,user:a.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(s),await this._notifyAllSubscribers("SIGNED_IN",s)}return{data:{user:s.user,session:s},error:null}}catch(t){if(F(t))return{data:{session:null,user:null},error:t};throw t}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){const{data:o,error:a}=t;if(a)throw a;e=(r=o.session)!==null&&r!==void 0?r:void 0}if(!(e!=null&&e.refresh_token))throw new ht;const{session:i,error:s}=await this._callRefreshToken(e.refresh_token);return s?{data:{user:null,session:null},error:s}:i?{data:{user:i.user,session:i},error:null}:{data:{user:null,session:null},error:null}})}catch(t){if(F(t))return{data:{user:null,session:null},error:t};throw t}}async _getSessionFromURL(e){try{if(!Fe())throw new sn("No browser detected.");if(this.flowType==="implicit"&&!this._isImplicitGrantFlow())throw new sn("Not a valid implicit grant flow url.");if(this.flowType=="pkce"&&!e)throw new yi("Not a valid PKCE flow url.");const t=Vn(window.location.href);if(e){if(!t.code)throw new yi("No code detected.");const{data:g,error:m}=await this._exchangeCodeForSession(t.code);if(m)throw m;const b=new URL(window.location.href);return b.searchParams.delete("code"),window.history.replaceState(window.history.state,"",b.toString()),{data:{session:g.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new sn(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});const{provider_token:r,provider_refresh_token:i,access_token:s,refresh_token:o,expires_in:a,token_type:l}=t;if(!s||!a||!o||!l)throw new sn("No session defined in URL");const c=Math.round(Date.now()/1e3),u=parseInt(a),h=c+u,{data:d,error:p}=await this._getUser(s);if(p)throw p;const f={provider_token:r,provider_refresh_token:i,access_token:s,expires_in:u,expires_at:h,refresh_token:o,token_type:l,user:d.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:f,redirectType:t.type},error:null}}catch(t){if(F(t))return{data:{session:null,redirectType:null},error:t};throw t}}_isImplicitGrantFlow(){const e=Vn(window.location.href);return!!(Fe()&&(e.access_token||e.error_description))}async _isPKCEFlow(){const e=Vn(window.location.href),t=await en(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;const{data:i,error:s}=t;if(s)return{error:s};const o=(r=i.session)===null||r===void 0?void 0:r.access_token;if(o){const{error:a}=await this.admin.signOut(o,e);if(a&&!(pl(a)&&(a.status===404||a.status===401)))return{error:a}}return e!=="others"&&(await this._removeSession(),await Jn(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){const t=sl(),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})))(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,i;try{const{data:{session:s},error:o}=t;if(o)throw o;await((r=this.stateChangeEmitters.get(e))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",s)),this._debug("INITIAL_SESSION","callback id",e,"session",s)}catch(s){await((i=this.stateChangeEmitters.get(e))===null||i===void 0?void 0:i.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",s),console.error(s)}})}async resetPasswordForEmail(e,t={}){let r=null,i=null;if(this.flowType==="pkce"){const s=tn();await Ot(this.storage,`${this.storageKey}-code-verifier`,s),r=await nn(s),i=s===r?"plain":"s256"}try{return await L(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:i,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(s){if(F(s))return{data:null,error:s};throw s}}async _refreshAccessToken(e){const t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{const r=Date.now();return await cl(async i=>(await ll(i*200),this._debug(t,"refreshing attempt",i),await L(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:Me})),(i,s,o)=>o&&o.error&&bi(o.error)&&Date.now()+(i+1)*200-r<on)}catch(r){if(this._debug(t,"error",r),F(r))return{data:{session:null,user:null},error:r};throw r}finally{this._debug(t,"end")}}_isValidSession(e){return typeof e=="object"&&e!==null&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){const r=await this._getUrlForProvider(e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),Fe()&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;const t="#_recoverAndRefresh()";this._debug(t,"begin");try{const r=await en(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),r!==null&&await this._removeSession();return}const i=Math.round(Date.now()/1e3),s=((e=r.expires_at)!==null&&e!==void 0?e:1/0)<i+ki;if(this._debug(t,`session has${s?"":" not"} expired with margin of ${ki}s`),s){if(this.autoRefreshToken&&r.refresh_token){const{error:o}=await this._callRefreshToken(r.refresh_token);o&&(console.error(o),bi(o)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",o),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(r){this._debug(t,"error",r),console.error(r);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new ht;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const i=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(i,"begin");try{this.refreshingDeferred=new Fn;const{data:s,error:o}=await this._refreshAccessToken(e);if(o)throw o;if(!s.session)throw new ht;await this._saveSession(s.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",s.session);const a={session:s.session,error:null};return this.refreshingDeferred.resolve(a),a}catch(s){if(this._debug(i,"error",s),F(s)){const o={session:null,error:s};return(t=this.refreshingDeferred)===null||t===void 0||t.resolve(o),o}throw(r=this.refreshingDeferred)===null||r===void 0||r.reject(s),s}finally{this.refreshingDeferred=null,this._debug(i,"end")}}async _notifyAllSubscribers(e,t,r=!0){const i=`#_notifyAllSubscribers(${e})`;this._debug(i,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});const s=[],o=Array.from(this.stateChangeEmitters.values()).map(async a=>{try{await a.callback(e,t)}catch(l){s.push(l)}});if(await Promise.all(o),s.length>0){for(let a=0;a<s.length;a+=1)console.error(s[a]);throw s[0]}}finally{this._debug(i,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.persistSession||(this.inMemorySession=e),this.persistSession&&e.expires_at&&await this._persistSession(e)}_persistSession(e){return this._debug("#_persistSession()",e),Ot(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),this.persistSession?await Jn(this.storage,this.storageKey):this.inMemorySession=null}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&Fe()&&window!=null&&window.removeEventListener&&window.removeEventListener("visibilitychange",e)}catch(t){console.error("removing visibilitychange callback failed",t)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const e=setInterval(()=>this._autoRefreshTokenTick(),on);this.autoRefreshTicker=e,e&&typeof e=="object"&&typeof e.unref=="function"?e.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}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{const e=Date.now();try{return await this._useSession(async t=>{const{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const i=Math.floor((r.expires_at*1e3-e)/on);this._debug("#_autoRefreshTokenTick()",`access token expires in ${i} ticks, a tick lasts ${on}ms, refresh threshold is ${Ti} ticks`),i<=Ti&&await this._callRefreshToken(r.refresh_token)})}catch(t){console.error("Auto refresh tick failed with error. This is likely a transient error.",t)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!Fe()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){const t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),e||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(t,"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(e,t){const r=[`provider=${encodeURIComponent(e)}`];if(t!=null&&t.redirectTo&&r.push(`redirect_to=${encodeURIComponent(t.redirectTo)}`),t!=null&&t.scopes&&r.push(`scopes=${encodeURIComponent(t.scopes)}`),this.flowType==="pkce"){const i=tn();await Ot(this.storage,`${this.storageKey}-code-verifier`,i);const s=await nn(i),o=i===s?"plain":"s256";this._debug("PKCE","code verifier",`${i.substring(0,5)}...`,"code challenge",s,"method",o);const a=new URLSearchParams({code_challenge:`${encodeURIComponent(s)}`,code_challenge_method:`${encodeURIComponent(o)}`});r.push(a.toString())}if(t!=null&&t.queryParams){const i=new URLSearchParams(t.queryParams);r.push(i.toString())}return`${this.url}/authorize?${r.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;const{data:i,error:s}=t;return s?{data:null,error:s}:await L(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _enroll(e){try{return await this._useSession(async t=>{var r,i;const{data:s,error:o}=t;if(o)return{data:null,error:o};const{data:a,error:l}=await L(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:(r=s==null?void 0:s.session)===null||r===void 0?void 0:r.access_token});return l?{data:null,error:l}:(!((i=a==null?void 0:a.totp)===null||i===void 0)&&i.qr_code&&(a.totp.qr_code=`data:image/svg+xml;utf-8,${a.totp.qr_code}`),{data:a,error:null})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _verify(e){try{return await this._useSession(async t=>{var r;const{data:i,error:s}=t;if(s)return{data:null,error:s};const{data:o,error:a}=await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return a?{data:null,error:a}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",o),{data:o,error:a})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _challenge(e){try{return await this._useSession(async t=>{var r;const{data:i,error:s}=t;return s?{data:null,error:s}:await L(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token})})}catch(t){if(F(t))return{data:null,error:t};throw t}}async _challengeAndVerify(e){const{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){const{data:{user:e},error:t}=await this._getUser();if(t)return{data:null,error:t};const r=(e==null?void 0:e.factors)||[],i=r.filter(s=>s.factor_type==="totp"&&s.status==="verified");return{data:{all:r,totp:i},error:null}}async _getAuthenticatorAssuranceLevel(){return await this._useSession(async e=>{var t,r;const{data:{session:i},error:s}=e;if(s)return{data:null,error:s};if(!i)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const o=this._decodeJWT(i.access_token);let a=null;o.aal&&(a=o.aal);let l=a;((r=(t=i.user.factors)===null||t===void 0?void 0:t.filter(u=>u.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(l="aal2");const c=o.amr||[];return{data:{currentLevel:a,nextLevel:l,currentAuthenticationMethods:c},error:null}})}}Jt.nextInstanceID=0;globalThis&&Mt()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug");class Il extends Jt{constructor(e){super(e)}}var Cl=globalThis&&globalThis.__awaiter||function(n,e,t,r){function i(s){return s instanceof t?s:new t(function(o){o(s)})}return new(t||(t=Promise))(function(s,o){function a(u){try{c(r.next(u))}catch(h){o(h)}}function l(u){try{c(r.throw(u))}catch(h){o(h)}}function c(u){u.done?s(u.value):i(u.value).then(a,l)}c((r=r.apply(n,e||[])).next())})};const Al={headers:Ya},jl={schema:"public"},Fl={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},Ll={};class Dl{constructor(e,t,r){var i,s,o,a,l,c,u,h;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw new Error("supabaseUrl is required.");if(!t)throw new Error("supabaseKey is required.");const d=nl(e);this.realtimeUrl=`${d}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${d}/auth/v1`,this.storageUrl=`${d}/storage/v1`,this.functionsUrl=`${d}/functions/v1`;const p=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,f={db:jl,realtime:Ll,auth:Object.assign(Object.assign({},Fl),{storageKey:p}),global:Al},g=rl(r??{},f);this.storageKey=(s=(i=g.auth)===null||i===void 0?void 0:i.storageKey)!==null&&s!==void 0?s:"",this.headers=(a=(o=g.global)===null||o===void 0?void 0:o.headers)!==null&&a!==void 0?a:{},this.auth=this._initSupabaseAuthClient((l=g.auth)!==null&&l!==void 0?l:{},this.headers,(c=g.global)===null||c===void 0?void 0:c.fetch),this.fetch=tl(t,this._getAccessToken.bind(this),(u=g.global)===null||u===void 0?void 0:u.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},g.realtime)),this.rest=new Ar(`${d}/rest/v1`,{headers:this.headers,schema:(h=g.db)===null||h===void 0?void 0:h.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new Qo(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new Ka(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t;return Cl(this,void 0,void 0,function*(){const{data:r}=yield this.auth.getSession();return(t=(e=r.session)===null||e===void 0?void 0:e.access_token)!==null&&t!==void 0?t:null})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,storageKey:s,flowType:o,debug:a},l,c){const u={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Il({url:this.authUrl,headers:Object.assign(Object.assign({},u),l),storageKey:s,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:i,flowType:o,debug:a,fetch:c})}_initRealtimeClient(e){return new Na(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},e==null?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",t==null?void 0:t.access_token)})}_handleTokenChanged(e,t,r){(e==="TOKEN_REFRESHED"||e==="SIGNED_IN")&&this.changedAccessToken!==r?(this.realtime.setAuth(r??null),this.changedAccessToken=r):e==="SIGNED_OUT"&&(this.realtime.setAuth(this.supabaseKey),t=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const Nl=(n,e,t)=>new Dl(n,e,t);function Ei(n,e){var t=Object.keys(n);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(n);e&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(n,i).enumerable})),t.push.apply(t,r)}return t}function P(n){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};e%2?Ei(Object(t),!0).forEach(function(r){k(n,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(n,Object.getOwnPropertyDescriptors(t)):Ei(Object(t)).forEach(function(r){Object.defineProperty(n,r,Object.getOwnPropertyDescriptor(t,r))})}return n}function Wt(n){return Wt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},Wt(n)}function J(n,e){if(!(n instanceof e))throw new TypeError("Cannot call a class as a function")}function xi(n,e){for(var t=0;t<e.length;t++){var r=e[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(n,r.key,r)}}function W(n,e,t){return e&&xi(n.prototype,e),t&&xi(n,t),Object.defineProperty(n,"prototype",{writable:!1}),n}function k(n,e,t){return e in n?Object.defineProperty(n,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):n[e]=t,n}function $s(n,e){if(typeof e!="function"&&e!==null)throw new TypeError("Super expression must either be null or a function");n.prototype=Object.create(e&&e.prototype,{constructor:{value:n,writable:!0,configurable:!0}}),Object.defineProperty(n,"prototype",{writable:!1}),e&&ur(n,e)}function bn(n){return bn=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},bn(n)}function ur(n,e){return ur=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,r){return t.__proto__=r,t},ur(n,e)}function ql(n,e){if(n==null)return{};var t,r,i=function(o,a){if(o==null)return{};var l,c,u={},h=Object.keys(o);for(c=0;c<h.length;c++)l=h[c],a.indexOf(l)>=0||(u[l]=o[l]);return u}(n,e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(n);for(r=0;r<s.length;r++)t=s[r],e.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(n,t)&&(i[t]=n[t])}return i}function Ml(n,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(n)}function Is(n){var e=function(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}();return function(){var t,r=bn(n);if(e){var i=bn(this).constructor;t=Reflect.construct(r,arguments,i)}else t=r.apply(this,arguments);return Ml(this,t)}}function de(n,e){return function(t){if(Array.isArray(t))return t}(n)||function(t,r){var i=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(i!=null){var s,o,a=[],l=!0,c=!1;try{for(i=i.call(t);!(l=(s=i.next()).done)&&(a.push(s.value),!r||a.length!==r);l=!0);}catch(u){c=!0,o=u}finally{try{l||i.return==null||i.return()}finally{if(c)throw o}}return a}}(n,e)||Nr(n,e)||function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}()}function yt(n){return function(e){if(Array.isArray(e))return hr(e)}(n)||function(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}(n)||Nr(n)||function(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}()}function Nr(n,e){if(n){if(typeof n=="string")return hr(n,e);var t=Object.prototype.toString.call(n).slice(8,-1);return t==="Object"&&n.constructor&&(t=n.constructor.name),t==="Map"||t==="Set"?Array.from(n):t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?hr(n,e):void 0}}function hr(n,e){(e==null||e>n.length)&&(e=n.length);for(var t=0,r=new Array(e);t<e;t++)r[t]=n[t];return r}function Re(n,e){var t=typeof Symbol<"u"&&n[Symbol.iterator]||n["@@iterator"];if(!t){if(Array.isArray(n)||(t=Nr(n))||e&&n&&typeof n.length=="number"){t&&(n=t);var r=0,i=function(){};return{s:i,n:function(){return r>=n.length?{done:!0}:{done:!1,value:n[r++]}},e:function(l){throw l},f:i}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,o=!0,a=!1;return{s:function(){t=t.call(n)},n:function(){var l=t.next();return o=l.done,l},e:function(l){a=!0,s=l},f:function(){try{o||t.return==null||t.return()}finally{if(a)throw s}}}}var st={DEBUG:!1,LIB_VERSION:"1.110.0"},Ul=Array.isArray,Cs=Object.prototype,As=Cs.hasOwnProperty,Xt=Cs.toString,Q=Ul||function(n){return Xt.call(n)==="[object Array]"},Pi=function(n){return Xt.call(n)==="[object Uint8Array]"},me=function(n){return typeof n=="function"},Le=function(n){return n===Object(n)&&!Q(n)},j=function(n){return n===void 0},le=function(n){return Xt.call(n)=="[object String]"},Ce=function(n){return n===null},bt=function(n){return j(n)||Ce(n)},Pe=function(n){return Xt.call(n)=="[object Number]"},dr=function(n){return Xt.call(n)==="[object Boolean]"},Bl=function(n){return n instanceof FormData},_=typeof window<"u"?window:void 0,Ae=typeof globalThis<"u"?globalThis:_,js=Array.prototype,Ri=js.forEach,Oi=js.indexOf,$i=Ae==null?void 0:Ae.navigator,x=Ae==null?void 0:Ae.document,He=Ae==null?void 0:Ae.location,fr=Ae==null?void 0:Ae.fetch,Ii=Ae==null?void 0:Ae.XMLHttpRequest,G=$i==null?void 0:$i.userAgent,oe=_??{},Ci="[PostHog.js]",w={_log:function(n){if(_&&(st.DEBUG||oe.POSTHOG_DEBUG)&&!j(_.console)&&_.console){for(var e=("__rrweb_original__"in _.console[n])?_.console[n].__rrweb_original__:_.console[n],t=arguments.length,r=new Array(t>1?t-1:0),i=1;i<t;i++)r[i-1]=arguments[i];e.apply(void 0,[Ci].concat(r))}},info:function(){for(var n=arguments.length,e=new Array(n),t=0;t<n;t++)e[t]=arguments[t];w._log.apply(w,["log"].concat(e))},warn:function(){for(var n=arguments.length,e=new Array(n),t=0;t<n;t++)e[t]=arguments[t];w._log.apply(w,["warn"].concat(e))},error:function(){for(var n=arguments.length,e=new Array(n),t=0;t<n;t++)e[t]=arguments[t];w._log.apply(w,["error"].concat(e))},critical:function(){for(var n,e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];(n=console).error.apply(n,[Ci].concat(t))},uninitializedWarning:function(n){w.error("You must initialize PostHog before calling ".concat(n))}},wn={},kn=function(n){return n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};function wt(n,e,t){if(Q(n)){if(Ri&&n.forEach===Ri)n.forEach(e,t);else if("length"in n&&n.length===+n.length){for(var r=0,i=n.length;r<i;r++)if(r in n&&e.call(t,n[r],r)===wn)return}}}function M(n,e,t){if(!bt(n)){if(Q(n))return wt(n,e,t);if(Bl(n)){var r,i=Re(n.entries());try{for(i.s();!(r=i.n()).done;){var s=r.value;if(e.call(t,s[1],s[0])===wn)return}}catch(a){i.e(a)}finally{i.f()}}else for(var o in n)if(As.call(n,o)&&e.call(t,n[o],o)===wn)return}}var te=function(n){for(var e=arguments.length,t=new Array(e>1?e-1:0),r=1;r<e;r++)t[r-1]=arguments[r];return wt(t,function(i){for(var s in i)i[s]!==void 0&&(n[s]=i[s])}),n};function D(n,e){return n.indexOf(e)!==-1}function fn(n){for(var e=Object.keys(n),t=e.length,r=new Array(t);t--;)r[t]=[e[t],n[e[t]]];return r}var Fs=function(){return Date.now=Date.now||function(){return+new Date},Date.now()},Ai=function(n){try{return n()}catch{return}},Ls=function(n){return function(){try{for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return n.apply(this,t)}catch(i){w.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),w.critical(i)}}},pr=function(n){var e={};return M(n,function(t,r){le(t)&&t.length>0&&(e[r]=t)}),e};function Hl(n,e){return t=n,r=function(s){return le(s)&&!Ce(e)?s.slice(0,e):s},i=new Set,function s(o,a){return o!==Object(o)?r?r(o,a):o:i.has(o)?void 0:(i.add(o),Q(o)?(l=[],wt(o,function(c){l.push(s(c))})):(l={},M(o,function(c,u){i.has(c)||(l[u]=s(c,u))})),l);var l}(t);var t,r,i}function qr(n){var e,t,r,i,s,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,l=0,c="",u=[];if(!n)return n;n=zl(n);do e=(s=n.charCodeAt(a++)<<16|n.charCodeAt(a++)<<8|n.charCodeAt(a++))>>18&63,t=s>>12&63,r=s>>6&63,i=63&s,u[l++]=o.charAt(e)+o.charAt(t)+o.charAt(r)+o.charAt(i);while(a<n.length);switch(c=u.join(""),n.length%3){case 1:c=c.slice(0,-2)+"==";break;case 2:c=c.slice(0,-1)+"="}return c}var zl=function(n){var e,t,r,i,s="";for(e=t=0,r=(n=(n+"").replace(/\r\n/g,`
`).replace(/\r/g,`
`)).length,i=0;i<r;i++){var o=n.charCodeAt(i),a=null;o<128?t++:a=o>127&&o<2048?String.fromCharCode(o>>6|192,63&o|128):String.fromCharCode(o>>12|224,o>>6&63|128,63&o|128),Ce(a)||(t>e&&(s+=n.substring(e,t)),s+=a,e=t=i+1)}return t>e&&(s+=n.substring(e,n.length)),s},Ut=function(){function n(e){return e&&(e.preventDefault=n.preventDefault,e.stopPropagation=n.stopPropagation),e}return n.preventDefault=function(){this.returnValue=!1},n.stopPropagation=function(){this.cancelBubble=!0},function(e,t,r,i,s){if(e)if(e.addEventListener&&!i)e.addEventListener(t,r,!!s);else{var o="on"+t,a=e[o];e[o]=function(l,c,u){return function(h){if(h=h||n(_==null?void 0:_.event)){var d,p=!0;me(u)&&(d=u(h));var f=c.call(l,h);return d!==!1&&f!==!1||(p=!1),p}}}(e,r,a)}else w.error("No valid element provided to register_event")}}();function Bt(n,e){var t=function(){if(!x)return e("document not found");var r=x.createElement("script");r.type="text/javascript",r.src=n,r.onload=function(o){return e(void 0,o)},r.onerror=function(o){return e(o)};var i,s=x.querySelectorAll("body > script");s.length>0?(i=s[0].parentNode)===null||i===void 0||i.insertBefore(r,s[0]):x.body.appendChild(r)};x!=null&&x.body?t():x==null||x.addEventListener("DOMContentLoaded",t)}function Mr(n){return n?kn(n).split(/\s+/):[]}function Sn(n){var e="";switch(Wt(n.className)){case"string":e=n.className;break;case"object":e=("baseVal"in n.className?n.className.baseVal:null)||n.getAttribute("class")||"";break;default:e=""}return Mr(e)}function Tn(n){var e="";return pn(n)&&!qs(n)&&n.childNodes&&n.childNodes.length&&M(n.childNodes,function(t){Ds(t)&&t.textContent&&(e+=kn(t.textContent).split(/(\s+)/).filter(pt).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255))}),kn(e)}function Ur(n){return!!n&&n.nodeType===1}function nt(n,e){return!!n&&!!n.tagName&&n.tagName.toLowerCase()===e.toLowerCase()}function Ds(n){return!!n&&n.nodeType===3}function Ns(n){return!!n&&n.nodeType===11}var gr=["a","button","form","input","select","textarea","label"];function Vl(n){var e=n.parentNode;return!(!e||!Ur(e))&&e}function Jl(n,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;if(!_||!n||nt(n,"html")||!Ur(n))return!1;if(t!=null&&t.url_allowlist){var r=_.location.href,i=t.url_allowlist;if(i&&!i.some(function(p){return r.match(p)}))return!1}if(t!=null&&t.dom_event_allowlist){var s=t.dom_event_allowlist;if(s&&!s.some(function(p){return e.type===p}))return!1}for(var o=!1,a=[n],l=!0,c=n;c.parentNode&&!nt(c,"body");)if(Ns(c.parentNode))a.push(c.parentNode.host),c=c.parentNode.host;else{if(!(l=Vl(c)))break;if(gr.indexOf(l.tagName.toLowerCase())>-1)o=!0;else{var u=_.getComputedStyle(l);u&&u.getPropertyValue("cursor")==="pointer"&&(o=!0)}a.push(l),c=l}if(!function(p,f){var g=f==null?void 0:f.element_allowlist;if(j(g))return!0;var m,b=Re(p);try{var E=function(){var S=m.value;if(g.some(function(O){return S.tagName.toLowerCase()===O}))return{v:!0}};for(b.s();!(m=b.n()).done;){var T=E();if(Wt(T)==="object")return T.v}}catch(S){b.e(S)}finally{b.f()}return!1}(a,t)||!function(p,f){var g=f==null?void 0:f.css_selector_allowlist;if(j(g))return!0;var m,b=Re(p);try{var E=function(){var S=m.value;if(g.some(function(O){return S.matches(O)}))return{v:!0}};for(b.s();!(m=b.n()).done;){var T=E();if(Wt(T)==="object")return T.v}}catch(S){b.e(S)}finally{b.f()}return!1}(a,t))return!1;var h=_.getComputedStyle(n);if(h&&h.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var d=n.tagName.toLowerCase();switch(d){case"html":return!1;case"form":return e.type==="submit";case"input":case"select":case"textarea":return e.type==="change"||e.type==="click";default:return o?e.type==="click":e.type==="click"&&(gr.indexOf(d)>-1||n.getAttribute("contenteditable")==="true")}}function pn(n){for(var e=n;e.parentNode&&!nt(e,"body");e=e.parentNode){var t=Sn(e);if(D(t,"ph-sensitive")||D(t,"ph-no-capture"))return!1}if(D(Sn(n),"ph-include"))return!0;var r=n.type||"";if(le(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=n.name||n.id||"";return!(le(i)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function qs(n){return!!(nt(n,"input")&&!["button","checkbox","submit","reset"].includes(n.type)||nt(n,"select")||nt(n,"textarea")||n.getAttribute("contenteditable")==="true")}function pt(n){return!(bt(n)||le(n)&&(n=kn(n),/^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.test((n||"").replace(/[- ]/g,""))||/(^\d{3}-?\d{2}-?\d{4}$)/.test(n)))}function ji(n){var e=Tn(n);return pt(e="".concat(e," ").concat(Ms(n)).trim())?e:""}function Ms(n){var e="";return n&&n.childNodes&&n.childNodes.length&&M(n.childNodes,function(t){var r;if(t&&((r=t.tagName)===null||r===void 0?void 0:r.toLowerCase())==="span")try{var i=Tn(t);e="".concat(e," ").concat(i).trim(),t.childNodes&&t.childNodes.length&&(e="".concat(e," ").concat(Ms(t)).trim())}catch(s){w.error(s)}}),e}function Wl(n){return function(e){var t=e.map(function(r){var i,s,o="";if(r.tag_name&&(o+=r.tag_name),r.attr_class){r.attr_class.sort();var a,l=Re(r.attr_class);try{for(l.s();!(a=l.n()).done;){var c=a.value;o+=".".concat(c.replace(/"/g,""))}}catch(d){l.e(d)}finally{l.f()}}var u=P(P(P(P({},r.text?{text:r.text}:{}),{},{"nth-child":(i=r.nth_child)!==null&&i!==void 0?i:0,"nth-of-type":(s=r.nth_of_type)!==null&&s!==void 0?s:0},r.href?{href:r.href}:{}),r.attr_id?{attr_id:r.attr_id}:{}),r.attributes),h={};return fn(u).sort(function(d,p){var f=de(d,1)[0],g=de(p,1)[0];return f.localeCompare(g)}).forEach(function(d){var p=de(d,2),f=p[0],g=p[1];return h[Fi(f.toString())]=Fi(g.toString())}),o+=":",o+=fn(u).map(function(d){var p=de(d,2),f=p[0],g=p[1];return"".concat(f,'="').concat(g,'"')}).join("")});return t.join(";")}(function(e){return e.map(function(t){var r,i,s={text:(r=t.$el_text)===null||r===void 0?void 0:r.slice(0,400),tag_name:t.tag_name,href:(i=t.attr__href)===null||i===void 0?void 0:i.slice(0,2048),attr_class:Gl(t),attr_id:t.attr__id,nth_child:t.nth_child,nth_of_type:t.nth_of_type,attributes:{}};return fn(t).filter(function(o){return de(o,1)[0].indexOf("attr__")===0}).forEach(function(o){var a=de(o,2),l=a[0],c=a[1];return s.attributes[l]=c}),s})}(n))}function Fi(n){return n.replace(/"|\\"/g,'\\"')}function Gl(n){var e=n.attr__class;return e?Q(e)?e:Mr(e):void 0}var Kl=function(){function n(e){J(this,n),this.clicks=[],this.enabled=e}return W(n,[{key:"isRageClick",value:function(e,t,r){if(!this.enabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(t-i.y)<30&&r-i.timestamp<1e3){if(this.clicks.push({x:e,y:t,timestamp:r}),this.clicks.length===3)return!0}else this.clicks=[{x:e,y:t,timestamp:r}];return!1}}]),n}(),Us="$people_distinct_id",gn="__alias",jt="__timers",Li="$autocapture_disabled_server_side",vr="$session_recording_enabled_server_side",Di="$console_log_recording_enabled_server_side",Ni="$session_recording_recorder_version_server_side",qi="$session_recording_network_payload_capture",Mi="$session_recording_canvas_recording",En="$sesid",vn="$session_is_sampled",gt="$enabled_feature_flags",_r="$early_access_features",vt="$stored_person_properties",ze="$stored_group_properties",mr="$surveys",xn="$flag_call_reported",yr="$user_state",br="$posthog_quota_limited",wr="$client_session_props",Ql=[Us,gn,"__cmpns",jt,vr,En,gt,yr,br,_r,ze,vt,mr,xn,wr];function Gn(n,e){return e.length>n?e.slice(0,n)+"...":e}var Je={_initializedTokens:[],_isDisabledServerSide:null,_isAutocaptureEnabled:!1,_setIsAutocaptureEnabled:function(n){var e,t=Ce(this._isDisabledServerSide)?!((e=n.persistence)===null||e===void 0||!e.props[Li]):this._isDisabledServerSide,r=!!n.config.autocapture;this._isAutocaptureEnabled=r&&!t},_previousElementSibling:function(n){if(n.previousElementSibling)return n.previousElementSibling;var e=n;do e=e.previousSibling;while(e&&!Ur(e));return e},_getAugmentPropertiesFromElement:function(n){if(!pn(n))return{};var e={};return M(n.attributes,function(t){if(t.name.indexOf("data-ph-capture-attribute")===0){var r=t.name.replace("data-ph-capture-attribute-",""),i=t.value;r&&i&&pt(i)&&(e[r]=i)}}),e},_getPropertiesFromElement:function(n,e,t){var r,i=n.tagName.toLowerCase(),s={tag_name:i};gr.indexOf(i)>-1&&!t&&(i.toLowerCase()==="a"||i.toLowerCase()==="button"?s.$el_text=Gn(1024,ji(n)):s.$el_text=Gn(1024,Tn(n)));var o=Sn(n);o.length>0&&(s.classes=o.filter(function(h){return h!==""}));var a=(r=this.config)===null||r===void 0?void 0:r.element_attribute_ignorelist;M(n.attributes,function(h){var d;if((!qs(n)||["name","id","class"].indexOf(h.name)!==-1)&&(a==null||!a.includes(h.name))&&!e&&pt(h.value)&&(d=h.name,!le(d)||d.substring(0,10)!=="_ngcontent"&&d.substring(0,7)!=="_nghost")){var p=h.value;h.name==="class"&&(p=Mr(p).join(" ")),s["attr__"+h.name]=Gn(1024,p)}});for(var l=1,c=1,u=n;u=this._previousElementSibling(u);)l++,u.tagName===n.tagName&&c++;return s.nth_child=l,s.nth_of_type=c,s},_getDefaultProperties:function(n){return{$event_type:n,$ce_version:1}},_extractCustomPropertyValue:function(n){var e=[];return M(x==null?void 0:x.querySelectorAll(n.css_selector),function(t){var r;["input","select"].indexOf(t.tagName.toLowerCase())>-1?r=t.value:t.textContent&&(r=t.textContent),pt(r)&&e.push(r)}),e.join(", ")},_getCustomProperties:function(n){var e=this,t={};return M(this._customProperties,function(r){M(r.event_selectors,function(i){M(x==null?void 0:x.querySelectorAll(i),function(s){D(n,s)&&pn(s)&&(t[r.name]=e._extractCustomPropertyValue(r))})})}),t},_getEventTarget:function(n){return j(n.target)?n.srcElement||null:(e=n.target)!==null&&e!==void 0&&e.shadowRoot?n.composedPath()[0]||null:n.target||null;var e},_captureEvent:function(n,e){var t,r=this,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:"$autocapture",s=this._getEventTarget(n);if(Ds(s)&&(s=s.parentNode||null),i==="$autocapture"&&n.type==="click"&&n instanceof MouseEvent&&(t=this.rageclicks)!==null&&t!==void 0&&t.isRageClick(n.clientX,n.clientY,new Date().getTime())&&this._captureEvent(n,e,"$rageclick"),s&&Jl(s,n,this.config)){for(var o,a,l=[s],c=s;c.parentNode&&!nt(c,"body");)Ns(c.parentNode)?(l.push(c.parentNode.host),c=c.parentNode.host):(l.push(c.parentNode),c=c.parentNode);var u,h=[],d={},p=!1;if(M(l,function(g){var m=pn(g);g.tagName.toLowerCase()==="a"&&(u=g.getAttribute("href"),u=m&&pt(u)&&u),D(Sn(g),"ph-no-capture")&&(p=!0),h.push(r._getPropertiesFromElement(g,e.config.mask_all_element_attributes,e.config.mask_all_text));var b=r._getAugmentPropertiesFromElement(g);te(d,b)}),e.config.mask_all_text||(s.tagName.toLowerCase()==="a"||s.tagName.toLowerCase()==="button"?h[0].$el_text=ji(s):h[0].$el_text=Tn(s)),u&&(h[0].attr__href=u),p)return!1;var f=te(this._getDefaultProperties(n.type),e.elementsChainAsString?{$elements_chain:Wl(h)}:{$elements:h},(o=h[0])!==null&&o!==void 0&&o.$el_text?{$el_text:(a=h[0])===null||a===void 0?void 0:a.$el_text}:{},this._getCustomProperties(l),d);return e.capture(i,f),!0}},_navigate:function(n){_&&(_.location.href=n)},_addDomEventHandlers:function(n){var e=this;if(_&&x){var t=function(r){r=r||(_==null?void 0:_.event),e._captureEvent(r,n)};Ut(x,"submit",t,!1,!0),Ut(x,"change",t,!1,!0),Ut(x,"click",t,!1,!0)}},_customProperties:[],rageclicks:null,config:void 0,init:function(n){var e;dr(n.__autocapture)||(this.config=n.__autocapture),(e=this.config)!==null&&e!==void 0&&e.url_allowlist&&(this.config.url_allowlist=this.config.url_allowlist.map(function(t){return new RegExp(t)})),this.rageclicks=new Kl(n.config.rageclick)},afterDecideResponse:function(n,e){var t=e.config.token;this._initializedTokens.indexOf(t)>-1?w.info('autocapture already initialized for token "'+t+'"'):(e.persistence&&e.persistence.register(k({},Li,!!n.autocapture_opt_out)),this._isDisabledServerSide=!!n.autocapture_opt_out,this._setIsAutocaptureEnabled(e),this._initializedTokens.push(t),n&&n.config&&n.config.enable_collect_everything&&this._isAutocaptureEnabled?(n.custom_properties&&(this._customProperties=n.custom_properties),this._addDomEventHandlers(e)):e.__autocapture=!1)},enabledForProject:function(n,e,t){if(!n)return!0;e=j(e)?10:e,t=j(t)?10:t;for(var r=0,i=0;i<n.length;i++)r+=n.charCodeAt(i);return r%e<t},isBrowserSupported:function(){return me(x==null?void 0:x.querySelectorAll)}};(function(n){for(var e in n)me(n[e])&&(n[e]=n[e].bind(n))})(Je),function(n){for(var e in n)me(n[e])&&(n[e]=Ls(n[e]))}(Je);var Kn="$active_feature_flags",an="$override_feature_flags",Ui="$feature_flag_payloads",Bi=function(n){var e,t={},r=Re(fn(n||{}));try{for(r.s();!(e=r.n()).done;){var i=de(e.value,2),s=i[0],o=i[1];o&&(t[s]=o)}}catch(a){r.e(a)}finally{r.f()}return t},Yl=function(){function n(e){J(this,n),this.instance=e,this._override_warning=!1,this.featureFlagEventHandlers=[],this.reloadFeatureFlagsQueued=!1,this.reloadFeatureFlagsInAction=!1}return W(n,[{key:"getFlags",value:function(){return Object.keys(this.getFlagVariants())}},{key:"getFlagVariants",value:function(){var e=this.instance.get_property(gt),t=this.instance.get_property(an);if(!t)return e||{};for(var r=te({},e),i=Object.keys(t),s=0;s<i.length;s++)t[i[s]]===!1?delete r[i[s]]:r[i[s]]=t[i[s]];return this._override_warning||(w.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:r}),this._override_warning=!0),r}},{key:"getFlagPayloads",value:function(){return this.instance.get_property(Ui)||{}}},{key:"reloadFeatureFlags",value:function(){this.reloadFeatureFlagsQueued||(this.reloadFeatureFlagsQueued=!0,this._startReloadTimer())}},{key:"setAnonymousDistinctId",value:function(e){this.$anon_distinct_id=e}},{key:"setReloadingPaused",value:function(e){this.reloadFeatureFlagsInAction=e}},{key:"resetRequestQueue",value:function(){this.reloadFeatureFlagsQueued=!1}},{key:"_startReloadTimer",value:function(){var e=this;this.reloadFeatureFlagsQueued&&!this.reloadFeatureFlagsInAction&&setTimeout(function(){!e.reloadFeatureFlagsInAction&&e.reloadFeatureFlagsQueued&&(e.reloadFeatureFlagsQueued=!1,e._reloadFeatureFlagsRequest())},5)}},{key:"_reloadFeatureFlagsRequest",value:function(){var e=this;if(!this.instance.config.advanced_disable_feature_flags){this.setReloadingPaused(!0);var t=this.instance.config.token,r=this.instance.get_property(vt),i=this.instance.get_property(ze),s=qr(JSON.stringify({token:t,distinct_id:this.instance.get_distinct_id(),groups:this.instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:r,group_properties:i,disable_flags:this.instance.config.advanced_disable_feature_flags||void 0}));this.instance._send_request(this.instance.requestRouter.endpointFor("api","/decide/?v=3"),{data:s},{method:"POST"},this.instance._prepare_callback(function(o){e.$anon_distinct_id=void 0,e.receivedFeatureFlags(o),e.setReloadingPaused(!1),e._startReloadTimer()}))}}},{key:"getFeatureFlag",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.instance.decideEndpointWasHit||this.getFlags()&&this.getFlags().length>0){var r,i=this.getFlagVariants()[e],s="".concat(i),o=this.instance.get_property(xn)||{};return(t.send_event||!("send_event"in t))&&(!(e in o)||!o[e].includes(s))&&(Q(o[e])?o[e].push(s):o[e]=[s],(r=this.instance.persistence)===null||r===void 0||r.register(k({},xn,o)),this.instance.capture("$feature_flag_called",{$feature_flag:e,$feature_flag_response:i})),i}w.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}},{key:"getFeatureFlagPayload",value:function(e){return this.getFlagPayloads()[e]}},{key:"isFeatureEnabled",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(this.instance.decideEndpointWasHit||this.getFlags()&&this.getFlags().length>0)return!!this.getFeatureFlag(e,t);w.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}},{key:"addFeatureFlagsHandler",value:function(e){this.featureFlagEventHandlers.push(e)}},{key:"removeFeatureFlagsHandler",value:function(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(function(t){return t!==e})}},{key:"receivedFeatureFlags",value:function(e){if(this.instance.persistence){this.instance.decideEndpointWasHit=!0;var t=this.getFlagVariants(),r=this.getFlagPayloads();(function(i,s){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:{},l=i.featureFlags,c=i.featureFlagPayloads;if(l)if(Q(l)){var u,h={};if(l)for(var d=0;d<l.length;d++)h[l[d]]=!0;s&&s.register((k(u={},Kn,l),k(u,gt,h),u))}else{var p,f=l,g=c;i.errorsWhileComputingFlags&&(f=P(P({},o),f),g=P(P({},a),g)),s&&s.register((k(p={},Kn,Object.keys(Bi(f))),k(p,gt,f||{}),k(p,Ui,g||{}),p))}})(e,this.instance.persistence,t,r),this._fireFeatureFlagsCallbacks()}}},{key:"override",value:function(e){if(!this.instance.__loaded||!this.instance.persistence)return w.uninitializedWarning("posthog.feature_flags.override");if(this._override_warning=!1,e===!1)this.instance.persistence.unregister(an);else if(Q(e)){for(var t={},r=0;r<e.length;r++)t[e[r]]=!0;this.instance.persistence.register(k({},an,t))}else this.instance.persistence.register(k({},an,e))}},{key:"onFeatureFlags",value:function(e){var t=this;if(this.addFeatureFlagsHandler(e),this.instance.decideEndpointWasHit){var r=this._prepareFeatureFlagsForCallbacks(),i=r.flags,s=r.flagVariants;e(i,s)}return function(){return t.removeFeatureFlagsHandler(e)}}},{key:"updateEarlyAccessFeatureEnrollment",value:function(e,t){var r,i,s=k({},"$feature_enrollment/".concat(e),t);this.instance.capture("$feature_enrollment_update",{$feature_flag:e,$feature_enrollment:t,$set:s}),this.setPersonPropertiesForFlags(s,!1);var o=P(P({},this.getFlagVariants()),{},k({},e,t));(r=this.instance.persistence)===null||r===void 0||r.register((k(i={},Kn,Object.keys(Bi(o))),k(i,gt,o),i)),this._fireFeatureFlagsCallbacks()}},{key:"getEarlyAccessFeatures",value:function(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0&&arguments[1],i=this.instance.get_property(_r);if(i&&!r)return e(i);this.instance._send_request(this.instance.requestRouter.endpointFor("api","/api/early_access_features/?token=".concat(this.instance.config.token)),{},{method:"GET"},function(s){var o,a=s.earlyAccessFeatures;return(o=t.instance.persistence)===null||o===void 0||o.register(k({},_r,a)),e(a)})}},{key:"_prepareFeatureFlagsForCallbacks",value:function(){var e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(function(r){return t[r]}),flagVariants:Object.keys(t).filter(function(r){return t[r]}).reduce(function(r,i){return r[i]=t[i],r},{})}}},{key:"_fireFeatureFlagsCallbacks",value:function(){var e=this._prepareFeatureFlagsForCallbacks(),t=e.flags,r=e.flagVariants;this.featureFlagEventHandlers.forEach(function(i){return i(t,r)})}},{key:"setPersonPropertiesForFlags",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],r=this.instance.get_property(vt)||{};this.instance.register(k({},vt,P(P({},r),e))),t&&this.instance.reloadFeatureFlags()}},{key:"resetPersonPropertiesForFlags",value:function(){this.instance.unregister(vt)}},{key:"setGroupPropertiesForFlags",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1],r=this.instance.get_property(ze)||{};Object.keys(r).length!==0&&Object.keys(r).forEach(function(i){r[i]=P(P({},r[i]),e[i]),delete e[i]}),this.instance.register(k({},ze,P(P({},r),e))),t&&this.instance.reloadFeatureFlags()}},{key:"resetGroupPropertiesForFlags",value:function(e){if(e){var t=this.instance.get_property(ze)||{};this.instance.register(k({},ze,P(P({},t),{},k({},e,{}))))}else this.instance.unregister(ze)}}]),n}();Math.trunc||(Math.trunc=function(n){return n<0?Math.ceil(n):Math.floor(n)}),Number.isInteger||(Number.isInteger=function(n){return Pe(n)&&isFinite(n)&&Math.floor(n)===n});var Hi="0123456789abcdef",Xl=function(){function n(e){if(J(this,n),this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}return W(n,[{key:"toString",value:function(){for(var e="",t=0;t<this.bytes.length;t++)e=e+Hi.charAt(this.bytes[t]>>>4)+Hi.charAt(15&this.bytes[t]),t!==3&&t!==5&&t!==7&&t!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}},{key:"clone",value:function(){return new n(this.bytes.slice(0))}},{key:"equals",value:function(e){return this.compareTo(e)===0}},{key:"compareTo",value:function(e){for(var t=0;t<16;t++){var r=this.bytes[t]-e.bytes[t];if(r!==0)return Math.sign(r)}return 0}}],[{key:"fromFieldsV7",value:function(e,t,r,i){if(!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||t<0||r<0||i<0||e>0xffffffffffff||t>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var s=new Uint8Array(16);return s[0]=e/Math.pow(2,40),s[1]=e/Math.pow(2,32),s[2]=e/Math.pow(2,24),s[3]=e/Math.pow(2,16),s[4]=e/Math.pow(2,8),s[5]=e,s[6]=112|t>>>8,s[7]=t,s[8]=128|r>>>24,s[9]=r>>>16,s[10]=r>>>8,s[11]=r,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new n(s)}}]),n}(),Zl=function(){function n(){J(this,n),k(this,"timestamp",0),k(this,"counter",0),k(this,"random",new ec)}return W(n,[{key:"generate",value:function(){var e=this.generateOrAbort();if(j(e)){this.timestamp=0;var t=this.generateOrAbort();if(j(t))throw new Error("Could not generate UUID after timestamp reset");return t}return e}},{key:"generateOrAbort",value:function(){var e=Date.now();if(e>this.timestamp)this.timestamp=e,this.resetCounter();else{if(!(e+1e4>this.timestamp))return;this.counter++,this.counter>4398046511103&&(this.timestamp++,this.resetCounter())}return Xl.fromFieldsV7(this.timestamp,Math.trunc(this.counter/Math.pow(2,30)),this.counter&Math.pow(2,30)-1,this.random.nextUint32())}},{key:"resetCounter",value:function(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}}]),n}(),Bs=function(n){if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<n.length;e++)n[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return n};_&&!j(_.crypto)&&crypto.getRandomValues&&(Bs=function(n){return crypto.getRandomValues(n)});var zi,ec=function(){function n(){J(this,n),k(this,"buffer",new Uint32Array(8)),k(this,"cursor",1/0)}return W(n,[{key:"nextUint32",value:function(){return this.cursor>=this.buffer.length&&(Bs(this.buffer),this.cursor=0),this.buffer[this.cursor++]}}]),n}(),tt=function(){return tc().toString()},tc=function(){return(zi||(zi=new Zl)).generate()},nc="Thu, 01 Jan 1970 00:00:00 GMT",$t="",rc=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function ic(n,e){if(e){var t=function(i){var s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:x;if($t)return $t;if(!s||["localhost","127.0.0.1"].includes(i))return"";for(var o=i.split("."),a=Math.min(o.length,8),l="dmn_chk_"+tt(),c=new RegExp("(^|;)\\s*"+l+"=1");!$t&&a--;){var u=o.slice(a).join("."),h=l+"=1;domain=."+u;s.cookie=h,c.test(s.cookie)&&(s.cookie=h+";expires="+nc,$t=u)}return $t}(n);if(!t){var r=function(i){var s=i.match(rc);return s?s[0]:""}(n);r!==t&&w.info("Warning: cookie subdomain discovery mismatch",r,t),t=r}return t?"; domain=."+t:""}return""}var ee,Ie={is_supported:function(){return!!x},error:function(n){w.error("cookieStore error: "+n)},get:function(n){if(x){try{for(var e=n+"=",t=x.cookie.split(";").filter(function(s){return s.length}),r=0;r<t.length;r++){for(var i=t[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch{}return null}},parse:function(n){var e;try{e=JSON.parse(Ie.get(n))||{}}catch{}return e},set:function(n,e,t,r,i){if(x)try{var s="",o="",a=ic(x.location.hostname,r);if(t){var l=new Date;l.setTime(l.getTime()+24*t*60*60*1e3),s="; expires="+l.toUTCString()}i&&(o="; secure");var c=n+"="+encodeURIComponent(JSON.stringify(e))+s+"; SameSite=Lax; path=/"+a+o;return c.length>3686.4&&w.warn("cookieStore warning: large cookie, len="+c.length),x.cookie=c,c}catch{return}},remove:function(n,e){try{Ie.set(n,"",-1,e)}catch{return}}},Qn=null,K={is_supported:function(){if(!Ce(Qn))return Qn;var n=!0;if(j(_))n=!1;else try{var e="__mplssupport__";K.set(e,"xyz"),K.get(e)!=='"xyz"'&&(n=!1),K.remove(e)}catch{n=!1}return n||w.error("localStorage unsupported; falling back to cookie store"),Qn=n,n},error:function(n){w.error("localStorage error: "+n)},get:function(n){try{return _==null?void 0:_.localStorage.getItem(n)}catch(e){K.error(e)}return null},parse:function(n){try{return JSON.parse(K.get(n))||{}}catch{}return null},set:function(n,e){try{_==null||_.localStorage.setItem(n,JSON.stringify(e))}catch(t){K.error(t)}},remove:function(n){try{_==null||_.localStorage.removeItem(n)}catch(e){K.error(e)}}},sc=["distinct_id",En,vn],Ft=P(P({},K),{},{parse:function(n){try{var e={};try{e=Ie.parse(n)||{}}catch{}var t=te(e,JSON.parse(K.get(n)||"{}"));return K.set(n,t),t}catch{}return null},set:function(n,e,t,r,i){try{K.set(n,e);var s={};sc.forEach(function(o){e[o]&&(s[o]=e[o])}),Object.keys(s).length&&Ie.set(n,s,t,r,i)}catch(o){K.error(o)}},remove:function(n,e){try{_==null||_.localStorage.removeItem(n),Ie.remove(n,e)}catch(t){K.error(t)}}}),ln={},oc={is_supported:function(){return!0},error:function(n){w.error("memoryStorage error: "+n)},get:function(n){return ln[n]||null},parse:function(n){return ln[n]||null},set:function(n,e){ln[n]=e},remove:function(n){delete ln[n]}},Qe=null,re={is_supported:function(){if(!Ce(Qe))return Qe;if(Qe=!0,j(_))Qe=!1;else try{var n="__support__";re.set(n,"xyz"),re.get(n)!=='"xyz"'&&(Qe=!1),re.remove(n)}catch{Qe=!1}return Qe},error:function(n){w.error("sessionStorage error: ",n)},get:function(n){try{return _==null?void 0:_.sessionStorage.getItem(n)}catch(e){re.error(e)}return null},parse:function(n){try{return JSON.parse(re.get(n))||null}catch{}return null},set:function(n,e){try{_==null||_.sessionStorage.setItem(n,JSON.stringify(e))}catch(t){re.error(t)}},remove:function(n){try{_==null||_.sessionStorage.removeItem(n)}catch(e){re.error(e)}}},ac=["localhost","127.0.0.1"],_n=!(!Ii||!("withCredentials"in new Ii))||!!fr,Hs=function(n){var e=x==null?void 0:x.createElement("a");return j(e)?null:(e.href=n,e)},lc=function(n,e){return!!function(t){try{new RegExp(t)}catch{return!1}return!0}(e)&&new RegExp(e).test(n)},cc=function(n){var e,t,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"&",i=[];return M(n,function(s,o){j(s)||j(o)||o==="undefined"||(e=encodeURIComponent(function(a){return a instanceof File}(s)?s.name:s.toString()),t=encodeURIComponent(o),i[i.length]=t+"="+e)}),i.join(r)},Vi=function(n,e){for(var t,r=((n.split("#")[0]||"").split("?")[1]||"").split("&"),i=0;i<r.length;i++){var s=r[i].split("=");if(s[0]===e){t=s;break}}if(!Q(t)||t.length<2)return"";var o=t[1];try{o=decodeURIComponent(o)}catch{w.error("Skipping decoding for malformed query param: "+o)}return o.replace(/\+/g," ")},Pn=function(n,e){var t=n.match(new RegExp(e+"=([^&]*)"));return t?t[1]:null},Te="Mobile",Rn="iOS",$e="Android",Gt="Tablet",zs=$e+" "+Gt,Vs="iPad",Js="Apple",Ws=Js+" Watch",Ln="Safari",Et="BlackBerry",Gs="Samsung",Ks=Gs+"Browser",Qs=Gs+" Internet",ot="Chrome",uc=ot+" OS",Ys=ot+" "+Rn,Br="Internet Explorer",Xs=Br+" "+Te,On="Opera",hc=On+" Mini",Hr="Edge",Zs="Microsoft "+Hr,kt="Firefox",eo=kt+" "+Rn,Kt="Nintendo",Qt="PlayStation",St="Xbox",to=$e+" "+Te,no=Te+" "+Ln,Lt="Windows",kr=Lt+" Phone",Ji="Nokia",Sr="Ouya",ro="Generic",dc=ro+" "+Te.toLowerCase(),io=ro+" "+Gt.toLowerCase(),Tr="Konqueror",ae="(\\d+(\\.\\d+)?)",Yn=new RegExp("Version/"+ae),fc=new RegExp(St,"i"),pc=new RegExp(Qt+" \\w+","i"),gc=new RegExp(Kt+" \\w+","i"),zr=new RegExp(Et+"|PlayBook|BB10","i"),vc={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000",5.1:"XP",5.2:"XP","6.0":"Vista",6.1:"7",6.2:"8",6.3:"8.1",6.4:"10","10.0":"10"},_c=function(n,e){return e&&D(e,Js)||function(t){return D(t,Ln)&&!D(t,ot)&&!D(t,$e)}(n)},Wi=function(n,e,t){return t?On:(e=e||"",D(n," OPR/")&&D(n,"Mini")?hc:D(n," OPR/")?On:zr.test(n)?Et:D(n,"IE"+Te)||D(n,"WPDesktop")?Xs:D(n,Ks)?Qs:D(n,Hr)||D(n,"Edg/")?Zs:D(n,"FBIOS")?"Facebook "+Te:D(n,ot)?ot:D(n,"CriOS")?Ys:D(n,"UCWEB")||D(n,"UCBrowser")?"UC Browser":D(n,"FxiOS")?eo:D(n,$e)?to:D(n.toLowerCase(),Tr.toLowerCase())?Tr:_c(n,e)?D(n,Te)?no:Ln:D(n,kt)?kt:D(n,"MSIE")||D(n,"Trident/")?Br:D(n,"Gecko")?kt:"")},mc=(k(ee={},Xs,[new RegExp("rv:"+ae)]),k(ee,Zs,[new RegExp(Hr+"?\\/"+ae)]),k(ee,ot,[new RegExp(ot+"/"+ae)]),k(ee,Ys,[new RegExp("CriOS\\/"+ae)]),k(ee,"UC Browser",[new RegExp("(UCBrowser|UCWEB)\\/"+ae)]),k(ee,Ln,[Yn]),k(ee,no,[Yn]),k(ee,On,[new RegExp("(Opera|OPR)\\/"+ae)]),k(ee,kt,[new RegExp(kt+"\\/"+ae)]),k(ee,eo,[new RegExp("FxiOS\\/"+ae)]),k(ee,Tr,[new RegExp("Konqueror[:/]?"+ae,"i")]),k(ee,Et,[new RegExp(Et+" "+ae),Yn]),k(ee,to,[new RegExp("android\\s"+ae)]),k(ee,Qs,[new RegExp(Ks+"\\/"+ae)]),k(ee,Br,[new RegExp("(rv:|MSIE )"+ae)]),k(ee,"Mozilla",[new RegExp("rv:"+ae)]),ee),Gi=[[new RegExp(St+"; "+St+" (.*?)[);]","i"),function(n){return[St,n&&n[1]||""]}],[new RegExp(Kt,"i"),[Kt,""]],[new RegExp(Qt,"i"),[Qt,""]],[zr,[Et,""]],[new RegExp(Lt,"i"),function(n,e){if(/Phone/.test(e)||/WPDesktop/.test(e))return[kr,""];if(new RegExp(Te).test(e)&&!/IEMobile\b/.test(e))return[Lt+" "+Te,""];var t=/Windows NT ([0-9.]+)/i.exec(e);if(t&&t[1]){var r=t[1],i=vc[r]||"";return/arm/i.test(e)&&(i="RT"),[Lt,i]}return[Lt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,function(n){if(n&&n[3]){var e=[n[3],n[4],n[5]||"0"];return[Rn,e.join(".")]}return[Rn,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,function(n){var e="";return n&&n.length>=3&&(e=j(n[2])?n[3]:n[2]),["watchOS",e]}],[new RegExp("("+$e+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+$e+")","i"),function(n){if(n&&n[2]){var e=[n[2],n[3],n[4]||"0"];return[$e,e.join(".")]}return[$e,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,function(n){var e=["Mac OS X",""];if(n&&n[1]){var t=[n[1],n[2],n[3]||"0"];e[1]=t.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[uc,""]],[/Linux|debian/i,["Linux",""]]],Ki=function(n){return gc.test(n)?Kt:pc.test(n)?Qt:fc.test(n)?St:new RegExp(Sr,"i").test(n)?Sr:new RegExp("("+kr+"|WPDesktop)","i").test(n)?kr:/iPad/.test(n)?Vs:/iPod/.test(n)?"iPod Touch":/iPhone/.test(n)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(n)?Ws:zr.test(n)?Et:/(kobo)\s(ereader|touch)/i.test(n)?"Kobo":new RegExp(Ji,"i").test(n)?Ji:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(n)||/(kf[a-z]+)( bui|\)).+silk\//i.test(n)?"Kindle Fire":/(Android|ZTE)/i.test(n)?!new RegExp(Te).test(n)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(n)?/pixel[\daxl ]{1,6}/i.test(n)&&!/pixel c/i.test(n)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(n)||/lmy47v/i.test(n)&&!/QTAQZ3/i.test(n)?$e:zs:$e:new RegExp("(pda|"+Te+")","i").test(n)?dc:new RegExp(Gt,"i").test(n)&&!new RegExp(Gt+" pc","i").test(n)?io:""},cn="https?://(.*)",Z={campaignParams:function(n){var e=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","gad_source","gbraid","wbraid","fbclid","msclkid"].concat(n||[]),t={};return M(e,function(r){var i=x?Vi(x.URL,r):"";i.length&&(t[r]=i)}),t},searchEngine:function(){var n=x==null?void 0:x.referrer;return n?n.search(cn+"google.([^/?]*)")===0?"google":n.search(cn+"bing.com")===0?"bing":n.search(cn+"yahoo.com")===0?"yahoo":n.search(cn+"duckduckgo.com")===0?"duckduckgo":null:null},searchInfo:function(){var n=Z.searchEngine(),e=n!="yahoo"?"q":"p",t={};if(!Ce(n)){t.$search_engine=n;var r=x?Vi(x.referrer,e):"";r.length&&(t.ph_keyword=r)}return t},browser:Wi,browserVersion:function(n,e,t){var r=Wi(n,e,t),i=mc[r];if(j(i))return null;for(var s=0;s<i.length;s++){var o=i[s],a=n.match(o);if(a)return parseFloat(a[a.length-2])}return null},browserLanguage:function(){return navigator.language||navigator.userLanguage},os:function(n){for(var e=0;e<Gi.length;e++){var t=de(Gi[e],2),r=t[0],i=t[1],s=r.exec(n),o=s&&(me(i)?i(s,n):i);if(o)return o}return["",""]},device:Ki,deviceType:function(n){var e=Ki(n);return e===Vs||e===zs||e==="Kobo"||e==="Kindle Fire"||e===io?Gt:e===Kt||e===St||e===Qt||e===Sr?"Console":e===Ws?"Wearable":e?Te:"Desktop"},referrer:function(){return(x==null?void 0:x.referrer)||"$direct"},referringDomain:function(){var n;return x!=null&&x.referrer&&((n=Hs(x.referrer))===null||n===void 0?void 0:n.host)||"$direct"},properties:function(){if(!G)return{};var n=de(Z.os(G),2),e=n[0],t=n[1];return te(pr({$os:e,$os_version:t,$browser:Z.browser(G,navigator.vendor,oe.opera),$device:Z.device(G),$device_type:Z.deviceType(G)}),{$current_url:He==null?void 0:He.href,$host:He==null?void 0:He.host,$pathname:He==null?void 0:He.pathname,$raw_user_agent:G.length>1e3?G.substring(0,997)+"...":G,$browser_version:Z.browserVersion(G,navigator.vendor,oe.opera),$browser_language:Z.browserLanguage(),$screen_height:_==null?void 0:_.screen.height,$screen_width:_==null?void 0:_.screen.width,$viewport_height:_==null?void 0:_.innerHeight,$viewport_width:_==null?void 0:_.innerWidth,$lib:"web",$lib_version:st.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Fs()/1e3})},people_properties:function(){if(!G)return{};var n=de(Z.os(G),2),e=n[0],t=n[1];return te(pr({$os:e,$os_version:t,$browser:Z.browser(G,navigator.vendor,oe.opera)}),{$browser_version:Z.browserVersion(G,navigator.vendor,oe.opera)})}},yc=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Xn=function(){function n(e){J(this,n),this.config=e,this.props={},this.campaign_params_saved=!1,this.name=function(t){var r="";return t.token&&(r=t.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),t.persistence_name?"ph_"+t.persistence_name:"ph_"+r+"_posthog"}(e),this.storage=this.buildStorage(e),this.load(),this.update_config(e,e),this.save()}return W(n,[{key:"buildStorage",value:function(e){yc.indexOf(e.persistence.toLowerCase())===-1&&(w.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var t=e.persistence.toLowerCase();return t==="localstorage"&&K.is_supported()?K:t==="localstorage+cookie"&&Ft.is_supported()?Ft:t==="sessionstorage"&&re.is_supported()?re:t==="memory"?oc:t==="cookie"?Ie:Ft.is_supported()?Ft:Ie}},{key:"properties",value:function(){var e={};return M(this.props,function(t,r){if(r===gt&&Le(t))for(var i=Object.keys(t),s=0;s<i.length;s++)e["$feature/".concat(i[s])]=t[i[s]];else a=r,l=!1,(Ce(o=Ql)?l:Oi&&o.indexOf===Oi?o.indexOf(a)!=-1:(M(o,function(c){if(l||(l=c===a))return wn}),l))||(e[r]=t);var o,a,l}),e}},{key:"load",value:function(){if(!this.disabled){var e=this.storage.parse(this.name);e&&(this.props=te({},e))}}},{key:"save",value:function(){this.disabled||this.storage.set(this.name,this.props,this.expire_days,this.cross_subdomain,this.secure)}},{key:"remove",value:function(){this.storage.remove(this.name,!1),this.storage.remove(this.name,!0)}},{key:"clear",value:function(){this.remove(),this.props={}}},{key:"register_once",value:function(e,t,r){var i=this;if(Le(e)){j(t)&&(t="None"),this.expire_days=j(r)?this.default_expiry:r;var s=!1;if(M(e,function(o,a){i.props.hasOwnProperty(a)&&i.props[a]!==t||(i.props[a]=o,s=!0)}),s)return this.save(),!0}return!1}},{key:"register",value:function(e,t){var r=this;if(Le(e)){this.expire_days=j(t)?this.default_expiry:t;var i=!1;if(M(e,function(s,o){e.hasOwnProperty(o)&&r.props[o]!==s&&(r.props[o]=s,i=!0)}),i)return this.save(),!0}return!1}},{key:"unregister",value:function(e){e in this.props&&(delete this.props[e],this.save())}},{key:"update_campaign_params",value:function(){this.campaign_params_saved||(this.register(Z.campaignParams(this.config.custom_campaign_params)),this.campaign_params_saved=!0)}},{key:"update_search_keyword",value:function(){this.register(Z.searchInfo())}},{key:"update_referrer_info",value:function(){this.register({$referrer:this.props.$referrer||Z.referrer(),$referring_domain:this.props.$referring_domain||Z.referringDomain()})}},{key:"get_referrer_info",value:function(){return pr({$referrer:this.props.$referrer,$referring_domain:this.props.$referring_domain})}},{key:"safe_merge",value:function(e){return M(this.props,function(t,r){r in e||(e[r]=t)}),e}},{key:"update_config",value:function(e,t){if(this.default_expiry=this.expire_days=e.cookie_expiration,this.set_disabled(e.disable_persistence),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==t.persistence){var r=this.buildStorage(e),i=this.props;this.clear(),this.storage=r,this.props=i,this.save()}}},{key:"set_disabled",value:function(e){this.disabled=e,this.disabled?this.remove():this.save()}},{key:"set_cross_subdomain",value:function(e){e!==this.cross_subdomain&&(this.cross_subdomain=e,this.remove(),this.save())}},{key:"get_cross_subdomain",value:function(){return!!this.cross_subdomain}},{key:"set_secure",value:function(e){e!==this.secure&&(this.secure=e,this.remove(),this.save())}},{key:"set_event_timer",value:function(e,t){var r=this.props[jt]||{};r[e]=t,this.props[jt]=r,this.save()}},{key:"remove_event_timer",value:function(e){var t=(this.props[jt]||{})[e];return j(t)||(delete this.props[jt][e],this.save()),t}},{key:"get_user_state",value:function(){return this.props[yr]||"anonymous"}},{key:"set_user_state",value:function(e){this.props[yr]=e,this.save()}},{key:"get_quota_limits",value:function(){return this.props[br]||{}}},{key:"set_quota_limits",value:function(e){this.props[br]=e,this.save()}}]),n}(),Qi=2,bc=4,wc=W(function n(e){var t,r,i=this,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};J(this,n),k(this,"bucketSize",100),k(this,"refillRate",10),k(this,"mutationBuckets",{}),k(this,"loggedTracker",{}),k(this,"refillBuckets",function(){Object.keys(i.mutationBuckets).forEach(function(o){i.mutationBuckets[o]=i.mutationBuckets[o]+i.refillRate,i.mutationBuckets[o]>=i.bucketSize&&delete i.mutationBuckets[o]})}),k(this,"getNodeOrRelevantParent",function(o){var a=i.rrweb.mirror.getNode(o);if((a==null?void 0:a.nodeName)!=="svg"&&a instanceof Element){var l=a.closest("svg");if(l)return[i.rrweb.mirror.getId(l),l]}return[o,a]}),k(this,"numberOfChanges",function(o){var a,l,c,u,h,d,p,f;return((a=(l=o.removes)===null||l===void 0?void 0:l.length)!==null&&a!==void 0?a:0)+((c=(u=o.attributes)===null||u===void 0?void 0:u.length)!==null&&c!==void 0?c:0)+((h=(d=o.texts)===null||d===void 0?void 0:d.length)!==null&&h!==void 0?h:0)+((p=(f=o.adds)===null||f===void 0?void 0:f.length)!==null&&p!==void 0?p:0)}),k(this,"throttleMutations",function(o){if(o.type!==3||o.data.source!==0)return o;var a=o.data,l=i.numberOfChanges(a);a.attributes&&(a.attributes=a.attributes.filter(function(u){var h,d,p,f=de(i.getNodeOrRelevantParent(u.id),2),g=f[0],m=f[1];return i.mutationBuckets[g]===0?!1:(i.mutationBuckets[g]=(h=i.mutationBuckets[g])!==null&&h!==void 0?h:i.bucketSize,i.mutationBuckets[g]=Math.max(i.mutationBuckets[g]-1,0),i.mutationBuckets[g]===0&&(i.loggedTracker[g]||(i.loggedTracker[g]=!0,(d=(p=i.options).onBlockedNode)===null||d===void 0||d.call(p,g,m))),u)}));var c=i.numberOfChanges(a);return c!==0||l===c?o:void 0}),this.rrweb=e,this.options=s,this.refillRate=(t=this.options.refillRate)!==null&&t!==void 0?t:this.refillRate,this.bucketSize=(r=this.options.bucketSize)!==null&&r!==void 0?r:this.bucketSize,setInterval(function(){i.refillBuckets()},1e3)}),mn=function(n){return n[n.DomContentLoaded=0]="DomContentLoaded",n[n.Load=1]="Load",n[n.FullSnapshot=2]="FullSnapshot",n[n.IncrementalSnapshot=3]="IncrementalSnapshot",n[n.Meta=4]="Meta",n[n.Custom=5]="Custom",n[n.Plugin=6]="Plugin",n}(mn||{}),kc={initiatorTypes:["audio","beacon","body","css","early-hint","embed","fetch","frame","iframe","icon","image","img","input","link","navigation","object","ping","script","track","video","xmlhttprequest"],maskRequestFn:function(n){return n},recordHeaders:!1,recordBody:!1,recordInitialRequests:!1,recordPerformance:!1,performanceEntryTypeToObserve:["first-input","navigation","paint","resource"],payloadSizeLimitBytes:1e6},Sc=["authorization","x-forwarded-for","authorization","cookie","set-cookie","x-api-key","x-real-ip","remote-addr","forwarded","proxy-authorization","x-csrf-token","x-csrftoken","x-xsrf-token"],Tc=["/s/","/e/","/i/vo/e/"];function Yi(n,e,t,r){if(bt(n))return n;var i=(e==null?void 0:e["content-length"])||function(s){return new Blob([s]).size}(n);return le(i)&&(i=parseInt(i)),i>t?"[SessionReplay] ".concat(r," body too large to record (").concat(i," bytes)"):n}var Ec=function(n,e){var t,r,i,s=n.session_recording,o=s.recordHeaders!==!1&&e.recordHeaders,a=s.recordBody!==!1&&e.recordBody,l=s.recordPerformance!==!1&&e.recordPerformance,c=(t=s,i=Math.min(1e6,(r=t.payloadSizeLimitBytes)!==null&&r!==void 0?r:1e6),function(d){return d!=null&&d.requestBody&&(d.requestBody=Yi(d.requestBody,d.requestHeaders,i,"Request")),d!=null&&d.responseBody&&(d.responseBody=Yi(d.responseBody,d.responseHeaders,i,"Response")),d}),u=function(d){return c(function(g){var m=Hs(g.name);if(!(m&&m.pathname&&Tc.includes(m.pathname)))return g}((p=d,Object.keys((f=p.requestHeaders)!==null&&f!==void 0?f:{}).forEach(function(g){var m;Sc.includes(g.toLowerCase())&&((m=p.requestHeaders)===null||m===void 0||delete m[g])}),p)));var p,f},h=me(n.session_recording.maskNetworkRequestFn);return h&&me(n.session_recording.maskCapturedNetworkRequestFn)&&w.warn("Both `maskNetworkRequestFn` and `maskCapturedNetworkRequestFn` are defined. `maskNetworkRequestFn` will be ignored."),h&&(n.session_recording.maskCapturedNetworkRequestFn=function(d){var p=n.session_recording.maskNetworkRequestFn({url:d.name});return P(P({},d),{},{name:p==null?void 0:p.url})}),s.maskRequestFn=me(n.session_recording.maskCapturedNetworkRequestFn)?function(d){var p,f,g,m=u(d);return m&&(p=(f=(g=n.session_recording).maskCapturedNetworkRequestFn)===null||f===void 0?void 0:f.call(g,m))!==null&&p!==void 0?p:void 0}:void 0,s.maskRequestFn||(s.maskRequestFn=u),P(P(P({},kc),s),{},{recordHeaders:o,recordBody:a,recordPerformance:l,recordInitialRequests:l})},xc="__ph_opt_in_out_";function Pc(n,e){ao(!0,n,e)}function Rc(n,e){ao(!1,n,e)}function Oc(n,e){return oo(n,e)==="1"}function so(n,e){return!!function(t){if(t&&t.respectDnt){var r=t&&t.window||_,i=r==null?void 0:r.navigator,s=!1;return M([i==null?void 0:i.doNotTrack,i.msDoNotTrack,r.doNotTrack],function(o){D([!0,1,"1","yes"],o)&&(s=!0)}),s}return!1}(e)||oo(n,e)==="0"}function $c(n,e){Vr(e=e||{}).remove(Jr(n,e),!!e.crossSubdomainCookie)}function Vr(n){return(n=n||{}).persistenceType==="localStorage"?K:n.persistenceType==="localStorage+cookie"?Ft:Ie}function Jr(n,e){return((e=e||{}).persistencePrefix||xc)+n}function oo(n,e){return Vr(e).get(Jr(n,e))}function ao(n,e,t){le(e)&&e.length?(Vr(t=t||{}).set(Jr(e,t),n?1:0,Pe(t.cookieExpiration)?t.cookieExpiration:null,t.crossSubdomainCookie,t.secureCookie),t.capture&&n&&t.capture(t.captureEventName||"$opt_in",t.captureProperties||{},{send_instantly:!0})):w.error("gdpr."+(n?"optIn":"optOut")+" called with an invalid token")}function Er(n){var e=!1;try{var t=n.config.token,r=n.config.respect_dnt,i=n.config.opt_out_capturing_persistence_type,s=n.config.opt_out_capturing_cookie_prefix||void 0,o=n.config.window;t&&(e=so(t,{respectDnt:r,persistenceType:i,persistencePrefix:s,window:o}))}catch(a){w.error("Unexpected error when checking capturing opt-out status: "+a)}return e}var Oe,lo=3e5,Xi=lo;(function(n){n[n.Mutation=0]="Mutation",n[n.MouseMove=1]="MouseMove",n[n.MouseInteraction=2]="MouseInteraction",n[n.Scroll=3]="Scroll",n[n.ViewportResize=4]="ViewportResize",n[n.Input=5]="Input",n[n.TouchMove=6]="TouchMove",n[n.MediaInteraction=7]="MediaInteraction",n[n.StyleSheetRule=8]="StyleSheetRule",n[n.CanvasMutation=9]="CanvasMutation",n[n.Font=10]="Font",n[n.Log=11]="Log",n[n.Drag=12]="Drag",n[n.StyleDeclaration=13]="StyleDeclaration",n[n.Selection=14]="Selection",n[n.AdoptedStyleSheet=15]="AdoptedStyleSheet"})(Oe||(Oe={}));var Ic=[Oe.MouseMove,Oe.MouseInteraction,Oe.Scroll,Oe.ViewportResize,Oe.Input,Oe.TouchMove,Oe.MediaInteraction,Oe.Drag],Zi=function(n){return{rrwebMethod:n,enqueuedAt:Date.now(),attempt:1}},ve="[SessionRecording]",Cc=function(){function n(e){var t=this;if(J(this,n),k(this,"queuedRRWebEvents",[]),k(this,"isIdle",!1),k(this,"_linkedFlagSeen",!1),k(this,"_lastActivityTimestamp",Date.now()),k(this,"windowId",null),k(this,"sessionId",null),k(this,"_linkedFlag",null),k(this,"_sampleRate",null),k(this,"_minimumDuration",null),k(this,"_forceAllowLocalhostNetworkCapture",!1),this.instance=e,this._captureStarted=!1,this._endpoint="/s/",this.stopRrweb=void 0,this.receivedDecide=!1,_==null||_.addEventListener("beforeunload",function(){t._flushBuffer()}),_==null||_.addEventListener("offline",function(){t._tryAddCustomEvent("browser offline",{})}),_==null||_.addEventListener("online",function(){t._tryAddCustomEvent("browser online",{})}),!this.instance.sessionManager)throw w.error(ve+" started without valid sessionManager"),new Error(ve+" started without valid sessionManager. This is a bug.");this.buffer=this.clearBuffer()}return W(n,[{key:"started",get:function(){return this._captureStarted}},{key:"sessionManager",get:function(){if(!this.instance.sessionManager)throw w.error(ve+" started without valid sessionManager"),new Error(ve+" started without valid sessionManager. This is a bug.");return this.instance.sessionManager}},{key:"isSampled",get:function(){return Pe(this._sampleRate)?this.instance.get_property(vn):null}},{key:"sessionDuration",get:function(){var e,t,r=(e=this.buffer)===null||e===void 0?void 0:e.data[((t=this.buffer)===null||t===void 0?void 0:t.data.length)-1],i=this.sessionManager.checkAndGetSessionAndWindowId(!0).sessionStartTimestamp;return r?r.timestamp-i:null}},{key:"isRecordingEnabled",get:function(){var e=!!this.instance.get_property(vr),t=!this.instance.config.disable_session_recording;return _&&e&&t}},{key:"isConsoleLogCaptureEnabled",get:function(){var e=!!this.instance.get_property(Di),t=this.instance.config.enable_recording_console_log;return t??e}},{key:"canvasRecording",get:function(){var e=this.instance.get_property(Mi);return e&&e.fps&&e.quality?{enabled:e.enabled,fps:e.fps,quality:e.quality}:void 0}},{key:"recordingVersion",get:function(){var e,t=this.instance.get_property(Ni);return((e=this.instance.config.session_recording)===null||e===void 0?void 0:e.recorderVersion)||t||"v1"}},{key:"networkPayloadCapture",get:function(){var e,t,r=this.instance.get_property(qi),i={recordHeaders:(e=this.instance.config.session_recording)===null||e===void 0?void 0:e.recordHeaders,recordBody:(t=this.instance.config.session_recording)===null||t===void 0?void 0:t.recordBody},s=(i==null?void 0:i.recordHeaders)||(r==null?void 0:r.recordHeaders),o=(i==null?void 0:i.recordBody)||(r==null?void 0:r.recordBody),a=this.instance.config.capture_performance||(r==null?void 0:r.capturePerformance);return s||o||a?{recordHeaders:s,recordBody:o,recordPerformance:a}:void 0}},{key:"status",get:function(){return this.receivedDecide?this.isRecordingEnabled?bt(this._linkedFlag)||this._linkedFlagSeen?dr(this.isSampled)?this.isSampled?"sampled":"disabled":"active":"buffering":"disabled":"buffering"}},{key:"startRecordingIfEnabled",value:function(){this.isRecordingEnabled?(this._startCapture(),w.info(ve+" started")):(this.stopRecording(),this.clearBuffer())}},{key:"stopRecording",value:function(){this._captureStarted&&this.stopRrweb&&(this.stopRrweb(),this.stopRrweb=void 0,this._captureStarted=!1,w.info(ve+" stopped"))}},{key:"makeSamplingDecision",value:function(e){var t,r=this.sessionId!==e;if(Pe(this._sampleRate)){var i,s=this.isSampled;r||!dr(s)?i=Math.random()<this._sampleRate:i=s,i||w.warn(ve+" Sample rate (".concat(this._sampleRate,") has determined that this sessionId (").concat(e,") will not be sent to the server.")),(t=this.instance.persistence)===null||t===void 0||t.register(k({},vn,i))}else{var o;(o=this.instance.persistence)===null||o===void 0||o.register(k({},vn,null))}}},{key:"afterDecideResponse",value:function(e){var t,r,i,s,o,a,l,c,u,h,d,p=this;this.instance.persistence&&this.instance.persistence.register((k(d={},vr,!!e.sessionRecording),k(d,Di,(o=e.sessionRecording)===null||o===void 0?void 0:o.consoleLogRecordingEnabled),k(d,Ni,(a=e.sessionRecording)===null||a===void 0?void 0:a.recorderVersion),k(d,qi,P({capturePerformance:e.capturePerformance},(l=e.sessionRecording)===null||l===void 0?void 0:l.networkPayloadCapture)),k(d,Mi,{enabled:(c=e.sessionRecording)===null||c===void 0?void 0:c.recordCanvas,fps:(u=e.sessionRecording)===null||u===void 0?void 0:u.canvasFps,quality:(h=e.sessionRecording)===null||h===void 0?void 0:h.canvasQuality}),d));var f=(t=e.sessionRecording)===null||t===void 0?void 0:t.sampleRate;this._sampleRate=bt(f)?null:parseFloat(f);var g,m=(r=e.sessionRecording)===null||r===void 0?void 0:r.minimumDurationMilliseconds;if(this._minimumDuration=j(m)?null:m,this._linkedFlag=((i=e.sessionRecording)===null||i===void 0?void 0:i.linkedFlag)||null,(s=e.sessionRecording)!==null&&s!==void 0&&s.endpoint&&(this._endpoint=(g=e.sessionRecording)===null||g===void 0?void 0:g.endpoint),Pe(this._sampleRate)&&this.sessionManager.onSessionId(function(O){p.makeSamplingDecision(O)}),!bt(this._linkedFlag)){var b,E,T=le(this._linkedFlag)?this._linkedFlag:(b=this._linkedFlag)===null||b===void 0?void 0:b.flag,S=le(this._linkedFlag)?null:(E=this._linkedFlag)===null||E===void 0?void 0:E.variant;this.instance.onFeatureFlags(function(O,I){var q=Le(I)&&T in I,R=S?I[T]===S:q;R&&w.info(ve+" linked flag matched",{linkedFlag:T,linkedVariant:S}),p._linkedFlagSeen=R})}this.receivedDecide=!0,this.startRecordingIfEnabled()}},{key:"log",value:function(e){var t,r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"log";(t=this.instance.sessionRecording)===null||t===void 0||t.onRRwebEmit({type:6,data:{plugin:"rrweb/console@1",payload:{level:r,trace:[],payload:[JSON.stringify(e)]}},timestamp:Fs()})}},{key:"_startCapture",value:function(){var e=this;if(!j(Object.assign)&&!(this._captureStarted||this.instance.config.disable_session_recording||Er(this.instance))){this._captureStarted=!0,this.sessionManager.checkAndGetSessionAndWindowId();var t=this.recordingVersion==="v2"?"recorder-v2.js":"recorder.js";this.instance.__loaded_recorder_version!==this.recordingVersion?Bt(this.instance.requestRouter.endpointFor("assets","/static/".concat(t,"?v=").concat(st.LIB_VERSION)),function(r){if(r)return w.error(ve+" could not load ".concat(t),r);e._onScriptLoaded()}):this._onScriptLoaded()}}},{key:"_isInteractiveEvent",value:function(e){var t;return e.type===3&&Ic.indexOf((t=e.data)===null||t===void 0?void 0:t.source)!==-1}},{key:"_updateWindowAndSessionIds",value:function(e){var t=this._isInteractiveEvent(e);t||this.isIdle||e.timestamp-this._lastActivityTimestamp>Xi&&(this.isIdle=!0,this._tryAddCustomEvent("sessionIdle",{reason:"user inactivity",timeSinceLastActive:e.timestamp-this._lastActivityTimestamp,threshold:Xi}));var r=!1;if(t&&(this._lastActivityTimestamp=e.timestamp,this.isIdle&&(this.isIdle=!1,this._tryAddCustomEvent("sessionNoLongerIdle",{reason:"user activity",type:e.type}),r=!0)),!this.isIdle){var i=this.sessionManager.checkAndGetSessionAndWindowId(!t,e.timestamp),s=i.windowId,o=i.sessionId,a=this.sessionId!==o,l=this.windowId!==s;this.windowId=s,this.sessionId=o,(r||[Qi,bc].indexOf(e.type)===-1&&(l||a))&&this._tryTakeFullSnapshot()}}},{key:"_tryRRWebMethod",value:function(e){try{return e.rrwebMethod(),!0}catch(t){return w.warn(ve+" could not emit queued rrweb event.",t),this.queuedRRWebEvents.length<10&&this.queuedRRWebEvents.push({enqueuedAt:e.enqueuedAt||Date.now(),attempt:e.attempt++,rrwebMethod:e.rrwebMethod}),!1}}},{key:"_tryAddCustomEvent",value:function(e,t){var r=this;return this._tryRRWebMethod(Zi(function(){return r.rrwebRecord.addCustomEvent(e,t)}))}},{key:"_tryTakeFullSnapshot",value:function(){var e=this;return this._tryRRWebMethod(Zi(function(){return e.rrwebRecord.takeFullSnapshot()}))}},{key:"_onScriptLoaded",value:function(){var e,t=this,r={blockClass:"ph-no-capture",blockSelector:void 0,ignoreClass:"ph-ignore-input",maskTextClass:"ph-mask",maskTextSelector:void 0,maskTextFn:void 0,maskAllInputs:!0,maskInputOptions:{},maskInputFn:void 0,slimDOMOptions:{},collectFonts:!1,inlineStylesheet:!0,recordCrossOriginIframes:!1};this.rrwebRecord=_.rrweb?_.rrweb.record:_.rrwebRecord;for(var i=this.instance.config.session_recording,s=0,o=Object.entries(i||{});s<o.length;s++){var a=de(o[s],2),l=a[0],c=a[1];l in r&&(r[l]=c)}if(this.canvasRecording&&this.canvasRecording.enabled&&(r.recordCanvas=!0,r.sampling={canvas:this.canvasRecording.fps},r.dataURLOptions={type:"image/webp",quality:this.canvasRecording.quality}),this.rrwebRecord){this.mutationRateLimiter=(e=this.mutationRateLimiter)!==null&&e!==void 0?e:new wc(this.rrwebRecord,{onBlockedNode:function(h,d){var p="Too many mutations on node '".concat(h,"'. Rate limiting. This could be due to SVG animations or something similar");w.info(p,{node:d}),t.log(ve+" "+p,"warn")}}),this._scheduleFullSnapshot();var u=this._gatherRRWebPlugins();this.stopRrweb=this.rrwebRecord(P({emit:function(h){t.onRRwebEmit(h)},plugins:u},r)),this.instance._addCaptureHook(function(h){try{if(h==="$pageview"){var d=_?t._maskUrl(_.location.href):"";if(!d)return;t._tryAddCustomEvent("$pageview",{href:d}),t._tryTakeFullSnapshot()}}catch(p){w.error("Could not add $pageview to rrweb session",p)}}),this._lastActivityTimestamp=Date.now(),this.isIdle=!1,this._tryAddCustomEvent("$session_options",{sessionRecordingOptions:r,activePlugins:u.map(function(h){return h==null?void 0:h.name})}),this._tryAddCustomEvent("$posthog_config",{config:this.instance.config})}else w.error(ve+"onScriptLoaded was called but rrwebRecord is not available. This indicates something has gone wrong.")}},{key:"_scheduleFullSnapshot",value:function(){var e=this;this._fullSnapshotTimer&&clearInterval(this._fullSnapshotTimer),this._fullSnapshotTimer=setInterval(function(){e._tryTakeFullSnapshot()},lo)}},{key:"_gatherRRWebPlugins",value:function(){var e=[];return oe.rrwebConsoleRecord&&this.isConsoleLogCaptureEnabled&&e.push(oe.rrwebConsoleRecord.getRecordConsolePlugin()),this.networkPayloadCapture&&me(oe.getRecordNetworkPlugin)&&(!ac.includes(location.hostname)||this._forceAllowLocalhostNetworkCapture?e.push(oe.getRecordNetworkPlugin(Ec(this.instance.config,this.networkPayloadCapture))):w.info(ve+" NetworkCapture not started because we are on localhost.")),e}},{key:"onRRwebEmit",value:function(e){if(this._processQueuedEvents(),e&&Le(e)){if(e.type===mn.Meta){var t=this._maskUrl(e.data.href);if(!t)return;e.data.href=t}e.type===mn.FullSnapshot&&this._scheduleFullSnapshot();var r=this.mutationRateLimiter?this.mutationRateLimiter.throttleMutations(e):e;if(r){var i=function(a){var l=a;if(l&&Le(l)&&l.type===6&&Le(l.data)&&l.data.plugin==="rrweb/console@1"){l.data.payload.payload.length>10&&(l.data.payload.payload=l.data.payload.payload.slice(0,10),l.data.payload.payload.push("...[truncated]"));for(var c=[],u=0;u<l.data.payload.payload.length;u++)l.data.payload.payload[u]&&l.data.payload.payload[u].length>2e3?c.push(l.data.payload.payload[u].slice(0,2e3)+"...[truncated]"):c.push(l.data.payload.payload[u]);return l.data.payload.payload=c,a}return a}(r),s=JSON.stringify(i).length;if(this._updateWindowAndSessionIds(i),!this.isIdle||i.type===mn.Custom){var o={$snapshot_bytes:s,$snapshot_data:i,$session_id:this.sessionId,$window_id:this.windowId};this.status!=="disabled"?this._captureSnapshotBuffered(o):this.clearBuffer()}}}}},{key:"_processQueuedEvents",value:function(){var e=this;if(this.queuedRRWebEvents.length){var t=yt(this.queuedRRWebEvents);this.queuedRRWebEvents=[],t.forEach(function(r){Date.now()-r.enqueuedAt>2e3?e._tryAddCustomEvent("rrwebQueueTimeout",{enqueuedAt:r.enqueuedAt,attempt:r.attempt,queueLength:t.length}):e._tryRRWebMethod(r)&&e._tryAddCustomEvent("rrwebQueueSuccess",{enqueuedAt:r.enqueuedAt,attempt:r.attempt,queueLength:t.length})})}}},{key:"_maskUrl",value:function(e){var t=this.instance.config.session_recording;if(t.maskNetworkRequestFn){var r,i={url:e};return(r=i=t.maskNetworkRequestFn(i))===null||r===void 0?void 0:r.url}return e}},{key:"clearBuffer",value:function(){return this.buffer=void 0,{size:0,data:[],sessionId:this.sessionId,windowId:this.windowId}}},{key:"_flushBuffer",value:function(){var e=this;this.flushBufferTimer&&(clearTimeout(this.flushBufferTimer),this.flushBufferTimer=void 0);var t=this._minimumDuration,r=this.sessionDuration,i=Pe(r)&&r>=0,s=Pe(t)&&i&&r<t;return this.status==="buffering"||s?(this.flushBufferTimer=setTimeout(function(){e._flushBuffer()},2e3),this.buffer||this.clearBuffer()):this.buffer&&this.buffer.data.length!==0?(this._captureSnapshot({$snapshot_bytes:this.buffer.size,$snapshot_data:this.buffer.data,$session_id:this.buffer.sessionId,$window_id:this.buffer.windowId}),this.clearBuffer()):this.buffer||this.clearBuffer()}},{key:"_captureSnapshotBuffered",value:function(e){var t,r=this,i=2+(((t=this.buffer)===null||t===void 0?void 0:t.data.length)||0);(!this.buffer||this.buffer.size+e.$snapshot_bytes+i>943718.4||this.buffer.sessionId&&this.buffer.sessionId!==this.sessionId)&&(this.buffer=this._flushBuffer()),Ce(this.buffer.sessionId)&&!Ce(this.sessionId)&&(this.buffer.sessionId=this.sessionId,this.buffer.windowId=this.windowId),this.buffer.size+=e.$snapshot_bytes,this.buffer.data.push(e.$snapshot_data),this.flushBufferTimer||(this.flushBufferTimer=setTimeout(function(){r._flushBuffer()},2e3))}},{key:"_captureSnapshot",value:function(e){this.instance.capture("$snapshot",e,{method:"POST",_url:this.instance.requestRouter.endpointFor("api",this._endpoint),_noTruncate:!0,_batchKey:"recordings",_metrics:{rrweb_full_snapshot:e.$snapshot_data.type===Qi}})}}]),n}(),Ac=function(){function n(e){J(this,n),this.instance=e,this.instance.decideEndpointWasHit=this.instance._hasBootstrappedFeatureFlags()}return W(n,[{key:"call",value:function(){var e=this,t=qr(JSON.stringify({token:this.instance.config.token,distinct_id:this.instance.get_distinct_id(),groups:this.instance.getGroups(),person_properties:this.instance.get_property(vt),group_properties:this.instance.get_property(ze),disable_flags:this.instance.config.advanced_disable_feature_flags||this.instance.config.advanced_disable_feature_flags_on_first_load||void 0}));this.instance._send_request(this.instance.requestRouter.endpointFor("api","/decide/?v=3"),{data:t,verbose:!0},{method:"POST"},function(r){return e.parseDecideResponse(r)})}},{key:"parseDecideResponse",value:function(e){var t,r=this;if(this.instance.featureFlags.setReloadingPaused(!1),this.instance.featureFlags._startReloadTimer(),(e==null?void 0:e.status)!==0){if(!x||!x.body)return w.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(function(){r.parseDecideResponse(e)},500);this.instance.toolbar.afterDecideResponse(e),(t=this.instance.sessionRecording)===null||t===void 0||t.afterDecideResponse(e),Je.afterDecideResponse(e,this.instance),this.instance._afterDecideResponse(e),this.instance.config.advanced_disable_feature_flags_on_first_load||this.instance.config.advanced_disable_feature_flags||this.instance.featureFlags.receivedFeatureFlags(e);var i=_==null?void 0:_.extendPostHogWithSurveys;e.surveys&&!i&&Bt(this.instance.requestRouter.endpointFor("assets","/static/surveys.js"),function(c){if(c)return w.error("Could not load surveys script",c);_.extendPostHogWithSurveys(r.instance)});var s=_==null?void 0:_.extendPostHogWithExceptionAutoCapture;if(e.autocaptureExceptions&&e.autocaptureExceptions&&j(s)&&Bt(this.instance.requestRouter.endpointFor("assets","/static/exception-autocapture.js"),function(c){if(c)return w.error("Could not load exception autocapture script",c);_.extendPostHogWithExceptionAutocapture(r.instance,e)}),e.siteApps)if(this.instance.config.opt_in_site_apps){var o,a=Re(e.siteApps);try{var l=function(){var c=o.value,u=c.id,h=c.url,d=r.instance.requestRouter.endpointFor("api",h);oe["__$$ph_site_app_".concat(u)]=r.instance,Bt(d,function(p){p&&w.error("Error while initializing PostHog app with config id ".concat(u),p)})};for(a.s();!(o=a.n()).done;)l()}catch(c){a.e(c)}finally{a.f()}}else e.siteApps.length>0&&w.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}else w.error("Failed to fetch feature flags from PostHog.")}}]),n}(),jc=["source"],Fc=_!=null&&_.location?Pn(_.location.hash,"__posthog")||Pn(location.hash,"state"):null,Lc=function(){function n(e){J(this,n),this.instance=e}return W(n,[{key:"afterDecideResponse",value:function(e){var t=e.toolbarParams||e.editorParams||(e.toolbarVersion?{toolbarVersion:e.toolbarVersion}:{});e.isAuthenticated&&t.toolbarVersion&&t.toolbarVersion.indexOf("toolbar")===0&&this.loadToolbar(P({},t))}},{key:"maybeLoadToolbar",value:function(){var e,t,r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,s=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;if(!_||!x)return!1;r=(e=r)!==null&&e!==void 0?e:_.location,s=(t=s)!==null&&t!==void 0?t:_.history;try{if(!i){try{_.localStorage.setItem("test","test"),_.localStorage.removeItem("test")}catch{return!1}i=_==null?void 0:_.localStorage}var o,a=Fc||Pn(r.hash,"__posthog")||Pn(r.hash,"state"),l=a?Ai(function(){return JSON.parse(atob(decodeURIComponent(a)))})||Ai(function(){return JSON.parse(decodeURIComponent(a))}):null;return l&&l.action==="ph_authorize"?((o=l).source="url",o&&Object.keys(o).length>0&&(l.desiredHash?r.hash=l.desiredHash:s?s.replaceState("",x.title,r.pathname+r.search):r.hash="")):((o=JSON.parse(i.getItem("_postHogToolbarParams")||"{}")).source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token)&&(this.loadToolbar(o),!0)}catch{return!1}}},{key:"loadToolbar",value:function(e){var t=this;if(!_||oe._postHogToolbarLoaded)return!1;oe._postHogToolbarLoaded=!0;var r=3e5,i=Math.floor(Date.now()/r)*r,s=this.instance.requestRouter.endpointFor("assets","/static/toolbar.js?t=".concat(i)),o=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,a=P(P({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},o?{instrument:!1}:{});a.source;var l=ql(a,jc);return _.localStorage.setItem("_postHogToolbarParams",JSON.stringify(l)),Bt(s,function(c){c?w.error("Failed to load toolbar",c):(oe.ph_load_toolbar||oe.ph_load_editor)(a,t.instance)}),Ut(_,"turbolinks:load",function(){oe._postHogToolbarLoaded=!1,t.loadToolbar(a)}),!0}},{key:"_loadEditor",value:function(e){return this.loadToolbar(e)}},{key:"maybeLoadEditor",value:function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:void 0,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:void 0,r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:void 0;return this.maybeLoadToolbar(e,t,r)}}]),n}(),co=function(){function n(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:3e3;J(this,n),this.isPolling=!0,this._event_queue=[],this._empty_queue_count=0,this._poller=void 0,this._pollInterval=e}return W(n,[{key:"setPollInterval",value:function(e){this._pollInterval=e,this.isPolling&&this.poll()}},{key:"poll",value:function(){}},{key:"unload",value:function(){}},{key:"getTime",value:function(){return new Date().getTime()}}]),n}(),Dc=function(n){$s(t,co);var e=Is(t);function t(r){var i,s=arguments.length>1&&arguments[1]!==void 0?arguments[1]:3e3;return J(this,t),(i=e.call(this,s)).handlePollRequest=r,i}return W(t,[{key:"enqueue",value:function(r,i,s){this._event_queue.push({url:r,data:i,options:s}),this.isPolling||(this.isPolling=!0,this.poll())}},{key:"poll",value:function(){var r=this;clearTimeout(this._poller),this._poller=setTimeout(function(){if(r._event_queue.length>0){var i=r.formatQueue(),s=function(a){var l=i[a],c=l.url,u=l.data,h=l.options;M(u,function(d,p){u[p].offset=Math.abs(u[p].timestamp-r.getTime()),delete u[p].timestamp}),r.handlePollRequest(c,u,h)};for(var o in i)s(o);r._event_queue.length=0,r._empty_queue_count=0}else r._empty_queue_count++;r._empty_queue_count>4&&(r.isPolling=!1,r._empty_queue_count=0),r.isPolling&&r.poll()},this._pollInterval)}},{key:"unload",value:function(){var r=this;clearTimeout(this._poller);var i=this._event_queue.length>0?this.formatQueue():{};this._event_queue.length=0;var s=Object.values(i);[].concat(yt(s.filter(function(o){return o.url.indexOf("/e")===0})),yt(s.filter(function(o){return o.url.indexOf("/e")!==0}))).map(function(o){var a=o.url,l=o.data,c=o.options;r.handlePollRequest(a,l,P(P({},c),{},{transport:"sendBeacon"}))})}},{key:"formatQueue",value:function(){var r={};return M(this._event_queue,function(i){var s=i.url,o=i.data,a=i.options,l=(a?a._batchKey:null)||s;j(r[l])&&(r[l]={data:[],url:s,options:a}),a&&r[l].options&&r[l].options._metrics&&!r[l].options._metrics.rrweb_full_snapshot&&(r[l].options._metrics.rrweb_full_snapshot=a._metrics.rrweb_full_snapshot),r[l].data.push(o)}),r}}]),t}(),ye=Uint8Array,ce=Uint16Array,xt=Uint32Array,Wr=new ye([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Gr=new ye([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),es=new ye([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),uo=function(n,e){for(var t=new ce(31),r=0;r<31;++r)t[r]=e+=1<<n[r-1];var i=new xt(t[30]);for(r=1;r<30;++r)for(var s=t[r];s<t[r+1];++s)i[s]=s-t[r]<<5|r;return[t,i]},ho=uo(Wr,2),Nc=ho[0],xr=ho[1];Nc[28]=258,xr[258]=28;for(var ts=uo(Gr,0)[1],Pr=new ce(32768),z=0;z<32768;++z){var Ye=(43690&z)>>>1|(21845&z)<<1;Ye=(61680&(Ye=(52428&Ye)>>>2|(13107&Ye)<<2))>>>4|(3855&Ye)<<4,Pr[z]=((65280&Ye)>>>8|(255&Ye)<<8)>>>1}var Ht=function(n,e,t){for(var r=n.length,i=0,s=new ce(e);i<r;++i)++s[n[i]-1];var o,a=new ce(e);for(i=0;i<e;++i)a[i]=a[i-1]+s[i-1]<<1;if(t){o=new ce(1<<e);var l=15-e;for(i=0;i<r;++i)if(n[i])for(var c=i<<4|n[i],u=e-n[i],h=a[n[i]-1]++<<u,d=h|(1<<u)-1;h<=d;++h)o[Pr[h]>>>l]=c}else for(o=new ce(r),i=0;i<r;++i)o[i]=Pr[a[n[i]-1]++]>>>15-n[i];return o},at=new ye(288);for(z=0;z<144;++z)at[z]=8;for(z=144;z<256;++z)at[z]=9;for(z=256;z<280;++z)at[z]=7;for(z=280;z<288;++z)at[z]=8;var $n=new ye(32);for(z=0;z<32;++z)$n[z]=5;var et,qc=Ht(at,9,0),Mc=Ht($n,5,0),fo=function(n){return(n/8>>0)+(7&n&&1)},po=function(n,e,t){(e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length);var r=new(n instanceof ce?ce:n instanceof xt?xt:ye)(t-e);return r.set(n.subarray(e,t)),r},je=function(n,e,t){t<<=7&e;var r=e/8>>0;n[r]|=t,n[r+1]|=t>>>8},It=function(n,e,t){t<<=7&e;var r=e/8>>0;n[r]|=t,n[r+1]|=t>>>8,n[r+2]|=t>>>16},Zn=function(n,e){for(var t=[],r=0;r<n.length;++r)n[r]&&t.push({s:r,f:n[r]});var i=t.length,s=t.slice();if(!i)return[new ye(0),0];if(i==1){var o=new ye(t[0].s+1);return o[t[0].s]=1,[o,1]}t.sort(function(O,I){return O.f-I.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],c=0,u=1,h=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=i-1;)a=t[t[c].f<t[h].f?c++:h++],l=t[c!=u&&t[c].f<t[h].f?c++:h++],t[u++]={s:-1,f:a.f+l.f,l:a,r:l};var d=s[0].s;for(r=1;r<i;++r)s[r].s>d&&(d=s[r].s);var p=new ce(d+1),f=Uc(t[u-1],p,0);if(f>e){r=0;var g=0,m=f-e,b=1<<m;for(s.sort(function(O,I){return p[I.s]-p[O.s]||O.f-I.f});r<i;++r){var E=s[r].s;if(!(p[E]>e))break;g+=b-(1<<f-p[E]),p[E]=e}for(g>>>=m;g>0;){var T=s[r].s;p[T]<e?g-=1<<e-p[T]++-1:++r}for(;r>=0&&g;--r){var S=s[r].s;p[S]==e&&(--p[S],++g)}f=e}return[new ye(p),f]},Uc=function n(e,t,r){return e.s==-1?Math.max(n(e.l,t,r+1),n(e.r,t,r+1)):t[e.s]=r},ns=function(n){for(var e=n.length;e&&!n[--e];);for(var t=new ce(++e),r=0,i=n[0],s=1,o=function(l){t[r++]=l},a=1;a<=e;++a)if(n[a]==i&&a!=e)++s;else{if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(i);s=1,i=n[a]}return[t.subarray(0,r),e]},Ct=function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},yn=function(n,e,t){var r=t.length,i=fo(e+2);n[i]=255&r,n[i+1]=r>>>8,n[i+2]=255^n[i],n[i+3]=255^n[i+1];for(var s=0;s<r;++s)n[i+s+4]=t[s];return 8*(i+4+r)},rs=function(n,e,t,r,i,s,o,a,l,c,u){je(e,u++,t),++i[256];for(var h=Zn(i,15),d=h[0],p=h[1],f=Zn(s,15),g=f[0],m=f[1],b=ns(d),E=b[0],T=b[1],S=ns(g),O=S[0],I=S[1],q=new ce(19),R=0;R<E.length;++R)q[31&E[R]]++;for(R=0;R<O.length;++R)q[31&O[R]]++;for(var Ee=Zn(q,7),ie=Ee[0],X=Ee[1],ue=19;ue>4&&!ie[es[ue-1]];--ue);var fe,v,y,$,V=c+5<<3,B=Ct(i,at)+Ct(s,$n)+o,A=Ct(i,d)+Ct(s,g)+o+14+3*ue+Ct(q,ie)+(2*q[16]+3*q[17]+7*q[18]);if(V<=B&&V<=A)return yn(e,u,n.subarray(l,l+c));if(je(e,u,1+(A<B)),u+=2,A<B){fe=Ht(d,p,0),v=d,y=Ht(g,m,0),$=g;var pe=Ht(ie,X,0);for(je(e,u,T-257),je(e,u+5,I-1),je(e,u+10,ue-4),u+=14,R=0;R<ue;++R)je(e,u+3*R,ie[es[R]]);u+=3*ue;for(var be=[E,O],Y=0;Y<2;++Y){var we=be[Y];for(R=0;R<we.length;++R){var ge=31&we[R];je(e,u,pe[ge]),u+=ie[ge],ge>15&&(je(e,u,we[R]>>>5&127),u+=we[R]>>>12)}}}else fe=qc,v=at,y=Mc,$=$n;for(R=0;R<a;++R)if(r[R]>255){ge=r[R]>>>18&31,It(e,u,fe[ge+257]),u+=v[ge+257],ge>7&&(je(e,u,r[R]>>>23&31),u+=Wr[ge]);var lt=31&r[R];It(e,u,y[lt]),u+=$[lt],lt>3&&(It(e,u,r[R]>>>5&8191),u+=Gr[lt])}else It(e,u,fe[r[R]]),u+=v[r[R]];return It(e,u,fe[256]),u+v[256]},Bc=new xt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Hc=new ye(0),zc=function(){for(var n=new xt(256),e=0;e<256;++e){for(var t=e,r=9;--r;)t=(1&t&&3988292384)^t>>>1;n[e]=t}return n}(),Vc=function(){var n=4294967295;return{p:function(e){for(var t=n,r=0;r<e.length;++r)t=zc[255&t^e[r]]^t>>>8;n=t},d:function(){return 4294967295^n}}},Jc=function(n,e,t,r,i){return function(s,o,a,l,c,u){var h=s.length,d=new ye(l+h+5*(1+Math.floor(h/7e3))+c),p=d.subarray(l,d.length-c),f=0;if(!o||h<8)for(var g=0;g<=h;g+=65535){var m=g+65535;m<h?f=yn(p,f,s.subarray(g,m)):(p[g]=u,f=yn(p,f,s.subarray(g,h)))}else{for(var b=Bc[o-1],E=b>>>13,T=8191&b,S=(1<<a)-1,O=new ce(32768),I=new ce(S+1),q=Math.ceil(a/3),R=2*q,Ee=function(qn){return(s[qn]^s[qn+1]<<q^s[qn+2]<<R)&S},ie=new xt(25e3),X=new ce(288),ue=new ce(32),fe=0,v=0,y=(g=0,0),$=0,V=0;g<h;++g){var B=Ee(g),A=32767&g,pe=I[B];if(O[A]=pe,I[B]=A,$<=g){var be=h-g;if((fe>7e3||y>24576)&&be>423){f=rs(s,p,0,ie,X,ue,v,y,V,g-V,f),y=fe=v=0,V=g;for(var Y=0;Y<286;++Y)X[Y]=0;for(Y=0;Y<30;++Y)ue[Y]=0}var we=2,ge=0,lt=T,Ne=A-pe&32767;if(be>2&&B==Ee(g-Ne))for(var _o=Math.min(E,be)-1,mo=Math.min(32767,g),yo=Math.min(258,be);Ne<=mo&&--lt&&A!=pe;){if(s[g+we]==s[g+we-Ne]){for(var qe=0;qe<yo&&s[g+qe]==s[g+qe-Ne];++qe);if(qe>we){if(we=qe,ge=Ne,qe>_o)break;var bo=Math.min(Ne,qe-2),Xr=0;for(Y=0;Y<bo;++Y){var Nn=g-Ne+Y+32768&32767,Zr=Nn-O[Nn]+32768&32767;Zr>Xr&&(Xr=Zr,pe=Nn)}}}Ne+=(A=pe)-(pe=O[A])+32768&32767}if(ge){ie[y++]=268435456|xr[we]<<18|ts[ge];var ei=31&xr[we],ti=31&ts[ge];v+=Wr[ei]+Gr[ti],++X[257+ei],++ue[ti],$=g+we,++fe}else ie[y++]=s[g],++X[s[g]]}}f=rs(s,p,u,ie,X,ue,v,y,V,g-V,f),u||(f=yn(p,f,Hc))}return po(d,0,l+fo(f)+c)}(n,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(n.length)))):12+e.mem,t,r,!i)},Rr=function(n,e,t){for(;t;++e)n[e]=t,t>>>=8},Wc=function(n,e){var t=e.filename;if(n[0]=31,n[1]=139,n[2]=8,n[8]=e.level<2?4:e.level==9?2:0,n[9]=3,e.mtime!=0&&Rr(n,4,Math.floor(new Date(e.mtime||Date.now())/1e3)),t){n[3]=8;for(var r=0;r<=t.length;++r)n[r+10]=t.charCodeAt(r)}},Gc=function(n){return 10+(n.filename&&n.filename.length+1||0)};function Kc(n,e){e===void 0&&(e={});var t=Vc(),r=n.length;t.p(n);var i=Jc(n,e,Gc(e),8),s=i.length;return Wc(i,e),Rr(i,s-8,t.d()),Rr(i,s-4,r),i}function Qc(n,e){var t=n.length;if(!e&&typeof TextEncoder<"u")return new TextEncoder().encode(n);for(var r=new ye(n.length+(n.length>>>1)),i=0,s=function(c){r[i++]=c},o=0;o<t;++o){if(i+5>r.length){var a=new ye(i+8+(t-o<<1));a.set(r),r=a}var l=n.charCodeAt(o);l<128||e?s(l):l<2048?(s(192|l>>>6),s(128|63&l)):l>55295&&l<57344?(s(240|(l=65536+(1047552&l)|1023&n.charCodeAt(++o))>>>18),s(128|l>>>12&63),s(128|l>>>6&63),s(128|63&l)):(s(224|l>>>12),s(128|l>>>6&63),s(128|63&l))}return po(r,0,i)}(function(n){n.GZipJS="gzip-js",n.Base64="base64"})(et||(et={}));var Kr=function(n,e,t){var r=e||{};r.ip=t.ip?1:0,r._=new Date().getTime().toString(),r.ver=st.LIB_VERSION;var i=n.split("?");if(i.length>1){var s,o=Re(i[1].split("&"));try{for(o.s();!(s=o.n()).done;){var a=s.value.split("=")[0];j(r[a])||delete r[a]}}catch(c){o.e(c)}finally{o.f()}}var l=n.indexOf("?")>-1?"&":"?";return n+l+cc(r)},Dn=function n(e,t){if(t.blob&&e.buffer)return new Blob([Pi(e)?e:e.buffer],{type:"text/plain"});if(t.sendBeacon||t.blob){var r=n(e,{method:"POST"});return new Blob([r],{type:"application/x-www-form-urlencoded"})}return t.method!=="POST"?null:(i=Q(e)||Pi(e)?"data="+encodeURIComponent(e):"data="+encodeURIComponent(e.data),"compression"in e&&e.compression&&(i+="&compression="+e.compression),i);var i},go=function(n){if(fr&&n.options.transport==="fetch"){var e,t=Dn(n.data,n.options),r=new Headers;M(r,function(s,o){r.append(o,s)}),n.options.method!=="POST"||n.options.blob||r.append("Content-Type","application/x-www-form-urlencoded");var i=n.url;return Pe(n.retriesPerformedSoFar)&&n.retriesPerformedSoFar>0&&(i=Kr(i,{retry_count:n.retriesPerformedSoFar},{})),void fr(i,{method:((e=n.options)===null||e===void 0?void 0:e.method)||"GET",headers:r,keepalive:n.options.method==="POST",body:t}).then(function(s){var o=s.status;return s.text().then(function(a){var l,c;if((l=n.onResponse)===null||l===void 0||l.call(n,{statusCode:o,responseText:a}),o!==200)me(n.onError)&&n.onError({statusCode:o,responseText:a}),(o<400||o>500)&&n.retryQueue.enqueue(P(P({},n),{},{headers:r,retriesPerformedSoFar:(n.retriesPerformedSoFar||0)+1})),(c=n.callback)===null||c===void 0||c.call(n,{status:0});else try{var u;(u=n.callback)===null||u===void 0||u.call(n,JSON.parse(a))}catch(h){w.error(h)}})}).catch(function(s){var o;w.error(s),(o=n.callback)===null||o===void 0||o.call(n,{status:0})})}return Yc(n)},Yc=function(n){var e=n.url,t=n.data,r=n.headers,i=n.options,s=n.callback,o=n.retriesPerformedSoFar,a=n.retryQueue,l=n.onError,c=n.timeout,u=c===void 0?6e4:c,h=n.onResponse;Pe(o)&&o>0&&(e=Kr(e,{retry_count:o},{}));var d=new XMLHttpRequest;d.open(i.method||"GET",e,!0);var p=Dn(t,i);M(r,function(f,g){d.setRequestHeader(g,f)}),i.method!=="POST"||i.blob||d.setRequestHeader("Content-Type","application/x-www-form-urlencoded"),d.timeout=u,d.withCredentials=!0,d.onreadystatechange=function(){if(d.readyState===4){var f={statusCode:d.status,responseText:d.responseText};if(h==null||h(f),d.status===200){if(s){var g;try{g=JSON.parse(d.responseText)}catch(m){return void w.error(m)}s(g)}}else me(l)&&l(f),(d.status<400||d.status>500)&&a.enqueue({url:e,data:t,options:i,headers:r,retriesPerformedSoFar:(o||0)+1,callback:s}),s==null||s({status:0})}},d.send(p)},_t,Xc=function(n){$s(t,co);var e=Is(t);function t(r,i){var s;return J(this,t),(s=e.call(this)).isPolling=!1,s.queue=[],s.areWeOnline=!0,s.onRequestError=r,s.rateLimiter=i,!j(_)&&"onLine"in _.navigator&&(s.areWeOnline=_.navigator.onLine,_.addEventListener("online",function(){s._handleWeAreNowOnline()}),_.addEventListener("offline",function(){s.areWeOnline=!1})),s}return W(t,[{key:"enqueue",value:function(r){var i=r.retriesPerformedSoFar||0;if(!(i>=10)){var s=function(l){var c=3e3*Math.pow(2,l),u=c/2,h=Math.min(18e5,c),d=(Math.random()-.5)*(h-u);return Math.ceil(h+d)}(i),o=new Date(Date.now()+s);this.queue.push({retryAt:o,requestData:r});var a="Enqueued failed request for retry in ".concat(s);navigator.onLine||(a+=" (Browser is offline)"),w.warn(a),this.isPolling||(this.isPolling=!0,this.poll())}}},{key:"poll",value:function(){var r=this;this._poller&&clearTimeout(this._poller),this._poller=setTimeout(function(){r.areWeOnline&&r.queue.length>0&&r.flush(),r.poll()},this._pollInterval)}},{key:"flush",value:function(){var r=new Date(Date.now()),i=this.queue.filter(function(l){return l.retryAt<r});if(i.length>0){this.queue=this.queue.filter(function(l){return l.retryAt>=r});var s,o=Re(i);try{for(o.s();!(s=o.n()).done;){var a=s.value.requestData;this._executeXhrRequest(a)}}catch(l){o.e(l)}finally{o.f()}}}},{key:"unload",value:function(){this._poller&&(clearTimeout(this._poller),this._poller=void 0);var r,i=Re(this.queue);try{for(i.s();!(r=i.n()).done;){var s=r.value.requestData,o=s.url,a=s.data,l=s.options;if(this.rateLimiter.isRateLimited(l._batchKey))w.warn("[RetryQueue] is quota limited. Dropping request.");else try{_==null||_.navigator.sendBeacon(o,Dn(a,P(P({},l),{},{sendBeacon:!0})))}catch(c){w.error(c)}}}catch(c){i.e(c)}finally{i.f()}this.queue=[]}},{key:"_executeXhrRequest",value:function(r){var i=r.url,s=r.data,o=r.options,a=r.headers,l=r.callback,c=r.retriesPerformedSoFar;this.rateLimiter.isRateLimited(o._batchKey)||go({url:i,data:s||{},options:o||{},headers:a||{},retriesPerformedSoFar:c||0,callback:l,retryQueue:this,onError:this.onRequestError,onResponse:this.rateLimiter.checkForLimiting})}},{key:"_handleWeAreNowOnline",value:function(){this.areWeOnline=!0,this.flush()}}]),t}(),un=1800,Zc=function(){function n(e,t,r,i){J(this,n),k(this,"_sessionIdChangedHandlers",[]),this.config=e,this.persistence=t,this._windowId=void 0,this._sessionId=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this._sessionIdGenerator=r||tt,this._windowIdGenerator=i||tt;var s=e.persistence_name||e.token,o=e.session_idle_timeout_seconds||un;if(Pe(o)?o>un?w.warn("session_idle_timeout_seconds cannot be greater than 30 minutes. Using 30 minutes instead."):o<60&&w.warn("session_idle_timeout_seconds cannot be less than 60 seconds. Using 60 seconds instead."):(w.warn("session_idle_timeout_seconds must be a number. Defaulting to 30 minutes."),o=un),this._sessionTimeoutMs=1e3*Math.min(Math.max(o,60),un),this._window_id_storage_key="ph_"+s+"_window_id",this._primary_window_exists_storage_key="ph_"+s+"_primary_window_exists",this._canUseSessionStorage()){var a=re.parse(this._window_id_storage_key),l=re.parse(this._primary_window_exists_storage_key);a&&!l?this._windowId=a:re.remove(this._window_id_storage_key),re.set(this._primary_window_exists_storage_key,!0)}this._listenToReloadWindow()}return W(n,[{key:"onSessionId",value:function(e){var t=this;return j(this._sessionIdChangedHandlers)&&(this._sessionIdChangedHandlers=[]),this._sessionIdChangedHandlers.push(e),this._sessionId&&e(this._sessionId,this._windowId),function(){t._sessionIdChangedHandlers=t._sessionIdChangedHandlers.filter(function(r){return r!==e})}}},{key:"_canUseSessionStorage",value:function(){return this.config.persistence!=="memory"&&!this.persistence.disabled&&re.is_supported()}},{key:"_setWindowId",value:function(e){e!==this._windowId&&(this._windowId=e,this._canUseSessionStorage()&&re.set(this._window_id_storage_key,e))}},{key:"_getWindowId",value:function(){return this._windowId?this._windowId:this._canUseSessionStorage()?re.parse(this._window_id_storage_key):null}},{key:"_setSessionId",value:function(e,t,r){e===this._sessionId&&t===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=t,this._sessionId=e,this.persistence.register(k({},En,[t,e,r])))}},{key:"_getSessionId",value:function(){if(this._sessionId&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this._sessionId,this._sessionStartTimestamp];var e=this.persistence.props[En];return Q(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}},{key:"resetSessionId",value:function(){this._setSessionId(null,null,null)}},{key:"_listenToReloadWindow",value:function(){var e=this;_==null||_.addEventListener("beforeunload",function(){e._canUseSessionStorage()&&re.remove(e._primary_window_exists_storage_key)})}},{key:"checkAndGetSessionAndWindowId",value:function(){var e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=(arguments.length>1&&arguments[1]!==void 0?arguments[1]:null)||new Date().getTime(),r=de(this._getSessionId(),3),i=r[0],s=r[1],o=r[2],a=this._getWindowId(),l=o&&o>0&&Math.abs(t-o)>864e5,c=!1,u=!s,h=!e&&Math.abs(t-i)>this._sessionTimeoutMs;u||h||l?(s=this._sessionIdGenerator(),a=this._windowIdGenerator(),w.info("[SessionId] new session ID generated",{sessionId:s,windowId:a,changeReason:{noSessionId:u,activityTimeout:h,sessionPastMaximumLength:l}}),o=t,c=!0):a||(a=this._windowIdGenerator(),c=!0);var d=i===0||!e||l?t:i,p=o===0?new Date().getTime():o;return this._setWindowId(a),this._setSessionId(s,d,p),c&&this._sessionIdChangedHandlers.forEach(function(f){return f(s,a)}),{sessionId:s,windowId:a,sessionStartTimestamp:p}}}]),n}();(function(n){n.US="us",n.EU="eu",n.CUSTOM="custom"})(_t||(_t={}));var eu=function(){function n(e){J(this,n),this.instance=e}return W(n,[{key:"apiHost",get:function(){return this.instance.config.api_host.trim().replace(/\/$/,"")}},{key:"uiHost",get:function(){var e;return(e=this.instance.config.ui_host)===null||e===void 0?void 0:e.replace(/\/$/,"")}},{key:"region",get:function(){switch(this.apiHost){case"https://app.posthog.com":case"https://us.posthog.com":return _t.US;case"https://eu.posthog.com":return _t.EU;default:return _t.CUSTOM}}},{key:"endpointFor",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"";if(t&&(t=t[0]==="/"?t:"/".concat(t)),e==="ui")return(this.uiHost||this.apiHost)+t;if(this.region===_t.CUSTOM)return this.apiHost+t;var r="i.posthog.com"+t;switch(e){case"assets":return"https://".concat(this.region,"-assets.").concat(r);case"api":return"https://".concat(this.region,".").concat(r)}}}]),n}(),tu=W(function n(e,t,r,i){J(this,n),this.name="posthog-js",this.setupOnce=function(s){s(function(o){var a,l,c,u,h;if(o.level!=="error"||!e.__loaded)return o;o.tags||(o.tags={});var d=e.requestRouter.endpointFor("ui","/person/"+e.get_distinct_id());o.tags["PostHog Person URL"]=d,e.sessionRecordingStarted()&&(o.tags["PostHog Recording URL"]=e.get_session_replay_url({withTimestamp:!0}));var p=((a=o.exception)===null||a===void 0?void 0:a.values)||[],f={$exception_message:(l=p[0])===null||l===void 0?void 0:l.value,$exception_type:(c=p[0])===null||c===void 0?void 0:c.type,$exception_personURL:d,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:(u=p[0])===null||u===void 0?void 0:u.value,$sentry_exception_type:(h=p[0])===null||h===void 0?void 0:h.type,$sentry_tags:o.tags};return t&&r&&(f.$sentry_url=(i||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),e.capture("$exception",f),o})}}),nu=function(){function n(e){var t=this;J(this,n),k(this,"_hasSeenPageView",!1),k(this,"_updateScrollData",function(){var r,i,s,o;t._pageViewData||(t._pageViewData=t._createPageViewData());var a=t._pageViewData,l=t._scrollY(),c=t._scrollHeight(),u=t._contentY(),h=t._contentHeight();a.lastScrollY=l,a.maxScrollY=Math.max(l,(r=a.maxScrollY)!==null&&r!==void 0?r:0),a.maxScrollHeight=Math.max(c,(i=a.maxScrollHeight)!==null&&i!==void 0?i:0),a.lastContentY=u,a.maxContentY=Math.max(u,(s=a.maxContentY)!==null&&s!==void 0?s:0),a.maxContentHeight=Math.max(h,(o=a.maxContentHeight)!==null&&o!==void 0?o:0)}),this._instance=e}return W(n,[{key:"_createPageViewData",value:function(){var e;return{pathname:(e=_==null?void 0:_.location.pathname)!==null&&e!==void 0?e:""}}},{key:"doPageView",value:function(){var e,t;return this._hasSeenPageView?(t=this._pageViewData,this._pageViewData=this._createPageViewData()):(this._hasSeenPageView=!0,t=void 0,this._pageViewData||(this._pageViewData=this._createPageViewData())),setTimeout(this._updateScrollData,0),P({$prev_pageview_pathname:(e=t)===null||e===void 0?void 0:e.pathname},this._calculatePrevPageScrollProperties(t))}},{key:"doPageLeave",value:function(){var e=this._pageViewData;return P({$prev_pageview_pathname:e==null?void 0:e.pathname},this._calculatePrevPageScrollProperties(e))}},{key:"_calculatePrevPageScrollProperties",value:function(e){if(!e||e.maxScrollHeight==null||e.lastScrollY==null||e.maxScrollY==null||e.maxContentHeight==null||e.lastContentY==null||e.maxContentY==null)return{};var t=e.maxScrollHeight,r=e.lastScrollY,i=e.maxScrollY,s=e.maxContentHeight,o=e.lastContentY,a=e.maxContentY;return t=Math.ceil(t),r=Math.ceil(r),i=Math.ceil(i),s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),{$prev_pageview_last_scroll:r,$prev_pageview_last_scroll_percentage:t<=1?1:hn(r/t,0,1),$prev_pageview_max_scroll:i,$prev_pageview_max_scroll_percentage:t<=1?1:hn(i/t,0,1),$prev_pageview_last_content:o,$prev_pageview_last_content_percentage:s<=1?1:hn(o/s,0,1),$prev_pageview_max_content:a,$prev_pageview_max_content_percentage:s<=1?1:hn(a/s,0,1)}}},{key:"startMeasuringScrollPosition",value:function(){_==null||_.addEventListener("scroll",this._updateScrollData,!0),_==null||_.addEventListener("scrollend",this._updateScrollData,!0),_==null||_.addEventListener("resize",this._updateScrollData)}},{key:"stopMeasuringScrollPosition",value:function(){_==null||_.removeEventListener("scroll",this._updateScrollData),_==null||_.removeEventListener("scrollend",this._updateScrollData),_==null||_.removeEventListener("resize",this._updateScrollData)}},{key:"_scrollElement",value:function(){if(!this._instance.config.scroll_root_selector)return _==null?void 0:_.document.documentElement;var e,t=Re(Q(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector]);try{for(t.s();!(e=t.n()).done;){var r=e.value,i=_==null?void 0:_.document.querySelector(r);if(i)return i}}catch(s){t.e(s)}finally{t.f()}}},{key:"_scrollHeight",value:function(){var e=this._scrollElement();return e?Math.max(0,e.scrollHeight-e.clientHeight):0}},{key:"_scrollY",value:function(){if(this._instance.config.scroll_root_selector){var e=this._scrollElement();return e&&e.scrollTop||0}return _&&(_.scrollY||_.pageYOffset||_.document.documentElement.scrollTop)||0}},{key:"_contentHeight",value:function(){var e=this._scrollElement();return(e==null?void 0:e.scrollHeight)||0}},{key:"_contentY",value:function(){var e=this._scrollElement(),t=(e==null?void 0:e.clientHeight)||0;return this._scrollY()+t}}]),n}();function hn(n,e,t){return Math.max(e,Math.min(n,t))}var Yt,Qr,ne,ru={icontains:function(n){return!!_&&_.location.href.toLowerCase().indexOf(n.toLowerCase())>-1},regex:function(n){return!!_&&lc(_.location.href,n)},exact:function(n){return(_==null?void 0:_.location.href)===n}},iu=function(){function n(e){J(this,n),this.instance=e}return W(n,[{key:"getSurveys",value:function(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0&&arguments[1],i=this.instance.get_property(mr);if(i&&!r)return e(i);this.instance._send_request(this.instance.requestRouter.endpointFor("api","/api/surveys/?token=".concat(this.instance.config.token)),{},{method:"GET"},function(s){var o,a=s.surveys||[];return(o=t.instance.persistence)===null||o===void 0||o.register(k({},mr,a)),e(a)})}},{key:"getActiveMatchingSurveys",value:function(e){var t=this,r=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.getSurveys(function(i){var s=i.filter(function(o){return!(!o.start_date||o.end_date)}).filter(function(o){var a,l,c,u;if(!o.conditions)return!0;var h=(a=o.conditions)===null||a===void 0||!a.url||ru[(l=(c=o.conditions)===null||c===void 0?void 0:c.urlMatchType)!==null&&l!==void 0?l:"icontains"](o.conditions.url),d=(u=o.conditions)===null||u===void 0||!u.selector||(x==null?void 0:x.querySelector(o.conditions.selector));return h&&d}).filter(function(o){if(!o.linked_flag_key&&!o.targeting_flag_key)return!0;var a=!o.linked_flag_key||t.instance.featureFlags.isFeatureEnabled(o.linked_flag_key),l=!o.targeting_flag_key||t.instance.featureFlags.isFeatureEnabled(o.targeting_flag_key);return a&&l});return e(s)},r)}}]),n}(),su=function(){function n(){var e=this;J(this,n),k(this,"limits",{}),k(this,"checkForLimiting",function(t){var r=t.responseText;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(function(i){w.info("[RateLimiter] ".concat(i||"events"," is quota limited.")),e.limits[i]=new Date().getTime()+6e4})}catch(i){return void w.warn('[RateLimiter] could not rate limit - continuing. Error: "'.concat(i==null?void 0:i.message,'"'),{text:r})}})}return W(n,[{key:"isRateLimited",value:function(e){var t=this.limits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}}]),n}(),ou=function(){return P({initialPathName:(He==null?void 0:He.pathname)||"",referringDomain:Z.referringDomain()},Z.campaignParams())},au=function(){function n(e,t,r){var i=this;J(this,n),k(this,"_onSessionIdCallback",function(s){var o=i._getStoredProps();if(!o||o.sessionId!==s){var a={sessionId:s,props:i._sessionSourceParamGenerator()};i._persistence.register(k({},wr,a))}}),this._sessionIdManager=e,this._persistence=t,this._sessionSourceParamGenerator=r||ou,this._sessionIdManager.onSessionId(this._onSessionIdCallback)}return W(n,[{key:"_getStoredProps",value:function(){return this._persistence.props[wr]}},{key:"getSessionProps",value:function(){var e,t=(e=this._getStoredProps())===null||e===void 0?void 0:e.props;return t?{$client_session_initial_referring_host:t.referringDomain,$client_session_initial_pathname:t.initialPathName,$client_session_initial_utm_source:t.utm_source,$client_session_initial_utm_campaign:t.utm_campaign,$client_session_initial_utm_medium:t.utm_medium,$client_session_initial_utm_content:t.utm_content,$client_session_initial_utm_term:t.utm_term}:{}}}]),n}(),lu=["ahrefsbot","ahrefssiteaudit","applebot","baiduspider","bingbot","bingpreview","bot.htm","bot.php","crawler","duckduckbot","facebookexternal","facebookcatalog","gptbot","http://yandex.com/bots","hubspot","ia_archiver","linkedinbot","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","semrushbot","sitebulb","slurp","turnitin","twitterbot","vercelbot","yahoo! slurp","yandexbot","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleweblight","mediapartners-google","storebot-google"],is=function(n,e){if(!n)return!1;var t=n.toLowerCase();return lu.concat(e||[]).some(function(r){var i=r.toLowerCase();return t.includes?t.includes(i):t.indexOf(i)!==-1})};(function(n){n[n.INIT_MODULE=0]="INIT_MODULE",n[n.INIT_SNIPPET=1]="INIT_SNIPPET"})(Yt||(Yt={}));var Or=function(){},dn={},he="posthog",vo=!_n&&(G==null?void 0:G.indexOf("MSIE"))===-1&&(G==null?void 0:G.indexOf("Mozilla"))===-1,ss=function(){var n,e,t;return{api_host:"https://app.posthog.com",api_method:"POST",api_transport:"XHR",ui_host:null,token:"",autocapture:!0,rageclick:!0,cross_subdomain_cookie:(e=x==null?void 0:x.location,t=e==null?void 0:e.hostname,!!le(t)&&t.split(".").slice(-2).join(".")!=="herokuapp.com"),persistence:"localStorage+cookie",persistence_name:"",cookie_name:"",loaded:Or,store_google:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageview:!0,capture_pageleave:!0,debug:!1,verbose:!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_cookie:!1,enable_recording_console_log:void 0,secure_cookie:(_==null||(n=_.location)===null||n===void 0?void 0:n.protocol)==="https:",ip:!0,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_blacklist:[],property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},inapp_protocol:"//",inapp_link_new_window:!1,request_batching:!0,properties_string_max_length:65535,session_recording:{},mask_all_element_attributes:!1,mask_all_text:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_disable_toolbar_metrics:!1,on_request_error:function(r){var i="Bad HTTP status: "+r.statusCode+" "+r.responseText;w.error(i)},get_device_id:function(r){return r},_onCapture:Or,capture_performance:void 0,name:"posthog",callback_fn:"posthog._jsc",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800}},$r=function(n,e,t,r){var i,s=t!==he&&ne?t?ne[t]:void 0:ne,o={initComplete:!1,syncCode:!1},a=function(l){return function(c){o[l]||(o[l]=!0,o.initComplete&&o.syncCode&&(r==null||r(c)))}};if(s&&Qr===Yt.INIT_MODULE)i=s;else{if(s&&!Q(s))return void w.error("You have already initialized "+t);i=new Yr}return i._init(n,e,t,a("initComplete")),i.toolbar.maybeLoadToolbar(),i.sessionRecording=new Cc(i),i.sessionRecording.startRecordingIfEnabled(),i.config.disable_scroll_properties||i.pageViewManager.startMeasuringScrollPosition(),i.__autocapture=i.config.autocapture,Je._setIsAutocaptureEnabled(i),Je._isAutocaptureEnabled&&(i.__autocapture=i.config.autocapture,Je.enabledForProject(i.config.token,100,100)?Je.isBrowserSupported()?Je.init(i):(i.__autocapture=!1,w.info("Disabling Automatic Event Collection because this browser is not supported")):(i.__autocapture=!1,w.info("Not in active bucket: disabling Automatic Event Collection."))),st.DEBUG=st.DEBUG||i.config.debug,!j(s)&&Q(s)&&(i._execute_array.call(i.people,s.people),i._execute_array(s)),a("syncCode")(i),i},cu=function(){function n(){J(this,n),k(this,"__forceAllowLocalhost",!1)}return W(n,[{key:"_forceAllowLocalhost",get:function(){return this.__forceAllowLocalhost},set:function(e){w.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}]),n}(),Yr=function(){function n(){var e=this;J(this,n),k(this,"webPerformance",new cu),this.config=ss(),this.compression={},this.decideEndpointWasHit=!1,this.SentryIntegration=tu,this.segmentIntegration=function(){return function(t){Promise&&Promise.resolve||w.warn("This browser does not have Promise support, and can not use the segment integration");var r=function(i,s){i.event.userId||i.event.anonymousId===t.get_distinct_id()||t.reset(),i.event.userId&&i.event.userId!==t.get_distinct_id()&&(t.register({distinct_id:i.event.userId}),t.reloadFeatureFlags());var o=t._calculate_event_properties(s,i.event.properties);return i.event.properties=Object.assign({},o,i.event.properties),i};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:function(){return!0},load:function(){return Promise.resolve()},track:function(i){return r(i,i.event.event)},page:function(i){return r(i,"$pageview")},identify:function(i){return r(i,"$identify")},screen:function(i){return r(i,"$screen")}}}(e)},this.__captureHooks=[],this.__request_queue=[],this.__loaded=!1,this.__loaded_recorder_version=void 0,this.__autocapture=void 0,this._jsc=function(){},this.analyticsDefaultEndpoint="/e/",this.elementsChainAsString=!1,this.featureFlags=new Yl(this),this.toolbar=new Lc(this),this.pageViewManager=new nu(this),this.surveys=new iu(this),this.rateLimiter=new su,this.requestRouter=new eu(this),this.people={set:function(t,r,i){var s=le(t)?k({},t,r):t;e.setPersonProperties(s),i==null||i({})},set_once:function(t,r,i){var s=le(t)?k({},t,r):t;e.setPersonProperties(void 0,s),i==null||i({})}}}return W(n,[{key:"init",value:function(e,t,r){if(j(r))w.critical("You must name your new library: init(token, config, name)");else if(j(e)||function(s){return le(s)&&s.trim().length===0}(e))w.critical("You must provide a token to initialize posthog");else{if(r!==he){var i=$r(e,t,r,function(s){ne[r]=s,s._loaded()});return ne[r]=i,i}w.critical("You must initialize the main posthog object right after you include the PostHog js snippet")}}},{key:"_init",value:function(e){var t,r,i,s=this,o=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=arguments.length>2?arguments[2]:void 0,l=arguments.length>3?arguments[3]:void 0;this.__loaded=!0,this.config={},this._triggered_notifs=[];var c,u={segmentRegister:!1,syncCode:!1},h=function(O){return function(){u[O]||(u[O]=!0,u.segmentRegister&&u.syncCode&&(l==null||l(s)))}};if(o.request_headers=o.request_headers||o.xhr_headers,this.set_config(te({},ss(),o,{name:a,token:e,callback_fn:(a===he?a:he+"."+a)+"._jsc"})),this._jsc=function(){},(_!=null&&(t=_.rrweb)!==null&&t!==void 0&&t.record||_!=null&&_.rrwebRecord)&&(this.__loaded_recorder_version=_==null||(c=_.rrweb)===null||c===void 0?void 0:c.version),this.persistence=new Xn(this.config),this.sessionPersistence=this.config.persistence==="sessionStorage"?this.persistence:new Xn(P(P({},this.config),{},{persistence:"sessionStorage"})),this._requestQueue=new Dc(this._handle_queued_event.bind(this)),this._retryQueue=new Xc(this.config.on_request_error,this.rateLimiter),this.__captureHooks=[],this.__request_queue=[],this.sessionManager=new Zc(this.config,this.persistence),this.sessionPropsManager=new au(this.sessionManager,this.persistence),this._gdpr_init(),o.segment?(this.config.get_device_id=function(){return o.segment.user().anonymousId()},o.segment.user().id()&&(this.register({distinct_id:o.segment.user().id()}),this.persistence.set_user_state("identified")),o.segment.register(this.segmentIntegration()).then(h("segmentRegister"))):h("segmentRegister")(),((r=o.bootstrap)===null||r===void 0?void 0:r.distinctID)!==void 0){var d,p,f=this.config.get_device_id(tt()),g=(d=o.bootstrap)!==null&&d!==void 0&&d.isIdentifiedID?f:o.bootstrap.distinctID;this.persistence.set_user_state((p=o.bootstrap)!==null&&p!==void 0&&p.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:o.bootstrap.distinctID,$device_id:g})}if(this._hasBootstrappedFeatureFlags()){var m,b,E=Object.keys(((m=o.bootstrap)===null||m===void 0?void 0:m.featureFlags)||{}).filter(function(O){var I,q;return!((I=o.bootstrap)===null||I===void 0||(q=I.featureFlags)===null||q===void 0||!q[O])}).reduce(function(O,I){var q,R;return O[I]=((q=o.bootstrap)===null||q===void 0||(R=q.featureFlags)===null||R===void 0?void 0:R[I])||!1,O},{}),T=Object.keys(((b=o.bootstrap)===null||b===void 0?void 0:b.featureFlagPayloads)||{}).filter(function(O){return E[O]}).reduce(function(O,I){var q,R,Ee,ie;return(q=o.bootstrap)!==null&&q!==void 0&&(R=q.featureFlagPayloads)!==null&&R!==void 0&&R[I]&&(O[I]=(Ee=o.bootstrap)===null||Ee===void 0||(ie=Ee.featureFlagPayloads)===null||ie===void 0?void 0:ie[I]),O},{});this.featureFlags.receivedFeatureFlags({featureFlags:E,featureFlagPayloads:T})}if(!this.get_distinct_id()){var S=this.config.get_device_id(tt());this.register_once({distinct_id:S,$device_id:S},""),this.persistence.set_user_state("anonymous")}_==null||(i=_.addEventListener)===null||i===void 0||i.call(_,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this)),h("syncCode")()}},{key:"_afterDecideResponse",value:function(e){var t;if(this.compression={},e.supportedCompression&&!this.config.disable_compression){var r,i={},s=Re(e.supportedCompression);try{for(s.s();!(r=s.n()).done;)i[r.value]=!0}catch(o){s.e(o)}finally{s.f()}this.compression=i}(t=e.analytics)!==null&&t!==void 0&&t.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),e.elementsChainAsString&&(this.elementsChainAsString=e.elementsChainAsString)}},{key:"_loaded",value:function(){var e=this.config.advanced_disable_decide;e||this.featureFlags.setReloadingPaused(!0);try{this.config.loaded(this)}catch(t){w.critical("`loaded` function failed",t)}this._start_queue_if_opted_in(),this.config.capture_pageview&&x&&this.capture("$pageview",{title:x.title},{send_instantly:!0}),e||(new Ac(this).call(),this.featureFlags.resetRequestQueue())}},{key:"_start_queue_if_opted_in",value:function(){var e;this.has_opted_out_capturing()||this.config.request_batching&&((e=this._requestQueue)===null||e===void 0||e.poll())}},{key:"_dom_loaded",value:function(){var e=this;this.has_opted_out_capturing()||wt(this.__request_queue,function(t){e._send_request.apply(e,yt(t))}),this.__request_queue=[],this._start_queue_if_opted_in()}},{key:"_prepare_callback",value:function(e,t){if(j(e))return null;if(_n)return function(o){e(o,t)};var r=this._jsc,i=""+Math.floor(1e8*Math.random()),s=this.config.callback_fn+"["+i+"]";return r[i]=function(o){delete r[i],e(o,t)},s}},{key:"_handle_unload",value:function(){var e,t;this.config.request_batching?(this.config.capture_pageview&&this.config.capture_pageleave&&this.capture("$pageleave"),(e=this._requestQueue)===null||e===void 0||e.unload(),(t=this._retryQueue)===null||t===void 0||t.unload()):this.config.capture_pageview&&this.config.capture_pageleave&&this.capture("$pageleave",null,{transport:"sendBeacon"})}},{key:"_handle_queued_event",value:function(e,t,r){var i=JSON.stringify(t);this.__compress_and_send_json_request(e,i,r||dn,Or)}},{key:"__compress_and_send_json_request",value:function(e,t,r,i){var s=function(c,u,h){return c===et.GZipJS?[Kc(Qc(u),{mtime:0}),P(P({},h),{},{blob:!0,urlQueryArgs:{compression:et.GZipJS}})]:[{data:qr(u)},h]}(this.compression[et.GZipJS]?et.GZipJS:et.Base64,t,r),o=de(s,2),a=o[0],l=o[1];this._send_request(e,a,l,i)}},{key:"_send_request",value:function(e,t,r,i){if(this.__loaded&&this._retryQueue&&!this.rateLimiter.isRateLimited(r._batchKey))if(vo)this.__request_queue.push([e,t,r,i]);else{var s={method:this.config.api_method,transport:this.config.api_transport,verbose:this.config.verbose};r=te(s,r||{}),_n||(r.method="GET");var o=_&&"sendBeacon"in _.navigator&&r.transport==="sendBeacon";if(e=Kr(e,r.urlQueryArgs||{},{ip:this.config.ip}),o)try{_==null||_.navigator.sendBeacon(e,Dn(t,P(P({},r),{},{sendBeacon:!0})))}catch{}else if(_n||!x)try{go({url:e,data:t,headers:this.config.request_headers,options:r,callback:i,retriesPerformedSoFar:0,retryQueue:this._retryQueue,onError:this.config.on_request_error,onResponse:this.rateLimiter.checkForLimiting})}catch(u){w.error(u)}else{var a,l=x.createElement("script");l.type="text/javascript",l.async=!0,l.defer=!0,l.src=e;var c=x.getElementsByTagName("script")[0];(a=c.parentNode)===null||a===void 0||a.insertBefore(l,c)}}}},{key:"_execute_array",value:function(e){var t,r=this,i=[],s=[],o=[];wt(e,function(l){l&&(t=l[0],Q(t)?o.push(l):me(l)?l.call(r):Q(l)&&t==="alias"?i.push(l):Q(l)&&t.indexOf("capture")!==-1&&me(r[t])?o.push(l):s.push(l))});var a=function(l,c){wt(l,function(u){if(Q(u[0])){var h=c;M(u,function(d){h=h[d[0]].apply(h,d.slice(1))})}else this[u[0]].apply(this,u.slice(1))},c)};a(i,this),a(s,this),a(o,this)}},{key:"_hasBootstrappedFeatureFlags",value:function(){var e,t;return((e=this.config.bootstrap)===null||e===void 0?void 0:e.featureFlags)&&Object.keys((t=this.config.bootstrap)===null||t===void 0?void 0:t.featureFlags).length>0||!1}},{key:"push",value:function(e){this._execute_array([e])}},{key:"capture",value:function(e,t){var r,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:dn;if(!this.__loaded||!this.sessionPersistence||!this._requestQueue)return w.uninitializedWarning("posthog.capture");if(!Er(this)){var s=(i=i||dn).transport;if(s&&(i.transport=s),!j(e)&&le(e)){if(!G||this.config.opt_out_useragent_filter||!is(G,this.config.custom_blocked_useragents)){this.sessionPersistence.update_search_keyword(),this.config.store_google&&this.sessionPersistence.update_campaign_params(),this.config.save_referrer&&this.sessionPersistence.update_referrer_info();var o={uuid:tt(),event:e,properties:this._calculate_event_properties(e,t||{})};e==="$identify"&&(o.$set=i.$set,o.$set_once=i.$set_once),(o=Hl(o,i._noTruncate?null:this.config.properties_string_max_length)).timestamp=i.timestamp||new Date,j(i.timestamp)||(o.properties.$event_time_override_provided=!0,o.properties.$event_time_override_system_time=new Date);var a=P(P({},o.properties.$set),o.$set);(function(h){if(Le(h)){for(var d in h)if(As.call(h,d))return!1;return!0}return!1})(a)||this.setPersonPropertiesForFlags(a),w.info("send",o);var l=JSON.stringify(o),c=(r=i._url)!==null&&r!==void 0?r:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),u=i!==dn;return!this.config.request_batching||u&&!i._batchKey||i.send_instantly?this.__compress_and_send_json_request(c,l,i):this._requestQueue.enqueue(c,o,i),this._invokeCaptureHooks(e,o),o}}else w.error("No event name provided to posthog.capture")}}},{key:"_addCaptureHook",value:function(e){this.__captureHooks.push(e)}},{key:"_invokeCaptureHooks",value:function(e,t){this.config._onCapture(e,t),M(this.__captureHooks,function(r){return r(e)})}},{key:"_calculate_event_properties",value:function(e,t){if(!this.persistence||!this.sessionPersistence)return t;var r=this.persistence.remove_event_timer(e),i=P({},t);if(i.token=this.config.token,e==="$snapshot"){var s=P(P({},this.persistence.properties()),this.sessionPersistence.properties());return i.distinct_id=s.distinct_id,i}var o=Z.properties();if(this.sessionManager){var a=this.sessionManager.checkAndGetSessionAndWindowId(),l=a.sessionId,c=a.windowId;i.$session_id=l,i.$window_id=c}if(this.sessionPropsManager&&this.config.__preview_send_client_session_params&&(e==="$pageview"||e==="$pageleave"||e==="$autocapture")){var u=this.sessionPropsManager.getSessionProps();i=te(i,u)}if(!this.config.disable_scroll_properties){var h={};e==="$pageview"?h=this.pageViewManager.doPageView():e==="$pageleave"&&(h=this.pageViewManager.doPageLeave()),i=te(i,h)}if(e==="$pageview"&&x&&(i.title=x.title),e==="$performance_event"){var d=this.persistence.properties();return i.distinct_id=d.distinct_id,i.$current_url=o.$current_url,i}if(!j(r)){var p=new Date().getTime()-r;i.$duration=parseFloat((p/1e3).toFixed(3))}G&&this.config.opt_out_useragent_filter&&(i.$browser_type=is(G,this.config.custom_blocked_useragents)?"bot":"browser"),i=te({},Z.properties(),this.persistence.properties(),this.sessionPersistence.properties(),i),Q(this.config.property_denylist)&&Q(this.config.property_blacklist)?M([].concat(yt(this.config.property_blacklist),yt(this.config.property_denylist)),function(g){delete i[g]}):w.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var f=this.config.sanitize_properties;return f&&(i=f(i,e)),i}},{key:"register",value:function(e,t){var r;(r=this.persistence)===null||r===void 0||r.register(e,t)}},{key:"register_once",value:function(e,t,r){var i;(i=this.persistence)===null||i===void 0||i.register_once(e,t,r)}},{key:"register_for_session",value:function(e){var t;(t=this.sessionPersistence)===null||t===void 0||t.register(e)}},{key:"unregister",value:function(e){var t;(t=this.persistence)===null||t===void 0||t.unregister(e)}},{key:"unregister_for_session",value:function(e){var t;(t=this.sessionPersistence)===null||t===void 0||t.unregister(e)}},{key:"_register_single",value:function(e,t){this.register(k({},e,t))}},{key:"getFeatureFlag",value:function(e,t){return this.featureFlags.getFeatureFlag(e,t)}},{key:"getFeatureFlagPayload",value:function(e){var t=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(t)}catch{return t}}},{key:"isFeatureEnabled",value:function(e,t){return this.featureFlags.isFeatureEnabled(e,t)}},{key:"reloadFeatureFlags",value:function(){this.featureFlags.reloadFeatureFlags()}},{key:"updateEarlyAccessFeatureEnrollment",value:function(e,t){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,t)}},{key:"getEarlyAccessFeatures",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return this.featureFlags.getEarlyAccessFeatures(e,t)}},{key:"onFeatureFlags",value:function(e){return this.featureFlags.onFeatureFlags(e)}},{key:"onSessionId",value:function(e){var t,r;return(t=(r=this.sessionManager)===null||r===void 0?void 0:r.onSessionId(e))!==null&&t!==void 0?t:function(){}}},{key:"getSurveys",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.surveys.getSurveys(e,t)}},{key:"getActiveMatchingSurveys",value:function(e){var t=arguments.length>1&&arguments[1]!==void 0&&arguments[1];this.surveys.getActiveMatchingSurveys(e,t)}},{key:"identify",value:function(e,t,r){if(!this.__loaded||!this.persistence)return w.uninitializedWarning("posthog.identify");if(Pe(e)&&(e=e.toString(),w.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))w.critical('The string "'.concat(e,'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'));else{var i=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var s=i;this.register_once({$had_persisted_distinct_id:!0,$device_id:s},"")}e!==i&&e!==this.get_property(gn)&&(this.unregister(gn),this.register({distinct_id:e}));var o=this.persistence.get_user_state()==="anonymous";e!==i&&o?(this.persistence.set_user_state("identified"),this.setPersonPropertiesForFlags(t||{},!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:i},{$set:t||{},$set_once:r||{}}),this.featureFlags.setAnonymousDistinctId(i)):(t||r)&&this.setPersonProperties(t,r),e!==i&&(this.reloadFeatureFlags(),this.unregister(xn))}else w.error("Unique user id has not been set in posthog.identify")}},{key:"setPersonProperties",value:function(e,t){(e||t)&&(this.setPersonPropertiesForFlags(e||{}),this.capture("$set",{$set:e||{},$set_once:t||{}}))}},{key:"group",value:function(e,t,r){if(e&&t){var i=this.getGroups();i[e]!==t&&this.resetGroupPropertiesForFlags(e),this.register({$groups:P(P({},i),{},k({},e,t))}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:t,$group_set:r}),this.setGroupPropertiesForFlags(k({},e,r))),i[e]===t||r||this.reloadFeatureFlags()}else w.error("posthog.group requires a group type and group key")}},{key:"resetGroups",value:function(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}},{key:"setPersonPropertiesForFlags",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];this.featureFlags.setPersonPropertiesForFlags(e,t)}},{key:"resetPersonPropertiesForFlags",value:function(){this.featureFlags.resetPersonPropertiesForFlags()}},{key:"setGroupPropertiesForFlags",value:function(e){var t=!(arguments.length>1&&arguments[1]!==void 0)||arguments[1];this.featureFlags.setGroupPropertiesForFlags(e,t)}},{key:"resetGroupPropertiesForFlags",value:function(e){this.featureFlags.resetGroupPropertiesForFlags(e)}},{key:"reset",value:function(e){var t,r,i,s;if(!this.__loaded)return w.uninitializedWarning("posthog.reset");var o=this.get_property("$device_id");(t=this.persistence)===null||t===void 0||t.clear(),(r=this.sessionPersistence)===null||r===void 0||r.clear(),(i=this.persistence)===null||i===void 0||i.set_user_state("anonymous"),(s=this.sessionManager)===null||s===void 0||s.resetSessionId();var a=this.config.get_device_id(tt());this.register_once({distinct_id:a,$device_id:e?a:o},"")}},{key:"get_distinct_id",value:function(){return this.get_property("distinct_id")}},{key:"getGroups",value:function(){return this.get_property("$groups")||{}}},{key:"get_session_id",value:function(){var e,t;return(e=(t=this.sessionManager)===null||t===void 0?void 0:t.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}},{key:"get_session_replay_url",value:function(e){if(!this.sessionManager)return"";var t=this.sessionManager.checkAndGetSessionAndWindowId(!0),r=t.sessionId,i=t.sessionStartTimestamp,s=this.requestRouter.endpointFor("ui","/replay/"+r);if(e!=null&&e.withTimestamp&&i){var o,a=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!i)return s;var l=Math.max(Math.floor((new Date().getTime()-i)/1e3)-a,0);s+="?t=".concat(l)}return s}},{key:"alias",value:function(e,t){return e===this.get_property(Us)?(w.critical("Attempting to create alias for existing People user - aborting."),-2):(j(t)&&(t=this.get_distinct_id()),e!==t?(this._register_single(gn,e),this.capture("$create_alias",{alias:e,distinct_id:t})):(w.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1))}},{key:"set_config",value:function(e){var t,r=P({},this.config);if(Le(e)&&(te(this.config,e),this.config.persistence_name||(this.config.persistence_name=this.config.cookie_name),this.config.disable_persistence||(this.config.disable_persistence=this.config.disable_cookie),(t=this.persistence)===null||t===void 0||t.update_config(this.config,r),this.sessionPersistence=this.config.persistence==="sessionStorage"?this.persistence:new Xn(P(P({},this.config),{},{persistence:"sessionStorage"})),K.is_supported()&&K.get("ph_debug")==="true"&&(this.config.debug=!0),this.config.debug&&(st.DEBUG=!0),this.sessionRecording&&!j(e.disable_session_recording))){var i=r.disable_session_recording!==e.disable_session_recording,s=!Er(this)&&!e.disable_session_recording&&!this.sessionRecording.started;(i||s)&&(e.disable_session_recording?this.sessionRecording.stopRecording():this.sessionRecording.startRecordingIfEnabled())}}},{key:"startSessionRecording",value:function(){this.set_config({disable_session_recording:!1})}},{key:"stopSessionRecording",value:function(){this.set_config({disable_session_recording:!0})}},{key:"sessionRecordingStarted",value:function(){var e;return!((e=this.sessionRecording)===null||e===void 0||!e.started)}},{key:"loadToolbar",value:function(e){return this.toolbar.loadToolbar(e)}},{key:"get_property",value:function(e){var t;return(t=this.persistence)===null||t===void 0?void 0:t.props[e]}},{key:"getSessionProperty",value:function(e){var t;return(t=this.sessionPersistence)===null||t===void 0?void 0:t.props[e]}},{key:"toString",value:function(){var e,t=(e=this.config.name)!==null&&e!==void 0?e:he;return t!==he&&(t=he+"."+t),t}},{key:"_gdpr_init",value:function(){this.config.opt_out_capturing_persistence_type==="localStorage"&&K.is_supported()&&(!this.has_opted_in_capturing()&&this.has_opted_in_capturing({persistence_type:"cookie"})&&this.opt_in_capturing({enable_persistence:!1}),!this.has_opted_out_capturing()&&this.has_opted_out_capturing({persistence_type:"cookie"})&&this.opt_out_capturing({clear_persistence:!1}),this.clear_opt_in_out_capturing({persistence_type:"cookie",enable_persistence:!1})),this.has_opted_out_capturing()?this._gdpr_update_persistence({clear_persistence:!0}):this.has_opted_in_capturing()||!this.config.opt_out_capturing_by_default&&!Ie.get("ph_optout")||(Ie.remove("ph_optout"),this.opt_out_capturing({clear_persistence:this.config.opt_out_persistence_by_default}))}},{key:"_gdpr_update_persistence",value:function(e){var t,r,i,s,o;if(e&&e.clear_persistence)i=!0;else{if(!e||!e.enable_persistence)return;i=!1}this.config.disable_persistence||((t=this.persistence)===null||t===void 0?void 0:t.disabled)===i||(s=this.persistence)===null||s===void 0||s.set_disabled(i),this.config.disable_persistence||((r=this.sessionPersistence)===null||r===void 0?void 0:r.disabled)===i||(o=this.sessionPersistence)===null||o===void 0||o.set_disabled(i)}},{key:"_gdpr_call_func",value:function(e,t){return t=te({capture:this.capture.bind(this),persistence_type:this.config.opt_out_capturing_persistence_type,cookie_prefix:this.config.opt_out_capturing_cookie_prefix,cookie_expiration:this.config.cookie_expiration,cross_subdomain_cookie:this.config.cross_subdomain_cookie,secure_cookie:this.config.secure_cookie},t||{}),K.is_supported()||t.persistence_type!=="localStorage"||(t.persistence_type="cookie"),e(this.config.token,{capture:t.capture,captureEventName:t.capture_event_name,captureProperties:t.capture_properties,persistenceType:t.persistence_type,persistencePrefix:t.cookie_prefix,cookieExpiration:t.cookie_expiration,crossSubdomainCookie:t.cross_subdomain_cookie,secureCookie:t.secure_cookie})}},{key:"opt_in_capturing",value:function(e){e=te({enable_persistence:!0},e||{}),this._gdpr_call_func(Pc,e),this._gdpr_update_persistence(e)}},{key:"opt_out_capturing",value:function(e){var t=te({clear_persistence:!0},e||{});this._gdpr_call_func(Rc,t),this._gdpr_update_persistence(t)}},{key:"has_opted_in_capturing",value:function(e){return this._gdpr_call_func(Oc,e)}},{key:"has_opted_out_capturing",value:function(e){return this._gdpr_call_func(so,e)}},{key:"clear_opt_in_out_capturing",value:function(e){var t=te({enable_persistence:!0},e??{});this._gdpr_call_func($c,t),this._gdpr_update_persistence(t)}},{key:"debug",value:function(e){e===!1?(_==null||_.console.log("You've disabled debug mode."),localStorage&&localStorage.removeItem("ph_debug"),this.set_config({debug:!1})):(_==null||_.console.log("You're now in debug mode. All calls to PostHog will be logged in your console.\nYou can disable this with `posthog.debug(false)`."),localStorage&&localStorage.setItem("ph_debug","true"),this.set_config({debug:!0}))}}]),n}();(function(n,e){for(var t=0;t<e.length;t++)n.prototype[e[t]]=Ls(n.prototype[e[t]])})(Yr,["identify"]);var os,as,Ue={},uu=function(){ne.init=function(n,e,t){if(t)return ne[t]||(ne[t]=Ue[t]=$r(n||"",e||{},t,function(i){ne[t]=Ue[t]=i,i._loaded()})),ne[t];var r=ne;return Ue[he]?r=Ue[he]:n&&(r=$r(n,e||{},he,function(i){Ue[he]=i,i._loaded()}),Ue[he]=r),ne=r,Qr===Yt.INIT_SNIPPET&&(oe[he]=ne),M(Ue,function(i,s){s!==he&&(ne[s]=i)}),r}};(function(n){n.Popover="popover",n.API="api",n.Widget="widget"})(os||(os={})),function(n){n.Open="open",n.MultipleChoice="multiple_choice",n.SingleChoice="single_choice",n.Rating="rating",n.Link="link"}(as||(as={}));var hu=(Qr=Yt.INIT_MODULE,ne=new Yr,uu(),ne.init(),function(){function n(){n.done||(n.done=!0,vo=!1,M(Ue,function(e){e._dom_loaded()}))}x!=null&&x.addEventListener&&(x.readyState==="complete"?n():x.addEventListener("DOMContentLoaded",n,!1)),_&&Ut(_,"load",n,!0)}(),ne);function ls(n,e,t){const r=n.slice();return r[11]=e[t],r}function cs(n,e,t){const r=n.slice();return r[14]=e[t],r}function us(n,e,t){const r=n.slice();return r[17]=e[t],r}function du(n){let e;return{c(){e=H("div"),e.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-refresh-cw spinner svelte-vt3xxd"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>',N(e,"class","date svelte-vt3xxd")},m(t,r){Ge(t,e,r)},p:rt,d(t){t&&De(e)}}}function fu(n){let e,t,r,i,s=n[1].toLocaleTimeString("en-us")+"",o,a,l,c,u,h,d,p,f,g,m,b;return{c(){e=H("div"),t=H("div"),r=H("span"),r.textContent="last refreshed:",i=Se(),o=We(s),a=Se(),l=H("div"),c=Zt("svg"),u=Zt("polyline"),h=Zt("polyline"),d=Zt("path"),f=Se(),g=H("span"),g.textContent="refresh",N(u,"points","23 4 23 10 17 10"),N(h,"points","1 20 1 14 7 14"),N(d,"d","M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"),N(c,"xmlns","http://www.w3.org/2000/svg"),N(c,"width","24"),N(c,"height","24"),N(c,"viewBox","0 0 24 24"),N(c,"fill","none"),N(c,"stroke","currentColor"),N(c,"stroke-width","2"),N(c,"stroke-linecap","round"),N(c,"stroke-linejoin","round"),N(c,"class",p=ii("feather feather-refresh-cw"+(n[0]?" spinner":""))+" svelte-vt3xxd"),N(l,"class","manual-refresh svelte-vt3xxd"),N(l,"role","button"),N(e,"class","date refresh-row svelte-vt3xxd")},m(E,T){Ge(E,e,T),C(e,t),C(t,r),C(t,i),C(t,o),C(e,a),C(e,l),C(l,c),C(c,u),C(c,h),C(c,d),C(l,f),C(l,g),m||(b=xo(l,"click",n[5]),m=!0)},p(E,T){T&2&&s!==(s=E[1].toLocaleTimeString("en-us")+"")&&it(o,s),T&1&&p!==(p=ii("feather feather-refresh-cw"+(E[0]?" spinner":""))+" svelte-vt3xxd")&&N(c,"class",p)},d(E){E&&De(e),m=!1,b()}}}function hs(n){let e;return{c(){e=H("div"),N(e,"class","line-circle svelte-vt3xxd"),si(e,"background-color",n[17])},m(t,r){Ge(t,e,r)},p(t,r){r&4&&si(e,"background-color",t[17])},d(t){t&&De(e)}}}function pu(n){let e,t,r=n[4](n[14].projected_arrival)+"",i;return{c(){e=H("span"),t=H("strong"),i=We(r)},m(s,o){Ge(s,e,o),C(e,t),C(t,i)},p(s,o){o&4&&r!==(r=s[4](s[14].projected_arrival)+"")&&it(i,r)},d(s){s&&De(e)}}}function gu(n){let e;return{c(){e=H("div"),e.textContent="ARRIVING NOW",N(e,"class","arriving-now-chip svelte-vt3xxd")},m(t,r){Ge(t,e,r)},p:rt,d(t){t&&De(e)}}}function ds(n){let e,t,r,i,s,o,a,l=n[14].route_display_name+"",c,u,h,d=n[14].direction.replace("TO_","to ")+"",p,f,g=Tt(n[14].colors),m=[];for(let S=0;S<g.length;S+=1)m[S]=hs(us(n,g,S));function b(S,O){return S[14].status==="ARRIVING_NOW"?gu:pu}let E=b(n),T=E(n);return{c(){e=H("div"),t=H("div"),r=H("div");for(let S=0;S<m.length;S+=1)m[S].c();i=Se(),T.c(),s=Se(),o=H("div"),a=H("strong"),c=We(l),u=Se(),h=H("span"),p=We(d),f=Se(),N(r,"class","line-circles svelte-vt3xxd"),N(o,"class","route-display-name"),N(t,"class","train-title svelte-vt3xxd"),N(e,"class","upcoming-train")},m(S,O){Ge(S,e,O),C(e,t),C(t,r);for(let I=0;I<m.length;I+=1)m[I]&&m[I].m(r,null);C(t,i),T.m(t,null),C(t,s),C(t,o),C(o,a),C(a,c),C(o,u),C(o,h),C(h,p),C(e,f)},p(S,O){if(O&4){g=Tt(S[14].colors);let I;for(I=0;I<g.length;I+=1){const q=us(S,g,I);m[I]?m[I].p(q,O):(m[I]=hs(q),m[I].c(),m[I].m(r,null))}for(;I<m.length;I+=1)m[I].d(1);m.length=g.length}E===(E=b(S))&&T?T.p(S,O):(T.d(1),T=E(S),T&&(T.c(),T.m(t,s))),O&4&&l!==(l=S[14].route_display_name+"")&&it(c,l),O&4&&d!==(d=S[14].direction.replace("TO_","to ")+"")&&it(p,d)},d(S){S&&De(e),Ir(m,S),T.d()}}}function fs(n){let e,t,r,i,s=ps(n[11].station)+"",o,a,l,c,u=Tt(n[11].original_upcoming_trains),h=[];for(let d=0;d<u.length;d+=1)h[d]=ds(cs(n,u,d));return{c(){e=H("div"),t=H("div"),r=H("div"),i=H("strong"),o=We(s),a=Se(),l=H("div");for(let d=0;d<h.length;d+=1)h[d].c();c=Se(),N(t,"class","station-title svelte-vt3xxd"),N(e,"class","station-card svelte-vt3xxd")},m(d,p){Ge(d,e,p),C(e,t),C(t,r),C(r,i),C(i,o),C(e,a),C(e,l);for(let f=0;f<h.length;f+=1)h[f]&&h[f].m(l,null);C(e,c)},p(d,p){if(p&4&&s!==(s=ps(d[11].station)+"")&&it(o,s),p&20){u=Tt(d[11].original_upcoming_trains);let f;for(f=0;f<u.length;f+=1){const g=cs(d,u,f);h[f]?h[f].p(g,p):(h[f]=ds(g),h[f].c(),h[f].m(l,null))}for(;f<h.length;f+=1)h[f].d(1);h.length=u.length}},d(d){d&&De(e),Ir(h,d)}}}function vu(n){let e,t,r=n[3].toLocaleTimeString("en-us")+"",i,s,o,a=n[3].toLocaleDateString("en-us",{weekday:"long",year:"numeric",month:"short",day:"numeric"})+"",l,c,u,h;function d(b,E){return b[1]!==null?fu:du}let p=d(n),f=p(n),g=Tt(n[2]),m=[];for(let b=0;b<g.length;b+=1)m[b]=fs(ls(n,g,b));return{c(){e=H("main"),t=H("div"),i=We(r),s=Se(),o=H("div"),l=We(a),c=Se(),f.c(),u=Se(),h=H("div");for(let b=0;b<m.length;b+=1)m[b].c();N(t,"class","time svelte-vt3xxd"),N(o,"class","date svelte-vt3xxd"),N(h,"class","stations-grid svelte-vt3xxd"),N(e,"class","svelte-vt3xxd")},m(b,E){Ge(b,e,E),C(e,t),C(t,i),C(e,s),C(e,o),C(o,l),C(e,c),f.m(e,null),C(e,u),C(e,h);for(let T=0;T<m.length;T+=1)m[T]&&m[T].m(h,null)},p(b,[E]){if(E&8&&r!==(r=b[3].toLocaleTimeString("en-us")+"")&&it(i,r),E&8&&a!==(a=b[3].toLocaleDateString("en-us",{weekday:"long",year:"numeric",month:"short",day:"numeric"})+"")&&it(l,a),p===(p=d(b))&&f?f.p(b,E):(f.d(1),f=p(b),f&&(f.c(),f.m(e,u))),E&20){g=Tt(b[2]);let T;for(T=0;T<g.length;T+=1){const S=ls(b,g,T);m[T]?m[T].p(S,E):(m[T]=fs(S),m[T].c(),m[T].m(h,null))}for(;T<m.length;T+=1)m[T].d(1);m.length=g.length}},i:rt,o:rt,d(b){b&&De(e),f.d(),Ir(m,b)}}}const _u="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImpreXB1d2JuZ2Vvc2FkdW1scHJxIiwicm9sZSI6ImFub24iLCJpYXQiOjE2OTM2ODgxNjAsImV4cCI6MjAwOTI2NDE2MH0.maQaKFE4FMG5driCzvRjCUWVPo4jrPpeNMTmV-UbPu4",mu="https://jkypuwbngeosadumlprq.supabase.co";let er="all";function ps(n){return n.replaceAll("_"," ").toLowerCase().split(" ").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(" ").replace("Street","St").replace("Fourteenth","14th").replace("Ninth","9th").replace("Twenty Third","23rd").replace("Thirty Third","33rd")}function yu(n,e,t){hu.init("phc_va4SvDQxndxZNipSDuoIyi7wgsjb4NsedSRfVyvuf9W",{api_host:"https://app.posthog.com"});const r=Nl(mu,_u);let i=!1,s=null;async function o(f){let g={headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"*"},body:f};console.log("sending refresh request...");const{data:m,error:b}=await r.functions.invoke("refresh-index",g);console.log("refresh edge function stopped..."),b&&console.error(b),console.log(m)}let a=[];async function l(f){console.log("called fetch...");let g=r.from("realtime").select("station, route_display_name, colors, direction, projected_arrival, status"),m=f.toLowerCase()==="all"?g:g.eq("station",f);const{data:b,error:E}=await m;if(b===null)throw new Error("fetched data was null...");t(6,a=b)}async function c(){await o(er),await l(er),t(1,s=new Date)}c(),setInterval(async()=>{await c()},3e4),setInterval(async()=>{await l(er)},1e3);let u=[],h=new Date;Oo(()=>{const f=setInterval(()=>{t(3,h=new Date)},1e3);return()=>{clearInterval(f)}});function d(f){let g=(f.getTime()-h.getTime())/6e4;return Math.round(Math.max(g,1)).toString()+"m"}async function p(){t(0,i=!0),await c(),t(0,i=!1)}return n.$$.update=()=>{if(n.$$.dirty&64){let f=new Map;for(let b of a){let E=b.station,T=new Date(b.projected_arrival);b.projected_arrival=T;let S=f.get(E),O=S==null?[b]:[...S,b];f.set(E,O)}let g=[];for(let b of a){let E=b.station;if(f.has(E)){let T=f.get(E);if(T!=null){let S={station:E,original_upcoming_trains:T};g.push(S),f.delete(E)}}}const m=["NEWARK","HARRISON","JOURNAL_SQUARE","GROVE_STREET","EXCHANGE_PLACE","WORLD_TRADE_CENTER","NEWPORT","HOBOKEN","CHRISTOPHER_STREET","NINTH_STREET","FOURTEENTH_STREET","TWENTY_THIRD_STREET","THIRTY_THIRD_STREET"];g.sort(function(b,E){return m.indexOf(b.station)<m.indexOf(E.station)?-1:1}),t(2,u=g)}},[i,s,u,h,d,p,a]}class bu extends Mo{constructor(e){super(),qo(this,e,yu,vu,To,{})}}new bu({target:document.getElementById("app")});