@mcpjam/inspector 3.12.9 → 3.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/start.js +32 -6
- package/dist/client/assets/OAuthDesktopReturnNotice-BZEaGzn6.css +2 -0
- package/dist/client/assets/{OAuthDesktopReturnNotice-DlTJhJwy.js → OAuthDesktopReturnNotice-D5tJNqny.js} +2 -2
- package/dist/client/assets/{app-bootstrap-BtbHLWDU.js → app-bootstrap-baadQQNk.js} +351 -368
- package/dist/client/assets/{button-12hqsTUk.js → button-DHPqnOj6.js} +2 -2
- package/dist/client/assets/chunk-D32TOXHM-BPB6AqSK.js +160 -0
- package/dist/client/assets/dead-clicks-autocapture-Cbczl2El.js +3 -0
- package/dist/client/assets/{error-reporting-D3byeSLw.js → error-reporting-B4hGM_ob.js} +1 -1
- package/dist/client/assets/error-reporting-CORfsjyM.js +120 -0
- package/dist/client/assets/{exception-autocapture-CzpTtsxv.js → exception-autocapture-CMOUrnel.js} +4 -4
- package/dist/client/assets/{failed-request-tracker-CmHxaDPF.js → failed-request-tracker-DoQRXuIy.js} +2 -2
- package/dist/client/assets/highlighted-body-KQOG7T2V-_ljE4u1k.js +3 -0
- package/dist/client/assets/{index-C0SfPmai.js → index-BBr8TZVx.js} +3 -3
- package/dist/client/assets/{jszip.min-BmAHHtmZ.js → jszip.min-C-vIQbxH.js} +2 -2
- package/dist/client/assets/mermaid-MCJ5UELQ-DTJaEEBm.js +1 -0
- package/dist/client/assets/posthog-recorder-Dby9Z8HR.js +110 -0
- package/dist/client/assets/{preload-helper-B22rzauv.js → preload-helper-Dvt1a6xa.js} +2 -2
- package/dist/client/assets/{react-BzkNdoI5.js → react-CD7Pk4KS.js} +2 -2
- package/dist/client/assets/{rolldown-runtime-BNuWddGb.js → rolldown-runtime-mzU9SaVm.js} +1 -1
- package/dist/client/assets/surveys-DYqpu8xl.js +3 -0
- package/dist/client/assets/trace-timeline-PnE1ouRj.js +71 -0
- package/dist/client/assets/{trace-timeline-Bg58ukyI.js → trace-timeline-WXINST5z.js} +1 -1
- package/dist/client/assets/{web-vitals-D4bU8W1t.js → web-vitals-BLq6M5vx.js} +2 -2
- package/dist/client/index.html +8 -8
- package/dist/server/{chunk-DGAFFBDM.js → chunk-2FVSBJQF.js} +1470 -890
- package/dist/server/chunk-I7ZVTBZP.js +3100 -0
- package/dist/server/{chunk-SH24KJBI.js → chunk-MBS3EZ3U.js} +13 -2
- package/dist/server/{chunk-4PYR7GMQ.js → chunk-QHYREDE3.js} +4 -4
- package/dist/server/{consent-lifetime-M7PS6RUU.js → consent-lifetime-TYLDY64H.js} +3 -3
- package/dist/server/harness-install-cli.js +23 -6
- package/dist/server/index.js +21146 -18727
- package/dist/server/{local-turn-ZWMMQGV3.js → local-turn-VQDSTY6T.js} +4 -4
- package/package.json +38 -38
- package/dist/client/assets/OAuthDesktopReturnNotice-FnFv52Ym.css +0 -2
- package/dist/client/assets/chunk-YOKDWASO--Bd-6XAf.js +0 -145
- package/dist/client/assets/dead-clicks-autocapture-RCao2exY.js +0 -3
- package/dist/client/assets/error-reporting-StyhxjHz.js +0 -102
- package/dist/client/assets/highlighted-body-KPVGNVTW-BweERQbm.js +0 -3
- package/dist/client/assets/mermaid-HWGCJPDP-C6s_jIuz.js +0 -1
- package/dist/client/assets/posthog-recorder-wc41pimR.js +0 -110
- package/dist/client/assets/surveys-D-NcCeqw.js +0 -3
- package/dist/client/assets/trace-timeline-CxoCCEiW.js +0 -137
- package/dist/server/chunk-WZVZ6LQX.js +0 -2876
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import{o as W0}from"./rolldown-runtime-mzU9SaVm.js";import{t as J0}from"./failed-request-tracker-DoQRXuIy.js";import{t as K0}from"./react-CD7Pk4KS.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"3.13.0"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2c0f7d7-2ea0-40e0-8149-88f72b84305a",e._sentryDebugIdIdentifier="sentry-dbid-b2c0f7d7-2ea0-40e0-8149-88f72b84305a")}catch{}})();var Cs=W0(K0(),1),iD=null,sD="write",Hd=null,Y0=String(101376);function oD(){return Hd?`https://discord.com/oauth2/authorize?${new URLSearchParams({client_id:Hd,scope:"bot applications.commands",permissions:Y0}).toString()}`:null}var X0=["timeout","network","upstream_status","bad_json","bad_payload","provisioning"],Q0=/^[A-Z][A-Z0-9_]{1,63}$/;function eb(e){return typeof e=="string"&&X0.includes(e)}function tb(e){if(!e||typeof e!="object")return;const{reason:t,upstreamStatus:r,networkCode:n}=e;if(!eb(t))return;const i={reason:t};return typeof r=="number"&&Number.isInteger(r)&&r>=100&&r<=599&&(i.upstreamStatus=r),typeof n=="string"&&Q0.test(n)&&(i.networkCode=n),i}var vv="mcpjam_guest_session_v1",Kc="mcpjam_guest_activated",aa=3e5,St=null,Ar=null,Tr=null,on=null,gv=!1,Lr=0,Yc=new Set,rb=6e5,Dn=null,Si=null;function mv(){for(const e of Yc)e()}function _v(e){Si!==null&&(clearTimeout(Si),Si=null),Dn=e,e&&(Si=setTimeout(()=>{Si=null,Dn===e&&_v(null)},Math.max(0,e.until-Date.now()))),mv()}function nb(){return Dn&&Dn.until<=Date.now()&&(Dn=null),Dn}function ca(e){const t=St?.guestId??null;St=e,t!==(St?.guestId??null)&&mv()}function aD(e){return Yc.add(e),()=>{Yc.delete(e)}}function cD(e){if(e)try{localStorage.getItem(Kc)!==e&&localStorage.setItem(Kc,e)}catch{}}function uD(e){if(!e)return!1;try{return localStorage.getItem(Kc)===e}catch{return!1}}function ib(){if(typeof window>"u")return;const e=window.__MCP_GUEST_BOOTSTRAP__;try{delete window.__MCP_GUEST_BOOTSTRAP__}catch{window.__MCP_GUEST_BOOTSTRAP__=void 0}e&&(typeof e.token!="string"||e.token.length===0||typeof e.expiresAt!="number"||typeof e.guestId!="string"||e.guestId.length===0||e.expiresAt-aa<=Date.now()||(St={guestId:e.guestId,token:e.token,expiresAt:e.expiresAt}))}ib();function gl(){if(gv)return null;try{const e=localStorage.getItem(vv);if(!e)return null;const t=JSON.parse(e);return typeof t.token=="string"&&t.token.length>0?t.token:null}catch{return null}}function Bd(){try{localStorage.removeItem(vv)}catch{}gv=!0}var Ni=class extends Error{status;upstreamFailure;constructor(e,t,r){super(e),this.name="GuestSessionRequestError",this.status=t,this.upstreamFailure=r}},yv=class extends Ni{retryAfterMs;constructor(e){super("guest-session creation refused (429)"),this.name="GuestSessionRefusedError",this.retryAfterMs=e}},sb=1e3;async function ob(e){if(typeof e.json!="function")return;let t;try{const r=await Promise.race([e.json(),new Promise(n=>{t=setTimeout(()=>n(void 0),sb)})]);return tb(r?.details)}catch{return}finally{t!==void 0&&clearTimeout(t)}}function ab(e){if(!e)return"";const t=e.networkCode??(e.upstreamStatus!==void 0?String(e.upstreamStatus):void 0);return` (${e.reason}${t?` ${t}`:""})`}function cb(e){const t=e?Number.parseInt(e,10):NaN;return Number.isFinite(t)&&t>0?t*1e3:rb}async function ml(e,t){const r={mode:e};t&&(r.legacyToken=t);let n;try{n=await fetch("/api/web/guest-session",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})}catch(s){throw new Ni(s instanceof Error?s.message:"network error")}if(n.status===204)return t&&Bd(),null;if(n.status===429)throw new yv(cb(n.headers?.get?.("retry-after")));if(!n.ok){const s=await ob(n);throw new Ni(`guest-session request failed: ${n.status} ${n.statusText}${ab(s)}`,n.status,s)}let i;try{i=await n.json()}catch(s){throw new Ni(`guest-session response was not valid JSON: ${s instanceof Error?s.message:String(s)}`)}if(typeof i?.token!="string"||typeof i?.expiresAt!="number")throw new Ni("guest-session response missing token or expiresAt");return t&&Bd(),i}async function ub(){if(St&&St.expiresAt-aa>Date.now())return St;if(nb())return null;if(Ar)return Ar;const e=gl(),t=Lr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await ml("lookup_or_create",e);return n&&t===Lr&&ca(n),n}catch(n){if(n instanceof yv)return _v({until:Date.now()+n.retryAfterMs}),null;throw console.error("Failed to create guest session:",n),n}finally{Ar===r&&(Ar=null)}})(),Ar=r,r.catch(()=>{}),Ar}async function lb(){try{return await ub()}catch{return null}}async function lD(){return(await lb())?.token??null}function Xc(){return St&&St.expiresAt-aa>Date.now()?St:null}async function db(){if(St&&St.expiresAt-aa>Date.now())return St.token;if(Tr)return(await Tr)?.token??null;const e=gl(),t=Lr;let r=Promise.resolve(null);return r=(async()=>{try{const n=await ml("lookup_only",e);return n&&t===Lr&&ca(n),n}finally{Tr===r&&(Tr=null)}})(),Tr=r,(await Tr)?.token??null}async function dD(){const e=Xc();if(e?.guestId)return e.guestId;try{await db()}catch{return null}return Xc()?.guestId??null}function hb(){Lr+=1,ca(null),Ar=null,Tr=null,on=null}async function hD(){let e=!1;try{const t=await fetch("/api/web/guest-session/revoke",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(t.ok)try{e=(await t.json())?.revoked===!0}catch{e=!1}}catch(t){console.error("Failed to revoke guest session:",t)}finally{hb()}return e}async function pD(){try{const e=await fetch("/api/web/guest-session/promotion-proof",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}});if(e.status===204||!e.ok)return null;const t=await e.json();return typeof t.token=="string"&&t.token.length>0?t.token:null}catch(e){return console.error("Failed to fetch guest promotion proof:",e),null}}async function pb(){if(on)return(await on)?.token??null;Lr+=1;const e=Lr;St=null,Ar=null,Tr=null,on=(async()=>{try{const t=await ml("lookup_or_create",gl());return t&&e===Lr&&ca(t),t}catch(t){throw console.error("Failed to refresh guest session:",t),t}})(),on.catch(()=>{});try{return(await on)?.token??null}finally{on=null}}async function fD(){try{return await pb()}catch{return null}}var vD=Object.freeze({maxObservations:24,maxSummaryChars:400,maxEvidenceRefs:8,maxEvidenceRefChars:200,maxModelIdChars:128,maxVersionChars:64}),gD=Object.freeze({status:"not-requested",reason:"not_requested",detail:"this run did not request model-backed observations, so nothing was charged"});function bv(e){return e.status==="skipped"&&e.skipReason==="could-not-run"}function fb(e){return e.status==="skipped"&&e.skipReason!=="could-not-run"}function vb(e){if(e.some(n=>n.status==="failed"))return{outcome:"failed"};const t=e.filter(bv);if(t.length===0)return e.length===0?{outcome:"incomplete",incompleteReason:"no checks were selected, so this run establishes nothing"}:{outcome:"passed"};const r=Array.from(new Set(t.map(n=>n.error?.message??"reason unavailable")));return{outcome:"incomplete",incompleteReason:`${t.length} of ${e.length} selected check(s) could not run, so this run does not establish conformance (${t.map(n=>n.id).join(", ")}): ${r.join(" ")}`}}var gb="2026-08-19",mb="https://docs.claude.com/en/docs/mcp",_b=["directory","verification","submission","review-criteria","authentication","lazy-authentication","enterprise-managed-auth","troubleshooting","mcp-apps/cross-compatibility","mcp-apps/external-links","mcp-apps/troubleshooting","mcp-apps/design-guidelines"],yb={},bb=_b.map(e=>({page:e,url:`${mb}/${e}`,revision:yb[e]??null,snapshotDate:gb})),wb=Object.freeze(Object.fromEntries(bb.map(e=>[e.page,e])));function wr(e,t){const r=wb[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}function wv(e){return e.class==="required"||e.class==="runtime-blocker"}var mD=["runtime-compatibility","directory-policy","optional-features","submission-artifacts","experience-insights"];function Sb(e){return wv(e)}var Eb=["experience"];var kb=["claude.experience.tool-descriptions-uninformative","claude.experience.tool-overlap","claude.experience.connector-purpose-unclear","claude.experience.consent-scope-unclear","claude.experience.listing-copy-placeholder","claude.experience.destructive-tool-underexplained","claude.experience.app-copy-mismatched"],_D=Object.freeze({readinessKind:"claude-directory-readiness",observationKinds:Eb,knownIds:kb,schemaVersion:"1"}),Ib=[{id:"claude.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell Claude when to use the tool",lane:"experience-insights",class:"heuristic",source:wr("review-criteria","§Tool quality"),remediation:"Describe when a tool should be reached for, not only what it does; Claude picks tools from these sentences."},{id:"claude.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:wr("review-criteria","§Tool quality"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening what separates them."},{id:"claude.experience.connector-purpose-unclear",title:"What this connector is for may not be clear from its surface",lane:"experience-insights",class:"manual-review",source:wr("review-criteria","§Usefulness"),remediation:"A reviewer should be able to say what the connector is for from the listing and the tool names alone."},{id:"claude.experience.consent-scope-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:wr("authentication","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."},{id:"claude.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:wr("submission","§Listing"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"claude.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:wr("review-criteria","§Safety"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"claude.experience.app-copy-mismatched",title:"An app's rendered copy may not match what its tool returns",lane:"experience-insights",class:"heuristic",source:wr("mcp-apps/design-guidelines","§Content"),remediation:"A widget that says something different from the tool's text response leaves the model and the user disagreeing."}],yD=Object.freeze({experienceLane:"experience-insights",engineVersion:"1",mappings:Ib}),Vd="2026-08-19",Eo="https://developers.openai.com/plugins",bD=`${Eo}/llms.txt`,wD=`${Eo}/changelog`,Sv=["quickstart","app-guidelines","reference","changelog","plan/use-case","plan/tools","concepts/plugins","concepts/skills","concepts/ui-guidelines","build/plugins","build/skills","build/mcp-server","build/chatgpt-ui","build/auth","build/monetization","build/examples","deploy/connect-chatgpt","deploy/submission","deploy/submission-errors","deploy/troubleshooting","guides/optimize-metadata","guides/submit-claude-plugin","guides/product-checkout-conversion-spec"],Ev=[{page:"help/plugins-in-chatgpt-and-codex",url:"https://help.openai.com/en/articles/20001256-plugins-in-chatgpt-and-codex"},{page:"help/submitting-apps-to-the-chatgpt-app-directory",url:"https://help.openai.com/en/articles/20001040-submitting-apps-to-the-chatgpt-app-directory"}],SD=[...Sv,...Ev.map(e=>e.page)],Gd={},Ab=[...Sv.map(e=>({page:e,url:`${Eo}/${e}`,revisionUrl:`${Eo}/${e}.md`,format:"markdown",revision:Gd[e]??null,snapshotDate:Vd})),...Ev.map(e=>({page:e.page,url:e.url,revisionUrl:e.url,format:"html",revision:Gd[e.page]??null,snapshotDate:Vd}))],Tb=Object.freeze(Object.fromEntries(Ab.map(e=>[e.page,e])));function Wt(e,t){const r=Tb[e];return{page:r.page,section:t,url:r.url,revision:r.revision,snapshotDate:r.snapshotDate}}var ED=["runtime-compatibility","directory-policy","plugin-package","release-contract","optional-features","submission-artifacts","experience-insights"],Tn={serverUrl:"serverUrl",pluginBundle:"pluginBundle",submissionProfile:"submissionProfile",draftSnapshot:"draftSnapshot",publishedSnapshot:"publishedSnapshot",toolListing:"toolListing",importedSkills:"importedSkills"},kD=Object.freeze({"skills-only":{hasMcpServer:!1,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Tn.pluginBundle],summary:"a skills package with no MCP server"},"mcp-only":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!1,requiredInputs:[Tn.serverUrl],summary:"an MCP endpoint with no uploaded package"},"mcp-imported-skills":{hasMcpServer:!0,hasUploadedPackage:!1,hasImportedSkills:!0,requiredInputs:[Tn.serverUrl,Tn.importedSkills],summary:"an MCP endpoint whose skills are imported at scan time"},"mcp-uploaded-skills":{hasMcpServer:!0,hasUploadedPackage:!0,hasImportedSkills:!1,requiredInputs:[Tn.serverUrl,Tn.pluginBundle],summary:"an MCP endpoint plus an uploaded skills package"}}),ID=Object.freeze({"technical-preflight":["runtime-compatibility","directory-policy","plugin-package"],"submission-ready":["runtime-compatibility","directory-policy","plugin-package","submission-artifacts","release-contract"]});function Rb(e){return typeof e=="object"&&e!==null&&e.readinessKind==="openai-directory-readiness"}var Pb=["experience"];var Ob=["openai.experience.tool-descriptions-uninformative","openai.experience.tool-overlap","openai.experience.naming-inconsistent","openai.experience.listing-copy-placeholder","openai.experience.listing-copy-overpromises","openai.experience.skill-overlap","openai.experience.destructive-tool-underexplained","openai.experience.auth-story-unclear"],AD=Object.freeze({readinessKind:"openai-directory-readiness",observationKinds:Pb,knownIds:Ob,schemaVersion:"1"}),Cb=[{id:"openai.experience.tool-descriptions-uninformative",title:"Tool descriptions may not tell the model when to use the tool",lane:"experience-insights",class:"heuristic",source:Wt("guides/optimize-metadata","§Tool descriptions"),remediation:"Describe when a tool should be reached for, not only what it does; the model picks tools from these sentences."},{id:"openai.experience.tool-overlap",title:"Two or more tools may cover the same job",lane:"experience-insights",class:"heuristic",source:Wt("plan/tools","§Naming"),remediation:"Overlapping tools make selection ambiguous; consider merging them or sharpening the descriptions that separate them."},{id:"openai.experience.naming-inconsistent",title:"Tool names may not follow one convention",lane:"experience-insights",class:"heuristic",source:Wt("plan/tools","§Naming"),remediation:"Pick one naming convention across the whole surface; mixed conventions read as two servers merged."},{id:"openai.experience.listing-copy-placeholder",title:"Listing copy may still contain placeholder text",lane:"experience-insights",class:"manual-review",source:Wt("app-guidelines","§Listing quality"),remediation:"Review the listing fields for template text before submitting; reviewers reject placeholder copy."},{id:"openai.experience.listing-copy-overpromises",title:"Listing copy may claim capabilities the tools do not implement",lane:"experience-insights",class:"manual-review",source:Wt("app-guidelines","§Listing quality"),remediation:"Check that every capability the listing advertises is reachable through a tool this server actually exposes."},{id:"openai.experience.skill-overlap",title:"Two or more skills may describe the same task",lane:"experience-insights",class:"heuristic",source:Wt("app-guidelines","§Listing quality"),remediation:"Skills that overlap compete for the same trigger; separate their scopes or fold them together."},{id:"openai.experience.destructive-tool-underexplained",title:"A destructive tool may not explain its consequences",lane:"experience-insights",class:"manual-review",source:Wt("app-guidelines","§Predictable side effects"),remediation:"Say plainly in the description what a destructive tool changes and whether it can be undone."},{id:"openai.experience.auth-story-unclear",title:"It may not be clear to a user what they are authorizing",lane:"experience-insights",class:"manual-review",source:Wt("build/auth","§Consent"),remediation:"State which account is connected and what scope it grants, in the copy the user sees at consent time."}],TD=Object.freeze({experienceLane:"experience-insights",engineVersion:"2",mappings:Cb}),$b=["https://claude.ai/api/mcp/auth_callback","https://claude.com/api/mcp/auth_callback"];var xb=".claudemcpcontent.com";var Mb="text/html;profile=mcp-app",Lb={toolListingMs:5e3,handshakeMs:3e3,widgetFirstPaintMs:3e3},Nb={minViewportWidthPx:320,minTouchTargetPx:44},Sr={nameMaxLength:100,taglineMaxLength:55,descriptionMaxLength:2e3,categoriesMin:1,categoriesMax:5,screenshotsMin:3,screenshotsMax:5,screenshotMinWidthPx:1e3,toolNameMaxLength:64},RD={callbackUrls:$b,loopbackRedirectIgnoresPort:!0,appContentDomainSuffix:xb,appContentDomainHashLength:32,appHtmlMime:Mb,latencyBudgets:Lb,appDesignBudgets:Nb,submissionLimits:Sr,source:wr("directory","Host profile constants")};function Qc(e){const t=Object.values(e).filter(r=>typeof r=="number");return Object.entries(e).filter(([r,n])=>t.indexOf(+r)===-1).map(([r,n])=>n)}function Zd(e,t="|"){return e.map(r=>Rv(r)).join(t)}function eu(e,t){return typeof t=="bigint"?t.toString():t}var Db=class{constructor(e){this._getter=e,this._value=void 0}get value(){const e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function ua(e){return new Db(e)}function zb(e){return e==null}function _l(e){const t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Ub(e,t){const r=e/t,n=Math.round(r),i=4*Number.EPSILON*Math.max(Math.abs(r),1);return Math.abs(r-n)<i?0:r-n}var Wd=Symbol("evaluating");function Fb(e,t,r){let n;Object.defineProperty(e,t,{get(){if(n!==Wd)return n===void 0&&(n=Wd,n=r()),n},set(i){Object.defineProperty(e,t,{value:i})},configurable:!0})}function rr(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yl(e){const t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function mr(e){return yl(e._zod.def)??e._zod.def.shape}function kv(e,t,r){Object.defineProperty(e,t,{get(){const n=r();return rr(this,t,n),n},enumerable:!0,configurable:!0})}function Iv(e,t,r){t in e?rr(e,t,r):e[t]=r}function Sn(e,t,r,n){const i=mr(t);for(const s of r){const o=Object.getOwnPropertyDescriptor(i,s);o.enumerable&&(o.get?kv(e,s,()=>{const a=t._zod.def.shape[s];return n?n(a,s):a}):Iv(e,s,n?n(o.value,s):o.value))}}function qb(e,t){for(const r of Reflect.ownKeys(t)){const n=Object.getOwnPropertyDescriptor(t,r);n.enumerable&&(n.get?kv(e,r,()=>t[r]):Iv(e,r,n.value))}}function kt(...e){const t={};for(const r of e){const n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function jb(e){return JSON.stringify(e)}function Hb(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Av="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function as(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Bb=ua(()=>{if($t.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch{return!1}});function Qn(e){if(as(e)===!1)return!1;const t=e.constructor;if(t===void 0||typeof t!="function")return!0;const r=t.prototype;return!(as(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Tv(e){return Qn(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Vb=new Set(["string","number","symbol"]);function ei(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Yr(e,t,r){const n=new e._zod.constr(t??e._zod.def);return(!t||r?.parent)&&(n._zod.parent=e),n}function te(e){const t=e;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Rv(e){return typeof e=="bigint"?e.toString()+"n":typeof e=="string"?`"${e}"`:`${e}`}function Gb(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var Pv={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Zb={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Wb(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i={};return Sn(i,e,la(e,t)),Yr(e,kt(r,{shape:i,checks:[]}))}function la(e,t){const r=mr(e),n=[];for(const i of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,i)?.enumerable)throw new Error(`Unrecognized key: "${String(i)}"`);t[i]&&n.push(i)}return n}function Jb(e,t){const r=e._zod.def,n=r.checks;if(n&&n.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=new Set(la(e,t)),s={};return Sn(s,e,Reflect.ownKeys(mr(e)).filter(o=>!i.has(o))),Yr(e,kt(r,{shape:s,checks:[]}))}function Kb(e,t){if(!Qn(t))throw new Error("Invalid input to extend: expected a plain object");const r=e._zod.def.checks;if(r&&r.length>0){const n=mr(e);for(const i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Yr(e,kt(e._zod.def,{shape:Ov(e,t)}))}function Ov(e,t){const r={};return Sn(r,e,Reflect.ownKeys(mr(e))),qb(r,t),r}function Yb(e,t){if(!Qn(t))throw new Error("Invalid input to safeExtend: expected a plain object");return Yr(e,kt(e._zod.def,{shape:Ov(e,t)}))}function Xb(e,t){if(!t?._zod?.def)throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const r={};return Sn(r,e,Reflect.ownKeys(mr(e))),Sn(r,t,Reflect.ownKeys(mr(t))),Yr(e,kt(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Jd(e,t,r,n="partial"){const i=t._zod.def.checks;if(i&&i.length>0)throw new Error(`.${n}() cannot be used on object schemas containing refinements`);const s=r?new Set(la(t,r)):void 0,o={};return Sn(o,t,Reflect.ownKeys(mr(t)),e&&((a,c)=>s&&!s.has(c)?a:new e({type:"optional",innerType:a}))),Yr(t,kt(t._zod.def,{shape:o,checks:[]}))}function Qb(e,t,r){const n=r?new Set(la(t,r)):void 0,i={};return Sn(i,t,Reflect.ownKeys(mr(t)),(s,o)=>n&&!n.has(o)?s:new e({type:"nonoptional",innerType:s})),Yr(t,kt(t._zod.def,{shape:i}))}function qt(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function ew(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function fr(e,t){return t.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Ei(e){return typeof e=="string"?e:e?.message}function Kd(e,t,r){var n;for(let i=t;i<e.length;i++)(n=e[i]).schema??(n.schema=r)}function qr(e,t,r){var n;const i=e.inst?._zod?.traits;i?.has("$ZodType")&&(i.has("$ZodCheck")?(n=e).schema??(n.schema=e.inst):e.schema=e.inst);const s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,o=e.message?e.message:Ei(e.inst?._zod.def?.error?.(e))??Ei(s?.(e))??Ei(t?.error?.(e))??Ei(r.customError?.(e))??Ei(r.localeError?.(e))??"Invalid input",a={};for(const c of Object.keys(e))c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__"||(a[c]=e[c]);return a.path??(a.path=[]),a.message=o,t?.reportInput&&(a.input=e.input),a}var tw=/[\uD800-\uDBFF]/;function bl(e){const t=e.length;if(!tw.test(e))return t;let r=t;for(let n=0;n<t-1;n++)(e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320&&(r--,n++);return r}function wl(e){return Array.isArray(e)?"array":typeof e=="string"?"string":"unknown"}function rw(e){const t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";const r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function cs(...e){const[t,r,n]=e;return typeof t=="string"?{message:t,code:"custom",input:r,inst:n}:{...t}}function nw(e,t){for(const r in t){const n=Object.getOwnPropertyDescriptor(t,r);n.get?Object.defineProperty(e,r,{...n,enumerable:!1}):iw(e,r,n.value)}}function jr(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function Sl(e,t,r){return jr(e,t,r,!1)}function Cv(e,t){for(const r in e){const n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return jr(this,r,n(this))},set(i){jr(this,r,i)}})}return t}function iw(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:jr(this,t,r.bind(this))},set(n){jr(this,t,n)}})}function sw(e,t){const r=Object.getPrototypeOf(e);return t in r?void 0:r}var Ya,Er=!1,ow={configurable:!0,get(){Er=!0}};function Te(e,t,r){const n=Object.getPrototypeOf(e._zod);if(t in n&&Ya!==e._zod){Ya=void 0;return}Ya=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,ow);const i=Er;Er=!1;try{const s=r(this);return Er?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s}),Er=Er||i,s}catch(s){throw delete this[t],Er=Er||i,s}},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i})}})}function aw(e,t,r,n){const i=sw(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){const s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var cw="~constantCatch";function uw(e){const t=()=>e;return t[cw]=!0,t}var Yd,Xa={value:void 0,enumerable:!1},Xd="captureStackTrace"in Error?Error:null;function lw(e){const t=Xd;if(t){const r=t.stackTraceLimit;if(typeof r=="number"){try{t.stackTraceLimit=0}catch{return Xd=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function x(e,t,r,n){const i={};function s(d){this.def=d,this.constr=h,this.traits=new Set}s.prototype=i;const o=r,a=o&&new WeakSet;function c(d,p){if(d._zod){if(d._zod.traits.has(e))return}else{Xa.value=new s(p);try{Object.defineProperty(d,"_zod",Xa)}finally{Xa.value=void 0}}if(d._zod.traits.add(e),t(d,p),a){const v=Object.getPrototypeOf(d),g=d._zod.constr.prototype;let m=v;for(;m&&m!==g;)m=Object.getPrototypeOf(m);const w=m??v;a.has(w)||(a.add(w),nw(w,o))}const f=h.prototype;for(const v in f)Object.prototype.hasOwnProperty.call(f,v)&&(v in d||(d[v]=f[v].bind(d)))}const u=n?.Parent??Object;class l extends u{}Object.defineProperty(l,"name",{value:e});function h(d){const p=n?.Parent?lw(l):this;c(p,d);const f=p._zod.deferred;if(f){for(const g of f)g();p._zod.deferred=void 0}const v=globalThis.__zod_globalConfig?.postProcessor;return v&&v(p),p}return Object.defineProperty(h,"init",{value:c}),Object.defineProperty(h,Symbol.hasInstance,{value:d=>n?.Parent&&d instanceof n.Parent?!0:d?._zod?.traits?.has(e)}),Object.defineProperty(h,"name",{value:e}),h}var fn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},$v=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}};(Yd=globalThis).__zod_globalConfig??(Yd.__zod_globalConfig={});var $t=globalThis.__zod_globalConfig;function er(e){return e&&Object.assign($t,e),$t}function dw(){const e=this._zod;return e.message??(e.message=JSON.stringify(e.def,eu,2)),e.message}function hw(e){this._zod.message=e}var pw={get:dw,set:hw,enumerable:!0,configurable:!0},Qa={value:void 0,enumerable:!1},Qd=new WeakSet([Object.prototype,Error.prototype]),xv=(e,t)=>{e.name="$ZodError",Qa.value=t,Object.defineProperty(e,"issues",Qa),Qa.value=void 0,Object.defineProperty(e,"message",pw);const r=Object.getPrototypeOf(e);Qd.has(r)||(Qd.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){const n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}}))},fw=x("$ZodError",xv),vw=x("$ZodError",xv,void 0,{Parent:Error});function gw(e,t,r){return Object.prototype.hasOwnProperty.call(e,t)||(t==="__proto__"?Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0}):e[t]=r()),e[t]}function mw(e,t=r=>r.message){const r={},n=[];for(const i of e.issues)i.path.length>0?gw(r,i.path[0],()=>[]).push(t(i)):n.push(t(i));return{formErrors:n,fieldErrors:r}}function _w(e,t=r=>r.message){const r={_errors:[]},n=(i,s=[])=>{for(const o of i.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(a=>n({issues:a},[...s,...o.path]));else if(o.code==="invalid_key")n({issues:o.issues},[...s,...o.path]);else if(o.code==="invalid_element")n({issues:o.issues},[...s,...o.path]);else{const a=[...s,...o.path];if(a.length===0)r._errors.push(t(o));else{let c=r,u=0;for(;u<a.length;){const l=a[u],h=u===a.length-1;if(l==="_errors"){h&&c._errors.push(t(o)),u++;continue}Object.prototype.hasOwnProperty.call(c,l)||Object.defineProperty(c,l,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});const d=c[l];h&&d._errors.push(t(o)),c=d,u++}}}};return n(e),r}function da(e,t){return{callee:t?.callee??e,Err:t?.Err}}var El=e=>{const t=(r,n,i,s)=>{const o=i?{...i,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise)throw new fn;if(a.issues.length){const c=new(s?.Err??e)(a.issues.map(u=>qr(u,o,er())));throw Av(c,s?.callee??t),c}return a.value};return t},kl=e=>{const t=async(r,n,i,s)=>{const o=i?{...i,async:!0}:{async:!0};let a=r._zod.run({value:n,issues:[]},o);if(a instanceof Promise&&(a=await a),a.issues.length){const c=new(s?.Err??e)(a.issues.map(u=>qr(u,o,er())));throw Av(c,s?.callee??t),c}return a.value};return t},ha=e=>(t,r,n)=>{const i=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},i);if(s instanceof Promise)throw new fn;return s.issues.length?Mv(e,s.issues,i):{success:!0,data:s.value}},PD=ha(vw);function Mv(e,t,r){let n;return{success:!1,get error(){return n||(n=new e(t.map(i=>qr(i,r,er()))),t=void 0,r=void 0),n},set error(i){n=i,t=void 0,r=void 0}}}var Il=e=>async(t,r,n)=>{const i=n?{...n,async:!0}:{async:!0};let s=t._zod.run({value:r,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?Mv(e,s.issues,i):{success:!0,data:s.value}},yw=Symbol.for("zod.compile.invalid"),bw=Symbol.for("zod.compile.fallback"),ww=((e,t,r)=>{const n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==yw)return!0;if(n.definite===!0&&r===void 0)return!1}return Sw(e,t,r)});function Sw(e,t,r){const n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun;let s;if(i?(n[bw]=!0,s=i({value:t,issues:[]},n)):s=e._zod.run({value:t,issues:[]},n),s instanceof Promise)throw new fn;return s.issues.length===0}var Ew=async(e,t,r)=>{const n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0};let i=e._zod.run({value:t,issues:[]},n);return i instanceof Promise&&(i=await i),i.issues.length===0},kw=e=>{const t=El(e),r=(n,i,s,o)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return t(n,i,a,da(r,o))};return r},Iw=e=>{const t=El(e),r=(n,i,s,o)=>t(n,i,s,da(r,o));return r},Aw=e=>{const t=kl(e),r=async(n,i,s,o)=>{const a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(n,i,a,da(r,o))};return r},Tw=e=>{const t=kl(e),r=async(n,i,s,o)=>await t(n,i,s,da(r,o));return r},Rw=e=>(t,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return ha(e)(t,r,i)},Pw=e=>(t,r,n)=>ha(e)(t,r,n),Ow=e=>async(t,r,n)=>{const i=n?{...n,direction:"backward"}:{direction:"backward"};return Il(e)(t,r,i)},Cw=e=>async(t,r,n)=>Il(e)(t,r,n),$w=/^[cC][0-9a-z]{6,}$/,xw=/^[0-9a-z]+$/,Mw=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Lw=/^[0-9a-vA-V]{20}$/,Nw=/^[A-Za-z0-9]{27}$/,Dw=/^[a-zA-Z0-9_-]{21}$/;function zw(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Uw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Fw=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,eh=e=>e?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,qw=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,jw="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function Hw(){return new RegExp(jw,"u")}var Bw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Vw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Gw=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Zw=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ww=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Jw=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Kw=/^https?$/,Yw=/^\+[1-9]\d{6,14}$/,Lv="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function Xw(e){return new RegExp(`^${e}$`)}var Qw=Xw(Lv);function tu(e){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof e.precision=="number"?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function eS(e){return new RegExp(`^${tu(e)}$`)}function tS(e){const t=["Z"];e.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${tu({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${tu({precision:e.precision})}`:r;return new RegExp(`^${Lv}T(?:${n})$`)}var rS=/^[\s\S]{0,}$/,nS=/^-?\d+$/,Al=/^-?\d+(?:\.\d+)?$/,iS=/^(?:true|false)$/i,sS=/^null$/i,oS=/^undefined$/i,aS=/^[^A-Z]*$/,cS=/^[^a-z]*$/,_t=x("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])}),Tl=e=>{const t=e.value;return!zb(t)&&t.length!==void 0},ko={number:"number",bigint:"bigint",object:"date"},Nv=x("$ZodCheckLessThan",(e,t)=>{_t.init(e,t);const r=ko[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value<=t.value:n.value<t.value)||n.issues.push({origin:ko[typeof n.value]??r,code:"too_big",maximum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Dv=x("$ZodCheckGreaterThan",(e,t)=>{_t.init(e,t);const r=ko[typeof t.value];e._zod.check=n=>{(t.inclusive?n.value>=t.value:n.value>t.value)||n.issues.push({origin:ko[typeof n.value]??r,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),uS=x("$ZodCheckMultipleOf",(e,t)=>{_t.init(e,t),e._zod.check=r=>{if(typeof r.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):Ub(r.value,t.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),lS=x("$ZodCheckNumberFormat",(e,t)=>{_t.init(e,t),t.format=t.format||"float64";const r=t.format?.includes("int"),n=r?"int":"number",[i,s]=Pv[t.format];e._zod.check=o=>{const a=o.value;if(r){if(!Number.isInteger(a)){o.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){a>0?o.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort}):o.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}a<i&&o.issues.push({origin:"number",input:a,code:"too_small",minimum:i,inclusive:!0,inst:e,continue:!t.abort}),a>s&&o.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}}),dS=x("$ZodCheckMaxLength",(e,t)=>{var r;_t.init(e,t),(r=e._zod.def).when??(r.when=Tl),e._zod.check=n=>{const i=n.value,s=i.length;if((typeof i=="string"&&s>t.maximum?bl(i):s)<=t.maximum)return;const o=wl(i);n.issues.push({origin:o,code:"too_big",maximum:t.maximum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),hS=x("$ZodCheckMinLength",(e,t)=>{var r;_t.init(e,t),(r=e._zod.def).when??(r.when=Tl),e._zod.check=n=>{const i=n.value,s=i.length;if((typeof i=="string"&&s>=t.minimum&&s<t.minimum*2?bl(i):s)>=t.minimum)return;const o=wl(i);n.issues.push({origin:o,code:"too_small",minimum:t.minimum,inclusive:!0,input:i,inst:e,continue:!t.abort})}}),pS=x("$ZodCheckLengthEquals",(e,t)=>{var r;_t.init(e,t),(r=e._zod.def).when??(r.when=Tl),e._zod.check=n=>{const i=n.value,s=i.length,o=typeof i=="string"&&s>=t.length&&s<=t.length*2?bl(i):s;if(o===t.length)return;const a=wl(i),c=o>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),pa=x("$ZodCheckStringFormat",(e,t)=>{var r,n;_t.init(e,t),t.pattern?(r=e._zod).check??(r.check=i=>{t.pattern.lastIndex=0,!t.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:t.format,input:i.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(n=e._zod).check??(n.check=()=>{})}),fS=x("$ZodCheckRegex",(e,t)=>{pa.init(e,t),e._zod.check=r=>{t.pattern.lastIndex=0,!t.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),vS=x("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=aS),pa.init(e,t)}),gS=x("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=cS),pa.init(e,t)}),mS=x("$ZodCheckIncludes",(e,t)=>{_t.init(e,t);const r=ei(t.includes);t.pattern=new RegExp(typeof t.position=="number"?`^.{${t.position},}${r}`:r),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),_S=x("$ZodCheckStartsWith",(e,t)=>{_t.init(e,t);const r=new RegExp(`^${ei(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),yS=x("$ZodCheckEndsWith",(e,t)=>{_t.init(e,t);const r=new RegExp(`.*${ei(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});function th(e,t,r){e.issues.length&&t.issues.push(...fr(r,e.issues))}var bS=x("$ZodCheckProperties",(e,t)=>{_t.init(e,t),Sl(e,Symbol.iterator,function*(){yield e});let r;e._zod.check=n=>{if(n.value==null){n.issues.push({expected:"object",code:"invalid_type",input:n.value,inst:e});return}r??(r=Reflect.ownKeys(t.shape).map(o=>[o,t.shape[o]]));const i=n.value;let s;for(const[o,a]of r){const c=a._zod.run({value:i[o],issues:[]},{});c instanceof Promise?(s??(s=[]),s.push(c.then(u=>th(u,n,o)))):th(c,n,o)}if(s)return Promise.all(s).then(()=>{})}}),wS=x("$ZodCheckOverwrite",(e,t)=>{_t.init(e,t),e._zod.check=r=>{r.value=t.tx(r.value)}}),SS=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const t=e.split(`
|
|
2
|
+
`).filter(i=>i),r=Math.min(...t.map(i=>i.length-i.trimStart().length)),n=t.map(i=>i.slice(r)).map(i=>" ".repeat(this.indent*2)+i);for(const i of n)this.content.push(i)}compile(){const e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
|
|
3
|
+
${t.join(`
|
|
4
|
+
`)}
|
|
5
|
+
};`)(...Object.values(this.closed))}},ES={major:4,minor:6,patch:5},Me=x("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=ES;const n=e._zod.def.checks,i=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(const s of i)for(const o of s._zod.onattach)o(e);if(i.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{const s=(a,c,u)=>{if(a.memo)return a;let l=qt(a),h;for(const d of c){if(d._zod.def.when){if(ew(a)||!d._zod.def.when(a))continue}else if(l)continue;const p=a.issues.length,f=d._zod.check(a);if(f instanceof Promise&&u?.async===!1)throw new fn;if(h||f instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await f,a.issues.length!==p&&(Kd(a.issues,p,e),l||(l=qt(a,p)))});else{if(a.issues.length===p)continue;Kd(a.issues,p,e),l||(l=qt(a,p))}}return h?h.then(()=>a):a},o=(a,c,u)=>{if(qt(a))return a.aborted=!0,a;const l=s(c,i,u);if(l instanceof Promise){if(u.async===!1)throw new fn;return l.then(h=>e._zod.parse(h,u))}return e._zod.parse(l,u)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){const l=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});return l instanceof Promise?l.then(h=>o(h,a,c)):o(l,a,c)}const u=e._zod.parse(a,c);if(u instanceof Promise){if(c.async===!1)throw new fn;return u.then(l=>s(l,i,c))}return s(u,i,c)}}},{get"~standard"(){return Sl(this,"~standard",Uv(this))},set"~standard"(e){jr(this,"~standard",e)}}),zv=(e,t)=>e.issues.length?{issues:e.issues.map(r=>qr(r,t,er()))}:{value:e.value};async function kS(e,t){const r={async:!0};return zv(await e._zod.run({value:t,issues:[]},r),r)}function Uv(e){return{validate:t=>{const r={async:!1};try{const n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return zv(n,r)}catch{}return kS(e,t)},vendor:"zod",version:1}}var Rl=x("$ZodString",(e,t)=>{Me.init(e,t),e._zod.pattern=t.pattern??rS,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),We=x("$ZodStringFormat",(e,t)=>{pa.init(e,t),Rl.init(e,t)}),IS=x("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=Fw),We.init(e,t)}),AS=x("$ZodUUID",(e,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=eh(r))}else t.pattern??(t.pattern=eh());We.init(e,t)}),TS=x("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=qw),We.init(e,t)});function Fv(e){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function RS(e,t){return!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t)?Fv(e)||2:PS(e,t)}function PS(e,t){if(!t.normalize&&t.protocol?.source===Kw.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<"u"){const r=URL;if(typeof r.parse=="function")return r.parse(e)??2}return new URL(e)}catch{return 2}}var OS=/[\t\n\r]/g;function rh(e){return e.replace(OS,"")}function CS(e,t){return t.lastIndex=0,t.test(e.hostname)}function $S(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var xS=x("$ZodURL",(e,t)=>{We.init(e,t),e._zod.check=r=>{try{const n=r.value.trim(),i=RS(n,t);if(i===1){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(i===2){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(i===!0){r.value=rh(n);return}t.hostname&&!CS(i,t.hostname)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort}),t.protocol&&!$S(i,t.protocol)&&r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort}),r.value=t.normalize?i.href:rh(n);return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),MS=x("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=Hw()),We.init(e,t)}),LS=x("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw new Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Dw:zw(t.length)),We.init(e,t)}),NS=x("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=$w),We.init(e,t)}),DS=x("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=xw),We.init(e,t)}),zS=x("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Mw),We.init(e,t)}),US=x("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Lw),We.init(e,t)}),FS=x("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Nw),We.init(e,t)}),qS=x("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=tS(t)),We.init(e,t)}),jS=x("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Qw),We.init(e,t)}),HS=x("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=eS(t)),We.init(e,t)}),BS=x("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Uw),We.init(e,t)}),VS=x("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=Bw),We.init(e,t)}),GS=/^[0-9a-fA-F:.]+$/;function qv(e){return GS.test(e)?Fv(`http://[${e}]`):!1}var ZS=x("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Vw),We.init(e,t),e._zod.check=r=>{qv(r.value)||r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}}),WS=x("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=Gw),We.init(e,t)});function JS(e){const t=e.split("/");if(t.length!==2)return!1;const[r,n]=t;if(!n)return!1;const i=Number(n);return`${i}`!==n||i<0||i>128?!1:qv(r)}var KS=x("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=Zw),We.init(e,t),e._zod.check=r=>{JS(r.value)||r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function jv(e){if(e==="")return!0;if(/\s/.test(e)||e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Hv=/^[0-9a-zA-Z+/]*={0,2}$/,YS=x("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Hv),We.init(e,t),e._zod.check=r=>{jv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Pl=/^[A-Za-z0-9_-]*$/;function XS(e){if(!Pl.test(e))return!1;const t=e.replace(/[-_]/g,r=>r==="-"?"+":"/");return jv(t.padEnd(Math.ceil(t.length/4)*4,"="))}var QS=x("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Pl),We.init(e,t),e._zod.check=r=>{XS(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),eE=x("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Yw),We.init(e,t)});function tE(e,t=null){try{const r=e.split(".");if(r.length!==3)return!1;const[n]=r;if(!n)return!1;const i=JSON.parse(atob(n));return!("typ"in i&&i?.typ!=="JWT"||!i.alg||t&&(!("alg"in i)||i.alg!==t))}catch{return!1}}var rE=x("$ZodJWT",(e,t)=>{We.init(e,t),e._zod.check=r=>{tE(r.value,t.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}}),Bv=x("$ZodNumber",(e,t)=>{Me.init(e,t),e._zod.pattern=Al,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch{}const i=r.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return r;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:String(i):void 0;return r.issues.push({expected:"number",code:"invalid_type",input:i,inst:e,...s?{received:s}:{}}),r}}),nE=x("$ZodNumberFormat",(e,t)=>{lS.init(e,t),Bv.init(e,t)}),iE=x("$ZodBoolean",(e,t)=>{Me.init(e,t),e._zod.pattern=iS,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=!!r.value}catch{}const i=r.value;return typeof i=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:i,inst:e}),r}}),sE=x("$ZodUndefined",(e,t)=>{Me.init(e,t),e._zod.pattern=oS,e._zod.values=new Set([void 0]),e._zod.parse=(r,n)=>{const i=r.value;return typeof i>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:i,inst:e}),r}}),oE=x("$ZodNull",(e,t)=>{Me.init(e,t),e._zod.pattern=sS,e._zod.values=new Set([null]),e._zod.parse=(r,n)=>{const i=r.value;return i===null||r.issues.push({expected:"null",code:"invalid_type",input:i,inst:e}),r}}),aE=x("$ZodAny",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),cE=x("$ZodUnknown",(e,t)=>{Me.init(e,t),e._zod.parse=r=>r}),uE=x("$ZodNever",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function nh(e,t,r){e.issues.length&&t.issues.push(...fr(r,e.issues)),t.value[r]=e.value}var lE=x("$ZodArray",(e,t)=>{Me.init(e,t);const r=$t.memoizer;r?.attach(e),e._zod.parse=(n,i)=>{const s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=r?r.alloc(e,n,Array(s.length),i):Array(s.length);const o=[],a=i?.abortEarly;for(let c=0;c<s.length;c++){const u=s[c],l=t.element._zod.run({value:u,issues:[]},i);if(l instanceof Promise)o.push(l.then(h=>nh(h,n,c)));else if(nh(l,n,c),a&&l.issues.length!==0&&qt(l))break}return o.length?Promise.all(o).then(()=>n):n}});function Io(e,t,r,n,i,s){const o=r in n,a=s==="optional";if(!(!o&&a&&i==="optional")){if(e.issues.length){if(i!==void 0&&a&&!o)return;t.issues.push(...fr(r,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}e.value===void 0?(o||i==="defaulted"&&!a)&&(t.value[r]=void 0):t.value[r]=e.value}}var dE=[];function Vv(e){const t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:dE,i=n.length?[...t,...n]:t;for(const o of i)if(!e.shape?.[o]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(o)}": expected a Zod schema`);const s=Gb(e.shape);return{...e,allKeys:i,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Gv(e,t,r,n,i,s,o){const a=[],c=i.keySet,u=i.catchall._zod,l=u.def.type,h=u.optin,d=u.optout;let p=0;for(const f in t){if(o&&r.issues.length!==p){if(qt(r,p))break;p=r.issues.length}if(c.has(f))continue;if(f==="__proto__"){l==="never"&&a.push(f);continue}if(l==="never"){a.push(f);continue}const v=u.run({value:t[f],issues:[]},n);v instanceof Promise?e.push(v.then(g=>Io(g,r,f,t,h,d))):Io(v,r,f,t,h,d)}return a.length&&r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0}),e.length?Promise.all(e).then(()=>r):r}var hE=x("$ZodObject",(e,t)=>{Me.init(e,t);const r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){const u=()=>{const l={...n};return Object.defineProperty(t,"shape",{value:l}),u.raw=l,l};u.raw=n,Object.defineProperty(t,"shape",{get:u})}const i=ua(()=>Vv(t));Te(e,"propValues",u=>{const l=u.def.shape,h={};for(const d in l){const p=l[d]._zod;if(p.values){Object.prototype.hasOwnProperty.call(h,d)||rr(h,d,new Set);for(const f of p.values)h[d].add(f);p.optin!==void 0&&h[d].add(void 0)}}return h});const s=as,o=t.catchall;let a;const c=$t.memoizer;c?.attach(e),e._zod.parse=(u,l)=>{a??(a=i.value);const h=u.value;if(!s(h))return u.issues.push({expected:"object",code:"invalid_type",input:h,inst:e}),u;u.value=c?c.alloc(e,u,{},l):{};const d=[],p=a.shape,f=l?.abortEarly;let v=u.issues.length;for(const g of a.allKeys){if(f&&u.issues.length!==v){if(qt(u,v))break;v=u.issues.length}if(g==="__proto__")continue;const m=p[g],w=m._zod.optin,S=m._zod.optout,O=m._zod.run({value:h[g],issues:[]},l);O instanceof Promise?d.push(O.then(R=>Io(R,u,g,h,w,S))):Io(O,u,g,h,w,S)}return o?Gv(d,h,u,l,i.value,e,f===!0):d.length?Promise.all(d).then(()=>u):u}}),pE=x("$ZodObjectJIT",(e,t)=>{hE.init(e,t);const r=e._zod.parse,n=ua(()=>Vv(t)),i=$t.memoizer,s=p=>{const f=n.value,v=f.symbolKeys,g=new SS(["payload","ctx"],{shape:p,inst:e,memo:i,syms:v}),m=R=>`shape[${R}]._zod.run({ value: input[${R}], issues: [] }, ctx)`,w=(R,I)=>`
|
|
6
|
+
let ${R}_ab = false;
|
|
7
|
+
for (let i = 0; i < ${R}.issues.length; i++) {
|
|
8
|
+
const iss = ${R}.issues[i];
|
|
9
|
+
iss.path = iss.path ? [${I}, ...iss.path] : [${I}];
|
|
10
|
+
payload.issues.push(iss);
|
|
11
|
+
if (iss.continue !== true) ${R}_ab = true;
|
|
12
|
+
}
|
|
13
|
+
if (${R}_ab && ctx && ctx.abortEarly) {
|
|
14
|
+
payload.value = newResult;
|
|
15
|
+
return payload;
|
|
16
|
+
}`;g.write("const input = payload.value;");const S=Object.create(null);let O=0;for(const R of f.allKeys)S[R]=`key_${O++}`;g.write(i?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(const R of f.allKeys){if(R==="__proto__")continue;const I=S[R],C=typeof R=="symbol"?`syms[${v.indexOf(R)}]`:jb(R),L=`${C} in input`,q=p[R],K=q?._zod?.optin,X=K!==void 0,k=q?._zod?.optout==="optional";if(g.write(`const ${I} = ${m(C)};`),X&&k){const ne=K==="optional"?`${I}_present`:`${I}.value !== undefined || ${I}_present`;g.write(`
|
|
17
|
+
const ${I}_present = ${L};
|
|
18
|
+
if (!${I}.issues.length || ${I}_present) {
|
|
19
|
+
if (${I}.issues.length) {${w(I,C)}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (${ne}) {
|
|
23
|
+
newResult[${C}] = ${I}.value;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
`)}else X?(g.write(`
|
|
28
|
+
if (${I}.issues.length) {${w(I,C)}
|
|
29
|
+
}
|
|
30
|
+
`),K==="defaulted"?g.write(`newResult[${C}] = ${I}.value;`):g.write(`
|
|
31
|
+
if (${I}.value !== undefined || ${L}) {
|
|
32
|
+
newResult[${C}] = ${I}.value;
|
|
33
|
+
}
|
|
34
|
+
`)):g.write(`
|
|
35
|
+
const ${I}_present = ${L};
|
|
36
|
+
if (${I}.issues.length) {${w(I,C)}
|
|
37
|
+
}
|
|
38
|
+
if (!${I}_present && !${I}.issues.length) {
|
|
39
|
+
payload.issues.push({
|
|
40
|
+
code: "invalid_type",
|
|
41
|
+
expected: "nonoptional",
|
|
42
|
+
input: undefined,
|
|
43
|
+
path: [${C}]
|
|
44
|
+
});
|
|
45
|
+
if (ctx && ctx.abortEarly) {
|
|
46
|
+
payload.value = newResult;
|
|
47
|
+
return payload;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (${I}_present) {
|
|
52
|
+
newResult[${C}] = ${I}.value;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
`)}return g.write("payload.value = newResult;"),g.write("return payload;"),g.compile()};let o;const a=as,c=!$t.jitless,l=c&&Bb.value,h=t.catchall;let d;e._zod.parse=(p,f)=>{d??(d=n.value);const v=p.value;return a(v)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||(o=s(t.shape)),p=o(p,f),h?Gv([],v,p,f,d,e,f?.abortEarly===!0):p):r(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:v,inst:e}),p)}});function ih(e,t,r,n){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!qt(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map(s=>s.issues.map(o=>qr(o,n,er())))}),t)}var Zv=x("$ZodUnion",(e,t)=>{Me.init(e,t),Te(e,"optin",n=>n.def.options.some(i=>i._zod.optin==="defaulted")?"defaulted":n.def.options.some(i=>i._zod.optin!==void 0)?"optional":void 0),Te(e,"optout",n=>n.def.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Te(e,"values",n=>{if(n.def.options.every(i=>i._zod.values))return new Set(n.def.options.flatMap(i=>Array.from(i._zod.values)))}),Te(e,"pattern",n=>{if(n.def.options.every(i=>i._zod.pattern)){const i=n.def.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>_l(s.source)).join("|")})$`)}});const r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,i)=>{if(r)return r(n,i);let s=!1;const o=[];for(const a of t.options){const c=a._zod.run({value:n.value,issues:[]},i);if(c instanceof Promise)o.push(c),s=!0;else{if(c.issues.length===0)return c;o.push(c)}}return s?Promise.all(o).then(a=>ih(a,n,e,i)):ih(o,n,e,i)}});function fE(e){const t=new Map;for(const r of e.options){const n=r._zod.propValues?.[e.discriminator];if(!n||n.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(r)}"`);for(const i of n)if(t.has(i)){if(i!==void 0)throw new Error(`Duplicate discriminator value "${String(i)}"`);t.set(i,null)}else t.set(i,r)}return t}var vE=x("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Zv.init(e,t);const r=e._zod.parse;Te(e,"propValues",i=>{const s={};let o=0;for(const a of i.def.options){const c=a._zod.propValues;if(!c||Object.keys(c).length===0)throw new Error(`Invalid discriminated union option at index "${i.def.options.indexOf(a)}"`);c[i.def.discriminator]?.has(void 0)&&o++;for(const[u,l]of Object.entries(c)){Object.prototype.hasOwnProperty.call(s,u)||rr(s,u,new Set);for(const h of l)s[u].add(h)}}return!i.def.unionFallback&&o>1&&s[i.def.discriminator]?.delete(void 0),s}),t.options.forEach((i,s)=>{const o=yl(i._zod.def);if(o&&!Object.prototype.hasOwnProperty.call(o,t.discriminator))throw new Error(`Invalid discriminated union option at index "${s}"`)});const n=ua(()=>fE(t));e._zod.parse=(i,s)=>{const o=i.value;if(!as(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;const a=o?.[t.discriminator],c=n.value.get(a);return c&&(a!==void 0||s.direction!=="backward")?c._zod.run(i,s):t.unionFallback||s.direction==="backward"?r(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,options:Array.from(n.value.keys()).filter(u=>n.value.get(u)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),gE=x("$ZodIntersection",(e,t)=>{Me.init(e,t),e._zod.parse=(r,n)=>{const i=r.value,s=t.left._zod.run({value:i,issues:[]},n),o=t.right._zod.run({value:i,issues:[]},n);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([a,c])=>sh(r,a,c)):sh(r,s,o)}});function ru(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Qn(e)&&Qn(t)){const r=Object.keys(t),n=Object.keys(e).filter(s=>r.indexOf(s)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,"__proto__")&&delete i.__proto__;for(const s of n){if(s==="__proto__")continue;const o=ru(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const r=[];for(let n=0;n<e.length;n++){const i=e[n],s=t[n],o=ru(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[n,...o.mergeErrorPath]};r.push(o.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function sh(e,t,r){const n=new Map;let i;const s=new Map,o=(u,l)=>{let h;if(u.code==="unrecognized_keys"&&!u.path?.length)i??(i=u),h=u.keys;else if(u.code==="invalid_key"&&u.origin==="record"&&u.path?.length===1){const d=String(u.path[0]);s.has(d)||s.set(d,u),h=[d]}else return!1;for(const d of h)n.has(d)||n.set(d,{}),n.get(d)[l]=!0;return!0};for(const u of t.issues)o(u,"l")||e.issues.push(u);for(const u of r.issues)o(u,"r")||e.issues.push(u);const a=[...n].filter(([,u])=>u.l&&u.r).map(([u])=>u);if(a.length){const u=i?a.filter(l=>i.keys.includes(l)):[];u.length&&e.issues.push({...i,keys:u});for(const l of a)!u.includes(l)&&s.has(l)&&e.issues.push(s.get(l))}const c=ru(t.value,r.value);if(!c.valid){if(qt(e))return e;throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var mE=x("$ZodTuple",(e,t)=>{Me.init(e,t);const r=t.items,n=$t.memoizer;n?.attach(e),e._zod.parse=(i,s)=>{const o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:"tuple",code:"invalid_type"}),i;i.value=n?n.alloc(e,i,[],s):[];const a=[],c=oh(r,"optin"),u=oh(r,"optout");if(!t.rest){if(o.length<c)return i.issues.push({code:"too_small",minimum:c,inclusive:!0,input:o,inst:e,origin:"array"}),i;o.length>r.length&&i.issues.push({code:"too_big",maximum:r.length,inclusive:!0,input:o,inst:e,origin:"array"})}const l=new Array(r.length),h=t.rest?s?.abortEarly:void 0;let d=!1;for(let p=0;p<r.length;p++){const f=r[p]._zod.run({value:o[p],issues:[]},s);f instanceof Promise?a.push(f.then(v=>{l[p]=v})):(l[p]=f,h&&!d&&f.issues.length&&(d=qt(f)))}if(t.rest&&!d){let p=r.length-1;const f=o.slice(r.length);let v=i.issues.length;for(const g of f){if(h&&i.issues.length!==v){if(qt(i,v))break;v=i.issues.length}p++;const m=t.rest._zod.run({value:g,issues:[]},s);m instanceof Promise?a.push(m.then(w=>ah(w,i,p))):ah(m,i,p)}}return a.length?Promise.all(a).then(()=>ch(l,i,r,o,u)):ch(l,i,r,o,u)}});function oh(e,t){for(let r=e.length-1;r>=0;r--)if(!(t==="optin"?e[r]._zod.optin!==void 0:e[r]._zod.optout==="optional"))return r+1;return 0}function ah(e,t,r){e.issues.length&&t.issues.push(...fr(r,e.issues)),t.value[r]=e.value}function ch(e,t,r,n,i){for(let s=0;s<r.length;s++){const o=e[s],a=s<n.length;if(!a&&s>=i&&r[s]._zod.optin==="optional"){t.value.length=s;break}if(o.issues.length){if(!a&&s>=i){t.value.length=s;break}t.issues.push(...fr(s,o.issues))}t.value[s]=o.value}for(let s=t.value.length-1;s>=n.length&&(r[s]._zod.optout==="optional"&&t.value[s]===void 0);s--)t.value.length=s;return t}var _E=x("$ZodRecord",(e,t)=>{Me.init(e,t);const r=$t.memoizer;r?.attach(e),e._zod.parse=(n,i)=>{const s=n.value;if(!Qn(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;const o=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},i):{};const c=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){if(c.add(typeof l=="number"?l.toString():l),l==="__proto__")continue;const h=t.keyType._zod.run({value:l,issues:[]},i);if(h instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(h.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:h.issues.map(f=>qr(f,i,er())),input:l,path:[l],inst:e});continue}const d=h.value;if(d==="__proto__")continue;const p=t.valueType._zod.run({value:s[l],issues:[]},i);p instanceof Promise?o.push(p.then(f=>{f.issues.length&&n.issues.push(...fr(l,f.issues)),n.value[d]=f.value})):(p.issues.length&&n.issues.push(...fr(l,p.issues)),n.value[d]=p.value)}let u;for(const l in s)if(!c.has(l))if(t.mode==="loose"){if(l==="__proto__")continue;n.value[l]=s[l]}else u=u??[],u.push(l);u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:u,continue:!0})}else{n.value=r?r.alloc(e,n,{},i):{};let c;for(const u of Reflect.ownKeys(s)){if(u==="__proto__"||!Object.prototype.propertyIsEnumerable.call(s,u))continue;let l=t.keyType._zod.run({value:u,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof u=="string"&&Al.test(u)&&l.issues.length){const p=t.keyType._zod.run({value:Number(u),issues:[]},i);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(l=p)}if(l.issues.length){t.mode==="loose"?n.value[u]=s[u]:a?(c=c??[],c.push(u)):n.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(p=>qr(p,i,er())),input:u,path:[u],inst:e});continue}const h=l.value;if(h==="__proto__")continue;const d=t.valueType._zod.run({value:s[u],issues:[]},i);d instanceof Promise?o.push(d.then(p=>{p.issues.length&&n.issues.push(...fr(u,p.issues)),n.value[h]=p.value})):(d.issues.length&&n.issues.push(...fr(u,d.issues)),n.value[h]=d.value)}c&&c.length>0&&n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>n):n}}),yE=x("$ZodEnum",(e,t)=>{Me.init(e,t);const r=Qc(t.entries),n=new Set(r);e._zod.values=n,Te(e,"pattern",i=>{const s=Qc(i.def.entries).filter(o=>Vb.has(typeof o));return new RegExp(s.length?`^(${s.map(o=>ei(o.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(i,s)=>{const o=i.value;return n.has(o)||i.issues.push({code:"invalid_value",values:r,input:o,inst:e}),i}}),bE=x("$ZodLiteral",(e,t)=>{Me.init(e,t);const r=new Set(t.values);e._zod.values=r,Te(e,"pattern",n=>{const i=n.def.values;return new RegExp(i.length?`^(${i.map(s=>typeof s=="string"?ei(s):s?ei(s.toString()):String(s)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(n,i)=>{const s=n.value;return r.has(s)||n.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),n}}),wE=x("$ZodTransform",(e,t)=>{Me.init(e,t),e._zod.optin="optional",$t.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new $v(e.constructor.name);const i=t.transform(r.value,r);if(n.async)return(i instanceof Promise?i:Promise.resolve(i)).then(s=>(r.value=s,r));if(i instanceof Promise)throw new fn;return r.value=i,r}});function uh(e,t){return e.value=t.issues.length?void 0:t.value,e}var Wv=x("$ZodOptional",(e,t)=>{Me.init(e,t),Te(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",Te(e,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),Te(e,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${_l(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;const i=t.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(s=>uh(r,s)):uh(r,i)}return t.innerType._zod.run(r,n)}}),SE=x("$ZodExactOptional",(e,t)=>{Wv.init(e,t),Te(e,"values",r=>r.def.innerType._zod.values),Te(e,"pattern",r=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),EE=x("$ZodNullable",(e,t)=>{Me.init(e,t),Te(e,"optin",r=>r.def.innerType._zod.optin),Te(e,"optout",r=>r.def.innerType._zod.optout),Te(e,"pattern",r=>{const n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${_l(n.source)}|null)$`):void 0}),Te(e,"values",r=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>r.value===null?r:t.innerType._zod.run(r,n)}),kE=x("$ZodDefault",(e,t)=>{Me.init(e,t),e._zod.optin="defaulted",Te(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>lh(s,t)):lh(i,t)}});function lh(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var IE=x("$ZodPrefault",(e,t)=>{Me.init(e,t),e._zod.optin="defaulted",Te(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>(n.direction==="backward"||r.value===void 0&&(r.value=t.defaultValue),t.innerType._zod.run(r,n))}),AE=x("$ZodNonOptional",(e,t)=>{Me.init(e,t),Te(e,"values",r=>{const n=r.def.innerType._zod.values;return n?new Set([...n].filter(i=>i!==void 0)):void 0}),e._zod.parse=(r,n)=>{const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(s=>dh(s,e)):dh(i,e)}});function dh(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}function hh(e,t,r,n){return t.issues.length?(e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map(i=>qr(i,n,er()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var TE=x("$ZodCatch",(e,t)=>{Me.init(e,t),Te(e,"optin",r=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),Te(e,"optout",r=>r.def.innerType._zod.optout),Te(e,"values",r=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run({value:r.value,issues:[]},n);return i instanceof Promise?i.then(s=>hh(r,s,t,n)):hh(r,i,t,n)}}),Jv=x("$ZodPipe",(e,t)=>{Me.init(e,t),Te(e,"values",r=>r.def.in._zod.values),Te(e,"optin",r=>r.def.in._zod.optin),Te(e,"optout",r=>r.def.out._zod.optout),Te(e,"propValues",r=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){const s=t.out._zod.run(r,n);return s instanceof Promise?s.then(o=>$s(o,t.in,n)):$s(s,t.in,n)}const i=t.in._zod.run(r,n);return i instanceof Promise?i.then(s=>$s(s,t.out,n)):$s(i,t.out,n)}});function $s(e,t,r){return e.issues.some(n=>n.code!=="unrecognized_keys")?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},r)}var RE=x("$ZodPreprocess",(e,t)=>{Jv.init(e,t)}),PE=x("$ZodReadonly",(e,t)=>{Me.init(e,t),Te(e,"propValues",r=>r.def.innerType._zod.propValues),Te(e,"values",r=>r.def.innerType._zod.values),Te(e,"optin",r=>r.def.innerType?._zod?.optin),Te(e,"optout",r=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);const i=t.innerType._zod.run(r,n);return i instanceof Promise?i.then(ph):ph(i)}});function ph(e){return e.memo||(e.value=Object.freeze(e.value)),e}var OE=x("$ZodLazy",(e,t)=>{Me.init(e,t),Fb(e._zod,"innerType",()=>{const r=t;return r._cachedInner||(r._cachedInner=t.getter()),r._cachedInner}),Te(e,"pattern",r=>r.innerType?._zod?.pattern),Te(e,"propValues",r=>r.innerType?._zod?.propValues),Te(e,"optin",r=>r.innerType?._zod?.optin??void 0),Te(e,"optout",r=>r.innerType?._zod?.optout??void 0),e._zod.parse=(r,n)=>e._zod.innerType._zod.run(r,n)}),CE=x("$ZodCustom",(e,t)=>{_t.init(e,t),Me.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=r=>{const n=r.value,i=t.fn(n);if(i instanceof Promise)return i.then(s=>fh(s,r,n,e));fh(i,r,n,e)}});function fh(e,t,r,n){if(!e){const i={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(i.params=n._zod.def.params),t.issues.push(cs(i))}}var $E=class extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform"),this.name="ZodCyclicError"}},nu="~memo",vh=[];function Kv(e){return e!==null&&typeof e=="object"}function ec(e){return e.map(t=>t.path?{...t,path:t.path.slice()}:{...t})}var Yv=new WeakMap,Di=0,no=1,Hi=2;function io(e,t,r){const n=Yv.get(e);if(n!==void 0)return n?Hi:Di;if(t.has(e))return Hi;t.add(e);let i=Di;const s=u=>{if(i!==Hi&&u?._zod){const l=io(u,t,r);l>i&&(i=l)}},o=(u,l)=>{let h=Di;for(const d of Reflect.ownKeys(u)){const p=Object.getOwnPropertyDescriptor(u,d);if(l&&!p.enumerable)continue;const f=p.get?no:p.value?._zod?io(p.value,t,r):Di;f>h&&(h=f)}return h},a=u=>{u>i&&(i=u)},c=e._zod.def;switch(c.type){case"object":{const u=yl(c);a(u?o(u,!0):no),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(const u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(const u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{const u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?io(u,t,!1):no);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(const u in c){const l=Object.getOwnPropertyDescriptor(c,u);if(!l||l.get)continue;const h=l.value;if(!(!h||typeof h!="object")){if(h._zod)s(h);else if(Array.isArray(h))for(const d of h)s(d)}}}return t.delete(e),xE(e,i)}function xE(e,t){return t!==no&&Yv.set(e,t===Hi),t}function ME(e,t){let r=e.buckets.get(t);return r||(r=new WeakMap,e.buckets.set(t,r)),r}var xs,Ms=[],LE={alloc(e,t,r){const n=xs;if(!n)return r;xs=void 0;const i={value:r,issues:null};return n.set(t.value,i),Ms.push(i),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const r=e._zod.parse,n=(i,s)=>{if(s.direction!=="backward"&&DE(s,i.value))throw new $E;return r(i,s)};e._zod.parse=n,e._zod.run===r&&(e._zod.run=n)})},attach(e){var t;let r,n=!1,i,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{const o=e._zod.parse,a=(c,u)=>{if(r===void 0){const m=io(e,new Set,!1);if(m===Di)return e._zod.parse=o,e._zod.run===a&&(e._zod.run=o),o(c,u);m===Hi||n?r=!0:n=!0}const l=c.value;if(!Kv(l))return o(c,u);let h=u[nu];h||(h={buckets:new WeakMap,backEdges:void 0},u[nu]=h);let d;i===u?d=s:(d=ME(h,e),i=u,s=d);const p=d.get(l);if(p)return c.value=p.value,p.issues?p.issues.length&&c.issues.push(...ec(p.issues)):(c.memo=!0,h.backEdges??(h.backEdges=new WeakSet),h.backEdges.add(p.value)),c;xs=d;const f=Ms.length,v=o(c,u);xs=void 0;const g=Ms.length>f?Ms.pop():void 0;return v instanceof Promise?v.then(m=>(g&&(g.issues=m.issues.length?ec(m.issues):vh),m)):(g&&(g.issues=v.issues.length?ec(v.issues):vh),v)};e._zod.parse=a,e._zod.run===o&&(e._zod.run=a)})}};function NE(){return LE}function DE(e,t){const r=e[nu]?.backEdges;return r!==void 0&&Kv(t)&&r.has(t)}var zE=()=>{const e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}const r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function i(s,o){return s==="number"&&typeof o=="number"&&!Number.isFinite(o)?String(o):n[s]??s}return s=>{switch(s.code){case"invalid_type":return`Invalid input: expected ${i(s.expected)}, received ${i(rw(s.input),s.input)}`;case"invalid_value":return s.values.length===1?`Invalid input: expected ${Rv(s.values[0])}`:`Invalid option: expected one of ${Zd(s.values,"|")}`;case"too_big":{const o=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);return a?`Too big: expected ${s.origin??"value"} to have ${o}${s.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${s.origin??"value"} to be ${o}${s.maximum.toString()}`}case"too_small":{const o=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);return a?`Too small: expected ${s.origin} to have ${o}${s.minimum.toString()} ${a.unit}`:`Too small: expected ${s.origin} to be ${o}${s.minimum.toString()}`}case"invalid_format":{const o=s;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Zd(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":return s.options&&Array.isArray(s.options)&&s.options.length>0?`Invalid discriminator value. Expected ${s.options.map(o=>`'${o}'`).join(" | ")}`:s.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function UE(){return{localeError:zE()}}var gh,FE=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){const r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};delete r.id;const n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function qE(){return new FE}(gh=globalThis).__zod_globalRegistry??(gh.__zod_globalRegistry=qE());var zi=globalThis.__zod_globalRegistry;function Xv(e){return e.checks&&(e.checks=[...e.checks]),e}function jE(e,t){return new e(Xv({type:"string",...te(t)}))}function HE(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...te(t)})}function BE(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...te(t)})}function VE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...te(t)})}function GE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...te(t)})}function ZE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...te(t)})}function WE(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...te(t)})}function JE(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...te(t)})}function KE(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...te(t)})}function YE(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...te(t)})}function XE(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...te(t)})}function QE(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...te(t)})}function ek(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...te(t)})}function tk(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...te(t)})}function rk(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...te(t)})}function nk(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...te(t)})}function ik(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...te(t)})}function sk(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...te(t)})}function ok(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...te(t)})}function ak(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...te(t)})}function ck(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...te(t)})}function uk(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...te(t)})}function lk(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...te(t)})}function dk(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...te(t)})}function hk(e,t){return new e({type:"string",format:"date",check:"string_format",...te(t)})}function pk(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...te(t)})}function fk(e,t){return new e({type:"string",format:"duration",check:"string_format",...te(t)})}function vk(e,t){return new e(Xv({type:"number",checks:[],...te(t)}))}function gk(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...te(t)})}function mk(e,t){return new e({type:"boolean",...te(t)})}function _k(e,t){return new e({type:"undefined",...te(t)})}function yk(e,t){return new e({type:"null",...te(t)})}function bk(e){return new e({type:"any"})}function wk(e){return new e({type:"unknown"})}function Sk(e,t){return new e({type:"never",...te(t)})}function mh(e,t){return new Nv({check:"less_than",...te(t),value:e,inclusive:!1})}function tc(e,t){return new Nv({check:"less_than",...te(t),value:e,inclusive:!0})}function _h(e,t){return new Dv({check:"greater_than",...te(t),value:e,inclusive:!1})}function rc(e,t){return new Dv({check:"greater_than",...te(t),value:e,inclusive:!0})}function yh(e,t){return new uS({check:"multiple_of",...te(t),value:e})}function Qv(e,t){return new dS({check:"max_length",...te(t),maximum:e})}function Ao(e,t){return new hS({check:"min_length",...te(t),minimum:e})}function eg(e,t){return new pS({check:"length_equals",...te(t),length:e})}function Ek(e,t){return new fS({check:"string_format",format:"regex",...te(t),pattern:e})}function kk(e){return new vS({check:"string_format",format:"lowercase",...te(e)})}function Ik(e){return new gS({check:"string_format",format:"uppercase",...te(e)})}function Ak(e,t){return new mS({check:"string_format",format:"includes",...te(t),includes:e})}function Tk(e,t){return new _S({check:"string_format",format:"starts_with",...te(t),prefix:e})}function Rk(e,t){return new yS({check:"string_format",format:"ends_with",...te(t),suffix:e})}function Pk(e,t){return new bS({check:"properties",shape:e,...te(t)})}function gi(e){return new wS({check:"overwrite",tx:e})}function Ok(e){return gi(t=>t.normalize(e))}function Ck(){return gi(e=>e.trim())}function $k(){return gi(e=>e.toLowerCase())}function xk(){return gi(e=>e.toUpperCase())}function Mk(){return gi(e=>Hb(e))}function Lk(e,t,r){return new e({type:"array",element:t,...te(r)})}function Nk(e,t,r){const n=te(r);return n.abort??(n.abort=!0),new e({type:"custom",check:"custom",fn:t,...n})}function Dk(e,t,r){return new e({type:"custom",check:"custom",fn:t,...te(r)})}function zk(e,t){const r=Uk(n=>(n.addIssue=i=>{if(typeof i=="string")n.issues.push(cs(i,n.value,r._zod.def));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),"input"in s||(s.input=n.value),s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(cs(s))}},e(n.value,n)),t);return r}function Uk(e,t){const r=new _t({check:"custom",...te(t)});return r._zod.check=e,r}function Bi(e,...t){for(const r of t)for(const n of Reflect.ownKeys(r))Object.prototype.propertyIsEnumerable.call(r,n)&&rr(e,n,r[n]);return e}function To(e){let t=e?.target??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:e?.metadata??zi,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function ut(e,t,r,n,i){const s=typeof t.unrepresentable=="function"?t.unrepresentable({zodSchema:e,path:n.path,message:i}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw new Error(i);return Object.assign(r,s),!0}function Fe(e,t,r={path:[],schemaPath:[]}){var n;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,r.schemaPath.includes(e)&&(s.cycle=r.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;const a=e._zod.toJSONSchema?.();if(a)o.schema=a;else{const u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,u);else{const h=o.schema,d=t.processors[i.type];if(!d)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);d(e,t,h,u)}const l=e._zod.parent;l&&(o.ref||(o.ref=l),Fe(l,t,u),t.seen.get(l).isParent=!0)}const c=t.metadataRegistry.get(e);return c&&Bi(o.schema,c),t.io==="input"&&ht(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&"_prefault"in o.schema&&((n=o.schema).default??(n.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function bh(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Ro(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;const n=new Map;for(const o of e.seen.entries()){const a=e.metadataRegistry.get(o[0])?.id;if(a){const c=n.get(a);if(c&&c!==o[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,o[0])}}const i=o=>{const a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const h=e.external.registry.get(o[0])?.id,d=e.external.uri??(f=>f);if(h)return{ref:d(h)};const p=o[1].defId??o[1].schema.id??`schema${e.counter++}`;return o[1].defId=p,{defId:p,ref:`${d("__shared")}#/${a}/${bh(p)}`}}const c="#",u=`${c}/${a}/`;if(o[1]===r&&!o[1].schema.id)return{ref:c};const l=o[1].schema.id??`__schema${e.counter++}`;return{defId:l,ref:u+bh(l)}},s=o=>{if(o[1].schema.$ref)return;const a=o[1],{ref:c,defId:u}=i(o);a.def={...a.schema},u&&(a.defId=u);const l=a.schema;for(const h in l)delete l[h];l.$ref=c};if(e.cycles==="throw")for(const o of e.seen.entries()){const a=o[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
|
|
56
|
+
|
|
57
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const o of e.seen.entries()){const a=o[1];if(t===o[0]){s(o);continue}if(e.external){const c=e.external.registry.get(o[0])?.id;if(t!==o[0]&&c){s(o);continue}}if(e.metadataRegistry.get(o[0])?.id){s(o);continue}if(a.cycle){s(o);continue}a.count>1&&e.reused==="ref"&&s(o)}e.external&&(e.sharedDefsExtractedFor=e.external)}function tg(e){const t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;const r=[];for(const n of t){if(!n||typeof n!="object")return;tg(n);const i=Object.keys(n);if(i.length!==1||i[0]!=="type")return;const s=n.type;for(const o of Array.isArray(s)?s:[s]){if(typeof o!="string")return;r.includes(o)||r.push(o)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var rg=new Set(["type","properties","required","additionalProperties"]),wh=["oneOf","anyOf"];function Sh(e){const t=e.additionalProperties;return t===void 0||t===!1||typeof t!="object"||t===null?null:Object.keys(t).length?t:null}function iu(e){const t=[];for(const s of e){if(typeof s!="object"||s.type!=="object")return null;for(const o in s)if(!rg.has(o))return null;t.push(s)}const r={},n=new Set;for(const s of t){for(const o in s.properties){if(Object.prototype.hasOwnProperty.call(r,o))continue;const a=[];for(const u of t){const l=u.properties?.[o]??Sh(u);l!=null&&(a.some(h=>JSON.stringify(h)===JSON.stringify(l))||a.push(l))}const c=a.length===1?a[0]:iu(a)??{allOf:a};rr(r,o,c)}for(const o of s.required??[])n.add(o)}const i={type:"object",properties:r};if(n.size&&(i.required=[...n]),t.every(s=>s.additionalProperties===!1))i.additionalProperties=!1;else{const s=[];for(const o of t){const a=Sh(o);a&&!s.some(c=>JSON.stringify(c)===JSON.stringify(a))&&s.push(a)}s.length===1?i.additionalProperties=s[0]:s.length>1&&(i.additionalProperties={allOf:s})}return i}function Fk(e){const t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(const i of rg)if(i in e)return;const r=t.filter(i=>wh.some(s=>Array.isArray(i[s])));let n=null;if(!r.length)n=iu(t);else{const i=r[0],s=wh.find(c=>Array.isArray(i[c]));if(Object.keys(i).length!==1)return;const o=t.filter(c=>c!==i),a=i[s].map(c=>iu([...o,c]));if(a.some(c=>!c))return;n={[s]:a}}n&&(delete e.allOf,Bi(e,n))}function Po(e,t){const r=e.seen.get(t);if(!r)throw new Error("Unprocessed schema. This is a bug in Zod.");const n=a=>{const c=e.seen.get(a);if(c.ref===null)return;const u=c.def??c.schema,l={...u},h=c.ref;if(c.ref=null,h){n(h);const p=e.seen.get(h),f=p.schema;if(f.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(u.allOf=u.allOf??[],u.allOf.push(f)):Bi(u,f),Bi(u,l),a._zod.parent===h)for(const v in u)v==="$ref"||v==="allOf"||v in l||delete u[v];if(f.$ref&&p.def)for(const v in u)v==="$ref"||v==="allOf"||v in p.def&&JSON.stringify(u[v])===JSON.stringify(p.def[v])&&delete u[v]}const d=a._zod.parent;if(d&&d!==h){n(d);const p=e.seen.get(d);if(p?.schema.$ref&&(u.$ref=p.schema.$ref,p.def))for(const f in u)f==="$ref"||f==="allOf"||f in p.def&&JSON.stringify(u[f])===JSON.stringify(p.def[f])&&delete u[f]}e.override({zodSchema:a,jsonSchema:u,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(const a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(const a of e.seen.entries())tg(a[1].def??a[1].schema);for(const a of e.deferred)a();if(e.intersections.length){const a=new Map;for(const c of e.seen.values())for(const u of[c.schema,c.def]){const l=u?.allOf;if(!Array.isArray(l))continue;const h=a.get(l);h?h.push(u):a.set(l,[u])}for(const c of e.intersections)for(const u of a.get(c)??[])Fk(u)}}const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,e.external?.uri){const a=e.external.registry.get(t)?.id;if(!a)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(a)}Bi(i,r.defId?r.schema:r.def??r.schema);const s=e.metadataRegistry.get(t)?.id;s!==void 0&&i.id===s&&delete i.id;const o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(const a of e.seen.entries()){const c=a[1];c.def&&c.defId&&(c.def.id===c.defId&&delete c.def.id,rr(o,c.defId,c.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target==="draft-2020-12"?i.$defs=o:i.definitions=o);try{const a=JSON.parse(JSON.stringify(i));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Oo(t,"input",e.processors),output:Oo(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch{throw new Error("Error converting schema to JSON.")}}function ht(e,t){const r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);const n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return ht(n.element,r);if(n.type==="set")return ht(n.valueType,r);if(n.type==="lazy")return ht(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return ht(n.innerType,r);if(n.type==="intersection")return ht(n.left,r)||ht(n.right,r);if(n.type==="record"||n.type==="map")return ht(n.keyType,r)||ht(n.valueType,r);if(n.type==="pipe")return e._zod.traits.has("$ZodCodec")?!0:ht(n.in,r)||ht(n.out,r);if(n.type==="object"){for(const i in n.shape)if(ht(n.shape[i],r))return!0;return!1}if(n.type==="union"){for(const i of n.options)if(ht(i,r))return!0;return!1}if(n.type==="tuple"){for(const i of n.items)if(ht(i,r))return!0;return!!(n.rest&&ht(n.rest,r))}return!1}var qk=(e,t={})=>r=>{const n=To({...r,processors:t});return Fe(e,n),Ro(n,e),Po(n,e)},Oo=(e,t,r={})=>n=>{const{libraryOptions:i,target:s}=n??{},o=To({...i??{},target:s,io:t,processors:r});return Fe(e,o),Ro(o,e),Po(o,e)},ti=(e,t,r)=>{(e[t]===void 0||r>e[t])&&(e[t]=r)},ri=(e,t,r)=>{(e[t]===void 0||r<e[t])&&(e[t]=r)},Eh=(e,t)=>{ti(e,"minimum",t),ri(e,"maximum",t)},ng=(e,t)=>{e.multipleOf??(e.multipleOf=[]),e.multipleOf.includes(t)||e.multipleOf.push(t)},ig=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},sg=(e,t)=>{e.mime=e.mime?e.mime.filter(r=>t.includes(r)):[...t]},og=(e,t)=>{e.format=t,t.includes("int")&&(e.isInt=!0)},kh=(e,t)=>ti(e,"minimum",t.minimum),Ih=(e,t)=>ri(e,"maximum",t.maximum),Ah=e=>(t,r)=>{og(t,r.format);const[n,i]=e[r.format];ti(t,"minimum",n),ri(t,"maximum",i)},jk={greater_than:(e,t)=>ti(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ri(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>ng(e,t.value),number_format:Ah(Pv),bigint_format:Ah(Zb),min_length:kh,max_length:Ih,length_equals:(e,t)=>Eh(e,t.length),min_size:kh,max_size:Ih,size_equals:(e,t)=>Eh(e,t.size),string_format:(e,t)=>{og(e,t.format),t.pattern&&ig(e,t.pattern),(t.format==="base64"||t.format==="base64url")&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>sg(e,t.mime)};function At(e){const t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(const s of n)jk[s._zod.def.check]?.(t,s._zod.def);const i=e._zod.bag;i.minimum!==void 0&&ti(t,"minimum",i.minimum),i.exclusiveMinimum!==void 0&&ti(t,"exclusiveMinimum",i.exclusiveMinimum),i.maximum!==void 0&&ri(t,"maximum",i.maximum),i.exclusiveMaximum!==void 0&&ri(t,"exclusiveMaximum",i.exclusiveMaximum),i.multipleOf!==void 0&&ng(t,i.multipleOf),i.format!==void 0&&(t.format??(t.format=i.format),i.format.includes("int")&&(t.isInt=!0)),i.mime&&sg(t,i.mime);for(const s of i.patterns??[])ig(t,s);return t}var Hk={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Bk=new Map([[Hv,Ww],[Pl,Jw]]),ag=e=>Bk.get(e)??e,cg=(e,t,r,n)=>{const i=r;i.type="string";const{minimum:s,maximum:o,format:a,patterns:c,contentEncoding:u,laxFormat:l}=At(e);if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),a&&(i.format=Hk[a]??a,i.format===""&&delete i.format,(a==="time"||l)&&delete i.format),u&&(i.contentEncoding=u),c&&c.size>0){const h=[...c].map(ag);h.length===1?i.pattern=h[0].source:h.length>1&&(i.allOf=[...h.map(d=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},ug=(e,t,r,n)=>{const i=r,{minimum:s,maximum:o,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:u,isInt:l}=At(e);i.type=l?"integer":"number";const h=typeof u=="number"&&u>=(s??Number.NEGATIVE_INFINITY),d=typeof c=="number"&&c<=(o??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";if(h?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof s=="number"&&(i.minimum=s),d?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o=="number"&&(i.maximum=o),a){const f=new Set;for(const m of a)Number.isFinite(m)&&m!==0?f.add(Math.abs(m)):ut(e,t,i,n,`A multipleOf divisor of ${m} cannot be represented in JSON Schema`);const[v,...g]=f;v!==void 0&&(i.multipleOf=v),g.length&&(i.allOf=[...i.allOf??[],...g.map(m=>({multipleOf:m}))])}},lg=(e,t,r,n)=>{r.type="boolean"},Vk=(e,t,r,n)=>{ut(e,t,r,n,"BigInt cannot be represented in JSON Schema")},Gk=(e,t,r,n)=>{ut(e,t,r,n,"Symbols cannot be represented in JSON Schema")},dg=(e,t,r,n)=>{t.target==="openapi-3.0"?(r.type="string",r.nullable=!0,r.enum=[null]):r.type="null"},hg=(e,t,r,n)=>{ut(e,t,r,n,"Undefined cannot be represented in JSON Schema")},Zk=(e,t,r,n)=>{ut(e,t,r,n,"Void cannot be represented in JSON Schema")},pg=(e,t,r,n)=>{r.not={}},fg=(e,t,r,n)=>{},vg=(e,t,r,n)=>{},Wk=(e,t,r,n)=>{ut(e,t,r,n,"Date cannot be represented in JSON Schema")},gg=(e,t,r,n)=>{const i=e._zod.def,s=Qc(i.entries);if(s.length===0){r.not={};return}s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),r.enum=s},mg=(e,t,r,n)=>{const i=e._zod.def;if(i.values.length===0){r.not={};return}const s=[];for(const o of i.values)if(o===void 0){if(ut(e,t,r,n,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o=="bigint"){if(ut(e,t,r,n,"BigInt literals cannot be represented in JSON Schema"))return;s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){const o=s[0];r.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?r.enum=[o]:r.const=o}else s.every(o=>typeof o=="number")&&(r.type="number"),s.every(o=>typeof o=="string")&&(r.type="string"),s.every(o=>typeof o=="boolean")&&(r.type="boolean"),s.every(o=>o===null)&&(r.type="null"),r.enum=s},Jk=(e,t,r,n)=>{ut(e,t,r,n,"NaN cannot be represented in JSON Schema")},Kk=(e,t,r,n)=>{const i=r,s=e._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},Yk=(e,t,r,n)=>{const i=r;i.type="string",i.format="binary",i.contentEncoding="binary";const{minimum:s,maximum:o,mime:a}=At(e);s!==void 0&&(i.minLength=s),o!==void 0&&(i.maxLength=o),a&&(a.length===0?i.not={}:a.length===1?i.contentMediaType=a[0]:i.anyOf=a.map(c=>({contentMediaType:c})))},Xk=(e,t,r,n)=>{r.type="boolean"},_g=(e,t,r,n)=>{ut(e,t,r,n,"Custom types cannot be represented in JSON Schema")},Qk=(e,t,r,n)=>{ut(e,t,r,n,"Function types cannot be represented in JSON Schema")},yg=(e,t,r,n)=>{ut(e,t,r,n,"Transforms cannot be represented in JSON Schema")},eI=(e,t,r,n)=>{ut(e,t,r,n,"Map cannot be represented in JSON Schema")},tI=(e,t,r,n)=>{ut(e,t,r,n,"Set cannot be represented in JSON Schema")},bg=(e,t,r,n)=>{const i=r,s=e._zod.def,{minimum:o,maximum:a}=At(e);typeof o=="number"&&(i.minItems=o),typeof a=="number"&&(i.maxItems=a),i.type="array",i.items=Fe(s.element,t,{...n,path:[...n.path,"items"]})};function us(e){const t=e._zod.def;return t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform")?us(t.out):t.type==="catch"?us(t.innerType):e._zod.optin}var wg=(e,t,r,n)=>{const i=r,s=e._zod.def,o=s.shape;if(Object.getOwnPropertySymbols(o).length&&ut(e,t,i,n,"Symbol keys cannot be represented in JSON Schema"))return;i.type="object",i.properties={};for(const c in o)rr(i.properties,c,Fe(o[c],t,{...n,path:[...n.path,"properties",c]}));const a=[];for(const c of Object.keys(o)){const u=s.shape[c];(t.io==="input"?us(u)===void 0:u._zod.optout===void 0)&&a.push(c)}a.length>0&&(i.required=a),s.catchall?._zod.def.type==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Fe(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},Sg=(e,t,r,n)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((a,c)=>Fe(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));s?r.oneOf=o:r.anyOf=o},Eg=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.left,t,{...n,path:[...n.path,"allOf",0]}),o=Fe(i.right,t,{...n,path:[...n.path,"allOf",1]}),a=u=>"allOf"in u&&Object.keys(u).length===1,c=[...a(s)?s.allOf:[s],...a(o)?o.allOf:[o]];r.allOf=c,t.intersections.push(c)},kg=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="array";const o=t.target==="draft-2020-12"?"prefixItems":"items",a=t.target==="draft-2020-12"||t.target==="openapi-3.0"?"items":"additionalItems",c=s.items.map((v,g)=>Fe(v,t,{...n,path:[...n.path,o,g]})),u=s.rest?Fe(s.rest,t,{...n,path:[...n.path,a,...t.target==="openapi-3.0"?[s.items.length]:[]]}):null;let l=s.items.length;for(;l>0;){const v=s.items[l-1];if(!(t.io==="input"?us(v)!==void 0:v._zod.optout==="optional"))break;l--}const h=s.items.length,d=!s.rest;t.target==="draft-2020-12"?(i.prefixItems=c,d?i.items=!1:u&&(i.items=u),l>0&&(i.minItems=l),d&&(i.maxItems=h)):t.target==="openapi-3.0"?(i.items={anyOf:c},u&&i.items.anyOf.push(u),l>0&&(i.minItems=l),d&&(i.maxItems=h)):(i.items=c,d?i.additionalItems=!1:u&&(i.additionalItems=u),l>0&&(i.minItems=l),d&&(i.maxItems=h));const{minimum:p,maximum:f}=At(e);typeof p=="number"&&(i.minItems=p),typeof f=="number"&&(i.maxItems=f)};function su(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);const f=e.get(t)?.def;if(!f)return t;const v=su(e,f,r);return v===f?t:v}for(const f of["anyOf","oneOf"]){const v=t[f];if(!Array.isArray(v))continue;const g=v.map(m=>su(e,m,r));g.some((m,w)=>m!==v[w])&&(t={...t,[f]:g})}const n=Array.isArray(t.type)?t.type:[t.type],i=!n.includes("string")&&n.some(f=>f==="number"||f==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!i&&!s?.some(f=>typeof f=="number"))return t;const{minimum:o,maximum:a,exclusiveMinimum:c,exclusiveMaximum:u,multipleOf:l,format:h,id:d,...p}=t;return p.enum?p.enum=p.enum.map(f=>typeof f=="number"?String(f):f):typeof p.const=="number"&&(p.const=String(p.const)),i&&(p.type="string",s||(p.pattern=(n.includes("number")?Al:nS).source)),p}var ou=new WeakMap;function rI(e){const t=new Map;for(const n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);const r=new Map;for(const n of ou.get(e)??[]){const i=e.seen.get(n),s=(i?.def??i?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;const o=su(t,s,new Set);o!==s&&r.set(s,o)}if(r.size)for(const n of e.seen.values())for(const i of[n.schema,n.def]){const s=i&&r.get(i.propertyNames);s&&(i.propertyNames=s)}}var Ig=(e,t,r,n)=>{const i=r,s=e._zod.def;i.type="object";const o=s.keyType,a=At(o).patterns;if(s.mode==="loose"&&a&&a.size>0){const l=Fe(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});i.patternProperties={};for(const h of a)rr(i.patternProperties,ag(h).source,l)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){i.propertyNames=Fe(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let l=ou.get(t);l||(l=[],ou.set(t,l),t.deferred.push(()=>rI(t))),l.push(e)}i.additionalProperties=Fe(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}const c=o._zod.values,u=t.io==="input"&&us(s.valueType)!==void 0;if(c&&!s.partial&&!u){const l=[...c].filter(h=>typeof h=="string"||typeof h=="number");l.length>0&&(i.required=l.map(String))}},Ag=(e,t,r,n)=>{const i=e._zod.def,s=Fe(i.innerType,t,n),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,r.nullable=!0):r.anyOf=[s,{type:"null"}]},Tg=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Ol=Symbol();function Rg(e,t,r,n,i){let s=!1;const o=JSON.stringify(e,(a,c)=>typeof c!="bigint"?c:(s=!0,null));return s?(ut(t,r,n,i,"BigInt defaults cannot be represented in JSON Schema"),Ol):JSON.parse(o)}var Pg=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType;const o=Rg(i.defaultValue,e,t,r,n);o!==Ol&&(r.default=o)},Og=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);if(s.ref=i.innerType,t.io!=="input")return;const o=Rg(i.defaultValue,e,t,r,n);o!==Ol&&(r._prefault=o)},Cg=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{ut(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=o},$g=(e,t,r,n)=>{const i=e._zod.def,s=i.in._zod.traits.has("$ZodTransform"),o=t.io==="input"?s?i.out:i.in:i.out;Fe(o,t,n);const a=t.seen.get(e);a.ref=o},xg=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType,r.readOnly=!0},nI=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Cl=(e,t,r,n)=>{const i=e._zod.def;Fe(i.innerType,t,n);const s=t.seen.get(e);s.ref=i.innerType},Mg=(e,t,r,n)=>{const i=e._zod.innerType;Fe(i,t,n);const s=t.seen.get(e);s.ref=i},Th={string:cg,number:ug,boolean:lg,bigint:Vk,symbol:Gk,null:dg,undefined:hg,void:Zk,never:pg,any:fg,unknown:vg,date:Wk,enum:gg,literal:mg,nan:Jk,template_literal:Kk,file:Yk,success:Xk,custom:_g,function:Qk,transform:yg,map:eI,set:tI,array:bg,object:wg,union:Sg,intersection:Eg,tuple:kg,record:Ig,nullable:Ag,nonoptional:Tg,default:Pg,prefault:Og,catch:Cg,pipe:$g,readonly:xg,promise:nI,optional:Cl,lazy:Mg};function OD(e,t){if("_idmap"in e){const n=e,i=To({...t,processors:Th}),s={};for(const a of n._idmap.entries()){const[c,u]=a;Fe(u,i)}const o={};i.external={registry:n,uri:t?.uri,defs:s};for(const a of n._idmap.entries()){const[c,u]=a;Ro(i,u),rr(o,c,Po(i,u))}return Object.keys(s).length>0&&(o.__shared={[i.target==="draft-2020-12"?"$defs":"definitions"]:s}),{schemas:o}}const r=To({...t,processors:Th});return Fe(e,r),Ro(r,e),Po(r,e)}var Rh=new WeakSet([Object.prototype,Error.prototype]);function Ls(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){const n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var iI=(e,t)=>{fw.init(e,t),e.name="ZodError";const r=Object.getPrototypeOf(e);Rh.has(r)||(Rh.add(r),Ls(r,"format",n=>i=>_w(n,i)),Ls(r,"flatten",n=>i=>mw(n,i)),Ls(r,"addIssue",n=>i=>{n.issues.push(i),n.message=JSON.stringify(n.issues,eu,2)}),Ls(r,"addIssues",n=>i=>{n.issues.push(...i),n.message=JSON.stringify(n.issues,eu,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},Mt=x("ZodError",iI,void 0,{Parent:Error}),sI=El(Mt),oI=kl(Mt),aI=ha(Mt),cI=Il(Mt),uI=kw(Mt),lI=Iw(Mt),dI=Aw(Mt),hI=Tw(Mt),pI=Rw(Mt),fI=Pw(Mt),vI=Ow(Mt),gI=Cw(Mt);function mI(){$t.localeError||er(UE())}function ws(){$t.memoizer||er({memoizer:NE()})}var De=x("ZodType",(e,t)=>(mI(),Me.init(e,t),e.def=t,e.type=t.type,e),{check(...e){const t=this.def;return this.clone(kt(t,{checks:[...t.checks??[],...e.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Yr(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(gA(e,t))},superRefine(e,t){return this.check(mA(e,t))},overwrite(e){return this.check(gi(e))},optional(){return Oh(this)},exactOptional(){return nA(this)},nullable(){return Ch(this)},nullish(){return Oh(Ch(this))},nonoptional(e){return uA(this,e)},array(){return Dt(this)},or(e){return JI([this,e])},and(e){return XI(this,e)},transform(e){return $h(this,Ug(e))},default(e){return oA(this,e)},prefault(e){return cA(this,e)},catch(e){return dA(this,e)},pipe(e){return $h(this,e)},readonly(){return fA(this)},describe(e){const t=this.clone();return zi.add(t,{description:e}),t},meta(...e){if(e.length===0)return zi.get(this);const t=this.clone();return zi.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Sl(this,"~standard",{...Uv(this),jsonSchema:{input:Oo(this,"input"),output:Oo(this,"output")}})},set"~standard"(e){jr(this,"~standard",e)},parse:function e(t,r){return sI(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await oI(this,t,r,{callee:e})},safeParse(e,t){return aI(this,e,t)},async safeParseAsync(e,t){return cI(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){jr(this,"spa",e)},validate(e,t){return ww(this,e,t)},validateAsync(e,t){return Ew(this,e,t)},encode:function e(t,r){return uI(this,t,r,{callee:e})},decode:function e(t,r){return lI(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await dI(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await hI(this,t,r,{callee:e})},safeEncode(e,t){return pI(this,e,t)},safeDecode(e,t){return fI(this,e,t)},async safeEncodeAsync(e,t){return vI(this,e,t)},async safeDecodeAsync(e,t){return gI(this,e,t)},toJSONSchema(e){return qk(this,{})(e)},get description(){return zi.get(this)?.description},get _def(){return this._zod.def}}),Lg=x("_ZodString",(e,t)=>{Rl.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>cg(e,r,n,i)},Cv({format:e=>At(e).format??null,minLength:e=>At(e).minimum??null,maxLength:e=>At(e).maximum??null},{regex(...e){return this.check(Ek(...e))},includes(...e){return this.check(Ak(...e))},startsWith(...e){return this.check(Tk(...e))},endsWith(...e){return this.check(Rk(...e))},min(...e){return this.check(Ao(...e))},max(...e){return this.check(Qv(...e))},length(...e){return this.check(eg(...e))},nonempty(...e){return this.check(Ao(1,...e))},lowercase(e){return this.check(kk(e))},uppercase(e){return this.check(Ik(e))},trim(){return this.check(Ck())},normalize(...e){return this.check(Ok(...e))},toLowerCase(){return this.check($k())},toUpperCase(){return this.check(xk())},slugify(){return this.check(Mk())}})),_I=x("ZodString",(e,t)=>{Rl.init(e,t),Lg.init(e,t)},{email(e){return this.check(HE(EI,e))},url(e){return this.check(JE(II,e))},jwt(e){return this.check(lk(FI,e))},emoji(e){return this.check(KE(AI,e))},guid(e){return this.check(BE(kI,e))},uuid(e){return this.check(VE(Ns,e))},uuidv4(e){return this.check(GE(Ns,e))},uuidv6(e){return this.check(ZE(Ns,e))},uuidv7(e){return this.check(WE(Ns,e))},nanoid(e){return this.check(YE(TI,e))},cuid(e){return this.check(XE(RI,e))},cuid2(e){return this.check(QE(PI,e))},ulid(e){return this.check(ek(OI,e))},base64(e){return this.check(ak(DI,e))},base64url(e){return this.check(ck(zI,e))},xid(e){return this.check(tk(CI,e))},ksuid(e){return this.check(rk($I,e))},ipv4(e){return this.check(nk(xI,e))},ipv6(e){return this.check(ik(MI,e))},cidrv4(e){return this.check(sk(LI,e))},cidrv6(e){return this.check(ok(NI,e))},e164(e){return this.check(uk(UI,e))},datetime(e){return this.check(dk(yI,e))},date(e){return this.check(hk(bI,e))},time(e){return this.check(pk(wI,e))},duration(e){return this.check(fk(SI,e))}});function Le(e){return jE(_I,e)}var Ye=x("ZodStringFormat",(e,t)=>{We.init(e,t),Lg.init(e,t)}),yI=x("ZodISODateTime",(e,t)=>{qS.init(e,t),Ye.init(e,t)}),bI=x("ZodISODate",(e,t)=>{jS.init(e,t),Ye.init(e,t)}),wI=x("ZodISOTime",(e,t)=>{HS.init(e,t),Ye.init(e,t)}),SI=x("ZodISODuration",(e,t)=>{BS.init(e,t),Ye.init(e,t)}),EI=x("ZodEmail",(e,t)=>{TS.init(e,t),Ye.init(e,t)}),kI=x("ZodGUID",(e,t)=>{IS.init(e,t),Ye.init(e,t)}),Ns=x("ZodUUID",(e,t)=>{AS.init(e,t),Ye.init(e,t)}),II=x("ZodURL",(e,t)=>{xS.init(e,t),Ye.init(e,t)}),AI=x("ZodEmoji",(e,t)=>{MS.init(e,t),Ye.init(e,t)}),TI=x("ZodNanoID",(e,t)=>{LS.init(e,t),Ye.init(e,t)}),RI=x("ZodCUID",(e,t)=>{NS.init(e,t),Ye.init(e,t)}),PI=x("ZodCUID2",(e,t)=>{DS.init(e,t),Ye.init(e,t)}),OI=x("ZodULID",(e,t)=>{zS.init(e,t),Ye.init(e,t)}),CI=x("ZodXID",(e,t)=>{US.init(e,t),Ye.init(e,t)}),$I=x("ZodKSUID",(e,t)=>{FS.init(e,t),Ye.init(e,t)}),xI=x("ZodIPv4",(e,t)=>{VS.init(e,t),Ye.init(e,t)}),MI=x("ZodIPv6",(e,t)=>{ZS.init(e,t),Ye.init(e,t)}),LI=x("ZodCIDRv4",(e,t)=>{WS.init(e,t),Ye.init(e,t)}),NI=x("ZodCIDRv6",(e,t)=>{KS.init(e,t),Ye.init(e,t)}),DI=x("ZodBase64",(e,t)=>{YS.init(e,t),Ye.init(e,t)}),zI=x("ZodBase64URL",(e,t)=>{QS.init(e,t),Ye.init(e,t)}),UI=x("ZodE164",(e,t)=>{eE.init(e,t),Ye.init(e,t)}),FI=x("ZodJWT",(e,t)=>{rE.init(e,t),Ye.init(e,t)}),Ng=x("ZodNumber",(e,t)=>{Bv.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>ug(e,r,n,i),e.isFinite=!0},Cv({minValue:e=>{const{minimum:t,exclusiveMinimum:r}=At(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:e=>{const{maximum:t,exclusiveMaximum:r}=At(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:e=>{const{isInt:t,multipleOf:r}=At(e);return!!t||!!r?.some(Number.isSafeInteger)},format:e=>At(e).format??null},{gt(e,t){return this.check(_h(e,t))},gte(e,t){return this.check(rc(e,t))},min(e,t){return this.check(rc(e,t))},lt(e,t){return this.check(mh(e,t))},lte(e,t){return this.check(tc(e,t))},max(e,t){return this.check(tc(e,t))},int(e){return this.check(Ph(e))},safe(e){return this.check(Ph(e))},positive(e){return this.check(_h(0,e))},nonnegative(e){return this.check(rc(0,e))},negative(e){return this.check(mh(0,e))},nonpositive(e){return this.check(tc(0,e))},multipleOf(e,t){return this.check(yh(e,t))},step(e,t){return this.check(yh(e,t))},finite(){return this}}));function Co(e){return vk(Ng,e)}var qI=x("ZodNumberFormat",(e,t)=>{nE.init(e,t),Ng.init(e,t)});function Ph(e){return gk(qI,e)}var jI=x("ZodBoolean",(e,t)=>{iE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>lg(e,r,n,i)});function an(e){return mk(jI,e)}var HI=x("ZodUndefined",(e,t)=>{sE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>hg(e,r,n,i)});function CD(e){return _k(HI,e)}var BI=x("ZodNull",(e,t)=>{oE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>dg(e,r,n,i)});function $D(e){return yk(BI,e)}var VI=x("ZodAny",(e,t)=>{aE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>fg(e,r,n,i)});function xD(){return bk(VI)}var GI=x("ZodUnknown",(e,t)=>{cE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>vg(e,r,n,i)});function au(){return wk(GI)}var ZI=x("ZodNever",(e,t)=>{uE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>pg(e,r,n,i)});function Dg(e){return Sk(ZI,e)}var WI=x("ZodArray",(e,t)=>{ws(),lE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>bg(e,r,n,i),e.element=t.element},{min(e,t){return this.check(Ao(e,t))},nonempty(e){return this.check(Ao(1,e))},max(e,t){return this.check(Qv(e,t))},length(e,t){return this.check(eg(e,t))},unwrap(){return this.element}});function Dt(e,t){return Lk(WI,e,t)}var $l=x("ZodObject",(e,t)=>{ws(),pE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>wg(e,r,n,i),aw(e,"shape",r=>r._zod.def.shape,!1)},{keyof(){return Or(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(kt(this._zod.def,{catchall:e}))},passthrough(){return this.clone(kt(this._zod.def,{catchall:au()}))},loose(){return this.clone(kt(this._zod.def,{catchall:au()}))},strict(){return this.clone(kt(this._zod.def,{catchall:Dg()}))},strip(){return this.clone(kt(this._zod.def,{catchall:void 0}))},extend(e){return Kb(this,e)},safeExtend(e){return Yb(this,e)},merge(e){return Xb(this,e)},pick(e){return Wb(this,e)},omit(e){return Jb(this,e)},partial(...e){return Jd(xl,this,e[0])},exactPartial(...e){return Jd(Fg,this,e[0],"exactPartial")},required(...e){return Qb(qg,this,e[0])}});function vn(e,t){const r={type:"object",shape:e??{},...te(t)};return new $l(r)}function MD(e,t){return new $l({type:"object",shape:e,catchall:Dg(),...te(t)})}function LD(e,t){return new $l({type:"object",shape:e,catchall:au(),...te(t)})}var zg=x("ZodUnion",(e,t)=>{Zv.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Sg(e,r,n,i),e.options=t.options});function JI(e,t){return new zg({type:"union",options:e,...te(t)})}var KI=x("ZodDiscriminatedUnion",(e,t)=>{zg.init(e,t),vE.init(e,t)});function ND(e,t,r){return new KI({type:"union",options:t,discriminator:e,...te(r)})}var YI=x("ZodIntersection",(e,t)=>{gE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Eg(e,r,n,i)});function XI(e,t){return new YI({type:"intersection",left:e,right:t})}var QI=x("ZodTuple",(e,t)=>{ws(),mE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>kg(e,r,n,i)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){const e=this._zod.def;if(e.checks?.length)throw new Error(".partial() cannot be used on tuple schemas containing refinements");return this.clone({...e,items:e.items.map(t=>new xl({type:"optional",innerType:t}))})}});function DD(e,t,r){const n=t instanceof Me,i=n?r:t;return new QI({type:"tuple",items:e,rest:n?t:null,...te(i)})}var cu=x("ZodRecord",(e,t)=>{ws(),_E.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ig(e,r,n,i),e.keyType=t.keyType,e.valueType=t.valueType});function uu(e,t,r){return!t||!t._zod?new cu({type:"record",keyType:Le(),valueType:e,...te(t)}):new cu({type:"record",keyType:e,valueType:t,...te(r)})}function eA(e,t,r){return new cu({type:"record",keyType:e,valueType:t,...te(r),partial:!0})}var lu=x("ZodEnum",(e,t)=>{yE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(n,i,s)=>gg(e,n,i,s),e.enum=t.entries,e.options=[...e._zod.values];const r=new Set(Object.keys(t.entries));e.extract=(n,i)=>{const s={};for(const o of n)if(r.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new lu({...t,checks:[],...te(i),entries:s})},e.exclude=(n,i)=>{const s={...t.entries};for(const o of n)if(r.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new lu({...t,checks:[],...te(i),entries:s})}});function Or(e,t){const r=Array.isArray(e)?Object.fromEntries(e.map(n=>[n,n])):e;return new lu({type:"enum",entries:r,...te(t)})}var tA=x("ZodLiteral",(e,t)=>{bE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>mg(e,r,n,i),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function zD(e,t){return new tA({type:"literal",values:Array.isArray(e)?e:[e],...te(t)})}var rA=x("ZodTransform",(e,t)=>{ws(),wE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>yg(e,r,n,i),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new $v(e.constructor.name);r.addIssue=s=>{if(typeof s=="string")r.issues.push(cs(s,r.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),"input"in o||(o.input=r.value),o.inst??(o.inst=e),r.issues.push(cs(o))}};const i=t.transform(r.value,r);return i instanceof Promise?i.then(s=>(r.value=s,r)):(r.value=i,r)}});function Ug(e){return new rA({type:"transform",transform:e})}var xl=x("ZodOptional",(e,t)=>{Wv.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Cl(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Oh(e){return new xl({type:"optional",innerType:e})}var Fg=x("ZodExactOptional",(e,t)=>{SE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Cl(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function nA(e){return new Fg({type:"optional",innerType:e})}var iA=x("ZodNullable",(e,t)=>{EE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Ag(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function Ch(e){return new iA({type:"nullable",innerType:e})}var sA=x("ZodDefault",(e,t)=>{kE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Pg(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function oA(e,t){return new sA({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Tv(t)}})}var aA=x("ZodPrefault",(e,t)=>{IE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Og(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function cA(e,t){return new aA({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Tv(t)}})}var qg=x("ZodNonOptional",(e,t)=>{AE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Tg(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function uA(e,t){return new qg({type:"nonoptional",innerType:e,...te(t)})}var lA=x("ZodCatch",(e,t)=>{TE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Cg(e,r,n,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function dA(e,t){return new lA({type:"catch",innerType:e,catchValue:typeof t=="function"?t:uw(t)})}var jg=x("ZodPipe",(e,t)=>{Jv.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>$g(e,r,n,i),e.in=t.in,e.out=t.out});function $h(e,t){return new jg({type:"pipe",in:e,out:t})}var hA=x("ZodPreprocess",(e,t)=>{jg.init(e,t),RE.init(e,t)}),pA=x("ZodReadonly",(e,t)=>{PE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>xg(e,r,n,i),e.unwrap=()=>e._zod.def.innerType});function fA(e){return new pA({type:"readonly",innerType:e})}var vA=x("ZodLazy",(e,t)=>{OE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>Mg(e,r,n,i),e.unwrap=()=>e._zod.def.getter()});function UD(e){return new vA({type:"lazy",getter:e})}var Ml=x("ZodCustom",(e,t)=>{CE.init(e,t),De.init(e,t),e._zod.processJSONSchema=(r,n,i)=>_g(e,r,n,i)});function FD(e,t){return Nk(Ml,e??(()=>!0),t)}function gA(e,t={}){return Dk(Ml,e,t)}function mA(e,t){return zk(e,t)}var _A=x("ZodInstanceOf",(e,t)=>{Ml.init(e,t)},{properties(e,t){return this.check(Pk(e,t))}});function qD(e,t={}){const r=new _A({type:"custom",check:"custom",fn:n=>n instanceof e,abort:!0,...te(t)});return r._zod.bag.Class=e,r._zod.check=n=>{n.value instanceof e||n.issues.push({code:"invalid_type",expected:e.name,input:n.value,inst:r,path:[...r._zod.def.path??[]]})},r}function jD(e,t){return new hA({type:"pipe",in:Ug(e),out:t})}var yA=["oauth-dcr","oauth-cimd","oauth-preregistered","static-header","authless","custom-connection"],bA=["no-user-data","processes-user-data","stores-user-data","shares-with-third-parties"],wA=["ownsOrIsAuthorizedForService","accurateDataHandlingDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],Ds=Le().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),SA=vn({url:Le().min(1),mimeType:Le().min(1),widthPx:Co().int().positive(),heightPx:Co().int().positive(),prompt:Le().min(1)}),HD=vn({name:Le().min(1).max(Sr.nameMaxLength),tagline:Le().min(1).max(Sr.taglineMaxLength),description:Le().min(1).max(Sr.descriptionMaxLength),categories:Dt(Le().min(1)).min(Sr.categoriesMin).max(Sr.categoriesMax),slug:Le().min(1).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/,"must be a lowercase kebab-case slug"),documentationUrl:Ds,privacyPolicyUrl:Ds,supportUrl:Ds,iconUrl:Ds,declaredAuthMode:Or(yA),dataHandling:Dt(Or(bA)).min(1),screenshots:Dt(SA).min(Sr.screenshotsMin).max(Sr.screenshotsMax),attestations:uu(Or(wA),an())}),so={maxCompressedBytes:104857600,maxUncompressedBytes:536870912,maxEntries:5e3},EA={canonical:".codex-plugin/plugin.json",accepted:[".agent-plugin/plugin.json",".claude-plugin/plugin.json"]},zt={nameMaxLength:100,displayNameMaxLength:100,shortDescriptionMaxLength:255,descriptionMaxLength:2e3,defaultPromptMaxLength:255,toolNameMaxLength:64,skillNameMaxLength:64},Hg=["productivity","education","developer-tools","design","writing","research","data-analysis","marketing","sales","finance","health","travel","entertainment"],oo={minEdgePx:48,maxEdgePx:4096,mustBeSquare:!0,maxBytes:5242880,acceptedMimeTypes:["image/png","image/jpeg","image/webp","image/svg+xml"]},kA={lightBackground:"#FFFFFF",darkBackground:"#212121",minRatio:2},cn={maxSkillMarkdownBytes:262144,maxPageBytes:1048576,maxSkillTotalBytes:5242880,maxImportedTotalBytes:8388608,maxSkills:5,maxPagesPerSkill:10},IA="/.well-known/openai-apps-challenge",AA="text/html;profile=mcp-app",TA="/mcp",RA=["readOnlyHint","destructiveHint","openWorldHint"],du={successCount:5,failureCount:3},PA={originChangeRequiresNewPlugin:!0,uiContentChangesStayLive:!0,uiContentCacheSeconds:3600},BD={archiveLimits:so,manifestLocations:EA,fieldLimits:zt,listingCategories:Hg,imageConstraints:oo,brandColorContrast:kA,mcpSkillLimits:cn,domainVerificationPath:IA,appHtmlMime:AA,expectedMcpPath:TA,requiredToolAnnotations:RA,submissionTestCases:du,releaseRules:PA,source:Wt("deploy/submission","Host profile constants")},W=e=>Wt("deploy/submission-errors",e),OA=[{id:"archive-too-large",category:"package-archive",severity:"blocking",message:"The uploaded archive exceeds the maximum compressed size.",limit:{name:"archiveLimits.maxCompressedBytes",value:so.maxCompressedBytes},source:W("§Shared package checks → Archive size")},{id:"archive-expands-too-large",category:"package-archive",severity:"blocking",message:"The archive's contents exceed the maximum uncompressed size when expanded.",limit:{name:"archiveLimits.maxUncompressedBytes",value:so.maxUncompressedBytes},source:W("§Shared package checks → Archive size")},{id:"archive-too-many-entries",category:"package-archive",severity:"blocking",message:"The archive contains more entries than the maximum allowed.",limit:{name:"archiveLimits.maxEntries",value:so.maxEntries},source:W("§Shared package checks → Entry count")},{id:"archive-encrypted-entry",category:"package-archive",severity:"blocking",message:"The archive contains an encrypted entry, which cannot be scanned.",source:W("§Shared package checks → Archive integrity")},{id:"archive-path-traversal",category:"package-archive",severity:"blocking",message:"An entry path escapes the package root via a `..` segment.",source:W("§Shared package checks → Entry paths")},{id:"archive-absolute-path",category:"package-archive",severity:"blocking",message:"An entry path is absolute rather than package-relative.",source:W("§Shared package checks → Entry paths")},{id:"archive-backslash-path",category:"package-archive",severity:"blocking",message:"An entry path uses a backslash separator.",source:W("§Shared package checks → Entry paths")},{id:"archive-empty-path-segment",category:"package-archive",severity:"blocking",message:"An entry path contains an empty or `.` segment.",source:W("§Shared package checks → Entry paths")},{id:"archive-path-whitespace",category:"package-archive",severity:"blocking",message:"An entry path has leading or trailing whitespace.",source:W("§Shared package checks → Entry paths")},{id:"archive-path-control-character",category:"package-archive",severity:"blocking",message:"An entry path contains a control character or NUL byte.",source:W("§Shared package checks → Entry paths")},{id:"archive-duplicate-path",category:"package-archive",severity:"blocking",message:"Two entries normalize to the same path, including case-insensitive collisions.",source:W("§Shared package checks → Entry paths")},{id:"archive-symlink-entry",category:"package-archive",severity:"blocking",message:"The archive contains a symlink or hardlink entry.",source:W("§Shared package checks → Archive integrity")},{id:"manifest-missing",category:"package-manifest",severity:"blocking",message:"The package contains no plugin manifest.",source:W("§Shared package checks → Manifest")},{id:"manifest-invalid-json",category:"package-manifest",severity:"blocking",message:"The plugin manifest is not valid JSON.",source:W("§Shared package checks → Manifest")},{id:"manifest-name-missing",category:"package-manifest",severity:"blocking",message:"The manifest declares no plugin name.",source:W("§Shared package checks → Manifest")},{id:"manifest-name-too-long",category:"package-manifest",severity:"blocking",message:"The manifest's plugin name exceeds the maximum length.",limit:{name:"fieldLimits.nameMaxLength",value:zt.nameMaxLength},source:W("§Shared package checks → Manifest")},{id:"manifest-version-invalid",category:"package-manifest",severity:"blocking",message:"The manifest's version is not a valid semantic version.",source:W("§Shared package checks → Manifest")},{id:"interface-display-name-missing",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document declares no display name.",source:W("§Listing fields → Interface")},{id:"interface-display-name-too-long",category:"package-manifest",severity:"blocking",message:"The interface display name exceeds the maximum length.",limit:{name:"fieldLimits.displayNameMaxLength",value:zt.displayNameMaxLength},source:W("§Listing fields → Interface")},{id:"interface-short-description-too-long",category:"package-manifest",severity:"blocking",message:"The interface short description exceeds the maximum length.",limit:{name:"fieldLimits.shortDescriptionMaxLength",value:zt.shortDescriptionMaxLength},source:W("§Listing fields → Interface")},{id:"interface-default-prompt-too-long",category:"package-manifest",severity:"blocking",message:"The interface default prompt exceeds the maximum length.",limit:{name:"fieldLimits.defaultPromptMaxLength",value:zt.defaultPromptMaxLength},source:W("§Listing fields → Interface")},{id:"interface-brand-color-invalid",category:"package-manifest",severity:"blocking",message:"The brand color is not a six-digit hex value.",source:W("§Listing fields → Interface")},{id:"interface-brand-color-low-contrast",category:"package-manifest",severity:"blocking",message:"The brand color does not meet the minimum contrast ratio against both the light and dark backgrounds.",source:W("§Listing fields → Interface")},{id:"interface-yaml-invalid",category:"package-manifest",severity:"blocking",message:"The OpenAI interface document is not valid YAML.",source:W("§Listing fields → Interface")},{id:"interface-unsupported-text",category:"package-manifest",severity:"blocking",message:"A text field contains control characters or Unicode line/paragraph separators.",source:W("§Listing fields → Text")},{id:"skill-metadata-missing",category:"package-skills",severity:"blocking",message:"A skill directory contains no SKILL.md.",source:W("§Skills → Structure")},{id:"skill-frontmatter-invalid",category:"package-skills",severity:"blocking",message:"A skill's SKILL.md frontmatter is missing or malformed.",source:W("§Skills → Frontmatter")},{id:"skill-name-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no name.",source:W("§Skills → Frontmatter")},{id:"skill-name-too-long",category:"package-skills",severity:"blocking",message:"A skill name exceeds the maximum length.",limit:{name:"fieldLimits.skillNameMaxLength",value:zt.skillNameMaxLength},source:W("§Skills → Frontmatter")},{id:"skill-description-missing",category:"package-skills",severity:"blocking",message:"A skill's frontmatter declares no description.",source:W("§Skills → Frontmatter")},{id:"skill-name-collision",category:"package-skills",severity:"blocking",message:"Two skills in the package declare the same name.",source:W("§Skills → Structure")},{id:"asset-unsupported-type",category:"package-assets",severity:"blocking",message:"An image is not one of the accepted formats.",source:W("§Images → Format")},{id:"asset-too-large",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum file size.",limit:{name:"imageConstraints.maxBytes",value:oo.maxBytes},source:W("§Images → Size")},{id:"asset-too-small",category:"package-assets",severity:"blocking",message:"An image is smaller than the minimum edge length.",limit:{name:"imageConstraints.minEdgePx",value:oo.minEdgePx},source:W("§Images → Dimensions")},{id:"asset-too-big-dimensions",category:"package-assets",severity:"blocking",message:"An image exceeds the maximum edge length.",limit:{name:"imageConstraints.maxEdgePx",value:oo.maxEdgePx},source:W("§Images → Dimensions")},{id:"asset-not-square",category:"package-assets",severity:"blocking",message:"An image is not square.",source:W("§Images → Dimensions")},{id:"asset-undecodable",category:"package-assets",severity:"blocking",message:"An image's dimensions could not be read from its bytes.",source:W("§Images → Format")},{id:"asset-svg-malformed",category:"package-assets",severity:"blocking",message:"An SVG is not well-formed XML or has no `svg` root element.",source:W("§Images → SVG")},{id:"asset-svg-no-dimensions",category:"package-assets",severity:"blocking",message:"An SVG declares neither a numeric width/height pair nor a numeric viewBox.",source:W("§Images → SVG")},{id:"asset-missing",category:"package-assets",severity:"blocking",message:"An asset referenced by the manifest is absent from the package.",source:W("§Images → Format")},{id:"listing-category-unknown",category:"listing-fields",severity:"blocking",message:"The listing names a category outside the supported set.",source:W("§Listing fields → Categories")},{id:"listing-description-too-long",category:"listing-fields",severity:"blocking",message:"The listing description exceeds the maximum length.",limit:{name:"fieldLimits.descriptionMaxLength",value:zt.descriptionMaxLength},source:W("§Listing fields → Description")},{id:"listing-promotional-metadata",category:"listing-fields",severity:"blocking",message:"Listing metadata contains promotional language, pricing claims, or ranking claims.",source:W("§Listing fields → Description")},{id:"listing-privacy-policy-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no privacy policy URL.",source:W("§Listing fields → Links")},{id:"listing-support-url-missing",category:"listing-fields",severity:"blocking",message:"The listing declares no support URL.",source:W("§Listing fields → Links")},{id:"mcp-endpoint-not-https",category:"mcp-server",severity:"blocking",message:"The MCP endpoint is not served over HTTPS.",source:W("§MCP tools → Endpoint")},{id:"mcp-endpoint-unreachable",category:"mcp-server",severity:"blocking",message:"The MCP endpoint could not be reached during the scan.",source:W("§MCP tools → Endpoint")},{id:"mcp-tool-name-too-long",category:"mcp-server",severity:"blocking",message:"A tool name exceeds the maximum length.",limit:{name:"fieldLimits.toolNameMaxLength",value:zt.toolNameMaxLength},source:W("§MCP tools → Metadata")},{id:"mcp-tool-description-missing",category:"mcp-server",severity:"blocking",message:"A tool declares no description.",source:W("§MCP tools → Metadata")},{id:"mcp-tool-annotations-missing",category:"mcp-server",severity:"blocking",message:"A tool is missing one or more of the required annotation hints.",source:W("§MCP tools → Annotations")},{id:"mcp-tool-schema-invalid",category:"mcp-server",severity:"blocking",message:"A tool's input or output schema is not a valid JSON Schema object.",source:W("§MCP tools → Schemas")},{id:"mcp-domain-not-verified",category:"mcp-server",severity:"blocking",message:"The MCP server's domain has not completed domain verification.",source:W("§MCP tools → Domain verification")},{id:"mcp-csp-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource loads from a domain absent from the declared content security policy.",source:W("§MCP tools → Content security policy")},{id:"mcp-ui-domain-missing",category:"mcp-server",severity:"blocking",message:"A UI resource declares no `_meta.ui.domain`.",source:W("§MCP tools → UI resources")},{id:"mcp-ui-domain-duplicate",category:"mcp-server",severity:"blocking",message:"Two UI resources declare the same `_meta.ui.domain`.",source:W("§MCP tools → UI resources")},{id:"mcp-ui-mime-invalid",category:"mcp-server",severity:"blocking",message:"A UI resource does not declare the plugin UI MIME profile.",source:W("§MCP tools → UI resources")},{id:"mcp-skill-too-many",category:"mcp-skills",severity:"blocking",message:"The server advertises more importable skills than the maximum.",limit:{name:"mcpSkillLimits.maxSkills",value:cn.maxSkills},source:W("§Skills → Imported from MCP")},{id:"mcp-skill-markdown-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's markdown exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxSkillMarkdownBytes",value:cn.maxSkillMarkdownBytes},source:W("§Skills → Imported from MCP")},{id:"mcp-skill-page-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's supporting page exceeds the maximum size.",limit:{name:"mcpSkillLimits.maxPageBytes",value:cn.maxPageBytes},source:W("§Skills → Imported from MCP")},{id:"mcp-skill-too-many-pages",category:"mcp-skills",severity:"blocking",message:"An imported skill has more supporting pages than the maximum.",limit:{name:"mcpSkillLimits.maxPagesPerSkill",value:cn.maxPagesPerSkill},source:W("§Skills → Imported from MCP")},{id:"mcp-skill-total-too-large",category:"mcp-skills",severity:"blocking",message:"An imported skill's total footprint exceeds the maximum.",limit:{name:"mcpSkillLimits.maxSkillTotalBytes",value:cn.maxSkillTotalBytes},source:W("§Skills → Imported from MCP")},{id:"mcp-skills-total-too-large",category:"mcp-skills",severity:"blocking",message:"The imported skills exceed the maximum combined size.",limit:{name:"mcpSkillLimits.maxImportedTotalBytes",value:cn.maxImportedTotalBytes},source:W("§Skills → Imported from MCP")},{id:"mcp-skill-digest-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's declared digest does not match the resource served for it.",source:W("§Skills → Imported from MCP")},{id:"mcp-skill-frontmatter-mismatch",category:"mcp-skills",severity:"blocking",message:"An imported skill's listing metadata disagrees with its SKILL.md frontmatter.",source:W("§Skills → Imported from MCP")},{id:"mcp-skill-scan-failed",category:"mcp-skills",severity:"blocking",message:"The skill scan failed, so the draft's imported skills were not updated.",source:W("§Skills → Imported from MCP")},{id:"review-success-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer successful test cases were supplied than required.",limit:{name:"submissionTestCases.successCount",value:du.successCount},source:W("§Review materials → Test cases")},{id:"review-failure-tests-missing",category:"review-materials",severity:"blocking",message:"Fewer graceful-failure test cases were supplied than required.",limit:{name:"submissionTestCases.failureCount",value:du.failureCount},source:W("§Review materials → Test cases")},{id:"review-demo-credentials-missing",category:"review-materials",severity:"blocking",message:"The submission authenticates users but supplies no reviewer demo credentials.",source:W("§Review materials → Demo access")},{id:"review-demo-recording-missing",category:"review-materials",severity:"blocking",message:"No demo recording was supplied.",source:W("§Review materials → Demo access")},{id:"review-release-notes-missing",category:"review-materials",severity:"blocking",message:"An updated submission supplies no release notes.",source:W("§Review materials → Release notes")},{id:"review-attestation-missing",category:"review-materials",severity:"blocking",message:"A required policy attestation was not affirmed.",source:W("§Review materials → Attestations")},{id:"review-identity-not-verified",category:"review-materials",severity:"blocking",message:"The submitting account has not completed identity verification.",source:W("§Review materials → Account")},{id:"review-write-permission-missing",category:"review-materials",severity:"blocking",message:"The submitting account lacks the app-write permission.",source:W("§Review materials → Account")},{id:"review-geography-missing",category:"review-materials",severity:"blocking",message:"The submission declares no country availability.",source:W("§Review materials → Availability")},{id:"review-annotation-justification-missing",category:"review-materials",severity:"advisory",message:"A tool annotated as destructive or open-world carries no justification for review.",source:W("§Review materials → Test cases")},{id:"review-scan-stale",category:"review-materials",severity:"blocking",message:"The draft's scan predates the current server contract; re-run Scan Tools.",source:W("§MCP tools → Scan")},{id:"exclusion-mcp-servers-in-skills-only",category:"exclusions",severity:"blocking",message:"A skills-only submission declares MCP servers, which that shape excludes.",source:W("§Shared package checks → Excluded content")},{id:"exclusion-app-config-in-public-package",category:"exclusions",severity:"blocking",message:"The package contains an `.app.json`, which maps registered connections for local or workspace use and is excluded from a public submission.",source:W("§Shared package checks → Excluded content")},{id:"exclusion-screenshots-without-ui",category:"exclusions",severity:"blocking",message:"Screenshots were supplied for a submission that renders no UI template.",source:W("§Images → Screenshots")},{id:"exclusion-bundle-in-mcp-only",category:"exclusions",severity:"blocking",message:"An MCP-only submission supplies a package archive.",source:W("§Shared package checks → Excluded content")},{id:"exclusion-unsupported-surface",category:"exclusions",severity:"blocking",message:"The package contains a surface the plugin directory does not support.",source:W("§Shared package checks → Excluded content")}],VD=Object.freeze(Object.fromEntries(OA.map(e=>[e.id,e]))),CA=["ownsOrIsAuthorizedForService","accurateDataDisclosure","compliesWithUsagePolicies","noProhibitedContent","maintainsSecurityPractices","respondsToSecurityReports","keepsListingAccurate"],$A=["none","account-identifiers","user-content","usage-analytics","payment-information","location","health","shared-with-third-parties"],xA=["in-submission-form","shared-out-of-band","not-required-authless"],nc=Le().url().refine(e=>e.startsWith("https://"),{message:"must be an https:// URL"}),xh=vn({prompt:Le().min(1),expectation:Le().min(1)}),MA=vn({reference:Le().min(1),mimeType:Le().min(1),widthPx:Co().int().positive(),heightPx:Co().int().positive(),prompt:Le().min(1)}),GD=vn({name:Le().min(1).max(zt.nameMaxLength),shortDescription:Le().min(1).max(zt.shortDescriptionMaxLength),description:Le().min(1).max(zt.descriptionMaxLength),categories:Dt(Or(Hg)).min(1),privacyPolicyUrl:nc,supportUrl:nc,documentationUrl:nc.optional(),testCases:vn({successful:Dt(xh),gracefulFailure:Dt(xh)}),demoCredentials:vn({provided:an(),delivery:Or(xA)}),demoRecordingProvided:an(),screenshots:Dt(MA).default([]),releaseNotes:Le().min(1).optional(),identityVerified:an(),accountPermissions:Dt(Le().min(1)).default([]),availableCountries:Dt(Le().length(2)).default([]),dataResidencyEligible:an().optional(),privacyPolicyDataTypes:Dt(Or($A)).default([]),annotationJustifications:uu(Le(),Le().min(1)).default({}),frameDomainExplanations:uu(Le(),Le().min(1)).default({}),domainVerificationToken:Le().min(1).optional(),lastScanAt:Le().datetime().optional(),hasPublishedVersion:an().optional(),attestations:eA(Or(CA),an())}),ZD=new TextDecoder("utf-8",{fatal:!1}),Ll=Symbol.for("yaml.alias"),LA=Symbol.for("yaml.document"),gn=Symbol.for("yaml.map"),Bg=Symbol.for("yaml.pair"),Nl=Symbol.for("yaml.scalar"),Ss=Symbol.for("yaml.seq"),nr=Symbol.for("yaml.node.type"),mi=e=>!!e&&typeof e=="object"&&e[nr]===Ll,Es=e=>!!e&&typeof e=="object"&&e[nr]===LA,Dl=e=>!!e&&typeof e=="object"&&e[nr]===gn,it=e=>!!e&&typeof e=="object"&&e[nr]===Bg,st=e=>!!e&&typeof e=="object"&&e[nr]===Nl,fa=e=>!!e&&typeof e=="object"&&e[nr]===Ss;function wt(e){if(e&&typeof e=="object")switch(e[nr]){case gn:case Ss:return!0}return!1}function nt(e){if(e&&typeof e=="object")switch(e[nr]){case Ll:case gn:case Nl:case Ss:return!0}return!1}var Vg=e=>(st(e)||wt(e))&&!!e.anchor,yt=Symbol("break visit"),Gg=Symbol("skip children"),Xt=Symbol("remove node");function ks(e,t){const r=Zg(t);Es(e)?zn(null,e.contents,r,Object.freeze([e]))===Xt&&(e.contents=null):zn(null,e,r,Object.freeze([]))}ks.BREAK=yt;ks.SKIP=Gg;ks.REMOVE=Xt;function zn(e,t,r,n){const i=Wg(e,t,r,n);if(nt(i)||it(i))return Jg(e,n,i),zn(e,i,r,n);if(typeof i!="symbol"){if(wt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=zn(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===yt)return yt;o===Xt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=zn("key",t.key,r,n);if(s===yt)return yt;s===Xt&&(t.key=null);const o=zn("value",t.value,r,n);if(o===yt)return yt;o===Xt&&(t.value=null)}}return i}async function zl(e,t){const r=Zg(t);Es(e)?await Un(null,e.contents,r,Object.freeze([e]))===Xt&&(e.contents=null):await Un(null,e,r,Object.freeze([]))}zl.BREAK=yt;zl.SKIP=Gg;zl.REMOVE=Xt;async function Un(e,t,r,n){const i=await Wg(e,t,r,n);if(nt(i)||it(i))return Jg(e,n,i),Un(e,i,r,n);if(typeof i!="symbol"){if(wt(t)){n=Object.freeze(n.concat(t));for(let s=0;s<t.items.length;++s){const o=await Un(s,t.items[s],r,n);if(typeof o=="number")s=o-1;else{if(o===yt)return yt;o===Xt&&(t.items.splice(s,1),s-=1)}}}else if(it(t)){n=Object.freeze(n.concat(t));const s=await Un("key",t.key,r,n);if(s===yt)return yt;s===Xt&&(t.key=null);const o=await Un("value",t.value,r,n);if(o===yt)return yt;o===Xt&&(t.value=null)}}return i}function Zg(e){return typeof e=="object"&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function Wg(e,t,r,n){if(typeof r=="function")return r(e,t,n);if(Dl(t))return r.Map?.(e,t,n);if(fa(t))return r.Seq?.(e,t,n);if(it(t))return r.Pair?.(e,t,n);if(st(t))return r.Scalar?.(e,t,n);if(mi(t))return r.Alias?.(e,t,n)}function Jg(e,t,r){const n=t[t.length-1];if(wt(n))n.items[e]=r;else if(it(n))e==="key"?n.key=r:n.value=r;else if(Es(n))n.contents=r;else{const i=mi(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}var NA={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},DA=e=>e.replace(/[!,[\]{}]/g,t=>NA[t]),Kg=class ar{constructor(t,r){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ar.defaultYaml,t),this.tags=Object.assign({},ar.defaultTags,r)}clone(){const t=new ar(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){const t=new ar(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ar.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ar.defaultTags)}return t}add(t,r){this.atNextDocument&&(this.yaml={explicit:ar.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ar.defaultTags),this.atNextDocument=!1);const n=t.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(r(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return r(0,"%YAML directive should contain exactly one part"),!1;const[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{const o=/^\d+\.\d+$/.test(s);return r(6,`Unsupported YAML version ${s}`,o),!1}}default:return r(0,`Unknown directive ${i}`,!0),!1}}tagName(t,r){if(t==="!")return"!";if(t[0]!=="!")return r(`Not a valid tag: ${t}`),null;if(t[1]==="<"){const o=t.slice(2,-1);return o==="!"||o==="!!"?(r(`Verbatim tags aren't resolved, so ${t} is invalid.`),null):(t[t.length-1]!==">"&&r("Verbatim tags must end with a >"),o)}const[,n,i]=t.match(/^(.*!)([^!]*)$/s);i||r(`The ${t} tag has no suffix`);const s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return r(String(o)),null}return n==="!"?t:(r(`Could not resolve tag: ${t}`),null)}tagString(t){for(const[r,n]of Object.entries(this.tags))if(t.startsWith(n))return r+DA(t.substring(n.length));return t[0]==="!"?t:`!<${t}>`}toString(t){const r=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(t&&n.length>0&&nt(t.contents)){const s={};ks(t.contents,(o,a)=>{nt(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(const[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!t||i.some(a=>a.startsWith(o)))&&r.push(`%TAG ${s} ${o}`);return r.join(`
|
|
58
|
+
`)}};Kg.defaultYaml={explicit:!1,version:"1.2"};Kg.defaultTags={"!!":"tag:yaml.org,2002:"};function Yg(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw new Error(t)}return!0}function Ui(e,t,r,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;i<s;++i){const o=n[i],a=Ui(e,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const s=n.get(i),o=Ui(e,n,i,s);o===void 0?n.delete(i):o!==s&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const s=Ui(e,n,i,i);s===void 0?n.delete(i):s!==i&&(n.delete(i),n.add(s))}else for(const[i,s]of Object.entries(n)){const o=Ui(e,n,i,s);o===void 0?delete n[i]:o!==s&&(n[i]=o)}return e.call(t,r,n)}function Bt(e,t,r){if(Array.isArray(e))return e.map((n,i)=>Bt(n,String(i),r));if(e&&typeof e.toJSON=="function"){if(!r||!Vg(e))return e.toJSON(t,r);const n={aliasCount:0,count:1,res:void 0};r.anchors.set(e,n),r.onCreate=s=>{n.res=s,delete r.onCreate};const i=e.toJSON(t,r);return r.onCreate&&r.onCreate(i),i}return typeof e=="bigint"&&!r?.keep?Number(e):e}var Ul=class{constructor(e){Object.defineProperty(this,nr,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:n,reviver:i}={}){if(!Es(e))throw new TypeError("A document argument is required");const s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},o=Bt(this,"",s);if(typeof n=="function")for(const{count:a,res:c}of s.anchors.values())n(c,a);return typeof i=="function"?Ui(i,{"":o},"",o):o}},zA=class extends Ul{constructor(e){super(Ll),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;t?.aliasResolveCache?r=t.aliasResolveCache:(r=[],ks(e,{Node:(i,s)=>{(mi(s)||Vg(s))&&r.push(s)}}),t&&(t.aliasResolveCache=r));let n;for(const i of r){if(i===this)break;i.anchor===this.source&&(n=i)}if(n&&t){const{anchors:i,doc:s,maxAliasCount:o}=t;let a=i.get(n);if(a||(Bt(n,null,t),a=i.get(n)),a?.res===void 0)throw new ReferenceError("This should not happen: Alias anchor was not resolved?");if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ao(s,n,i)),a.count*a.aliasCount>o))throw new ReferenceError("Excessive alias count indicates a resource exhaustion attack")}return n}toJSON(e,t){if(!t)return{source:this.source};const r=this.resolve(t.doc,t);if(!r){const n=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(n)}return t.anchors.get(r).res}toString(e,t,r){const n=`*${this.source}`;if(e){if(Yg(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${n} `}return n}};function ao(e,t,r){if(mi(t)){const n=t.resolve(e),i=r&&n&&r.get(n);return i?i.count*i.aliasCount:0}else if(wt(t)){let n=0;for(const i of t.items){const s=ao(e,i,r);s>n&&(n=s)}return n}else if(it(t)){const n=ao(e,t.key,r),i=ao(e,t.value,r);return Math.max(n,i)}return 1}var Xg=e=>!e||typeof e!="function"&&typeof e!="object",Ke=class extends Ul{constructor(e){super(Nl),this.value=e}toJSON(e,t){return t?.keep?this.value:Bt(this.value,e,t)}toString(){return String(this.value)}};Ke.BLOCK_FOLDED="BLOCK_FOLDED";Ke.BLOCK_LITERAL="BLOCK_LITERAL";Ke.PLAIN="PLAIN";Ke.QUOTE_DOUBLE="QUOTE_DOUBLE";Ke.QUOTE_SINGLE="QUOTE_SINGLE";var UA="tag:yaml.org,2002:";function FA(e,t,r){if(t){const n=r.filter(s=>s.tag===t),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${t} not found`);return i}return r.find(n=>n.identify?.(e)&&!n.format)}function $o(e,t,r){if(Es(e)&&(e=e.contents),nt(e))return e;if(it(e)){const h=r.schema[gn].createNode?.(r.schema,null,r);return h.items.push(e),h}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<"u"&&e instanceof BigInt)&&(e=e.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=r;let c;if(n&&e&&typeof e=="object"){if(c=a.get(e),c)return c.anchor??(c.anchor=i(e)),new zA(c.anchor);c={anchor:null,node:null},a.set(e,c)}t?.startsWith("!!")&&(t=UA+t.slice(2));let u=FA(e,t,o.tags);if(!u){if(e&&typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object"){const h=new Ke(e);return c&&(c.node=h),h}u=e instanceof Map?o[gn]:Symbol.iterator in Object(e)?o[Ss]:o[gn]}s&&(s(u),delete r.onTagObj);const l=u?.createNode?u.createNode(r.schema,e,r):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(r.schema,e,r):new Ke(e);return t?l.tag=t:u.default||(l.tag=u.tag),c&&(c.node=l),l}function Mh(e,t,r){let n=r;for(let i=t.length-1;i>=0;--i){const s=t[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){const o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return $o(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:e,sourceObjects:new Map})}var qA=e=>e==null||typeof e=="object"&&!!e[Symbol.iterator]().next().done,Qg=class extends Ul{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>nt(r)||it(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(qA(e))this.add(t);else{const[r,...n]=e,i=this.get(r,!0);if(wt(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(r,Mh(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}deleteIn(e){const[t,...r]=e;if(r.length===0)return this.delete(t);const n=this.get(t,!0);if(wt(n))return n.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){const[r,...n]=e,i=this.get(r,!0);return n.length===0?!t&&st(i)?i.value:i:wt(i)?i.getIn(n,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!it(t))return!1;const r=t.value;return r==null||e&&st(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){const[t,...r]=e;if(r.length===0)return this.has(t);const n=this.get(t,!0);return wt(n)?n.hasIn(r):!1}setIn(e,t){const[r,...n]=e;if(n.length===0)this.set(r,t);else{const i=this.get(r,!0);if(wt(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(r,Mh(this.schema,n,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${n}`)}}},jA=e=>e.replace(/^(?!$)(?: $)?/gm,"#");function ls(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Fn=(e,t,r)=>e.endsWith(`
|
|
59
|
+
`)?ls(r,t):r.includes(`
|
|
60
|
+
`)?`
|
|
61
|
+
`+ls(r,t):(e.endsWith(" ")?"":" ")+r,em="flow",HA="block",BA="quoted";function va(e,t,r="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return e;i<s&&(s=0);const c=Math.max(1+s,1+i-t.length);if(e.length<=c)return e;const u=[],l={};let h=i-t.length;typeof n=="number"&&(n>i-Math.max(2,s)?u.push(0):h=i-n);let d,p,f=!1,v=-1,g=-1,m=-1;r==="block"&&(v=Lh(e,v,t.length),v!==-1&&(h=v+c));for(let S;S=e[v+=1];){if(r==="quoted"&&S==="\\"){switch(g=v,e[v+1]){case"x":v+=3;break;case"u":v+=5;break;case"U":v+=9;break;default:v+=1}m=v}if(S===`
|
|
62
|
+
`)r==="block"&&(v=Lh(e,v,t.length)),h=v+t.length+c,d=void 0;else{if(S===" "&&p&&p!==" "&&p!==`
|
|
63
|
+
`&&p!==" "){const O=e[v+1];O&&O!==" "&&O!==`
|
|
64
|
+
`&&O!==" "&&(d=v)}if(v>=h)if(d)u.push(d),h=d+c,d=void 0;else if(r==="quoted"){for(;p===" "||p===" ";)p=S,S=e[v+=1],f=!0;const O=v>m+1?v-2:g-1;if(l[O])return e;u.push(O),l[O]=!0,h=O+c,d=void 0}else f=!0}p=S}if(f&&a&&a(),u.length===0)return e;o&&o();let w=e.slice(0,u[0]);for(let S=0;S<u.length;++S){const O=u[S],R=u[S+1]||e.length;O===0?w=`
|
|
65
|
+
${t}${e.slice(0,R)}`:(r==="quoted"&&l[O]&&(w+=`${e[O]}\\`),w+=`
|
|
66
|
+
${t}${e.slice(O+1,R)}`)}return w}function Lh(e,t,r){let n=t,i=t+1,s=e[i];for(;s===" "||s===" ";)if(t<i+r)s=e[++t];else{do s=e[++t];while(s&&s!==`
|
|
67
|
+
`);n=t,i=t+1,s=e[i]}return n}var ga=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),ma=e=>/^(%|---|\.\.\.)/m.test(e);function VA(e,t,r){if(!t||t<0)return!1;const n=t-r,i=e.length;if(i<=n)return!1;for(let s=0,o=0;s<i;++s)if(e[s]===`
|
|
68
|
+
`){if(s-o>n)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Vi(e,t){const r=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return r;const{implicitKey:n}=t,i=t.options.doubleQuotedMinMultiLineLength,s=t.indent||(ma(e)?" ":"");let o="",a=0;for(let c=0,u=r[c];u;u=r[++c])if(u===" "&&r[c+1]==="\\"&&r[c+2]==="n"&&(o+=r.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(r[c+1]){case"u":{o+=r.slice(a,c);const l=r.substr(c+2,4);switch(l){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:l.substr(0,2)==="00"?o+="\\x"+l.substr(2):o+=r.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||r[c+2]==='"'||r.length<i)c+=1;else{for(o+=r.slice(a,c)+`
|
|
69
|
+
|
|
70
|
+
`;r[c+2]==="\\"&&r[c+3]==="n"&&r[c+4]!=='"';)o+=`
|
|
71
|
+
`,c+=2;o+=s,r[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+r.slice(a):r,n?o:va(o,s,BA,ga(t,!1))}function hu(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
|
|
72
|
+
`)||/[ \t]\n|\n[ \t]/.test(e))return Vi(e,t);const r=t.indent||(ma(e)?" ":""),n="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
73
|
+
${r}`)+"'";return t.implicitKey?n:va(n,r,em,ga(t,!1))}function qn(e,t){const{singleQuote:r}=t.options;let n;if(r===!1)n=Vi;else{const i=e.includes('"'),s=e.includes("'");i&&!s?n=hu:s&&!i?n=Vi:n=r?hu:Vi}return n(e,t)}var pu;try{pu=new RegExp(`(^|(?<!
|
|
74
|
+
))
|
|
75
|
+
+(?!
|
|
76
|
+
|$)`,"g")}catch{pu=/\n+(?!\n|$)/g}function co({comment:e,type:t,value:r},n,i,s){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(r))return qn(r,n);const u=n.indent||(n.forceBlockIndent||ma(r)?" ":""),l=o==="literal"?!0:o==="folded"||t===Ke.BLOCK_FOLDED?!1:t===Ke.BLOCK_LITERAL?!0:!VA(r,c,u.length);if(!r)return l?`|
|
|
77
|
+
`:`>
|
|
78
|
+
`;let h,d;for(d=r.length;d>0;--d){const O=r[d-1];if(O!==`
|
|
79
|
+
`&&O!==" "&&O!==" ")break}let p=r.substring(d);const f=p.indexOf(`
|
|
80
|
+
`);f===-1?h="-":r===p||f!==p.length-1?(h="+",s&&s()):h="",p&&(r=r.slice(0,-p.length),p[p.length-1]===`
|
|
81
|
+
`&&(p=p.slice(0,-1)),p=p.replace(pu,`$&${u}`));let v=!1,g,m=-1;for(g=0;g<r.length;++g){const O=r[g];if(O===" ")v=!0;else if(O===`
|
|
82
|
+
`)m=g;else break}let w=r.substring(0,m<g?m+1:g);w&&(r=r.substring(w.length),w=w.replace(/\n+/g,`$&${u}`));let S=(v?u?"2":"1":"")+h;if(e&&(S+=" "+a(e.replace(/ ?[\r\n]+/g," ")),i&&i()),!l){const O=r.replace(/\n+/g,`
|
|
83
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let R=!1;const I=ga(n,!0);o!=="folded"&&t!==Ke.BLOCK_FOLDED&&(I.onOverflow=()=>{R=!0});const C=va(`${w}${O}${p}`,u,HA,I);if(!R)return`>${S}
|
|
84
|
+
${u}${C}`}return r=r.replace(/\n+/g,`$&${u}`),`|${S}
|
|
85
|
+
${u}${w}${r}${p}`}function GA(e,t,r,n){const{type:i,value:s}=e,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:l}=t;if(a&&s.includes(`
|
|
86
|
+
`)||l&&/[[\]{},]/.test(s))return qn(s,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||l||!s.includes(`
|
|
87
|
+
`)?qn(s,t):co(e,t,r,n);if(!a&&!l&&i!==Ke.PLAIN&&s.includes(`
|
|
88
|
+
`))return co(e,t,r,n);if(ma(s)){if(c==="")return t.forceBlockIndent=!0,co(e,t,r,n);if(a&&c===u)return qn(s,t)}const h=s.replace(/\n+/g,`$&
|
|
89
|
+
${c}`);if(o){const d=v=>v.default&&v.tag!=="tag:yaml.org,2002:str"&&v.test?.test(h),{compat:p,tags:f}=t.doc.schema;if(f.some(d)||p?.some(d))return qn(s,t)}return a?h:va(h,c,em,ga(t,!1))}function ZA(e,t,r,n){const{implicitKey:i,inFlow:s}=t,o=typeof e.value=="string"?e:Object.assign({},e,{value:String(e.value)});let{type:a}=e;a!==Ke.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ke.QUOTE_DOUBLE);const c=l=>{switch(l){case Ke.BLOCK_FOLDED:case Ke.BLOCK_LITERAL:return i||s?qn(o.value,t):co(o,t,r,n);case Ke.QUOTE_DOUBLE:return Vi(o.value,t);case Ke.QUOTE_SINGLE:return hu(o.value,t);case Ke.PLAIN:return GA(o,t,r,n);default:return null}};let u=c(a);if(u===null){const{defaultKeyType:l,defaultStringType:h}=t.options,d=i&&l||h;if(u=c(d),u===null)throw new Error(`Unsupported default string type ${d}`)}return u}function WA(e,t){const r=Object.assign({blockQuote:!0,commentString:jA,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},e.schema.toStringOptions,t);let n;switch(r.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:e,flowCollectionPadding:r.flowCollectionPadding?" ":"",indent:"",indentStep:typeof r.indent=="number"?" ".repeat(r.indent):" ",inFlow:n,options:r}}function JA(e,t){if(t.tag){const i=e.filter(s=>s.tag===t.tag);if(i.length>0)return i.find(s=>s.format===t.format)??i[0]}let r,n;if(st(t)){n=t.value;let i=e.filter(s=>s.identify?.(n));if(i.length>1){const s=i.filter(o=>o.test);s.length>0&&(i=s)}r=i.find(s=>s.format===t.format)??i.find(s=>!s.format)}else n=t,r=e.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!r){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return r}function KA(e,t,{anchors:r,doc:n}){if(!n.directives)return"";const i=[],s=(st(e)||wt(e))&&e.anchor;s&&Yg(s)&&(r.add(s),i.push(`&${s}`));const o=e.tag??(t.default?null:t.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function xo(e,t,r,n){if(it(e))return e.toString(t,r,n);if(mi(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw new TypeError("Cannot stringify circular structure without alias nodes");t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i;const s=nt(e)?e:t.doc.createNode(e,{onTagObj:c=>i=c});i??(i=JA(t.doc.schema.tags,s));const o=KA(s,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(s,t,r,n):st(s)?ZA(s,t,r,n):s.toString(t,r,n);return o?st(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
90
|
+
${t.indent}${a}`:a}function YA({key:e,value:t},r,n,i){const{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:l,simpleKeys:h}}=r;let d=nt(e)&&e.comment||null;if(h){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(wt(e)||!nt(e)&&typeof e=="object")throw new Error("With simple keys, collection cannot be used as a key value")}let p=!h&&(!e||d&&t==null&&!r.inFlow||wt(e)||(st(e)?e.type===Ke.BLOCK_FOLDED||e.type===Ke.BLOCK_LITERAL:typeof e=="object"));r=Object.assign({},r,{allNullValues:!1,implicitKey:!p&&(h||!s),indent:a+c});let f=!1,v=!1,g=xo(e,r,()=>f=!0,()=>v=!0);if(!p&&!r.inFlow&&g.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(r.inFlow){if(s||t==null)return f&&n&&n(),g===""?"?":p?`? ${g}`:g}else if(s&&!h||t==null&&p)return g=`? ${g}`,d&&!f?g+=Fn(g,r.indent,u(d)):v&&i&&i(),g;f&&(d=null),p?(d&&(g+=Fn(g,r.indent,u(d))),g=`? ${g}
|
|
91
|
+
${a}:`):(g=`${g}:`,d&&(g+=Fn(g,r.indent,u(d))));let m,w,S;nt(t)?(m=!!t.spaceBefore,w=t.commentBefore,S=t.comment):(m=!1,w=null,S=null,t&&typeof t=="object"&&(t=o.createNode(t))),r.implicitKey=!1,!p&&!d&&st(t)&&(r.indentAtStart=g.length+1),v=!1,!l&&c.length>=2&&!r.inFlow&&!p&&fa(t)&&!t.flow&&!t.tag&&!t.anchor&&(r.indent=r.indent.substring(2));let O=!1;const R=xo(t,r,()=>O=!0,()=>v=!0);let I=" ";if(d||m||w){if(I=m?`
|
|
92
|
+
`:"",w){const C=u(w);I+=`
|
|
93
|
+
${ls(C,r.indent)}`}R===""&&!r.inFlow?I===`
|
|
94
|
+
`&&S&&(I=`
|
|
95
|
+
|
|
96
|
+
`):I+=`
|
|
97
|
+
${r.indent}`}else if(!p&&wt(t)){const C=R[0],L=R.indexOf(`
|
|
98
|
+
`),q=L!==-1,K=r.inFlow??t.flow??t.items.length===0;if(q||!K){let X=!1;if(q&&(C==="&"||C==="!")){let k=R.indexOf(" ");C==="&"&&k!==-1&&k<L&&R[k+1]==="!"&&(k=R.indexOf(" ",k+1)),(k===-1||L<k)&&(X=!0)}X||(I=`
|
|
99
|
+
${r.indent}`)}}else(R===""||R[0]===`
|
|
100
|
+
`)&&(I="");return g+=I+R,r.inFlow?O&&n&&n():S&&!O?g+=Fn(g,r.indent,u(S)):v&&i&&i(),g}function XA(e,t){(e==="debug"||e==="warn")&&console.warn(t)}var zs="<<",ic={identify:e=>e===zs||typeof e=="symbol"&&e.description===zs,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ke(Symbol(zs)),{addToJSMap:tm}),stringify:()=>zs},QA=(e,t)=>(ic.identify(t)||st(t)&&(!t.type||t.type===Ke.PLAIN)&&ic.identify(t.value))&&e?.doc.schema.tags.some(r=>r.tag===ic.tag&&r.default);function tm(e,t,r){const n=rm(e,r);if(fa(n))for(const i of n.items)sc(e,t,i);else if(Array.isArray(n))for(const i of n)sc(e,t,i);else sc(e,t,n)}function sc(e,t,r){const n=rm(e,r);if(!Dl(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,e,Map);for(const[s,o]of i)t instanceof Map?t.has(s)||t.set(s,o):t instanceof Set?t.add(s):Object.prototype.hasOwnProperty.call(t,s)||Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return t}function rm(e,t){return e&&mi(t)?t.resolve(e.doc,e):t}function nm(e,t,{key:r,value:n}){if(nt(r)&&r.addToJSMap)r.addToJSMap(e,t,n);else if(QA(e,r))tm(e,t,n);else{const i=Bt(r,"",e);if(t instanceof Map)t.set(i,Bt(n,i,e));else if(t instanceof Set)t.add(i);else{const s=eT(r,i,e),o=Bt(n,s,e);s in t?Object.defineProperty(t,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[s]=o}}return t}function eT(e,t,r){if(t===null)return"";if(typeof t!="object")return String(t);if(nt(e)&&r?.doc){const n=WA(r.doc,{});n.anchors=new Set;for(const s of r.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=e.toString(n);if(!r.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),XA(r.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),r.mapKeyWarned=!0}return i}return JSON.stringify(t)}function Fl(e,t,r){const n=$o(e,void 0,r),i=$o(t,void 0,r);return new mn(n,i)}var mn=class im{constructor(t,r=null){Object.defineProperty(this,nr,{value:Bg}),this.key=t,this.value=r}clone(t){let{key:r,value:n}=this;return nt(r)&&(r=r.clone(t)),nt(n)&&(n=n.clone(t)),new im(r,n)}toJSON(t,r){const n=r?.mapAsMap?new Map:{};return nm(r,n,this)}toString(t,r,n){return t?.doc?YA(this,t,r,n):JSON.stringify(this)}};function sm(e,t,r){return(t.inFlow??e.flow?rT:tT)(e,t,r)}function tT({comment:e,items:t},r,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=r,l=Object.assign({},r,{indent:s,type:null});let h=!1;const d=[];for(let f=0;f<t.length;++f){const v=t[f];let g=null;if(nt(v))!h&&v.spaceBefore&&d.push(""),Mo(r,d,v.commentBefore,h),v.comment&&(g=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(!h&&w.spaceBefore&&d.push(""),Mo(r,d,w.commentBefore,h))}h=!1;let m=xo(v,l,()=>g=null,()=>h=!0);g&&(m+=Fn(m,s,u(g))),h&&g&&(h=!1),d.push(n+m)}let p;if(d.length===0)p=i.start+i.end;else{p=d[0];for(let f=1;f<d.length;++f){const v=d[f];p+=v?`
|
|
101
|
+
${c}${v}`:`
|
|
102
|
+
`}}return e?(p+=`
|
|
103
|
+
`+ls(u(e),c),a&&a()):h&&o&&o(),p}function rT({items:e},t,{flowChars:r,itemIndent:n}){const{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=t;n+=s;const c=Object.assign({},t,{indent:n,inFlow:!0,type:null});let u=!1,l=0;const h=[];for(let f=0;f<e.length;++f){const v=e[f];let g=null;if(nt(v))v.spaceBefore&&h.push(""),Mo(t,h,v.commentBefore,!1),v.comment&&(g=v.comment);else if(it(v)){const w=nt(v.key)?v.key:null;w&&(w.spaceBefore&&h.push(""),Mo(t,h,w.commentBefore,!1),w.comment&&(u=!0));const S=nt(v.value)?v.value:null;S?(S.comment&&(g=S.comment),S.commentBefore&&(u=!0)):v.value==null&&w?.comment&&(g=w.comment)}g&&(u=!0);let m=xo(v,c,()=>g=null);u||(u=h.length>l||m.includes(`
|
|
104
|
+
`)),f<e.length-1?m+=",":t.options.trailingComma&&(t.options.lineWidth>0&&(u||(u=h.reduce((w,S)=>w+S.length+2,2)+(m.length+2)>t.options.lineWidth)),u&&(m+=",")),g&&(m+=Fn(m,n,a(g))),h.push(m),l=h.length}const{start:d,end:p}=r;if(h.length===0)return d+p;if(!u){const f=h.reduce((v,g)=>v+g.length+2,2);u=t.options.lineWidth>0&&f>t.options.lineWidth}if(u){let f=d;for(const v of h)f+=v?`
|
|
105
|
+
${s}${i}${v}`:`
|
|
106
|
+
`;return`${f}
|
|
107
|
+
${i}${p}`}else return`${d}${o}${h.join(" ")}${o}${p}`}function Mo({indent:e,options:{commentString:t}},r,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const s=ls(t(n),e);r.push(s.trimStart())}}function pn(e,t){const r=st(t)?t.value:t;for(const n of e)if(it(n)&&(n.key===t||n.key===r||st(n.key)&&n.key.value===r))return n}var Pr=class extends Qg{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(gn,e),this.items=[]}static from(e,t,r){const{keepUndefined:n,replacer:i}=r,s=new this(e),o=(a,c)=>{if(typeof i=="function")c=i.call(t,a,c);else if(Array.isArray(i)&&!i.includes(a))return;(c!==void 0||n)&&s.items.push(Fl(a,c,r))};if(t instanceof Map)for(const[a,c]of t)o(a,c);else if(t&&typeof t=="object")for(const a of Object.keys(t))o(a,t[a]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let r;it(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new mn(e,e?.value):r=new mn(e.key,e.value);const n=pn(this.items,r.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${r.key} already set`);st(n.value)&&Xg(r.value)?n.value.value=r.value:n.value=r.value}else if(i){const s=this.items.findIndex(o=>i(r,o)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){const t=pn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=pn(this.items,e)?.value;return(!t&&st(r)?r.value:r)??void 0}has(e){return!!pn(this.items,e)}set(e,t){this.add(new mn(e,t),!0)}toJSON(e,t,r){const n=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(n);for(const i of this.items)nm(t,n,i);return n}toString(e,t,r){if(!e)return JSON.stringify(this);for(const n of this.items)if(!it(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),sm(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}},nT={collection:"map",default:!0,nodeClass:Pr,tag:"tag:yaml.org,2002:map",resolve(e,t){return Dl(e)||t("Expected a mapping for this tag"),e},createNode:(e,t,r)=>Pr.from(e,t,r)},Lo=class extends Qg{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ss,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Us(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const r=Us(e);if(typeof r!="number")return;const n=this.items[r];return!t&&st(n)?n.value:n}has(e){const t=Us(e);return typeof t=="number"&&t<this.items.length}set(e,t){const r=Us(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);const n=this.items[r];st(n)&&Xg(t)?n.value=t:this.items[r]=t}toJSON(e,t){const r=[];t?.onCreate&&t.onCreate(r);let n=0;for(const i of this.items)r.push(Bt(i,String(n++),t));return r}toString(e,t,r){return e?sm(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){const{replacer:n}=r,i=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let o of t){if(typeof n=="function"){const a=t instanceof Set?o:String(s++);o=n.call(t,a,o)}i.items.push($o(o,void 0,r))}}return i}};function Us(e){let t=st(e)?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),typeof t=="number"&&Number.isInteger(t)&&t>=0?t:null}var iT={collection:"seq",default:!0,nodeClass:Lo,tag:"tag:yaml.org,2002:seq",resolve(e,t){return fa(e)||t("Expected a sequence for this tag"),e},createNode:(e,t,r)=>Lo.from(e,t,r)};function Nh(e){return typeof e=="bigint"||Number.isInteger(e)}var Fs=({value:e})=>JSON.stringify(e),sT=[{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:e=>e,stringify:Fs},{identify:e=>e==null,createNode:()=>new Ke(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Fs},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:e=>e==="true",stringify:Fs},{identify:Nh,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:r})=>r?BigInt(e):parseInt(e,10),stringify:({value:e})=>Nh(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Fs}],WD=[nT,iT].concat(sT,{default:!0,tag:"",test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function oT(e,t,r){const{replacer:n}=r,i=new Lo(e);i.tag="tag:yaml.org,2002:pairs";let s=0;if(t&&Symbol.iterator in Object(t))for(let o of t){typeof n=="function"&&(o=n.call(t,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(Fl(a,c,r))}return i}var aT=class om extends Lo{constructor(){super(),this.add=Pr.prototype.add.bind(this),this.delete=Pr.prototype.delete.bind(this),this.get=Pr.prototype.get.bind(this),this.has=Pr.prototype.has.bind(this),this.set=Pr.prototype.set.bind(this),this.tag=om.tag}toJSON(t,r){if(!r)return super.toJSON(t);const n=new Map;r?.onCreate&&r.onCreate(n);for(const i of this.items){let s,o;if(it(i)?(s=Bt(i.key,"",r),o=Bt(i.value,s,r)):s=Bt(i,"",r),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(t,r,n){const i=oT(t,r,n),s=new this;return s.items=i.items,s}};aT.tag="tag:yaml.org,2002:omap";var cT=class am extends Pr{constructor(t){super(t),this.tag=am.tag}add(t){let r;it(t)?r=t:t&&typeof t=="object"&&"key"in t&&"value"in t&&t.value===null?r=new mn(t.key,null):r=new mn(t,null),pn(this.items,r.key)||this.items.push(r)}get(t,r){const n=pn(this.items,t);return!r&&it(n)?st(n.key)?n.key.value:n.key:n}set(t,r){if(typeof r!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof r}`);const n=pn(this.items,t);n&&!r?this.items.splice(this.items.indexOf(n),1):!n&&r&&this.items.push(new mn(t))}toJSON(t,r){return super.toJSON(t,r,Set)}toString(t,r,n){if(!t)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},t,{allNullValues:!0}),r,n);throw new Error("Set items must all have null values")}static from(t,r,n){const{replacer:i}=n,s=new this(t);if(r&&Symbol.iterator in Object(r))for(let o of r)typeof i=="function"&&(o=i.call(r,o,o)),s.items.push(Fl(o,null,n));return s}};cT.tag="tag:yaml.org,2002:set";var fu=Symbol("break visit"),uT=Symbol("skip children"),cm=Symbol("remove item");function ni(e,t){"type"in e&&e.type==="document"&&(e={start:e.start,value:e.value}),um(Object.freeze([]),e,t)}ni.BREAK=fu;ni.SKIP=uT;ni.REMOVE=cm;ni.itemAtPath=(e,t)=>{let r=e;for(const[n,i]of t){const s=r?.[n];if(s&&"items"in s)r=s.items[i];else return}return r};ni.parentCollection=(e,t)=>{const r=ni.itemAtPath(e,t.slice(0,-1)),n=t[t.length-1][0],i=r?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function um(e,t,r){let n=r(t,e);if(typeof n=="symbol")return n;for(const i of["key","value"]){const s=t[i];if(s&&"items"in s){for(let o=0;o<s.items.length;++o){const a=um(Object.freeze(e.concat([[i,o]])),s.items[o],r);if(typeof a=="number")o=a-1;else{if(a===fu)return fu;a===cm&&(s.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(t,e))}}return typeof n=="function"?n(t,e):n}var vu=["2025-03-26","2025-06-18","2025-11-25","2026-07-28"],lT=vu[vu.length-1];function qs(e){return e===lT?`Latest (${e})`:e}var dT=new Set(["2024-10-07","2024-11-05","2025-03-26","2025-06-18","2025-11-25"]);function hT(e){return vu.includes(e)}function pT(e){return e.length>0&&!dT.has(e)}var fT=["verified","refuted","unverifiable"],vT=["oauth2-dcr","oauth2-cimd","oauth2-preregistered","api-key","none"],gT=["omit","fixed","challenge","all-supported"],mT=["none","client_secret_basic","client_secret_post"],_T=["hosted","org","local"],_a=["none","minimal","low","medium","high","xhigh","max"],yT=["none","openrouter"],bT=new Set(["modelId","source","connectionRef","nativeModelId","settings","fallback"]),wT=new Set(["kind","id"]),ST=new Set(["kind","providerKey","customProviderName"]),ET=new Set(["reasoningEffort","temperature"]),kT=new Set(["provider","model"]),IT=new Set(_T),AT=new Set(_a),TT=new Set(yT),RT=/^[a-z0-9][a-z0-9._:-]*\/[^\s/]\S*$/;function ii(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function PT(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Nr(e,t){return e===""?t:`${e}.${t}`}function ds(e,t,r,n){for(const i of Object.keys(e))t.has(i)||n.push({path:Nr(r,i),code:"unknown_key",message:`unknown key "${i}" (a selection never carries credentials)`})}function Gi(e,t,r,n,i){const s=Nr(r,t);if(!PT(e,t)||e[t]===void 0){i&&n.push({path:s,code:"required",message:"is required"});return}const o=e[t];if(typeof o!="string"){n.push({path:s,code:"invalid_type",message:"must be a string"});return}if(o.trim()===""||o.trim()!==o){n.push({path:s,code:"invalid_value",message:"must be a non-empty string without surrounding whitespace"});return}return o}function OT(e,t){const r="connectionRef";if(!ii(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}if(e.kind==="orgProvider"){ds(e,wT,r,t);const n=Gi(e,"id",r,t,!0);return n===void 0?void 0:{kind:"orgProvider",id:n}}if(e.kind==="localProvider"){ds(e,ST,r,t);const n=Gi(e,"providerKey",r,t,!0),i=Gi(e,"customProviderName",r,t,!1);return n===void 0?void 0:{kind:"localProvider",providerKey:n,...i!==void 0?{customProviderName:i}:{}}}t.push({path:Nr(r,"kind"),code:e.kind===void 0?"required":"invalid_value",message:'must be "orgProvider" or "localProvider"'})}function CT(e,t){const r="settings";if(!ii(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}ds(e,ET,r,t);const n={};if(e.reasoningEffort!==void 0&&(typeof e.reasoningEffort=="string"&&AT.has(e.reasoningEffort)?n.reasoningEffort=e.reasoningEffort:t.push({path:Nr(r,"reasoningEffort"),code:"invalid_value",message:`must be one of ${_a.map(i=>`"${i}"`).join(", ")}`})),e.temperature!==void 0){const i=e.temperature;typeof i!="number"||!Number.isFinite(i)?t.push({path:Nr(r,"temperature"),code:"invalid_type",message:"must be a finite number"}):i<0||i>2?t.push({path:Nr(r,"temperature"),code:"out_of_range",message:"must be within [0, 2]"}):n.temperature=i}return n}function $T(e,t){const r="fallback";if(e===void 0){t.push({path:r,code:"required",message:"is required"});return}if(!ii(e)){t.push({path:r,code:"invalid_type",message:"must be a plain object"});return}ds(e,kT,r,t);let n=!0;if((typeof e.provider!="string"||!TT.has(e.provider))&&(n=!1,t.push({path:Nr(r,"provider"),code:e.provider===void 0?"required":"invalid_value",message:'must be "none" or "openrouter"'})),e.model!=="none"&&(n=!1,t.push({path:Nr(r,"model"),code:e.model===void 0?"required":"invalid_value",message:'must be "none" (no surface substitutes a different model)'})),!!n)return{provider:e.provider,model:"none"}}function JD(e){const t=[];if(!ii(e))return{ok:!1,issues:[{path:"",code:"invalid_type",message:"must be a plain object"}]};ds(e,bT,"",t);const r=Gi(e,"modelId","",t,!0);r!==void 0&&!RT.test(r)&&t.push({path:"modelId",code:"model_id_not_canonical",message:`"${r}" is not a canonical "provider/model" id`});let n;e.source===void 0?t.push({path:"source",code:"required",message:"is required"}):typeof e.source=="string"&&IT.has(e.source)?n=e.source:t.push({path:"source",code:"invalid_value",message:e.source==="legacy"?'"legacy" is read-only: a legacy selection is never saved':'must be "hosted", "org" or "local"'});const i=e.connectionRef===void 0?void 0:OT(e.connectionRef,t);if(n==="hosted"&&e.connectionRef!==void 0)t.push({path:"connectionRef",code:"connection_ref_mismatch",message:'must be absent when source is "hosted"'});else if(n==="org"||n==="local"){const u=n==="org"?"orgProvider":"localProvider";e.connectionRef===void 0?t.push({path:"connectionRef",code:"connection_ref_mismatch",message:`is required when source is "${n}" (kind "${u}")`}):ii(e.connectionRef)&&(e.connectionRef.kind==="orgProvider"||e.connectionRef.kind==="localProvider")&&e.connectionRef.kind!==u&&t.push({path:"connectionRef.kind",code:"connection_ref_mismatch",message:`must be "${u}" when source is "${n}"`})}const s=Gi(e,"nativeModelId","",t,!1),o=e.settings===void 0?void 0:CT(e.settings,t),a=$T(e.fallback,t);if(t.length>0)return{ok:!1,issues:t};const c=o!==void 0&&(o.reasoningEffort!==void 0||o.temperature!==void 0);return{ok:!0,selection:{modelId:r,source:n,...i!==void 0?{connectionRef:i}:{},...s!==void 0?{nativeModelId:s}:{},...c?{settings:{...o.reasoningEffort!==void 0?{reasoningEffort:o.reasoningEffort}:{},...o.temperature!==void 0?{temperature:o.temperature}:{}}}:{},fallback:a}}}function KD(e){return ii(e)&&e.source==="legacy"&&typeof e.modelId=="string"&&e.modelId.trim()!==""}function YD(e){const t=encodeURIComponent;let r="";if(e.source!=="legacy"&&e.connectionRef){const n=e.connectionRef;r=n.kind==="orgProvider"?t(n.id):n.customProviderName!==void 0?`${t(n.providerKey)}:${t(n.customProviderName)}`:t(n.providerKey)}return`${e.source}:${r}:${t(e.modelId)}`}function XD(e){return{provider:e==="chat"?"openrouter":"none",model:"none"}}var xT=["inline","fullscreen","pip"],QD=new Set(xT),uo=["mode","originAllowlist"],ez={allow_all:new Set(uo),read_only:new Set(uo),allowlist:new Set([...uo,"toolAllowlist"])},tz=new Set([...uo,"toolAllowlist"]),rz=new Set(gT),nz=new Set(mT),iz=new Set(fT),sz=new Set(vT),MT=["clientName","redirectUris","userAgent"],oz=new Set(MT);function LT(e){const t=new Uint8Array(e);let r="";for(let n=0;n<t.length;n++)r+=t[n].toString(16).padStart(2,"0");return r}async function lm(e){const t=new TextEncoder().encode(e);return LT(await crypto.subtle.digest("SHA-256",t))}function gu(e){return Array.isArray(e)?e.map(gu):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>[t,gu(r)])):e}function NT(e){return JSON.stringify(gu(e))}function az(e,t){if(t==="openai-apps"){const n=e;return typeof n?.type=="string"?n.type.replace("openai:",""):"unknown"}const r=e;return typeof r?.method=="string"?r.method:r?.result!==void 0?"result":r?.error!==void 0?"error":"unknown"}async function cz(e){const t=await crypto.subtle.digest("SHA-256",e),r=new Uint8Array(t);let n="";for(let i=0;i<r.length;i++)n+=r[i].toString(16).padStart(2,"0");return n}async function uz(e){return lm(NT(e))}async function DT(e){const t=[...e].sort((r,n)=>r.path<n.path?-1:r.path>n.path?1:0);return lm(t.map(r=>`${r.path}\0${r.contentHash}\0`).join(""))}var zT=/^[A-Za-z]:[\\/]/,UT=/[\u0000-\u001f\u007f]/,FT=new TextEncoder;function qT(e){return FT.encode(e).length}function jT(e){let t=e.length;for(;t>0;){const r=e[t-1];if(r!=="."&&r!==" ")break;t-=1}return e.slice(0,t)}function dm(e){if(typeof e!="string"||e.length===0)return{ok:!1,code:"PATH_EMPTY",message:"path is empty"};if(e.includes("\0"))return{ok:!1,code:"PATH_NUL_BYTE",message:"path contains a NUL byte"};if(UT.test(e))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:"path contains control characters"};if(e.startsWith("/")||e.startsWith("\\")||zT.test(e))return{ok:!1,code:"PATH_ABSOLUTE",message:`absolute paths are not allowed: "${e}"`};const t=e.replace(/\\/g,"/").split("/").filter(r=>r!==""&&r!==".");for(const r of t){if(r==="..")return{ok:!1,code:"PATH_TRAVERSAL",message:`path traversal ("..") is not allowed: "${e}"`};if(r.includes(":"))return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segments must not contain ":" (drive prefix / alternate data stream): "${e}"`};const n=jT(r);if(n===""||n==="."||n==="..")return{ok:!1,code:"PATH_INVALID_CHARACTER",message:`path segment "${r}" is not portable (empty or dot name after trailing dot/space stripping)`}}return t.length===0?{ok:!1,code:"PATH_EMPTY",message:"path is empty"}:{ok:!0,path:t.join("/").normalize("NFC")}}function HT(e){return e.normalize("NFKC").toLowerCase()}function lz(e,t){return t===e||t.startsWith(`${e}/`)}function dz(e,t){const r=dm(t);return r.ok?{ok:!0,path:e===""?r.path:`${e}/${r.path}`}:r.code==="PATH_ABSOLUTE"||r.code==="PATH_TRAVERSAL"?{ok:!1,code:"PATH_ESCAPES_ROOT",message:`referenced path escapes the bundle root: "${t}"`}:r}function hz(e,t,r){e.length>t.maxEntries&&r.error("BUNDLE_TOO_MANY_ENTRIES",`bundle has ${e.length} entries; the limit is ${t.maxEntries}`);const n=new Set,i=new Map,s=[];let o=0,a=!1;for(const c of e){if(c.kind==="symlink"||c.kind==="hardlink"){r.error("PATH_LINK_ENTRY",`${c.kind} entries are not allowed`,{path:c.path});continue}const u=dm(c.path);if(!u.ok){r.error(u.code,u.message,{path:c.path});continue}const l=u.path;if(qT(l)>t.maxPathBytes){r.error("PATH_TOO_LONG",`path exceeds ${t.maxPathBytes} bytes`,{path:l});continue}if(l.split("/").length>t.maxPathDepth){r.error("PATH_TOO_DEEP",`path exceeds nesting depth ${t.maxPathDepth}`,{path:l});continue}if(n.has(l)){r.error("PATH_DUPLICATE",`duplicate normalized path: "${l}"`,{path:c.path});continue}n.add(l);const h=HT(l),d=i.get(h);if(d!==void 0){r.error("PATH_CASE_COLLISION",`"${l}" collides with "${d}" on case-insensitive filesystems`,{path:l});continue}if(i.set(h,l),c.kind!=="directory"){if(!Number.isFinite(c.size)||c.size<0){r.error("FILE_SIZE_MISMATCH","entry declares an invalid size",{path:l});continue}if(c.size>t.maxFileBytes){r.error("FILE_TOO_LARGE",`file exceeds the per-file limit of ${t.maxFileBytes} bytes`,{path:l});continue}o+=c.size,!a&&o>t.maxTotalBytes&&(a=!0,r.error("BUNDLE_TOO_LARGE",`total uncompressed content exceeds ${t.maxTotalBytes} bytes`)),s.push({sourcePath:c.path,path:l,size:c.size})}}return s.sort((c,u)=>c.path<u.path?-1:c.path>u.path?1:0),s}var BT=class extends Error{code;issues;constructor(e){const t=e.find(n=>n.severity==="error"),r=t?.code??"MANIFEST_INVALID_FIELD";super(t?`plugin bundle validation failed: ${t.code}: ${t.message}`:"plugin bundle validation failed"),this.name="PluginBundleError",this.code=r,this.issues=e}},pz=class{all=[];error(e,t,r){this.all.push({code:e,severity:"error",message:t,...r})}warn(e,t,r){this.all.push({code:e,severity:"warning",message:t,...r})}hasErrors(){return this.all.some(e=>e.severity==="error")}issues(){return[...this.all]}warnings(){return this.all.filter(e=>e.severity==="warning")}throwIfErrors(){if(this.hasErrors())throw new BT(this.issues())}absorbDemoted(e){for(const t of e.issues())this.all.push(t.severity==="error"?{...t,severity:"warning"}:t)}firstErrorMessage(){return this.all.find(e=>e.severity==="error")?.message}};var VT=/(secret|token|password|passwd|api[-_]?key|private[-_]?key|credential)/i,hm=/(bearer\s+\S|-----BEGIN|\b(?:sk|pk|rk|xox[a-z])-[A-Za-z0-9]|[a-z][a-z0-9+.-]*:\/\/[^/\s:@]*:[^/\s@]+@|[A-Za-z0-9+/_-]{40,})/i;function fz(e){return hm.test(e)}var ki=Symbol("drop");function mu(e,t,r,n,i){if(r>32)return i.reportedTooDeep||(i.reportedTooDeep=!0,n.issues.error("VALUE_TOO_DEEP",`${n.label}: field "${t}" nests deeper than 32 levels`,n.context)),ki;if(typeof e=="string")return hm.test(e)?(n.issues.warn(n.secretCode,`${n.label}: value of "${t}" looks secret-bearing and is not stored`,n.context),ki):e;if(typeof e=="number"||typeof e=="boolean"||e===null)return e;if(Array.isArray(e)){const s=[];for(let o=0;o<e.length;o++){const a=mu(e[o],`${t}[${o}]`,r+1,n,i);a!==ki&&s.push(a)}return s}if(typeof e=="object"){const s={};for(const[o,a]of Object.entries(e)){const c=t===""?o:`${t}.${o}`;if(VT.test(o)){n.issues.warn(n.secretCode,`${n.label}: field "${c}" looks secret-bearing and is not stored`,n.context);continue}const u=mu(a,c,r+1,n,i);u!==ki&&(s[o]=u)}return s}return ki}function vz(e,t){return mu(e,"",0,t,{reportedTooDeep:!1})}var gz="skills",mz="SKILL.md",pm=64,Dh=1024;function GT(e){return e.length<1||e.length>pm||e.includes("--")?!1:/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(e)}var _u=class extends Error{constructor(){super("yaml value nests too deeply"),this.name="YamlValueTooDeepError"}};function yu(e,t=0){const r=e.trim();if(r.length>=2&&(r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")))return r.slice(1,-1);if(r==="true")return!0;if(r==="false")return!1;if(r==="null"||r==="~")return null;if(/^-?\d+(\.\d+)?$/.test(r))return Number(r);if(r.startsWith("[")&&r.endsWith("]")){if(t>=32)throw new _u;const n=r.slice(1,-1).trim();return n===""?[]:n.split(",").map(i=>yu(i,t+1))}return r}function ZT(e){const t={},r=[],n=[],i=e.split(/\r?\n/);let s=0;for(;s<i.length;){const o=i[s];if(/^\s*$/.test(o)||/^\s*#/.test(o)){s++;continue}const a=/^([A-Za-z0-9_.-]+):\s*(.*)$/.exec(o);if(!a){r.push(o),s++;continue}const c=a[1],u=a[2];if(u===""){const l=[];let h=s+1;for(;h<i.length;){const d=i[h];if(/^\s*$/.test(d)||/^\s*#/.test(d)){h++;continue}const p=/^\s+-\s*(.*)$/.exec(d);if(p){try{l.push(yu(p[1]))}catch(f){if(!(f instanceof _u))throw f;n.push(d)}h++;continue}if(/^\s+\S/.test(d)){r.push(d),h++;continue}break}l.length>0?t[c]=l:t[c]="",s=h;continue}if(u==="|"||u==="|-"||u===">"||u===">-"){const l=[];let h=null,d=s+1;for(;d<i.length;){const p=i[d];if(/^\s*$/.test(p)){l.push(""),d++;continue}const f=p.length-p.trimStart().length;if(f===0)break;h===null&&(h=f),l.push(p.slice(Math.min(h,f))),d++}for(;l.length>0&&l[l.length-1]==="";)l.pop();t[c]=u.startsWith("|")?l.join(`
|
|
108
|
+
`):l.map(p=>p||`
|
|
109
|
+
`).join(" "),s=d;continue}try{t[c]=yu(u)}catch(l){if(!(l instanceof _u))throw l;n.push(o)}s++}return{data:t,unparsed:r,tooDeep:n}}function WT(e){const t=/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(e);return t?{frontmatter:t[1],body:e.slice(t[0].length)}:null}function JT(e){return!Array.isArray(e)||e.some(t=>typeof t!="string")?null:e}async function _z(e){const{pluginName:t,directory:r,directoryName:n,skillFilePath:i,skillText:s,skillContentHash:o,files:a,issues:c}=e,u=`skill:${n}`,l={path:i,componentKey:u},h=WT(s);if(h===null)return c.error("SKILL_FRONTMATTER_MISSING",`skill "${n}" is missing YAML frontmatter in SKILL.md`,l),null;const{data:d,unparsed:p,tooDeep:f}=ZT(h.frontmatter);for(const C of p)c.warn("SKILL_FRONTMATTER_UNPARSED",`skill "${n}": frontmatter line not interpreted: ${C.trim()}`,l);for(const C of f)c.error("VALUE_TOO_DEEP",`skill "${n}": frontmatter value nests deeper than 32 levels: ${C.trim().slice(0,80)}`,l);const v=d.name;if(typeof v!="string"||v.length===0)return c.error("SKILL_MISSING_NAME",`skill "${n}" is missing the required "name" field`,l),null;if(!GT(v))return c.error("SKILL_INVALID_NAME",`skill name "${v}" must be kebab-case ([a-z0-9-], 1-${pm} chars, no "--")`,l),null;v!==n&&c.warn("SKILL_NAME_MISMATCH",`skill name "${v}" does not match its directory "${n}"`,l);const g=d.description;if(typeof g!="string"||g.length===0)return c.error("SKILL_MISSING_DESCRIPTION",`skill "${n}" is missing the required "description" field`,l),null;if(g.length>Dh)return c.error("SKILL_DESCRIPTION_TOO_LONG",`skill "${n}" description exceeds ${Dh} characters`,l),null;let m;const w=d.allow_implicit_invocation;w!==void 0&&(typeof w!="boolean"?c.warn("SKILL_INVALID_METADATA",`skill "${n}": "allow_implicit_invocation" must be a boolean`,l):m=w);const S=[],O=d.mcp_tools;if(O!==void 0){const C=JT(O);if(C===null)c.warn("SKILL_INVALID_METADATA",`skill "${n}": "mcp_tools" must be a list of strings`,l);else for(const L of C)S.includes(L)||S.push(L)}const R=a.filter(C=>C.path!==i).map(C=>({path:C.path,relativePath:C.path.slice(r.length+1),size:C.size,contentHash:C.contentHash})),I=await DT(a.map(C=>({path:C.path.slice(r.length+1),contentHash:C.contentHash})));return{componentKey:u,directory:r,directoryName:n,skillFilePath:i,name:v,description:g,modelRef:`${t}/${v}`,instructions:h.body.trim(),frontmatter:d,frontmatterRaw:h.frontmatter,...m!==void 0?{allowImplicitInvocation:m}:{},mcpToolDependencies:S,supportingFiles:R,contentHash:o,aggregateHash:I}}var yz=new TextDecoder("utf-8",{fatal:!1}),KT=new Set(["access_token","refresh_token","id_token","client_secret","code","code_verifier","authorization_code","authorization","state","cookie","set_cookie","api_key"]),YT=[/^authorization$/i,/^proxy-authorization$/i,/^cookie$/i,/^set-cookie$/i,/^x-api-key$/i,/^api-key$/i,/^apikey$/i,/^x-auth-token$/i,/^x-csrf-token$/i,/^x-session-token$/i,/^x-access-token$/i,/^x-refresh-token$/i,/^x-client-secret$/i,/^x-credential$/i];function ql(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9]+/g,"_").toLowerCase()}var XT=["_type","_types","_endpoint","_endpoints","_supported","_method","_methods","_uri","_uris","_url","_urls","_alg","_algs","_values","_in"];function QT(e){return XT.some(t=>e.endsWith(t))}function jl(e){return KT.has(e)?!0:QT(e)?!1:/(^|_)(token|secret|password|credential|cookie|auth)(_|$)/.test(e)||/(^|_)api_?key(_|$)/.test(e)}function eR(e){return jl(ql(e))}function tR(e){return jl(ql(e))||YT.some(t=>t.test(e))}function rR(e){return jl(ql(e))}function Hl(e){return typeof e!="string"||e.length<=8?"[redacted]":`${e.slice(0,4)}...[redacted]...${e.slice(-2)}`}var fm="client_secret|access_token|refresh_token|id_token|code_verifier|code|assertion|password|api[-_]?key|token|secret|state",vm=new RegExp(`(^|[^\\w-])((?:[\\w-]*[_-])?(?:${fm}))=[^&\\s"'<>]+`,"gi"),gm=`(?:(?:[\\w-]*[_-])?(?:${fm}))`,nR=new RegExp(`("${gm}"\\s*:\\s*)"(?:\\\\.|[^"\\\\])*"`,"gi"),iR=new RegExp(`("${gm}"\\s*:\\s*)"(?:\\\\[\\s\\S]?|[^"\\\\])*$`,"gi");var sR=new RegExp(`\\b((?:[\\w-]*[_-])?(?:client[-_]?secret|access[-_]?token|refresh[-_]?token|id[-_]?token|code[-_]?verifier))(\\s*[:=]\\s*)("(?:\\\\.|[^"\\\\])*"|[^&\\s"'<>,;]+)`,"gi");function mm(e){const t=e.replace(/[.,;:!?)\]}]+$/,"");return!/^[a-z]{1,20}$/.test(t)}function oR(e,t,r,n){return mm(n)?`${t}${r}[redacted]`:e}function Dr(e,t={}){const r=t.maxScanned??4e3,n=t.maxLength??500,i=e.length>r,s=(i?e.slice(0,r):e).replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*@/gi,"$1[redacted]@").replace(/(^|[\s(<"'])[^\s/@:]+:[^\s/]+@(?=[\w.-]+)/g,"$1[redacted]@").replace(sR,(o,a,c,u)=>`${a}${c}${u.startsWith('"')?'"[redacted]"':"[redacted]"}`).replace(vm,"$1$2=[redacted]").replace(/\b((?:proxy-)?authorization\s*[:=]\s*)(bearer|basic)\s+\S+/gi,"$1$2 [redacted]").replace(/\b(bearer|basic)(\s+)(\S+)/gi,oR).replace(nR,'$1"[redacted]"');return(i?s.replace(iR,'$1"[redacted]').replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/?#]*$/gi,"$1[redacted]"):s).slice(0,n)}function aR(e){if(!e)return;if(typeof e=="string"){const r=e.trim();if(!r)return;if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{const s=JSON.parse(r);if(typeof s=="object"&&s!==null&&!Array.isArray(s)){const o=Object.entries(s).flatMap(([a,c])=>typeof c=="string"?[[a,c]]:typeof c=="number"||typeof c=="boolean"?[[a,String(c)]]:[]);return o.length>0?Object.fromEntries(o):void 0}}catch{}const n=new URLSearchParams(r),i=Object.fromEntries(n.entries());return Object.keys(i).length>0?i:void 0}if(typeof e!="object"||e===null||Array.isArray(e))return;const t=Object.entries(e).flatMap(([r,n])=>typeof n=="string"?[[r,n]]:typeof n=="number"||typeof n=="boolean"?[[r,String(n)]]:[]);return t.length>0?Object.fromEntries(t):void 0}function cR(e){return Object.keys(e).every(t=>t.length<=64&&/^[A-Za-z0-9_.\-[\]]+$/.test(t))}var uR=3;function lR(e,t){return/^https?:\/\//i.test(e)?t>=uR?"[redacted]":Bl(e,t+1):e.replace(vm,"$1$2=[redacted]")}function Bl(e,t=0){try{const r=new URL(e);r.username="",r.password="";let n=!1;const i=new URLSearchParams;for(const[s,o]of r.searchParams.entries()){const a=rR(s)?"[redacted]":lR(o,t);n||=a!==o,i.append(s,a)}return n&&(r.search=i.toString()),r.hash&&(r.hash="#[redacted]"),r.toString()}catch{return Dr(e)}}function _m(e){const t=e.trim();if(!t)return e;if(/^https?:\/\//i.test(t))return Bl(t);if(t.includes("=")||t.includes("&")||t.startsWith("{")&&t.endsWith("}")||t.startsWith("[")&&t.endsWith("]")){const r=aR(t);if(r&&cR(r))return Qt(r)}return Dr(t)}function Qt(e){return Array.isArray(e)?e.map(t=>Qt(t)):typeof e=="string"?_m(e):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).map(([t,r])=>eR(t)?[t,Hl(r)]:[t,Qt(r)]))}function dR(e){const t=_m(e);return typeof t=="string"?t:Hl(e)}function zh(e){return Object.fromEntries(Object.entries(e).map(([t,r])=>tR(t)?[t,Hl(r)]:[t,dR(r)]))}function bz(e){const t=typeof e.callbackState=="string"&&e.callbackState.length>0;return e.issuedState?{statePresent:t,stateMatched:t&&e.callbackState===e.issuedState}:{statePresent:t}}function hR(e){return bu(e,[])}function bu(e,t){return Array.isArray(e)?e.map(r=>bu(r,t)):!e||typeof e!="object"?typeof e=="string"?pR(e):e:Object.fromEntries(Object.entries(e).map(([r,n])=>[r,vR(r,n,t)?"[REDACTED]":bu(n,[...t,r])]))}function pR(e){return e.replace(/\b(authorization|proxy-authorization|cookie|set-cookie)\s*:\s*[^\r\n]*/giu,(t,r)=>`${r}: [REDACTED]`).replace(/\bBearer(\s+)(\S+)/giu,fR).replace(/\b(access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)=([^&\s]+)/giu,"$1=[REDACTED]").replace(/(["']?(?:access_token|refresh_token|client_secret|id_token|code|code_verifier|accessToken|refreshToken|clientSecret|idToken|codeVerifier)["']?\s*:\s*["'])[^"']*(["'])/giu,"$1[REDACTED]$2")}function fR(e,t,r){return/^[A-Za-z_][A-Za-z0-9_-]*=/u.test(r)?e:mm(r)?`Bearer${t}[REDACTED]`:e}function vR(e,t,r){const n=e.toLowerCase().replace(/[^a-z0-9]/gu,"");return n==="code"?mR(t,r):n==="authorization"||n==="proxyauthorization"||n==="cookie"||n==="setcookie"?!0:(n==="codeverifier"||n==="accesstoken"||n.endsWith("accesstoken")||n==="refreshtoken"||n.endsWith("refreshtoken")||n==="clientsecret"||n.endsWith("clientsecret")||n==="idtoken"||n.endsWith("idtoken"))&&gR(t)||n==="apikey"||n==="xapikey"}function gR(e){return typeof e=="string"&&e.length>0}function mR(e,t){return t[t.length-1]==="error"||t[t.length-1]==="snapshotError"||typeof e!="string"||/^[A-Z0-9_:-]+$/u.test(e)?!1:e.length>0}var _R="ERA_NEGOTIATION_FAILED";function yR(e){return!!e&&typeof e=="object"&&e.code===_R}function Vl(e){const t=new Set;let r=e;for(;yR(r)&&!t.has(r);){t.add(r);const n=r.data,i=(n&&typeof n=="object"?n.cause:void 0)??r.cause;if(i===void 0||i===r)break;r=i}return r}var Pt={ParseError:-32700,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602,InternalError:-32603,HeaderMismatch:-32020,MissingRequiredClientCapability:-32021,UnsupportedProtocolVersion:-32022,ResourceNotFound:-32602,ConnectionClosed:-32e3,RequestTimeout:-32001,UrlElicitationRequired:-32042},bR={HeaderMismatch:-32001,MissingRequiredClientCapability:-32003,UnsupportedProtocolVersion:-32004},wR="/troubleshooting/error-codes",Uh={"jsonrpc/internal_error":"user_server","jsonrpc/invalid_response_format":"user_server","jsonrpc/parse_error":"ambiguous","jsonrpc/method_not_found":"ambiguous","jsonrpc/invalid_params":"ambiguous","jsonrpc/unsupported_protocol_version":"ambiguous","provider/invalid_tool_name":"ambiguous","oauth/well_known_unreachable":"ambiguous","transport/socket_hang_up":"ambiguous","transport/econnrefused":"user_config","transport/enotfound":"user_config","auth/http_401":"user_config","auth/http_403":"user_config","auth/missing_bearer":"user_config","auth/insufficient_scope":"user_config","auth/oauth_refresh_failed":"user_config","auth/consent_required":"user_config","oauth/invalid_client":"user_config","oauth/invalid_grant":"user_config","oauth/redirect_mismatch":"user_config","provider/auth_error":"user_config","provider/quota":"user_config","provider/mcpjam_limit":"user_config","provider/mcpjam_platform_budget":"user_config","account/suspended":"user_config","provider/mcpjam_limit_daily":"user_config","provider/mcpjam_limit_monthly":"user_config","provider/mcpjam_limit_insufficient":"user_config","provider/fallback_prohibited":"ambiguous","server/rate_limited":"user_server","server/http_error":"user_server","jsonrpc/missing_required_client_capability":"user_config","jsonrpc/url_elicitation_required":"user_config","sdk/stateless_requires_http":"user_config","sdk/protocol_version_pin_unsupported":"user_config","sdk/not_yet_supported_in_stateless":"mcpjam","sdk/paginated_tool_header_discovery_unsupported":"mcpjam","provider/not_allowlisted":"mcpjam","oauth/no_bearer_challenge":"ambiguous","oauth/non_compliant_challenge":"user_server","auth/authorization_server_unreachable":"ambiguous","auth/proxy_rejected":"ambiguous","jsonrpc/connection_closed":"ambiguous","jsonrpc/request_timeout":"ambiguous","transport/etimedout":"ambiguous","transport/econnreset":"ambiguous","transport/eai_again":"ambiguous","transport/fetch_failed":"ambiguous","transport/undici":"ambiguous","jsonrpc/invalid_request":"ambiguous","jsonrpc/header_mismatch":"ambiguous","internal/unknown":"ambiguous","provider/empty_response":"ambiguous"};function pe(e,t,r,n,i,s,o="error"){return{slug:e,title:t,oneLine:r,likelyCauses:n,nextSteps:i,docsAnchor:`${wR}#${s}`,severity:o,...Uh[e]?{origin:Uh[e]}:{}}}var wu={"jsonrpc/parse_error":pe("jsonrpc/parse_error","Parse error (-32700)","The MCP wire contained JSON the inspector could not parse as JSON-RPC.",["The server emitted invalid JSON on the response channel.","A proxy or middleware mangled the response body.","Server emitted log output on stdout instead of stderr (STDIO transport).","The inspector sent malformed JSON and the server returned a parse error."],["Check the server's stdout/stderr for unintended log output.","Use the inspector's Traffic Log to inspect the raw response."],"parse-error"),"jsonrpc/invalid_request":pe("jsonrpc/invalid_request","Invalid request (-32600)","The server rejected the payload as not a well-formed JSON-RPC request.",["Client sent a request shape the server's MCP runtime does not accept.","Outdated server SDK that disagrees with the protocol version advertised."],["Verify the negotiated MCP protocol version.","Update the server's MCP SDK."],"invalid-request"),"jsonrpc/method_not_found":pe("jsonrpc/method_not_found","Method not found (-32601)","The server does not implement the JSON-RPC method that was called.",["The server hasn't implemented the requested MCP method.","Client and server are on incompatible MCP protocol versions.","The capability you expected was not advertised in `initialize`."],["Check the server's advertised capabilities in the connection info.","Confirm the protocol version negotiated at `initialize`."],"method-not-found"),"jsonrpc/invalid_params":pe("jsonrpc/invalid_params","Invalid params (-32602)","The server rejected the request parameters.",["Required field is missing from the call.","Field type does not match the tool's input schema.","Server-side validator is stricter than the published schema."],["Re-check the tool's input schema in the Tools tab.","Compare your call payload against the schema in the inspector."],"invalid-params"),"jsonrpc/internal_error":pe("jsonrpc/internal_error","Internal error (-32603)","The server hit an unexpected error while handling the request.",["Unhandled exception inside the server's tool/resource/prompt handler.","Downstream dependency (database, API) failed during the call."],["Check the server's logs around the time of the error.","Retry the request once the server is healthy."],"internal-error"),"jsonrpc/invalid_response_format":pe("jsonrpc/invalid_response_format","Invalid response format (-32603)","The server replied, but the result was not a valid MCP tool, resource, or prompt payload.",["The handler returned a string or custom object instead of the MCP result shape (usually `{ content: [...] }`)."],["Inspect the result in the Traffic Log and compare it to the MCP result shape.",'Return `{ content: [{ type: "text", text: "..." }] }` from the handler, or the matching resource/prompt result.'],"invalid-response-format"),"jsonrpc/connection_closed":pe("jsonrpc/connection_closed","Connection closed (-32000)","The underlying transport closed before the response could be delivered.",["STDIO server process exited or crashed mid-request.","HTTP server dropped the streaming connection.","Network blip between the inspector and the server."],["Restart the server and reconnect.","Check the server logs for a crash or exit message."],"connection-closed"),"jsonrpc/request_timeout":pe("jsonrpc/request_timeout","Request timed out (-32001)","The server did not respond within the configured request timeout.",["Server is overloaded or stuck on the operation.","Long-running tool call exceeds the inspector's per-request timeout.","Network latency between client and server."],["Increase the per-server request timeout in the Servers tab.","Use MCP `tasks/*` for operations that legitimately run long."],"request-timeout"),"jsonrpc/header_mismatch":pe("jsonrpc/header_mismatch","Protocol header mismatch (-32020)","The server returned an `MCP-Protocol-Version` header that does not match what the client negotiated.",["Server is enforcing a different protocol version than the one negotiated at `initialize`.","A proxy stripped or rewrote the `MCP-Protocol-Version` header."],["Verify the server's protocol-version pinning in the connection settings.","If you set an explicit protocol version per server, ensure it matches what the server advertises."],"header-mismatch"),"jsonrpc/unsupported_protocol_version":pe("jsonrpc/unsupported_protocol_version","Unsupported protocol version (-32022)","The server does not support any protocol version this inspector offered.",["Server pinned to a newer MCP draft your inspector build does not understand.","Server pinned to a legacy version this build dropped support for."],["Update the inspector to a newer build.","Check the supported versions list in the server's `server/discover` result (modern) or `initialize` response (legacy)."],"unsupported-protocol-version"),"jsonrpc/missing_required_client_capability":pe("jsonrpc/missing_required_client_capability","Missing required client capability (-32021)","The server refused the request because the client did not advertise a capability the operation requires.",["A server-initiated input request (elicitation, sampling) needs a client capability MCPJam did not declare.","The connection advertised a capability set the server considers insufficient for this operation."],["Enable the required client capability in the connection's Client settings.","Check the server's documentation for which client capabilities it requires."],"missing-required-client-capability"),"jsonrpc/url_elicitation_required":pe("jsonrpc/url_elicitation_required","URL elicitation required (-32042)","The server needs the user to visit an external URL to complete the operation.",["Server requested a URL elicitation (OAuth, payment, confirmation).","Operation cannot proceed until the user opens the URL in a browser."],["Open the elicited URL and complete the flow.","Re-issue the request after the external step completes."],"url-elicitation-required","warning"),"transport/econnrefused":pe("transport/econnrefused","Connection refused","Nothing is listening on the host and port the server URL points at.",["Server isn't running.","Port number is wrong in the server URL.","Server is bound to a different interface (e.g. only `127.0.0.1` but you're connecting via the LAN IP)."],["Start the server.","Double-check the URL's host and port.","For Docker/containers, confirm the port is published to your host."],"econnrefused"),"transport/econnreset":pe("transport/econnreset","Connection reset","The remote side closed the TCP connection abruptly.",["Server process crashed mid-request.","Intermediate proxy or load balancer dropped the connection.","Server hit an OS-level resource limit."],["Inspect the server logs for a crash.","Retry the request."],"econnreset"),"transport/etimedout":pe("transport/etimedout","Connection timed out","The OS-level TCP connection attempt did not complete in time.",["Wrong host/port in the server URL.","Firewall is silently dropping packets.","Server is overloaded and never accepted the connection."],["Verify the URL is reachable from your machine (e.g. `curl`).","Check firewall / VPN rules."],"etimedout"),"transport/enotfound":pe("transport/enotfound","Host not found","DNS lookup failed for the server's hostname.",["Hostname is misspelled in the URL.","DNS resolver is misconfigured.","You're offline."],["Confirm the hostname in the URL is correct.","Try resolving the host with `nslookup` or `dig`."],"enotfound"),"transport/eai_again":pe("transport/eai_again","Temporary DNS failure","DNS resolution failed with a transient error.",["Local DNS resolver is overloaded or restarting.","Upstream DNS server is briefly unavailable."],["Wait a few seconds and retry.","Switch to a different DNS resolver if this persists."],"eai-again","warning"),"transport/undici":pe("transport/undici","HTTP transport error","The underlying HTTP client (undici / fetch) reported a low-level transport failure.",["Server closed the connection mid-response.","TLS handshake failed.","Socket-level error during streaming."],["Inspect the Traffic Log for the failed request.","Verify the server's TLS certificate is valid."],"undici-transport-error"),"transport/fetch_failed":pe("transport/fetch_failed","Fetch failed","The HTTP request never produced a response.",["Server is unreachable (offline, wrong URL, blocked by firewall).","TLS handshake failed (self-signed cert, expired cert).","Mixed-content block (HTTPS page calling HTTP endpoint in browser)."],["Open the URL in a browser to confirm it loads.","If self-signed, install the certificate or switch to a trusted one."],"fetch-failed"),"transport/socket_hang_up":pe("transport/socket_hang_up","Socket hang up","The server closed the connection without sending a response.",["Server crashed or restarted during the request.","Reverse proxy timed the request out."],["Retry the request.","Check server-side logs for the crash."],"socket-hang-up"),"auth/http_401":pe("auth/http_401","Unauthorized (401)","The server requires authentication that wasn't provided or is no longer valid.",["Missing or expired bearer token.","OAuth access token expired and refresh failed.","Server changed its required authentication scheme."],["Re-authenticate using the Reconnect button on the server card.","If using OAuth, run through the OAuth flow again from Servers."],"unauthorized-401"),"auth/http_403":pe("auth/http_403","Forbidden (403)","You authenticated successfully but lack permission for the operation.",["OAuth scopes granted don't cover the requested operation.","Server-side ACL blocks this account."],["Re-run OAuth and request the additional scopes if the server allows.","Ask the server admin to grant the necessary permissions."],"forbidden-403"),"auth/oauth_refresh_failed":pe("auth/oauth_refresh_failed","OAuth token refresh failed","An expired OAuth access token could not be refreshed.",["Refresh token was revoked.","Refresh token expired.","Server returned `invalid_grant` to the refresh attempt."],["Click Reconnect on the server card to run a fresh OAuth flow."],"oauth-refresh-failed"),"auth/consent_required":pe("auth/consent_required","Sign-in required","This server needs your permission before it can connect.",["Reconnect ran without opening the sign-in prompt, so no OAuth token exists for this server yet."],["Click Reconnect and approve the request in the window that opens."],"consent-required","warning"),"auth/missing_bearer":pe("auth/missing_bearer","Missing bearer token","The API call did not include the required `Authorization: Bearer ...` header.",["Inspector session expired.","Sign-in token failed to attach to the request."],["Refresh the page and sign in again."],"missing-bearer"),"auth/insufficient_scope":pe("auth/insufficient_scope","Insufficient scope (403)","The server reported insufficient_scope: the grant does not cover this operation.",["The authorization did not request the scopes the server now requires.","The server added a scope requirement after the grant was issued."],["Re-authorize and grant the scopes the server names in its challenge."],"insufficient-scope"),"auth/authorization_server_unreachable":pe("auth/authorization_server_unreachable","Authorization server unreachable","The stored token could not be refreshed because the authorization server was unreachable or did not return a usable response.",["The authorization server is down or slow.","The refresh request could not leave the network it was made from."],["Retry in a minute; if it persists, check the authorization server's status.","Reconnect the server to obtain a fresh token once the authorization server is reachable."],"authorization-server-unreachable","warning"),"auth/proxy_rejected":pe("auth/proxy_rejected","HTML access rejection (403)","The response was HTTP 403 with an HTML content type and no authentication challenge; a proxy or firewall may be involved.",["An IP allowlist or WAF blocks the address the request came from.","A corporate proxy or SSO portal intercepted the request."],["Allow MCPJam's egress addresses, or the address you connect from, on the server's firewall.","Open the server URL in a browser from the same network to see what answers."],"proxy-rejected"),"oauth/no_bearer_challenge":pe("oauth/no_bearer_challenge","401 without a Bearer challenge","The response was HTTP 401 without a Bearer challenge. This response did not explain how to authorize.",["The server or an intermediary omitted a Bearer challenge.","The server expects a static API key and does not implement OAuth."],["Check OAuth discovery, including the well-known metadata fallback supported by newer MCP versions.","If the server expects an API key, configure it as a header on the server instead of OAuth."],"no-bearer-challenge"),"oauth/non_compliant_challenge":pe("oauth/non_compliant_challenge","Bearer challenge on the wrong status","The response reported invalid_token with HTTP 403; MCP requires HTTP 401 for an invalid or expired token.",["The server maps every authorization failure to 403.","A gateway rewrites the server's 401 to 403."],["Re-authorize the server to replace the rejected token.","Report the status mismatch to the server author; invalid-token recovery expects HTTP 401."],"non-compliant-challenge","warning"),"oauth/invalid_grant":pe("oauth/invalid_grant","OAuth: invalid grant","The OAuth server rejected the authorization code or refresh token.",["Authorization code was already redeemed.","Refresh token was revoked.","Authorization code expired (typical lifetime ~60s)."],["Start the OAuth flow again from the server card."],"oauth-invalid-grant"),"oauth/invalid_client":pe("oauth/invalid_client","OAuth: invalid client","The OAuth server does not recognize the client credentials.",["Client was deleted on the authorization server.","Dynamic registration cache is stale.","`client_id` was rotated server-side."],["Re-register the client (Reconnect from the server card triggers DCR if supported)."],"oauth-invalid-client"),"oauth/redirect_mismatch":pe("oauth/redirect_mismatch","OAuth: redirect URI mismatch","The redirect URI in the request does not match the one registered with the OAuth server.",["Authorization server requires the inspector's callback URL to be registered explicitly.","Server's allow-list is wrong."],["Add the inspector's callback URL to the OAuth server's allowed redirects.","Verify the inspector's base URL hasn't changed."],"oauth-redirect-mismatch"),"oauth/well_known_unreachable":pe("oauth/well_known_unreachable","OAuth metadata unreachable","The OAuth `.well-known` discovery endpoint could not be fetched.",["Authorization server is down.","Wrong issuer URL.","CORS blocks the discovery request from the browser."],["Confirm the issuer URL in the server config.","Open the `.well-known/openid-configuration` (or `oauth-authorization-server`) URL in a browser."],"oauth-well-known-unreachable"),"sdk/not_yet_supported_in_stateless":pe("sdk/not_yet_supported_in_stateless","Operation not supported on stateless transport","The inspector's stateless HTTP transport does not yet implement this MCP operation.",["Operation requires a server-initiated channel (subscriptions, MRTR) the stateless preview transport hasn't wired up yet."],["Switch the server to the legacy stateful transport in its protocol-mode toggle."],"not-yet-supported-in-stateless","warning"),"sdk/stateless_requires_http":pe("sdk/stateless_requires_http","Stateless transport requires HTTP","Stateless mode can only be used with an HTTP-transport server, not STDIO.",["You enabled the stateless protocol toggle on a stdio server."],["Disable the stateless toggle for stdio servers."],"stateless-requires-http"),"sdk/protocol_version_pin_unsupported":pe("sdk/protocol_version_pin_unsupported","Server doesn't support the pinned protocol version","This connection is pinned to one MCP protocol version, and the server does not offer it.",["The client profile you're emulating pins a protocol version this server hasn't adopted — a host set to the latest revision against a server that still speaks a 2025 one.","A per-server protocol override left pinned to a version the server dropped or never shipped."],["Set the protocol version to Automatic to negotiate whatever the server does support.","Or pick the version the server advertises — `server/discover` (modern) or the `initialize` response (legacy) lists them."],"protocol-version-pin-unsupported"),"sdk/paginated_tool_header_discovery_unsupported":pe("sdk/paginated_tool_header_discovery_unsupported","Paginated tool discovery not supported with header overrides","Paginated tools discovery cannot run alongside per-request header overrides on this transport.",["Conflicting combination of progressive tool discovery + per-server header overrides."],["Disable progressive tool discovery for this server, or move headers into the server config."],"paginated-tool-and-header-discovery-unsupported","warning"),"provider/invalid_tool_name":pe("provider/invalid_tool_name","Provider rejected the tool name","An LLM provider rejected a tool name (Anthropic's strict tool-name validator is the most common source).",["Tool name contains characters or length the provider does not allow.","Two attached servers expose tools whose namespaced names collide after sanitization."],["Rename the offending tool on the server.","Detach one of the colliding servers from the chat surface."],"provider-invalid-tool-name"),"provider/auth_error":pe("provider/auth_error","Provider authentication error","Your LLM provider rejected the API key for this request.",["Key is missing.","Key is invalid or revoked.","Key is for a different environment (project, region)."],["Add or update your API key under Settings → LLM Providers.","Verify the key in the provider's dashboard."],"provider-auth-error"),"provider/not_allowlisted":pe("provider/not_allowlisted","Model provider not enabled on MCPJam","This model's provider is not enabled on MCPJam's hosted AI gateway, so MCPJam can't run it. Retrying or changing your API key won't help.",["MCPJam's hosted gateway does not have this model's provider on its provider allowlist."],["Choose a model from a different provider.","Add your own key for this provider under Settings → LLM Providers (BYOK) to run the model on your key instead of MCPJam's gateway."],"provider-not-allowlisted","warning"),"provider/mcpjam_limit_daily":pe("provider/mcpjam_limit_daily","Out of MCPJam credits","Your organization's daily MCPJam credits are used up. They reset tomorrow.",["Chat, evals and swarm generation all draw on one daily bucket, shared across the organization."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the daily allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_monthly":pe("provider/mcpjam_limit_monthly","Out of MCPJam credits","Your organization's available MCPJam credits are used up for this billing period.",["Paid plans include a monthly credit allowance shared across the organization. It renews with the billing period."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the billing period to renew.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/mcpjam_limit_insufficient":pe("provider/mcpjam_limit_insufficient","Not enough MCPJam credits","Your organization has MCPJam credits left, but not enough for this request.",["MCPJam reserves a request's worst-case cost before it runs, so an expensive model or a long conversation can need more than the remaining balance."],["Try a cheaper model or a shorter conversation.","On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/fallback_prohibited":pe("provider/fallback_prohibited","Provider failed, fallback not permitted","The model's provider failed and this model selection does not allow a fallback provider, so the request stopped rather than running somewhere other than where it was asked to.",[`The provider serving this model returned an error or was unreachable, and the selection's fallback policy is "none" — the default for evals, swarms and judges, so a result never silently comes from a different provider.`],["Retry — the provider's failure may be temporary.","Pick a different model, or a model on a connection you control."],"provider-failed-fallback-not-permitted","warning"),"provider/mcpjam_platform_budget":pe("provider/mcpjam_platform_budget","MCPJam shared free allowance unavailable","The shared free allowance is exhausted or temporarily paused.",["This limit applies across free usage, not just your account."],["Wait until the supplied reset time, if present.","Use purchased credits or your own provider key for chat."],"mcpjam-platform-budget","warning"),"account/suspended":pe("account/suspended","Account suspended","This account has been suspended by MCPJam.",["Support has suspended this account."],["Contact founders@mcpjam.com for support."],"account-suspended","warning"),"provider/mcpjam_limit":pe("provider/mcpjam_limit","Out of MCPJam credits","Your organization is out of MCPJam credits, so this request could not continue.",["Chat, evals and swarm generation all draw on the same MCPJam allowance."],["On Free, upgrade for a larger monthly allowance and access to top-ups. On eligible paid plans, buy shared credits to continue testing.","Wait for the allowance to reset.","Your own API key covers supported model inference. MCPJam features can still require credits; Swarm generation and persona turns always do."],"out-of-mcpjam-credits","warning"),"provider/quota":pe("provider/quota","Provider quota / rate limit","Your LLM provider rejected the request because you hit a rate limit or quota.",["Daily/monthly quota exhausted.","Per-minute rate limit exceeded.","Free tier limits hit."],["Wait for the limit window to reset.","Upgrade your provider plan.","Switch to a different provider in Settings."],"provider-quota","warning"),"server/rate_limited":pe("server/rate_limited","MCP server rate limit","The MCP server rejected the request with HTTP 429 (too many requests).",["The server enforces its own per-client rate limit.","An upstream API the server calls is throttling it.","A burst of tool calls exceeded what the server allows."],["Wait for the server's limit window to reset, then retry.","Reduce concurrency or the number of tool calls in the run.","Check the server's own rate-limit documentation or logs."],"server-rate-limited","warning"),"server/http_error":pe("server/http_error","MCP server returned an HTTP error","The MCP server answered the request with an HTTP error status.",["404: the URL points at the wrong endpoint path (for example, a missing `/mcp`).","405: the endpoint does not accept MCP requests (POST).","5xx: the server hit an error of its own while handling the request."],["Check the server URL, including the MCP endpoint path.","Check the server's logs for the failed request."],"server-http-error"),"provider/empty_response":pe("provider/empty_response","Model returned no response","The model returned no response, so the turn could not complete.",["The model request ended without usable content."],["Rerun the affected cases. If this recurs, report it with the run details."],"model-empty-response"),"internal/unknown":pe("internal/unknown","Unknown error","An error occurred that the inspector could not classify.",["Unhandled error path.","New error class the inspector hasn't been taught about yet."],["Open the details panel and copy the raw message.","File an issue with the raw message so we can add it to the catalog."],"unknown-error")};function ym(e,t=0){if(!e||typeof e!="object"||t>3)return;const r=e.code,n=typeof r=="string"?r:void 0;if(n!==void 0&&SR(n))return n;const i=e.cause;if(i!==void 0&&i!==e){const s=ym(i,t+1);if(s!==void 0)return s}return n}function SR(e){return ER.has(e)||e.startsWith("UND_ERR_")}var ER=new Set(["ECONNREFUSED","ECONNRESET","EAI_AGAIN","ENETDOWN","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function kR(e){return!!e&&typeof e=="object"&&typeof e.slug=="string"&&typeof e.title=="string"&&typeof e.oneLine=="string"&&typeof e.docsAnchor=="string"&&typeof e.severity=="string"&&typeof e.rawMessage=="string"&&Array.isArray(e.likelyCauses)&&Array.isArray(e.nextSteps)}function si(e){const t=hR(e);return typeof t=="string"?t:String(e)}function IR(e){if(!e||typeof e!="object")return;const t=e.name;return typeof t=="string"?t:void 0}function Gl(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function Zl(e){if(!e||typeof e!="object")return;const t=e.code;if(typeof t=="number"&&Number.isFinite(t))return t;const r=e.error;if(r&&typeof r=="object"){const n=r.code;if(typeof n=="number"&&Number.isFinite(n))return n}}function AR(e){if(!e||typeof e!="object")return;const t=e.code;return typeof t=="string"?t:void 0}function bm(e){if(!e||typeof e!="object")return;const t=e.statusCode;if(typeof t=="number")return t;const r=e.status;if(typeof r=="number")return r}function wm(e){return wu[e]??wu["internal/unknown"]}var TR=200;function Su(e){const t=e.replace(/\s+/g," ").trim();return t.length<=TR?t:`${t.slice(0,199).trimEnd()}…`}function Sm(e,t,r,n,i){if(t==="server/http_error"&&typeof n=="number")return{...e,oneLine:i!==void 0&&i>=400&&i!==n?`The MCP server answered the request with HTTP ${n}, then with HTTP ${i} to the SSE fallback.`:`The MCP server answered the request with HTTP ${n}.`};if(t==="provider/mcpjam_limit_insufficient"){const s=Jl(r);return s?{...e,oneLine:s}:e}return t!=="internal/unknown"||!r?e:{...e,oneLine:Su(r)}}var RR=["Backend step returned no content (stream error or empty response)","Backend step returned no messages (stream error or empty response)"];function PR(e){if(/NotYetSupportedInStateless/i.test(e))return"sdk/not_yet_supported_in_stateless";if(/StatelessRequiresHttpTransport/i.test(e))return"sdk/stateless_requires_http";if(/PaginatedToolHeaderDiscoveryUnsupported/i.test(e))return"sdk/paginated_tool_header_discovery_unsupported";if(/which this client is pinned to/i.test(e))return"sdk/protocol_version_pin_unsupported"}var OR={[Pt.ParseError]:"jsonrpc/parse_error",[Pt.InvalidRequest]:"jsonrpc/invalid_request",[Pt.MethodNotFound]:"jsonrpc/method_not_found",[Pt.InvalidParams]:"jsonrpc/invalid_params",[Pt.InternalError]:"jsonrpc/internal_error",[Pt.ConnectionClosed]:"jsonrpc/connection_closed",[Pt.HeaderMismatch]:"jsonrpc/header_mismatch",[Pt.MissingRequiredClientCapability]:"jsonrpc/missing_required_client_capability",[Pt.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[bR.UnsupportedProtocolVersion]:"jsonrpc/unsupported_protocol_version",[Pt.UrlElicitationRequired]:"jsonrpc/url_elicitation_required"};function CR(e){return/header[^a-z]*mismatch/i.test(e)||/MCP-Protocol-Version/i.test(e)?"jsonrpc/header_mismatch":"jsonrpc/request_timeout"}var $R=/^(?:MCP error -32603:\s*)?invalid response format$/i;function Em(e){return $R.test(e.trim())}function xR(e){return Em(e)?"jsonrpc/invalid_response_format":"jsonrpc/internal_error"}function km(e){const t=e.toUpperCase();switch(t){case"ECONNREFUSED":return"transport/econnrefused";case"ECONNRESET":return"transport/econnreset";case"ETIMEDOUT":return"transport/etimedout";case"ENOTFOUND":return"transport/enotfound";case"EAI_AGAIN":return"transport/eai_again";default:return t.startsWith("UND_ERR_")?"transport/undici":void 0}}function MR(e){const t=e.toLowerCase();if(/\bsocket\s+hang\s+up\b/i.test(e))return"transport/socket_hang_up";for(const r of e.matchAll(/\b(E[A-Z]{2,}(?:_[A-Z]+)*|UND_ERR_[A-Z_]+)\b/g)){const n=km(r[1]);if(n)return n}if(/\bfetch\s+failed\b/i.test(e))return"transport/fetch_failed";if(/\bgetaddrinfo\b/i.test(e))return"transport/enotfound";if(/\bconnection\s+(?:refused|reset|closed|timed?\s*out|aborted|error|failed)\b/i.test(e)||/\b(?:failed|unable)\s+to\s+connect\b/i.test(e))return t.includes("refused")?"transport/econnrefused":t.includes("reset")?"transport/econnreset":t.includes("timed out")||t.includes("timeout")?"transport/etimedout":t.includes("closed")?"jsonrpc/connection_closed":"transport/fetch_failed";if(/Invalid tool name/i.test(e))return"provider/invalid_tool_name";if(Em(e))return"jsonrpc/invalid_response_format"}function LR(e){const t=DR(e);if(!t)return;const r=NR(e)??(typeof t.error=="string"?t.error:typeof t.error_code=="string"?t.error_code:void 0);if(r)switch(r.toLowerCase()){case"invalid_grant":return"oauth/invalid_grant";case"invalid_client":return"oauth/invalid_client";case"invalid_redirect_uri":case"redirect_uri_mismatch":return"oauth/redirect_mismatch";default:return}}function NR(e){if(!e||typeof e!="object"||e.name!=="OAuthResponseError")return;const t=e.code;return typeof t=="string"&&t?t:void 0}function DR(e){if(!e||typeof e!="object")return;const t="body"in e?e.body:"data"in e?e.data:e;if(!(!t||typeof t!="object"))return t}function Im(e){if(!(e instanceof Error))return;const t=e.cause;if(!t||typeof t!="object")return;const r=typeof t.name=="string"?t.name:"Error",n=typeof t.message=="string"?si(t.message):"";if(n)return{name:r,message:n}}var Fh={AUTH_ERROR:"auth/http_401",OAUTH_REQUIRED:"auth/http_401"};function zR(e){const t=IR(e);if(t==="MCPAuthError"||t==="UnauthorizedError")return"auth/http_401";const r=AR(e);if(r&&Fh[r])return Fh[r]}function oc(e){if(e===401)return"auth/http_401";if(e===403)return"auth/http_403";if(e===429)return"provider/quota"}function UR(e){if(/(?:^|[^\w.:])401\b/.test(e))return"auth/http_401";if(/(?:^|[^\w.:])403\b/.test(e))return"auth/http_403";if(/(?:^|[^\w.:])429\b|too many requests/i.test(e))return"provider/quota"}function FR(e){const t=Gl(e),r=e&&typeof e=="object"?e:null,n=r?.data?.code??r?.code;if(n==="platform_free_budget_exhausted")return{slug:"provider/mcpjam_platform_budget",rawCode:n};if(n==="account_suspended")return{slug:"account/suspended",rawCode:n};if(RR.some(v=>t.startsWith(v)))return{slug:"provider/empty_response"};const i=PR(t);if(i)return{slug:i};const s=zR(e);if(s)return{slug:s};const o=Zl(e);if(o!==void 0){if(o===-32001)return{slug:CR(t),rawCode:o};if(o===Pt.InternalError)return{slug:xR(t),rawCode:o};const v=OR[o];if(v)return{slug:v,rawCode:o};const g=oc(o);if(g)return{slug:g,rawCode:o}}const a=ym(e);if(a){const v=km(a);if(v)return{slug:v,rawCode:a}}if(/missing\s+(?:or\s+invalid\s+)?bearer/i.test(t)||/bearer\s+token\s+(?:is\s+)?required/i.test(t))return{slug:"auth/missing_bearer"};if(Jl(t))return{slug:"provider/mcpjam_limit_insufficient"};if(/\bout of MCPJam credits\b/i.test(t))return{slug:"provider/mcpjam_limit"};const c=XR(t);if(c)return{slug:c};const u=Wl(e);if(u!==void 0){const v=oc(u);if(v)return{slug:v,rawCode:u}}const l=Am(e)?.streamable,h=l!==void 0&&l>=400?l:Eu(e);if(h!==void 0&&h>=400&&oc(h)===void 0)return{slug:"server/http_error",rawCode:h};const d=LR(e);if(d)return{slug:d};const p=UR(t);if(p)return{slug:p};if(/refresh\s+token/i.test(t)&&/(failed|invalid|expired|revoked)/i.test(t))return{slug:"auth/oauth_refresh_failed"};if(/consent\s+is\s+required/i.test(t)||/^\s*reauthenticate\b[\s\S]*\bto\s+continue\b/i.test(t))return{slug:"auth/consent_required"};const f=MR(t);return f?{slug:f}:/well[-_]?known/i.test(t)&&/(unreachable|fail|404)/i.test(t)?{slug:"oauth/well_known_unreachable"}:{slug:"internal/unknown"}}var qR=new Set(["auth/http_401","auth/http_403","auth/missing_bearer","auth/oauth_refresh_failed","auth/authorization_server_unreachable","oauth/invalid_client","oauth/invalid_grant","provider/auth_error","provider/quota"]);function Wl(e){const t=new Set;let r=e;for(let n=0;n<5&&r&&typeof r=="object"&&!t.has(r);n++){t.add(r);const i=bm(r);if(i!==void 0)return i;const s=Zl(r);if(s!==void 0&&s>=100&&s<=599)return s;if(r.name==="UnauthorizedError")return 401;const o=Vl(r);r=o!==r?o:r.cause}}var jR=new Set(["StreamableHTTPError","SseError"]);function HR(e){if(e.name==="SdkHttpError")return!0;const t=e.constructor;return typeof t=="function"&&jR.has(t.name)}function Eu(e){const t=[e],r=new Set;for(;t.length>0&&r.size<8;){const n=t.shift();if(!n||typeof n!="object"||r.has(n))continue;if(r.add(n),HR(n)){const s=bm(n)??Zl(n);if(s!==void 0&&s>=100&&s<=599)return s}const i=Vl(n);t.push(i!==n?i:n.cause,n.streamableCause)}}function Am(e){let t=e;const r=new Set;for(;t&&typeof t=="object"&&!r.has(t);){r.add(t);const n=t.streamableCause;if(n!==void 0)return{streamable:Eu(n),fallback:Eu(t.cause)};const i=Vl(t);t=i!==t?i:t.cause}}function BR(e,t){if(!t)return;if(t.refresh?.outcome==="authorization_server_unreachable")return"auth/authorization_server_unreachable";if(t.refresh?.outcome==="token_rejected")return"auth/oauth_refresh_failed";const r=t.challenge;if(!r)return;const n=Wl(e);if(n===401&&r.scheme!=="bearer")return"oauth/no_bearer_challenge";if(n===401)return"auth/http_401";if(n===403)return r.scheme==="bearer"&&r.error==="insufficient_scope"?"auth/insufficient_scope":r.scheme==="bearer"&&r.error==="invalid_token"?"oauth/non_compliant_challenge":r.scheme==="none"&&r.bodyKind==="html"?"auth/proxy_rejected":"auth/http_403"}function VR(e,t,r){if(t==="auth/insufficient_scope"&&r?.challenge?.scopes?.length)return{...e,oneLine:Su(si(`${e.oneLine} Required scopes: ${r.challenge.scopes.join(" ")}.`))};const n=r?.challenge?.error;return!n||t!=="auth/http_401"&&t!=="auth/http_403"?e:{...e,oneLine:Su(si(`${e.oneLine} The server reported \`${n}\`.`))}}var GR=new Set(["user_server","user_config","mcpjam","ambiguous"]);function ZR(e){return typeof e=="string"&&GR.has(e)}function WR(e){const t=e?.origin;return ZR(t)?t:"ambiguous"}function Tm(e,t,r){return r?.credentialOwner==="mcpjam"&&qR.has(t)?{...e,origin:"mcpjam"}:e}function JR(e,t){return e==="provider/quota"&&t?.surface==="mcpServer"?"server/rate_limited":e}function KR(e,t){try{const r=si(Gl(e)),n=BR(e,t),i=n?{slug:n}:FR(e),s=JR(i.slug,t),o=i.rawCode??(n?Wl(e):void 0),a=Tm(VR(Sm(wm(s),s,r,o,s==="server/http_error"?Am(e)?.fallback:void 0),s,t),s,t),c=Im(e);return{...a,rawMessage:r,...o!==void 0?{rawCode:o}:{},...c?{cause:c}:{}}}catch{return Rm(e,"Unknown")}}function wz(e,t,r){try{const n=Tm(wm(e),e,r),i=t!==void 0?si(Gl(t)):"",s=Im(t);return{...n,rawMessage:i,...s?{cause:s}:{}}}catch{return Rm(t,"")}}function Rm(e,t){const r=wu["internal/unknown"];let n=t;try{n=si(e instanceof Error?e.message:String(e??t))}catch{n=t}return{...Sm(r,"internal/unknown",n),rawMessage:n}}var YR=/\bThis request needs about (\d+) MCPJam credits; your organization has (\d+) left[^.]{0,40}\./i;function Jl(e){const t=YR.exec(e);if(!t)return;const r=Number(t[1]),n=Number(t[2]);return Number.isSafeInteger(r)&&Number.isSafeInteger(n)&&n>0&&r>n?t[0]:void 0}function XR(e){if(Jl(e))return"provider/mcpjam_limit_insufficient";const t=/\b(daily|monthly)\s+mcpjam[\w\s-]{0,40}model limit/i.exec(e);if(t)return t[1].toLowerCase()==="monthly"?"provider/mcpjam_limit_monthly":"provider/mcpjam_limit_daily";if(/mcpjam[\w\s-]{0,40}model limit/i.test(e))return"provider/mcpjam_limit"}var ku="[A-Za-z0-9!#$%&'*+.^_`|~-]+";function QR(e){const t={},r=new RegExp(`(${ku})\\s*=\\s*(?:"((?:\\\\.|[^"\\\\])*)"|([^,\\s]+))`,"g");for(let n=r.exec(e);n;n=r.exec(e)){const i=n[2];t[n[1].toLowerCase()]=i!==void 0?i.replace(/\\([\s\S])/g,"$1"):n[3]??""}return t}function gr(e){return Pm(e)[0]??{}}function Kl(e){if(!e)return;const t=e.split(/\s+/).map(r=>r.trim()).filter(Boolean);return t.length>0?Array.from(new Set(t)):void 0}function eP(e,t){const r=[],n=new Set;for(const i of[...e??[],...t??[]]){const s=i?.trim();!s||n.has(s)||(n.add(s),r.push(s))}return r}function Pm(e){if(!e)return[];const t=[];let r="",n=!1;for(let a=0;a<e.length;a++){const c=e[a];n&&c==="\\"&&a+1<e.length?(r+=c+e[a+1],a++):c==='"'?(n=!n,r+=c):c===","&&!n?(t.push(r),r=""):r+=c}t.push(r);const i=[],s=new RegExp(`^(${ku})\\s+(?!\\s*=)(.+)$`,"s"),o=new RegExp(`^(${ku})$`);for(const a of t){const c=a.trim();if(!c)continue;const u=s.exec(c),l=u?null:o.exec(c);u?i.push({scheme:u[1].toLowerCase(),params:[u[2]]}):l?i.push({scheme:l[1].toLowerCase(),params:[]}):i.length>0&&i[i.length-1].params.push(c)}return i.filter(a=>a.scheme==="bearer").map(a=>QR(a.params.join(", ")))}function tP(e){return Pm(e).length>0}var Hr=class extends Error{status;constructor(e,t){super(e),this.name="UnexpectedProbeStatusError",this.status=t}},Om="MCP server returned HTTP ";function Sz(e){return e.startsWith(Om)}function Is(e){if(e.status===401)return{kind:"challenged",specCompliant:!0};if(e.status===200)return{kind:"anonymous_allowed"};if(e.status===403&&tP(e.wwwAuthenticateHeader))return{kind:"challenged",specCompliant:!1};const t=e.serverMessage||e.statusText,r=`${Om}${e.status}${t?` ${t}`:""}`;return e.status===403?e.wwwAuthenticateHeader?.trim()?{kind:"unexpected",message:`${r}, and its WWW-Authenticate header offers no Bearer challenge. MCP OAuth has nothing to discover from without one, so the flow cannot continue against this server.`}:{kind:"unexpected",message:`${r} with no WWW-Authenticate challenge. MCP requires 401 with a WWW-Authenticate header to begin OAuth, so there is nothing to discover from. A bare 403 usually means a proxy, WAF, or IP allowlist rejected the request before the MCP server saw it.`}:{kind:"unexpected",message:`${r} where MCP requires 401 Unauthorized (or 200, if the server allows anonymous access).`}}function Ez(e){return e.step!=="request_without_token"||e.status===void 0?!1:Is({status:e.status,statusText:e.statusText,wwwAuthenticateHeader:e.wwwAuthenticateHeader}).kind==="challenged"}function kz(e){const t=Number.isInteger(e.maxRetries)&&e.maxRetries>=0?e.maxRetries:1;switch(e.authMode){case"m2m":return"throw";case"debugger":return"manual";case"interactive":return e.attempt<t?"reauthorize":"throw"}}function rP(e){const t=e.customScopes?.trim();if(t)return t;const r=e.challengedScopes?.filter(Boolean)??[];if(r.length>0)return Array.from(new Set(r)).join(" ");const n=e.supportedScopes?.filter(Boolean)??[];if(n.length!==0)return Array.from(new Set(n)).join(" ")}var nP;nP=globalThis.crypto;var iP="Resource server does not implement OAuth 2.0 Protected Resource Metadata.",qh="No response while loading OAuth protected resource metadata.",sP="Failed to request resource metadata";function ya(e){const t=e instanceof Error?e.message:String(e);return`${sP}: ${t}`}function Iz(e){return e==="Resource server does not implement OAuth 2.0 Protected Resource Metadata."||e===ya(new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata."))}function oP(e){try{const t=new URL(e);return t.protocol=t.protocol.toLowerCase(),t.hostname=t.hostname.toLowerCase(),t.hash="",t.pathname!=="/"&&t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}catch{return e}}function aP(e,t){if(e.origin!==t.origin||t.pathname.length<e.pathname.length)return!1;const r=t.pathname.endsWith("/")?t.pathname:`${t.pathname}/`,n=e.pathname.endsWith("/")?e.pathname:`${e.pathname}/`;return r.startsWith(n)}function cP(e,t,r){const n=c=>({value:e,source:t,status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c});let i;try{i=new URL(e)}catch{return n(`Resource indicator "${e}" is not a parseable URI.`)}if(i.hash)return n(`Resource indicator "${e}" must not include a fragment (RFC 8707 §2).`);if(i.protocol!=="https:"&&i.protocol!=="http:")return n(`Resource indicator "${e}" must be an https URL (RFC 9728 §2).`);let s;try{s=new URL(r)}catch{return n(`Server URL "${r}" is not a parseable URI.`)}if(i.origin!==s.origin){const c=`Resource indicator "${e}" is on a different origin than the server URL "${r}" — honoring it would let the server steer tokens to an audience it doesn't own.`;return{value:e,source:t,status:"incompatible",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:c,reason:c}}const o=aP(i,s),a=i.protocol!=="https:"?`Resource indicator "${e}" must use the https scheme to comply with RFC 9728.`:o?void 0:`Resource indicator "${e}" does not satisfy the protected-resource binding for server URL "${r}" required for RFC 9728 conformance.`;return{value:e,source:t,status:"valid",strictClientCompatible:o,rfc9728Compliant:a===void 0,...a?{rfc9728Reason:a}:{},...o?{}:{reason:`Resource indicator "${e}" is not a path prefix of the server URL "${r}"; clients that enforce the official MCP SDK's strict binding will refuse it.`}}}function uP(e){return e.resolved?e.resolved.value:e.serverUrl===void 0?e.prmResource:Iu({serverUrl:e.serverUrl,prmResource:e.prmResource}).value}function Iu(e){const t=[[e.prmResource,"prm"],[e.authorizationUrlResource,"authorization"],[e.configuredResource,"configured"]];for(const[n,i]of t){const s=n?.trim();if(s)return cP(s,i,e.serverUrl)}try{new URL(e.serverUrl)}catch{return{value:e.serverUrl,source:"server",status:"invalid",strictClientCompatible:!1,rfc9728Compliant:!1,rfc9728Reason:`Server URL "${e.serverUrl}" is not a parseable URI.`,reason:`Server URL "${e.serverUrl}" is not a parseable URI.`}}const r=new URL(e.serverUrl).protocol==="https:"?void 0:`Resource indicator "${e.serverUrl}" must use the https scheme to comply with RFC 9728.`;return{value:oP(e.serverUrl),source:"server",status:"valid",strictClientCompatible:!0,rfc9728Compliant:r===void 0,...r?{rfc9728Reason:r}:{}}}var Cm="2025-11-25";async function $m(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError))throw n;if(!t)return;try{return await r(e,{})}catch(i){if(!(i instanceof TypeError))throw i;return}}}function lP(e,t="",r={}){const n=t.endsWith("/")?t.slice(0,-1):t;return r.prependPathname?`${n}/.well-known/${e}`:`/.well-known/${e}${n}`}async function jh(e,t,r=fetch){return $m(e,{"MCP-Protocol-Version":t,Accept:"application/json"},r)}function dP(e,t){return e?t==="/"?!1:e.status>=400&&e.status<500||e.status===502:!0}async function hP(e,t,r,n){const i=new URL(e),s=n?.protocolVersion??Cm;let o;if(n?.metadataUrl)o=new URL(n.metadataUrl);else{const u=lP(t,i.pathname);o=new URL(u,n?.metadataServerUrl??i),o.search=i.search}let a=await jh(o,s,r),c=!a;return!n?.metadataUrl&&dP(a,i.pathname)&&(a=await jh(new URL(`/.well-known/${t}`,i),s,r),c||=!a),{response:a,sawNoResponse:c}}function pP(e){const t=typeof e=="string"?new URL(e):e;if(t.pathname==="/")return[{url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"},{url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}];const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return[{url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"},{url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"},{url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}]}async function ba(e,t,r=fetch){const{response:n,sawNoResponse:i}=await hP(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n)throw new Error(qh);if(n.status===404)throw await n.text().catch(()=>{}),new Error(i?qh:iP);if(!n.ok)throw await n.text().catch(()=>{}),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return await n.json()}async function fP(e,{fetchFn:t=fetch,protocolVersion:r=Cm}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"};for(const{url:i,type:s}of pP(e)){const o=await $m(i,n,t);if(o){if(!o.ok){if(await o.text().catch(()=>{}),o.status>=400&&o.status<500||o.status===502)continue;throw new Error(`HTTP ${o.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return await o.json()}}}async function Az(e,t){let r,n;try{r=await ba(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers?.length&&(n=r.authorization_servers[0])}catch(s){if(s instanceof TypeError)throw s}n||(n=String(new URL("/",e)));const i=await fP(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:String(n),authorizationServerMetadata:i,resourceMetadata:r}}function vP(e){const t=e?.token_endpoint_auth_methods_supported;if(!Array.isArray(t)||t.length===0)return["client_secret_basic"];const r=t.filter(n=>typeof n=="string");return r.length>0?r:["client_secret_basic"]}function wa(e){const t=vP(e.authorizationServerMetadata);return e.hasClientSecret?t.includes("client_secret_basic")?{ok:!0,method:"client_secret_basic",supportedMethods:t}:t.includes("client_secret_post")?{ok:!0,method:"client_secret_post",supportedMethods:t}:t.includes("none")?{ok:!0,method:"none",supportedMethods:t}:{ok:!1,message:`Unsupported OAuth client authentication method: ${t.join(", ")||"none advertised"}.`,supportedMethods:t}:{ok:!0,method:"none",supportedMethods:t}}function Hh(e){return new URLSearchParams([["v",e]]).toString().slice(2)}function Br(e){const{clientId:t,clientSecret:r,tokenEndpointAuthMethod:n}=e;if(r&&n==="client_secret_basic")return{headers:{Authorization:`Basic ${btoa(`${Hh(t??"")}:${Hh(r)}`)}`},bodyParams:{}};const i={};return t&&(i.client_id=t),r&&n!=="none"&&(i.client_secret=r),{headers:{},bodyParams:i}}function Sa(e){const t=e.token_endpoint_auth_method;if(!(e.client_secret&&(!t||t==="none")))return t||"none"}var Bh=300,Yl="Authenticated request failed",xm="Token request failed",gP=[xm,Yl];function Tz(e){return e.startsWith(`${Yl}: `)}function ir(e){if(typeof e!="string")return;const t=e.trim();return t||void 0}function Au(e){return e.replace(/\s+/g," ").trim()}function Mm(e){if(typeof e=="string")return ir(e);if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,r=ir(t.error_type),n=ir(t.error_description),i=ir(t.error_message)??n??ir(t.message),s=ir(t.error);if(r&&i)return ir(`${r}: ${i}`);if(s&&n)return ir(`${s}: ${n}`);if(s)return s;const o=t.error;if(o&&typeof o=="object"&&!Array.isArray(o)){const a=ir(o.message);if(a)return a}return i}function Lm(e,t){const r=Au(Dr(t.statusText??"",{maxLength:Bh})),n=Mm(t.body),i=n?Au(Dr(n,{maxLength:Bh})):void 0;return`${e}: ${t.status}${r?` ${r}`:""}${i?`: ${i}`:""}`}function Ea(e){return Lm(Yl,e)}function ka(e){return Lm(xm,e)}function mP(e){for(const t of gP){if(!e.startsWith(`${t}: `))continue;const r=e.slice(t.length+2),n=/^\d{3}/.exec(r)?.[0];if(!n)return t;const i=r.indexOf(": ",n.length),s=i===-1?void 0:/^[a-z][a-z0-9_]*(?=:|$)/.exec(r.slice(i+2))?.[0];return s?`${t}: ${n}: ${s}`:`${t}: ${n}`}}function Vh(e){try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4);let n;if(typeof globalThis.atob=="function")n=globalThis.atob(r);else if(typeof Buffer<"u")n=Buffer.from(r,"base64").toString("utf-8");else return null;return JSON.parse(n)}catch{return null}}function _P(e){const t=e.split(".");return t.length!==3?null:{header:Vh(t[0]),payload:Vh(t[1]),signature:t[2]}}function Vr(e){return _P(e)?.payload??null}function Ne(e){try{return new Date(e*1e3).toLocaleString()}catch{return String(e)}}var Rz={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0};function Ia(){return{isInitiatingAuth:!1,currentStep:"idle",serverUrl:void 0,wwwAuthenticateHeader:void 0,challengedScopes:void 0,resourceMetadataUrl:void 0,resourceMetadata:void 0,resourceIndicator:void 0,resourceIndicatorSuppressed:void 0,authorizationServerUrl:void 0,authorizationServerMetadata:void 0,clientId:void 0,clientSecret:void 0,tokenEndpointAuthMethod:void 0,codeVerifier:void 0,codeChallenge:void 0,codeChallengeMethod:void 0,authorizationUrl:void 0,authorizationCode:void 0,state:void 0,recordedIssuer:void 0,authorizationResponseIss:void 0,requestedScopes:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],error:void 0}}function jn(e,t){return`${e.substring(0,t)}...`}function Tu(e){if(typeof e=="string"&&e.trim()!=="")try{return new URL(e).pathname}catch{return`${e} (not an absolute URL)`}return Nm(e)}function Nm(e){let t;try{t=typeof e=="string"||typeof e=="object"&&e!==null?JSON.stringify(e)??String(e):String(e)}catch{t="[unserializable value]"}return`${t} (not an absolute URL)`}function yP(e){const t=e.resourceMetadata?.authorization_servers;if(t==null)return;const r=Array.isArray(t)?t[0]:t;if(r!==void 0)return[{label:"Auth Server",value:(typeof r=="string"&&r.trim()!==""?r:void 0)??Nm(r)}]}function ac(e,t,r){return e.resourceIndicatorSuppressed?"omitted (emulation)":t.resourceValue(e)||r}function bP(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:t.initialMcpMethod}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl!==void 0?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl!==void 0?[{label:"GET",value:Tu(e.resourceMetadataUrl)}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:yP(e)}]}function wP(e){return[{id:"cimd_prepare",label:"Client uses HTTPS URL as client_id",description:"Client prepares to use URL-based client identification",from:"client",to:"client",details:e.clientId?[{label:"client_id (URL)",value:e.clientId.includes("http")?e.clientId:"https://www.mcpjam.com/.well-known/oauth/client-metadata.json"},{label:"Method",value:"Client ID Metadata Document (CIMD)"}]:[{label:"Note",value:"HTTPS URL points to metadata document"}]},{id:"cimd_fetch_request",label:"Fetch metadata from client_id URL",description:"Authorization Server fetches client metadata from the URL",from:"authServer",to:"client",details:[{label:"Action",value:"GET client_id URL"},{label:"Note",value:"Server initiates metadata fetch during authorization"}]},{id:"cimd_metadata_response",label:"JSON metadata document",description:"Client hosting returns metadata with redirect_uris and client info",from:"client",to:"authServer",details:[{label:"Content-Type",value:"application/json"},{label:"Contains",value:"client_id, client_name, redirect_uris, etc."}]},{id:"received_client_credentials",label:"Validate metadata and redirect_uris",description:"Authorization Server validates fetched metadata",from:"authServer",to:"authServer",details:[{label:"Validates",value:"client_id matches URL, redirect_uris are valid"},{label:"Security",value:"SSRF protection, domain trust policies"}]}]}function SP(e,t,r){if(r==="cimd")return wP(e);const n=t.clientCredentialsExtras?.(e)??[];return r==="dcr"?[{id:"request_client_registration",label:`POST /register (${t.protocolVersion})`,description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"},...t.dcrNotes??[]]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:jn(e.clientId,20)},...n]:void 0}]:[{id:"received_client_credentials",label:`Use Pre-registered Client (${t.protocolVersion})`,description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:jn(e.clientId,20)},{label:"Note",value:"Pre-registered (no DCR needed)"},...n]:[{label:"Note",value:"Pre-registered client credentials"}]}]}function Aa(e,t,r){return[...r.includesProtectedResourceMetadata?bP(e,r):[],{id:"request_authorization_server_metadata",label:r.authorizationServerMetadata.label,description:r.authorizationServerMetadata.description,from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:Tu(e.authorizationServerMetadata.token_endpoint)},{label:"Auth",value:Tu(e.authorizationServerMetadata.authorization_endpoint)}]:void 0},...SP(e,r,t),{id:"generate_pkce_parameters",label:r.pkce.label,description:r.pkce.description,from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:jn(e.codeChallenge,15)},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:ac(e,r,"—")},{label:"Protocol",value:r.protocolVersion}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:ac(e,r,"")},...r.authorizationRequestExtras?.(e)??[]]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:jn(e.authorizationCode,20)}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:jn(e.authorizationCode,20)}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:ac(e,r,"")}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:`Bearer ${jn(e.accessToken,15)}`}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function ie(e,t,r,n,i,s={}){const{level:o="info",error:a}=s;return[...e.infoLogs||[],{id:r,step:t,label:n,data:i,timestamp:Date.now(),level:o,error:a}]}function EP(e,t,r,n){return!r||r.source!=="prm"||r.strictClientCompatible&&r.rfc9728Compliant?t:ie({...e,infoLogs:t},"received_resource_metadata","resource-identifier-mismatch","Resource identifier mismatch",{"Advertised resource":r.value,"Server URL":n,Status:r.status,Reason:r.reason,"RFC 9728 compliant":r.rfc9728Compliant,...r.rfc9728Reason?{"RFC 9728 reason":r.rfc9728Reason}:{},Note:r.status==="valid"?"The flow will send this interoperability-safe resource, but it is not RFC 9728 compliant and strict conformance surfaces will reject it.":"The debugger will send the advertised resource as-is so you can observe real behavior, but MCP clients — including MCPJam's Quick OAuth and the official MCP SDK — validate it against the server URL and will refuse to connect."},{level:"warning"})}function Ta(e,t,r,n){return ie({...e,infoLogs:t},r,"non-compliant-challenge-status","Non-compliant challenge status",{Received:`${n.status}${n.statusText?` ${n.statusText}`:""}`,Expected:"401 Unauthorized",Note:"The server sent a WWW-Authenticate Bearer challenge, so the debugger continues OAuth discovery from it. MCP requires 401 here — clients that decide to authenticate from the status code alone, including the official MCP SDK, will not start OAuth against this server."},{level:"warning"})}function Ct(e){return e instanceof Error?{message:e.message,details:{name:e.name,stack:e.stack}}:typeof e=="string"?{message:e}:{message:"Unexpected error",details:e}}function En(e,t){if(!e||e.length===0)return e||void 0;const r=[...e],n={...r[r.length-1]};return r[r.length-1]={...n,error:t,duration:n.duration!==void 0?n.duration:Date.now()-n.timestamp},r}function lt(e,t={}){const r={},n=new Map,i=s=>{if(s)for(const[o,a]of Object.entries(s)){const c=o.toLowerCase(),u=n.get(c);u&&u!==o&&delete r[u],n.set(c,o),r[o]=a}};return i(e),i(t),r}function at(e,t={}){const r=lt(e,t);for(const n of Object.keys(r))n.toLowerCase()==="authorization"&&delete r[n];return r}function Xl(e,t,r,n={}){try{const i=new URL(e).origin;return new URL(t,e).origin===i?lt(r,n):at(r,n)}catch{return at(r,n)}}function zr(e){if(!e)return{};if(e instanceof Headers){const t={};return e.forEach((r,n)=>{t[n]=r}),t}return Array.isArray(e)?Object.fromEntries(e.map(([t,r])=>[t,String(r)])):Object.fromEntries(Object.entries(e).map(([t,r])=>[t,String(r)]))}function kP(e){if(typeof globalThis.btoa=="function"){const t=Array.from(e,r=>String.fromCharCode(r)).join("");return globalThis.btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}if(typeof Buffer<"u")return Buffer.from(e).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"");throw new Error("No base64 encoder available")}function Gr(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=new Uint8Array(e);return crypto.getRandomValues(r),Array.from(r,n=>t[n%66]).join("")}async function Ra(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return kP(new Uint8Array(r))}var Pa="Authorization server metadata missing required 'issuer' field",IP=new Set(["2025-03-26"]),AP=new Set(["2025-03-26","2025-06-18"]);function TP(e){return!IP.has(e)}function RP(e){return!AP.has(e)}function Dm(e,t){if(RP(t)){if(!e||e.length===0)return`PKCE is REQUIRED for ${t} protocol, but authorization server does not advertise code_challenge_methods_supported. Server is not compliant with ${t} spec.`;if(!e.includes("S256"))return`Authorization server advertises PKCE without S256 (advertised: ${e.join(", ")}). MCPJam will not downgrade to a weaker code challenge method, so the ${t} flow stops here. Use the OAuth debugger to observe this server's behavior without connecting.`}}function Ql(e){const t=e.authorizationServers?.find(r=>typeof r=="string"&&r.trim()!=="")?.trim();return t?{authorizationServerUrl:t,substituted:!1}:TP(e.protocolVersion)?{authorizationServerUrl:e.fallbackServerUrl,substituted:!0,error:`Protected resource metadata does not list an authorization server. RFC 9728 \`authorization_servers\` is required by the ${e.protocolVersion} MCP profile; without it there is no server authorized to issue tokens for this resource, and using the MCP server's own URL would invent one.`}:{authorizationServerUrl:e.fallbackServerUrl,substituted:!0}}var PP="io.modelcontextprotocol/oauth-client-credentials",OP="io.modelcontextprotocol/protocolVersion",CP="io.modelcontextprotocol/clientCapabilities",$P="io.modelcontextprotocol/clientInfo";function ed(e){switch(e){case"2025-11-25":return"2025-11-25";case"2026-07-28":return"2026-07-28";case"2025-06-18":case"2025-03-26":return"2024-11-05";default:return e}}function zm(e){return e!=="client_credentials"?{}:{extensions:{[PP]:{}}}}function jt(e){return{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:e.protocolVersion,capabilities:zm(e.authMode),clientInfo:{name:e.clientName,version:e.clientVersion}},id:e.id}}function js(e){return{jsonrpc:"2.0",method:"tools/list",params:{_meta:{[OP]:e.protocolVersion,[CP]:zm(e.authMode),[$P]:{name:e.clientName,version:e.clientVersion}}},id:e.id}}var xP="***REDACTED***",MP=new Set(["client_secret","registration_access_token","access_token","refresh_token"]),Oa="Authorization server metadata does not include a registration_endpoint. Configure a pre-registered client or use a different registration strategy.",Ca="Authorization server metadata does not include a registration_endpoint required for DCR conformance.";function LP(e){const t=r=>{let n;try{n=new URL(r)}catch{return!0}if(n.protocol!=="http:"&&n.protocol!=="https:")return!0;if(n.protocol!=="http:")return!1;const i=n.hostname;return i==="localhost"||i==="127.0.0.1"||i==="[::1]"};return e.some(t)?"native":"web"}function $a(e){const{dynamicRegistrationDefaults:t}=e,r={...t,redirect_uris:t.redirect_uris??[e.redirectUri],grant_types:t.grant_types??["authorization_code","refresh_token"],response_types:t.response_types??["code"],token_endpoint_auth_method:t.token_endpoint_auth_method??"none"};return e.scope&&(r.scope=e.scope),{method:"POST",url:e.registrationEndpoint,headers:at(e.customHeaders,{"Content-Type":"application/json"}),body:r}}function Ru(e){if(Array.isArray(e))return e.map(Ru);if(e&&typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))t[r]=MP.has(r.toLowerCase())?xP:Ru(n);return t}return e}function NP(e){return{status:e.status,statusText:e.statusText,headers:{...e.headers},body:Ru(e.body)}}function Gh(e,t){const r=[...e||[]];if(r.length>0){const n=r[r.length-1];r[r.length-1]={...n,response:t,duration:Date.now()-(n.timestamp||Date.now())}}return r}var lo="Configure a pre-registered client or enable DCR on the authorization server.";async function xa(e){let t;try{t=await e.requestExecutor(e.request)}catch(o){const a=o instanceof Error?o.message:String(o),c={status:0,statusText:"Network Error",headers:{},body:{error:a}},u=`Client registration failed: ${a}`;return{status:"network_error",response:c,httpHistory:Gh(e.httpHistory,c),error:u,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${u}. ${lo}`}}const r=NP({status:t.status,statusText:t.statusText,headers:t.headers,body:t.body}),n=Gh(e.httpHistory,r);if(!t.ok){const o=`Dynamic Client Registration failed (${t.status}).`;return{status:"http_error",response:r,httpHistory:n,error:o,fallbackNote:`Dynamic Client Registration failed (${t.status}); using pre-registered client credentials.`,errorWithFallbackHint:`${o} ${lo}`}}const i=t.body;if(!i||typeof i!="object"||Array.isArray(i)){const o="Client registration failed: the registration response body was not a JSON object";return{status:"invalid_response",response:r,httpHistory:n,error:o,fallbackNote:"Client registration failed; using pre-registered client credentials.",errorWithFallbackHint:`${o}. ${lo}`}}const s={"Client ID":i.client_id,"Client Name":i.client_name,"Token Auth Method":i.token_endpoint_auth_method||"none","Redirect URIs":i.redirect_uris,"Grant Types":i.grant_types,"Response Types":i.response_types};return i.client_secret&&(s["Client Secret Issued"]=!0,s.Note="Server issued client_secret - this will be used in token requests"),{status:"registered",response:r,httpHistory:n,clientInfo:i,credentials:{clientId:typeof i.client_id=="string"?i.client_id:void 0,clientSecret:typeof i.client_secret=="string"?i.client_secret:void 0,tokenEndpointAuthMethod:typeof i.token_endpoint_auth_method=="string"?i.token_endpoint_auth_method:void 0,clientSecretExpiresAt:typeof i.client_secret_expires_at=="number"?i.client_secret_expires_at:void 0},missingClientId:typeof i.client_id!="string",nonCanonicalSuccessStatus:t.status!==201,infoLogData:s}}function Ma(e){return e?.sendResourceIndicator!==!1}function Zr(e,t){const r=e?.scopeRequest;if(!r)return rP(t);switch(r.mode){case"omit":return;case"fixed":return r.scopes.join(" ");case"challenge":{const n=t.challengedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}case"all-supported":{const n=t.supportedScopes?.filter(Boolean)??[];return n.length>0?Array.from(new Set(n)).join(" "):void 0}}}function La(e,t){if(!t)return e;const r={...e};return t.dcrClientName!==void 0&&(r.client_name=t.dcrClientName),t.tokenEndpointAuthMethod!==void 0&&(r.token_endpoint_auth_method=t.tokenEndpointAuthMethod),t.dcrRedirectUris!==void 0&&(r.redirect_uris=[...t.dcrRedirectUris]),r}function Wr(e,t){return e?.tokenEndpointAuthMethod??t}function DP(e,t){return t?.userAgent?{...e??{},"User-Agent":t.userAgent}:e}function kn(e,t){return e?.mcpProtocolVersion??t}function zP(e,t){return Aa(e,t,{protocolVersion:"2025-03-26",includesProtectedResourceMetadata:!1,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET /.well-known/oauth-authorization-server from MCP base URL",description:"Direct discovery from MCP server base URL with fallback to /authorize, /token, /register"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:r=>r.serverUrl})}function UP(e){return new URL(e).origin}function Zh(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var FP=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:u,dynamicRegistration:l,customScopes:h,customHeaders:d,authMode:p,hasClientSecret:f=!1,strictConformance:v=!1,registrationStrategy:g="dcr",emulation:m}=e,w=o,S=kn(m,"2025-03-26"),O=kn(m,ed("2025-03-26")),R=Ma(m),I=La(l??{},m);if(g==="dcr"&&!I.client_name)throw new Error("Dynamic registration metadata must include client_name");const C=()=>r?r():t,L=(k,ne={})=>a({url:k,method:ne.method||"GET",headers:zr(ne.headers),body:ne.body}),q=k=>{const ne=wa({authorizationServerMetadata:C().authorizationServerMetadata,hasClientSecret:!!(k||f)});if(!ne.ok)throw new Error(ne.message);return ne.method},K=async k=>{const{clientId:ne,clientSecret:H}=await u?.({serverName:s,serverUrl:i})??{};if(!ne)return;const oe=q(H),P={"Client ID":ne,"Client Secret":H||f?"Configured":"Not provided (public client)","Token Auth Method":oe,Note:k};return{clientId:ne,clientSecret:H||void 0,tokenEndpointAuthMethod:oe,infoLogs:ie(C(),"received_client_credentials","preregistered-fallback","Pre-registered Client",P)}},X={state:t,updateState:n,proceedToNextStep:async()=>{const k=C();n({isInitiatingAuth:!0});const ne=H=>{c?.(()=>{X.proceedToNextStep()},H)};try{switch(k.currentStep){case"idle":n({currentStep:"discovery_start",serverUrl:i,httpHistory:[],isInitiatingAuth:!1}),ne(50);return;case"request_without_token":if(!k.serverUrl)throw new Error("No server URL available");try{const z=await L(k.serverUrl,{method:"POST",headers:lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":S}),body:JSON.stringify(jt({protocolVersion:O,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:1}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const $e=ae[ae.length-1];$e.response=se,$e.duration=Date.now()-($e.timestamp||Date.now())}const he=Is({status:z.status,statusText:z.statusText,wwwAuthenticateHeader:z.headers["www-authenticate"],serverMessage:z.body?.error?.message});if(he.kind==="challenged"||he.kind==="anonymous_allowed"){let $e=he.kind==="anonymous_allowed"?ie(k,"discovery_start","optional-auth","Optional Authentication",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"}):k.infoLogs;he.kind==="challenged"&&!he.specCompliant&&($e=Ta(k,$e,"discovery_start",se)),n({currentStep:"discovery_start",lastResponse:se,httpHistory:ae,infoLogs:$e,isInitiatingAuth:!1})}else throw n({lastResponse:se,httpHistory:ae}),new Hr(he.message,z.status)}catch(z){throw z instanceof Hr?z:new Error(`Failed to request MCP server: ${z instanceof Error?z.message:String(z)}`)}break;case"discovery_start":const H=k.serverUrl,oe={method:"GET",url:Zh(H)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",authorizationServerUrl:H,lastRequest:oe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:oe}],isInitiatingAuth:!1}),ne(50);return;case"request_authorization_server_metadata":if(!k.authorizationServerUrl)throw new Error("No authorization server URL available");const P=Zh(k.authorizationServerUrl);let ee=null,y=null;for(const z of P)try{const se=at(d,{"MCP-Protocol-Version":"2025-03-26"}),ae=[...k.httpHistory||[]];ae.length>0&&(ae[ae.length-1].request={method:"GET",url:z,headers:se}),n({lastRequest:{method:"GET",url:z,headers:se},httpHistory:ae});const he=await L(z,{method:"GET",headers:se});if(he.ok){ee=he.body,y=he;break}else if(he.status>=400&&he.status<500)continue}catch{continue}if(!ee){const z=UP(k.authorizationServerUrl);ee={issuer:z,authorization_endpoint:`${z}/authorize`,token_endpoint:`${z}/token`,registration_endpoint:`${z}/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]};const se=ie(C(),"received_authorization_server_metadata","fallback-endpoints","Using Fallback Endpoints",{Note:"Metadata discovery failed, using default endpoints per 2025-03-26 spec","Authorization Endpoint":ee.authorization_endpoint,"Token Endpoint":ee.token_endpoint,"Registration Endpoint":ee.registration_endpoint});n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ee,infoLogs:se,isInitiatingAuth:!1});break}if(!ee.issuer)throw new Error(Pa);if(!ee.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ee.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ee.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const B={status:y.status,statusText:y.statusText,headers:y.headers,body:ee},Y=[...k.httpHistory||[]];if(Y.length>0){const z=Y[Y.length-1];z.response=B,z.duration=Date.now()-(z.timestamp||Date.now())}const le=ee.code_challenge_methods_supported||[];(!le||le.length===0||!le.includes("S256"))&&console.warn("Authorization server may not support PKCE S256 (REQUIRED for 2025-03-26 spec)"),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ee,lastResponse:B,httpHistory:Y,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!k.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(g==="preregistered"){const{clientId:z,clientSecret:se}=await u?.({serverName:s,serverUrl:i})??{};if(!z){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const ae=q(se),he={"Client ID":z,"Client Secret":se||f?"Configured":"Not provided (public client)","Token Auth Method":ae,Note:"Using pre-registered client credentials (skipped DCR)"},$e=ie(C(),"received_client_credentials","dcr","Pre-registered Client",he);n({currentStep:"received_client_credentials",clientId:z,clientSecret:se||void 0,tokenEndpointAuthMethod:ae,infoLogs:$e,isInitiatingAuth:!1})}else if(k.authorizationServerMetadata.registration_endpoint){const z=k.authorizationServerMetadata.scopes_supported,se=Zr(m,{customScopes:h,supportedScopes:z}),ae=$a({registrationEndpoint:k.authorizationServerMetadata.registration_endpoint,redirectUri:w,dynamicRegistrationDefaults:I,scope:se,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:ae,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ne(50);return}else{if(v){n({error:Ca,isInitiatingAuth:!1});return}const z=await K("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!z){n({error:Oa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:z.clientId,clientSecret:z.clientSecret,tokenEndpointAuthMethod:z.tokenEndpointAuthMethod,infoLogs:z.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!k.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!k.lastRequest?.body)throw new Error("No client metadata in request");{const z=await xa({request:k.lastRequest,requestExecutor:a,httpHistory:k.httpHistory});if(z.status!=="registered"){if(n({lastResponse:z.response,httpHistory:z.httpHistory,error:z.error}),v){z.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const ae=await K(z.fallbackNote);if(!ae){n({error:z.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:ae.clientId,clientSecret:ae.clientSecret,tokenEndpointAuthMethod:ae.tokenEndpointAuthMethod,infoLogs:ae.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(z.missingClientId){n({lastResponse:z.response,httpHistory:z.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const se=ie(C(),"received_client_credentials","dcr","Dynamic Client Registration",z.infoLogData);n({currentStep:"received_client_credentials",clientId:z.credentials.clientId,clientSecret:z.credentials.clientSecret,tokenEndpointAuthMethod:Sa(z.clientInfo),lastResponse:z.response,httpHistory:z.httpHistory,infoLogs:se,error:void 0,isInitiatingAuth:!1})}break;case"received_client_credentials":const de=Gr(43),Oe=await Ra(de),Ie=ie(C(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:Oe,method:"S256",...R?{resource:k.serverUrl||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"},note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});n({currentStep:"generate_pkce_parameters",codeVerifier:de,codeChallenge:Oe,codeChallengeMethod:"S256",...R?{}:{resourceIndicatorSuppressed:!0},state:Gr(16),infoLogs:Ie,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!k.authorizationServerMetadata?.authorization_endpoint||!k.clientId)throw new Error("Missing authorization endpoint or client ID");const _e=new URL(k.authorizationServerMetadata.authorization_endpoint);_e.searchParams.set("response_type","code"),_e.searchParams.set("client_id",k.clientId),_e.searchParams.set("redirect_uri",w),_e.searchParams.set("code_challenge",k.codeChallenge||""),_e.searchParams.set("code_challenge_method","S256"),_e.searchParams.set("state",k.state||""),k.serverUrl&&R&&_e.searchParams.set("resource",k.serverUrl);const ge=Zr(m,{customScopes:h,supportedScopes:k.authorizationServerMetadata.scopes_supported});ge&&_e.searchParams.set("scope",ge);const Je=ie(C(),"authorization_request","auth-url","Authorization URL",{url:_e.toString()});n({currentStep:"authorization_request",authorizationUrl:_e.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:Je,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!k.authorizationCode||k.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const z=Br({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Wr(m,k.tokenEndpointAuthMethod)}),se={grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,...z.bodyParams};k.codeVerifier&&(se.code_verifier=k.codeVerifier),k.serverUrl&&R&&(se.resource=k.serverUrl);const ae={method:"POST",url:k.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...z.headers},body:se};n({currentStep:"token_request",lastRequest:ae,lastResponse:void 0,...R?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...k.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ae}],isInitiatingAuth:!1}),ne(50);return}case"token_request":if(!k.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!k.authorizationCode)throw new Error("Missing authorization code");if(!k.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const z=Br({clientId:k.clientId,clientSecret:k.clientSecret,tokenEndpointAuthMethod:Wr(m,k.tokenEndpointAuthMethod)}),se=new URLSearchParams({grant_type:"authorization_code",code:k.authorizationCode,redirect_uri:w,code_verifier:k.codeVerifier||"",...z.bodyParams});k.serverUrl&&R&&se.set("resource",k.serverUrl);const ae=await L(k.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...z.headers},body:se.toString()}),he={status:ae.status,statusText:ae.statusText,headers:ae.headers,body:ae.body},$e=[...k.httpHistory||[]];if($e.length>0){const ve=$e[$e.length-1];ve.response=he,ve.duration=Date.now()-(ve.timestamp||Date.now())}if(!ae.ok){n({lastResponse:he,httpHistory:$e,authorizationCode:void 0,error:ka(ae),isInitiatingAuth:!1});return}const we=ae.body;let Se=(C().infoLogs||[]).filter(ve=>ve.id!=="auth-code"&&ve.id!=="oauth-tokens"&&ve.id!=="token");if(k.authorizationCode&&(Se=[...Se,{id:"auth-code",level:"info",step:"received_authorization_code",label:"Authorization Code",data:{code:k.authorizationCode},timestamp:Date.now()}]),we.access_token){const ve={access_token:we.access_token};we.refresh_token&&(ve.refresh_token=we.refresh_token),Se=[...Se,{id:"oauth-tokens",level:"info",step:"received_access_token",label:"OAuth Tokens",data:ve,timestamp:Date.now()}]}if(we.access_token){const ve=Vr(we.access_token);if(ve){const me={...ve};me.exp&&(me.exp=`${me.exp} (${Ne(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${Ne(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${Ne(me.nbf)})`);const Ee={...me};if(me.aud){const Ge=k.serverUrl,U=(Array.isArray(me.aud)?me.aud:[me.aud]).some(Z=>Z===Ge);Ee._validation={expected_audience:Ge,audience_matches:U,note:U?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Ee._validation={note:"⚠ No audience claim found - server should validate token binding"};Se=[...Se,{id:"token",step:"received_access_token",level:"info",label:"Access Token (Decoded JWT)",data:Ee,timestamp:Date.now()}]}}if(we.id_token){const ve=Vr(we.id_token);if(ve){const me={...ve};me.exp&&(me.exp=`${me.exp} (${Ne(me.exp)})`),me.iat&&(me.iat=`${me.iat} (${Ne(me.iat)})`),me.nbf&&(me.nbf=`${me.nbf} (${Ne(me.nbf)})`),me.auth_time&&(me.auth_time=`${me.auth_time} (${Ne(me.auth_time)})`),me._note="OIDC ID Token - Used for user identity verification",Se=[...Se,{id:"id-token",step:"received_access_token",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:me,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:we.access_token,refreshToken:we.refresh_token,tokenType:we.token_type||"Bearer",expiresIn:we.expires_in,lastResponse:he,httpHistory:$e,infoLogs:Se,error:void 0,isInitiatingAuth:!1})}catch(z){const se={status:0,statusText:"Network Error",headers:{},body:{error:z instanceof Error?z.message:String(z)}},ae=[...k.httpHistory||[]];if(ae.length>0){const he=ae[ae.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}n({lastResponse:se,httpHistory:ae,error:`Token exchange failed: ${z instanceof Error?z.message:String(z)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");const Xe={method:"POST",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:jt({protocolVersion:O,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2})},Ce=ie(C(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-03-26",Client:"MCP Inspector v1.0.0",Endpoint:k.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Xe,lastResponse:void 0,httpHistory:[...k.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Xe}],infoLogs:Ce,isInitiatingAuth:!1}),ne(50);return;case"authenticated_mcp_request":if(!k.serverUrl||!k.accessToken)throw new Error("Missing server URL or access token");try{const z=await L(k.serverUrl,{method:"POST",headers:lt(d,{Authorization:`Bearer ${k.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify(jt({protocolVersion:O,authMode:p,clientName:"MCP Inspector",clientVersion:"1.0.0",id:2}))}),se={status:z.status,statusText:z.statusText,headers:z.headers,body:z.body},ae=[...k.httpHistory||[]];if(ae.length>0){const ve=ae[ae.length-1];ve.response=se,ve.duration=Date.now()-(ve.timestamp||Date.now())}if(!z.ok){if(z.status>=400&&z.status<500)try{const ve={method:"GET",url:k.serverUrl,headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}},me={step:"complete",timestamp:Date.now(),request:ve};ae.push(me);const Ee=await L(k.serverUrl,{method:"GET",headers:{Authorization:`Bearer ${k.accessToken}`,Accept:"text/event-stream"}});me.response={status:Ee.status,statusText:Ee.statusText,headers:Ee.headers,body:Ee.body},me.duration=Date.now()-me.timestamp;const Ge=Ee.body;if(Ge&&typeof Ge=="object"&&Ge.isOldTransport&&Ge.endpoint){const U=Ge.endpoint,Z=new URL(U,k.serverUrl).toString(),Q=ie(C(),"authenticated_mcp_request","http-sse-detected","HTTP+SSE Transport Detected (2024-11-05)",{Transport:"HTTP+SSE (2024-11-05 - Deprecated)","SSE Stream URL":k.serverUrl,"POST Endpoint":Z,"First Event":Ge.events?.[0],"Migration Note":"This transport is deprecated. Please update your server to use the 2025-03-26 Streamable HTTP transport.","How It Works":"Client connected via GET for SSE stream. Subsequent requests use POST to: "+Z});n({currentStep:"complete",lastResponse:{status:Ee.status,statusText:"OK - HTTP+SSE Transport",headers:Ee.headers,body:{transport:"HTTP+SSE (2024-11-05)",sseStreamUrl:k.serverUrl,postEndpoint:Z,events:Ge.events}},httpHistory:ae,infoLogs:Q,error:void 0,isInitiatingAuth:!1});return}}catch(ve){console.error("GET fallback failed:",ve)}n({lastResponse:se,httpHistory:ae,error:Ea(z),isInitiatingAuth:!1});return}let he=C().infoLogs||[];const $e=z.headers["content-type"]||"",we=$e.includes("text/event-stream");let Se=null;if(we&&z.body?.transport==="sse"?Se=z.body.mcpResponse:Se=z.body,we&&Se?.result?.protocolVersion){const ve={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(ve["Server Name"]=Se.result.serverInfo.name,ve["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(ve.Capabilities=Se.result.capabilities),he=ie(C(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ve)}else if(we)he=ie(C(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":$e,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:z.body?.events?`${z.body.events.length} events parsed`:"No events parsed"});else if(Se?.result?.protocolVersion){const ve={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":Se.result.protocolVersion};Se.result.serverInfo&&(ve["Server Name"]=Se.result.serverInfo.name,ve["Server Version"]=Se.result.serverInfo.version),Se.result.capabilities&&(ve.Capabilities=Se.result.capabilities),he=ie(C(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ve)}n({currentStep:"complete",lastResponse:se,httpHistory:ae,infoLogs:he,error:void 0,isInitiatingAuth:!1})}catch(z){const se=Ct(z),ae={status:0,statusText:"Network Error",headers:{},body:{error:se.message,details:se.details}},he=[...k.httpHistory||[]];if(he.length>0){const Se={...he[he.length-1],response:ae,duration:Date.now()-(he[he.length-1]?.timestamp||Date.now()),error:se};he[he.length-1]=Se}const $e=C(),we=ie($e,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:$e.lastRequest,error:se},{level:"error",error:se});n({lastResponse:ae,httpHistory:he,infoLogs:we,error:`Authenticated MCP request failed: ${se.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(H){const oe=C(),P=Ct(H),ee=ie(oe,oe.currentStep,`error-${oe.currentStep}-${Date.now()}`,"Step failed",{step:oe.currentStep,request:oe.lastRequest,response:oe.lastResponse,error:P},{level:"error",error:P}),y=En(oe.httpHistory,P),B={error:P.message,infoLogs:ee,isInitiatingAuth:!1};y&&(B.httpHistory=y),n(B)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(Ia())}};return X};function td(e){const t=new URL(e);if(t.pathname!=="/"&&t.pathname!==""){const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;return new URL(`/.well-known/oauth-protected-resource${r}`,t.origin).toString()}return new URL("/.well-known/oauth-protected-resource",t.origin).toString()}var Wh="Could not discover authorization server metadata.";function qP(e){if("error"in e){const t=e.error instanceof Error?e.error.message:String(e.error);return`${e.url} failed: ${t}`}return e.status>=200&&e.status<300?`${e.url} returned HTTP ${e.status} with no metadata document`:`${e.url} returned HTTP ${e.status}`}function rd(e){return e.length===0?`${Wh} No well-known URL was tried.`:`${Wh} ${e.map(qP).join("; ")}.`}function _i(e,t){return uP({serverUrl:e.serverUrl??t,prmResource:e.resourceMetadata?.resource,resolved:e.resourceIndicator})}function nd(e){const t=e.state.serverUrl??e.fallbackServerUrl,r=e.prmResource?.trim();if(!r){const o='Protected Resource Metadata is missing its required "resource" identifier (RFC 9728 §2).';if(e.enforcement!=="warn")throw new Error(o);return{resourceIndicator:Iu({serverUrl:t}),infoLogs:ie({...e.state,infoLogs:e.infoLogs},"received_resource_metadata","resource-identifier-mismatch","Resource identifier missing",{"Server URL":t,Reason:o,Note:"The debugger will fall back to the server URL as the resource indicator, but strict MCP clients treat this metadata as invalid."},{level:"warning"})}}const n=Iu({serverUrl:t,prmResource:r}),i=e.enforcement!=="warn"&&n.status!=="valid",s=e.enforcement==="reject-rfc9728"&&!n.rfc9728Compliant;if(n.source==="prm"&&(i||s))throw new Error((s?n.rfc9728Reason:void 0)??n.reason??"Protected Resource Metadata advertises an unusable resource identifier.");return{resourceIndicator:n,infoLogs:EP(e.state,e.infoLogs,n,t)}}var jP=e=>_i(e);function HP(e,t){return Aa(e,t,{protocolVersion:"2025-06-18",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try RFC8414 path, then RFC8414 root (no OIDC support)"},pkce:{label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter"},resourceValue:jP})}function Jh(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return r}var BP=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:u,dynamicRegistration:l,customScopes:h,customHeaders:d,resourceMetadataUrl:p,authMode:f,hasClientSecret:v=!1,strictConformance:g=!1,resourceIndicatorEnforcement:m="warn",requiredMetadataEnforcement:w="reject",registrationStrategy:S="dcr",emulation:O}=e,R=o,I=kn(O,"2025-06-18"),C=kn(O,ed("2025-06-18")),L=Ma(O),q=La(l??{},O);if(S==="dcr"&&!q.client_name)throw new Error("Dynamic registration metadata must include client_name");const K=()=>r?r():t,X=()=>_i(K(),i),k=(P,ee={})=>a({url:P,method:ee.method||"GET",headers:zr(ee.headers),body:ee.body}),ne=P=>{const ee=wa({authorizationServerMetadata:K().authorizationServerMetadata,hasClientSecret:!!(P||v)});if(!ee.ok)throw new Error(ee.message);return ee.method},H=async P=>{const{clientId:ee,clientSecret:y}=await u?.({serverName:s,serverUrl:i})??{};if(!ee)return;const B=ne(y),Y={"Client ID":ee,"Client Secret":y||v?"Configured":"Not provided (public client)","Token Auth Method":B,Note:P};return{clientId:ee,clientSecret:y||void 0,tokenEndpointAuthMethod:B,infoLogs:ie(K(),"received_client_credentials","preregistered-fallback","Pre-registered Client",Y)}},oe={state:t,updateState:n,proceedToNextStep:async()=>{const P=K();n({isInitiatingAuth:!0});const ee=y=>{c?.(()=>{oe.proceedToNextStep()},y)};try{switch(P.currentStep){case"idle":{const U=lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":I}),Z=jt({protocolVersion:C,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),Q={method:"POST",url:i,headers:U,body:Z};n({currentStep:"request_without_token",serverUrl:i,lastRequest:Q,lastResponse:void 0,httpHistory:[...P.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:Q}],isInitiatingAuth:!1}),ee(50);return}case"request_without_token":if(!P.serverUrl)throw new Error("No server URL available");try{const U=await k(P.serverUrl,{method:"POST",headers:lt(d,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":I}),body:JSON.stringify(jt({protocolVersion:C,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),Z={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Q=[...P.httpHistory||[]];if(Q.length>0){const T=Q[Q.length-1];T.response=Z,T.duration=Date.now()-(T.timestamp||Date.now())}const _=Is({status:U.status,statusText:U.statusText,wwwAuthenticateHeader:U.headers["www-authenticate"],serverMessage:U.body?.error?.message});if(_.kind==="challenged"){const T=U.headers["www-authenticate"],E=gr(T),$=Kl(E.scope);let F=T?ie(P,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:T,...$&&$.length>0?{scope:$.join(" ")}:{},"Received from":P.serverUrl||"Unknown"}):P.infoLogs;_.specCompliant||(F=Ta(P,F,"received_401_unauthorized",Z)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:T||void 0,challengedScopes:$,lastResponse:Z,httpHistory:Q,infoLogs:F,isInitiatingAuth:!1})}else if(_.kind==="anonymous_allowed"){const T=ie(P,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,challengedScopes:void 0,lastResponse:Z,httpHistory:Q,infoLogs:T,isInitiatingAuth:!1})}else throw n({lastResponse:Z,httpHistory:Q}),new Hr(_.message,U.status)}catch(U){throw U instanceof Hr?U:new Error(`Failed to request MCP server: ${U instanceof Error?U.message:String(U)}`)}break;case"received_401_unauthorized":{const U=gr(P.wwwAuthenticateHeader);let Z=p||U.resource_metadata;if(!Z&&P.serverUrl&&(Z=td(P.serverUrl)),!Z)throw new Error("Could not determine resource metadata URL");const Q={method:"GET",url:Z,headers:lt(d,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:Z,lastRequest:Q,lastResponse:void 0,httpHistory:[...P.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:Q}],isInitiatingAuth:!1}),ee(50);return}case"request_resource_metadata":if(!P.serverUrl)throw new Error("No server URL available");const y=[...P.httpHistory||[]];let B=y.length>0&&y[y.length-1]?.step==="request_resource_metadata"&&!y[y.length-1]?.response?y.pop():void 0;const Y=[],le=U=>{if(!U)return{};if(U instanceof Headers){const Z={};return U.forEach((Q,_)=>{Z[_]=Q}),Z}return Array.isArray(U)?Object.fromEntries(U):Object.fromEntries(Object.entries(U).map(([Z,Q])=>[Z,String(Q)]))},de=async(U,Z={})=>{const Q=typeof U=="string"?U:U.toString(),_=Xl(i,Q,d,le(Z.headers)),T=B?{...B,timestamp:Date.now(),request:{method:Z.method||"GET",url:Q,headers:_,body:Z.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:Z.method||"GET",url:Q,headers:_,body:Z.body}};B=void 0,Y.push(T);try{const E=await k(Q,{method:Z.method||"GET",headers:_,body:Z.body});T.response={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},T.duration=Date.now()-T.timestamp;const $={status:E.status,statusText:E.statusText,headers:E.headers},F=typeof E.body=="string"?E.body:JSON.stringify(E.body??{});return new Response(F,$)}catch(E){throw T.error=Ct(E),T.duration=Date.now()-T.timestamp,E}};try{const U=(p||gr(P.wwwAuthenticateHeader).resource_metadata)&&P.resourceMetadataUrl?{resourceMetadataUrl:P.resourceMetadataUrl}:void 0,Z=await ba(P.serverUrl,U,de),Q=[...y,...Y],_=Y[Y.length-1],T=Ql({authorizationServers:Z.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-06-18"}),E=T.authorizationServerUrl;if(T.error&&w!=="observe"){n({resourceMetadata:Z,resourceMetadataUrl:_?.request?.url||P.resourceMetadataUrl,lastRequest:_?.request,lastResponse:_?.response,httpHistory:Q,error:T.error,isInitiatingAuth:!1});return}let $=P.infoLogs??[];T.error&&($=ie({...K(),infoLogs:$},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:T.error,"Using instead":E}));const{resourceIndicator:F,infoLogs:V}=nd({state:P,fallbackServerUrl:i,prmResource:Z.resource,enforcement:m,infoLogs:$});n({currentStep:"received_resource_metadata",resourceMetadata:Z,resourceIndicator:F,resourceMetadataUrl:_?.request?.url||P.resourceMetadataUrl,authorizationServerUrl:E,lastRequest:_?.request,lastResponse:_?.response,httpHistory:Q,infoLogs:V,isInitiatingAuth:!1})}catch(U){const Z=En([...y,...Y],Ct(U));throw n({lastResponse:Y[Y.length-1]?.response,httpHistory:Z}),new Error(ya(U))}break;case"received_resource_metadata":if(!P.authorizationServerUrl)throw new Error("No authorization server URL available");const Oe={method:"GET",url:Jh(P.authorizationServerUrl)[0],headers:at(d,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Oe,lastResponse:void 0,httpHistory:[...P.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Oe}],isInitiatingAuth:!1}),ee(50);return;case"request_authorization_server_metadata":if(!P.authorizationServerUrl)throw new Error("No authorization server URL available");const Ie=Jh(P.authorizationServerUrl);let _e=null;const ge=[];let Je={},Xe=null;for(const U of Ie)try{const Z=at(d,{}),Q=[...P.httpHistory||[]];Q.length>0&&(Q[Q.length-1].request={method:"GET",url:U,headers:Z}),n({lastRequest:{method:"GET",url:U,headers:Z},httpHistory:Q});const _=await k(U,{method:"GET",headers:at(d,{})});if(_.ok){_e=_.body,Je=_.headers,Xe=_,_e||ge.push({url:U,status:_.status});break}ge.push({url:U,status:_.status})}catch(Z){ge.push({url:U,error:Z});continue}if(!_e||!Xe)throw new Error(rd(ge));if(!_e.issuer)throw new Error(Pa);if(!_e.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!_e.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!_e.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const Ce={status:Xe.status,statusText:Xe.statusText,headers:Je,body:_e},z=[...P.httpHistory||[]];z.length>0&&(z[z.length-1].response=Ce);const se=_e.code_challenge_methods_supported||[];se.includes("S256")?n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Ce,httpHistory:z,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",se),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:_e,lastResponse:Ce,httpHistory:z,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!P.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(S==="preregistered"){const{clientId:U,clientSecret:Z}=await u?.({serverName:s,serverUrl:i})??{};if(!U){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const Q=ne(Z),_={"Client ID":U,"Client Secret":Z||v?"Configured":"Not provided (public client)","Token Auth Method":Q,Note:"Using pre-registered client credentials from server config (skipped DCR)"},T=ie(K(),"received_client_credentials","dcr","Pre-registered Client",_);n({currentStep:"received_client_credentials",clientId:U,clientSecret:Z||void 0,tokenEndpointAuthMethod:Q,infoLogs:T,isInitiatingAuth:!1})}else if(P.authorizationServerMetadata.registration_endpoint){const U=P.resourceMetadata?.scopes_supported||P.authorizationServerMetadata.scopes_supported,Z=Zr(O,{customScopes:h,challengedScopes:P.challengedScopes,supportedScopes:U}),Q=$a({registrationEndpoint:P.authorizationServerMetadata.registration_endpoint,redirectUri:R,dynamicRegistrationDefaults:q,scope:Z,customHeaders:d});n({currentStep:"request_client_registration",lastRequest:Q,lastResponse:void 0,httpHistory:[...P.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:Q}],isInitiatingAuth:!1}),ee(50);return}else{if(g){n({error:Ca,isInitiatingAuth:!1});return}const U=await H("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!U){n({error:Oa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:U.clientId,clientSecret:U.clientSecret,tokenEndpointAuthMethod:U.tokenEndpointAuthMethod,infoLogs:U.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":{if(!P.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!P.lastRequest?.body)throw new Error("No client metadata in request");const U=await xa({request:P.lastRequest,requestExecutor:a,httpHistory:P.httpHistory});if(U.status!=="registered"){if(n({lastResponse:U.response,httpHistory:U.httpHistory,error:U.error}),g){U.status==="invalid_response"&&n({isInitiatingAuth:!1});return}const Q=await H(U.fallbackNote);if(!Q){n({error:U.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:Q.clientId,clientSecret:Q.clientSecret,tokenEndpointAuthMethod:Q.tokenEndpointAuthMethod,infoLogs:Q.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(U.missingClientId){n({lastResponse:U.response,httpHistory:U.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const Z=ie(K(),"received_client_credentials","dcr","Dynamic Client Registration",U.infoLogData);n({currentStep:"received_client_credentials",clientId:U.credentials.clientId,clientSecret:U.credentials.clientSecret,tokenEndpointAuthMethod:Sa(U.clientInfo),lastResponse:U.response,httpHistory:U.httpHistory,infoLogs:Z,error:void 0,isInitiatingAuth:!1});break}case"received_client_credentials":const ae=Gr(43),he=await Ra(ae),$e=ie(K(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:he,method:"S256",...L?{resource:X()||"Unknown"}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:ae,codeChallenge:he,codeChallengeMethod:"S256",...L?{}:{resourceIndicatorSuppressed:!0},state:Gr(16),infoLogs:$e,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!P.authorizationServerMetadata?.authorization_endpoint||!P.clientId)throw new Error("Missing authorization endpoint or client ID");const we=new URL(P.authorizationServerMetadata.authorization_endpoint);we.searchParams.set("response_type","code"),we.searchParams.set("client_id",P.clientId),we.searchParams.set("redirect_uri",R),we.searchParams.set("code_challenge",P.codeChallenge||""),we.searchParams.set("code_challenge_method","S256"),we.searchParams.set("state",P.state||"");const Se=X();Se&&L&&we.searchParams.set("resource",Se);const ve=Zr(O,{customScopes:h,challengedScopes:P.challengedScopes,supportedScopes:P.resourceMetadata?.scopes_supported||P.authorizationServerMetadata.scopes_supported});ve&&we.searchParams.set("scope",ve);const me=ie(K(),"authorization_request","auth-url","Authorization URL",{url:we.toString()});n({currentStep:"authorization_request",authorizationUrl:we.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:me,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!P.authorizationCode||P.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!P.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const U=Br({clientId:P.clientId,clientSecret:P.clientSecret,tokenEndpointAuthMethod:Wr(O,P.tokenEndpointAuthMethod)}),Z={grant_type:"authorization_code",code:P.authorizationCode,redirect_uri:R,...U.bodyParams};P.codeVerifier&&(Z.code_verifier=P.codeVerifier);const Q=X();Q&&L&&(Z.resource=Q);const _={method:"POST",url:P.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...U.headers},body:Z};n({currentStep:"token_request",lastRequest:_,lastResponse:void 0,...L?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...P.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:_}],isInitiatingAuth:!1}),ee(50);return}case"token_request":if(!P.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!P.authorizationCode)throw new Error("Missing authorization code");if(!P.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const U=Br({clientId:P.clientId,clientSecret:P.clientSecret,tokenEndpointAuthMethod:Wr(O,P.tokenEndpointAuthMethod)}),Z=new URLSearchParams({grant_type:"authorization_code",code:P.authorizationCode,redirect_uri:R,code_verifier:P.codeVerifier||"",...U.bodyParams}),Q=X();Q&&L&&Z.set("resource",Q);const _=await k(P.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(d,{"Content-Type":"application/x-www-form-urlencoded"}),...U.headers},body:Z.toString()}),T={status:_.status,statusText:_.statusText,headers:_.headers,body:_.body},E=[...P.httpHistory||[]];if(E.length>0){const V=E[E.length-1];V.response=T,V.duration=Date.now()-(V.timestamp||Date.now())}if(!_.ok){n({lastResponse:T,httpHistory:E,authorizationCode:void 0,error:ka(_),isInitiatingAuth:!1});return}const $=_.body;let F=(K().infoLogs||[]).filter(V=>V.id!=="auth-code"&&V.id!=="oauth-tokens"&&V.id!=="token");if(P.authorizationCode&&(F=[...F,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:P.authorizationCode},timestamp:Date.now()}]),$.access_token){const V={access_token:$.access_token};$.refresh_token&&(V.refresh_token=$.refresh_token),F=[...F,{id:"oauth-tokens",step:"token_request",level:"info",label:"OAuth Tokens",data:V,timestamp:Date.now()}]}if($.access_token){const V=Vr($.access_token);if(V){const N={...V};N.exp&&(N.exp=`${N.exp} (${Ne(N.exp)})`),N.iat&&(N.iat=`${N.iat} (${Ne(N.iat)})`),N.nbf&&(N.nbf=`${N.nbf} (${Ne(N.nbf)})`);const G={...N};if(N.aud){const J=P.serverUrl,Vt=(Array.isArray(N.aud)?N.aud:[N.aud]).some(Qr=>Qr===J);G._validation={expected_audience:J,audience_matches:Vt,note:Vt?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else G._validation={note:"⚠ No audience claim found - server should validate token binding"};F=[...F,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:G,timestamp:Date.now()}]}}if($.id_token){const V=Vr($.id_token);if(V){const N={...V};N.exp&&(N.exp=`${N.exp} (${Ne(N.exp)})`),N.iat&&(N.iat=`${N.iat} (${Ne(N.iat)})`),N.nbf&&(N.nbf=`${N.nbf} (${Ne(N.nbf)})`),N.auth_time&&(N.auth_time=`${N.auth_time} (${Ne(N.auth_time)})`),N._note="OIDC ID Token - Used for user identity verification",F=[...F,{id:"id-token",step:"token_request",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:N,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:$.access_token,refreshToken:$.refresh_token,tokenType:$.token_type||"Bearer",expiresIn:$.expires_in,lastResponse:T,httpHistory:E,infoLogs:F,error:void 0,isInitiatingAuth:!1})}catch(U){const Z={status:0,statusText:"Network Error",headers:{},body:{error:U instanceof Error?U.message:String(U)}},Q=[...P.httpHistory||[]];if(Q.length>0){const _=Q[Q.length-1];_.response=Z,_.duration=Date.now()-(_.timestamp||Date.now())}n({lastResponse:Z,httpHistory:Q,error:`Token exchange failed: ${U instanceof Error?U.message:String(U)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!P.serverUrl||!P.accessToken)throw new Error("Missing server URL or access token");const Ee={method:"POST",url:P.serverUrl,headers:{Authorization:`Bearer ${P.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":I},body:jt({protocolVersion:C,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Ge=ie(K(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-06-18",Client:"MCPJam Inspector v1.0.0",Endpoint:P.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Ee,lastResponse:void 0,httpHistory:[...P.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Ee}],infoLogs:Ge,isInitiatingAuth:!1}),ee(50);return;case"authenticated_mcp_request":if(!P.serverUrl||!P.accessToken)throw new Error("Missing server URL or access token");try{const U=await k(P.serverUrl,{method:"POST",headers:lt(d,{Authorization:`Bearer ${P.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":I}),body:JSON.stringify(jt({protocolVersion:C,authMode:f,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),Z={status:U.status,statusText:U.statusText,headers:U.headers,body:U.body},Q=[...P.httpHistory||[]];if(Q.length>0){const F=Q[Q.length-1];F.response=Z,F.duration=Date.now()-(F.timestamp||Date.now())}if(!U.ok){n({lastResponse:Z,httpHistory:Q,error:Ea(U),isInitiatingAuth:!1});return}let _=K().infoLogs||[];const T=U.headers["content-type"]||"",E=T.includes("text/event-stream");let $=null;if(E&&U.body?.transport==="sse"?$=U.body.mcpResponse:$=U.body,E&&$?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":$.result.protocolVersion};$.result.serverInfo&&(F["Server Name"]=$.result.serverInfo.name,F["Server Version"]=$.result.serverInfo.version),$.result.capabilities&&(F.Capabilities=$.result.capabilities),_=ie(K(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}else if(E)_=ie(K(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":T,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:U.body?.events?`${U.body.events.length} events parsed`:"No events parsed"});else if($?.result?.protocolVersion){const F={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":$.result.protocolVersion};$.result.serverInfo&&(F["Server Name"]=$.result.serverInfo.name,F["Server Version"]=$.result.serverInfo.version),$.result.capabilities&&(F.Capabilities=$.result.capabilities),_=ie(K(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",F)}n({currentStep:"complete",lastResponse:Z,httpHistory:Q,infoLogs:_,error:void 0,isInitiatingAuth:!1})}catch(U){const Z=Ct(U),Q={status:0,statusText:"Network Error",headers:{},body:{error:Z.message,details:Z.details}},_=[...P.httpHistory||[]];if(_.length>0){const $={..._[_.length-1],response:Q,duration:Date.now()-(_[_.length-1]?.timestamp||Date.now()),error:Z};_[_.length-1]=$}const T=K(),E=ie(T,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:T.lastRequest,error:Z},{level:"error",error:Z});n({lastResponse:Q,httpHistory:_,infoLogs:E,error:`Authenticated MCP request failed: ${Z.message}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(y){const B=K(),Y=Ct(y),le=ie(B,B.currentStep,`error-${B.currentStep}-${Date.now()}`,"Step failed",{step:B.currentStep,request:B.lastRequest,response:B.lastResponse,error:Y},{level:"error",error:Y}),de=En(B.httpHistory,Y),Oe={error:Y.message,infoLogs:le,isInitiatingAuth:!1};de&&(Oe.httpHistory=de),n(Oe)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(Ia())}};return oe};function Na(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase();return t==="localhost"||t.endsWith(".localhost")||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(t)||t==="::1"}function Pz(e){try{const{protocol:t,hostname:r}=new URL(e);return t==="http:"&&Na(r)}catch{return!1}}function Um(e,t={}){let r;try{r=new URL(e)}catch{throw new Error("Client ID metadata URL must be a valid absolute URL")}const n=t.allowLoopback===!0&&r.protocol==="http:"&&Na(r.hostname);if(!n&&(r.protocol!=="https:"||!r.hostname))throw new Error("Client ID metadata URL must be an absolute HTTPS URL");const i=n?/^http:\/\//i:/^https:\/\//i;if(!i.test(e))throw new Error(n?"Client ID metadata URL must use the http:// scheme (with two slashes)":"Client ID metadata URL must use the https:// scheme (with two slashes)");if(/[\u0000-\u0020\u007f\\]/.test(e))throw new Error("Client ID metadata URL must not contain control characters, whitespace, or backslashes");if(r.hash||e.includes("#"))throw new Error("Client ID metadata URL must not contain a fragment component");const s=e.split(/[?#]/,1)[0].replace(i,""),o=s.indexOf("/"),a=o===-1?s:s.slice(0,o),c=o===-1?"":s.slice(o);if(!a)throw new Error("Client ID metadata URL must contain a host immediately after https://");if(r.username||r.password||a.includes("@"))throw new Error("Client ID metadata URL must not contain a userinfo component");if(!c)throw new Error("Client ID metadata URL must contain a path component");const u=l=>{const h=l.replace(/%2e/gi,".");return h==="."||h===".."};if(c.split("/").some(u))throw new Error("Client ID metadata URL must not contain single-dot or double-dot path segments");return e}var VP=e=>_i(e);function GP(e,t){return Aa(e,t,{protocolVersion:"2025-11-25",includesProtectedResourceMetadata:!0,initialMcpMethod:"initialize",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
|
|
110
|
+
Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:VP})}function Kh(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}var ZP=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:u,dynamicRegistration:l,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:g=!1,strictConformance:m=!1,resourceIndicatorEnforcement:w="warn",requiredMetadataEnforcement:S="reject",registrationStrategy:O="cimd",emulation:R}=e,I=o,C=kn(R,"2025-11-25"),L=kn(R,ed("2025-11-25")),q=Ma(R),K=La(l??{},R);let X=h??"";if(O==="dcr"&&!K.client_name)throw new Error("Dynamic registration metadata must include client_name");if(O==="cimd"&&!X)throw new Error("Client ID metadata URL is required for CIMD registration");O==="cimd"&&(X=Um(X));const k=()=>r?r():t,ne=()=>_i(k(),i),H=(y,B={})=>a({url:y,method:B.method||"GET",headers:zr(B.headers),body:B.body}),oe=y=>{const B=wa({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||g)});if(!B.ok)throw new Error(B.message);return B.method},P=async y=>{const{clientId:B,clientSecret:Y}=await u?.({serverName:s,serverUrl:i})??{};if(!B)return;const le=oe(Y),de={"Client ID":B,"Client Secret":Y||g?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:B,clientSecret:Y||void 0,tokenEndpointAuthMethod:le,infoLogs:ie(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},ee={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const B=Y=>{c?.(()=>{ee.proceedToNextStep()},Y)};try{switch(y.currentStep){case"idle":{const _=lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),T=jt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:_,body:T};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const _=await H(y.serverUrl,{method:"POST",headers:lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),body:JSON.stringify(jt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),T={status:_.status,statusText:_.statusText,headers:_.headers,body:_.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=T,F.duration=Date.now()-(F.timestamp||Date.now())}const $=Is({status:_.status,statusText:_.statusText,wwwAuthenticateHeader:_.headers["www-authenticate"],serverMessage:_.body?.error?.message});if($.kind==="challenged"){const F=_.headers["www-authenticate"],V=gr(F),N=Kl(V.scope);let G=F?ie(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...N&&N.length>0?{scope:N.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;$.specCompliant||(G=Ta(y,G,"received_401_unauthorized",T)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:N,lastResponse:T,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if($.kind==="anonymous_allowed"){const F=ie(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:T,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:T,httpHistory:E}),new Hr($.message,_.status)}catch(_){throw _ instanceof Hr?_:new Error(`Failed to request MCP server: ${_ instanceof Error?_.message:String(_)}`)}break;case"received_401_unauthorized":{const _=gr(y.wwwAuthenticateHeader);let T=f||_.resource_metadata;if(!T&&y.serverUrl&&(T=td(y.serverUrl)),!T)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:T,headers:lt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:T,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const Y=[...y.httpHistory||[]];let le=Y.length>0&&Y[Y.length-1]?.step==="request_resource_metadata"&&!Y[Y.length-1]?.response?Y.pop():void 0;const de=[],Oe=async(_,T={})=>{const E=typeof _=="string"?_:_.toString(),$=Xl(i,E,p,zr(T.headers)),F=le?{...le,timestamp:Date.now(),request:{method:T.method||"GET",url:E,headers:$,body:T.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:T.method||"GET",url:E,headers:$,body:T.body}};le=void 0,de.push(F);try{const V=await H(E,{method:T.method||"GET",headers:$,body:T.body});F.response={status:V.status,statusText:V.statusText,headers:V.headers,body:V.body},F.duration=Date.now()-F.timestamp;const N={status:V.status,statusText:V.statusText,headers:V.headers},G=typeof V.body=="string"?V.body:JSON.stringify(V.body??{});return new Response(G,N)}catch(V){throw F.error=Ct(V),F.duration=Date.now()-F.timestamp,V}};try{const _=(f||gr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,T=await ba(y.serverUrl,_,Oe),E=[...Y,...de],$=de[de.length-1],F=Ql({authorizationServers:T.authorization_servers,fallbackServerUrl:i,protocolVersion:"2025-11-25"}),V=F.authorizationServerUrl;if(F.error&&S!=="observe"){n({resourceMetadata:T,resourceMetadataUrl:$?.request?.url||y.resourceMetadataUrl,lastRequest:$?.request,lastResponse:$?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let N=y.infoLogs??[];F.error&&(N=ie({...k(),infoLogs:N},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":V}));const G=nd({state:y,fallbackServerUrl:i,prmResource:T.resource,enforcement:w,infoLogs:N}),J=G.resourceIndicator;N=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:T,resourceIndicator:J,resourceMetadataUrl:$?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:V,lastRequest:$?.request,lastResponse:$?.response,httpHistory:E,infoLogs:N,isInitiatingAuth:!1})}catch(_){const T=En([...Y,...de],Ct(_));throw n({lastResponse:de[de.length-1]?.response,httpHistory:T}),new Error(ya(_))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Ie={method:"GET",url:Kh(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Ie,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Ie}],isInitiatingAuth:!1}),B(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=Kh(y.authorizationServerUrl);let ge=null;const Je=[];let Xe={},Ce=null;for(const _ of _e)try{const T=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:_,headers:T}),n({lastRequest:{method:"GET",url:_,headers:T},httpHistory:E});const $=await H(_,{method:"GET",headers:at(p,{})});if($.ok){ge=$.body,Xe=$.headers,Ce=$,ge||Je.push({url:_,status:$.status});break}Je.push({url:_,status:$.status})}catch(T){Je.push({url:_,error:T});continue}if(!ge||!Ce)throw new Error(rd(Je));if(!ge.issuer)throw new Error(Pa);if(!ge.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ge.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ge.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Ce.status,statusText:Ce.statusText,headers:Xe,body:ge},se=[...y.httpHistory||[]];if(se.length>0){const _=se[se.length-1];_.response=z,_.duration=Date.now()-(_.timestamp||Date.now())}const ae=ge.code_challenge_methods_supported||[],he=Dm(ae,"2025-11-25"),$e=typeof ge.client_id_metadata_document_supported=="boolean"?ge.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)",we=ie(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":$e});if(he){if(m||S!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ge,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ge,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(O==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:X,isInitiatingAuth:!1}),B(800);return}else if(O==="preregistered"){const{clientId:_,clientSecret:T}=await u?.({serverName:s,serverUrl:i})??{};if(!_){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(T),$={"Client ID":_,"Client Secret":T||g?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ie(k(),"received_client_credentials","dcr","Pre-registered Client",$);n({currentStep:"received_client_credentials",clientId:_,clientSecret:T||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const _=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,T=Zr(R,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:_}),E=$a({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:I,dynamicRegistrationDefaults:K,scope:T,customHeaders:p});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}else{if(m){n({error:Ca,isInitiatingAuth:!1});return}const _=await P("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!_){n({error:Oa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:_.clientId,clientSecret:_.clientSecret,tokenEndpointAuthMethod:_.tokenEndpointAuthMethod,infoLogs:_.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const _=await xa({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(_.status!=="registered"){if(n({lastResponse:_.response,httpHistory:_.httpHistory,error:_.error,isInitiatingAuth:!1}),m)return;const E=await P(_.fallbackNote);if(!E){n({error:_.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(_.missingClientId){n({lastResponse:_.response,httpHistory:_.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const T=ie(k(),"received_client_credentials","dcr","Dynamic Client Registration",_.infoLogData);n({currentStep:"received_client_credentials",clientId:_.credentials.clientId,clientSecret:_.credentials.clientSecret,tokenEndpointAuthMethod:Sa(_.clientInfo),lastResponse:_.response,httpHistory:_.httpHistory,infoLogs:T,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),B(800);return;case"cimd_fetch_request":try{const _={method:"GET",url:X,headers:zr(void 0)},T=Date.now(),E=await H(X,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const $={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:_,lastResponse:$,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:T,duration:Date.now()-T,request:_,response:$}],isInitiatingAuth:!1}),B(800);return}catch(_){n({error:`CIMD metadata fetch failed: ${_ instanceof Error?_.message:String(_)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const _=y.lastResponse?.body;if(!_||typeof _!="object")throw new Error("CIMD metadata document was not available");if(_.client_id!==X)throw new Error("CIMD client_id mismatch");const T=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":X,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":_.client_name||"MCPJam","Redirect URIs":_.redirect_uris||[],"Token Auth Method":_.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};T?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const $=ie(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:X,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:$,isInitiatingAuth:!1})}catch(_){n({error:`CIMD validation failed: ${_ instanceof Error?_.message:String(_)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=Gr(43),ve=await Ra(Se),me=ie(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:ve,method:"S256",...q?{resource:ne()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:ve,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:Gr(16),infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",I),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ne());const Ge=Zr(R,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ie(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const _=Br({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Wr(R,y.tokenEndpointAuthMethod)}),T={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:I,..._.bodyParams};y.codeVerifier&&(T.code_verifier=y.codeVerifier),q&&(T.resource=ne());const E={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",..._.headers},body:T};n({currentStep:"token_request",lastRequest:E,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const _=Br({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Wr(R,y.tokenEndpointAuthMethod)}),T=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:I,code_verifier:y.codeVerifier||"",..._.bodyParams});q&&T.set("resource",ne());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),..._.headers},body:T.toString()}),$={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=$,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:$,httpHistory:F,authorizationCode:void 0,error:ka(E),isInitiatingAuth:!1});return}const V=E.body;let N=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(N=[...N,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),V.access_token){const G={access_token:V.access_token};V.refresh_token&&(G.refresh_token=V.refresh_token),N=[...N,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(V.access_token){const G=Vr(V.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${Ne(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${Ne(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${Ne(J.nbf)})`);const Vt={...J};if(J.aud){const Qr=y.serverUrl,wi=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ka=>Ka===Qr);Vt._validation={expected_audience:Qr,audience_matches:wi,note:wi?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Vt._validation={note:"⚠ No audience claim found - server should validate token binding"};N=[...N,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Vt,timestamp:Date.now()}]}}if(V.id_token){const G=Vr(V.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${Ne(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${Ne(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${Ne(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${Ne(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",N=[...N,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:V.access_token,refreshToken:V.refresh_token,tokenType:V.token_type||"Bearer",expiresIn:V.expires_in,lastResponse:$,httpHistory:F,infoLogs:N,error:void 0,isInitiatingAuth:!1})}catch(_){const T={status:0,statusText:"Network Error",headers:{},body:{error:_ instanceof Error?_.message:String(_)}},E=[...y.httpHistory||[]];if(E.length>0){const $=E[E.length-1];$.response=T,$.duration=Date.now()-($.timestamp||Date.now())}n({lastResponse:T,httpHistory:E,error:`Token exchange failed: ${_ instanceof Error?_.message:String(_)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const Z={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C},body:jt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Q=ie(k(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-11-25",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Z,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Z}],infoLogs:Q,isInitiatingAuth:!1}),B(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const _=await H(y.serverUrl,{method:"POST",headers:lt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":C}),body:JSON.stringify(jt({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),T={status:_.status,statusText:_.statusText,headers:_.headers,body:_.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=T,G.duration=Date.now()-(G.timestamp||Date.now())}if(!_.ok){n({lastResponse:T,httpHistory:E,error:Ea(_),isInitiatingAuth:!1});return}let $=k().infoLogs||[];const F=_.headers["content-type"]||"",V=F.includes("text/event-stream");let N=null;if(V&&_.body?.transport==="sse"?N=_.body.mcpResponse:N=_.body,V&&N?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":N.result.protocolVersion};N.result.serverInfo&&(G["Server Name"]=N.result.serverInfo.name,G["Server Version"]=N.result.serverInfo.version),N.result.capabilities&&(G.Capabilities=N.result.capabilities),$=ie(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(V)$=ie(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:_.body?.events?`${_.body.events.length} events parsed`:"No events parsed"});else if(N?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":N.result.protocolVersion};N.result.serverInfo&&(G["Server Name"]=N.result.serverInfo.name,G["Server Version"]=N.result.serverInfo.version),N.result.capabilities&&(G.Capabilities=N.result.capabilities),$=ie(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}n({currentStep:"complete",lastResponse:T,httpHistory:E,infoLogs:$,error:void 0,isInitiatingAuth:!1})}catch(_){const T={status:0,statusText:"Network Error",headers:{},body:{error:_ instanceof Error?_.message:String(_)}},E=[...y.httpHistory||[]];if(E.length>0){const $=E[E.length-1];$.response=T,$.duration=Date.now()-($.timestamp||Date.now())}n({lastResponse:T,httpHistory:E,error:`Authenticated MCP request failed: ${_ instanceof Error?_.message:String(_)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(Y){const le=k(),de=Ct(Y),Oe=ie(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Ie=En(le.httpHistory,de),_e={error:de.message,infoLogs:Oe,isInitiatingAuth:!1};Ie&&(_e.httpHistory=Ie),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(Ia())}};return ee},WP=e=>_i(e);function JP(e){const t=e.requestedScopes??[],r=e.challengedScopes??[],n=[];if(t.length>0&&n.push({label:"requested scopes",value:t.join(" ")}),r.length>0){const i=eP(t,r);n.push({label:"challenged scopes",value:r.join(" ")}),n.push({label:"scope union",value:i.join(" ")})}return n}function KP(e){const t=e.recordedIssuer??e.authorizationServerMetadata?.issuer;return t?[{label:"bound to issuer",value:t}]:[]}function YP(e,t){return Aa(e,t,{protocolVersion:"2026-07-28",includesProtectedResourceMetadata:!0,initialMcpMethod:"tools/list",authorizationServerMetadata:{label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending"},pkce:{label:`Generate PKCE (REQUIRED)
|
|
111
|
+
Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter"},resourceValue:WP,dcrNotes:[{label:"Deprecated",value:"DCR is deprecated in 2026-07-28 (PR #2858). Prefer CIMD or a pre-registered client; DCR remains a compatibility fallback for authorization servers without CIMD support."}],clientCredentialsExtras:KP,authorizationRequestExtras:JP})}function Yh(e){const t=new URL(e),r=[];if(t.pathname==="/"||t.pathname==="")r.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),r.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const n=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;r.push(new URL(`/.well-known/oauth-authorization-server${n}`,t.origin).toString()),r.push(new URL(`/.well-known/openid-configuration${n}`,t.origin).toString()),r.push(new URL(`${n}/.well-known/openid-configuration`,t.origin).toString())}return r}function Xh(e){const t=e.replace(/[\u0000-\u001f\u007f\u0085\u2028\u2029]+/g," ").trim();return`\`${t.length>256?`${t.slice(0,256)}…`:t}\``}function XP(e,t){let r,n;try{r=new URL(e),n=new URL(t)}catch{return!1}if(r.origin!==n.origin||r.search||r.hash||n.search||n.hash)return!1;const i=a=>a.endsWith("/")?a.slice(0,-1):a,s=i(r.pathname),o=i(n.pathname);return s===o?!1:s===""||s==="/"?o.length>0:o.startsWith(`${s}/`)}function QP(e,t){try{return new URL(e).origin===new URL(t).origin}catch{return!1}}function Qh(e,t){return e==null?!1:typeof e!="string"?!0:!QP(e,t)}function ep(e){return typeof e=="string"?`"${e}"`:"a non-string value"}function eO(e){const{advertisedIssuer:t,discoveryUrl:r,tokenEndpoint:n,registrationEndpoint:i,allowPathScopedIssuer:s}=e,o=XP(t,r),a=s&&o,c=a&&Qh(n,t),u=a&&Qh(i,t);return a&&!c&&!u?{accepted:!0,hint:""}:{accepted:!1,hint:c?` The path-scoped authorization server's token endpoint (${ep(n)}) is not on the same origin as its issuer ("${t}"); refusing to send credentials off-origin.`:u?` The path-scoped authorization server's registration endpoint (${ep(i)}) is not on the same origin as its issuer ("${t}"); refusing dynamic registration off-origin.`:o?` The advertised issuer is the same-origin root of the discovery URL — a multi-tenant, path-scoped authorization server. Enable "Path-scoped authorization server" in the server's OAuth configuration (Advanced settings) to allow this.`:""}}function tO(e){const{recordedIssuer:t,returnedIss:r,issParameterSupported:n,enforcePresentIssMismatch:i=!0}=e;if(r!=null&&r!==""){if(t!==void 0&&r!==t){const s=`Authorization response \`iss\` does not match the issuer this flow started with. Recorded from authorization-server metadata: ${Xh(t)}; returned on the callback: ${Xh(r)}.`;return i?{ok:!1,reason:`${s} Refusing to exchange the authorization code; not displaying any server-supplied error parameters (RFC 9207).`}:{ok:!0,warning:`${s} This protocol version does not require RFC 9207 issuer validation, so the flow continues; on 2026-07-28 this stops the flow before the authorization code is redeemed.`}}return{ok:!0}}return n===!0?{ok:!1,reason:"Authorization server advertised `authorization_response_iss_parameter_supported: true` but the callback did not include an `iss` parameter (RFC 9207 requires it)."}:{ok:!0}}var rO=e=>{const{state:t,getState:r,updateState:n,serverUrl:i,serverName:s,redirectUrl:o,requestExecutor:a,scheduleAutoAdvance:c,loadPreregisteredCredentials:u,dynamicRegistration:l,clientIdMetadataUrl:h,customScopes:d,customHeaders:p,resourceMetadataUrl:f,authMode:v,hasClientSecret:g=!1,strictConformance:m=!1,allowPathScopedIssuer:w=!1,resourceIndicatorEnforcement:S="warn",requiredMetadataEnforcement:O="reject",registrationStrategy:R="cimd",emulation:I}=e,C=o,L=kn(I,"2026-07-28"),q=Ma(I),K=La(l??{},I);let X=h??"";if(R==="dcr"&&!K.client_name)throw new Error("Dynamic registration metadata must include client_name");if(R==="cimd"&&!X)throw new Error("Client ID metadata URL is required for CIMD registration");R==="cimd"&&(X=Um(X));const k=()=>r?r():t,ne=()=>_i(k(),i),H=(y,B={})=>a({url:y,method:B.method||"GET",headers:zr(B.headers),body:B.body}),oe=y=>{const B=wa({authorizationServerMetadata:k().authorizationServerMetadata,hasClientSecret:!!(y||g)});if(!B.ok)throw new Error(B.message);return B.method},P=async y=>{const{clientId:B,clientSecret:Y}=await u?.({serverName:s,serverUrl:i})??{};if(!B)return;const le=oe(Y),de={"Client ID":B,"Client Secret":Y||g?"Configured":"Not provided (public client)","Token Auth Method":le,Note:y};return{clientId:B,clientSecret:Y||void 0,tokenEndpointAuthMethod:le,infoLogs:ie(k(),"received_client_credentials","preregistered-fallback","Pre-registered Client",de)}},ee={state:t,updateState:n,proceedToNextStep:async()=>{const y=k();n({isInitiatingAuth:!0});const B=Y=>{c?.(()=>{ee.proceedToNextStep()},Y)};try{switch(y.currentStep){case"idle":{const _=lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),T=js({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}),E={method:"POST",url:i,headers:_,body:T};n({currentStep:"request_without_token",serverUrl:i,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}case"request_without_token":if(!y.serverUrl)throw new Error("No server URL available");try{const _=await H(y.serverUrl,{method:"POST",headers:lt(p,{"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(js({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:1}))}),T={status:_.status,statusText:_.statusText,headers:_.headers,body:_.body},E=[...y.httpHistory||[]];if(E.length>0){const F=E[E.length-1];F.response=T,F.duration=Date.now()-(F.timestamp||Date.now())}const $=Is({status:_.status,statusText:_.statusText,wwwAuthenticateHeader:_.headers["www-authenticate"],serverMessage:_.body?.error?.message});if($.kind==="challenged"){const F=_.headers["www-authenticate"],V=gr(F),N=Kl(V.scope);let G=F?ie(y,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:F,...N&&N.length>0?{scope:N.join(" ")}:{},"Received from":y.serverUrl||"Unknown"}):y.infoLogs;$.specCompliant||(G=Ta(y,G,"received_401_unauthorized",T)),n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:F||void 0,challengedScopes:N,lastResponse:T,httpHistory:E,infoLogs:G,isInitiatingAuth:!1})}else if($.kind==="anonymous_allowed"){const F=ie(y,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});n({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:T,httpHistory:E,infoLogs:F,isInitiatingAuth:!1})}else throw n({lastResponse:T,httpHistory:E}),new Hr($.message,_.status)}catch(_){throw _ instanceof Hr?_:new Error(`Failed to request MCP server: ${_ instanceof Error?_.message:String(_)}`)}break;case"received_401_unauthorized":{const _=gr(y.wwwAuthenticateHeader);let T=f||_.resource_metadata;if(!T&&y.serverUrl&&(T=td(y.serverUrl)),!T)throw new Error("Could not determine resource metadata URL");const E={method:"GET",url:T,headers:lt(p,{})};n({currentStep:"request_resource_metadata",resourceMetadataUrl:T,lastRequest:E,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}case"request_resource_metadata":if(!y.serverUrl)throw new Error("No server URL available");const Y=[...y.httpHistory||[]];let le=Y.length>0&&Y[Y.length-1]?.step==="request_resource_metadata"&&!Y[Y.length-1]?.response?Y.pop():void 0;const de=[],Oe=async(_,T={})=>{const E=typeof _=="string"?_:_.toString(),$=Xl(i,E,p,zr(T.headers)),F=le?{...le,timestamp:Date.now(),request:{method:T.method||"GET",url:E,headers:$,body:T.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:T.method||"GET",url:E,headers:$,body:T.body}};le=void 0,de.push(F);try{const V=await H(E,{method:T.method||"GET",headers:$,body:T.body});F.response={status:V.status,statusText:V.statusText,headers:V.headers,body:V.body},F.duration=Date.now()-F.timestamp;const N={status:V.status,statusText:V.statusText,headers:V.headers},G=typeof V.body=="string"?V.body:JSON.stringify(V.body??{});return new Response(G,N)}catch(V){throw F.error=Ct(V),F.duration=Date.now()-F.timestamp,V}};try{const _=(f||gr(y.wwwAuthenticateHeader).resource_metadata)&&y.resourceMetadataUrl?{resourceMetadataUrl:y.resourceMetadataUrl}:void 0,T=await ba(y.serverUrl,_,Oe),E=[...Y,...de],$=de[de.length-1],F=Ql({authorizationServers:T.authorization_servers,fallbackServerUrl:i,protocolVersion:"2026-07-28"}),V=F.authorizationServerUrl;if(F.error&&O!=="observe"){n({resourceMetadata:T,resourceMetadataUrl:$?.request?.url||y.resourceMetadataUrl,lastRequest:$?.request,lastResponse:$?.response,httpHistory:E,error:F.error,isInitiatingAuth:!1});return}let N=y.infoLogs??[];F.error&&(N=ie({...k(),infoLogs:N},"received_resource_metadata","authorization-server-substituted","Derived: Authorization Server (not advertised)",{Finding:F.error,"Using instead":V}));const G=nd({state:y,fallbackServerUrl:i,prmResource:T.resource,enforcement:S,infoLogs:N}),J=G.resourceIndicator;N=G.infoLogs,n({currentStep:"received_resource_metadata",resourceMetadata:T,resourceIndicator:J,resourceMetadataUrl:$?.request?.url||y.resourceMetadataUrl,authorizationServerUrl:V,lastRequest:$?.request,lastResponse:$?.response,httpHistory:E,infoLogs:N,isInitiatingAuth:!1})}catch(_){const T=En([...Y,...de],Ct(_));throw n({lastResponse:de[de.length-1]?.response,httpHistory:T}),new Error(ya(_))}break;case"received_resource_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const Ie={method:"GET",url:Yh(y.authorizationServerUrl)[0],headers:at(p,{})};n({currentStep:"request_authorization_server_metadata",lastRequest:Ie,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:Ie}],isInitiatingAuth:!1}),B(50);return;case"request_authorization_server_metadata":if(!y.authorizationServerUrl)throw new Error("No authorization server URL available");const _e=Yh(y.authorizationServerUrl);let ge=null;const Je=[];let Xe={},Ce=null;for(const _ of _e)try{const T=at(p,{}),E=[...y.httpHistory||[]];E.length>0&&(E[E.length-1].request={method:"GET",url:_,headers:T}),n({lastRequest:{method:"GET",url:_,headers:T},httpHistory:E});const $=await H(_,{method:"GET",headers:at(p,{})});if($.ok){ge=$.body,Xe=$.headers,Ce=$,ge||Je.push({url:_,status:$.status});break}Je.push({url:_,status:$.status})}catch(T){Je.push({url:_,error:T});continue}if(!ge||!Ce)throw new Error(rd(Je));if(!ge.issuer)throw new Error(Pa);if(ge.issuer!==y.authorizationServerUrl){const _=eO({advertisedIssuer:ge.issuer,discoveryUrl:y.authorizationServerUrl,tokenEndpoint:ge.token_endpoint,registrationEndpoint:ge.registration_endpoint,allowPathScopedIssuer:w});if(!_.accepted)throw new Error(`Authorization server metadata \`issuer\` does not match the authorization server URL it was discovered from (expected "${y.authorizationServerUrl}", got "${ge.issuer}"). RFC 8414 §3.3 requires an exact match; refusing to continue.`+_.hint)}if(!ge.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!ge.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!ge.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const z={status:Ce.status,statusText:Ce.statusText,headers:Xe,body:ge},se=[...y.httpHistory||[]];if(se.length>0){const _=se[se.length-1];_.response=z,_.duration=Date.now()-(_.timestamp||Date.now())}const ae=ge.code_challenge_methods_supported||[],he=Dm(ae,"2026-07-28"),$e=typeof ge.client_id_metadata_document_supported=="boolean"?ge.client_id_metadata_document_supported:"false (not advertised, defaults to false per spec)";let we=ie(k(),"received_authorization_server_metadata","cimd-support","Derived: CIMD Support",{"CIMD Supported":$e});if(ge.issuer!==y.authorizationServerUrl&&(we=ie({...k(),infoLogs:we},"received_authorization_server_metadata","path-scoped-issuer","Path-scoped authorization server",{"Discovery URL":y.authorizationServerUrl,"Advertised issuer":ge.issuer,Note:'The advertised issuer is the same-origin root of the discovery URL. Accepted because "Path-scoped authorization server" is enabled for this server; strict RFC 8414 §3.3 conformance requires an exact issuer match, and strict MCP clients may refuse to connect.'},{level:"warning"})),he){if(m||O!=="observe"){n({lastResponse:z,httpHistory:se,infoLogs:we,error:he,isInitiatingAuth:!1});return}console.warn("Authorization server may not support S256 PKCE method. Supported methods:",ae),n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ge,lastResponse:z,httpHistory:se,infoLogs:we,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1})}else n({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:ge,lastResponse:z,httpHistory:se,infoLogs:we,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!y.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(R==="cimd"){if(y.authorizationServerMetadata.client_id_metadata_document_supported!==!0){n({error:"The authorization server does not support Client ID Metadata Documents (client_id_metadata_document_supported is not advertised in AS metadata). Try using 'dcr' or 'preregistered' registration strategy instead.",isInitiatingAuth:!1});return}n({currentStep:"cimd_prepare",clientId:X,isInitiatingAuth:!1}),B(800);return}else if(R==="preregistered"){const{clientId:_,clientSecret:T}=await u?.({serverName:s,serverUrl:i})??{};if(!_){n({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const E=oe(T),$={"Client ID":_,"Client Secret":T||g?"Configured":"Not provided (public client)","Token Auth Method":E,Note:"Using pre-registered client credentials from server config (skipped DCR)"},F=ie(k(),"received_client_credentials","dcr","Pre-registered Client",$);n({currentStep:"received_client_credentials",clientId:_,clientSecret:T||void 0,tokenEndpointAuthMethod:E,infoLogs:F,isInitiatingAuth:!1})}else if(y.authorizationServerMetadata.registration_endpoint){const _=y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported,T=Zr(I,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:_}),E=$a({registrationEndpoint:y.authorizationServerMetadata.registration_endpoint,redirectUri:C,dynamicRegistrationDefaults:{...K,application_type:K.application_type??LP(K.redirect_uris??[C])},scope:T,customHeaders:p}),$=ie(k(),"request_client_registration","dcr-deprecated","DCR is deprecated in 2026-07-28",{Note:"Dynamic Client Registration (RFC 7591) is deprecated as a registration mechanism in 2026-07-28 (PR #2858). It remains a compatibility fallback; prefer CIMD or a pre-registered client where the authorization server supports it."},{level:"warning"});n({currentStep:"request_client_registration",lastRequest:E,lastResponse:void 0,infoLogs:$,httpHistory:[...y.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:E}],isInitiatingAuth:!1}),B(50);return}else{if(m){n({error:Ca,isInitiatingAuth:!1});return}const _=await P("Authorization server did not advertise registration_endpoint; using pre-registered client credentials.");if(!_){n({error:Oa,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:_.clientId,clientSecret:_.clientSecret,tokenEndpointAuthMethod:_.tokenEndpointAuthMethod,infoLogs:_.infoLogs,error:void 0,isInitiatingAuth:!1})}break;case"request_client_registration":if(!y.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!y.lastRequest?.body)throw new Error("No client metadata in request");{const _=await xa({request:y.lastRequest,requestExecutor:a,httpHistory:y.httpHistory});if(_.status!=="registered"){if(n({lastResponse:_.response,httpHistory:_.httpHistory,error:_.error,isInitiatingAuth:!1}),m)return;const E=await P(_.fallbackNote);if(!E){n({error:_.errorWithFallbackHint,isInitiatingAuth:!1});return}n({currentStep:"received_client_credentials",clientId:E.clientId,clientSecret:E.clientSecret,tokenEndpointAuthMethod:E.tokenEndpointAuthMethod,infoLogs:E.infoLogs,error:void 0,isInitiatingAuth:!1});break}if(_.missingClientId){n({lastResponse:_.response,httpHistory:_.httpHistory,error:"Dynamic Client Registration response is missing a client_id.",isInitiatingAuth:!1});return}const T=ie(k(),"received_client_credentials","dcr","Dynamic Client Registration",_.infoLogData);n({currentStep:"received_client_credentials",clientId:_.credentials.clientId,clientSecret:_.credentials.clientSecret,tokenEndpointAuthMethod:Sa(_.clientInfo),lastResponse:_.response,httpHistory:_.httpHistory,infoLogs:T,error:void 0,isInitiatingAuth:!1})}break;case"cimd_prepare":n({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),B(800);return;case"cimd_fetch_request":try{const _={method:"GET",url:X,headers:zr(void 0)},T=Date.now(),E=await H(X,{method:"GET"});if(!E.ok)throw new Error(`CIMD endpoint returned HTTP ${E.status}`);const $={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body};n({currentStep:"cimd_metadata_response",lastRequest:_,lastResponse:$,httpHistory:[...y.httpHistory||[],{step:"cimd_fetch_request",timestamp:T,duration:Date.now()-T,request:_,response:$}],isInitiatingAuth:!1}),B(800);return}catch(_){n({error:`CIMD metadata fetch failed: ${_ instanceof Error?_.message:String(_)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const _=y.lastResponse?.body;if(!_||typeof _!="object")throw new Error("CIMD metadata document was not available");if(_.client_id!==X)throw new Error("CIMD client_id mismatch");const T=y.authorizationServerMetadata?.client_id_metadata_document_supported,E={"Client ID":X,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":_.client_name||"MCPJam","Redirect URIs":_.redirect_uris||[],"Token Auth Method":_.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};T?E["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":E["Server Support"]="⚠ Not advertised (attempting anyway)";const $=ie(k(),"received_client_credentials","cimd","Client ID Metadata Document",E);n({currentStep:"received_client_credentials",clientId:X,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:$,isInitiatingAuth:!1})}catch(_){n({error:`CIMD validation failed: ${_ instanceof Error?_.message:String(_)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const Se=Gr(43),ve=await Ra(Se),me=ie(k(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:ve,method:"S256",...q?{resource:ne()}:{resource:"(omitted — emulated client does not send RFC 8707 resource)"}});n({currentStep:"generate_pkce_parameters",codeVerifier:Se,codeChallenge:ve,codeChallengeMethod:"S256",...q?{}:{resourceIndicatorSuppressed:!0},state:Gr(16),recordedIssuer:k().authorizationServerMetadata?.issuer,infoLogs:me,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!y.authorizationServerMetadata?.authorization_endpoint||!y.clientId)throw new Error("Missing authorization endpoint or client ID");const Ee=new URL(y.authorizationServerMetadata.authorization_endpoint);Ee.searchParams.set("response_type","code"),Ee.searchParams.set("client_id",y.clientId),Ee.searchParams.set("redirect_uri",C),Ee.searchParams.set("code_challenge",y.codeChallenge||""),Ee.searchParams.set("code_challenge_method","S256"),Ee.searchParams.set("state",y.state||""),q&&Ee.searchParams.set("resource",ne());const Ge=Zr(I,{customScopes:d,challengedScopes:y.challengedScopes,supportedScopes:y.resourceMetadata?.scopes_supported||y.authorizationServerMetadata.scopes_supported});Ge&&Ee.searchParams.set("scope",Ge);const U=ie(k(),"authorization_request","auth-url","Authorization URL",{url:Ee.toString()});n({currentStep:"authorization_request",authorizationUrl:Ee.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,requestedScopes:Ge?Ge.split(/\s+/).filter(Boolean):void 0,infoLogs:U,isInitiatingAuth:!1});break;case"authorization_request":n({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":{if(!y.authorizationCode||y.authorizationCode.trim()===""){n({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const _=tO({recordedIssuer:y.recordedIssuer,returnedIss:y.authorizationResponseIss,issParameterSupported:void 0,enforcePresentIssMismatch:!0});if(!_.ok){n({error:_.reason,isInitiatingAuth:!1});return}const T=Br({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Wr(I,y.tokenEndpointAuthMethod)}),E={grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:C,...T.bodyParams};y.codeVerifier&&(E.code_verifier=y.codeVerifier),q&&(E.resource=ne());const $={method:"POST",url:y.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded",...T.headers},body:E};n({currentStep:"token_request",lastRequest:$,lastResponse:void 0,...q?{}:{resourceIndicatorSuppressed:!0},accessToken:void 0,refreshToken:void 0,httpHistory:[...y.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:$}],isInitiatingAuth:!1}),B(50);return}case"token_request":if(!y.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!y.authorizationCode)throw new Error("Missing authorization code");if(!y.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const _=Br({clientId:y.clientId,clientSecret:y.clientSecret,tokenEndpointAuthMethod:Wr(I,y.tokenEndpointAuthMethod)}),T=new URLSearchParams({grant_type:"authorization_code",code:y.authorizationCode,redirect_uri:C,code_verifier:y.codeVerifier||"",..._.bodyParams});q&&T.set("resource",ne());const E=await H(y.authorizationServerMetadata.token_endpoint,{method:"POST",headers:{...at(p,{"Content-Type":"application/x-www-form-urlencoded"}),..._.headers},body:T.toString()}),$={status:E.status,statusText:E.statusText,headers:E.headers,body:E.body},F=[...y.httpHistory||[]];if(F.length>0){const G=F[F.length-1];G.response=$,G.duration=Date.now()-(G.timestamp||Date.now())}if(!E.ok){n({lastResponse:$,httpHistory:F,authorizationCode:void 0,error:ka(E),isInitiatingAuth:!1});return}const V=E.body;let N=(k().infoLogs||[]).filter(G=>G.id!=="auth-code"&&G.id!=="oauth-tokens"&&G.id!=="token");if(y.authorizationCode&&(N=[...N,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:y.authorizationCode},timestamp:Date.now()}]),V.access_token){const G={access_token:V.access_token};V.refresh_token&&(G.refresh_token=V.refresh_token),N=[...N,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:G,timestamp:Date.now()}]}if(V.access_token){const G=Vr(V.access_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${Ne(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${Ne(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${Ne(J.nbf)})`);const Vt={...J};if(J.aud){const Qr=y.serverUrl,wi=(Array.isArray(J.aud)?J.aud:[J.aud]).some(Ka=>Ka===Qr);Vt._validation={expected_audience:Qr,audience_matches:wi,note:wi?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Vt._validation={note:"⚠ No audience claim found - server should validate token binding"};N=[...N,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Vt,timestamp:Date.now()}]}}if(V.id_token){const G=Vr(V.id_token);if(G){const J={...G};J.exp&&(J.exp=`${J.exp} (${Ne(J.exp)})`),J.iat&&(J.iat=`${J.iat} (${Ne(J.iat)})`),J.nbf&&(J.nbf=`${J.nbf} (${Ne(J.nbf)})`),J.auth_time&&(J.auth_time=`${J.auth_time} (${Ne(J.auth_time)})`),J._note="OIDC ID Token - Used for user identity verification",N=[...N,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:J,timestamp:Date.now()}]}}n({currentStep:"received_access_token",accessToken:V.access_token,refreshToken:V.refresh_token,tokenType:V.token_type||"Bearer",expiresIn:V.expires_in,lastResponse:$,httpHistory:F,infoLogs:N,error:void 0,isInitiatingAuth:!1})}catch(_){const T={status:0,statusText:"Network Error",headers:{},body:{error:_ instanceof Error?_.message:String(_)}},E=[...y.httpHistory||[]];if(E.length>0){const $=E[E.length-1];$.response=T,$.duration=Date.now()-($.timestamp||Date.now())}n({lastResponse:T,httpHistory:E,error:`Token exchange failed: ${_ instanceof Error?_.message:String(_)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");const Z={method:"POST",url:y.serverUrl,headers:{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"},body:js({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2})},Q=ie(k(),"authenticated_mcp_request","authenticated-verify","Authenticated MCP Verify Request (tools/list)",{Request:"Stateless tools/list with OAuth bearer token","Protocol Version":"2026-07-28",Client:"MCPJam Inspector v1.0.0",Endpoint:y.serverUrl});n({currentStep:"authenticated_mcp_request",lastRequest:Z,lastResponse:void 0,httpHistory:[...y.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Z}],infoLogs:Q,isInitiatingAuth:!1}),B(50);return;case"authenticated_mcp_request":if(!y.serverUrl||!y.accessToken)throw new Error("Missing server URL or access token");try{const _=await H(y.serverUrl,{method:"POST",headers:lt(p,{Authorization:`Bearer ${y.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream","MCP-Protocol-Version":L,"Mcp-Method":"tools/list"}),body:JSON.stringify(js({protocolVersion:L,authMode:v,clientName:"MCPJam Inspector",clientVersion:"1.0.0",id:2}))}),T={status:_.status,statusText:_.statusText,headers:_.headers,body:_.body},E=[...y.httpHistory||[]];if(E.length>0){const G=E[E.length-1];G.response=T,G.duration=Date.now()-(G.timestamp||Date.now())}if(!_.ok){n({lastResponse:T,httpHistory:E,error:Ea(_),isInitiatingAuth:!1});return}let $=k().infoLogs||[];const F=_.headers["content-type"]||"",V=F.includes("text/event-stream");let N=null;if(V&&_.body?.transport==="sse"?N=_.body.mcpResponse:N=_.body,V&&N?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":N.result.protocolVersion};N.result.serverInfo&&(G["Server Name"]=N.result.serverInfo.name,G["Server Version"]=N.result.serverInfo.version),N.result.capabilities&&(G.Capabilities=N.result.capabilities),$=ie(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(V)$=ie(k(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":F,Note:"Server returned streaming response. tools/list verify response delivered via SSE stream.",Events:_.body?.events?`${_.body.events.length} events parsed`:"No events parsed"});else if(N?.result?.protocolVersion){const G={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":N.result.protocolVersion};N.result.serverInfo&&(G["Server Name"]=N.result.serverInfo.name,G["Server Version"]=N.result.serverInfo.version),N.result.capabilities&&(G.Capabilities=N.result.capabilities),$=ie(k(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",G)}else if(N?.result){const G=Array.isArray(N.result.tools)?N.result.tools.length:void 0;$=ie(k(),"authenticated_mcp_request","mcp-token-verified","Access token verified (tools/list)",{Transport:"Streamable HTTP","Response Format":"JSON",Result:"Bearer token accepted; tools/list succeeded",...G!==void 0?{"Tools listed":G}:{}})}n({currentStep:"complete",lastResponse:T,httpHistory:E,infoLogs:$,error:void 0,isInitiatingAuth:!1})}catch(_){const T={status:0,statusText:"Network Error",headers:{},body:{error:_ instanceof Error?_.message:String(_)}},E=[...y.httpHistory||[]];if(E.length>0){const $=E[E.length-1];$.response=T,$.duration=Date.now()-($.timestamp||Date.now())}n({lastResponse:T,httpHistory:E,error:`Authenticated MCP request failed: ${_ instanceof Error?_.message:String(_)}`,isInitiatingAuth:!1})}break;case"complete":n({isInitiatingAuth:!1});break;default:n({isInitiatingAuth:!1})}}catch(Y){const le=k(),de=Ct(Y),Oe=ie(le,le.currentStep,`error-${le.currentStep}-${Date.now()}`,"Step failed",{step:le.currentStep,request:le.lastRequest,response:le.lastResponse,error:de},{level:"error",error:de}),Ie=En(le.httpHistory,de),_e={error:de.message,infoLogs:Oe,isInitiatingAuth:!1};Ie&&(_e.httpHistory=Ie),n(_e)}},startGuidedFlow:async()=>{n({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{n(Ia())}};return ee};function Oz({protocolVersion:e,registrationStrategy:t,flowState:r}){switch(e){case"2025-03-26":return zP(r,t==="cimd"?"dcr":t);case"2025-06-18":return HP(r,t==="cimd"?"dcr":t);case"2025-11-25":return GP(r,t);case"2026-07-28":return YP(r,t);default:throw new Error(`Unknown protocol version: ${e}`)}}function Da(e){return e.replace(/^\[|\]$/g,"").trim().toLowerCase().replace(/\.+$/,"")}function Fm(e){const t=e.split(".").map(s=>parseInt(s,10));if(t.length!==4||t.some(s=>!Number.isInteger(s)||s<0||s>255))return!0;const[r,n,i]=t;return r===0||r===10||r===100&&n>=64&&n<=127||r===127||r===169&&n===254||r===172&&n>=16&&n<=31||r===192&&n===0&&i===0||r===192&&n===0&&i===2||r===192&&n===88&&i===99||r===192&&n===168||r===198&&(n===18||n===19)||r===198&&n===51&&i===100||r===203&&n===0&&i===113||r>=224&&r<=239||r>=240}function qm(e){let t=e.trim().toLowerCase().split("%")[0];t.startsWith("[")&&t.endsWith("]")&&(t=t.slice(1,-1));const r=t.match(/^(.*:)(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(r){const o=[r[2],r[3],r[4],r[5]].map(a=>parseInt(a,10));if(o.some(a=>a<0||a>255))return null;t=`${r[1]}${(o[0]<<8|o[1]).toString(16)}:${(o[2]<<8|o[3]).toString(16)}`}const n=o=>{if(o==="")return[];const a=[];for(const c of o.split(":")){if(!/^[0-9a-f]{1,4}$/.test(c))return null;a.push(parseInt(c,16))}return a},i=t.split("::");if(i.length>2)return null;if(i.length===2){const o=n(i[0]),a=n(i[1]);if(!o||!a)return null;const c=8-o.length-a.length;return c<1?null:[...o,...Array(c).fill(0),...a]}const s=n(t);return s&&s.length===8?s:null}function tp(e,t){return Fm(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function nO(e){const t=qm(e);if(!t||t.slice(0,6).every(n=>n===0)&&t[6]===0&&(t[7]===0||t[7]===1))return!0;const r=t[0]>>8;return(r&254)===252||t[0]>=65152&&t[0]<=65215||r===255||t[0]===8193&&t[1]===3512||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0?!0:t[0]===100&&t[1]===65435?t[2]===1?!0:tp(t[6],t[7]):t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?tp(t[6],t[7]):!1}function iO(e){const t=Da(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?Fm(t):t.includes(":")?nO(t):!1}function sO(e){const t=Da(e);return t==="localhost"||t.endsWith(".localhost")?!0:iO(t)}function oO(e){const t=Da(e);return/^\d+\.\d+\.\d+\.\d+$/.test(t)?jm(t):t.includes(":")?aO(t):!1}function jm(e){const t=e.split(".").map(o=>parseInt(o,10));if(t.length!==4||t.some(o=>!Number.isInteger(o)||o<0||o>255))return!0;const[r,n,i,s]=t;return r===0||r===169&&n===254||r===100&&n===100&&i===100&&s===200||r>=224&&r<=239||r>=240}function rp(e,t){return jm(`${e>>8}.${e&255}.${t>>8}.${t&255}`)}function aO(e){const t=qm(e);return t?t.slice(0,6).every(r=>r===0)&&t[6]===0&&(t[7]===0||t[7]===1)?t[7]===0:t[0]>=65152&&t[0]<=65215||t[0]>>8===255||t[0]===256&&t[1]===0&&t[2]===0&&t[3]===0||t[0]===64768&&t[1]===3778&&t[2]===0&&t[3]===0&&t[4]===0&&t[5]===0&&t[6]===0&&t[7]===596?!0:t[0]===100&&t[1]===65435||t[0]===0&&t[1]===0&&t[2]===0&&t[3]===0&&t[4]===0&&(t[5]===65535||t[5]===0)?rp(t[6],t[7]):!1:!0}var cO=new Set(["metadata.google.internal","metadata.goog"]);function uO(e){const t=Da(e);return cO.has(t)?!0:oO(t)}function Hm(e){const t=e.replace(/^\[|\]$/g,"").toLowerCase(),r=t.match(/^::(?:ffff:)?(\d{1,3})\.\d{1,3}\.\d{1,3}\.\d{1,3}$/);if(r)return parseInt(r[1],10)===127;const n=t.match(/^::(?:ffff:)?([0-9a-f]{1,4}):[0-9a-f]{1,4}$/);return n?parseInt(n[1],16)>>8===127:!1}function Cz(e){if(!e)return!1;try{const t=new URL(e).hostname;return Na(t)||Hm(t)}catch{return!1}}var Ii=class extends Error{url;reason;constructor(e,t,r){super(r),this.name="OAuthOutboundUrlBlockedError",this.url=e,this.reason=t}};function lO(e,t={}){let r;try{r=new URL(e)}catch{throw new Ii(e,"invalid-url","Outbound OAuth fetch URL is not a valid absolute URL")}if(r.protocol!=="https:"&&r.protocol!=="http:")throw new Ii(e,"invalid-scheme",`Outbound OAuth fetch must be http(s); got "${r.protocol}"`);const n=r.hostname;if(uO(n))throw new Ii(e,"private-host",`Refusing outbound OAuth fetch to link-local or cloud-metadata host "${n}"`);if(t.allowPrivateNetwork===!0)return r;if(Na(n)||Hm(n)){if(t.allowLoopback===!0)return r;throw new Ii(e,"private-host",`Refusing outbound OAuth fetch to loopback host "${n}" (no loopback opt-in)`)}if(sO(n))throw new Ii(e,"private-host",`Refusing outbound OAuth fetch to private/reserved host "${n}"`);return r}var dO=class extends Error{field;constructor(e,t){super(`OAuth response from ${t} carried a redacted \`${e}\`. Trace redaction was applied to data the OAuth flow consumes; a redaction sentinel is a non-empty string, so it would be sent upstream as a credential and rejected as invalid. Redaction belongs to the trace projection layer only.`),this.name="OAuthRedactedCredentialError",this.field=e}},hO=["access_token","refresh_token","id_token","client_secret"],pO=[/^\[redacted\]$/,/^[\s\S]{4}\.\.\.\[redacted\]\.\.\.[\s\S]{2}$/];function fO(e){try{const t=new URL(e.url);return`${t.origin}${t.pathname}`}catch{return"the authorization server"}}function vO(e,t){const r=e?.body;if(!r||typeof r!="object"||Array.isArray(r))return e;const n=r;for(const i of hO){const s=n[i];if(typeof s=="string"&&pO.some(o=>o.test(s)))throw new dO(i,fO(t))}return e}function gO(e){const{protocolVersion:t,allowLoopbackMetadataFetch:r,allowPrivateMetadataFetch:n,...i}=e,s=r??!1,o=n??!1,c={...i,requestExecutor:async u=>(lO(u.url,{allowLoopback:s,allowPrivateNetwork:o}),vO(await i.requestExecutor(u),u)),customHeaders:DP(i.customHeaders,i.emulation)};switch(t){case"2025-03-26":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-03-26 protocol. Use 'dcr' or 'preregistered' instead.");return FP(c);case"2025-06-18":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-06-18 protocol. Use 'dcr' or 'preregistered' instead.");return BP(c);case"2025-11-25":return ZP(c);case"2026-07-28":return rO(c);default:throw new Error(`Unknown protocol version: ${t}`)}}function $z(e){switch(e){case"2025-03-26":return"dcr";case"2025-06-18":return"dcr";case"2025-11-25":return"cimd";case"2026-07-28":return"cimd";default:return"dcr"}}function xz(e){switch(e){case"2025-03-26":return["dcr","preregistered"];case"2025-06-18":return["dcr","preregistered"];case"2025-11-25":return["cimd","dcr","preregistered"];case"2026-07-28":return["cimd","dcr","preregistered"];default:return["dcr","preregistered"]}}var Mz={"2025-03-26":{label:qs("2025-03-26"),description:"Original MCP OAuth specification with direct discovery",features:["Dynamic Client Registration (DCR) SHOULD be supported","Direct RFC8414 discovery from MCP server base URL","Fallback to default endpoints (/authorize, /token, /register)","PKCE is REQUIRED for all clients","No Protected Resource Metadata (RFC9728)"]},"2025-06-18":{label:qs("2025-06-18"),description:"MCP OAuth specification with resource metadata",features:["Dynamic Client Registration (DCR) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 discovery ONLY (no OIDC) with root fallback","PKCE recommended but not strictly enforced"]},"2025-11-25":{label:qs("2025-11-25"),description:"MCP OAuth specification with CIMD support",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","Enhanced security with URL-based client IDs"]},"2026-07-28":{label:qs("2026-07-28"),description:"Newest MCP OAuth specification: 2025-11-25 discovery plus OIDC application_type",features:["Client ID Metadata Documents (CIMD) SHOULD be supported","Protected Resource Metadata (RFC9728) required","RFC8414 OR OIDC discovery without root fallback","PKCE strictly required and enforced","SEP-837: OIDC application_type sent on Dynamic Client Registration"]}},mO=["idle","request_without_token","received_401_unauthorized","discovery_start","request_resource_metadata","received_resource_metadata","request_authorization_server_metadata","received_authorization_server_metadata","cimd_prepare","cimd_fetch_request","cimd_metadata_response","request_client_registration","received_client_credentials","generate_pkce_parameters","authorization_request","received_authorization_code","token_request","received_access_token","authenticated_mcp_request","complete","verify_list_tools","verify_call_tool"],_O={idle:{title:"Idle",summary:"The OAuth flow is ready to start.",teachableMoments:["Review your server selection and OAuth configuration before starting."]},request_without_token:{title:"Initial MCP Request",summary:"The client sends an unauthenticated initialize request to discover whether OAuth is required.",teachableMoments:["OAuth flows usually begin with a protected resource request that deliberately lacks credentials.","The response determines which discovery path the client must follow."]},received_401_unauthorized:{title:"401 Unauthorized Received",summary:"The MCP server indicates OAuth is required and often provides discovery hints in WWW-Authenticate.",teachableMoments:["Look for the resource metadata URL or realm in the header to understand where discovery begins."],tips:["If you get 200 instead, the server may allow optional OAuth or anonymous access."]},discovery_start:{title:"Start Discovery",summary:"The client derives authorization server endpoints from the MCP server URL.",teachableMoments:["Legacy servers rely on RFC8414 discovery directly from the MCP base URL.","Understanding how fallback URLs are constructed helps debug missing metadata issues."]},request_resource_metadata:{title:"Request Resource Metadata",summary:"The client requests RFC9728 resource metadata to learn which authorization server to use.",teachableMoments:["Protected resource metadata links the resource to one or more authorization servers.","If this step fails, check the MCP server's well-known configuration and headers."]},received_resource_metadata:{title:"Resource Metadata Received",summary:"The response describes supported authorization servers, scopes, and bearer method details.",teachableMoments:["Validate that the authorization server URL looks correct for the environment you're targeting."]},request_authorization_server_metadata:{title:"Request Authorization Server Metadata",summary:"The client requests the authorization server's well-known metadata endpoint (RFC8414 or OIDC).",teachableMoments:["Different protocol versions prioritize different discovery strategies (path insertion, appending, etc.).","Failure here often points to misconfigured issuer URLs or CORS/proxy issues."]},received_authorization_server_metadata:{title:"Authorization Server Metadata Received",summary:"Inspector validates the authorization, token, and optional registration endpoints.",teachableMoments:["Confirm PKCE methods include S256 for modern flows.","Check the available scopes and grant types to ensure the server supports what you need."]},cimd_prepare:{title:"Prepare CIMD",summary:"Draft protocol: the client prepares to use a Client ID Metadata Document (CIMD).",teachableMoments:["CIMD replaces static client IDs with an HTTPS URL that hosts client metadata."]},cimd_fetch_request:{title:"Authorization Server Fetches CIMD",summary:"The authorization server fetches the client's metadata document over HTTPS.",teachableMoments:["Monitor this step to diagnose TLS or hosting issues with your metadata document."]},cimd_metadata_response:{title:"CIMD Validated",summary:"The client confirms the authorization server successfully read the client metadata document.",teachableMoments:["Ensure redirect URIs declared in the document match the environment you're testing."]},request_client_registration:{title:"Request Dynamic Client Registration",summary:"The client submits metadata to register a public client with the authorization server.",teachableMoments:["Dynamic registration is optional in draft flows but required in earlier specs unless you pre-register.","Watch for HTTP 4xx responses that indicate validation failures."]},received_client_credentials:{title:"Client Credentials Received",summary:"The client stores client_id (and optionally client_secret) for the remainder of the flow.",teachableMoments:["Keep an eye on whether the server returned a secret; public clients should use PKCE instead."]},generate_pkce_parameters:{title:"Generate PKCE Parameters",summary:"The client creates a code verifier and challenge to protect the authorization code exchange.",teachableMoments:["PKCE S256 is required in draft specs and strongly recommended everywhere else."]},authorization_request:{title:"Authorization Request Ready",summary:"The client composes the authorization URL and waits for the user to approve access.",teachableMoments:["Inspect the URL to ensure scopes and redirect URI are what you expect."]},received_authorization_code:{title:"Authorization Code Received",summary:"The user completed consent and the client captured the returned authorization code.",teachableMoments:["State mismatches here usually indicate multiple concurrent authorizations or stale popups."]},token_request:{title:"Request Tokens with Authorization Code",summary:"The client calls the token endpoint with the authorization code and PKCE verifier.",teachableMoments:["Token endpoint errors often reveal scope or client configuration problems."]},received_access_token:{title:"Tokens Received",summary:"The client stores access and refresh tokens for subsequent authenticated MCP requests.",teachableMoments:["Check the token type and expiry to confirm the server honored offline access or refresh tokens."]},authenticated_mcp_request:{title:"Authenticated MCP Request",summary:"The client retries the MCP initialize call with the freshly issued access token.",teachableMoments:["Use this step to validate that MCP servers accept OAuth tokens and return capabilities."]},complete:{title:"Flow Complete",summary:"The client verified the server with OAuth credentials and recorded the final response.",teachableMoments:["Continue exploring with authenticated requests or reset to run the flow again."]},verify_list_tools:{title:"Verify: List Tools",summary:"Connect to the MCP server with the obtained token and list available tools.",teachableMoments:["This step confirms the OAuth token is actually usable for MCP operations."]},verify_call_tool:{title:"Verify: Call Tool",summary:"Execute a tool on the MCP server to confirm end-to-end functionality.",teachableMoments:["Calling a tool validates not just authentication but also authorization scopes."]}};function np(e){return _O[e]??{title:e,summary:"No additional information available for this step."}}function Rr(e){const t=mO.indexOf(e);return t===-1?Number.MAX_SAFE_INTEGER:t}function yO(e){return JSON.parse(JSON.stringify(e))}function bO(e){return{...e,request:{...e.request,url:Bl(e.request.url),headers:zh(e.request.headers),body:Qt(e.request.body)},...e.response?{response:{...e.response,headers:zh(e.response.headers),body:Qt(e.response.body)}}:{},...e.error?{error:{...e.error,...e.error.message?{message:Dr(e.error.message)}:{},details:Qt(e.error.details)}}:{}}}function wO(...e){const t=e.filter(r=>r!=null);if(t.length!==0)return Math.max(...t)}function SO(){return{syntheticStepTimestamps:{},lastSyntheticTimestamp:0}}function EO(e,t,r){if(!e)return r;const n=e.syntheticStepTimestamps[t];return typeof n=="number"?n:r}function ip(e,t,r,n){const i=EO(t,r,n),s=e.get(r);if(s)return s.startedAt=Math.min(s.startedAt,i),s.completedAt=Math.max(s.completedAt??i,n),s;const o={step:r,startedAt:i,completedAt:n};return e.set(r,o),o}function en(e,t,r,n,i,s){if(!n||e.has(r))return;let o=Date.now();t&&(o=Math.max(o,t.lastSyntheticTimestamp+1),t.syntheticStepTimestamps[r]=o,t.lastSyntheticTimestamp=o);const a=i==null?void 0:s?Qt(i):JSON.parse(JSON.stringify(i));e.set(r,{step:r,startedAt:o,completedAt:o,details:a})}function kO(e,t){if(e!==t.currentStep)return!1;switch(e){case"authorization_request":return!!t.authorizationUrl;case"received_authorization_code":return!!t.authorizationCode;case"received_access_token":return!!t.accessToken;case"complete":return t.currentStep==="complete";default:return!1}}function IO(e){if(!(!e||e.status<400))return Mm(e.body)??`HTTP ${e.status} ${e.statusText}`}function AO(e){if(e.error?.message)return e.error.message;if(e.step==="request_client_registration")return IO(e.response)}function sp(e){return!e.error||!e.clientId||Rr(e.currentStep)<=Rr("request_client_registration")?!1:e.error.startsWith("Dynamic Client Registration failed")||e.error.startsWith("Client registration failed:")}function TO(e){const{state:t,context:r,sanitize:n=!0}=e,i=t.error?n?Dr(t.error):t.error:void 0,s={version:1,currentStep:t.currentStep,steps:[],httpHistory:(t.httpHistory??[]).map(l=>n?bO(l):yO(l)),...i?{error:i}:{}},o=Rr(t.currentStep),a=new Map;for(const l of t.httpHistory??[]){const h=ip(a,r,l.step,l.timestamp);h.details||(h.details={request:n?Qt(l.request):l.request,...l.response?{response:n?Qt(l.response):l.response}:{}});const d=AO(l);d&&(h.error=Au(n?Dr(d):d.slice(0,500)))}for(const l of t.infoLogs??[]){const h=ip(a,r,l.step,l.timestamp);h.message=l.label;const d=n?Qt(l.data):l.data;d&&typeof d=="object"&&d!==null&&!Array.isArray(d)&&(h.details=d),l.error?.message&&(h.error=n?Dr(l.error.message):l.error.message)}const c=Math.max(Date.now(),...(t.httpHistory??[]).map(l=>l.timestamp),...(t.infoLogs??[]).map(l=>l.timestamp),r?.lastSyntheticTimestamp??0);r&&(r.lastSyntheticTimestamp=Math.max(r.lastSyntheticTimestamp,c)),en(a,r,"received_client_credentials",!!t.clientId,{clientId:t.clientId},n),en(a,r,"generate_pkce_parameters",!!t.codeVerifier,{codeVerifier:t.codeVerifier},n),en(a,r,"authorization_request",!!t.authorizationUrl,{authorizationUrl:t.authorizationUrl},n),en(a,r,"received_authorization_code",!!t.authorizationCode,t.authorizationCode?{code:t.authorizationCode}:void 0,n),en(a,r,"received_access_token",!!t.accessToken,{tokenType:t.tokenType,expiresIn:t.expiresIn},n),en(a,r,"complete",t.currentStep==="complete",void 0,n);const u=a.get("request_client_registration");if(u?.error&&Rr(t.currentStep)>Rr("request_client_registration")&&t.clientId&&(u.recovered=!0,u.recoveredAt=wO(u.recoveredAt,u.completedAt,a.get("received_client_credentials")?.startedAt),u.recoveryMessage="Using pre-registered client credentials after registration failed."),t.error&&!sp(t)&&!a.has(t.currentStep)){en(a,r,t.currentStep,!0,void 0,n);const l=a.get(t.currentStep);l&&(l.error=i)}return s.steps=Array.from(a.values()).sort((l,h)=>l.startedAt-h.startedAt||Rr(l.step)-Rr(h.step)).map(l=>{const h=Rr(l.step),d=l.step===t.currentStep&&!!t.error&&!sp(t),p=l.error??(d?i:void 0),f=l.recovered?"success":p?"error":h<o||t.currentStep==="complete"||kO(l.step,t)?"success":l.step===t.currentStep?"pending":"success";return{step:l.step,title:np(l.step).title,status:f,message:l.message??np(l.step).summary,...p?{error:p}:{},...l.details?{details:l.details}:{},...l.recovered?{recovered:!0}:{},...l.recoveredAt?{recoveredAt:l.recoveredAt}:{},...l.recoveryMessage?{recoveryMessage:l.recoveryMessage}:{},startedAt:l.startedAt,completedAt:f==="pending"?void 0:l.completedAt}}),s}function Hs(e){return{message:e instanceof Error?e.message:String(e)}}async function Lz(e){const{maxSteps:t=40,onAuthorizationRequest:r,onTraceUpdate:n,getState:i,sanitizeTrace:s=!0,...o}=e;let a=e.state;const c=SO(),u=i??(()=>a),l=(v,g=u(),m=c)=>{n?.({trace:TO({state:g,context:m,sanitize:s}),state:g,reason:v})},h=v=>{a={...a,...v},e.updateState(v),l("state_update",a)},d=gO({...o,getState:u,updateState:h});let p=0;for(;u().currentStep!=="complete"&&p<t;){p+=1;const v=u();if(v.currentStep==="authorization_request"){if(!v.authorizationUrl)return h({error:"Authorization URL was not generated."}),{completed:!1,redirected:!1,state:u(),error:{message:"Authorization URL was not generated."}};if(!r)return h({error:"Authorization request requires an authorization handler."}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:u(),error:{message:"Authorization request requires an authorization handler."}};try{const w=await r({authorizationUrl:v.authorizationUrl,state:v});if(w.type==="redirect")return l("redirect"),{completed:!1,redirected:!0,authorizationUrl:v.authorizationUrl,state:u()};h({currentStep:"received_authorization_code",authorizationCode:w.authorizationCode,error:void 0});continue}catch(w){return h({error:Hs(w).message}),{completed:!1,redirected:!1,authorizationUrl:v.authorizationUrl,state:u(),error:Hs(w)}}}const g=v.currentStep;try{await d.proceedToNextStep()}catch(w){return u().error?l("error"):h({error:Hs(w).message}),{completed:!1,redirected:!1,state:u(),error:Hs(w)}}const m=u();if(m.currentStep===g)return m.error?l("error",m):h({error:`Step ${g} did not advance.`}),{completed:!1,redirected:!1,state:u(),error:{message:u().error||`Step ${g} did not advance.`}}}const f=u();return p>=t&&f.currentStep!=="complete"?(h({error:"OAuth login exceeded its step guard."}),{completed:!1,redirected:!1,state:u(),error:{message:"OAuth login exceeded its step guard."}}):(l(f.currentStep==="complete"?"complete":"state_update"),{completed:f.currentStep==="complete",redirected:!1,authorizationUrl:f.authorizationUrl,state:f,...f.error?{error:{message:f.error}}:{}})}function Nz(e){const t=CO(e.endsWith(" Configure a pre-registered client or enable DCR on the authorization server.")?e.slice(0,-(lo.length+1)):e).slice(0,PO);return mP(t)??LO(t)}var RO=160,PO=4e3,OO=46;function CO(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===OO;)t-=1;return t===e.length?e:e.slice(0,t)}var $O=[[/(\bCould not resolve (?:[a-z-]{1,63} ){0,8}?)[^\s"'();]{1,253}(?=[)"',]*(?:;|$))/g,"$1<host>"],[/[^\s"'()]{1,253}(?= resolves to a private or reserved address\b)/g,"<host>"],[/(\bhost \()[^\s)]{1,253}(\))/g,"$1<host>$2"],[/(\bconnection to ")[^\s"]{1,253}(")/g,"$1<host>$2"]],xO=/(?<![\w:.])(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}(?![\w:])/gi,MO=/\b(?:\d{1,3}\.){3}\d{1,3}\b/g;function LO(e){return $O.reduce((t,[r,n])=>t.replace(r,n),e.replace(/\bhttps?:\/\/[^\s"'<>)]+/g,"<url>")).replace(xO,"<ip>").replace(MO,"<ip>").replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi,"<id>").replace(/\b[A-Za-z0-9_-]{16,}\b/g,t=>/\d/.test(t)?"<id>":t).replace(/\s+/g," ").trim().slice(0,RO)}var Dz=["server-initialize","ping","logging-set-level","completion-complete","capabilities-consistent","tools-list","tools-input-schemas-valid","tools-x-mcp-header-declarations-valid","prompts-list","resources-list","protocol-invalid-method-error","localhost-host-rebinding-rejected","localhost-host-valid-accepted","server-sse-polling-session","server-accepts-multiple-post-streams","server-sse-streams-functional","notification-post-accepted","get-stream-or-405","session-id-visible-ascii","post-response-content-type","modern-client-handshake","modern-server-discover","modern-result-type-present","modern-cacheable-result-hints","modern-cache-hint-coverage","modern-cache-hint-values-valid","modern-cache-scope-stable-across-pages","modern-protocol-version-header-mismatch","modern-method-header-mismatch","modern-name-header-mismatch","modern-unsupported-version-error","modern-missing-method-header-rejected","modern-header-names-case-insensitive","modern-undeclared-capability-error","modern-no-session-id","modern-removed-methods-not-found","modern-resource-not-found-invalid-params","modern-resource-read-no-empty-contents","modern-tool-output-schema-conformant","modern-logs-require-log-level","modern-subscription-ack-precedes-notifications","modern-subscription-filter-and-tagging","modern-subscription-graceful-close","wire-schema-valid"],NO={"2025-03-26":"legacy","2025-06-18":"legacy","2025-11-25":"legacy","2026-07-28":"modern"},zz=Object.keys(NO),Uz={"server-initialize":["legacy"],ping:["legacy"],"capabilities-consistent":["legacy","modern"],"server-sse-polling-session":["legacy"],"server-accepts-multiple-post-streams":["legacy"],"server-sse-streams-functional":["legacy"],"notification-post-accepted":["legacy"],"get-stream-or-405":["legacy"],"session-id-visible-ascii":["legacy"],"post-response-content-type":["legacy","modern"],"localhost-host-rebinding-rejected":["legacy"],"localhost-host-valid-accepted":["legacy"],"tools-list":["legacy","modern"],"tools-input-schemas-valid":["legacy","modern"],"tools-x-mcp-header-declarations-valid":["modern"],"prompts-list":["legacy","modern"],"resources-list":["legacy","modern"],"logging-set-level":["legacy","modern"],"completion-complete":["legacy","modern"],"protocol-invalid-method-error":["legacy","modern"],"modern-client-handshake":["modern"],"modern-server-discover":["modern"],"modern-result-type-present":["modern"],"modern-cacheable-result-hints":["modern"],"modern-cache-hint-coverage":["modern"],"modern-cache-hint-values-valid":["modern"],"modern-cache-scope-stable-across-pages":["modern"],"modern-protocol-version-header-mismatch":["modern"],"modern-method-header-mismatch":["modern"],"modern-name-header-mismatch":["modern"],"modern-unsupported-version-error":["modern"],"modern-missing-method-header-rejected":["modern"],"modern-header-names-case-insensitive":["modern"],"modern-undeclared-capability-error":["modern"],"modern-no-session-id":["modern"],"modern-removed-methods-not-found":["modern"],"modern-resource-not-found-invalid-params":["modern"],"modern-resource-read-no-empty-contents":["modern"],"modern-tool-output-schema-conformant":["modern"],"modern-logs-require-log-level":["modern"],"modern-subscription-ack-precedes-notifications":["modern"],"modern-subscription-filter-and-tagging":["modern"],"modern-subscription-graceful-close":["modern"],"wire-schema-valid":["legacy","modern"]};function DO(){return"8.21.0"}var Fz=DO();function Bm(e,t){if(!t||t.pendingCheckIds.length===0)return{scored:[...e],pending:[]};const r=new Set(t.pendingCheckIds),n=[],i=[];for(const s of e)(r.has(s.id)?i:n).push(s);return{scored:n,pending:i}}var zO=95,Vm=5,UO={should:2,may:1};function FO(e){const t=e.reduce((r,n)=>r+UO[n.tier],0);return Math.min(t,Vm)}function id(e,t,r,n){const i=e.passed+e.failed+e.couldNotRun,s=FO(t);let o=null;if(i>0){const a=zO*e.passed/i,c=Vm-s;o=Math.round(a+c),r!=="passed"?o=Math.min(o,94):t.length>0&&(o=Math.min(o,99))}return{score:o,outcome:r,applicable:i,...e,pending:e.pending??0,advisories:t,advicePointsLost:s,...n!==void 0?{protocolVersion:n}:{}}}function sd(e,t=[],r,n){const{scored:i,pending:s}=Bm(e,n),o={passed:i.filter(c=>c.status==="passed").length,failed:i.filter(c=>c.status==="failed").length,couldNotRun:i.filter(bv).length,notApplicable:i.filter(fb).length,pending:s.length},{outcome:a}=vb(i);return id(o,t,a,r)}function od(e){const t={passed:Ai(e,a=>a.passed),failed:Ai(e,a=>a.failed),couldNotRun:Ai(e,a=>a.couldNotRun),notApplicable:Ai(e,a=>a.notApplicable),pending:Ai(e,a=>a.pending??0)},r=e.flatMap(a=>a.advisories??[]),n=e.map(a=>a.outcome),i=n.includes("failed")?"failed":n.includes("incomplete")?"incomplete":"passed",s=e.filter(a=>a.applicable>0),o=new Set(s.map(a=>a.protocolVersion));return id(t,r,i,s.length>0&&o.size===1?[...o][0]:void 0)}function Ai(e,t){return e.reduce((r,n)=>r+t(n),0)}function qz(e){if(e.score===null)return`not scored — 0 applicable checks (${e.notApplicable} not applicable)`;const t=[`${e.passed}/${e.applicable} applicable checks passed`];e.failed>0&&t.push(`${e.failed} failed`),e.couldNotRun>0&&t.push(`${e.couldNotRun} could not run`),e.advisories.length>0&&t.push(`${e.advisories.length} advisor${e.advisories.length===1?"y":"ies"} (−${e.advicePointsLost})`),(e.pending??0)>0&&t.push(`${e.pending} pending (unscored by this profile)`);const r=e.protocolVersion?` [${e.protocolVersion}]`:"";return`${e.score}/100 — ${t.join(", ")}${r}`}function op(e){return sd(e.checks,(e.readiness??[]).filter(t=>t.informational!==!0).map(t=>({id:t.id,tier:t.specStrength==="MAY"?"may":"should"})),e.protocolVersion,e.profile)}function Gm(e,t,r){const{scored:n}=Bm(e,r);return sd(e,n.flatMap(i=>(i.warnings??[]).map((s,o)=>({id:`${i.id}-warning-${o+1}`,tier:"may"}))),t,r)}function ap(e){return Gm(e.checks,e.protocolVersion)}function qO(e){return Gm(e.checks,e.discovery.protocolVersion,e.profile)}function cp(e){return e.outcome==="not-applicable"?id({passed:0,failed:0,couldNotRun:0,notApplicable:e.steps.length},[],"passed",e.protocolVersion):sd(e.steps.map(t=>({id:t.step,status:t.status,...t.skipReason?{skipReason:t.skipReason}:{},...t.error?.message?{error:{message:t.error.message}}:{}})),[],e.protocolVersion)}var jO=8;function HO(e){return cr(e,0,new WeakSet)}function cr(e,t,r){if(e===null)return null;switch(typeof e){case"string":case"boolean":return e;case"number":return Number.isFinite(e)?e:String(e);case"bigint":return e.toString();case"undefined":case"function":case"symbol":return}const n=e;if(r.has(n))return"[circular]";if(t>=jO)return"[max-depth]";if(n instanceof Date)return n.toISOString();if(n instanceof URL)return n.toString();r.add(n);try{if(Array.isArray(n))return n.map(s=>cr(s,t+1,r)??null);if(n instanceof Map)return[...n.entries()].map(([s,o])=>[cr(s,t+1,r)??null,cr(o,t+1,r)??null]);if(n instanceof Set)return[...n].map(s=>cr(s,t+1,r)??null);const i={};if(n instanceof Error){i.name=n.name,i.message=n.message;const s=n;s.code!==void 0&&(i.code=cr(s.code,t+1,r)),s.statusCode!==void 0&&(i.statusCode=cr(s.statusCode,t+1,r)),s.cause!==void 0&&(i.cause=cr(s.cause,t+1,r))}for(const[s,o]of Object.entries(n)){const a=cr(o,t+1,r);a!==void 0&&(i[s]=a)}return i}finally{r.delete(n)}}function Zm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zn(e){const t=Object.entries(e).filter(([,r])=>r===void 0?!1:Array.isArray(r)?r.length>0:Zm(r)?Object.keys(r).length>0:!0);if(t.length!==0)return HO(Object.fromEntries(t))}function BO(e){if(e.httpAttempts.length!==0)return e.httpAttempts.map(t=>`${`${t.request.method} ${t.request.url}`} → ${t.response?`${t.response.status} ${t.response.statusText}`:"No response"}`).join(`
|
|
112
|
+
`)}function VO(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0?{details:Zn({details:e.details,errorDetails:e.error?.details})}:{}}}function GO(e,t){return{id:e.id,title:e.title,category:e.category,status:e.status,...t?.has(e.id)?{pending:!0}:{},...e.skipReason?{skipReason:e.skipReason}:{},durationMs:e.durationMs,description:e.description,...e.error?.message?{error:e.error.message}:{},...e.details!==void 0||e.error?.details!==void 0||e.warnings?.length?{details:Zn({details:e.details,errorDetails:e.error?.details,warnings:e.warnings})}:{}}}function ZO(e){const t=BO(e);return{id:e.step,title:e.title||e.step,category:"oauth",status:e.status,durationMs:e.durationMs,description:e.summary,...e.error?.message?{error:e.error.message}:{},...e.error?.details!==void 0||e.warnings?.length||e.teachableMoments?.length?{details:Zn({errorDetails:e.error?.details,warnings:e.warnings,teachableMoments:e.teachableMoments})}:{},...t?{output:t}:{}}}function oi(e){const t=e.outcome;return t!=="passed"&&t!=="failed"&&t!=="incomplete"?{}:{outcome:t,...e.incompleteReason?{incompleteReason:e.incompleteReason}:{}}}function ad(e){const t=e.map(r=>oi(r).outcome??(r.outcome==="not-applicable"||r.passed?"passed":"failed"));if(t.includes("failed"))return{outcome:"failed"};if(t.includes("incomplete")){const r=e.find(n=>oi(n).outcome==="incomplete");return{outcome:"incomplete",...r?.incompleteReason?{incompleteReason:r.incompleteReason}:{}}}return{outcome:"passed"}}function up(e,t,r){return{id:`mcp-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:(()=>{const n=new Set(e.profile?.pendingCheckIds??[]);return e.checks.map(i=>VO(i,n))})()}}function Pu(e,t,r,n="apps"){const i=new Set(e.profile?.pendingCheckIds??[]);return{id:`${n}-${r+1}`,title:t,target:e.target,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.checks.map(s=>GO(s,i))}}function lp(e,t,r){return{id:`oauth-${r+1}`,title:t,target:e.serverUrl,passed:e.passed,durationMs:e.durationMs,summary:e.summary,cases:e.steps.map(ZO)}}function WO(e){return"checks"in e&&!("results"in e)&&"serverUrl"in e&&!("target"in e)}function JO(e){return"checks"in e&&!("results"in e)&&"target"in e}function KO(e){return"checks"in e&&!("results"in e)&&"discovery"in e&&Zm(e.discovery)&&"wire"in e.discovery}function YO(e){return"steps"in e&&!("results"in e)}function XO(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"checks"in e.results[0]}function QO(e){return"results"in e&&"target"in e}function eC(e){return"results"in e&&"serverUrl"in e&&!("target"in e)&&e.results.length>0&&"steps"in e.results[0]}function tC(e){const t=e[0]?.profile;return t?e.every(r=>r.profile?.profileId===t.profileId&&r.profile?.profileVersion===t.profileVersion&&r.profile?.manifestDigest===t.manifestDigest)?{profile:t}:{}:{}}function rC(e){return"results"in e?{schemaVersion:1,kind:"protocol-conformance",name:e.name,passed:e.passed,...ad(e.results),score:od(e.results.map(op)),...tC(e.results),durationMs:e.durationMs,groups:e.results.map((t,r)=>up(t,t.label,r))}:{schemaVersion:1,kind:"protocol-conformance",name:"MCP Protocol Conformance",passed:e.passed,...oi(e),score:op(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[up(e,"MCP Protocol Conformance",0)]}}function nC(e){return"results"in e?{schemaVersion:1,kind:"apps-conformance",name:e.name,passed:e.passed,...ad(e.results),score:od(e.results.map(ap)),durationMs:e.durationMs,groups:e.results.map((t,r)=>Pu(t,t.label,r))}:{schemaVersion:1,kind:"apps-conformance",name:"MCP Apps Conformance",passed:e.passed,...oi(e),score:ap(e),durationMs:e.durationMs,groups:[Pu(e,"MCP Apps Conformance",0)]}}function iC(e){return"results"in e?{schemaVersion:1,kind:"oauth-conformance",name:e.name,passed:e.passed,...ad(e.results),score:od(e.results.map(cp)),durationMs:e.durationMs,groups:e.results.map((t,r)=>lp(t,t.label,r))}:{schemaVersion:1,kind:"oauth-conformance",name:"OAuth Conformance",passed:e.passed,...oi(e),score:cp(e),durationMs:e.durationMs,groups:[lp(e,`${e.protocolVersion}/${e.registrationStrategy}`,0)]}}function sC(e){return"lanes"in e&&"findings"in e&&"badges"in e&&!("readinessKind"in e)}var oC={kind:"claude-directory-readiness",providerName:"Claude Directory Readiness",isResult:sC,isDispositive:e=>Sb(e)};function aC(e){return e.status==="violated"?"failed":e.status==="satisfied"?"passed":"skipped"}function cC(e,t){const r=t.isDispositive,n=[],i=new Set,s=e.lanes.map(o=>{const a=e.findings.filter(c=>c.lane===o.lane);for(const c of a)i.add(c),!r(c)&&n.push({id:c.id,title:c.title,group:o.lane,kind:c.class,status:c.status,message:c.remediation??c.notEvaluatedReason,details:Zn({provenance:c.provenance,source:c.source,derivedFrom:c.derivedFrom,observed:c.details})});return{id:o.lane,title:o.lane,target:e.context.target,passed:o.status==="ready",durationMs:0,summary:o.summary,cases:a.filter(r).map(c=>({id:c.id,title:c.title,category:c.class,status:aC(c),skipReason:c.status==="not-evaluated"?"could-not-run":c.status==="not-applicable"?"not-applicable":void 0,durationMs:0,description:c.remediation,error:c.status==="violated"?c.remediation??"Requirement not satisfied":c.status==="not-evaluated"?c.notEvaluatedReason:void 0,details:Zn({provenance:c.provenance,intrusiveness:c.intrusiveness,source:c.source,requiresCapabilities:c.requiresCapabilities,derivedFrom:c.derivedFrom,observed:c.details})}))}});for(const o of e.findings)i.has(o)||n.push({id:o.id,title:o.title,group:o.lane,kind:o.class,status:o.status,message:o.remediation??o.notEvaluatedReason??"reported outside any lane in this result",details:Zn({provenance:o.provenance,source:o.source,orphanedLane:o.lane})});return{schemaVersion:1,kind:t.kind,name:t.providerName,passed:e.status==="ready",outcome:e.status==="ready"?"passed":e.status==="not-ready"?"failed":"incomplete",incompleteReason:e.status==="incomplete"?e.summary:void 0,durationMs:e.durationMs,groups:s,advisories:n}}var uC={kind:"openai-directory-readiness",providerName:"OpenAI Plugin Directory Readiness",isResult:e=>Rb(e),isDispositive:e=>wv(e)},lC=[uC,oC];function dC(e){return lC.find(t=>t.isResult(e))}function jz(e){const t=dC(e);if(t)return cC(e,t);if(WO(e)||XO(e))return rC(e);if(KO(e))return{schemaVersion:1,kind:"tasks-conformance",name:"MCP Tasks Conformance",passed:e.passed,...oi(e),score:qO(e),...e.profile?{profile:e.profile}:{},durationMs:e.durationMs,groups:[Pu(e,"MCP Tasks Conformance",0,"tasks")]};if(JO(e)||QO(e))return nC(e);if(YO(e)||eC(e))return iC(e);throw new Error("Unsupported conformance result shape")}var Hz=Object.freeze({chatgpt:!0,copilot:!0,mcpjam:!0,claude:!1,"claude-desktop":!1,cursor:!1,codex:!1,goose:!1,slack:!1,vscode:!1,notion:!1}),hC=["low","medium","high","xhigh","max"],pC=["minimal","low","medium","high"],Wm={"claude-code":[],codex:["low","medium","high","xhigh"],cursor:[]};function fC(e,t){switch(e){case"openai":{const r=Km(t);return r.length===0?void 0:/^gpt-5\.\d+(?:[.-]|$)/.test(t)&&r.includes("none")?"none":r.includes("medium")?"medium":void 0}case"anthropic":return Ym(t).includes("high")?"high":void 0;case"google":return Xm(t).includes("high")?"high":void 0;default:return}}function vC(e){const t=e.indexOf("/");return t>0?e.slice(0,t):void 0}function Bz(e,t,r){if(t==="org")return;const n=r??vC(e);if(n!==void 0)return fC(n,Jm(e))}function Jm(e){const t=e.indexOf("/");return t>=0?e.slice(t+1):e}function Km(e){if(/-(?:pro|chat)(?:[.-]|$)/.test(e))return[];if(/^(?:o1|o3|o3-mini|o4-mini)(?:-\d{4}-\d{2}-\d{2})?$/.test(e))return["low","medium","high"];if(/-codex(?:[.-]|$)/.test(e))return/^gpt-5\.1-codex-max$|^gpt-5\.2-codex$/.test(e)?["low","medium","high","xhigh"]:[];const t=/^gpt-5\.(\d+)(?:[.-]|$)/.exec(e);return t?Number(t[1])>=2?["none","low","medium","high","xhigh"]:["none","low","medium","high"]:/^gpt-5(?:-|$)/.test(e)?["minimal","low","medium","high"]:[]}function Ym(e){const t=/^claude-(opus|sonnet|haiku|fable)-(\d+)(?:[.-](\d{1,2})(?!\d))?(?:[.-]|$)/.exec(e);if(!t)return[];const r=Number(t[2]),n=t[3]===void 0?0:Number(t[3]),i=hC;return t[1]==="haiku"?[]:r>=5?i:r!==4||n>=10?[]:t[1]==="opus"?n>=7?i:n===6?["low","medium","high","max"]:n===5?["low","medium","high"]:[]:t[1]==="sonnet"&&n>=6?["low","medium","high","max"]:[]}function Xm(e){return/^gemini-3\.\d+-pro(?:-preview)?(?:-\d+)?$/.test(e)?["low","medium","high"]:/^gemini-3-pro(?:-preview)?(?:-\d+)?$/.test(e)?["low","high"]:/^gemini-3(?:\.\d+)?-flash(?:-preview)?(?:-\d+)?$/.test(e)?pC:[]}function gC(e,t){const r=Jm(t);switch(e){case"openai":return Km(r);case"anthropic":return Ym(r);case"google":return Xm(r);default:return[]}}var mC=new Set(_a);function ho(e){const t=new Set(e.filter(r=>mC.has(r)));return _a.filter(r=>t.has(r))}function Vz(e){return ho(Wm[e]??[])}function _C(e){if(e.harness!==void 0){const t=new Set(_C({...e,harness:void 0}));return ho((Wm[e.harness]??[]).filter(r=>t.has(r)))}switch(e.route){case"hosted":return ho(e.catalogEfforts??[]);case"org":return[];case"orgCloud":case"direct":return ho(gC(e.providerKey,e.modelId))}}function Qm(e){const t=e.connectionRef,r=e.settings,n=r!==void 0&&(r.reasoningEffort!==void 0||r.temperature!==void 0);return{modelId:e.modelId,source:e.source,...t===void 0?{}:t.kind==="orgProvider"?{connectionRef:{kind:t.kind,id:t.id}}:{connectionRef:{kind:t.kind,providerKey:t.providerKey,...t.customProviderName!==void 0?{customProviderName:t.customProviderName}:{}}},...e.nativeModelId!==void 0?{nativeModelId:e.nativeModelId}:{},...n?{settings:{...r.reasoningEffort!==void 0?{reasoningEffort:r.reasoningEffort}:{},...r.temperature!==void 0?{temperature:r.temperature}:{}}}:{},fallback:{provider:e.fallback.provider,model:e.fallback.model}}}function Gz(e){return JSON.stringify(Qm(e))}function yC(e){if(e.source==="legacy")return!0;if(e.source!=="hosted"||e.nativeModelId!==void 0)return!1;const t=e.settings;return t===void 0||t.reasoningEffort===void 0&&t.temperature===void 0}function dp(e){const t=bC(e);return t===void 0?e.modelId:`${e.modelId}\0${t}`}function bC(e){if(yC(e))return;const{fallback:t,...r}=Qm(e);return JSON.stringify(r)}var hp={none:"None",minimal:"Minimal",low:"Low",medium:"Med",high:"High",xhigh:"X-High",max:"Max"};function wC(e){if(e.source==="legacy")return"Your key";if(e.source==="hosted")return"MCPJam";const t=e.connectionRef;return t?.kind==="localProvider"?t.customProviderName??t.providerKey:"Org key"}function pp(e){return e.source==="legacy"?void 0:e.settings}function Zz(e,t){const r=t.filter(l=>l.modelId===e.modelId&&dp(l)!==dp(e)),n=l=>pp(l)?.reasoningEffort,i=n(e);if(r.length===0)return i===void 0?[]:[hp[i]];const s=[],o=wC(e),a=e.source==="legacy"?"legacy":fp(e);r.some(l=>(l.source==="legacy"?"legacy":fp(l))!==a)&&s.push(o);const c=l=>l.source==="legacy"?void 0:l.nativeModelId;if(r.some(l=>c(l)!==c(e))){const l=c(e);l!==void 0&&s.push(l)}(i!==void 0||r.some(l=>n(l)!==i))&&s.push(i===void 0?"Default":hp[i]);const u=l=>pp(l)?.temperature;if(r.some(l=>u(l)!==u(e))){const l=u(e);s.push(l===void 0?"Default temp":`Temp ${l}`)}return s}function fp(e){const t=e.connectionRef;return t===void 0?e.source:t.kind==="orgProvider"?`${e.source}:${t.id}`:`${e.source}:${t.providerKey}:${t.customProviderName??""}`}var SC="=?base64?";function EC(e){const t=e.toLowerCase();if(t==="mcp-protocol-version")return"protocol-version";if(t==="mcp-method")return"method";if(t==="mcp-name")return"name";if(t==="mcp-session-id")return"session";if(t==="last-event-id")return"resumption";if(t.startsWith("mcp-param-"))return"param"}function kC(e){const t=globalThis;if(typeof t.atob=="function"){const r=t.atob(e),n=new Uint8Array(r.length);for(let i=0;i<r.length;i+=1)n[i]=r.charCodeAt(i);return new TextDecoder("utf-8",{fatal:!0}).decode(n)}if(t.Buffer)return t.Buffer.from(e,"base64").toString("utf8");throw new Error("no base64 decoder available")}function po(e){if(!e.startsWith("=?base64?")||!e.endsWith("?=")||e.length<11)return{raw:e,encoded:!1,value:e};const t=e.slice(9,e.length-2);try{return{raw:e,encoded:!0,value:kC(t)}}catch(r){return{raw:e,encoded:!0,value:e,decodeError:r instanceof Error?r.message:String(r)}}}var IC=new Set(["tools/call","resources/read","prompts/get"]),e_=new Set(["tasks/get","tasks/update","tasks/cancel"]);function AC(e){return e===void 0?!1:IC.has(e)||e_.has(e)}var vp=["protocol-version","method","name","param","session","resumption"];function TC(e){return e!==void 0&&e_.has(e)?".params.taskId":e==="resources/read"?".params.uri":".params.name"}function RC(e){const t=e.declarations??[],r=UC(t,e.arguments);return t.map(n=>{const i=`${t_}${n.headerName}`,s=r[i];return{header:i.toLowerCase(),displayName:i,expected:s===void 0?void 0:po(s).value,bodyField:`.params.arguments${n.path.map(o=>`.${o}`).join("")}`}})}function Wz(e,t,r){const n=new Map;for(const[d,p]of Object.entries(e))n.set(d.toLowerCase(),{name:d,value:p});const i=n.get("mcp-protocol-version")?.value??t?.protocolVersion,s=!!i&&hT(i)&&pT(i)&&!!t,o=[],a=new Set,c=s&&t?[{header:"mcp-protocol-version",family:"protocol-version",bodyValue:t.protocolVersion,bodyField:"._meta protocolVersion",required:!0},{header:"mcp-method",family:"method",bodyValue:t.method,bodyField:".method",required:!0},{header:"mcp-name",family:"name",bodyValue:t.name,bodyField:TC(t.method),required:AC(t.method)}]:[];for(const d of c){a.add(d.header);const p=n.get(d.header);if(!p){d.required&&d.bodyValue!==void 0?o.push({name:d.header,family:d.family,status:"missing",bodyValue:d.bodyValue,bodyField:d.bodyField}):!d.required&&t?.method!==void 0&&o.push({name:d.header,family:d.family,status:"not-required"});continue}const f=po(p.value),v={name:p.name,family:d.family,raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):d.bodyValue===void 0?o.push({...v,status:"unchecked"}):f.value===d.bodyValue?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.bodyValue,bodyField:d.bodyField})}const u=r!==void 0&&"arguments"in r,l=s&&r?RC(r):[],h=s&&r?.declarations!==void 0;for(const d of l){a.add(d.header);const p=n.get(d.header);if(!p){if(!u){o.push({name:d.displayName,family:"param",status:"unchecked"});continue}o.push(d.expected===void 0?{name:d.displayName,family:"param",status:"not-required"}:{name:d.displayName,family:"param",status:"missing",bodyValue:d.expected,bodyField:d.bodyField});continue}const f=po(p.value),v={name:p.name,family:"param",raw:p.value,decoded:f.encoded&&!f.decodeError?f.value:void 0};f.decodeError?o.push({...v,status:"undecodable"}):u?d.expected===void 0?o.push({...v,status:"mismatch",bodyValue:"(absent from arguments)",bodyField:d.bodyField}):f.value===d.expected?o.push({...v,status:"match",bodyField:d.bodyField}):o.push({...v,status:"mismatch",bodyValue:d.expected,bodyField:d.bodyField}):o.push({...v,status:"unchecked"})}for(const[d,p]of n){if(a.has(d))continue;const f=EC(p.name);if(!f)continue;const v=po(p.value),g=s&&f==="param"&&!!v.decodeError,m=h&&f==="param"&&!g;o.push({name:p.name,family:f,raw:p.value,decoded:v.encoded&&!v.decodeError?v.value:void 0,status:g?"undecodable":m?"undeclared":"unchecked"})}return o.sort((d,p)=>vp.indexOf(d.family)-vp.indexOf(p.family)||d.name.localeCompare(p.name))}var gp="x-mcp-header",t_="Mcp-Param-",PC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,OC=new Set(["string","integer","boolean","number"]),CC=["items","prefixItems","contains","additionalProperties","unevaluatedProperties","unevaluatedItems","propertyNames","patternProperties","dependentSchemas","oneOf","anyOf","allOf","not","if","then","else","$defs","definitions"],$C=new Set(["patternProperties","dependentSchemas","$defs","definitions"]);function xC(e){return e.length===0?"<root>":e.join(".")}function Jz(e){const t=[],r=new Map,n=(s,o,a)=>{if(s===null||typeof s!="object")return;const c=s;if(gp in c){const l=xC(o);if(!a||o.length===0)return`${l}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;const h=c[gp];if(typeof h!="string"||h.length===0)return`${l}: x-mcp-header MUST be a non-empty string`;if(!PC.test(h))return`${l}: x-mcp-header '${h}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;const d=typeof c.type=="string"?c.type:void 0;if(d===void 0||!OC.has(d))return`${l}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${d??"<none>"}`;const p=h.toLowerCase(),f=r.get(p);if(f!==void 0)return`x-mcp-header '${h}' is not case-insensitively unique (also declared as '${f}')`;r.set(p,h),t.push({path:o,headerName:h,type:d})}const u=c.properties;if(u!==null&&typeof u=="object")for(const[l,h]of Object.entries(u)){const d=n(h,[...o,l],a);if(d!==void 0)return d}for(const l of CC){const h=c[l];if(h===void 0)continue;const d=h!==null&&typeof h=="object"&&$C.has(l),p=Array.isArray(h)?h:d?Object.values(h):[h];for(const f of p){const v=n(f,[...o,`<${l}>`],!1);if(v!==void 0)return v}}},i=n(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}function MC(e){const t=globalThis,r=new TextEncoder().encode(e);if(typeof t.btoa=="function"){let n="";for(const i of r)n+=String.fromCodePoint(i);return t.btoa(n)}if(t.Buffer)return t.Buffer.from(e,"utf8").toString("base64");throw new Error("no base64 encoder available")}function LC(e){if(e.length===0||e.startsWith("=?base64?")&&e.endsWith("?=")||e!==e.trim())return!0;for(let t=0;t<e.length;t+=1){const r=e.codePointAt(t);if(!(r===9||r>=32&&r<=126))return!0}return!1}function NC(e){if(!LC(e))return e;const t=MC(e);return`${SC}${t}?=`}function DC(e){if(typeof e=="string")return e;if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number")return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function zC(e,t){let r=e;for(const n of t){if(r===null||typeof r!="object")return;r=r[n]}return r}function UC(e,t){const r={};for(const n of e){const i=zC(t,n.path);if(i==null)continue;const s=DC(i);s!==void 0&&(r[`${t_}${n.headerName}`]=NC(s))}return r}var FC="tracestate",qC="baggage",jC=/^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/,HC="0".repeat(32),BC="0".repeat(16);function VC(e){if(typeof e!="string")return;const t=jC.exec(e);if(!t)return;const[,r,n,i,s]=t;if(!(r==="ff"||r!=="00")&&!(n===HC||i===BC))return{version:r,traceId:n,spanId:i,flags:s,sampled:(Number.parseInt(s,16)&1)===1}}function GC(e){return VC(e)!==void 0}var ZC=32,WC=/^(?:[a-z][a-z0-9_\-*/]{0,255}|[a-z0-9][a-z0-9_\-*/]{0,240}@[a-z][a-z0-9_\-*/]{0,13})$/,JC=/^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;function KC(e){if(typeof e!="string"||e.length===0)return!1;const t=e.split(",");if(t.length>ZC)return!1;let r=0;for(const n of t){const i=n.trim();if(i.length===0)continue;r+=1;const s=i.indexOf("=");if(s<=0||!WC.test(i.slice(0,s))||!JC.test(i.slice(s+1)))return!1}return r>0}var YC=180,XC=8192,QC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,mp=/^[\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]*$/;function e$(e){if(typeof e!="string"||e.length===0||e.length>XC)return!1;const t=e.split(",");if(t.length>YC)return!1;for(const r of t){const n=r.trim();if(n.length===0)return!1;const[i,...s]=n.split(";"),o=i.indexOf("=");if(o<=0||!QC.test(i.slice(0,o).trim())||!mp.test(i.slice(o+1).trim()))return!1;for(const a of s)if(!mp.test(a.replace(/=/g,"").trim()))return!1}return!0}function t$(e){if(!(!e||!GC(e.traceparent)))return{traceparent:e.traceparent,...KC(e.tracestate)?{tracestate:e.tracestate}:{},...e$(e.baggage)?{baggage:e.baggage}:{}}}function Kz(e){if(!e||typeof e!="object")return;const t=r=>{const n=e[r];return typeof n=="string"?n:void 0};return t$({traceparent:t("traceparent")??"",tracestate:t(FC),baggage:t(qC)})}var Yz=Pt.MissingRequiredClientCapability,A="u">typeof window?window:void 0,dt="u">typeof globalThis?globalThis:A,rt=dt?.navigator,D=dt?.document,je=dt?.location,hs=dt?.fetch,cd=dt?.XMLHttpRequest&&"withCredentials"in new dt.XMLHttpRequest?dt.XMLHttpRequest:void 0,_p=dt?.AbortController,r$=dt?.CompressionStream,ft=rt?.userAgent;function r_(){return!(!A||A.navigator.onLine===!1)}var Ti=typeof globalThis<"u"?globalThis:A;Ti&&typeof self>"u"&&(Ti.self=Ti),Ti&&typeof File>"u"&&(Ti.File=function(){});var re=A??{},yp="0.9.0",vr={DEBUG:!1,LIB_VERSION:yp,LIB_NAME:"browser-common",JS_SDK_VERSION:yp},Jt=(function(e){return e.AnonymousId="anonymous_id",e.DistinctId="distinct_id",e.Props="props",e.EnablePersonProcessing="enable_person_processing",e.PersonMode="person_mode",e.FeatureFlagDetails="feature_flag_details",e.FeatureFlags="feature_flags",e.FeatureFlagPayloads="feature_flag_payloads",e.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",e.BootstrapFeatureFlags="bootstrap_feature_flags",e.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",e.OverrideFeatureFlags="override_feature_flags",e.Queue="queue",e.AiQueue="ai_queue",e.AiCaptureQueue="ai_capture_queue",e.LogsQueue="logs_queue",e.OptedOut="opted_out",e.SessionId="session_id",e.SessionStartTimestamp="session_start_timestamp",e.SessionLastTimestamp="session_timestamp",e.PersonProperties="person_properties",e.GroupProperties="group_properties",e.InstalledAppBuild="installed_app_build",e.InstalledAppVersion="installed_app_version",e.SessionReplay="session_replay",e.PushRegistered="push_registered",e.SessionReplayEventTriggerActivatedSession="session_replay_event_trigger_activated_session",e.SurveyLastSeenDate="survey_last_seen_date",e.SurveysInProgress="surveys_in_progress",e.SurveysSeen="surveys_seen",e.Surveys="surveys",e.RemoteConfig="remote_config",e.FlagsEndpointWasHit="flags_endpoint_was_hit",e.DeviceId="device_id",e})({}),Ou=(function(e){return e.GZipJS="gzip-js",e.Base64="base64",e})({}),n$=["$snapshot","$pageview","$pageleave","$set","survey dismissed","survey sent","survey shown","$identify","$groupidentify","$create_alias","$$client_ingestion_warning","$web_experiment_applied","$feature_enrollment_update","$feature_flag_called"],i$=["token"];function ce(e,t){return e.indexOf(t)!==-1}var za=function(e){return e.trim()},Cu=function(e){return e.replace(/^\$/,"")};function n_(e){var t;const r=[];return(t=JSON.stringify(e,function(n,i){if(typeof i=="bigint")return i.toString();if(typeof i!="function"&&typeof i!="symbol"){if(i instanceof Error)return{name:i.name,message:i.message,stack:i.stack};if(i&&typeof i=="object"){for(;r.length>0&&r[r.length-1]!==this;)r.pop();if(r.includes(i))return"[Circular]";r.push(i)}return i}}))!==null&&t!==void 0?t:"null"}var i_=Object.prototype,ud=i_.hasOwnProperty,Ua=i_.toString,ue=Array.isArray||function(e){return Ua.call(e)==="[object Array]"},tt=e=>typeof e=="function",be=e=>e===Object(e)&&!ue(e),bt=e=>{if(be(e)){for(const t in e)if(ud.call(e,t))return!1;return!0}return!1},M=e=>e===void 0,ye=e=>Ua.call(e)=="[object String]",Zi=e=>ye(e)&&e.trim().length===0,He=e=>e===null,fe=e=>M(e)||He(e),Ze=e=>Ua.call(e)=="[object Number]"&&e==e,ur=e=>Ze(e)&&e>0,gt=e=>Ua.call(e)==="[object Boolean]",s$=e=>ce(n$,e),o$=e=>ce(i$,e);function s_(e){return e===null||typeof e!="object"}function No(e,t){return{}.toString.call(e)===`[object ${t}]`}function yi(e){switch({}.toString.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object DOMError]":case"[object WebAssembly.Exception]":return!0;default:return o_(e,Error)}}function ld(e){return"u">typeof Event&&o_(e,Event)}function o_(e,t){try{return e instanceof t}catch{return!1}}var a$=[!0,"true",1,"1","yes"],cc=e=>ce(a$,e),c$=[!1,"false",0,"0","no"];function bp(e,t,r,n,i,s,o){try{var a=e[s](o),c=a.value}catch(u){r(u);return}a.done?t(c):Promise.resolve(c).then(n,i)}function Ue(e){return function(){var t=this,r=arguments;return new Promise(function(n,i){var s=e.apply(t,r);function o(c){bp(s,n,i,o,a,"next",c)}function a(c){bp(s,n,i,o,a,"throw",c)}o(void 0)})}}var u$=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterestbot","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"],wp=function(e,t=[]){if(!e)return!1;const r=e.toLowerCase();return u$.concat(t).some(n=>{const i=n.toLowerCase();return r.indexOf(i)!==-1})};function Yt(e,t,r,n,i){return t>r&&(n.warn("min cannot be greater than max."),t=r),Ze(e)?e>r?(n.warn(" cannot be greater than max: "+r+". Using max value instead."),r):t>e?(n.warn(" cannot be less than min: "+t+". Using min value instead."),t):e:(n.warn(" must be a number. using max or fallback. max: "+r+", fallback: "+i),Yt(i??r,t,r,n))}var l$=class{constructor(e){this.C={},this.I=e.I,this.R=Yt(e.bucketSize,0,100,e.A),this.$=Yt(e.refillRate,0,this.R,e.A),this.O=Yt(e.refillInterval,0,864e5,e.A)}F(e,t){const r=Math.floor((t-e.lastAccess)/this.O);r>0&&(e.tokens=Math.min(e.tokens+r*this.$,this.R),e.lastAccess=e.lastAccess+r*this.O)}consumeRateLimit(e){var t;const r=Date.now(),n=String(e);let i=this.C[n];return i?this.F(i,r):(i={tokens:this.R,lastAccess:r},this.C[n]=i),i.tokens===0||(i.tokens--,i.tokens===0&&((t=this.I)===null||t===void 0||t.call(this,e)),i.tokens===0)}stop(){this.C={}}},ai="Mobile",ps="Android",Do="Tablet",a_="Android Tablet",c_="iPad",u_="Apple Watch",fo="Safari",Fa="BlackBerry",l_="Samsung Internet",vo="Chrome",d_="Chrome iOS",h_="Internet Explorer",p_="Internet Explorer Mobile",f_="Opera",v_="Microsoft Edge",go="Firefox",g_="Firefox iOS",zo="Nintendo",Uo="PlayStation",qa="Xbox",m_="Android Mobile",__="Mobile Safari",uc="Windows",y_="Windows Phone",Sp="Nokia",$u="Ouya",d$="Generic "+ai.toLowerCase(),b_="Generic "+Do.toLowerCase(),xu="Konqueror",w_="Oculus Browser",S_="Vivaldi",E_="Yandex",k_="Whale",I_="DuckDuckGo",A_="Pale Moon",T_="Waterfox",Mu="Brave",R_="Claude",P_="Codex",O_="ChatGPT",C_="Google Search App",lc=new RegExp("Version/(\\d+(\\.\\d+)?)"),dc=new RegExp("(Claude|Codex|ChatGPT)\\/(\\d+(\\.\\d+)?)"),h$=new RegExp(qa,"i"),p$=new RegExp("PlayStation \\w+","i"),f$=new RegExp("Nintendo \\w+","i"),dd=new RegExp("BlackBerry|PlayBook|BB10","i"),v$={"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"},$_=function(e,t,r,n){return t=t||"",(function(i){return i?.brave?Mu:null})(r)||(n?.detectGoogleSearchApp&&ce(e,"GSA/")?C_:ce(e," OPR/")&&ce(e,"Mini")?"Opera Mini":ce(e," OPR/")?f_:dd.test(e)?Fa:ce(e,"IEMobile")||ce(e,"WPDesktop")?p_:ce(e,"OculusBrowser")?w_:ce(e,"SamsungBrowser")?l_:ce(e,"Edge")||ce(e,"Edg/")?v_:ce(e,"Vivaldi/")?S_:ce(e,"YaBrowser/")?E_:ce(e,"Whale/")?k_:ce(e,"DuckDuckGo/")||ce(e,"Ddg/")?I_:ce(e,"Claude/")?R_:ce(e,"Codex/")?P_:ce(e,"ChatGPT/")?O_:ce(e,"FBIOS")?"Facebook Mobile":ce(e,"UCWEB")||ce(e,"UCBrowser")?"UC Browser":ce(e,"CriOS")?d_:ce(e,"CrMo")||ce(e,vo)?vo:ce(e,ps)&&ce(e,fo)?m_:ce(e,"FxiOS")?g_:ce(e.toLowerCase(),xu.toLowerCase())?xu:ce(e,"Brave/")?Mu:((i,s)=>s&&ce(s,"Apple")||(function(o){return ce(o,fo)&&!ce(o,vo)&&!ce(o,ps)})(i))(e,t)?ce(e,ai)?__:fo:ce(e,"PaleMoon/")?A_:ce(e,"Waterfox/")?T_:ce(e,go)?go:ce(e,"MSIE")||ce(e,"Trident/")?h_:ce(e,"Gecko")?go:"")},g$={[p_]:[new RegExp("rv:(\\d+(\\.\\d+)?)")],[v_]:[new RegExp("Edge?\\/(\\d+(\\.\\d+)?)")],[vo]:[new RegExp("(Chrome|CrMo)\\/(\\d+(\\.\\d+)?)")],[d_]:[new RegExp("CriOS\\/(\\d+(\\.\\d+)?)")],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/(\\d+(\\.\\d+)?)")],[fo]:[lc],[__]:[lc],[f_]:[new RegExp("(Opera|OPR)\\/(\\d+(\\.\\d+)?)")],[go]:[new RegExp("Firefox\\/(\\d+(\\.\\d+)?)")],[g_]:[new RegExp("FxiOS\\/(\\d+(\\.\\d+)?)")],[xu]:[new RegExp("Konqueror[:/]?(\\d+(\\.\\d+)?)","i")],[Fa]:[new RegExp("BlackBerry (\\d+(\\.\\d+)?)"),lc],[m_]:[new RegExp("android\\s(\\d+(\\.\\d+)?)","i")],[l_]:[new RegExp("SamsungBrowser\\/(\\d+(\\.\\d+)?)")],[w_]:[new RegExp("OculusBrowser\\/(\\d+(\\.\\d+)?)")],[S_]:[new RegExp("Vivaldi\\/(\\d+(\\.\\d+)?)")],[E_]:[new RegExp("YaBrowser\\/(\\d+(\\.\\d+)?)")],[k_]:[new RegExp("Whale\\/(\\d+(\\.\\d+)?)")],[Mu]:[new RegExp("Brave\\/(\\d+(\\.\\d+)?)")],[R_]:[dc],[P_]:[dc],[O_]:[dc],[I_]:[new RegExp("(DuckDuckGo|Ddg)\\/(\\d+(\\.\\d+)?)")],[A_]:[new RegExp("PaleMoon\\/(\\d+(\\.\\d+)?)")],[T_]:[new RegExp("Waterfox\\/(\\d+(\\.\\d+)?)")],[C_]:[new RegExp("GSA\\/(\\d+(\\.\\d+)?)")],[h_]:[new RegExp("(rv:|MSIE )(\\d+(\\.\\d+)?)")],Mozilla:[new RegExp("rv:(\\d+(\\.\\d+)?)")]},m$=function(e,t,r,n){const i=$_(e,t,r,n),s=g$[i];if(M(s))return null;for(let o=0;s.length>o;o++){const a=e.match(s[o]);if(a)return parseFloat(a[a.length-2])}return null},Ep=[[new RegExp("Xbox; Xbox (.*?)[);]","i"),e=>[qa,e&&e[1]||""]],[new RegExp(zo,"i"),[zo,""]],[new RegExp(Uo,"i"),[Uo,""]],[dd,[Fa,""]],[new RegExp(uc,"i"),(e,t)=>{if(/Phone/.test(t)||/WPDesktop/.test(t))return[y_,""];if(new RegExp(ai).test(t)&&!/IEMobile\b/.test(t))return["Windows Mobile",""];const r=/Windows NT ([0-9.]+)/i.exec(t);if(r&&r[1]){let n=v$[r[1]]||"";return/arm/i.test(t)&&(n="RT"),[uc,n]}return[uc,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,e=>e&&e[3]?["iOS",[e[3],e[4],e[5]||"0"].join(".")]:["iOS",""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,e=>{let t="";return e&&e.length>=3&&(t=M(e[2])?e[3]:e[2]),["watchOS",t]}],[new RegExp("(Android (\\d+)\\.(\\d+)\\.?(\\d+)?|Android)","i"),e=>e&&e[2]?[ps,[e[2],e[3],e[4]||"0"].join(".")]:[ps,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,e=>{const t=["Mac OS X",""];return e&&e[1]&&(t[1]=[e[1],e[2],e[3]||"0"].join(".")),t}],[/Mac/i,["Mac OS X",""]],[/CrOS/,["Chrome OS",""]],[/Linux|debian/i,["Linux",""]]],x_=function(e){for(let t=0;Ep.length>t;t++){const[r,n]=Ep[t],i=r.exec(e),s=i&&(tt(n)?n(i,e):n);if(s)return s}return["",""]},M_=function(e){return f$.test(e)?zo:p$.test(e)?Uo:h$.test(e)?qa:new RegExp($u,"i").test(e)?$u:new RegExp("(Windows Phone|WPDesktop)","i").test(e)?y_:/iPad/.test(e)?c_:/iPod/.test(e)?"iPod Touch":/iPhone/.test(e)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(e)?u_:dd.test(e)?Fa:/(kobo)\s(ereader|touch)/i.test(e)?"Kobo":new RegExp(Sp,"i").test(e)?Sp:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(e)||/(kf[a-z]+)( bui|\)).+silk\//i.test(e)?"Kindle Fire":/(Android|ZTE)/i.test(e)?new RegExp(ai).test(e)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(e)||/pixel[\daxl ]{1,6}/i.test(e)&&!/pixel c/i.test(e)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(e)||/lmy47v/i.test(e)&&!/QTAQZ3/i.test(e)?ps:a_:new RegExp("(pda|Mobile)","i").test(e)?d$:new RegExp(Do,"i").test(e)&&!new RegExp("Tablet pc","i").test(e)?b_:""},_$=function(e,t){var r;const n=M_(e);return n===c_||n===a_||n==="Kobo"||n==="Kindle Fire"||n===b_?Do:n===zo||n===qa||n===Uo||n===$u?"Console":n===u_?"Wearable":n?ai:t?.userAgentDataPlatform==="Android"&&((r=t?.maxTouchPoints)!==null&&r!==void 0?r:0)>0?600>Math.min((i=t?.screenWidth)!==null&&i!==void 0?i:0,(s=t?.screenHeight)!==null&&s!==void 0?s:0)/((o=t?.devicePixelRatio)!==null&&o!==void 0?o:1)?ai:Do:"Desktop";var i,s,o},hc=/\bFBAV\/(\d+(?:\.\d+)*)/i,kp=[[/\bInstagram(?:[ /](\d+(?:\.\d+)*))?\b/i,"Instagram"],[/\bBarcelona[ /](\d+(?:\.\d+)*)?/i,"Threads"],[/\b(?:MessengerForiOS|(?:FBAN|FB_IAB)\/Orca-Android)\b/i,"Messenger",hc],[/\bFBAN\/EMA\b/i,"Facebook Lite",hc],[/\b(?:FBIOS|(?:FBAN|FB_IAB)\/(?:FB4A|FBIOS))\b/i,"Facebook",hc],[/\bLinkedInApp(?:\]?\/(\d+(?:\.\d+)*))?\b/i,"LinkedIn"],[/\bTwitter(?:Android| for (?:iPhone|iPad|Android))(?:\/(\d+(?:\.\d+)*))?\b/i,"Twitter"],[/\b(?:musical_ly|trill)(?:[_/](\d+\.\d+(?:\.\d+)*))?(?=\b|_)/i,"TikTok",/\bapp_version\/(\d+(?:\.\d+)*)/i],[/\b(?:MicroMessenger|WeChat)\/(\d+(?:\.\d+)*)?/i,"WeChat"],[/\bLine\/(\d+(?:\.\d+)*)?/i,"Line"],[/\bGSA\/(\d+(?:\.\d+)*)?/i,"Google"],[/\[Pinterest\/(?:iOS|Android)\b|\bPinterest(?: for (?:Android(?: Tablet)?|iOS))?\/(\d+(?:\.\d+)*)/i,"Pinterest"],[/\b(?:WA4A|WAiOS)\/(\d+(?:\.\d+)*)?/i,"WhatsApp"],[/\bSnapchat[ /](\d+(?:\.\d+)*)?/i,"Snapchat"],[/\bBing(?:Web|Sapphire)\/(\d+(?:\.\d+)*)?/i,"Bing"],[/\bNAVER\(inapp; search;/i,"Naver",/\bNAVER\(inapp; search;[^;)]*; (\d+(?:\.\d+)*)/i],[/\bKAKAOTALK[ /](\d+\.\d+(?:\.\d+)*)?/i,"KakaoTalk"]],Lu="[Truncated]",As="[Unserializable]";function Wn(e){let t="";for(let r=0;e.length>r;r++){const n=e.charCodeAt(r);if(55296>n||n>56319)t+=56320>n||n>57343?e[r]:"�";else{const i=e.charCodeAt(r+1);56320>i||i>57343?t+="�":(t+=e[r]+e[r+1],r++)}}return t}function L_(e,t){if(!t)return e;let r=[];try{r=Object.keys(t)}catch{r=[]}for(const n of r){let i;try{i=t[n]}catch{i=As}Object.defineProperty(e,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return e}var mo=3e5,N_=class{record(e){if(e.kind==="too-large")return;if(e.kind!=="retry-later")return void this.reset();if(!e.retryAfterMs)return;const t=this.isOpen(),r=Date.now(),n=Math.min(e.retryAfterMs,mo);if(!t)return this.ts=r,void(this.es=r+n);this.es=Math.max(this.es,Math.min(r+n,this.ts+mo))}remainingMs(){const e=Date.now();if(this.ts-5e3>e)return this.reset(),0;const t=Math.min(mo,Math.max(0,this.es-e));return t===0&&this.reset(),t}isOpen(){return this.remainingMs()>0}reset(){this.es=0,this.ts=0}constructor(){this.es=0,this.ts=0}},y$=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ip(e,t){return typeof(r=e)=="string"&&y$.test(r)?e:t();var r}function D_(e,t){const r=new Error(t);try{Object.defineProperty(r,"name",{value:e,writable:!0,enumerable:!0,configurable:!0})}catch{}return r}function Jr(e){return e&&e.split("#")[0]}function Ap(e){try{return e()}catch{return}}function z_(e,t){const r=setTimeout(e,t);return r!=null&&r.unref&&r?.unref(),r}function Tp(e,t,r){return U_.apply(this,arguments)}function U_(){return(U_=Ue(function*(e,t,r){let n;try{return yield Promise.race([e,new Promise((i,s)=>{n=z_(()=>{try{r?.(),i()}catch(o){s(o)}},t)})])}finally{clearTimeout(n)}})).apply(this,arguments)}var Bs,Rp,pc;function b$(e){const t=globalThis._posthogChunkIds;if(!t)return;const r=Object.keys(t);return pc&&r.length===Rp||(Rp=r.length,pc=r.reduce((n,i)=>{Bs||(Bs={});const s=Bs[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],u=c?.filename,l=t[i];if(u&&l){n[u]=l,Bs[i]=[u,l];break}}}return n},{})),pc}function Wi(e){return Wi=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Wi(e)}function w$(e,t,r){return(t=(function(n){var i=(function(s){if(Wi(s)!="object"||!s)return s;var o=s[Symbol.toPrimitive];if(o!==void 0){var a=o.call(s,"string");if(Wi(a)!="object")return a;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(s)})(n);return Wi(i)=="symbol"?i:i+""})(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Pp(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function b(e){for(var t=1;arguments.length>t;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Pp(Object(r),!0).forEach(function(n){w$(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Pp(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}var S$=class{constructor(e,t,r=[]){this.coercers=e,this.stackParser=t,this.modifiers=r}buildFromUnknown(e,t={}){const r=t&&t.mechanism||{handled:!0,type:"generic"},n=this.buildCoercingContext(r,t,0).apply(e),i=this.buildParsingContext(t),s=this.parseStacktrace(n,i);return{$exception_list:this.convertToExceptionList(s,r),$exception_level:"error"}}modifyFrames(e){var t=this;return Ue(function*(){for(const r of e)r.stacktrace&&r.stacktrace.frames&&ue(r.stacktrace.frames)&&(r.stacktrace.frames=yield t.applyModifiers(r.stacktrace.frames));return e})()}coerceFallback(e){var t;return{type:"Error",value:"Unknown error",stack:(t=e.syntheticException)===null||t===void 0?void 0:t.stack,synthetic:!0}}parseStacktrace(e,t){var r;let n,i;if(e.cause!=null&&(n=this.parseStacktrace(e.cause,t)),e.stack!=""&&e.stack!=null)try{i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?t.skipFirstLines:0),t.chunkIdMap)}catch{}return b(b({},e),{},{cause:n,stack:i,errors:(r=e.errors)===null||r===void 0?void 0:r.map(s=>this.parseStacktrace(s,t))})}applyChunkIds(e,t){return e.map(r=>(r.filename&&t&&(r.chunk_id=t[r.filename]),r))}applyCoercers(e,t){for(const r of this.coercers)if(r.match(e))return r.coerce(e,t);return this.coerceFallback(t)}applyModifiers(e){var t=this;return Ue(function*(){let r=e;for(const n of t.modifiers)r=yield n(r);return r})()}convertToExceptionList(e,t){const r=[],n=(i,s,o)=>{var a;const c=r.length,u=s===void 0?b(b({type:typeof t.type=="string"&&t.type.length>0?t.type:"generic"},typeof t.handled=="boolean"?{handled:t.handled}:t.handled===void 0?{handled:!0}:{}),{},{synthetic:typeof t.synthetic=="boolean"?t.synthetic:i.synthetic,exception_id:c}):{type:"chained",source:o,synthetic:i.synthetic,exception_id:c,parent_id:s},l={type:i.type,value:i.value,mechanism:u};i.stack&&(l.stacktrace={type:"raw",frames:i.stack}),r.push(l),i.cause&&n(i.cause,c,"cause");for(const h of(a=i.errors)!==null&&a!==void 0?a:[])n(h,c,"member")};return n(e),r}buildParsingContext(e){var t;return{chunkIdMap:b$(this.stackParser),skipFirstLines:(t=e.skipFirstLines)!==null&&t!==void 0?t:1}}getAggregateErrors(e){try{if(yi(e)){let r=Object.getPrototypeOf(e);for(let n=0;r&&100>n;n++){var t;const i=(t=Object.getOwnPropertyDescriptor(r,"constructor"))===null||t===void 0?void 0:t.value;if(typeof i=="function"&&i.name==="AggregateError"){const s=e.errors;return ue(s)?s:void 0}r=Object.getPrototypeOf(r)}}}catch{}}buildCoercingContext(e,t,r=0){let n=0,i=0,s=!1;const o=new Set,a=[],c={},u=(d,p,f=0)=>{const v=l(p,f),g=v.apply;if(v.apply=I=>{a.push(d);try{return g(I)}finally{a.pop()}},f>4||f>0&&a.indexOf(d)!==-1)return this.coerceFallback(v);const m=typeof d=="object"&&d!==null||typeof d=="function";if(f===0&&n>=50||m&&o.has(d))return;m&&o.add(d),f===0&&n++;const w=this.getAggregateErrors(d);let S,O;s||(s=!!w);try{if(S=this.applyCoercers(d,v),!S)throw c}catch(I){if(I===c)return void(f===0&&n--);if(!s)throw I;S=this.coerceFallback(v)}if(!w||n>=50)return S;try{O=w.length}catch{return S}if(!Number.isInteger(O)||0>O||O>4294967295)return S;const R=[];for(let I=0;50>n&&1e3>i&&O>I;I++){let C;i++;try{C=v.next(w[I])}catch{n++,C=this.coerceFallback(l(p+1))}C&&R.push(C)}return b(b({},S),{},{errors:R})},l=(d,p=0)=>b(b({},t),{},{syntheticException:d==0?t.syntheticException:void 0,mechanism:d==0?e:{},apply(f){const v=u(f,d,p+1);if(!v)throw c;return v},next:f=>u(f,d+1)}),h=l(r);return b(b({},h),{},{apply:d=>{var p;return(p=u(d,r))!==null&&p!==void 0?p:this.coerceFallback(h)}})}},E$=/^([a-z][a-z0-9.+-]+):/i,k$=["http","https","file","blob","app","capacitor","ionic","webpack","webpack-internal","ng"];function I$(e){if(!e||e==="<anonymous>")return!1;const t=E$.exec(e);return!t||k$.includes(t[1].toLowerCase())}function Nu(e,t,r,n,i){const s={platform:e,filename:t,function:r==="<anonymous>"?"?":r,in_app:I$(t)};return M(n)||(s.lineno=n),M(i)||(s.colno=i),s}var F_=(e,t)=>{const r=e.indexOf("safari-extension")!==-1,n=e.indexOf("safari-web-extension")!==-1;return r||n?[e.indexOf("@")!==-1?e.split("@")[0]:"?",r?`safari-extension:${t}`:`safari-web-extension:${t}`]:[e,t]},A$=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,T$=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,R$=/\((\S*)(?::(\d+))(?::(\d+))\)/,P$=(e,t)=>{const r=A$.exec(e);if(r){const[,i,s,o]=r;return Nu(t,i,"?",+s,+o)}const n=T$.exec(e);if(n){if(n[2]&&n[2].indexOf("eval")===0){const o=R$.exec(n[2]);o&&(n[2]=o[1],n[3]=o[2],n[4]=o[3])}const[i,s]=F_(n[1]||"?",n[2]);return Nu(t,s,i,n[3]?+n[3]:void 0,n[4]?+n[4]:void 0)}},O$=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,C$=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,$$=(e,t)=>{const r=O$.exec(e);if(r){if(r[3]&&r[3].indexOf(" > eval")>-1){const s=C$.exec(r[3]);s&&(r[1]=r[1]||"eval",r[3]=s[1],r[4]=s[2],r[5]="")}let n=r[3],i=r[1]||"?";return[i,n]=F_(i,n),Nu(t,n,i,r[4]?+r[4]:void 0,r[5]?+r[5]:void 0)}},Op=/\(error: (.*)\)/;function hd(e,t){return e.filename===t.filename&&e.function===t.function&&e.module===t.module&&e.lineno===t.lineno&&e.colno===t.colno}function x$(e){for(let t=1;10>=t;t++){const r=e.length-2*t;if(0>r)break;let n=!0;for(let i=0;t>i;i++)if(!hd(e[r+i],e[r+t+i])){n=!1;break}if(n){for(let i=0;t>i;i++)e[r+i]=e[r+t+i];return e.length=r+t,{start:r,length:t}}}}function M$(e,t){const r=t.start+t.length,n=j_(e,t);n&&e.splice(r+n===e.length?r:t.start,n)}function q_(e,t){let r=t.start;for(;r>0&&hd(e[r-1],e[r-1+t.length]);)r--;return t.start-r}function j_(e,t){const r=t.start+t.length;let n=r;for(;e.length>n&&hd(e[n],e[n-t.length]);)n++;return n-r}function L$(e,t){const r=t[0];let n=e.length-(r?q_(e,r):0);for(const i of t)n-=j_(e,i);return n}function N$(e,t,r){for(let n=0;e.length>n;n++){const i=e[(t+n)%e.length],s=e[(r+n)%e.length];if(i!==s)return s>i}return!1}var D$=class{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,t){const r=ye(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?t.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){const t=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?`${t}: ${e.message}`:t}isDOMException(e){return No(e,"DOMException")}isDOMError(e){return No(e,"DOMError")}},z$=class{match(e){return yi(e)}coerce(e,t){var r;const n=this.getStack(e),i=n===void 0?(r=t.syntheticException)===null||r===void 0?void 0:r.stack:void 0,s=!!i;return{type:this.getType(e),value:this.getMessage(e,t),stack:n??i,cause:e.cause?t.next(e.cause):void 0,synthetic:s}}getType(e){return e.name||e.constructor.name}getMessage(e,t){const r=e.message;return String(r.error&&typeof r.error.message=="string"?r.error.message:r)}getStack(e){try{const t=e.stacktrace;if(typeof t=="string"&&t.length>0)return t;const r=e.stack;return typeof r=="string"&&r.length>0?r:void 0}catch{return}}},U$=class{match(e){return!!No(e,"ErrorEvent")&&(e.error!=null||this.ar(e))}coerce(e,t){var r;if(e.error!=null)return t.apply(e.error);const n=t.apply(e.message);return b(b({},n),{},{stack:(r=this.lr(e))!==null&&r!==void 0?r:n.stack,synthetic:!0})}ar(e){return ye(e.message)&&e.message.length>0}lr(e){var t,r;const n=e,i=(t=n.lineno)!==null&&t!==void 0?t:0,s=(r=n.colno)!==null&&r!==void 0?r:0;if(ye(n.filename)&&n.filename.length!==0&&i!==0)return`Error
|
|
113
|
+
at ${n.filename}:${i}:${s}`}},F$=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i,q$=class{match(e){return typeof e=="string"}coerce(e,t){var r;const[n,i]=this.getInfos(e);return{type:n??"Error",value:i??e,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}getInfos(e){let t="Error",r=e;const n=e.match(F$);return n&&(t=n[1],r=n[2]),[t,r]}},j$=["fatal","error","warning","log","info","debug"];function H_(e,t=40){const r=Object.keys(e);if(r.sort(),!r.length)return"[object has no keys]";for(let n=r.length;n>0;n--){const i=r.slice(0,n).join(", ");if(t>=i.length)return n===r.length?i:i.length>t?`${i.slice(0,t)}...`:i}return""}var H$=class{match(e){return typeof e=="object"&&e!==null}coerce(e,t){var r,n;const i=this.getErrorPropertyFromObject(e);return i?t.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=this.getStack(e))!==null&&r!==void 0?r:(n=t.syntheticException)===null||n===void 0?void 0:n.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){if(ld(e))return e.constructor.name;const t="name"in e?e.name:void 0;return ye(t)&&!Zi(t)?t:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){let r=`'${e.name}' captured as exception`;return"message"in e&&typeof e.message=="string"&&(r+=` with message: '${e.message}'`),r}if("message"in e&&typeof e.message=="string")return e.message;const t=this.getObjectClassName(e);return`${t&&t!=="Object"?`'${t}'`:"Object"} captured as exception with keys: ${H_(e)}`}isSeverityLevel(e){return ye(e)&&!Zi(e)&&j$.indexOf(e)>=0}getStack(e){try{return ye(e.stacktrace)&&e.stacktrace.length>0?e.stacktrace:ye(e.stack)&&e.stack.length>0?e.stack:void 0}catch{return}}getErrorPropertyFromObject(e){for(const t in e)if({}.hasOwnProperty.call(e,t)){const r=e[t];if(yi(r))return r}}getObjectClassName(e){try{const t=Object.getPrototypeOf(e);return t?t.constructor.name:void 0}catch{return}}},B$=class{match(e){return ld(e)}coerce(e,t){var r;const n=e.constructor.name;return{type:n,value:`${n} captured as exception with keys: ${H_(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},V$=class{match(e){return s_(e)}coerce(e,t){var r;return{type:"Error",value:`Primitive value captured as exception: ${String(e)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}}},G$=class{match(e){return No(e,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(e)}isCustomEventWrappingRejection(e){if(!ld(e))return!1;try{const t=e.detail;return t!=null&&typeof t=="object"&&"reason"in t}catch{return!1}}coerce(e,t){var r;const n=this.getUnhandledRejectionReason(e);return s_(n)?{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(n)}`,stack:(r=t.syntheticException)===null||r===void 0?void 0:r.stack,synthetic:!0}:t.apply(n)}getUnhandledRejectionReason(e){try{if("reason"in e)return e.reason;if("detail"in e&&e.detail!=null&&typeof e.detail=="object"&&"reason"in e.detail)return e.detail.reason}catch{}return e}},Fo="$message",qo="$timestamp",Z$=new Set([Fo,qo]),fc={enabled:!0,max_bytes:32768};function jo(e){var t;return e?{enabled:(t=e.enabled)!==null&&t!==void 0?t:fc.enabled,max_bytes:J$(e.max_bytes,fc.max_bytes)}:b({},fc)}var W$=class{constructor(e){this.ns=[],this.ss=0,this.Ir=jo(e)}setConfig(e){this.Ir=jo(e),this.rs()}add(e){const t=(function(n){let i;try{i=n_(n)}catch{return}try{const s=JSON.parse(i);if(!be(s))return;const o=s,a=o[Fo],c=o[qo];return!ye(a)||a.trim().length===0||!ye(c)&&!Ze(c)?void 0:{step:o,json:i}}catch{return}})(e);if(!t)return;const r=(function(n){if("u">typeof TextEncoder)return new TextEncoder().encode(n).length;const i=encodeURIComponent(n);let s=0;for(let o=0;i.length>o;o++)i[o]==="%"?(s+=1,o+=2):s+=1;return s})(t.json);r>this.Ir.max_bytes||(this.ns.push({step:t.step,bytes:r}),this.ss+=r,this.rs())}getAttachable(){return this.ns.map(e=>e.step)}clear(){this.ns=[],this.ss=0}size(){return this.ns.length}rs(){for(;this.ss>this.Ir.max_bytes&&this.ns.length>0;){const e=this.ns.shift();e&&(this.ss-=e.bytes)}}};function J$(e,t){if(!Ze(e)||e===1/0||e===-1/0)return t;const r=Math.floor(e);return 0>r?t:r}var Cp=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}};function $p(e){return typeof e=="string"||e}function xp(e){return typeof e=="string"?e:void 0}var K$=["$feature_flag","$feature_flag_response","$feature_flag_has_experiment","$feature_flag_id","$feature_flag_version","$feature_flag_reason","$feature_flag_request_id","$feature_flag_evaluated_at","$feature_flag_error","locally_evaluated","$groups","$process_person_profile","$geoip_disable","$current_url","$pathname","$referring_domain","utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid","gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx","$session_id","$window_id","$lib","$lib_version","$device_id","$is_server"],B_="NativeGzipValidationError",Du=e=>e.length>=2&&e[0]===31&&e[1]===139,Mp=(e,t)=>e===Ou.GZipJS||t===Ou.GZipJS||t==="gzip",Lp=e=>!(!e||typeof e!="object")&&("name"in e?String(e.name):"")==="NotReadableError",Ri,Vs=e=>{throw D_(B_,`Native gzip produced invalid output: ${e}`)},Y$=(Np=Ue(function*(e,t){18>e.size&&Vs("too-short");const r=new Uint8Array(yield e.slice(0,10).arrayBuffer());Du(r)&&r[2]===8||Vs("invalid-header");const n=new DataView(yield e.slice(e.size-8).arrayBuffer());n.getUint32(0,!0)!==(s=>{const o=(()=>{if(Ri)return Ri;Ri=[];for(let c=0;256>c;c++){let u=c;for(let l=0;8>l;l++)u=1&u?3988292384^u>>>1:u>>>1;Ri[c]=u>>>0}return Ri})();let a=4294967295;for(let c=0;s.length>c;c++)a=o[255&(a^s[c])]^a>>>8;return(4294967295^a)>>>0})(t)&&Vs("invalid-crc");const i=t.length>>>0;n.getUint32(4,!0)!==i&&Vs("invalid-size")}),function(e,t){return Np.apply(this,arguments)}),Np;function zu(){return zu=Ue(function*(e,t=!0,r){try{const i=new TextEncoder().encode(e),s=new globalThis.CompressionStream("gzip"),o=s.writable.getWriter(),a=o.write(i).then(()=>o.close()).catch((n=Ue(function*(l){try{yield o.abort(l)}catch{}throw l}),function(l){return n.apply(this,arguments)})),c=new Response(s.readable).blob(),[u]=yield Promise.all([c,a]);return yield Y$(u,i),u}catch(i){if(r?.rethrow)throw i;return t&&console.error("Failed to gzip compress data",i),null}var n}),zu.apply(this,arguments)}function V_(e,t){if(e==null)return{};var r,n,i=(function(o,a){if(o==null)return{};var c={};for(var u in o)if({}.hasOwnProperty.call(o,u)){if(a.includes(u))continue;c[u]=o[u]}return c})(e,t);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);for(n=0;s.length>n;n++)t.includes(r=s[n])||{}.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}var X$={}.propertyIsEnumerable;function Ho(e,t){try{return G_(e,t,{ancestors:new WeakSet,remainingNodes:1e4},0)}catch{return[]}}function pd(e,t,r,n){if(0>=r.remainingNodes)return{stringValue:Lu};if(r.remainingNodes--,gt(e))return{boolValue:e};if(typeof e=="bigint")return(function(i,s){const o=i.toString(),a=BigInt("9223372036854775808");return i>=a||-a>i?(s?.debug(`Attribute ${o} is outside the int64 range; encoding it as a string`),{stringValue:o}):{intValue:o}})(e,t);if(typeof e=="number"){if(!Number.isFinite(e))return{stringValue:String(e)};if(Number.isInteger(e)){if(Number.isSafeInteger(e))return{intValue:String(e)};if(typeof BigInt>"u")return{stringValue:String(e)};const i=BigInt(e).toString();return e>=9223372036854776e3||-9223372036854776e3>e?(t?.debug(`Attribute ${i} is outside the int64 range; encoding it as a string`),{stringValue:i}):{intValue:i}}return{doubleValue:e}}if(typeof e=="string")return{stringValue:Wn(e)};if(typeof e=="function")return{stringValue:"[Function]"};if(typeof e=="symbol")return{stringValue:String(e)};if(typeof e=="object"&&e!==null){if(r.ancestors.has(e))return{stringValue:"[Circular]"};if(n>=20)return{stringValue:Lu};if(e instanceof Date){const i=e.getTime(),s=Number.isFinite(i)?e.toISOString():String(e);return{stringValue:typeof s=="string"?Wn(s):String(s)}}r.ancestors.add(e);try{try{const i=e.toJSON;if(typeof i=="function")return pd(i.call(e),t,r,n+1)}catch{}return ue(e)?{arrayValue:{values:Q$(e,t,r,n+1)}}:{kvlistValue:{values:G_(e,t,r,n+1)}}}finally{r.ancestors.delete(e)}}return{stringValue:Wn(String(e))}}function Q$(e,t,r,n){const i=[],s=Math.min(e.length,1e3);let o=0;for(;s>o&&r.remainingNodes>0;o++)try{const a=o in e?e[o]:void 0;if(fe(a))continue;i.push(pd(a,t,r,n))}catch{i.push({stringValue:As})}return e.length>o&&i.push({stringValue:Lu}),i}function G_(e,t,r,n){const i=[];for(const s in e)if(X$.call(e,s)){if(!s){t?.debug("Dropping an attribute with an empty key");continue}if(i.length>=1e3||0>=r.remainingNodes){t?.debug("Attributes truncated: the value exceeds the OTLP encoder budget");break}try{const o=e[s];if(He(o)||M(o))continue;i.push({key:Wn(s),value:pd(o,t,r,n)})}catch{i.push({key:Wn(s),value:{stringValue:As}})}}return i}function Z_(e,t,r){return b(b(b(b({},L_({},e.resourceAttributes)),{},{"service.name":e.serviceName||"unknown_service"},e.environment&&{"deployment.environment":e.environment}),e.serviceVersion&&{"service.version":e.serviceVersion}),{},{"telemetry.sdk.name":t,"telemetry.sdk.version":r})}var e1=["service.name","deployment.environment","service.version","telemetry.sdk.name","telemetry.sdk.version"];function W_(e,t){const r=L_({},e),n={};for(const i of e1)({}).hasOwnProperty.call(r,i)&&(n[i]=r[i],delete r[i]);return[...Ho(r,t),...Ho(n,t)]}var Dp={darwin:"macOS",win32:"Windows",cygwin:"Windows",linux:"Linux",android:"Android",freebsd:"FreeBSD",openbsd:"OpenBSD",netbsd:"NetBSD",sunos:"SunOS",aix:"AIX",haiku:"Haiku","Mac OS X":"macOS"},J_={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},t1=J_.info;function r1(e){try{return Wn(String(e))}catch{return As}}function n1(e,t,r,n){const i=e.level||"info",{text:s,number:o}=J_[i]||t1,a=(function(d=Date.now()){return String(d)+"000000"})(Ze(n)?n:void 0),c={};t.distinctId&&(c.posthogDistinctId=t.distinctId),t.sessionId&&(c.sessionId=t.sessionId),t.windowId&&(c["window.id"]=t.windowId),fe(t.sessionStartTimestamp)||(c.sessionStartTimestamp=String(t.sessionStartTimestamp)),fe(t.lastActivityTimestamp)||(c.lastActivityTimestamp=String(t.lastActivityTimestamp)),t.currentUrl&&(c["url.full"]=t.currentUrl),t.screenName&&(c["screen.name"]=t.screenName),t.appState&&(c["app.state"]=t.appState),t.activeFeatureFlags&&t.activeFeatureFlags.length>0&&(c.feature_flags=t.activeFeatureFlags);const u=b({},c),l=e.attributes;if(l){let d=[];try{d=Object.keys(l)}catch{d=[]}for(const p of d){let f;try{f=l[p]}catch{f=As}Object.defineProperty(u,p,{value:f,enumerable:!0,writable:!0,configurable:!0})}}const h={timeUnixNano:a,observedTimeUnixNano:a,severityNumber:o,severityText:s,body:{stringValue:r1(e.body)},attributes:Ho(u,r)};return e.trace_id&&(h.traceId=e.trace_id),e.span_id&&(h.spanId=e.span_id),M(e.trace_flags)||(h.flags=e.trace_flags),h}function K_(e,t,r){return Z_(e,t,r)}function Y_(e,t,r,n){return{resourceLogs:[{resource:{attributes:W_(t)},scopeLogs:[{scope:{name:r,version:n},logRecords:e}]}]}}var X_=class{constructor(e){this.ls=e,this.us=0}get pending(){return!!this.hs}arm(e){this.clear(),this.us=Date.now()+e,this.hs=z_(()=>{this.hs=void 0,this.ls()},e)}armNoEarlierThan(e){this.hs&&Date.now()+e<=this.us||this.arm(e)}clear(){this.hs&&(clearTimeout(this.hs),this.hs=void 0)}};function Q_(){return .75+.5*Math.random()}function ey(e,t,r,n){const i=Math.min(Math.max(0,t-1),6),s=e*Math.pow(2,i);return Math.round((n===void 0?s:Math.min(s,Math.max(n,e)))*r)}var i1=class{constructor(e,t,r,n,i,s=()=>Promise.resolve(),o){var a;this._instance=e,this.Ir=t,this.A=r,this.cs=n,this.ds=i,this.vs=s,this.fs=o,this.ps=new X_(()=>this.gs()),this.ys=null,this.bs=0,this._s=0,this.ws=new N_,this.ks=0,this.Ss=1,this.xs=0,this.Cs=0,this.$s=!1,this.Ts=t.maxBufferSize,this.Is=Math.max((a=t.maxQueueSize)!==null&&a!==void 0?a:t.maxBufferSize,t.maxBufferSize),this.Ms=t.flushIntervalMs,this.Es=t.maxBatchRecordsPerPost,this.Ps=t.rateCapWindowMs,this.Rs=t.maxLogsPerInterval}clearQueue(){this._s++,this._instance.setPersistedProperty(Jt.LogsQueue,[])}reset(){this.ps.clear(),this.xs=0,this.Cs=0,this.$s=!1,this.ks=0,this.Ss=1,this.ws.reset(),this.Es=this.Ir.maxBatchRecordsPerPost}onReconnect(){this.ks=0,this.Ss=1,this.ws.isOpen()?this.As()&&this.Fs():this.gs()}captureLog(e,t){var r;if(this._instance.isDisabled||this._instance.optedOut||!e?.body)return;const n=this.Os(e);if(n===null)return;if(!n.body)return void this.A.info("Log was rejected in beforeSend function");if(!this.Ds())return;const i={record:n1(n,(r=t?.context)!==null&&r!==void 0?r:this.cs(),this.A,t?.occurredAtMs)};this.ds(()=>this.Ls(i))}Os(e){const t=this.Ir.beforeSend;if(!t)return e;const r=ue(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.A.info("Log was rejected in beforeSend function"),null;n=s}catch(s){return this.A.error("Error in beforeSend function for log:",s),null}return n}Ds(){if(this.Rs===void 0)return!0;const e=Date.now(),t=e-this.xs;return this.Ps>t&&t>=0||(this.xs=e,this.Cs=0,this.$s=!1),this.Rs>this.Cs?(this.Cs++,!0):(this.$s||(this.A.warn(`captureLog dropping logs: exceeded ${this.Rs} logs per ${this.Ps}ms`),this.$s=!0),!1)}flush(){var e=this;return Ue(function*(){if(!e._instance.isDisabled)return e.ys||(e.ys=e.Ns().finally(()=>{e.ys=null})),e.ys})()}Ns(){var e=this;return Ue(function*(){var t;e.ps.clear();let r=(t=e._instance.getPersistedProperty(Jt.LogsQueue))!==null&&t!==void 0?t:[];if(r.length===0)return;const n=r.length;let i=0;for(;r.length>0&&n>i;){var s,o;const a=e._s;e.bs=0;const c=Math.min(r.length,e.Es),u=r.slice(0,c),l=Y_(u.map(d=>d.record),e.qs(),(s=e.fs)!==null&&s!==void 0?s:e._instance.getLibraryId(),e._instance.getLibraryVersion()),h=yield e._instance.js(l);if(e._s!==a)return;if(h.kind==="too-large"&&u.length>1)e.Es=Math.max(1,Math.floor(u.length/2)),e.A.warn(`Logs batch of size ${u.length} was too large for the ingestion endpoint, reducing batch size to ${e.Es}`);else if(e.ws.record(h),e.ps.pending&&e.ps.arm(Math.max(e.Ms,e.ws.remainingMs())),h.kind==="retry-later"||(h.kind==="too-large"?e.A.warn("Dropping a single log record with batch size 1 — the record is larger than the server cap and cannot be split further."):h.kind==="ok"&&e.Ir.maxBatchRecordsPerPost>e.Es&&(e.Es=Math.min(e.Ir.maxBatchRecordsPerPost,e.Es+1)),yield e.Bs(u.length),r=(o=e._instance.getPersistedProperty(Jt.LogsQueue))!==null&&o!==void 0?o:[],i+=u.length,h.kind==="fatal"))throw h.error}})()}Bs(e){var t=this;return Ue(function*(){var r;const n=Math.max(0,e-t.bs),i=(r=t._instance.getPersistedProperty(Jt.LogsQueue))!==null&&r!==void 0?r:[];t._instance.setPersistedProperty(Jt.LogsQueue,i.slice(n)),yield t.vs()})()}qs(){return K_(this.Ir,this._instance.getLibraryId(),this._instance.getLibraryVersion())}Ls(e){var t;if(this._instance.optedOut)return;const r=(t=this._instance.getPersistedProperty(Jt.LogsQueue))!==null&&t!==void 0?t:[];this.Is>r.length||(r.shift(),this.bs++,this.A.info("Logs queue is full, dropping oldest record.")),r.push(e),this._instance.setPersistedProperty(Jt.LogsQueue,r),this.Ts>r.length||this.ws.isOpen()?this.Fs():this.gs()}Fs(){this.ps.pending||this.ps.arm(Math.max(this.Ms,this.ws.remainingMs()))}Hs(){return Math.max(ey(this.Ms,this.ks,this.Ss,3e4),this.ws.remainingMs())}As(){const e=this._instance.getPersistedProperty(Jt.LogsQueue);return!!e&&e.length>0}shutdown(e){var t=this;return Ue(function*(){t.ps.clear();const r=t.flush().catch(()=>{});e!==void 0?yield Tp(r,e):yield r})()}flushWithTimeout(e){var t=this;return Ue(function*(){const r=t.flush();yield Tp(r,e,()=>{r.catch(()=>{})})})()}gs(){this.flush().then(()=>{this.ks=0,this.Ss=1},e=>{this.ks++,this.Ss=Q_(),this.A.error("PostHog logs flush failed:",e)}).finally(()=>{!this._instance.isDisabled&&this.As()&&this.ps.armNoEarlierThan(this.Hs())})}},vc=[0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4];function zp(e){return String(e)+"000000"}function Up(e,t,r,n){let i="";return n&&(i=Object.keys(n).sort().map(s=>`${JSON.stringify(s)}:${JSON.stringify(n[s])}`).join(",")),`${e}\0${t}\0${r??""}\0${i}`}var s1=class{constructor(e,t,r){this._instance=e,this.Ir=t,this.A=r,this.zs=new Map,this.ps=new X_(()=>this.flush().catch(n=>{this.A.error("Metrics flush failed:",n)})),this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.ws=new N_,this.ks=0,this.Ss=1,this.Gs=0}count(e,t=1,r){this.Zs({name:e,type:"count",value:t,unit:r?.unit,attributes:r?.attributes})}gauge(e,t,r){this.Zs({name:e,type:"gauge",value:t,unit:r?.unit,attributes:r?.attributes})}histogram(e,t,r){this.Zs({name:e,type:"histogram",value:t,unit:r?.unit,attributes:r?.attributes})}flush(){var e=this;const t=this.ys,r=(function(){var n=Ue(function*(){t&&(yield t.catch(()=>{})),yield e.Qs()});return function(){return n.apply(this,arguments)}})()().finally(()=>{this.ys===r&&(this.ys=null)});return this.ys=r,r}drainWindow(){if(this.zs.size===0)return null;const e=this.zs;return this.zs=new Map,this.Us=!1,this.Ws=new Map,this.Vs=new Set,this.Js(e)}reset(){this.Gs++,this.ws.reset(),this.ks=0,this.Ss=1,this.ps.clear(),this.zs=new Map,this.ys=null,this.Us=!1,this.Ws=new Map,this.Vs=new Set}Zs(e){if(this._instance.isDisabled||this._instance.optedOut)return;const t=this.Os(e);if(t===null)return;if(!t.name||typeof t.name!="string")return void this.A.warn("Dropping metric with empty name");if(typeof t.value!="number"||!Number.isFinite(t.value))return void this.A.warn(`Dropping metric '${t.name}': value must be a finite number`);if(t.type==="count"&&0>t.value)return void this.A.warn(`Dropping count '${t.name}': counters are monotonic, value must be >= 0`);let r,n;try{r=t.attributes?b({},t.attributes):void 0,n=Up(t.type,t.name,t.unit,r)}catch(o){this.A.warn(`Dropping metric '${t.name}': attributes could not be serialized`,o);return}let i=this.zs.get(n);if(!i){if(!this.Ks())return;i={name:t.name,type:t.type,unit:t.unit,attributes:r,windowStartMs:Date.now()},this.zs.set(n,i)}const s=this.Ws.get(t.name);s===void 0?this.Ws.set(t.name,t.type):s===t.type||this.Vs.has(t.name)||(this.Vs.add(t.name),this.A.warn(`Metric name '${t.name}' is already used as a ${s}; recording it as a ${t.type} too will blend both series in charts. Use a distinct name.`)),this.Xs(i,t.value),this.Fs()}Ks(){return this.Ir.maxSeriesPerFlush>this.zs.size||(this.Us||(this.Us=!0,this.A.warn(`Metric series cap reached (${this.Ir.maxSeriesPerFlush} per flush window); dropping new series until the next flush. Reduce attribute cardinality.`)),!1)}Xs(e,t){switch(e.type){case"count":var r;e.total=((r=e.total)!==null&&r!==void 0?r:0)+t;break;case"gauge":e.last=t;break;case"histogram":{e.hist||(e.hist={count:0,sum:0,min:t,max:t,bucketCounts:new Array(vc.length+1).fill(0)});const n=e.hist;n.count+=1,n.sum+=t,n.min=Math.min(n.min,t),n.max=Math.max(n.max,t),n.bucketCounts[(function(i,s){for(let o=0;s.length>o;o++)if(s[o]>=i)return o;return s.length})(t,vc)]+=1;break}}}Os(e){const t=this.Ir.beforeSend;if(!t)return e;const r=ue(t)?t:[t];let n=e;for(const i of r)try{const s=i(n);if(!s)return this.A.info("Metric was rejected in beforeSend function"),null;n=s}catch(s){return this.A.error("Error in beforeSend function for metric:",s),null}return n}Fs(){this.ps.pending||this.ps.arm(this.Hs())}Hs(){return Math.max(ey(this.Ir.flushIntervalMs,this.ks,this.Ss,3e4),this.ws.remainingMs())}Qs(){var e=this;return Ue(function*(){if(e.ps.clear(),e.zs.size===0)return;const t=e.zs;e.zs=new Map,e.Us=!1,e.Ws=new Map,e.Vs=new Set;const r=e.Gs,n=yield e._instance.Ys(e.Js(t));if(r===e.Gs)switch(e.ws.record(n),n.kind==="retry-later"?(e.ks++,e.Ss=Q_()):(e.ks=0,e.Ss=1),e.ps.pending&&e.ps.arm(e.Hs()),n.kind){case"ok":return;case"retry-later":e.ho(t),e.ps.armNoEarlierThan(e.Hs());return;case"too-large":e.A.warn("Metrics batch exceeded the server size limit and was dropped");return;case"fatal":e.A.error("Failed to send metrics batch:",n.error);return}})()}Js(e){return t=this.co(e),r=(function(s,o,a){return Z_(s,o,a)})(this.Ir,this._instance.getLibraryId(),this._instance.getLibraryVersion()),n=this._instance.getLibraryId(),i=this._instance.getLibraryVersion(),{resourceMetrics:[{resource:{attributes:W_(r)},scopeMetrics:[{scope:{name:n,version:i},metrics:t}]}]};var t,r,n,i}co(e){const t=zp(Date.now()),r=new Map;for(const o of e.values()){var n;const a=Up(o.type,o.name,o.unit,void 0);let c=r.get(a);c||(c=b({name:o.name},o.unit&&{unit:o.unit}),o.type==="count"?c.sum={aggregationTemporality:1,isMonotonic:!0,dataPoints:[]}:o.type==="gauge"?c.gauge={dataPoints:[]}:c.histogram={aggregationTemporality:1,dataPoints:[]},r.set(a,c));const u=Ho((n=o.attributes)!==null&&n!==void 0?n:{},this.A),l=zp(o.windowStartMs);if(o.type==="count"){var i;const h={attributes:u,startTimeUnixNano:l,timeUnixNano:t,asDouble:(i=o.total)!==null&&i!==void 0?i:0};c.sum.dataPoints.push(h)}else if(o.type==="gauge"){var s;const h={attributes:u,timeUnixNano:t,asDouble:(s=o.last)!==null&&s!==void 0?s:0};c.gauge.dataPoints.push(h)}else o.hist&&c.histogram.dataPoints.push({attributes:u,startTimeUnixNano:l,timeUnixNano:t,count:o.hist.count,sum:o.hist.sum,min:o.hist.min,max:o.hist.max,bucketCounts:o.hist.bucketCounts,explicitBounds:vc})}return Array.from(r.values())}ho(e){for(const[n,i]of e){const s=this.zs.get(n);if(s)switch(s.windowStartMs=Math.min(s.windowStartMs,i.windowStartMs),s.type){case"count":var t,r;s.total=((t=s.total)!==null&&t!==void 0?t:0)+((r=i.total)!==null&&r!==void 0?r:0);break;case"gauge":break;case"histogram":if(i.hist)if(s.hist){s.hist.count+=i.hist.count,s.hist.sum+=i.hist.sum,s.hist.min=Math.min(s.hist.min,i.hist.min),s.hist.max=Math.max(s.hist.max,i.hist.max);for(let o=0;s.hist.bucketCounts.length>o;o++)s.hist.bucketCounts[o]+=i.hist.bucketCounts[o]}else s.hist=i.hist}else this.Ks()&&this.zs.set(n,i)}}},ty=(e,{debugEnabled:t}={})=>{const r={N(n,...i){A&&(vr.DEBUG||A.POSTHOG_DEBUG||t)&&!M(A.console)&&A.console&&("__rrweb_original__"in A.console[n]?A.console[n].__rrweb_original__:A.console[n])(e,...i)},debug(...n){r.N("debug",...n)},info(...n){r.N("log",...n)},warn(...n){r.N("warn",...n)},error(...n){r.N("error",...n)},critical(...n){console.error(e,...n)},uninitializedWarning(n){r.error(`You must initialize PostHog before calling ${n}`)},createLogger:(n,i)=>ty(`${e} ${n}`,i)};return r},j=ty("[PostHog.js]"),Ve=j.createLogger,o1=Ve("[ExternalScriptsLoader]"),Bo=e=>{const t=D?.querySelectorAll("script");if(t){for(let r=0;t.length>r;r++)if(t[r].src===e||t[r].getAttribute("src")===e)return t[r]}},un=(e,t,r)=>{if(e.config.disable_external_dependency_loading)return o1.warn(`${t} was requested but loading of external scripts is disabled.`),r("Loading of external scripts is disabled");const n=Bo(t);if(n){if(n.__posthog_loading_callback_fired)return r();const s=n.__posthog_loading_error;return s?r(s):(n.addEventListener("load",o=>{n.__posthog_loading_callback_fired=!0,r(void 0,o)}),void n.addEventListener("error",o=>{n.__posthog_loading_error=o,r(o)}))}const i=()=>{if(!D)return r("document not found");if(Bo(t))return un(e,t,r);let s=D.createElement("script");if(s.type="text/javascript",s.crossOrigin="anonymous",s.src=t,s.onload=a=>{s.__posthog_loading_callback_fired=!0,r(void 0,a)},s.onerror=a=>{s.__posthog_loading_error=a,r(a)},e.config.prepare_external_dependency_script&&(s=e.config.prepare_external_dependency_script(s)),!s)return r("prepare_external_dependency_script returned null");if(e.config.external_scripts_inject_target==="head")D.head.appendChild(s);else{const a=D.querySelectorAll("body > script");var o;a.length>0?(o=a[0].parentNode)===null||o===void 0||o.insertBefore(s,a[0]):D.body.appendChild(s)}};D?.body?i():D?.addEventListener("DOMContentLoaded",i)},gc={},Fp=(e,t)=>{let r=`/static/${t}.js?v=${e.version}`;return t==="toolbar"&&(r=`${r}&t=${Math.floor(Date.now()/3e5)*3e5}`),e.requestRouter.endpointFor("assets",r)};re.__PosthogExtensions__=re.__PosthogExtensions__||{},re.__PosthogExtensions__.loadExternalDependency=(e,t,r)=>{if(t==="remote-config"){const i=e.requestRouter.endpointFor("assets",`/array/${e.config.token}/config.js`);un(e,i,r);return}const n=e.config.strict_script_versioning;if(n){const i=e.requestRouter.endpointFor("assets",`/static/${e.version}/${t}.js`),s=gc[i];if(n==="fallback"&&s){if(Bo(s))return void un(e,s,r);delete gc[i]}un(e,i,n==="fallback"?(o,a)=>{if(o)if(typeof o=="string")r(o);else{var c;const u=Fp(e,t);gc[i]=u;const l=Bo(i);l==null||(c=l.parentNode)===null||c===void 0||c.removeChild(l),un(e,u,r)}else r(void 0,a)}:r);return}un(e,Fp(e,t),r)},re.__PosthogExtensions__.loadSiteApp=(e,t,r)=>{const n=e.requestRouter.endpointFor("api",t);un(e,n,r)},vr.DEBUG=!1,vr.LIB_VERSION="1.435.3",vr.LIB_NAME="web";var et=vr,a1="$people_distinct_id",Nt="distinct_id",fd="$device_id",mc="$device_model",Vo="__alias",c1="__cmpns",qp="$fbc",Jn="$fbc_persistence",jp="$fbp",Ji="$fbp_persistence",Uu="__timers",ry="$autocapture_disabled_server_side",Fu="$heatmaps_enabled_server_side",qu="$exception_capture_enabled_server_side",ny="$error_tracking_suppression_rules",ju="$error_tracking_capture_extension_exceptions",Hu="$web_vitals_enabled_server_side",vd="$dead_clicks_enabled_server_side",gd="$product_tours_enabled_server_side",iy="$logs_capture_enabled_server_side",sy="$web_vitals_allowed_metrics",Ki="$session_recording_remote_config",u1="$session_recording_enabled_server_side",l1="$replay_sample_rate",d1="$replay_override_sampling",h1="$replay_override_linked_flag",p1="$replay_override_url_trigger",f1="$replay_override_event_trigger",Hn="$sesid",oy="$session_is_sampled",v1="$session_past_minimum_duration",g1="$session_recording_url_trigger_activated_session",m1="$session_recording_event_trigger_activated_session",_1="$debug_first_full_snapshot_timestamp",y1="$sess_rec_flush_size",Ut="$enabled_feature_flags",hr="$active_feature_flags",Bu="$early_access_features",_n="$feature_flag_details",Cr="$feature_flag_payloads",yn="$feature_flag_request_id",Yi="$minimal_flag_called_events",Zt="$override_feature_flags",ln="$override_feature_flag_payloads",$r="$stored_person_properties",xr="$stored_group_properties",ay="$groups",Fi="$surveys",Go="$surveys_loaded_at",cy="$surveys_activated",uy="$surveys_activated_session",ly="$surveys_activated_timestamps",Vu="ph_product_tours",b1="$product_tours_activated",w1="$product_tours_activated_session",S1="$conversations_widget_session_id",E1="$conversations_ticket_id",k1="$conversations_widget_state",I1="$conversations_user_traits",Mr="$flag_call_reported",qi="$flag_call_reported_session_id",fs="$feature_flag_errors",Ur="$feature_flag_evaluated_at",vt="$user_state",Gu="$client_session_props",A1="$capture_rate_limit",dy="$initial_campaign_params",hy="$initial_referrer_info",Bn="$initial_person_info",md="$epp",_c="$posthog_cookieless",py="$cookieless_mode",fy="$sdk_debug_extensions_init_method",vy="$sdk_debug_extensions_init_time_ms",_d="$sdk_debug_recording_script_not_loaded",yd="$sdk_debug_replay_stale_config",gy="$sdk_debug_replay_event_trigger_status",my="$sdk_debug_replay_linked_flag_trigger_status",_y="$sdk_debug_replay_matched_recording_trigger_groups",yy="$sdk_debug_replay_pending_trigger_conditions",by="$sdk_debug_replay_remote_trigger_matching_config",wy="$sdk_debug_replay_trigger_groups_count",Sy="$sdk_debug_replay_url_trigger_status",T1="$session_recording_start_reason",bd="PostHog loadExternalDependency extension not found.",pr="anonymous",_o="identified",Ey="identified_only",vs="visibilitychange",Zo="beforeunload",wd="$pageview",Hp="$pageleave",ky="$identify",Bp="$groupidentify";function Vn(e,t){ue(e)&&e.forEach(t)}function Pe(e,t){if(!fe(e))if(ue(e))e.forEach(t);else if((r=>r instanceof FormData)(e))e.forEach((r,n)=>t(r,n));else for(const r in e)ud.call(e,r)&&t(e[r],r)}var ze=function(e,...t){for(const r of t)for(const n in r)r[n]!==void 0&&(e[n]=r[n]);return e};function yo(e){const t=Object.keys(e);let r=t.length;const n=new Array(r);for(;r--;)n[r]=[t[r],e[t[r]]];return n}var R1=function(e){return function(...t){try{return e.apply(this,t)}catch(r){j.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),j.critical(r)}}},Sd=function(e){const t={};return Pe(e,function(r,n){(ye(r)&&r.length>0||Ze(r))&&(t[n]=r)}),t};function Iy(e){const t=b({},e);for(const r of["name","message","stack","cause","errors"])try{r in e&&(t[r]=e[r])}catch{}return t}var P1=["herokuapp.com","vercel.app","netlify.app"];function O1(e){const t=e?.hostname;if(!ye(t))return!1;const r=t.split(".").slice(-2).join(".");for(const n of P1)if(r===n)return!1;return!0}function Ae(e,t,r,n){const{capture:i=!1,passive:s=!0}=n??{};e?.addEventListener(t,r,{capture:i,passive:s})}function Zu(e){return e.name==="ph_toolbar_internal"}var Xi=e=>{if(D){try{const t=e+"=",r=D.cookie.split(";").filter(n=>n.length);for(let n=0;r.length>n;n++){let i=r[n];for(;i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(t)===0)return decodeURIComponent(i.substring(t.length,i.length))}}catch{}return null}};Math.trunc||(Math.trunc=function(e){return 0>e?Math.ceil(e):Math.floor(e)}),Number.isInteger||(Number.isInteger=function(e){return Ze(e)&&isFinite(e)&&Math.floor(e)===e});var C1=class Wu{constructor(t){if(this.bytes=t,t.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(t,r,n,i){if(!Number.isInteger(t)||!Number.isInteger(r)||!Number.isInteger(n)||!Number.isInteger(i)||0>t||0>r||0>n||0>i||t>0xffffffffffff||r>4095||n>1073741823||i>4294967295)throw new RangeError("invalid field value");const s=new Uint8Array(16);return s[0]=t/Math.pow(2,40),s[1]=t/Math.pow(2,32),s[2]=t/Math.pow(2,24),s[3]=t/Math.pow(2,16),s[4]=t/256,s[5]=t,s[6]=112|r>>>8,s[7]=r,s[8]=128|n>>>24,s[9]=n>>>16,s[10]=n>>>8,s[11]=n,s[12]=i>>>24,s[13]=i>>>16,s[14]=i>>>8,s[15]=i,new Wu(s)}toString(){let t="";for(let r=0;this.bytes.length>r;r++)t=t+(this.bytes[r]>>>4).toString(16)+(15&this.bytes[r]).toString(16),r!==3&&r!==5&&r!==7&&r!==9||(t+="-");if(t.length!==36)throw new Error("Invalid UUIDv7 was generated");return t}clone(){return new Wu(this.bytes.slice(0))}equals(t){return this.compareTo(t)===0}compareTo(t){for(let r=0;16>r;r++){const n=this.bytes[r]-t.bytes[r];if(n!==0)return Math.sign(n)}return 0}},$1=class{generate(){const e=this.generateOrAbort();if(!M(e))return e;{this.Ct=0;const t=this.generateOrAbort();if(M(t))throw new Error("Could not generate UUID after timestamp reset");return t}}generateOrAbort(){const e=(()=>{const t=Date.now();return Ze(t)&&isFinite(t)?Math.min(Math.max(Math.floor(t),0),0xffffffffffff):0})();if(e>this.Ct)this.Ct=e,this.Mt();else{if(this.Ct>=e+1e4)return;this.It++,this.It>4398046511103&&(this.Ct++,this.Mt())}return C1.fromFieldsV7(this.Ct,Math.trunc(this.It/Math.pow(2,30)),this.It&Math.pow(2,30)-1,this.Tt.nextUint32())}Mt(){this.It=1024*this.Tt.nextUint32()+(1023&this.Tt.nextUint32())}constructor(){this.Ct=0,this.It=0,this.Tt=new x1}},Ay=e=>{if("u">typeof UUIDV7_DENY_WEAK_RNG&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(let t=0;e.length>t;t++)e[t]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return e};A&&!M(A.crypto)&&crypto.getRandomValues&&(Ay=e=>crypto.getRandomValues(e));var x1=class{nextUint32(){return this.Rt.length>this.At||(Ay(this.Rt),this.At=0),this.Rt[this.At++]}constructor(){this.Rt=new Uint32Array(8),this.At=1/0}},Vp,Ft=()=>M1().toString(),M1=()=>(Vp||(Vp=new $1)).generate(),Pi="",L1=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,Rn=null,qe={Et(){if(!He(Rn))return Rn;if(Rn=!1,D)try{const e=`__ph_cookie_support_${Ft()}`;qe.$t(e,"xyz"),Rn=Xi(e)==='"xyz"',qe.Lt(e)}catch{Rn=!1}return Rn},Pt(e){j.error("cookieStore error: "+e)},Ot:Xi,Dt(e){let t;try{t=JSON.parse(qe.Ot(e))||{}}catch{}return t},$t(e,t,r,n,i){if(!D)return!1;try{let s="",o="";const a=(function(u,l){if(l){let h=(function(d,p=D){if(Pi)return Pi;if(!p||["localhost","127.0.0.1"].includes(d))return"";const f=d.split(".");let v=Math.min(f.length,8);const g="dmn_chk_"+Ft();for(;!Pi&&v--;){const m=f.slice(v).join("."),w=g+"=1;domain=."+m+";path=/";p.cookie=w+";max-age=3",p.cookie.includes(g)&&(p.cookie=w+";max-age=0",Pi=m)}return Pi})(u);if(!h){const d=(p=>{const f=p.match(L1);return f?f[0]:""})(u);d!==h&&j.info("Warning: cookie subdomain discovery mismatch",d,h),h=d}return h?"; domain=."+h:""}return""})(D.location.hostname,n);if(r){const u=new Date;u.setTime(u.getTime()+864e5*r),s="; expires="+u.toUTCString()}i&&(o="; secure");const c=e+"="+encodeURIComponent(JSON.stringify(t))+s+"; SameSite=Lax; path=/"+a+o;return c.length>3686.4&&j.warn("cookieStore warning: large cookie, len="+c.length),D.cookie=c,!0}catch{return!1}},Lt(e,t){if(D?.cookie&&(!t||!He(Xi(e))))try{qe.$t(e,"",-1,t)}catch{return}}},yc=null,ke={Et(){if(!He(yc))return yc;let e=!0;if(M(A))e=!1;else try{const t="__mplssupport__";ke.$t(t,"xyz"),ke.Ot(t)!=='"xyz"'&&(e=!1),ke.Lt(t)}catch{e=!1}return e||j.error("localStorage unsupported; falling back to cookie store"),yc=e,e},Pt(e){j.error("localStorage error: "+e)},Ot(e){try{return A?.localStorage.getItem(e)}catch(t){ke.Pt(t)}return null},Dt(e){try{return JSON.parse(ke.Ot(e))||{}}catch{}return null},$t(e,t){try{return A?.localStorage.setItem(e,JSON.stringify(t)),!0}catch(r){ke.Pt(r)}return!1},Lt(e){try{A?.localStorage.removeItem(e)}catch(t){ke.Pt(t)}}},bc=[$r,hr,Ut,_n,Cr,yn,Ur,fs,Mr],dn=[fd,Nt,Hn,oy,md,Bn,Jn,vt],Wo=e=>e+"_cpm",N1=["__proto__","constructor","prototype"],wc=e=>{if(!be(e))return{};const t={};return Object.keys(e).forEach(r=>{N1.indexOf(r)===-1&&(t[r]=e[r])}),t},Sc=(e,t=[])=>{const r={};return[...dn,...t].forEach(n=>{const i=e[n];M(i)||He(i)||i===""||(r[n]=i)}),r},Ty=e=>{let t=5381,r=2166136261;for(let n=0;e.length>n;n++){const i=e.charCodeAt(n);t=33*t^i,r=Math.imul(r^i,16777619)}return e.length.toString(36)+"."+(t>>>0).toString(36)+"."+(r>>>0).toString(36)},Gp=(e,t)=>({p:t,f:Ty(JSON.stringify(e))}),Zp=(e,t)=>{if(!t)return{properties:[],isValid:!1};try{const r=qe.Dt(Wo(e)),n=r?.f===Ty(t)&&ue(r.p);return{properties:n?r.p:[],isValid:n}}catch{return{properties:[],isValid:!1}}},Ec=(e,t)=>t+"|"+(qe.Ot(Wo(e))||""),Pn={},Ju={Et:()=>!0,Pt(e){j.error("memoryStorage error: "+e)},Ot:e=>e in Pn?Pn[e]:null,Dt:e=>e in Pn?Pn[e]:null,$t:(e,t)=>(Pn[e]=t,!0),Lt(e){delete Pn[e]}},tn=null,xe={Et(){if(!He(tn))return tn;if(tn=!0,M(A))tn=!1;else try{const e="__support__";xe.$t(e,"xyz"),xe.Ot(e)!=='"xyz"'&&(tn=!1),xe.Lt(e)}catch{tn=!1}return tn},Pt(e){j.error("sessionStorage error: ",e)},Ot(e){try{return A?.sessionStorage.getItem(e)}catch(t){xe.Pt(t)}return null},Dt(e){try{return JSON.parse(xe.Ot(e))||null}catch{}return null},$t(e,t){try{return A?.sessionStorage.setItem(e,JSON.stringify(t)),!0}catch(r){xe.Pt(r)}return!1},Lt(e){try{A?.sessionStorage.removeItem(e)}catch(t){xe.Pt(t)}}},D1=class{constructor(e){this._instance=e}get Ir(){return this._instance.config}get consent(){return this.Do()?0:this.Lo}isOptedOut(){return this.Ir.cookieless_mode==="always"||this.isRejected()||this.consent===-1&&this.Ir.cookieless_mode==="on_reject"}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Ir.opt_out_capturing_by_default}optInOut(e){this.No.$t(this.qo,e?1:0,this.Ir.cookie_expiration,this.Ir.cross_subdomain_cookie,this.Ir.secure_cookie)}reset(){this.No.Lt(this.qo,this.Ir.cross_subdomain_cookie)}get qo(){const{token:e,opt_out_capturing_cookie_prefix:t,consent_persistence_name:r}=this._instance.config;return r||(t?t+e:"__ph_opt_in_out_"+e)}get Lo(){const e=this.No.Ot(this.qo);return cc(e)?1:ce(c$,e)?0:-1}get No(){const e=this.Ir.opt_out_capturing_persistence_type,t=e==="localStorage"?ke:qe,r=t.Et()?t:Ju;if(!this.jo||this.jo!==r){this.jo=r;const n=e==="localStorage"?qe:ke;n.Ot(this.qo)&&(this.jo.Ot(this.qo)||this.optInOut(cc(n.Ot(this.qo))),n.Lt(this.qo,this.Ir.cross_subdomain_cookie))}return this.jo}Do(){return!!this.Ir.respect_dnt&&[rt?.doNotTrack,rt?.msDoNotTrack,re.doNotTrack,rt?.globalPrivacyControl].some(e=>cc(e))}};function Ry(e,t){var r;const n=e==null||(r=e.config)===null||r===void 0?void 0:r.get_current_url;if(!tt(n))return t;try{const i=n(t);return ye(i)&&i?i:t}catch(i){return j.error("Error in get_current_url, falling back to window.location.href",i),t}}function Wp(e){var t;return e instanceof Element&&(e.id==="__POSTHOG_TOOLBAR__"||!!(!((t=e.closest)===null||t===void 0)&&t.call(e,".toolbar-global-fade-container")))}function tr(e){return!!e&&e.nodeType===1}function ct(e,t){return!!e&&!!e.tagName&&e.tagName.toLowerCase()===t.toLowerCase()}function Py(e){return!!e&&e.nodeType===3}function Ed(e){return!!e&&e.nodeType===11&&tr(e.host)}function kd(e){return e?za(e).split(/\s+/):[]}function Jp(e,t){const r=(function(n){var i;const s=A==null||(i=A.location)===null||i===void 0?void 0:i.href;return M(s)?void 0:Ry(n,s)})(t);return!!(r&&e&&e.some(n=>r.match(n)))}function ci(e){let t="";switch(typeof e.className){case"string":t=e.className;break;case"object":t=(e.className&&"baseVal"in e.className?e.className.baseVal:null)||e.getAttribute("class")||"";break;default:t=""}return kd(t)}function Oy(e){return fe(e)?null:za(e).split(/(\s+)/).filter(t=>es(t)).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function gs(e){let t="";return Kn(e)&&!ms(e)&&e.childNodes&&e.childNodes.length&&Pe(e.childNodes,function(r){var n;Py(r)&&r.textContent&&(t+=(n=Oy(r.textContent))!==null&&n!==void 0?n:"")}),za(t)}function Qi(e){var t;return M(e.target)?e.srcElement||null:!((t=e.target)===null||t===void 0)&&t.shadowRoot?e.composedPath()[0]||null:e.target||null}var Id=["a","button","form","input","select","textarea","label"];function Ku(e,t){const r=e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector;try{return!!r&&r.call(e,t)}catch{return!1}}function Yu(e,t){if(M(t))return!0;for(const r of e)if(t.some(n=>Ku(r,n)))return!0;return!1}function Cy(e){const t=e.parentNode;return!(!t||!tr(t))&&t}var kc=[".ph-no-autocapture","[data-ph-no-autocapture]"],$y=["next","previous","prev",">","<"],z1=[...$y,"+","-","−","–"],Kp=(e,t)=>/[a-z0-9]/i.test(t)?e.includes(t):e===t,Yp=[".ph-no-rageclick",".ph-no-capture"],U1=["","text","search","email","password","url","tel","number"];function xy(e,t){if(!A||Ad(e))return!1;let r,n,i;var s,o;if(gt(t)?(r=!!t&&Yp,n=void 0,i=!1):(r=(s=t?.css_selector_ignorelist)!==null&&s!==void 0?s:Yp,n=t?.content_ignorelist,i=(o=t?.ignore_text_selection)!==null&&o!==void 0&&o),r===!1||i&&(function(c){return!(!c||!tr(c))&&(!!ct(c,"textarea")||(ct(c,"input")?ce(U1,(c.getAttribute("type")||"").toLowerCase()):(function(u){var l;if(u.isContentEditable)return!0;const h=(l=u.getAttribute)===null||l===void 0?void 0:l.call(u,"contenteditable");return h==="true"||h===""})(c)))})(e))return!1;const{targetElementList:a}=My(e,!1);return!(function(c,u){if(c===!1||M(c))return!1;let l;if(c===!0)l=$y;else{if(!ue(c))return!1;if(c.length>10)return j.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;l=c.map(h=>h.toLowerCase())}return u.some(({safeText:h,ariaLabel:d})=>l.some(p=>Kp(h,p)||Kp(d,p)))})(n,a.map(c=>{var u;return{safeText:gs(c).toLowerCase(),ariaLabel:((u=c.getAttribute("aria-label"))===null||u===void 0?void 0:u.toLowerCase().trim())||""}}))&&!Yu(a,r)}var Ad=e=>!e||ct(e,"html")||!tr(e),My=(e,t)=>{if(!A||Ad(e))return{parentIsUsefulElement:!1,targetElementList:[]};let r=!1;const n=[e];let i=e;for(;i.parentNode&&!ct(i,"body");){if(Ed(i.parentNode)){n.push(i.parentNode.host),i=i.parentNode.host;continue}const s=Cy(i);if(!s)break;if(t||Id.indexOf(s.tagName.toLowerCase())>-1)r=!0;else try{const o=A.getComputedStyle(s);o&&o.getPropertyValue("cursor")==="pointer"&&(r=!0)}catch{}n.push(s),i=s}return{parentIsUsefulElement:r,targetElementList:n}};function Kn(e){const t=new Set;let r=0;for(let s=e;s.parentNode&&!ct(s,"body");s=s.parentNode){if(r++>=1e3||t.has(s))return!1;t.add(s);const o=ci(s);if(ce(o,"ph-sensitive")||ce(o,"ph-no-capture"))return!1}if(ce(ci(e),"ph-include"))return!0;const n=e.type||"";if(ye(n))switch(n.toLowerCase()){case"hidden":case"password":return!1}const i=e.name||e.id||"";return!ye(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 ms(e){return!!(ct(e,"input")&&!["button","checkbox","submit","reset"].includes(e.type)||ct(e,"select")||ct(e,"textarea")||e.getAttribute("contenteditable")==="true")}var Xp=new RegExp("^(?:(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}))$"),Qp=/(^|[^0-9A-Za-z_])([0-9][0-9 -]*[0-9])(?=$|[^0-9A-Za-z_])/g,F1=[16,15,14,13],q1=new RegExp("^(\\d{3}-?\\d{2}-?\\d{4})$"),ef=new RegExp("(^|[^0-9])((?!000|666)[0-9]{3}-?(?!00)[0-9]{2}-?(?!0000)[0-9]{4})(?=$|([^0-9]))","g"),tf=/[0-9A-Za-z_]/;function j1(e){let t=0,r=!1;for(let n=e.length-1;n>=0;n--){let i=e.charCodeAt(n)-48;r&&(i*=2,i>9&&(i-=9)),t+=i,r=!r}return t%10==0}function es(e,t=!0){return!(fe(e)||ye(e)&&(e=za(e),(t?Xp.test((e||"").replace(/[- ]/g,"")):(function(r){let n;for(Qp.lastIndex=0;n=Qp.exec(r);){const i=n[2];if(!i)continue;const s=i.replace(/[- ]/g,"");for(let o=0;s.length>o;o++)for(const a of F1){const c=o+a;if(s.length>=c){const u=s.slice(o,c);if(Xp.test(u)&&j1(u))return!0}}}return!1})(e))||(t?q1.test(e):(function(r){let n;for(ef.lastIndex=0;n=ef.exec(r);){const i=n[1],s=n[3];if(!(i&&s&&tf.test(i)&&tf.test(s)))return!0}return!1})(e))))}function rf(e){let t=gs(e);return t=`${t} ${Ly(e)}`.trim(),es(t)?t:""}function Ly(e){let t="";return e&&e.childNodes&&e.childNodes.length&&Pe(e.childNodes,function(r){var n;if(r&&((n=r.tagName)===null||n===void 0?void 0:n.toLowerCase())==="span")try{const i=gs(r);t=`${t} ${i}`.trim(),r.childNodes&&r.childNodes.length&&(t=`${t} ${Ly(r)}`.trim())}catch(i){j.error("[AutoCapture]",i)}}),t}function nf(e){return e.replace(/"|\\"/g,'\\"')}function H1(e){const t=e.attr__class;if(t)return ue(t)?t:kd(t)}var Gs=Ve("[Dead Clicks]"),B1=()=>!0,V1=e=>{var t;const r=!!(!((t=e.instance.persistence)===null||t===void 0)&&t.get_property(vd)),n=e.instance.config.capture_dead_clicks;return gt(n)?n:!!be(n)||r},sf=class{get lazyLoadedDeadClicksAutocapture(){return this.Bo}constructor(e,t,r){this.instance=e,this.isEnabled=t,this.onCapture=r,this.startIfEnabledOrStop()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"captureDeadClicks"in t&&(this.instance.persistence&&this.instance.persistence.register({[vd]:t.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.Ho(()=>{this.zo()}):this.stop()}Ho(e){var t,r,n;!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.initDeadClicksAutocapture?e():(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this.instance,"dead-clicks-autocapture",i=>{i?Gs.error("failed to load script",i):e()})}zo(){var e;if(D){if(!this.Bo&&(!((e=re.__PosthogExtensions__)===null||e===void 0)&&e.initDeadClicksAutocapture)){const t=be(this.instance.config.capture_dead_clicks)?b({},this.instance.config.capture_dead_clicks):{};t.__onCapture=this.onCapture,this.onCapture&&(t.capture_dead_swipes=!1),this.Bo=re.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,t),this.Bo.start(D),Gs.info("starting...")}}else Gs.error("`document` not found. Cannot start.")}stop(){this.Bo&&(this.Bo.stop(),this.Bo=void 0,Gs.info("stopping..."))}},Oi=Ve("[SegmentIntegration]");function of(e,t,r=!0){const n=e.config.segment;if(!n)return t();const{analytics:i,filterProperties:s}=(a=>tt(a.register))(o=n)?{analytics:o}:o;var o;(function(a,c,u,l){const h=p=>{const f=()=>p.anonymousId()||Ft();a.config.get_device_id=f,l&&p.id()&&(a.register({distinct_id:p.id(),$device_id:f()}),a.persistence.set_property(vt,_o)),u(l?void 0:p.anonymousId()||void 0)},d=c.user();"then"in d&&tt(d.then)?d.then(h):h(d)})(e,i,a=>{i.register(((c,u,{filterProperties:l}={})=>{typeof Promise<"u"&&Promise.resolve||Oi.warn("This browser does not have Promise support, and can not use the segment integration");const h=(d,p)=>{if(!p)return d;const f=!!u&&d.event.anonymousId===u&&!d.event.userId;f||d.event.userId||d.event.anonymousId===c.get_distinct_id()||(Oi.info("No userId set, resetting PostHog"),c.reset()),f||(u=void 0),d.event.userId&&d.event.userId!==c.get_distinct_id()&&(Oi.info("UserId set, identifying with PostHog"),c.identify(d.event.userId));let v=c.calculateEventProperties(p,d.event.properties);if(!fe(l)){const g=d.event.properties||{},m={};for(const S of Object.keys(v))ud.call(g,S)||(m[S]=v[S]);const w=((S,O)=>{const R=ue(S)?S:[S];let I=b({},O);for(const C of R)try{if(I=C(I),fe(I))return null}catch(L){return Oi.error("Error in Segment filterProperties:",L),null}return I})(l,m);if(fe(w))return d;v=w}return d.event.properties=Object.assign({},v,d.event.properties),d};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded(){return!0},load(){return Promise.resolve()},track(d){return h(d,d.event.event)},page(d){return h(d,wd)},identify(d){return h(d,ky)},screen(d){return h(d,"$screen")}}})(e,a,{filterProperties:s})).then(()=>{t()},c=>{Oi.error("Failed to register the Segment integration",c),t()})},r)}var Ny="posthog-js";function Dy(e,{organization:t,projectId:r,prefix:n,severityAllowList:i=["error"],sendExceptionsToPostHog:s=!0}={}){return o=>{var a,c,u,l,h;if(i!=="*"&&!i.includes(o.level)||!e.__loaded)return o;o.tags||(o.tags={});const d=e.requestRouter.endpointFor("ui",`/project/${e.config.token}/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}));const p=((a=o.exception)===null||a===void 0?void 0:a.values)||[],f=p.map(m=>b(b({},m),{},{stacktrace:m.stacktrace?b(b({},m.stacktrace),{},{type:"raw",frames:(m.stacktrace.frames||[]).map(w=>b(b({},w),{},{platform:"web:javascript"}))}):void 0})),v={$exception_message:((c=p[0])===null||c===void 0?void 0:c.value)||o.message,$exception_type:(u=p[0])===null||u===void 0?void 0:u.type,$exception_level:o.level,$exception_list:f,$sentry_event_id:o.event_id,$sentry_exception:o.exception,$sentry_exception_message:((l=p[0])===null||l===void 0?void 0:l.value)||o.message,$sentry_exception_type:(h=p[0])===null||h===void 0?void 0:h.type,$sentry_tags:o.tags};var g;return t&&r&&(v.$sentry_url=(n||"https://sentry.io/organizations/")+t+"/issues/?project="+r+"&query="+o.event_id),s&&((g=e.exceptions)===null||g===void 0||g.sendExceptionEvent(v)),o}}var G1=class{constructor(e,t,r,n,i,s){this.name=Ny,this.setupOnce=function(o){o(Dy(e,{organization:t,projectId:r,prefix:n,severityAllowList:i,sendExceptionsToPostHog:s==null||s}))}}},af=class{constructor(e){this.Uo=(t,r,n)=>{n&&(n.noSessionId||n.activityTimeout||n.sessionPastMaximumLength||n.crossTabAdoption)&&(j.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:t,changeReason:n}),this.Wo=void 0,this._instance.scrollManager.resetContext())},this._instance=e,this.Vo()}Vo(){var e;this.Go=(e=this._instance.sessionManager)===null||e===void 0?void 0:e.onSessionId(this.Uo)}destroy(){var e;(e=this.Go)===null||e===void 0||e.call(this),this.Go=void 0}doPageView(e,t){var r;const n=this.Zo(e,t);return this.Wo={pathname:(r=A?.location.pathname)!==null&&r!==void 0?r:"",pageViewId:t,timestamp:e},this._instance.scrollManager.resetContext(),n}doPageLeave(e){var t;return this.Zo(e,(t=this.Wo)===null||t===void 0?void 0:t.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Wo)===null||e===void 0?void 0:e.pageViewId}}Zo(e,t){const r=this.Wo;if(!r)return{$pageview_id:t};let n={$pageview_id:t,$prev_pageview_id:r.pageViewId};const i=this._instance.scrollManager.getContext();if(i&&!this._instance.config.disable_scroll_properties){let{maxScrollHeight:s,lastScrollY:o,maxScrollY:a,maxContentHeight:c,lastContentY:u,maxContentY:l}=i;if(!(M(s)||M(o)||M(a)||M(c)||M(u)||M(l))){s=Math.ceil(s),o=Math.ceil(o),a=Math.ceil(a),c=Math.ceil(c),u=Math.ceil(u),l=Math.ceil(l);const h=s>1?Yt(o/s,0,1,j):1,d=s>1?Yt(a/s,0,1,j):1,p=c>1?Yt(u/c,0,1,j):1,f=c>1?Yt(l/c,0,1,j):1;n=ze(n,{$prev_pageview_last_scroll:o,$prev_pageview_last_scroll_percentage:h,$prev_pageview_max_scroll:a,$prev_pageview_max_scroll_percentage:d,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:p,$prev_pageview_max_content:l,$prev_pageview_max_content_percentage:f})}}return r.pathname&&(n.$prev_pageview_pathname=r.pathname),r.timestamp&&(n.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),n}},Ci=["flags","surveys"],Z1={[a1]:{exposure:"hidden"},[Vo]:{exposure:"hidden"},[c1]:{exposure:"hidden"},[Uu]:{exposure:"hidden"},[Jn]:{exposure:"hidden"},[Ji]:{exposure:"hidden"},[ry]:{exposure:"event"},[Fu]:{exposure:"hidden"},[iy]:{exposure:"hidden"},[qu]:{exposure:"event"},[ny]:{exposure:"hidden"},[ju]:{exposure:"event"},[Hu]:{exposure:"event"},[vd]:{exposure:"event"},[gd]:{exposure:"hidden"},[sy]:{exposure:"event"},[Ki]:{exposure:"hidden"},[u1]:{exposure:"hidden"},[Hn]:{exposure:"hidden"},[oy]:{exposure:"event"},[l1]:{exposure:"event",shouldSkipFromEventProperties:e=>He(e)},[v1]:{exposure:"event"},[g1]:{exposure:"event"},[m1]:{exposure:"event"},[_1]:{exposure:"event"},[y1]:{exposure:"hidden"},[Ut]:{exposure:"hidden",storageGroup:"flags"},[hr]:{exposure:"hidden",storageGroup:"flags"},[Bu]:{exposure:"hidden"},[_n]:{exposure:"hidden",storageGroup:"flags"},[Cr]:{exposure:"hidden",storageGroup:"flags"},[yn]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[Yi]:{exposure:"hidden",storageGroup:"flags"},[Zt]:{exposure:"hidden"},[ln]:{exposure:"hidden"},[$r]:{exposure:"hidden"},[xr]:{exposure:"hidden"},[Fi]:{exposure:"hidden",storageGroup:"surveys"},[Go]:{exposure:"hidden",storageGroup:"surveys",volatile:!0},[cy]:{exposure:"event"},[uy]:{exposure:"hidden"},[ly]:{exposure:"hidden"},[Vu]:{exposure:"hidden"},[b1]:{exposure:"hidden"},[w1]:{exposure:"hidden"},[S1]:{exposure:"event"},[E1]:{exposure:"event"},[k1]:{exposure:"event"},[I1]:{exposure:"event"},[Mr]:{exposure:"hidden"},[qi]:{exposure:"hidden"},[ay]:{exposure:"event"},[fs]:{exposure:"hidden"},[Ur]:{exposure:"hidden",storageGroup:"flags",volatile:!0},[vt]:{exposure:"hidden"},[Gu]:{exposure:"hidden"},[A1]:{exposure:"hidden"},[dy]:{exposure:"hidden"},[hy]:{exposure:"hidden"},[Bn]:{exposure:"hidden"},[md]:{exposure:"hidden"},[d1]:{exposure:"event"},[h1]:{exposure:"event"},[p1]:{exposure:"event"},[f1]:{exposure:"event"},[fy]:{exposure:"event"},[vy]:{exposure:"event"},[_d]:{exposure:"hidden"},[yd]:{exposure:"hidden"},[gy]:{exposure:"hidden"},[my]:{exposure:"hidden"},[_y]:{exposure:"hidden"},[yy]:{exposure:"hidden"},[by]:{exposure:"hidden"},[wy]:{exposure:"hidden"},[Sy]:{exposure:"hidden"},[T1]:{exposure:"event"}},W1=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],ot=e=>{const t=Z1[e];if(t)return t;for(const[r,n]of W1)if(e.indexOf(r)===0)return n},Gn=(e,t)=>{try{let r;return JSON.stringify(e,(n,i)=>{var s;return yi(i)?((s=r)!==null&&s!==void 0||(r=new WeakMap),r.has(i)||r.set(i,Iy(i)),r.get(i)):typeof i=="bigint"?i.toString():i},t)}catch{return n_(e)}},_r=e=>{const t=D?.createElement("a");return M(t)?null:(t.href=e,t)},ui=function(e,t){const r=((e.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&");let n;for(let i=0;r.length>i;i++){const s=r[i].split("=");if(s[0]===t){n=s;break}}if(!ue(n)||2>n.length)return"";{let i=n[1];try{i=decodeURIComponent(i)}catch{j.error("Skipping decoding for malformed query param: "+i)}return i.replace(/\+/g," ")}},_s=function(e,t,r){if(!e||!t||!t.length)return e;const n=e.split("#"),i=n[1],s=(n[0]||"").split("?"),o=s[1],a=s[0],c=(o||"").split("&"),u=[];for(let h=0;c.length>h;h++){const d=c[h].split("=");ue(d)&&(t.includes(d[0])?u.push(d[0]+"="+r):u.push(c[h]))}let l=a;return o!=null&&(l+="?"+u.join("&")),i!=null&&(l+="#"+i),l},Jo=function(e,t){const r=e.match(new RegExp(t+"=([^&]*)"));return r?r[1]:null},zy=(e,t)=>e>=t&&r_(),Uy=(e,t,r,n)=>{if(e===0){if(r_()){const i=t+1;return i===r&&n(),i}return t}return 0},li=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],J1=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...li],ys="<masked>",K1=["li_fat_id"];function Fy(e,t,r){if(!D)return{};const n=t?[...li,...r||[]]:[],i=qy(_s(D.URL,n,ys),e),s=(function(){const o={};return Pe(K1,function(a){const c=Xi(a);o[a]=c||null}),o})();return ze(s,i)}function qy(e,t){const r=J1.concat(t||[]),n={};return Pe(r,function(i){const s=ui(e,i);n[i]=s||null}),n}function jy(e){const t=(function(i){return i?i.search("https?://(.*)google.([^/?]*)")===0?"google":i.search("https?://(.*)bing.com")===0?"bing":i.search("https?://(.*)yahoo.com")===0?"yahoo":i.search("https?://(.*)duckduckgo.com")===0?"duckduckgo":null:null})(e),r=t!="yahoo"?"q":"p",n={};if(!He(t)){n.$search_engine=t;const i=D?ui(D.referrer,r):"";i.length&&(n.ph_keyword=i)}return n}function Hy(){return navigator.language||navigator.userLanguage}function Y1(){const e=Hy();return typeof e=="string"?e.split("-")[0]:void 0}var Ko="$direct";function By(){return D?.referrer||Ko}function Vy(e,t,r=!1){const n=e?[...li,...t||[]]:[],i=r?Jr(je?.href):je?.href,s=i?.substring(0,1e3);return{r:By().substring(0,1e3),u:s?_s(s,n,ys):void 0}}function Gy(e,t=!1){var r;const{r:n,u:i}=e,s=t?Jr(i):i,o={$referrer:n,$referring_domain:n==null?void 0:n==Ko?Ko:(r=_r(n))===null||r===void 0?void 0:r.host};if(s){o.$current_url=s;const a=_r(s);o.$host=a?.host,o.$pathname=a?.pathname;const c=qy(s);ze(o,c)}if(n){const a=jy(n);ze(o,a)}return o}function Zy(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function X1(){try{return new Date().getTimezoneOffset()}catch{return}}var Q1={flags:Ur,surveys:Go},ex=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"],Zs=e=>`${e}_cookie_identity_change_pending`,Ws=e=>{let t="",r=0;for(const n of e){const i=encodeURIComponent(JSON.stringify(n).slice(1,-1)).length;if(r+i>1e3)break;t+=n,r+=i}return t},Qe="main",lr=[Ut,hr,_n,Cr,yn,Ur,Yi,$r],Ic=e=>lr.indexOf(e)!==-1,Wy=[Jn,Ji],cf=e=>Wy.indexOf(e)!==-1,yr=(e,t)=>{try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}},On=e=>{if(!e)return{};const t=JSON.parse(e);return be(t)?t:{}},uf=(e,t)=>{Pe(e,(r,n)=>{const i=ot(n);i&&i.exposure!=="event"||{}.hasOwnProperty.call(t,n)||delete e[n]})},Ac=class{constructor(e,t,r=!0){if(this.Qo={},this.Jo=!1,this.Ko=!1,this.Xo=!1,this.Yo=!1,this.ta=!1,this.ea=new Map,this.ia=!1,this.na=!1,this.sa=!1,this.ra=new Set,this.oa=new Set,this.Ir=e,this.aa=r,this.props={},this.la=void 0,this.ua=(n=>{let i="";return n.token&&(i=n.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),n.persistence_name?"ph_"+n.persistence_name:"ph_"+i+"_posthog"})(e),this.hi=e.disable_persistence||!!t,this.No=this.ha(e),this.Xo=this.ca(e),this.load(),this.da(),e.debug&&j.info("Persistence loaded",e.persistence,b({},this.props)),this.update_config(e,e,t),this.save(),A){const n=()=>this.flush();Ae(A,"beforeunload",n,{capture:!1}),Ae(A,"pagehide",n,{capture:!1}),this.va=i=>{if(this.Jo&&(!i.storageArea||i.storageArea===A?.localStorage)&&i.key)if(i.key!==this.ua){if(this.Xo){const s=Ci.find(o=>i.key===this.fa(o));s&&this.pa(i.key,s)}}else this.pa(i.key,Qe)},Ae(A,"storage",this.va)}}markCrossTabFeatureFlagChanges(e){Object.entries(e).forEach(([t,r])=>{const n=this.ea.get(t);if(!Ic(t)||n===!0)return;if(r===!0)return void this.ga(t,!0);const i=new Set(n||[]);r.forEach(s=>i.add(s)),i.size&&this.ga(t,i)})}onCrossTabFeatureFlagChange(e){return this.oa.add(e),()=>this.oa.delete(e)}destroy(){this.va&&A&&(A.removeEventListener("storage",this.va),this.va=void 0),this.oa.clear()}pa(e,t,r=!0){if(this.hi)return!1;let n,i;try{if(i=ke.Ot(e),He(i)){const a=this.ma(t);return a.storageValue=null,t!==Qe&&(a.persisted=!1),!1}n=On(i)}catch{return!1}const s=t===Qe?n:ke.Dt(this.ua);if(s&&this.ya(s))return!1;const o=this.ba(n,t,r);return t===Qe&&this.Xo&&!yr(this._a().main,n)||this.wa(n,t,!0,i),o}ya(e){const t=this.props[Nt],r=e[Nt];return!M(t)&&!M(r)&&t!==r}wa(e,t,r,n){const i=this.ma(t);i.storageValue=n,t!==Qe&&(i.persisted=r);try{i.fingerprint=this.ka(e,t)}catch{i.fingerprint=void 0}}ba(e,t,r){let n=!1;return lr.forEach(i=>{var s;const o=(s=ot(i))===null||s===void 0?void 0:s.storageGroup;if(t===Qe&&this.Xo&&o||t!==Qe&&o!==t)return;const a=i in e,c=this.Sa(i,a?e[i]:void 0),u=this.ea.has(i)?i in this.props:a;u===i in this.props&&yr(c,this.props[i])||(u?this.xa(i,c,!1):this.Ca(i,!1),n=!0)}),n&&r&&this.oa.forEach(i=>i()),n}$a(){if(!this.Jo)return!1;try{this.sa=!1;const e=ke.Ot(this.ua),t=this.ma(Qe);let r,n=!1,i=!1;if(e!==t.storageValue)if(He(e))t.storageValue=null;else{if(r=On(e),this.sa=!this.na&&this.ya(r),this.sa)return!1;i=this.ba(r,Qe,!1),!this.Xo||yr(this._a().main,r)?this.wa(r,Qe,!0,e):t.storageValue=e,n=!0}return this.Xo&&Ci.forEach(s=>{const o=ke.Ot(this.fa(s)),a=this.ma(s),c=r||{},u=n&&lr.some(h=>{var d;return((d=ot(h))===null||d===void 0?void 0:d.storageGroup)===s&&h in c});if(o===a.storageValue&&!u)return;if(He(o))return a.storageValue=null,a.persisted=!1,void(u&&(i=this.ba(c,s,!1)||i));const l=On(o);i=this.ba(l,s,!1)||i,this.wa(l,s,!0,o)}),i}catch{return!1}}ga(e,t){this.ea.set(e,t);const r=ot(e);r!=null&&r.volatile||(this.ma((this.Xo?r?.storageGroup:void 0)||Qe).fingerprint=void 0,this.Ta(e))}Ia(){lr.forEach(e=>this.ea.set(e,!0))}da(){if(this.Jo)try{const e=ke.Ot(this.ua),t=On(e);this.ma(Qe).storageValue=e,lr.forEach(r=>{var n;const i=this.Xo?(n=ot(r))===null||n===void 0?void 0:n.storageGroup:void 0,s=i?ke.Ot(this.fa(i)):null;if(i){const a=this.ma(i);a.storageValue=s,a.persisted=!He(s)}const o=i&&!He(s)?On(s):t;r in this.props?this.Ma(r,o[r],this.props[r]):r in o&&this.ga(r,!0)})}catch{}}Sa(e,t){const r=this.ea.get(e);if(!r)return t;if(r===!0)return this.props[e];if(e==="$active_feature_flags"){const s=new Set(ue(t)?t:[]),o=new Set(ue(this.props[e])?this.props[e]:[]);return r.forEach(a=>o.has(a)?s.add(a):s.delete(a)),Array.from(s)}const n=be(t)?b({},t):{},i=be(this.props[e])?this.props[e]:{};return r.forEach(s=>{s in i?n[s]=i[s]:delete n[s]}),n}Ma(e,t,r){if(!Ic(e))return;const n=this.ea.get(e);if(n===!0)return;let i=t;if(this.Jo)try{var s;const a=this.Xo?(s=ot(e))===null||s===void 0?void 0:s.storageGroup:void 0,c=a?this.fa(a):this.ua;i=On(ke.Ot(c))[e]}catch{}const o=new Set(n||[]);if(e==="$active_feature_flags"){if(!M(t)&&!ue(t)||!M(i)&&!ue(i)||!ue(r))return void this.ga(e,!0);const a=new Set(t||[]),c=new Set(i||[]),u=new Set(r);new Set([...a,...u]).forEach(l=>{a.has(l)!==u.has(l)&&o.add(l)}),o.forEach(l=>{c.has(l)===u.has(l)&&o.delete(l)})}else{if(!be(r))return void(yr(i,r)?this.ea.delete(e):this.ga(e,!0));{if(!M(t)&&!be(t)||M(t)&&bt(r)&&M(i))return void this.ga(e,!0);const a=be(t)?t:{},c=be(i)?i:{};new Set([...Object.keys(a),...Object.keys(r)]).forEach(u=>{u in a==u in r&&yr(a[u],r[u])||o.add(u)}),o.forEach(u=>{u in c==u in r&&yr(c[u],r[u])&&o.delete(u)})}}o.size?this.ga(e,o):this.ea.delete(e)}Ea(){var e;const t=(e=this.Ir)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return Ze(t)&&t>0?t:0}Pa(e){if(this.Ir.cookieWinsOnConflict&&this.Ir.persistence.toLowerCase()==="localstorage+cookie")if(e)try{const t=Sc(e,this.Ir.cookie_persisted_properties||[]),r=Gp(t,this.Ir.cookie_persisted_properties||[]),n=JSON.stringify(t)+"|"+JSON.stringify(r),i=qe.Ot(this.ua)||void 0;i&&Ec(this.ua,i)===n&&(this.Ra=n,this.Aa=i)}catch{}else try{const t=qe.Ot(this.ua)||void 0;this.Ra=t?Ec(this.ua,t):void 0,this.Aa=t}catch{}}syncCookieProperties(){return this.Fa(this.Ir)}Fa(e,t=!1){if(this.hi&&!t||this.ta||!e.cookieWinsOnConflict||e.persistence.toLowerCase()!=="localstorage+cookie")return!1;let r;try{r=qe.Ot(this.ua)||void 0}catch{}if(!r||r===this.Aa)return!1;const n=Ec(this.ua,r);let i;try{i=wc(JSON.parse(r))}catch{return!1}if((qe.Ot(this.ua)||void 0)!==r)return!1;this.Ra=n,this.Aa=r;const s=Zp(this.ua,r),o=[...dn,...s.properties],a={};if(Object.keys(i).forEach(v=>{const g=i[v];(M(g)||He(g)||g===""||v==="$user_state"&&g!=="anonymous"&&g!=="identified")&&(a[v]=!0,delete i[v])}),bt(i))return!1;const c="distinct_id"in i||i.$user_state==="anonymous"||i.$user_state==="identified",u=this.props,l=u[Nt],h=u[vt],d=ze({},u);[...dn,...e.cookie_persisted_properties||[]].forEach(v=>{if(o.indexOf(v)!==-1&&!(v in i)&&!a[v]&&(c||v!=="distinct_id"&&v!=="$user_state")){const g=d[v];(s.isValid||dn.indexOf(v)===-1||g!==!1&&g!==0)&&delete d[v]}}),this.props=ze(d,i),lr.forEach(v=>{const g=v in this.props;v in u===g&&yr(u[v],this.props[v])||(g?this.Ma(v,u[v],this.props[v]):this.ga(v,!0))}),!c||"$user_state"in i||"$user_state"in this.props||this.xa(vt,pr);const p=this.props[Nt],f=this.props[vt];return!c||p===l&&f===h||(this.na=!0,this.Yo=!0,xe.$t(Zs(this.ua),!0),this.Ca($r),this.Ca(hr),this.Ca(Ut),this.Ca(_n),this.Ca(Cr),this.Ca(yn),this.Ca(Ur),this.Ca(fs),this.Ca(Mr),f!=="anonymous"||h!=="identified"&&i.$user_state!=="anonymous"&&(M(l)||p===l)||(uf(this.props,i),this.Ca(xr)),f==="identified"?this.props.$user_id=p:delete this.props.$user_id,this.Ca(Vo)),!0}consumeCookieIdentityChange(){const e=Zs(this.ua),t=this.Yo||!!xe.Ot(e);return this.Yo=!1,t&&xe.Lt(e),t}Oa(e=!1){return!(this.ta||this.hi&&!e||!this.Ir.cookieWinsOnConflict||this.Ir.persistence.toLowerCase()!=="localstorage+cookie"||(this.ta=!0,0))}Da(){this.ta&&(M(this.La)||(clearTimeout(this.La),this.La=void 0),delete this.Qo[Qe],this.Na(!0))}qa(e=!0){if(this.ta)try{e?this.Da():M(this.La)||(clearTimeout(this.La),this.La=void 0)}finally{this.ta=!1}}isDisabled(){return!!this.hi}ha(e){ex.indexOf(e.persistence.toLowerCase())===-1&&(j.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");const t=((o=[],a=!1)=>{const c=[...dn,...o];return b(b({},ke),{},{Dt(u){try{let h,d={};try{h=qe.Ot(u)||void 0,d=h?wc(JSON.parse(h)):{}}catch{}const p=JSON.parse(ke.Ot(u)||"{}");let f;if(a){const v=Zp(u,h),g=[...dn,...v.properties],m={};Object.keys(d).forEach(S=>{const O=d[S];He(O)||O===""||S==="$user_state"&&O!=="anonymous"&&O!=="identified"||(m[S]=O)});const w="distinct_id"in m||m.$user_state==="anonymous"||m.$user_state==="identified";if(Object.keys(m).length>0){var l;const S=p[Nt],O=(l=p.$user_state)!==null&&l!==void 0?l:pr;c.forEach(R=>{if(g.indexOf(R)!==-1&&!(R in d)&&(w||R!=="distinct_id"&&R!=="$user_state")){const I=p[R];(v.isValid||dn.indexOf(R)===-1||I!==!1&&I!==0)&&delete p[R]}}),!w||"$user_state"in d||"$user_state"in p||(p[vt]=pr),!w||("distinct_id"in m?m[Nt]:p[Nt])===S&&("$user_state"in m?m[vt]:p[vt])===O||(bc.forEach(R=>delete p[R]),m.$user_state==="identified"&&"distinct_id"in m?p.$user_id=m[Nt]:delete p.$user_id,m.$user_state!=="identified"&&(delete p[ay],delete p[xr]),delete p.__alias)}f=ze(p,m)}else f=ze(d,p);return ke.$t(u,f),f}catch{}return null},$t(u,l,h,d,p,f){const v=ke.$t(u,l,void 0,void 0,f);try{const g=Sc(l,o);if(Object.keys(g).length){if(a){const m=Wo(u),w=Gp(g,o);if(qe.$t(m,w,h,d,p,f),qe.Ot(m)!==JSON.stringify(w)){qe.Lt(m,d);const S=Sc(l);return qe.$t(u,S,h,d,p,f),v}}qe.$t(u,g,h,d,p,f)}}catch(g){ke.Pt(g)}return v},Lt(u,l){try{A?.localStorage.removeItem(u),qe.Lt(u,l),qe.Lt(Wo(u),l)}catch(h){ke.Pt(h)}}})})(e.cookie_persisted_properties||[],e.cookieWinsOnConflict);let r,n=!1,i=!1;const s=e.persistence.toLowerCase();return s==="localstorage"&&ke.Et()?(r=ke,i=!0):s==="localstorage+cookie"&&t.Et()?(r=t,i=!0,n=!0):s==="sessionstorage"&&xe.Et()?r=xe:s==="memory"?r=Ju:s==="cookie"&&qe.Et()?(r=qe,n=!0):t.Et()?(r=t,i=!0,n=!0):qe.Et()?(r=qe,n=!0):r=Ju,this.Jo=i,this.Ko=n,r}fa(e){return`${this.ua}__${e}`}ca(e){return this.Jo&&!!e.split_storage}properties(){const e={};return Pe(this.props,(t,r)=>{const n=ot(r);if(!n||n.exposure==="event"){var i;if(!(n==null||(i=n.shouldSkipFromEventProperties)===null||i===void 0)&&i.call(n,t))return;e[r]=t}}),e}load(e=!1){if(this.hi&&!e)return;const t=this.Ir.cookieWinsOnConflict&&this.Ir.persistence.toLowerCase()==="localstorage+cookie",r=t?ke.Dt(this.ua):null;let n={};if(t)try{n=wc(qe.Dt(this.ua)),Pe(n,(a,c)=>{(M(a)||He(a)||a==="")&&delete n[c]})}catch{}const i=this.No.Dt(this.ua);if(i&&(this.props=ze({},i)),this.Xo&&this.ja(),t&&i){var s,o;const a=r?.[Nt],c=(s=r?.$user_state)!==null&&s!==void 0?s:pr,u=i[Nt],l=(o=i.$user_state)!==null&&o!==void 0?o:pr;if(u!==a||l!==c){this.Yo=!0,xe.$t(Zs(this.ua),!0);const h=ze({},this.props);bc.forEach(p=>delete h[p]),l!=="anonymous"||c!=="identified"&&n.$user_state!=="anonymous"&&(M(a)||u===a)||(uf(h,n),delete h[xr]),this.props=h;const d=new Set;bc.forEach(p=>{var f;const v=(f=ot(p))===null||f===void 0?void 0:f.storageGroup;v&&d.add(v)}),d.forEach(p=>{const f={};Pe(this.props,(v,g)=>{var m;((m=ot(g))===null||m===void 0?void 0:m.storageGroup)===p&&(f[g]=v)}),bt(f)?(ke.Lt(this.fa(p)),this.Qo[p]={}):ke.$t(this.fa(p),f)&&(this.Qo[p]={persisted:!0,fingerprint:this.ka(f,p)})})}}xe.Ot(Zs(this.ua))&&(this.Yo=!0)}ja(){for(const e of Ci){const t=ke.Dt(this.fa(e));if(t&&!bt(t)){const r=this.ma(e);r.persisted=!0,this.Ba(e)||(r.fingerprint=this.ka(t,e)),this.Ha(e,t)||ze(this.props,t)}}}Ba(e){return Object.keys(this.props).some(t=>{var r;return((r=ot(t))===null||r===void 0?void 0:r.storageGroup)===e})}Ha(e,t){const r=Q1[e];if(!r)return!1;const n=t[r],i=this.props[r];return Ze(n)&&Ze(i)&&i>n}refreshKey(e){var t;if(this.hi||this.ra.has(e))return;const r=this.Xo?(t=ot(e))===null||t===void 0?void 0:t.storageGroup:void 0,n=r?ke.Dt(this.fa(r)):this.No.Dt(this.ua);if(n&&e in n)this.xa(e,n[e],!1);else{if(r){const i=this.No.Dt(this.ua);if(i&&e in i)return void this.xa(e,i[e],!1)}this.Ca(e,!1)}}save(){if(this.hi)return;const e=this.Ea();e>0?M(this.La)&&(this.La=setTimeout(()=>{this.La=void 0,this.Na()},e)):this.Na()}flush(){M(this.La)||(clearTimeout(this.La),this.La=void 0,this.Na())}Na(e=!1){if(this.hi||this.ta&&!e)return;e||(this.syncCookieProperties(),this.Ir.cookieWinsOnConflict&&this.Ir.persistence.toLowerCase()==="localstorage+cookie"||Wy.forEach(i=>this.refreshKey(i)));const t=!e&&!this.ia;t||(this.sa=!1);const r=!!t&&this.$a();if(this.sa)return void(this.Ir.debug&&j.warn("skipping persistence write because storage belongs to a different distinct ID"));if(this.Xo)return this.za(),void(r&&this.oa.forEach(i=>i()));const n=this.Ua(this.No,this.ua,this.props,Qe);n==="written"&&this.Pa(this.props),n!=="failed"&&(this.ea.clear(),this.na=!1,this.ra.clear()),r&&this.oa.forEach(i=>i())}za(){const{main:e,groups:t}=this._a(),r=this.Ua(this.No,this.ua,e,Qe);r==="written"&&this.Pa(e),r!=="failed"&&(this.na=!1,this.ra.clear(),lr.forEach(i=>{var s;(s=ot(i))!==null&&s!==void 0&&s.storageGroup||this.ea.delete(i)}));for(const i of Ci){var n;const s=t[i];if(bt(s)&&!(!((n=this.Qo[i])===null||n===void 0)&&n.persisted)){lr.forEach(a=>{var c;((c=ot(a))===null||c===void 0?void 0:c.storageGroup)===i&&this.ea.delete(a)});continue}const o=this.Ua(ke,this.fa(i),s,i);o!=="failed"&&lr.forEach(a=>{const c=ot(a);c?.storageGroup!==i||o!=="written"&&c.volatile||this.ea.delete(a)})}}_a(){const e={},t={flags:{},surveys:{}};return Pe(this.props,(r,n)=>{var i;const s=(i=ot(n))===null||i===void 0?void 0:i.storageGroup;s?t[s][n]=r:e[n]=r}),{main:e,groups:t}}ka(e,t){if(t===Qe)return JSON.stringify(e)+"|"+this.Wa+"|"+this.Va+"|"+this.Ga;const r={};return Pe(e,(n,i)=>{var s;r[i]=!((s=ot(i))===null||s===void 0)&&s.volatile?"__volatile__":n}),JSON.stringify(r)}Ua(e,t,r,n){const i=this.ma(n);if(n!==Qe&&!i.dirty&&!M(i.fingerprint))return"skipped";let s;try{if(s=this.ka(r,n),s===i.fingerprint)return i.dirty=!1,"skipped"}catch{s=void 0}return e.$t(t,r,this.Wa,this.Va,this.Ga,this.Ir.debug)?(i.dirty=!1,n!==Qe&&(i.persisted=!0),M(s)||(i.fingerprint=s),this.Jo&&(i.storageValue=ke.Ot(t)),"written"):(this.Ir.debug&&j.warn(`failed to persist storage entry "${t}"; will retry on next save`),"failed")}remove({keepGroupEntries:e=!1}={}){if(this.Ia(),M(this.La)||(clearTimeout(this.La),this.La=void 0),this.No.Lt(this.ua,!1),this.No.Lt(this.ua,!0),!e&&this.aa)for(const t of Ci)ke.Lt(this.fa(t));e?delete this.Qo[Qe]:this.Qo={},this.Ra=void 0,this.Aa=void 0}clear(){this.remove(),this.props={}}register_once(e,t,r){if(be(e)){this.syncCookieProperties(),M(t)&&(t="None"),this.Wa=M(r)?this.Za:r;let n=!1;if(Pe(e,(i,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==t||(this.xa(s,i),n=!0)}),n)return this.save(),!0}return!1}register(e,t){if(be(e)){this.syncCookieProperties(),this.Wa=M(t)?this.Za:t;let r=!1;if(Pe(e,(n,i)=>{e.hasOwnProperty(i)&&(this.props[i]!==n||be(n)||ue(n))&&(this.xa(i,n),r=!0)}),r)return this.save(),!0}return!1}unregister(e){this.syncCookieProperties();const t=typeof e=="string"?[e]:e;let r=!1;for(const n of t)n in this.props&&(this.Ca(n),r=!0);r&&this.save()}update_campaign_params(){const e=D?.URL;if(e===this.la)return;const t=Fy(this.Ir.custom_campaign_params,this.Ir.mask_personal_data_properties,this.Ir.custom_personal_data_properties),r=!bt(Sd(t));return r&&this.register(t),this.la=e,r?t:void 0}update_search_keyword(){this.register((function(){const e=D?.referrer;return e?jy(e):{}})())}update_referrer_info(){var e;this.register_once({$referrer:By(),$referring_domain:D?.referrer&&((e=_r(D.referrer))===null||e===void 0?void 0:e.host)||Ko},void 0)}set_initial_person_info(){if(this.props.$initial_campaign_params||this.props.$initial_referrer_info)return;const e=Vy(this.Ir.mask_personal_data_properties,this.Ir.custom_personal_data_properties,this.Ir.disable_capture_url_hashes);this.register_once({[Bn]:this.Ko?{r:Ws(e.r),u:e.u?Ws(e.u):void 0}:e},void 0)}get_initial_props(){const e={};Pe([hy,dy],r=>{const n=this.props[r];n&&Pe(n,function(i,s){e["$initial_"+Cu(s)]=i})});const t=this.props[Bn];if(t){const r=(function(n,i=!1){const s=Gy(n,i),o={};return Pe(s,function(a,c){o[`$initial_${Cu(c)}`]=a}),o})(t,this.Ir.disable_capture_url_hashes);ze(e,r)}return e}safe_merge(e){return Pe(this.props,function(t,r){r in e||(e[r]=t)}),e}update_config(e,t,r){const n=e.persistence!==t.persistence,i=!((p,f)=>{if(p.length!==f.length)return!1;const v=[...p].sort(),g=[...f].sort();return v.every((m,w)=>m===g[w])})(e.cookie_persisted_properties||[],t.cookie_persisted_properties||[]),s=n||i,o=e.cookieWinsOnConflict!==t.cookieWinsOnConflict,a=e.disable_persistence||!!r,c=!!this.hi&&!a;a||this.Fa(t,c),this.Ir=e,!a&&(n||i||o)&&(this.Ra=void 0,this.Aa=void 0,this.Fa(b(b({},e),{},{cookie_persisted_properties:t.cookie_persisted_properties}),c));const u=s||o?this.ha(e):this.No;this.Qa();const l=this.ca(e),h=s||l!==this.Xo,d=!a&&(h||e.cross_subdomain_cookie!==this.Va||e.secure_cookie!==this.Ga)&&this.Oa(c);this.ia=h;try{if(this.Za=this.Wa=e.cookie_expiration,this.set_disabled(a),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),h){const p=this.props;this.clear(),this.No=u,this.Xo=l,this.props=p,this.save()}else o&&(this.No=u,a||(delete this.Qo[Qe],this.Na()))}finally{this.ia=!1,d&&this.qa()}}Qa(){const e=this.props[Bn];if(!this.Ko||!be(e)||typeof e.r!="string")return;const t=Ws(e.r),r=typeof e.u=="string"?Ws(e.u):e.u;t===e.r&&r===e.u||this.xa(Bn,b(b({},e),{},{r:t,u:r}))}set_disabled(e){this.hi=e,this.hi?this.remove():this.save()}set_cross_subdomain(e){e!==this.Va&&(this.Va=e,this.remove({keepGroupEntries:!0}),this.save())}set_secure(e){e!==this.Ga&&(this.Ga=e,this.remove({keepGroupEntries:!0}),this.save())}set_event_timer(e,t){const r=this.props.__timers||{};r[e]=t,this.xa(Uu,r),this.save()}remove_event_timer(e){const t=this.props.__timers||{},r=t[e];return M(r)||(delete t[e],this.xa(Uu,t),this.save()),r}get_property(e){return this.props[e]}set_property(e,t){this.xa(e,t),this.save()}xa(e,t,r=!0){var n;const i=this.props[e];this.props[e]=t,r&&(e!=="distinct_id"&&e!=="$user_state"||i===t||(this.na=!0),cf(e)&&!yr(i,t)&&this.ra.add(e),this.Ma(e,i,t),(n=ot(e))!==null&&n!==void 0&&n.volatile||this.Ta(e))}Ca(e,t=!0){delete this.props[e],t&&(Ic(e)&&this.ga(e,!0),cf(e)&&this.ra.add(e),this.Ta(e))}Ta(e){var t;const r=(t=ot(e))===null||t===void 0?void 0:t.storageGroup;r&&(this.ma(r).dirty=!0)}ma(e){return this.Qo[e]||(this.Qo[e]={})}},It={GZipJS:"gzip-js",Base64:"base64"},$i={Activation:"events",Cancellation:"cancelEvents"},Tc={Popover:"popover",API:"api",Widget:"widget",ExternalSurvey:"external_survey"},Et={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent",ABANDONED:"survey abandoned"},Rc={SURVEY_ID:"$survey_id",SURVEY_NAME:"$survey_name",SURVEY_RESPONSE:"$survey_response",SURVEY_ITERATION:"$survey_iteration",SURVEY_ITERATION_START_DATE:"$survey_iteration_start_date",SURVEY_PARTIALLY_COMPLETED:"$survey_partially_completed",SURVEY_SUBMISSION_ID:"$survey_submission_id",SURVEY_QUESTIONS:"$survey_questions",SURVEY_COMPLETED:"$survey_completed",PRODUCT_TOUR_ID:"$product_tour_id",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date",SURVEY_LANGUAGE:"$survey_language"},Xu={Popover:"popover",Inline:"inline"};function Js(e){let t=!0;return{dispose(){if(t){t=!1;const r=e();r&&tt(r.then)&&r.then(void 0,()=>{})}}}}var tx={SHOWN:"product tour shown",DISMISSED:"product tour dismissed",COMPLETED:"product tour completed",STEP_SHOWN:"product tour step shown",STEP_COMPLETED:"product tour step completed",BUTTON_CLICKED:"product tour button clicked",STEP_SELECTOR_FAILED:"product tour step selector failed",BANNER_CONTAINER_SELECTOR_FAILED:"product tour banner container selector failed",BANNER_ACTION_CLICKED:"product tour banner action clicked"},lf={TOUR_ID:"$product_tour_id",TOUR_NAME:"$product_tour_name",TOUR_ITERATION:"$product_tour_iteration",TOUR_RENDER_REASON:"$product_tour_render_reason",TOUR_STEP_ID:"$product_tour_step_id",TOUR_STEP_ORDER:"$product_tour_step_order",TOUR_STEP_TYPE:"$product_tour_step_type",TOUR_DISMISS_REASON:"$product_tour_dismiss_reason",TOUR_BUTTON_TEXT:"$product_tour_button_text",TOUR_BUTTON_ACTION:"$product_tour_button_action",TOUR_BUTTON_LINK:"$product_tour_button_link",TOUR_BUTTON_TOUR_ID:"$product_tour_button_tour_id",TOUR_STEPS_COUNT:"$product_tour_steps_count",TOUR_STEP_SELECTOR:"$product_tour_step_selector",TOUR_STEP_SELECTOR_FOUND:"$product_tour_step_selector_found",TOUR_STEP_ELEMENT_TAG:"$product_tour_step_element_tag",TOUR_STEP_ELEMENT_ID:"$product_tour_step_element_id",TOUR_STEP_ELEMENT_CLASSES:"$product_tour_step_element_classes",TOUR_STEP_ELEMENT_TEXT:"$product_tour_step_element_text",TOUR_ERROR:"$product_tour_error",TOUR_MATCHES_COUNT:"$product_tour_matches_count",TOUR_FAILURE_PHASE:"$product_tour_failure_phase",TOUR_WAITED_FOR_ELEMENT:"$product_tour_waited_for_element",TOUR_WAIT_DURATION_MS:"$product_tour_wait_duration_ms",TOUR_BANNER_SELECTOR:"$product_tour_banner_selector",TOUR_LINKED_SURVEY_ID:"$product_tour_linked_survey_id",USE_MANUAL_SELECTOR:"$use_manual_selector",INFERENCE_DATA_PRESENT:"$inference_data_present",TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},df=Ve("[RateLimiter]"),rx=class{constructor(e){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=t=>{const r=t.text;if(r&&r.length)try{(JSON.parse(r).quota_limited||[]).forEach(n=>{df.info(`${n||"events"} is quota limited.`),this.serverLimits[n]=new Date().getTime()+6e4})}catch(n){df.warn(`could not rate limit - continuing. Error: "${n?.message}"`,{text:r});return}},this.instance=e,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var e;return((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_per_second)||10}get captureEventsBurstLimit(){var e;return Math.max(((e=this.instance.config.rate_limiting)===null||e===void 0?void 0:e.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext(e=!1){var t,r,n;const{captureEventsBurstLimit:i,captureEventsPerSecond:s}=this,o=new Date().getTime(),a=(t=(r=this.instance.persistence)===null||r===void 0?void 0:r.get_property("$capture_rate_limit"))!==null&&t!==void 0?t:{tokens:i,last:o};a.tokens+=(o-a.last)/1e3*s,a.last=o,a.tokens>i&&(a.tokens=i);const c=1>a.tokens;if(c||e||(a.tokens=Math.max(0,a.tokens-1)),c&&!e){const u=(Ze(a.dropped)?a.dropped:0)+1;a.dropped=u,!this.lastEventRateLimited&&this.Ja(u)&&(a.dropped=0)}return this.lastEventRateLimited=c,(n=this.instance.persistence)===null||n===void 0||n.set_property("$capture_rate_limit",a),{isRateLimited:c,remainingTokens:a.tokens}}Ka(e){const t=this.instance.config.property_denylist;return!ue(t)||!t.includes(e)}Xa(){var e;if(this.Ka("$current_url")&&this.Ka("$pathname")&&je?.pathname)return`${(e=je.origin)!==null&&e!==void 0?e:""}${je.pathname}`}Ja(e){var t,r;const{captureEventsBurstLimit:n,captureEventsPerSecond:i}=this,s=this.Xa(),o=this.Ka("$session_id")?(t=(r=this.instance).get_session_id)===null||t===void 0?void 0:t.call(r):void 0,a=[`${e} event(s) dropped since the last warning`,s?`triggered on ${s}`:void 0,o?`session ${o}`:void 0].filter(Boolean).join(", ");return!!this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:`posthog-js client rate limited: ${a}. Config is set to ${i} events per second and ${n} events burst limit.`},{skip_client_rate_limiting:!0})}isServerRateLimited(e){const t=this.serverLimits[e||"events"]||!1;return t!==!1&&new Date().getTime()<t}},br=Ve("[RemoteConfig]"),Jy=class{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=re._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.config}Ya(e){var t,r,n;!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.loadExternalDependency?(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"remote-config",()=>e(this.remoteConfig)):e()}tl(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets",`/array/${this._instance.config.token}/config`),callback:e})}load(){try{if(this.remoteConfig)return br.info("Using preloaded remote config",this.remoteConfig),void this.el(this.remoteConfig);if(this._instance.il())return void br.warn("Remote config is disabled. Falling back to local config.");this.Ya(e=>{if(!e)return br.info("No config found after loading remote JS config. Falling back to JSON."),void this.tl(t=>{this.el(t.json,t)});this.el(e)})}catch(e){br.error("Error loading remote config",e),this.el()}}el(e,t){!e&&t&&(t.statusCode===0?t.error||br.warn("Failed to fetch remote config from PostHog."):br.error("Failed to fetch remote config from PostHog."));try{this._instance.el(e?{ok:!0,config:e}:{ok:!1})}catch(n){br.error("Error applying remote config",n)}if(e?.hasFeatureFlags!==!1&&!this._instance.config.advanced_disable_feature_flags_on_first_load)try{var r;(r=this._instance.featureFlags)===null||r===void 0||r.ensureFlagsLoaded()}catch(n){br.error("Error loading feature flags",n)}}},Tt=Uint8Array,mt=Uint16Array,di=Uint32Array,Td=new Tt([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]),Rd=new Tt([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]),hf=new Tt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ky=function(e,t){for(var r=new mt(31),n=0;31>n;++n)r[n]=t+=1<<e[n-1];var i=new di(r[30]);for(n=1;30>n;++n)for(var s=r[n];r[n+1]>s;++s)i[s]=s-r[n]<<5|n;return[r,i]},Yy=Ky(Td,2),Qu=Yy[1];Yy[0][28]=258,Qu[258]=28;for(var pf=Ky(Rd,0)[1],el=new mt(32768),Be=0;32768>Be;++Be){var Cn=(43690&Be)>>>1|(21845&Be)<<1;el[Be]=((65280&(Cn=(61680&(Cn=(52428&Cn)>>>2|(13107&Cn)<<2))>>>4|(3855&Cn)<<4))>>>8|(255&Cn)<<8)>>>1}var ts=function(e,t,r){for(var n=e.length,i=0,s=new mt(t);n>i;++i)++s[e[i]-1];var o,a=new mt(t);for(i=0;t>i;++i)a[i]=a[i-1]+s[i-1]<<1;if(r){o=new mt(1<<t);var c=15-t;for(i=0;n>i;++i)if(e[i])for(var u=i<<4|e[i],l=t-e[i],h=a[e[i]-1]++<<l,d=h|(1<<l)-1;d>=h;++h)o[el[h]>>>c]=u}else for(o=new mt(n),i=0;n>i;++i)o[i]=el[a[e[i]-1]++]>>>15-e[i];return o},In=new Tt(288);for(Be=0;144>Be;++Be)In[Be]=8;for(Be=144;256>Be;++Be)In[Be]=9;for(Be=256;280>Be;++Be)In[Be]=7;for(Be=280;288>Be;++Be)In[Be]=8;var Yo=new Tt(32);for(Be=0;32>Be;++Be)Yo[Be]=5;var nx=ts(In,9,0),ix=ts(Yo,5,0),Xy=function(e){return(e/8|0)+(7&e&&1)},Qy=function(e,t,r){(t==null||0>t)&&(t=0),(r==null||r>e.length)&&(r=e.length);var n=new(e instanceof mt?mt:e instanceof di?di:Tt)(r-t);return n.set(e.subarray(t,r)),n},sr=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8},xi=function(e,t,r){var n=t/8|0;e[n]|=r<<=7&t,e[n+1]|=r>>>8,e[n+2]|=r>>>16},Pc=function(e,t){for(var r=[],n=0;e.length>n;++n)e[n]&&r.push({s:n,f:e[n]});var i=r.length,s=r.slice();if(!i)return[new Tt(0),0];if(i==1){var o=new Tt(r[0].s+1);return o[r[0].s]=1,[o,1]}r.sort(function(R,I){return R.f-I.f}),r.push({s:-1,f:25001});var a=r[0],c=r[1],u=0,l=1,h=2;for(r[0]={s:-1,f:a.f+c.f,l:a,r:c};l!=i-1;)a=r[r[h].f>r[u].f?u++:h++],c=r[u!=l&&r[h].f>r[u].f?u++:h++],r[l++]={s:-1,f:a.f+c.f,l:a,r:c};var d=s[0].s;for(n=1;i>n;++n)s[n].s>d&&(d=s[n].s);var p=new mt(d+1),f=tl(r[l-1],p,0);if(f>t){n=0;var v=0,g=f-t,m=1<<g;for(s.sort(function(R,I){return p[I.s]-p[R.s]||R.f-I.f});i>n;++n){var w=s[n].s;if(t>=p[w])break;v+=m-(1<<f-p[w]),p[w]=t}for(v>>>=g;v>0;){var S=s[n].s;t>p[S]?v-=1<<t-p[S]++-1:++n}for(;n>=0&&v;--n){var O=s[n].s;p[O]==t&&(--p[O],++v)}f=t}return[new Tt(p),f]},tl=function(e,t,r){return e.s==-1?Math.max(tl(e.l,t,r+1),tl(e.r,t,r+1)):t[e.s]=r},ff=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new mt(++t),n=0,i=e[0],s=1,o=function(c){r[n++]=c},a=1;t>=a;++a)if(e[a]==i&&a!=t)++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=e[a]}return[r.subarray(0,n),t]},Mi=function(e,t){for(var r=0,n=0;t.length>n;++n)r+=e[n]*t[n];return r},bo=function(e,t,r){var n=r.length,i=Xy(t+2);e[i]=255&n,e[i+1]=n>>>8,e[i+2]=255^e[i],e[i+3]=255^e[i+1];for(var s=0;n>s;++s)e[i+s+4]=r[s];return 8*(i+4+n)},vf=function(e,t,r,n,i,s,o,a,c,u,l){sr(t,l++,r),++i[256];for(var h=Pc(i,15),d=h[0],p=h[1],f=Pc(s,15),v=f[0],g=f[1],m=ff(d),w=m[0],S=m[1],O=ff(v),R=O[0],I=O[1],C=new mt(19),L=0;w.length>L;++L)C[31&w[L]]++;for(L=0;R.length>L;++L)C[31&R[L]]++;for(var q=Pc(C,7),K=q[0],X=q[1],k=19;k>4&&!K[hf[k-1]];--k);var ne,H,oe,P,ee=u+5<<3,y=Mi(i,In)+Mi(s,Yo)+o,B=Mi(i,d)+Mi(s,v)+o+14+3*k+Mi(C,K)+(2*C[16]+3*C[17]+7*C[18]);if(y>=ee&&B>=ee)return bo(t,l,e.subarray(c,c+u));if(sr(t,l,1+(y>B)),l+=2,y>B){ne=ts(d,p,0),H=d,oe=ts(v,g,0),P=v;var Y=ts(K,X,0);for(sr(t,l,S-257),sr(t,l+5,I-1),sr(t,l+10,k-4),l+=14,L=0;k>L;++L)sr(t,l+3*L,K[hf[L]]);l+=3*k;for(var le=[w,R],de=0;2>de;++de){var Oe=le[de];for(L=0;Oe.length>L;++L)sr(t,l,Y[Ie=31&Oe[L]]),l+=K[Ie],Ie>15&&(sr(t,l,Oe[L]>>>5&127),l+=Oe[L]>>>12)}}else ne=nx,H=In,oe=ix,P=Yo;for(L=0;a>L;++L)if(n[L]>255){var Ie;xi(t,l,ne[257+(Ie=n[L]>>>18&31)]),l+=H[Ie+257],Ie>7&&(sr(t,l,n[L]>>>23&31),l+=Td[Ie]);var _e=31&n[L];xi(t,l,oe[_e]),l+=P[_e],_e>3&&(xi(t,l,n[L]>>>5&8191),l+=Rd[_e])}else xi(t,l,ne[n[L]]),l+=H[n[L]];return xi(t,l,ne[256]),l+H[256]},sx=new di([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),ox=new Tt(0),ax=(function(){for(var e=new di(256),t=0;256>t;++t){for(var r=t,n=9;--n;)r=(1&r&&3988292384)^r>>>1;e[t]=r}return e})(),Oc=function(e,t,r){for(;r;++t)e[t]=r,r>>>=8};function cx(e,t){t===void 0&&(t={});var r=(function(){var d=4294967295;return{p(p){for(var f=d,v=0;p.length>v;++v)f=ax[255&f^p[v]]^f>>>8;d=f},d(){return 4294967295^d}}})(),n=e.length;r.p(e);var i,s,o,a,c,u,l=(a=10+((i=t).filename&&i.filename.length+1||0),c=8,(function(d,p,f,v,g,m){var w=d.length,S=new Tt(v+w+5*(1+Math.floor(w/7e3))+g),O=S.subarray(v,S.length-g),R=0;if(!p||8>w)for(var I=0;w>=I;I+=65535){var C=I+65535;w>C?R=bo(O,R,d.subarray(I,C)):(O[I]=m,R=bo(O,R,d.subarray(I,w)))}else{for(var L=sx[p-1],q=L>>>13,K=8191&L,X=(1<<f)-1,k=new mt(32768),ne=new mt(X+1),H=Math.ceil(f/3),oe=2*H,P=function(_){return(d[_]^d[_+1]<<H^d[_+2]<<oe)&X},ee=new di(25e3),y=new mt(288),B=new mt(32),Y=0,le=0,de=(I=0,0),Oe=0,Ie=0;w>I;++I){var _e=P(I),ge=32767&I,Je=ne[_e];if(k[ge]=Je,ne[_e]=ge,I>=Oe){var Xe=w-I;if((Y>7e3||de>24576)&&Xe>423){R=vf(d,O,0,ee,y,B,le,de,Ie,I-Ie,R),de=Y=le=0,Ie=I;for(var Ce=0;286>Ce;++Ce)y[Ce]=0;for(Ce=0;30>Ce;++Ce)B[Ce]=0}var z=2,se=0,ae=K,he=ge-Je&32767;if(Xe>2&&_e==P(I-he))for(var $e=Math.min(q,Xe)-1,we=Math.min(32767,I),Se=Math.min(258,Xe);we>=he&&--ae&&ge!=Je;){if(d[I+z]==d[I+z-he]){for(var ve=0;Se>ve&&d[I+ve]==d[I+ve-he];++ve);if(ve>z){if(z=ve,se=he,ve>$e)break;var me=Math.min(he,ve-2),Ee=0;for(Ce=0;me>Ce;++Ce){var Ge=I-he+Ce+32768&32767,U=Ge-k[Ge]+32768&32767;U>Ee&&(Ee=U,Je=Ge)}}}he+=(ge=Je)-(Je=k[ge])+32768&32767}if(se){ee[de++]=268435456|Qu[z]<<18|pf[se];var Z=31&Qu[z],Q=31&pf[se];le+=Td[Z]+Rd[Q],++y[257+Z],++B[Q],Oe=I+z,++Y}else ee[de++]=d[I],++y[d[I]]}}R=vf(d,O,m,ee,y,B,le,de,Ie,I-Ie,R),m||(R=bo(O,R,ox))}return Qy(S,0,v+Xy(R)+g)})(s=e,(o=t).level==null?6:o.level,o.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(s.length)))):12+o.mem,a,c,!u)),h=l.length;return(function(d,p){var f=p.filename;if(d[0]=31,d[1]=139,d[2]=8,d[8]=2>p.level?4:p.level==9?2:0,d[9]=3,p.mtime!=0&&Oc(d,4,Math.floor(new Date(p.mtime||Date.now())/1e3)),f){d[3]=8;for(var v=0;f.length>=v;++v)d[v+10]=f.charCodeAt(v)}})(l,t),Oc(l,h-8,r.d()),Oc(l,h-4,n),l}var ux=!!cd||!!hs,e0=new WeakMap,t0="text/plain",Cc=0,wo=!1,r0=(e,t)=>{const[r,n]=e.split("#"),[i,s]=r.split("?");if(!s)return e;const o=s.split("&").filter(a=>a.split("=")[0]!==t).join("&");return`${i}${o?`?${o}`:""}${n?`#${n}`:""}`},Ts=(e,t,r=!0)=>{var n;const[i,s]=e.split("?"),o=b({},t),a=(n=s?.split("&").map(u=>{var l;const[h,d]=u.split("="),p=r&&(l=o[h])!==null&&l!==void 0?l:d;return delete o[h],`${h}=${p}`}))!==null&&n!==void 0?n:[],c=(function(u,l="&"){let h,d;const p=[];return Pe(u,function(f,v){M(f)||M(v)||v==="undefined"||(h=encodeURIComponent((g=>g instanceof File)(f)?f.name:f.toString()),d=encodeURIComponent(v),p[p.length]=d+"="+h)}),p.join(l)})(o);return c&&a.push(c),a.length>0?`${i}?${a.join("&")}`:i},$c=e=>{if(e.nl)return e.nl;const{data:t,compression:r}=e;if(!t)return;if(r===It.GZipJS){const i=cx((function(s){var o=s.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(s);for(var a=new Tt(s.length+(s.length>>>1)),c=0,u=function(p){a[c++]=p},l=0;o>l;++l){if(c+5>a.length){var h=new Tt(c+8+(o-l<<1));h.set(a),a=h}var d=s.charCodeAt(l);128>d?u(d):2048>d?(u(192|d>>>6),u(128|63&d)):d>55295&&57344>d?(u(240|(d=65536+(1047552&d)|1023&s.charCodeAt(++l))>>>18),u(128|d>>>12&63),u(128|d>>>6&63),u(128|63&d)):(u(224|d>>>12),u(128|d>>>6&63),u(128|63&d))}return Qy(a,0,c)})(Gn(t)),{mtime:0});return{contentType:t0,body:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),estimatedSize:i.byteLength}}if(r===It.Base64){const i=(s=>"data="+encodeURIComponent(typeof s=="string"?s:Gn(s)))((function(s){return s&&btoa(encodeURIComponent(s).replace(/%([0-9A-F]{2})/g,(o,a)=>String.fromCharCode(parseInt(a,16))))})(Gn(t)));return{contentType:"application/x-www-form-urlencoded",body:i,estimatedSize:new Blob([i]).size}}const n=Gn(t);return{contentType:"application/json",body:n,estimatedSize:new Blob([n]).size}},n0=e=>{const t=()=>e.transport==="sendBeacon"?{url:Ts(e.url,{compression:It.Base64}),encodedBody:$c(b(b({},e),{},{compression:It.Base64,nl:void 0}))}:{url:r0(e.url,"compression"),encodedBody:$c(b(b({},e),{},{compression:void 0,nl:void 0}))};let r;try{r=$c(e)}catch(i){if(Mp(e.compression,ui(e.url,"compression")))return j.error("Failed to gzip request body, sending uncompressed payload",i),t();throw i}return r&&Mp(e.compression,ui(e.url,"compression"))&&!((n=r.body)instanceof ArrayBuffer?Du(new Uint8Array(n)):ArrayBuffer.isView(n)&&Du(new Uint8Array(n.buffer,n.byteOffset,n.byteLength)))?(wo=!0,t()):{url:e.url,encodedBody:r};var n},i0=e=>{try{return n0(e)}catch(r){var t;j.error(r),(t=e.callback)===null||t===void 0||t.call(e,{statusCode:0,error:r});return}},lx=(function(){var e=Ue(function*(t){const r=yield(function(i){return zu.apply(this,arguments)})(Gn(t.data),et.DEBUG,{rethrow:!0});if(!r)return t;const n=yield r.arrayBuffer();return b(b({},t),{},{nl:{contentType:t0,body:n,estimatedSize:n.byteLength}})});return function(t){return e.apply(this,arguments)}})(),dx=/Failed to fetch|NetworkError|Load failed/i,s0=e=>e?.name==="TypeError"&&dx.test(e?.message||""),o0=e=>{try{const t=(function(r,n=Date.now()){if(typeof r!="string"||!r)return;const i=r.trim(),s=/^\d+\s*,/.test(i)?i.slice(0,i.indexOf(",")).trim():i;if(/^\d+$/.test(s)){const c=1e3*Math.min(Number(s),300);return c>0?c:void 0}if(!/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*[ ,]/.test(s))return;const o=/^\w{3} \w{3} /.test(s)?s+" GMT":s,a=Date.parse(o)-n;return Number.isFinite(a)&&a>0?Math.min(a,mo):void 0})(e());return M(t)?void 0:Math.min(t,3e4)}catch{return}},a0=e=>{const t=i0(e);if(!t)return;const r=new cd;e0.set(r,!0);const{url:n,encodedBody:i}=t;r.open(e.method||"GET",n,!0);const{contentType:s,body:o}=i??{};Pe(e.headers,function(a,c){r.setRequestHeader(c,a)}),s&&r.setRequestHeader("Content-Type",s),e.timeout&&(r.timeout=e.timeout),r.onreadystatechange=()=>{if(r.readyState===4){var a;const c={statusCode:r.status,text:r.responseText};if(r.status===200)try{c.json=JSON.parse(r.responseText)}catch{}(a=e.callback)===null||a===void 0||a.call(e,c,o0(()=>r.getResponseHeader("Retry-After")))}},r.send(o)},c0=e=>{const t=i0(e);if(!t)return;const{url:r,encodedBody:n}=t,{contentType:i,body:s,estimatedSize:o}=n??{},a=new Headers;Pe(e.headers,function(f,v){a.append(v,f)}),i&&a.append("Content-Type",i);let c=null,u=!1;if(_p){const f=new _p;c={signal:f.signal,timeout:setTimeout(()=>{u=!0;try{f.abort(D_("AbortError","PostHog request timed out"+((v=e.timeout)?` after ${v}ms`:"")))}catch(g){h(g)}var v},e.timeout)}}let l=!1;const h=f=>{var v;l||(l=!0,u&&f?.name==="AbortError"||s0(f)?j.warn(f):j.error(f),(v=e.callback)===null||v===void 0||v.call(e,{statusCode:0,error:f}))};let d=0;const p=()=>{Cc-=d,d=0,c&&clearTimeout(c.timeout)};try{const f=b({method:e?.method||"GET",headers:a,referrerPolicy:"strict-origin",body:s,signal:c?.signal},e.fetchOptions),v=o??(M(s)?0:void 0);f.keepalive=f.method==="POST"&&!e.sl&&f.keepalive!==!1&&f.body===s&&!M(v)&&v>=0&&52428.8>Cc+v,f.keepalive&&(d=v,Cc+=d),hs(r,f).then(g=>g.text().then(m=>{var w;if(l)return;const S={statusCode:g.status,text:m};if(g.status===200)try{S.json=JSON.parse(m)}catch(O){j.error(O)}l=!0,p(),(w=e.callback)===null||w===void 0||w.call(e,S,o0(()=>g.headers.get("Retry-After")))})).catch(g=>{p(),h(g)}).finally(p)}catch(f){p(),h(f)}},rl=e=>{try{var t;const{url:r,encodedBody:n}=n0(e),{contentType:i,body:s,estimatedSize:o}=n??{};if(!s)return;const a=s instanceof Blob?s:new Blob([s],{type:i});if(rt.sendBeacon(r,a))return;const c=ue(e.data)?e.data:(t=e.data)===null||t===void 0?void 0:t.batch;if(ue(c)&&c.length>1&&(o??0)>16384){const u=Math.ceil(c.length/2),l=h=>ue(e.data)?h:b(b({},e.data),{},{batch:h});rl(b(b({},e),{},{data:l(c.slice(0,u))})),rl(b(b({},e),{},{data:l(c.slice(u))}));return}j.warn(`Beacon of ~${o??0} bytes was rejected by the browser, falling back to ${hs?"fetch":"XHR"}`),hs?c0(b(b({},e),{},{sl:!0})):a0(e)}catch(r){j.warn("Beacon send failed",r)}},gf=(e,t,r,n)=>{const i=n==="query"?t==="POST"?"sent_at":"_":void 0;return Ts(r===It.GZipJS?r0(e,"compression"):e,b(b({},i?{[i]:Date.now().toString()}:{}),r===It.GZipJS?{}:{compression:r}))},hx=(()=>{const e=[];return hs&&e.push({transport:"fetch",method:c0}),cd&&e.push({transport:"XHR",method:a0}),rt!=null&&rt.sendBeacon&&e.push({transport:"sendBeacon",method:rl}),e})(),u0=!ux&&ft?.indexOf("MSIE")===-1&&ft?.indexOf("Mozilla")===-1;function l0(e,t,r){var n,i,s;r&&(t=b(b({},t),{},{callback:o=>r(o)})),e.__loaded?u0?e.__request_queue.push(t):e.rateLimiter.isServerRateLimited(t.batchKey)?t.fireCallbackOnDrop&&((i=t.callback)===null||i===void 0||i.call(t,{statusCode:429})):(t.transport=t.transport||e.config.api_transport,t.headers=b(b({},e.config.request_headers),t.headers),t.compression=t.compression==="best-available"?(n=e.compression)!==null&&n!==void 0?n:t.compressionFallback:t.compression,(M(e.config.disable_beacon)?e.config.__preview_disable_beacon:e.config.disable_beacon)&&(t.disableTransport=["sendBeacon"]),t.fetchOptions=t.fetchOptions||e.config.fetch_options,((o,a)=>{var c,u,l;const h=b(b({},o),{},{callback:a??(g=>{var m;return(m=o.callback)===null||m===void 0?void 0:m.call(o,g)})});h.timeout=h.timeout||6e4;const d=(c=h.transport)!==null&&c!==void 0?c:"fetch";d==="sendBeacon"&&M(h.compression)&&h.data&&(h.compression=It.Base64),h.method==="POST"&&h.data&&(h.timestampMode==="capture-body"?h.data=(g=>{var m,w;const S=(ue(g)?g:[g]).map(R=>b(b({},R),R.timestamp instanceof Date&&!isNaN(R.timestamp.getTime())?{timestamp:R.timestamp.toISOString()}:{})),O=S[0];return{api_key:(m=O==null||(w=O.properties)===null||w===void 0?void 0:w.token)!==null&&m!==void 0?m:O?.token,batch:S,sent_at:new Date().toISOString()}})(h.data):h.timestampMode==="body"&&(h.data=((g,m=new Date().toISOString())=>ue(g)?g.map(w=>b(b({},w),{},{sent_at:m})):b(b({},g),{},{sent_at:m}))(h.data))),h.url=gf(h.url,h.method,h.compression,h.timestampMode);const p=hx.filter(g=>!h.disableTransport||!g.transport||!h.disableTransport.includes(g.transport)),f=(u=(l=(function(g,m){for(let w=0;g.length>w;w++)if(m(g[w]))return g[w]})(p,g=>g.transport===d))===null||l===void 0?void 0:l.method)!==null&&u!==void 0?u:p[0].method;if(!f)throw new Error("No available transport method");const v=g=>{try{f(g)}catch(w){var m;s0(w)?j.warn(w):j.error(w),(m=h.callback)===null||m===void 0||m.call(h,{statusCode:0,error:w})}};d!=="sendBeacon"&&!h.preferSyncCompression&&h.data&&h.compression===It.GZipJS&&r$&&typeof Promise<"u"&&!wo?lx(h).then(g=>{v(g)}).catch(g=>{if(Lp(g))return wo=!0,void v(b(b({},h),{},{compression:void 0,url:gf(o.url,o.method,void 0,o.timestampMode)}));(m=>{if(!m||typeof m!="object")return!1;const w="name"in m?String(m.name):"";return Lp(m)||w===B_})(g)&&(wo=!0),v(h)}):v(h)})(t,(o,a)=>{var c,u,l;e.rateLimiter.checkForLimiting(o),400>o.statusCode||(c=(u=e.config).on_request_error)===null||c===void 0||c.call(u,o),r?r(o,a):(l=t.callback)===null||l===void 0||l.call(t,o)})):t.fireCallbackOnDrop&&((s=t.callback)===null||s===void 0||s.call(t,{statusCode:0}))}var px=class{constructor(e,t){this.rl=!0,this.ol=[],this.al=Yt(t?.flush_interval_ms||3e3,250,5e3,j.createLogger("flush interval"),3e3),this.ll=e}enqueue(e){this.ol.push(e),this.ul||this.hl()}unload(){this.cl();const e=this.ol.length>0?this.dl():{},t=Object.values(e);[...t.filter(r=>r.url.indexOf("/e")===0),...t.filter(r=>r.url.indexOf("/e")!==0)].map(r=>{this.vl(r,"sendBeacon")})}enable(){this.rl=!1,this.hl()}hl(){this.rl||(this.ul=setTimeout(()=>{if(this.cl(),this.ol.length>0){const e=this.dl();for(const t in e)this.vl(e[t])}},this.al))}vl(e,t){try{this.ll(e,t)}catch(r){j.error(r)}}cl(){clearTimeout(this.ul),this.ul=void 0}dl(){const e={};return Pe(this.ol,t=>{var r;const n=t,i=((n?n.batchKey:null)||n.url)+(n.batchGroup?`:${n.batchGroup}`:"");M(e[i])&&(e[i]=b(b({},n),{},{data:[]})),(r=e[i].data)===null||r===void 0||r.push(n.data)}),this.ol=[],e}},fx=["retriesPerformedSoFar"],vx=class{constructor(e){this._instance=e,this.fl=!1,this.pl=3e3,this.ol=[],this.ol=[],this.gl=!0,this.resume()}resume(){if(!M(A)&&"onLine"in A.navigator){if(this.gl=A.navigator.onLine,this.ml)return;this.ml=()=>{this.gl=!0,this.yl()},this.bl=()=>{this.gl=!1},Ae(A,"online",this.ml),Ae(A,"offline",this.bl)}}get length(){return this.ol.length}retriableRequest(e,t){let{retriesPerformedSoFar:r}=e,n=V_(e,fx);ur(r)&&(n.url=Ts(n.url,{retry_count:r})),l0(this._instance,t?b(b({},n),{},{transport:t}):n,(i,s)=>{var o;if(i.statusCode!==200&&(400>i.statusCode||i.statusCode>=500)){if((i.statusCode===0?3:10)>(r??0))return void this.Ls(b({retriesPerformedSoFar:r},n),s);i.statusCode===0&&j.warn(`Request failed before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped retrying after ${r??0} retries.`)}(o=n.callback)===null||o===void 0||o.call(n,i)})}Ls(e,t){const r=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=r+1;const n=Math.max((function(o){const a=3e3*Math.pow(2,o),c=a/2,u=Math.min(18e5,a),l=(Math.random()-.5)*(u-c);return Math.ceil(u+l)})(r),t??0),i=Date.now()+n;this.ol.push({retryAt:i,requestOptions:e});let s=`Enqueued failed request for retry in ${n}`;navigator.onLine||(s+=" (Browser is offline)"),j.warn(s),this.fl||(this.fl=!0,this._l())}_l(){if(this.wl&&clearTimeout(this.wl),this.ol.length===0)return this.fl=!1,void(this.wl=void 0);this.wl=setTimeout(()=>{this.gl&&this.ol.length>0&&this.yl(),this._l()},this.pl)}yl(){const e=Date.now(),t=[],r=this.ol.filter(n=>e>n.retryAt||(t.push(n),!1));if(this.ol=t,r.length>0)for(const{requestOptions:n}of r)this.retriableRequest(n)}unload(){this.wl&&(clearTimeout(this.wl),this.wl=void 0),this.fl=!1,M(A)||(this.ml&&(A.removeEventListener("online",this.ml),this.ml=void 0),this.bl&&(A.removeEventListener("offline",this.bl),this.bl=void 0));for(const{requestOptions:e}of this.ol)try{this._instance._send_request(b(b({},e),{},{transport:"sendBeacon"}))}catch(t){j.error(t)}this.ol=[]}},gx=class{constructor(e){this._instance=e,this.kl=()=>{var t,r,n,i;this.Sl||(this.Sl={});const s=this.scrollElement(),o=this.scrollY(),a=s?Math.max(0,s.scrollHeight-s.clientHeight):0,c=o+(s?.clientHeight||0),u=s?.scrollHeight||0;this.Sl.lastScrollY=Math.ceil(o),this.Sl.maxScrollY=Math.max(o,(t=this.Sl.maxScrollY)!==null&&t!==void 0?t:0),this.Sl.maxScrollHeight=Math.max(a,(r=this.Sl.maxScrollHeight)!==null&&r!==void 0?r:0),this.Sl.lastContentY=c,this.Sl.maxContentY=Math.max(c,(n=this.Sl.maxContentY)!==null&&n!==void 0?n:0),this.Sl.maxContentHeight=Math.max(u,(i=this.Sl.maxContentHeight)!==null&&i!==void 0?i:0)}}get xl(){return this._instance.config.scroll_root_selector}getContext(){return this.Sl}resetContext(){const e=this.Sl;return this.Sl=void 0,setTimeout(this.kl,0),e}startMeasuringScrollPosition(){Ae(A,"scroll",this.kl,{capture:!0}),Ae(A,"scrollend",this.kl,{capture:!0}),Ae(A,"resize",this.kl)}scrollElement(){if(this.xl){const r=ue(this.xl)?this.xl:[this.xl];for(const n of r){var e;const i=A==null||(e=A.document)===null||e===void 0?void 0:e.querySelector(n);if(i)return i}return}var t;return A==null||(t=A.document)===null||t===void 0?void 0:t.documentElement}Cl(e){var t,r;const n=e==="y"?"scrollTop":"scrollLeft";if(this.xl){const i=this.scrollElement();return i&&i[n]||0}return A?e==="y"?A.scrollY||A.pageYOffset||((t=A.document)===null||t===void 0||(t=t.documentElement)===null||t===void 0?void 0:t.scrollTop)||0:A.scrollX||A.pageXOffset||((r=A.document)===null||r===void 0||(r=r.documentElement)===null||r===void 0?void 0:r.scrollLeft)||0:0}scrollY(){return this.Cl("y")}scrollX(){return this.Cl("x")}},mx=e=>Vy(e?.config.mask_personal_data_properties,e?.config.custom_personal_data_properties,e?.config.disable_capture_url_hashes),mf=class{constructor(e,t,r,n){this.qe=i=>{const s=this.$l();if(s&&s.sessionId===i)return;const o={sessionId:i,props:this.Tl(this._instance)};this.Il.register({[Gu]:o})},this._instance=e,this.Ml=t,this.Il=r,this.Tl=n||mx,this.Ml.onSessionId(this.qe)}$l(){return this.Il.props[Gu]}getSetOnceProps(){var e;const t=(e=this.$l())===null||e===void 0?void 0:e.props;return t?"r"in t?Gy(t,this._instance.config.disable_capture_url_hashes):{$referring_domain:t.referringDomain,$pathname:t.initialPathName,utm_source:t.utm_source,utm_campaign:t.utm_campaign,utm_medium:t.utm_medium,utm_content:t.utm_content,utm_term:t.utm_term}:{}}getSessionProps(){const e={};return Pe(Sd(this.getSetOnceProps()),(t,r)=>{r==="$current_url"&&(r="url"),e[`$session_entry_${Cu(r)}`]=t}),e}},Xo=class{on(e,t){return this.El[e]||(this.El[e]=[]),this.El[e].push(t),()=>{this.El[e]=this.El[e].filter(r=>r!==t)}}emit(e,t){for(const r of this.El[e]||[])r(t);for(const r of this.El["*"]||[])r(e,t)}constructor(){this.El={}}},$n=Ve("[SessionId]"),_f=864e5,yf=class{on(e,t){return this.Pl.on(e,t)}constructor(e,t,r){var n;if(this.Rl=null,this.Al=null,this.Fl=[],this.Ol=void 0,this.Dl=!1,this.Pl=new Xo,this.Ll=(s,o)=>!(!ur(s)||!ur(o))&&Math.abs(s-o)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Ir=e.config,this.Il=e.persistence,this.je=void 0,this.Xt=void 0,this._sessionStartTimestamp=null,this.Nl=void 0,this._sessionActivityTimestamp=null,this.ql=t||Ft,this.jl=r||Ft;const i=this.Ir.persistence_name||this.Ir.token;if(this._sessionTimeoutMs=1e3*Yt(this.Ir.session_idle_timeout_seconds||1800,60,36e3,$n.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Bl(),this.Hl="ph_"+i+"_window_id",this.zl="ph_"+i+"_primary_window_exists",this.Ul()){const s=xe.Dt(this.Hl),o=xe.Dt(this.zl);s&&!o?this.je=s:xe.Lt(this.Hl),xe.$t(this.zl,!0)}(n=this.Ir.bootstrap)!==null&&n!==void 0&&n.sessionID&&this.setBootstrapSessionId(this.Ir.bootstrap.sessionID),this.Wl()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return M(this.Fl)&&(this.Fl=[]),this.Fl.push(e),this.Xt&&e(this.Xt,this.je),()=>{this.Fl=this.Fl.filter(t=>t!==e)}}Ul(){return this.Ir.persistence!=="memory"&&!this.Il.hi&&xe.Et()}Vl(e){e!==this.je&&(this.je=e,this.Ul()&&xe.$t(this.Hl,e))}Gl(){return this.je?this.je:this.Ul()?xe.Dt(this.Hl):null}Zl(e){const t=this.Rl;return!He(t)&&!He(e)&&5e3>Math.abs(e-t)}Ql(e,t,r){const n=t!==this._sessionActivityTimestamp,i=!(e!==this.Xt||r!==this._sessionStartTimestamp);this._sessionStartTimestamp=r,this._sessionActivityTimestamp=t,this.Xt=e,i&&!n||i&&this.Zl(t)||(this.Rl=t,this.Il.register({[Hn]:[t,e,r]}))}Jl(){var e;const t=(e=this.Ir)===null||e===void 0?void 0:e.persistence_save_debounce_ms;return ur(t)&&t>0}Kl(){this.Jl()?this.Il.refreshKey(Hn):(this.Il.flush(),this.Il.load())}Xl(){var e;if(He(this._sessionActivityTimestamp)||this._sessionActivityTimestamp===this.Rl)return;this.Kl();const[,t,r]=this.Yl();t===this.Xt&&r===this._sessionStartTimestamp&&(this.Rl=this._sessionActivityTimestamp,this.Il.register({[Hn]:[this._sessionActivityTimestamp,(e=this.Xt)!==null&&e!==void 0?e:null,this._sessionStartTimestamp]}),this.Il.flush())}tu(){const[e]=this.Yl(),t=ur(e)?e:0,r=ur(this._sessionActivityTimestamp)?this._sessionActivityTimestamp:0;return Math.max(t,r)}eu(e){return this.Kl(),this.Ll(e,this.tu())}Yl(){const e=this.Il.props[Hn];return ue(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.Rl=null,this.Nl=void 0,clearTimeout(this.iu),this.iu=void 0,this.Ql(null,null,null)}setBootstrapSessionId(e,t=!1){const r=((n,i=new Date().getTime())=>{try{const s=(o=>{const a=o.replace(/-/g,"");if(a.length!==32)throw new Error("Not a valid UUID");if(a[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(a.substring(0,12),16)})(n);return s>i+6e4?void $n.error("Bootstrap sessionID cannot be in the future"):s}catch(s){$n.error("Invalid sessionID in bootstrap",s);return}})(e);return!M(r)&&(t?this.Nl={sessionId:e,sessionStartTimestamp:r}:this.Ql(e,new Date().getTime(),r),!0)}destroy(){this.Dl=!0,this.Xl(),clearTimeout(this.iu),this.iu=void 0,this.Ol&&A&&(A.removeEventListener(Zo,this.Ol,{capture:!1}),this.Ol=void 0),this.Fl=[]}Wl(){this.Ol=()=>{this.Xl(),this.Ul()&&xe.Lt(this.zl)},Ae(A,Zo,this.Ol,{capture:!1})}checkAndGetSessionAndWindowId(e=!1,t=null,r=!1){if(this.Ir.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');const n=t||new Date().getTime(),i=this.Xt;if(r)this.Al=n;else if(He(this.Al)||this.Al>n||n-this.Al>=1e3){var s,o;(s=(o=this.Il).syncCookieProperties)===null||s===void 0||s.call(o),this.Al=n}let[,a,c]=this.Yl();const u=!M(i)&&a!==i,l=this.tu();let h=this.Gl();const d=this.Nl,p=!!d&&(d.sessionStartTimestamp>n+6e4||n-d.sessionStartTimestamp>_f),f=d?p:ur(c)&&Math.abs(n-c)>_f;let v=!1,g=u,m=!a||!!d;const w=a;let S=!m&&!e&&this.Ll(n,l);if(S&&(S=this.eu(n),S||$n.info("cross-tab refresh kept the session alive",{sessionId:a}),[,a,c]=this.Yl(),S||(m=!a||!!d)),m||S||f){g=!1;const C=d&&!p;a=C?d.sessionId:this.ql(),h=this.jl(),$n.info("new session ID assigned",{sessionId:a,windowId:h,bootstrapped:!!C,changeReason:{noSessionId:m,activityTimeout:S,sessionPastMaximumLength:f}}),c=C?d.sessionStartTimestamp:n,this.Nl=void 0,v=!0}else h||(h=this.jl(),v=!0),g=g||a!==w,g&&($n.info("adopted cross-tab session id",{sessionId:a,windowId:h}),v=!0);const O=ur(l)&&e&&!f?l:n,R=ur(c)?c:new Date().getTime();this.Vl(h),this.Ql(a,O,R),e||this.Bl();const I={noSessionId:m,activityTimeout:S,sessionPastMaximumLength:f,crossTabAdoption:g};return v&&this.Fl.forEach(C=>C(a,h,I)),{sessionId:a,windowId:h,sessionStartTimestamp:R,changeReason:v?I:void 0,lastActivityTimestamp:l}}Bl(){this.Dl||(clearTimeout(this.iu),this.iu=setTimeout(()=>{if(!this.Dl)if(this.eu(new Date().getTime())){const e=this.Xt;this.resetSessionId(),this.Pl.emit("forcedIdleReset",{idleSessionId:e})}else this.Bl()},1.1*this.sessionTimeoutMs))}},d0=function(e,t){if(!e)return!1;const r=e.userAgent;if(r&&wp(r,t))return!0;try{const n=e?.userAgentData;if(n?.brands&&n.brands.some(i=>wp(i?.brand,t)))return!0}catch{}return!!e.webdriver};function h0(){return(h0=Ue(function*(){const e=rt?.userAgentData;if(e?.getHighEntropyValues)try{const t=yield e.getHighEntropyValues(["model"]),r=t?.model;return ye(r)&&r.length>0?r:void 0}catch(t){j.info("Unable to resolve $device_model from userAgentData.getHighEntropyValues",t);return}})).apply(this,arguments)}function _x(e,t){let r=`$survey_${t}/${e.id}`;return e.current_iteration&&e.current_iteration>0&&(r=`$survey_${t}/${e.id}/${e.current_iteration}`),r}function p0(e){var t;return!!(!((t=e.conditions)===null||t===void 0||(t=t.events)===null||t===void 0||(t=t.values)===null||t===void 0)&&t.length)}var Qo=(e,t)=>{if(!(r=>{try{new RegExp(r)}catch{return!1}return!0})(t))return!1;try{return new RegExp(t).test(e)}catch{return!1}},Ks=e=>e.toLowerCase(),f0={exact:(e,t)=>t.some(r=>e.some(n=>r===n)),is_not:(e,t)=>t.every(r=>e.every(n=>r!==n)),regex:(e,t)=>t.some(r=>e.some(n=>Qo(r,n))),not_regex:(e,t)=>t.every(r=>e.every(n=>!Qo(r,n))),icontains:(e,t)=>t.map(Ks).some(r=>e.map(Ks).some(n=>r.includes(n))),not_icontains:(e,t)=>t.map(Ks).every(r=>e.map(Ks).every(n=>!r.includes(n))),gt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n>parseFloat(i))}),lt:(e,t)=>t.some(r=>{const n=parseFloat(r);return!isNaN(n)&&e.some(i=>n<parseFloat(i))})};function v0(e,t){return!e||Object.entries(e).every(([r,n])=>{const i=t?.[r];if(i==null)return!1;const s=f0[n.operator];return!!s&&s(n.values.map(String),[String(i)])})}function xc(e,t,r){return Gn({distinct_id:e,userPropertiesToSet:t,userPropertiesToSetOnce:r})}var nl="custom",bf="i.posthog.com",yx=/^\/static\//,bx=["/s/","/e/","/i/"],wx=class{constructor(e){this.nu={},this.instance=e}get apiHost(){const e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){const e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e;let t=(e=this.instance.config.ui_host)===null||e===void 0?void 0:e.replace(/\/$/,"");return t||(t=this.apiHost.replace(`.${bf}`,".posthog.com")),t==="https://app.posthog.com"?"https://us.posthog.com":t}get region(){return this.nu[this.apiHost]||(this.nu[this.apiHost]=/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"us":/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?"eu":nl),this.nu[this.apiHost]}su(e){if(!yx.test(e))return;const t=this.instance.config.asset_host;return typeof t=="string"&&t.trim().replace(/\/$/,"")||void 0}ru(e){const t=_r(e);return t?t.protocol+"//"+t.host+t.pathname:void 0}ou(e,t,r){if(e==="ui")return r;let n=r;const i=this.instance.config.rewriteRequestPath;if(i){var s;const o=((s=_r(r))===null||s===void 0?void 0:s.href)||r;n=i(new URL(o)).toString()}if(i&&e==="api"&&bx.some(o=>t.indexOf(o)===0)){const o=this.ru(n);if(o){const a=this.apiHost;let c=this.au;c?.apiHost===a&&c.rewriteRequestPath===i||(c={apiHost:a,rewriteRequestPath:i,urls:new Set},this.au=c),c.urls.add(o)}}return n}isIngestionEndpoint(e){const t=this.au,r=this.ru(e);return t?.apiHost===this.apiHost&&t.rewriteRequestPath===this.instance.config.rewriteRequestPath&&!!r&&t.urls.has(r)}endpointFor(e,t=""){if(t&&(t=t[0]==="/"?t:`/${t}`),e==="ui")return this.ou(e,t,this.uiHost+t);if(e==="flags")return this.ou(e,t,this.flagsApiHost+t);if(e==="assets"){const n=this.su(t);if(n)return this.ou(e,t,`${n}${t}`)}if(this.region===nl)return this.ou(e,t,this.apiHost+t);const r=bf+t;switch(e){case"assets":return this.ou(e,t,`https://${this.region}-assets.${r}`);case"api":return this.ou(e,t,`https://${this.region}.${r}`)}}},Re=Ve("[Surveys]"),g0=e=>{try{const t=(r=>((n,i)=>`seenSurvey_${(function(s){return s.current_iteration&&s.current_iteration>0?`${s.id}_${s.current_iteration}`:s.id})(i)}`)(0,r))(e);if(localStorage.getItem(t))return;localStorage.setItem(t,"true")}catch(t){Re.error("Failed to persist survey seen state",t)}},Sx=[Tc.Popover,Tc.Widget,Tc.API],Ex={ignoreConditions:!1,ignoreDelay:!1,displayType:Xu.Popover},kx=Ve("[PostHog ExternalIntegrations]"),Ix={intercom:"intercom-integration",crispChat:"crisp-chat-integration"},Ax=class{constructor(e){this._instance=e}Ho(e,t){var r,n;(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,e,i=>{if(i)return kx.error("failed to load script",i);t()})}startIfEnabledOrStop(){var e;for(const[i,s]of Object.entries((e=this._instance.config.integrations)!==null&&e!==void 0?e:{})){var t,r,n;s&&!((t=re.__PosthogExtensions__)!==null&&t!==void 0&&(t=t.integrations)!==null&&t!==void 0&&t[i])&&this.Ho(Ix[i],()=>{var o;(o=re.__PosthogExtensions__)===null||o===void 0||(o=o.integrations)===null||o===void 0||(o=o[i])===null||o===void 0||o.start(this._instance)}),!s&&(r=re.__PosthogExtensions__)!==null&&r!==void 0&&(r=r.integrations)!==null&&r!==void 0&&r[i]&&((n=re.__PosthogExtensions__)===null||n===void 0||(n=n.integrations)===null||n===void 0||(n=n[i])===null||n===void 0||n.stop())}}},Tx=class{constructor(e,t){this.A=e,this.bo=t,this.lu=new Map,this.To=!1}add(e){var t=this;return Ue(function*(){if(t.To)throw new Error("Cannot add an extension to a disposed ExtensionRuntime");if(t.lu.has(e.name))throw new Error(`Browser extension "${e.name}" is already registered`);t.lu.set(e.name,e);try{const r=e.setup(t.bo);r&&(yield r)}catch(r){const n=t.lu.get(e.name)===e;n&&t.lu.delete(e.name),t.A.error(`Failed to set up browser extension "${e.name}"`,r),n&&t.uu(e)}})()}getExtension(e){return this.lu.get(e)}dispose(){if(this.To)return;this.To=!0;const e=Array.from(this.lu.values()).reverse();this.lu.clear();for(const t of e)this.uu(t)}uu(e){try{var t;const r=(t=e.dispose)===null||t===void 0?void 0:t.call(e);r&&tt(r.then)&&r.then(void 0,n=>{this.A.error(`Failed to dispose browser extension "${e.name}"`,n)})}catch(r){this.A.error(`Failed to dispose browser extension "${e.name}"`,r)}}},Rx=class{constructor(e){this._instance=e}initialize(){}get(e){const t=this._instance.persistence;if(typeof e=="string")return t?.get_property(e);const r={};for(const n of e){const i=t?.get_property(n);M(i)||(r[n]=i)}return r}set(e,t){var r;(r=this._instance.persistence)===null||r===void 0||r.register(typeof e=="string"?{[e]:t}:e)}remove(e){var t;(t=this._instance.persistence)===null||t===void 0||t.unregister(e)}},wf="extensionsRemoteConfig",Px=class{constructor(e){this.instance=e,this.To=!1,this.A=j,this.hu=e.cu,this.kv=new Rx(e),this.onEvent=t=>Js(this.instance.on("eventCaptured",r=>{try{t({event:r.event,properties:r.properties})}catch(n){this.A.error("Browser extension event listener failed",n)}})),this.onRemoteConfig=t=>{if(this.To)return Js(()=>{});const r=i=>{try{t(i)}catch(s){this.A.error("Browser extension remote config listener failed",s)}},n=this.instance.du.on(wf,r);return this.hu&&r(this.hu),Js(n)},this.vu=new Tx(j.createLogger("[BrowserExtensions]"),this)}get logger(){return this.A}get distinctId(){return this.instance.get_distinct_id()}get anonymousId(){var e;return(e=this.instance.get_property("$device_id"))!==null&&e!==void 0?e:this.distinctId}get deviceId(){const e=this.instance.get_property(fd);return typeof e=="string"?e:void 0}get library(){return{name:et.LIB_NAME,version:et.LIB_VERSION}}get initialPersonProperties(){var e,t;return(e=(t=this.instance.persistence)===null||t===void 0?void 0:t.get_initial_props())!==null&&e!==void 0?e:{}}get groups(){return this.instance.getGroups()}get session(){try{var e,t,r,n;const i=(e=this.instance.sessionManager)===null||e===void 0?void 0:e.checkAndGetSessionAndWindowId(!0);return{sessionId:(t=i?.sessionId)!==null&&t!==void 0?t:"",windowId:(r=i?.windowId)!==null&&r!==void 0?r:"",sessionStartTimestamp:(n=i?.sessionStartTimestamp)!==null&&n!==void 0?n:0}}catch{return{sessionId:"",windowId:"",sessionStartTimestamp:0}}}get canCapture(){return this.instance.is_capturing()}get projectToken(){return this.instance.config.token}add(e){return this.vu.add(e)}getExtension(e){return this.vu.getExtension(e)}capture(e,t,r){r?this.instance.capture(e,t,{timestamp:r.timestamp,uuid:r.uuid,$set:r.set,$set_once:r.setOnce}):this.instance.capture(e,t)}registerDynamicEventProperties(e){return Js(this.instance.fu(e))}handleRemoteConfig(e){this.To||(this.hu=e,this.instance.du.emit(wf,e))}sendRequest(e){var t=this;return Ue(function*(r,n={}){var i;const s=t.instance.requestRouter.endpointFor((i=n.target)!==null&&i!==void 0?i:"api",r),o={method:n.method,url:n.query?Ts(s,n.query):s,data:n.body,headers:n.headers,timeout:n.timeoutMs,fireCallbackOnDrop:!0,transport:n.transport,compression:n.compression,compressionFallback:n.target==="flags"&&n.compression==="best-available"?Ou.Base64:void 0,timestampMode:n.sentAt};return n.transport==="sendBeacon"?(t.instance._send_request(o),{statusCode:202}):new Promise(a=>{o.callback=a,t.instance._send_request(o)})}).apply(this,arguments)}dispose(){this.To||(this.To=!0,this.vu.dispose())}},rs={},Mc=0,ns=()=>{},Sf='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',xn="Surveys module not available",Ef="sanitize_properties is deprecated. Use before_send instead",m0="Invalid value for property_denylist config: ",Ox=["$recording_status","$sdk_debug_recording_script_not_loaded","$sdk_debug_replay_url_trigger_status","$sdk_debug_replay_event_trigger_status","$sdk_debug_replay_linked_flag_trigger_status","$sdk_debug_replay_rrweb_error","$sdk_debug_replay_internal_buffer_length","$sdk_debug_replay_flushed_size"],Cx=["$feature_flag_called","$$heatmap","$snapshot"],kf=e=>e.charAt(0)==="$"&&!ce(Cx,e),$x=/^[A-Za-z0-9_-]{1,400}$/,If=/^fb\.[0-9]+\.[0-9]+\.[A-Za-z0-9_-]+(?:\.[A-Za-z0-9_-]+)?$/,Af=/^fb\.[0-9]+\.[0-9]+\.[0-9]+$/,xx=["token","distinct_id",py],ji="posthog",Mx=e=>{const t={};return e&&e!=="unset"&&("2025-11-30">e||(t.strictMinimumDuration=!0),"2026-05-30">e||(t.canvasCapture={resolutionScale:.6}),"2026-06-25">e||(t.streamNetworkBody=!0),"2026-08-30">e||(t.captureJsonLd=!0)),t},Lc=e=>{var t;return b({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,asset_host:null,token:"",autocapture:!0,cross_subdomain_cookie:O1(D?.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:ns,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:e??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,__preview_cookie_wins_on_conflict:!1,debug:je&&ye(je?.search)&&je.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!1,disableDeviceModel:!1,reuseAnonymousId:!1,disable_external_dependency_loading:!1,strict_script_versioning:"fallback",enable_recording_console_log:void 0,secure_cookie:(A==null||(t=A.location)===null||t===void 0?void 0:t.protocol)==="https:",ip:!1,opt_out_capturing_by_default:!1,opt_out_persistence_by_default:!1,opt_out_useragent_filter:!1,opt_out_capturing_persistence_type:"localStorage",consent_persistence_name:null,opt_out_capturing_cookie_prefix:null,opt_in_site_apps:!1,property_denylist:[],respect_dnt:!1,sanitize_properties:null,request_headers:{},request_batching:!0,properties_string_max_length:65535,mask_all_element_attributes:!1,mask_all_text:!1,mask_personal_data_properties:!1,custom_personal_data_properties:[],advanced_disable_flags:!1,advanced_disable_decide:!1,advanced_disable_feature_flags:!1,advanced_disable_feature_flags_on_first_load:!1,advanced_only_evaluate_survey_feature_flags:!1,advanced_feature_flags_dedup_per_session:!1,advanced_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,feature_flag_request_max_retries:1,surveys_request_timeout_ms:1e4,on_request_error(r){j.error("Bad HTTP status: "+r.statusCode+" "+r.text)},get_device_id:r=>r,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Ey,before_send:void 0,get_current_url:void 0,request_queue_config:{flush_interval_ms:3e3},error_tracking:{},_onCapture:ns},(r=>({rageclick:r&&r>="2026-05-30"?{content_ignorelist:z1,ignore_text_selection:!0}:!r||"2025-11-30">r||{content_ignorelist:!0},capture_pageview:!r||"2025-05-24">r||"history_change",session_recording:Mx(r),external_scripts_inject_target:r&&r>="2026-01-30"?"head":"body",internal_or_test_user_hostname:r&&r>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0,persistence_save_debounce_ms:r&&r>="2026-05-30"?250:0,split_storage:!(!r||"2026-05-30">r),detect_google_search_app:!(!r||"2026-05-30">r),disable_capture_url_hashes:!(!r||"2026-06-25">r),cookieWinsOnConflict:!(!r||r==="unset"||"2026-08-29">r)}))(e))},Lx=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["__preview_disable_beacon","disable_beacon"],["store_google","save_campaign_params"],["verbose","debug"],["__preview_cookie_wins_on_conflict","cookieWinsOnConflict"]],Tf=e=>{const t={};for(const[i,s]of Lx)M(e[i])||(t[s]=e[i]);const r=ze({},t,e),n=e.__preview_external_dependency_versioned_paths;return M(n)||(M(e.strict_script_versioning)&&(r.strict_script_versioning=!!n),ye(n)&&M(e.asset_host)&&(r.asset_host=n)),ue(e.property_blacklist)&&(M(e.property_denylist)?r.property_denylist=e.property_blacklist:ue(e.property_denylist)?r.property_denylist=[...e.property_blacklist,...e.property_denylist]:j.error(m0+e.property_denylist)),r},Nx=class{constructor(){this.__forceAllowLocalhost=!1}get pu(){return this.__forceAllowLocalhost}set pu(e){j.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}},is=class kr{gu(t){if(!t)return;const r=this.lu.indexOf(t);r!==-1&&this.lu.splice(r,1)}mu(t,r){var n;return this.gu(t),this.lu.push(r),(n=r.initialize)===null||n===void 0||n.call(r),r}yu(){return this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isRejected()}bu(){if(this._u||this.config.reuseAnonymousId||this.config.segment||this.yu())return;const t=this.config.persistence==="memory"||this.config.persistence==="sessionStorage";if(!t&&!this.config.disable_persistence||this.wu)return;let r,n,i;t?(r=`persistence is set to '${this.config.persistence}'`,n=this.config.persistence==="memory"?"on every page load":"for every new browser tab or window",i="Either set persistence to 'localStorage+cookie', keep this persistence and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."):(r="persistence is disabled (disable_persistence is true)",n="on every page load",i="Either set disable_persistence to false, keep persistence disabled and pass a stable ID through bootstrap.distinctID, or enable reuseAnonymousId."),this._u=!0,console.warn("[PostHog.js]",`${r} but no bootstrap.distinctID was provided. PostHog will mint a new distinct ID ${n}, so calling identify() merges a new ID onto the person each time. A person can then pass the distinct-ID limit and its events stop appearing on person pages and the session tab. ${i}`)}ku(){if(this.yu()||this.get_distinct_id()!=="$posthog_cookieless")return;const t=this.persistence;if(!t)return;this.Su()||t.load(!0);const r=this.get_distinct_id();if(!r||r==="$posthog_cookieless"){const n=this.config.get_device_id(Ft());this.register({distinct_id:n,$device_id:n}),t.set_property(vt,pr)}this.xu()}get decideEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}get flagsEndpointWasHit(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.hasLoadedFlags)!==null&&t!==void 0&&t}constructor(){var t;this.Cu=!1,this.$u=!1,this.webPerformance=new Nx,this.Tu=!1,this.version=et.LIB_VERSION,this.Iu=new Set,this.Mu="",this.du=new Xo,this.lu=[],this.Eu=[],this.Pu=!1,this.wu=!1,this._u=!1,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Lc(),this.SentryIntegration=G1,this.sentryIntegration=n=>(function(i,s){const o=Dy(i,s);return{name:Ny,processEvent:a=>o(a)}})(this,n),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Ru=!1,this.Au=null,this.Fu=null,this.Ou=null,this.scrollManager=new gx(this),this.pageViewManager=new af(this),this.rateLimiter=new rx(this),this.requestRouter=new wx(this),this.consent=new D1(this),this.externalIntegrations=new Ax(this);const r=(t=kr.__defaultExtensionClasses)!==null&&t!==void 0?t:{};this.featureFlags=r.featureFlags&&new r.featureFlags(this),this.toolbar=r.toolbar&&new r.toolbar(this),this.surveys=r.surveys&&new r.surveys(this),this.conversations=r.conversations&&new r.conversations(this),this.logs=r.logs&&new r.logs(this),this.metrics=r.metrics&&new r.metrics(this),this.experiments=r.experiments&&new r.experiments(this),this.exceptions=r.exceptions&&new r.exceptions(this),this.people={set:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(o),s?.({})},set_once:(n,i,s)=>{const o=ye(n)?{[n]:i}:n;this.setPersonProperties(void 0,o),s?.({})}},this.on("eventCaptured",n=>j.info(`send "${n?.event}"`,n))}init(t,r,n){if(n&&n!==ji){var i;const s=(i=rs[n])!==null&&i!==void 0?i:new kr;return s._init(t,r,n),rs[n]=s,rs[ji][n]=s,s}return this._init(t,r,n)}_init(t,r={},n){var i,s,o;const a=ye(t)?t.trim():"";if(!a)return j.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;var c;if(this.__loaded)return a!==((c=this.config)===null||c===void 0?void 0:c.token)?console.warn("[PostHog.js]",`You have already initialized PostHog with a different project token! Re-initializing is a no-op, so events will keep going to the project this instance was initialized with. To capture into a second project, load PostHog once, then initialize a named instance after the SDK has loaded, e.g. posthog.init('${a}', { ... }, 'project2')`):console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config=Lc(r.defaults),r.debug=this.Du(r.debug),this.Lu=r,this.Nu=[],r.person_profiles?this.Fu=r.person_profiles:r.process_person&&(this.Fu=r.process_person);const u=Lc(r.defaults),l=Tf(r),h=ze({},u,l,{name:n,token:a});be(u.rageclick)&&be(l.rageclick)&&(h.rageclick=ze({},u.rageclick,l.rageclick)),be(u.session_recording)&&be(l.session_recording)&&(h.session_recording=ze({},u.session_recording,l.session_recording)),this.set_config(h),this.config.on_xhr_error&&j.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=r.disable_compression?void 0:It.GZipJS;const d=this.Su();if(this.persistence=new Ac(this.config,d),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ac(b(b({},this.config),{},{persistence:"sessionStorage"}),d,!1),this.Mu="ph_"+(this.config.persistence_name||this.config.token)+"_session_registered_properties",this.config.persistence!=="memory"&&!d&&xe.Et()){const m=xe.Dt(this.Mu);ue(m)&&m.forEach(w=>{ye(w)&&this.Iu.add(w)})}else xe.Lt(this.Mu);const p=b({},this.persistence.props),f=b({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.qu=new px((m,w)=>this.ju(m,w),this.config.request_queue_config),this.Bu=new vx(this),this.__request_queue=[];const v=this.yu();v||(this.sessionManager=new yf(this),this.sessionPropsManager=new mf(this,this.sessionManager,this.persistence),this.sessionManager.onSessionId((m,w,S)=>{(S!=null&&S.activityTimeout||S!=null&&S.sessionPastMaximumLength||S!=null&&S.crossTabAdoption)&&this.Hu()})),this.zu(),this.config.__preview_deferred_init_extensions?(j.info("Deferring extension initialization to improve startup performance"),setTimeout(()=>{this.Uu(v)},0)):(j.info("Initializing extensions synchronously"),this.Uu(v)),et.DEBUG=et.DEBUG||this.config.debug,et.DEBUG&&j.info("Starting in debug mode",{this:this,config:r,thisC:b({},this.config),p,s:f}),this.config.identity_distinct_id&&!((i=r.bootstrap)!==null&&i!==void 0&&i.distinctID)&&(r.bootstrap=b(b({},r.bootstrap),{},{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0}));const g=(s=r.bootstrap)===null||s===void 0?void 0:s.distinctID;if(this.wu=!!g&&!Zi(g),(o=r.bootstrap)===null||o===void 0?void 0:o.distinctID){const m=r.bootstrap.distinctID,w=this.get_distinct_id(),S=this.persistence.get_property(vt);if(r.bootstrap.isIdentifiedID&&w!=null&&w!==m&&S==="anonymous")this.identify(m);else if(r.bootstrap.isIdentifiedID&&w!=null&&w!==m&&S==="identified")j.warn("Bootstrap distinctID differs from an already-identified user. The existing identity is preserved. Call reset() before reinitializing if you intend to switch users.");else{const O=this.config.get_device_id(Ft()),R=r.bootstrap.isIdentifiedID?O:m;this.persistence.set_property(vt,r.bootstrap.isIdentifiedID?_o:pr),this.register({distinct_id:m,$device_id:R})}}if(v)this.register_once({distinct_id:_c,$device_id:null},"");else if(!this.get_distinct_id()){const m=this.config.get_device_id(Ft());this.register_once({distinct_id:m,$device_id:m},""),this.persistence.set_property(vt,pr)}return Ae(A,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),Ae(A,"pageshow",()=>{var m;this.Cu=!1,this.$u||(m=this.Bu)===null||m===void 0||m.resume()}),r.segment?of(this,()=>this.Wu()):this.Wu(),tt(this.config._onCapture)&&this.config._onCapture!==ns&&(j.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",m=>this.config._onCapture(m.event,m))),this.config.ip&&j.warn('The `ip` config option has NO EFFECT AT ALL and has been deprecated. Use a custom transformation or "Discard IP data" project setting instead. See https://posthog.com/tutorials/web-redact-properties#hiding-customer-ip-address for more information.'),this.config.disableDeviceModel||(function(){return h0.apply(this,arguments)})().then(m=>{m&&this.register({[mc]:m})}).catch(ns),this}Vu(t){const r=t;return ye(r.name)&&tt(r.setup)}Gu(t,r){this.Vu(t)?r.push(()=>{this.Zu().add(t).catch(()=>{var n;return(n=t.dispose)===null||n===void 0?void 0:n.call(t)}).catch(n=>{j.error(`Failed to dispose browser extension "${t.name}"`,n)})}):this.lu.push(t)}zu(){var t,r,n;const i=(t=(r=this.config.__extensionClasses)===null||r===void 0?void 0:r.featureFlags)!==null&&t!==void 0?t:(n=kr.__defaultExtensionClasses)===null||n===void 0?void 0:n.featureFlags;var s,o,a;i&&(this.featureFlags&&this.featureFlags instanceof i||((s=this.Qu)===null||s===void 0||s.call(this),this.Qu=void 0,this.featureFlags=new i(this)),tt(this.featureFlags.onReloading)&&tt(this.featureFlags.setup)?this.Qu||(this.Qu=this.featureFlags.onReloading(()=>{this.du.emit("featureFlagsReloading",!0)}),this.Zu().add(this.featureFlags)):(o=(a=this.featureFlags).initialize)===null||o===void 0||o.call(a))}Uu(t){const r=performance.now(),n=b(b({},kr.__defaultExtensionClasses),this.config.__extensionClasses),i=[];var s,o,a,c,u,l,h;n.exceptions&&this.lu.push(this.exceptions=(s=this.exceptions)!==null&&s!==void 0?s:new n.exceptions(this)),n.historyAutocapture&&this.lu.push(this.historyAutocapture=new n.historyAutocapture(this)),n.tracingHeaders&&this.lu.push(this.tracingHeaders=new n.tracingHeaders(this)),n.siteApps&&this.lu.push(this.siteApps=new n.siteApps(this)),n.sessionRecording&&!t&&this.lu.push(this.sessionRecording=new n.sessionRecording(this)),this.config.disable_scroll_properties||i.push(()=>{this.scrollManager.startMeasuringScrollPosition()}),n.autocapture&&this.Gu(this.autocapture=new n.autocapture(this),i),n.surveys&&this.Gu(this.surveys=(o=this.surveys)!==null&&o!==void 0?o:new n.surveys(this),i),n.logs&&this.Gu(this.logs=(a=this.logs)!==null&&a!==void 0?a:new n.logs(this),i),n.metrics&&this.lu.push(this.metrics=(c=this.metrics)!==null&&c!==void 0?c:new n.metrics(this)),n.conversations&&this.lu.push(this.conversations=(u=this.conversations)!==null&&u!==void 0?u:new n.conversations(this)),n.productTours&&this.lu.push(this.productTours=new n.productTours(this)),n.heatmaps&&this.lu.push(this.heatmaps=new n.heatmaps(this)),n.webVitalsAutocapture&&this.lu.push(this.webVitalsAutocapture=new n.webVitalsAutocapture(this)),n.exceptionObserver&&this.lu.push(this.exceptionObserver=new n.exceptionObserver(this)),n.deadClicksAutocapture&&this.lu.push(this.deadClicksAutocapture=new n.deadClicksAutocapture(this,V1)),n.toolbar&&this.lu.push(this.toolbar=(l=this.toolbar)!==null&&l!==void 0?l:new n.toolbar(this)),n.experiments&&this.lu.push(this.experiments=(h=this.experiments)!==null&&h!==void 0?h:new n.experiments(this)),this.lu.forEach(d=>{d.initialize&&i.push(()=>{var p;(p=d.initialize)===null||p===void 0||p.call(d)})}),i.push(()=>{if(this.Ju){const d=this.Ju;this.Ju=void 0,this.lu.forEach(p=>{var f;return(f=p.onRemoteConfig)===null||f===void 0?void 0:f.call(p,d)})}}),this.Ku(i,r)}Ku(t,r){for(;t.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-r>=30&&t.length>0)return void setTimeout(()=>{this.Ku(t,r)},0);const i=t.shift();if(i)try{i()}catch(s){j.error("Error initializing extension:",s)}}const n=Math.round(performance.now()-r);this.register_for_session({[fy]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[vy]:n}),this.config.__preview_deferred_init_extensions&&j.info(`PostHog extensions initialized (${n}ms)`)}el(t){var r;if(!D||!D.body)return j.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout(()=>{this.el(t)},500);if(this.config.__preview_deferred_init_extensions&&(this.Ju=t),this.cu=t,this.compression=void 0,t.ok){var n;const i=t.config;i.supportedCompression&&!this.config.disable_compression&&(this.compression=ce(i.supportedCompression,It.GZipJS)?It.GZipJS:ce(i.supportedCompression,It.Base64)?It.Base64:void 0),(n=i.analytics)!==null&&n!==void 0&&n.endpoint&&(this.analyticsDefaultEndpoint=i.analytics.endpoint)}this.set_config({person_profiles:this.Fu?this.Fu:Ey}),(r=this.Xu)===null||r===void 0||r.handleRemoteConfig(t),this.lu.forEach(i=>{var s;return(s=i.onRemoteConfig)===null||s===void 0?void 0:s.call(i,t)})}Wu(){try{this.config.loaded(this)}catch(t){j.critical("`loaded` function failed",t)}if(this.Yu(),this.config.internal_or_test_user_hostname&&je?.hostname){const t=je.hostname,r=this.config.internal_or_test_user_hostname;(typeof r=="string"?t===r:r.test(t))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout(()=>{(this.consent.isOptedIn()||this.yu())&&this.th()},1),this.eh=new Jy(this),this.eh.load()}Yu(){var t;this.is_capturing()&&this.config.request_batching&&((t=this.qu)===null||t===void 0||t.enable())}_dom_loaded(){this.is_capturing()&&Vn(this.__request_queue,t=>this.ju(t)),this.__request_queue=[],this.Yu()}_handle_unload(){var t,r,n,i,s,o;this.Cu=!0,(t=this.surveys)===null||t===void 0||(r=t.handlePageUnload)===null||r===void 0||r.call(t),(n=this.metrics)===null||n===void 0||n.flush("sendBeacon"),this.config.request_batching?(this.ih()&&this.capture(Hp),(i=this.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=this.qu)===null||s===void 0||s.unload(),(o=this.Bu)===null||o===void 0||o.unload()):this.ih()&&this.capture(Hp,null,{transport:"sendBeacon"})}_send_request(t){l0(this,t)}ju(t,r){this.Bu?this.Bu.retriableRequest(t,r):this._send_request(r?b(b({},t),{},{transport:r}):t)}_execute_array(t){Mc++;try{let r;const n=[],i=[],s=[];Vn(t,a=>{if(a)if(r=a[0],ue(r))s.push(a);else if(tt(a))try{a.call(this)}catch(c){j.error("Error executing queued PostHog call",a,c)}else ue(a)&&r==="alias"?n.push(a):ue(a)&&r.indexOf("capture")!==-1&&tt(this[r])?s.push(a):i.push(a)});const o=function(a,c){Vn(a,function(u){try{if(ue(u[0])){let l=c;Pe(u,function(h){l=l[h[0]].apply(l,h.slice(1))})}else c[u[0]].apply(c,u.slice(1))}catch(l){j.error("Error executing queued PostHog call",u,l)}})};o(n,this),o(i,this),o(s,this)}finally{Mc--}}push(t){if(Mc>0&&ue(t)&&ye(t[0])){const r=kr.prototype[t[0]];tt(r)&&r.apply(this,t.slice(1));return}this._execute_array([t])}get nh(){return{property:qp,persistenceKey:Jn,cookieName:"_fbc",pattern:If,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Jn]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Jn)}}}get sh(){return{property:jp,persistenceKey:Ji,cookieName:"_fbp",pattern:Af,register:(t,r)=>{var n;return(n=this.persistence)===null||n===void 0?void 0:n.register({[Ji]:{value:t,delivered:r}})},unregister:()=>{var t;return(t=this.persistence)===null||t===void 0?void 0:t.unregister(Ji)}}}rh(t){var r;const n=(r=this.persistence)===null||r===void 0?void 0:r.get_property(t.persistenceKey);return ye(n)&&t.pattern.test(n)?{value:n,delivered:!1}:be(n)&&ye(n.value)&&t.pattern.test(n.value)?{value:n.value,delivered:n.delivered===!0}:void 0}oh(t,r,n){return r===n?.value?{value:r,pending:!n.delivered}:(t.register(r,!1),{value:r,pending:!0})}ah(t){if(!this.config.save_campaign_params||this.yu())return;const r=Xi(t.cookieName);return ye(r)&&t.pattern.test(r)?r:void 0}uh(t,r,n,i){if(!this.persistence)return;const s=this.nh;this.persistence.refreshKey(s.persistenceKey);const o=this.rh(s);if(i)return void s.unregister();if(n)return ye(r)&&If.test(r)?this.oh(s,r,o):void s.unregister();const a=ye(t)&&$x.test(t)?t:void 0,c=this.ah(s);return c&&((u,l,h)=>{const d=u.split(".");if(l)return d[3]===l;if(!h)return!0;const p=h.value.split(".");return d[3]===p[3]||Number(d[2])>Number(p[2])})(c,a,o)?this.oh(s,c,o):a?o?.value.split(".")[3]===a?{value:o.value,pending:!o.delivered}:this.oh(s,`fb.1.${Date.now()}.${a}`,o):o?{value:o.value,pending:!o.delivered}:void 0}hh(t,r,n){if(!this.persistence)return;const i=this.sh;this.persistence.refreshKey(i.persistenceKey);const s=this.rh(i);if(n)return void i.unregister();if(r)return ye(t)&&Af.test(t)?this.oh(i,t,s):void i.unregister();const o=this.ah(i);return o?this.oh(i,o,s):s?{value:s.value,pending:!s.delivered}:void 0}dh(t,r){if(!this.persistence)return;this.persistence.refreshKey(t.persistenceKey);const n=this.rh(t);n?.value!==r||n.delivered||t.register(r,!0)}capture(t,r,n){var i,s;if(!(this.__loaded&&this.persistence&&this.sessionPersistence&&this.qu))return void j.uninitializedWarning("posthog.capture");if(!this.is_capturing())return;if(M(t)||!ye(t))return void j.error("No event name provided to posthog.capture");this.ku();const o=!this.config.opt_out_useragent_filter&&this._is_bot();if(o&&!this.config.__preview_capture_bot_pageviews)return;const a=n?.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(a?.isRateLimited)return void j.critical("This capture call is ignored due to client rate limiting.");let c;r!=null&&r.$current_url&&!ye(r?.$current_url)&&(j.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),r==null||delete r.$current_url),t!=="$exception"||n!=null&&n.fh||j.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically."),this.sessionPersistence.update_search_keyword(),this.config.save_campaign_params&&(c=this.sessionPersistence.update_campaign_params()),this.config.save_referrer&&this.sessionPersistence.update_referrer_info(),(this.config.save_campaign_params||this.config.save_referrer)&&this.persistence.set_initial_person_info();const u=new Date,l=n?.timestamp||u,h=Ip(n?.uuid,Ft);let d={uuid:h,event:t,properties:this.calculateEventProperties(t,r||{},l,h)};t==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(d.event="$bot_pageview",d.properties.$browser_type="bot"),a&&(d.properties.$lib_rate_limit_remaining_tokens=a.remainingTokens);const p=t==="$feature_flag_called"&&d.properties.$feature_flag_has_experiment===!1&&this.get_property("$minimal_flag_called_events")===!0;n!=null&&n.$set&&!p&&(d.$set=n?.$set);const f=be(r?.$set)?r.$set:void 0,v=ue(r?.$unset)?r.$unset:[],g=n?.$unset||[],m=H=>{var oe;const P=!!n?.$set&&H in n.$set;return{hasProvided:P||!!f&&H in f,provided:P?n==null||(oe=n.$set)===null||oe===void 0?void 0:oe[H]:f?.[H],unset:v.indexOf(H)!==-1||g.indexOf(H)!==-1}},w=m(qp),S=m(jp),O=[{channel:this.nh,hasProvided:w.hasProvided,update:this.uh(c?.fbclid,w.provided,w.hasProvided,w.unset)},{channel:this.sh,hasProvided:S.hasProvided,update:this.hh(S.provided,S.hasProvided,S.unset)}];for(const{channel:H,hasProvided:oe,update:P}of O)P&&d.properties.$process_person_profile===!0&&P.pending&&!oe&&!p&&(d.$set=b({[H.property]:P.value},d.$set));const R=n?.$unset;R&&(d.$unset=R);const I=p?void 0:this.ph(n?.$set_once,t!==Bp,t===ky);if(I&&(d.$set_once=I),n!=null&&n._noTruncate||(C=this.config.properties_string_max_length,d=(function(H,oe){const P=new Set;return(function ee(y,B){if(y!==Object(y))return oe?oe(y):y;if(P.has(y))return;let Y;if(P.add(y),ue(y))Y=[],Vn(y,le=>{Y.push(ee(le))});else{const le={};Pe(yi(y)?Iy(y):y,(de,Oe)=>{P.has(de)||(le[Oe]=ee(de,Oe))}),Y=le}return Y})(H)})(d,H=>ye(H)?H.slice(0,C):H)),d.timestamp=l,M(n?.timestamp)||(d.properties.$event_time_override_provided=!0,d.properties.$event_time_override_system_time=u),p&&(d.properties=((H,oe=[])=>{const P={},ee=y=>{H[y]!==void 0&&(P[y]=H[y])};return K$.forEach(ee),oe.forEach(ee),P})(d.properties,xx)),t===Et.DISMISSED||t===Et.SENT){const H=r?.[Rc.SURVEY_ID],oe=r?.[Rc.SURVEY_ITERATION];g0({id:H,current_iteration:oe}),d.$set=b(b({},d.$set),{},{[_x({id:H,current_iteration:oe},t===Et.SENT?"responded":"dismissed")]:!0})}else t===Et.SHOWN&&(d.$set=b(b({},d.$set),{},{[Rc.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));var C;if(t===tx.SHOWN){const H=r?.[lf.TOUR_TYPE];H&&(d.$set=b(b({},d.$set),{},{[`${lf.TOUR_LAST_SEEN_DATE}/${H}`]:new Date().toISOString()}))}const L=b(b({},d.properties.$set),d.$set);if(bt(L)||this.setPersonPropertiesForFlags(L),!fe(this.config.before_send)){const H=this.Os(d);if(!H)return;d=H,d.uuid=Ip(d.uuid,Ft)}this.sessionRecording&&!this.Pu&&kf(t)&&(this.Pu=!0,setTimeout(()=>this.Pu=!1,3e4));const q=O.filter(({channel:H,update:oe})=>{var P,ee,y;const B=(P=(ee=d.$set)===null||ee===void 0?void 0:ee[H.property])!==null&&P!==void 0?P:be((y=d.properties)===null||y===void 0?void 0:y.$set)?d.properties.$set[H.property]:void 0;return oe?.pending&&B===oe.value});this.du.emit("eventCaptured",d);const K=(i=n?._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),X=n?._batchKey==="recordings"||/\/s\/(?:\?|$)/.test(K),k=b(b(b({method:"POST",url:K,data:d,compression:"best-available",preferSyncCompression:n?.send_instantly,timestampMode:X?"body":"capture-body",batchKey:n?._batchKey},X&&(!((s=d.properties)===null||s===void 0)&&s.$session_id)?{batchGroup:d.properties.$session_id+(d.properties.$window_id?`-${d.properties.$window_id}`:"")}:{}),n?.transport?{transport:n.transport}:{}),q.length?{fireCallbackOnDrop:!0,callback:H=>{if(H.statusCode>=200&&300>H.statusCode)for(const{channel:oe,update:P}of q)this.dh(oe,P.value)}}:{});if(!this.config.request_batching||n&&!n?._batchKey||n?.send_instantly||q.length){var ne;let H;!k.transport&&!k.callback&&bt((ne=this.config.request_headers)!==null&&ne!==void 0?ne:{})&&this.Cu&&(H="sendBeacon"),this.ju(k,H)}else this.qu.enqueue(k);return d}_addCaptureHook(t){return this.on("eventCaptured",r=>t(r.event,r))}getExtension(t){var r;return(r=this.Xu)===null||r===void 0?void 0:r.getExtension(t)}Zu(){var t;return(t=this.Xu)!==null&&t!==void 0?t:this.Xu=new Px(this)}fu(t){this.Eu.push(t);let r=!0;return()=>{if(!r)return;r=!1;const n=this.Eu.indexOf(t);n!==-1&&this.Eu.splice(n,1)}}gh(t=!0){var r,n,i;return!!(!((r=this.persistence)===null||r===void 0)&&r.consumeCookieIdentityChange())&&(this.Ou=null,this.persistence.get_property("$user_state")==="anonymous"&&((i=this.sessionPersistence)===null||i===void 0||i.clear(),this.Iu.clear(),this.mh()),(n=this.featureFlags)===null||n===void 0||n.reset(),t&&this.reloadFeatureFlags(),!0)}calculateEventProperties(t,r,n,i,s){if(n=n||new Date,!this.persistence||!this.sessionPersistence)return r;this.persistence.syncCookieProperties(),this.gh();const o=s?void 0:this.persistence.remove_event_timer(t);let a=b({},r);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,this.yu()&&(a[py]=!0),t==="$snapshot"){const w=b(b({},this.persistence.properties()),this.sessionPersistence.properties());return a.distinct_id=w.distinct_id,(!ye(a.distinct_id)&&!Ze(a.distinct_id)||Zi(a.distinct_id))&&j.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}const c=(function(w,S,O,R=!1){var I,C,L,q;if(!ft)return{};const K=w?[...li,...S||[]]:[],[X,k]=x_(ft),[ne,H]=(function(Ie){for(let _e=0;kp.length>_e;_e++){const[ge,Je,Xe]=kp[_e],Ce=Ie.match(ge);if(Ce){const z=Xe&&Ie.match(Xe)||Ce;return[Je,z?.[1]||""]}}return["",""]})(ft),oe=(function(){const Ie="u">typeof navigator?navigator:void 0;return Ie?.brave?{brave:!0}:{}})(),P={};M(O)||(P.detectGoogleSearchApp=O);const ee={},y=(I=navigator)===null||I===void 0||(I=I.userAgentData)===null||I===void 0?void 0:I.platform,B=(C=navigator)===null||C===void 0?void 0:C.maxTouchPoints,Y=A==null||(L=A.screen)===null||L===void 0?void 0:L.width,le=A==null||(q=A.screen)===null||q===void 0?void 0:q.height,de=A?.devicePixelRatio;M(y)||(ee.userAgentDataPlatform=y),M(B)||(ee.maxTouchPoints=B),M(Y)||(ee.screenWidth=Y),M(le)||(ee.screenHeight=le),M(de)||(ee.devicePixelRatio=de);const Oe=ze(Sd({$os:X,$os_version:k,$browser:$_(ft,navigator.vendor,oe,P),$webview_app:ne,$webview_app_version:H,$device:M_(ft),$device_type:_$(ft,ee),$timezone:Zy(),$timezone_offset:X1()}),{$current_url:_s(R?Jr(je?.href):je?.href,K,ys),$host:je?.host,$pathname:je?.pathname,$raw_user_agent:ft.length>1e3?ft.substring(0,997)+"...":ft,$browser_version:m$(ft,navigator.vendor,oe,P),$browser_language:Hy(),$browser_language_prefix:Y1(),$screen_height:A?.screen.height,$screen_width:A?.screen.width,$viewport_height:A?.innerHeight,$viewport_width:A?.innerWidth,$lib:vr.LIB_NAME,$lib_version:vr.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3});return vr.SDK_DIST_CHANNEL&&(Oe.$sdk_dist_channel=vr.SDK_DIST_CHANNEL),Oe})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties,this.config.detect_google_search_app,this.config.disable_capture_url_hashes);if(this.sessionManager){const{sessionId:w,windowId:S}=this.sessionManager.checkAndGetSessionAndWindowId(s,n.getTime(),!0);a.$session_id=w,a.$window_id=S}this.sessionPropsManager&&ze(a,this.sessionPropsManager.getSessionProps());try{var u;if(this.sessionRecording){const w=this.sessionRecording.sdkDebugProperties,S=!this.Pu&&kf(t);for(const O in w)(S||ce(Ox,O))&&(a[O]=w[O])}a.$sdk_debug_retry_queue_size=(u=this.Bu)===null||u===void 0?void 0:u.length}catch(w){a.$sdk_debug_error_capturing_properties=String(w)}let l;if(this.requestRouter.region===nl&&(a.$lib_custom_api_host=this.config.api_host),l=t!=="$pageview"||s?t!=="$pageleave"||s?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(n):this.pageViewManager.doPageView(n,i),a=ze(a,l),t==="$pageview"&&D&&(a.title=D.title),!M(o)){const w=n.getTime()-o;a.$duration=parseFloat((w/1e3).toFixed(3))}ft&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser");const h=this.persistence.properties(),d=this.sessionPersistence.properties(),p=a.$groups,f=h.$groups;be(p)&&!bt(p)&&(a.$groups=b(b({},be(f)?f:{}),p)),Pe(["$referrer","$referring_domain"],w=>{w in h&&delete d[w]});const v={};if(this.Eu.length>0)for(const w of this.Eu.slice())try{ze(v,w())}catch(S){j.error("Failed to produce browser extension event properties",S)}a=ze({},c,h,d,b(b({},v),a)),a.$is_identified=this._isIdentified(),ue(this.config.property_denylist)?Pe(this.config.property_denylist,function(w){delete a[w]}):j.error(m0+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);const g=this.config.sanitize_properties;g&&(j.error(Ef),a=g(a,t));const m=this.yh();return a.$process_person_profile=m,m&&!s&&this.bh("_calculate_event_properties"),a}ph(t,r=!0,n=!1){var i;if(!this.persistence||!this.yh()||this.Tu&&!n)return t;const s=this.persistence.get_initial_props(),o=(i=this.sessionPropsManager)===null||i===void 0?void 0:i.getSetOnceProps();let a=ze({},s,o||{},t||{});const c=this.config.sanitize_properties;return c&&(j.error(Ef),a=c(a,"$set_once")),r&&(this.Tu=!0),bt(a)?void 0:a}register(t,r){var n;(n=this.persistence)===null||n===void 0||n.register(t,r)}register_once(t,r,n){var i;(i=this.persistence)===null||i===void 0||i.register_once(t,r,n)}register_for_session(t){var r,n;(r=this.persistence)===null||r===void 0||r.syncCookieProperties(),this.gh(),(n=this.sessionPersistence)===null||n===void 0||n.register(t),Object.keys(t).forEach(i=>this.Iu.add(i)),this.mh()}unregister(t){var r;(r=this.persistence)===null||r===void 0||r.unregister(t)}unregister_for_session(t){var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t),this.Iu.delete(t),this.mh()}_h(t,r){this.register({[t]:r})}Hu(){this.Iu.forEach(t=>{var r;(r=this.sessionPersistence)===null||r===void 0||r.unregister(t)}),this.Iu.clear(),this.mh()}mh(){var t;if(!this.Mu)return;if(this.config.persistence==="memory"||!((t=this.sessionPersistence)===null||t===void 0)&&t.hi||!xe.Et())return void xe.Lt(this.Mu);const r=[];this.Iu.forEach(n=>r.push(n)),r.length>0?xe.$t(this.Mu,r):xe.Lt(this.Mu)}getFeatureFlag(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlag(t,r)}getFeatureFlagPayload(t){var r;return(r=this.featureFlags)===null||r===void 0?void 0:r.getFeatureFlagPayload(t)}getFeatureFlagResult(t,r){var n;return(n=this.featureFlags)===null||n===void 0?void 0:n.getFeatureFlagResult(t,r)}getAllFeatureFlags(){var t,r;return(t=(r=this.featureFlags)===null||r===void 0?void 0:r.getAllFeatureFlags())!==null&&t!==void 0?t:[]}isFeatureEnabled(t,r){var n,i;return(n=(i=this.featureFlags)===null||i===void 0?void 0:i.isFeatureEnabled(t,r))!==null&&n!==void 0?n:r?.defaultValue}reloadFeatureFlags(){var t;(t=this.featureFlags)===null||t===void 0||t.reloadFeatureFlags()}updateFlags(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateFlags(t,r,n)}updateEarlyAccessFeatureEnrollment(t,r,n){var i;(i=this.featureFlags)===null||i===void 0||i.updateEarlyAccessFeatureEnrollment(t,r,n)}getEarlyAccessFeatures(t,r=!1,n){var i;return(i=this.featureFlags)===null||i===void 0?void 0:i.getEarlyAccessFeatures(t,r,n)}on(t,r){return this.du.on(t,r)}onFeatureFlags(t){return this.featureFlags?this.featureFlags.onFeatureFlags(t):(t([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded(t){return this.surveys?this.surveys.onSurveysLoaded(t):(t([],{isLoaded:!1,error:xn}),()=>{})}onSessionId(t){var r,n;return(r=(n=this.sessionManager)===null||n===void 0?void 0:n.onSessionId(t))!==null&&r!==void 0?r:()=>{}}getSurveys(t,r=!1){this.surveys?this.surveys.getSurveys(t,r):t([],{isLoaded:!1,error:xn})}getActiveMatchingSurveys(t,r=!1){this.surveys?this.surveys.getActiveMatchingSurveys(t,r):t([],{isLoaded:!1,error:xn})}onActiveMatchingSurveysChanged(t){return this.surveys?this.surveys.onActiveMatchingSurveysChanged(t):(t([],{isLoaded:!1,error:xn}),()=>{})}renderSurvey(t,r){var n;(n=this.surveys)===null||n===void 0||n.renderSurvey(t,r)}displaySurvey(t,r=Ex){var n;(n=this.surveys)===null||n===void 0||n.displaySurvey(t,r)}cancelPendingSurvey(t){var r;(r=this.surveys)===null||r===void 0||r.cancelPendingSurvey(t)}canRenderSurvey(t){var r,n;return(r=(n=this.surveys)===null||n===void 0?void 0:n.canRenderSurvey(t))!==null&&r!==void 0?r:{visible:!1,disabledReason:xn}}canRenderSurveyAsync(t,r=!1){var n,i;return(n=(i=this.surveys)===null||i===void 0?void 0:i.canRenderSurveyAsync(t,r))!==null&&n!==void 0?n:Promise.resolve({visible:!1,disabledReason:xn})}wh(t){return!t||Zi(t)?(j.critical("Unique user id has not been set in posthog.identify"),!1):t==="$posthog_cookieless"?(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.`),!1):!["distinct_id","distinctid"].includes(t.toLowerCase())&&!["undefined","null"].includes(t.toLowerCase())||(j.critical(`The string "${t}" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.`),!1)}identify(t,r,n){if(!this.__loaded||!this.persistence)return j.uninitializedWarning("posthog.identify");if(Ze(t)&&(t=t.toString(),j.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),!this.wh(t)||!this.bh("posthog.identify"))return;this.ku();const i=this.get_distinct_id(),s=this.persistence.syncCookieProperties()&&this.get_distinct_id()!==i,o=this.gh(!1),a=this.persistence.Oa();let c=!1;try{const l=this.get_distinct_id();this.register({$user_id:t}),this.get_property("$device_id")||this.register_once({$had_persisted_distinct_id:!0,$device_id:l},""),t!==l&&t!==this.get_property("__alias")&&(this.unregister(Vo),this.register({distinct_id:t}));const h=(this.persistence.get_property("$user_state")||"anonymous")===pr,d=t!==l,p=!d&&h;if(d&&h){var u;const f=this.config.reuseAnonymousId?{distinct_id:t}:{distinct_id:t,$anon_distinct_id:l};this.persistence.set_property(vt,_o),this.setPersonPropertiesForFlags({$set:r||{},$set_once:n||{}},!1),this.config.cookieWinsOnConflict&&this.persistence.Da(),this.capture("$identify",f,{$set:r||{},$set_once:n||{}})&&(this.Ou=xc(t,r,n)),(u=this.featureFlags)===null||u===void 0||u.setAnonymousDistinctId(this.config.reuseAnonymousId?void 0:l)}else if(p){this.persistence.set_property(vt,_o);const f=r||{},v=n||{};this.setPersonPropertiesForFlags({$set:f,$set_once:v},!1),this.config.cookieWinsOnConflict&&this.persistence.Da(),this.capture("$set",{$set:f,$set_once:v})&&(this.Ou=xc(t,r,n))}else(r||n)&&this.setPersonProperties(r,n);d||s||o?(this.reloadFeatureFlags(),this.featureFlags?this.featureFlags.resetFlagCallReported():this.unregister(Mr)):p&&(r||n)&&this.reloadFeatureFlags(),c=!0}finally{a&&this.persistence.qa(c)}}setPersonProperties(t,r){if(!t&&!r||!this.bh("posthog.setPersonProperties"))return;const n=xc(this.get_distinct_id(),t,r);this.Ou!==n?(this.setPersonPropertiesForFlags({$set:t||{},$set_once:r||{}},!0),this.capture("$set",{$set:t||{},$set_once:r||{}})&&(this.Ou=n)):j.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}unsetPersonProperties(t){var r;const n=(ue(t)?t:[t]).filter(i=>ye(i)&&i.length>0);n.length!==0&&this.bh("posthog.unsetPersonProperties")&&((r=this.featureFlags)===null||r===void 0||r.unsetPersonPropertiesForFlags(n,!0),this.capture("$set",{$unset:n}),this.Ou=null)}group(t,r,n){var i;if(!t||!r)return void j.error("posthog.group requires a group type and group key");(i=this.persistence)===null||i===void 0||i.syncCookieProperties(),this.gh();const s=this.getGroups(),o=s[t]!==r;if(o&&this.resetGroupPropertiesForFlags(t),this.register({$groups:b(b({},s),{},{[t]:r})}),(o||n)&&this.yh()){const a={$group_type:t,$group_key:r};n&&(a.$group_set=n),this.capture(Bp,a)}n&&this.setGroupPropertiesForFlags({[t]:n}),o&&!n&&this.reloadFeatureFlags()}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(t,r=!0){var n;(n=this.featureFlags)===null||n===void 0||n.setPersonPropertiesForFlags(t,r)}resetPersonPropertiesForFlags(t=!0){var r;(r=this.featureFlags)===null||r===void 0||r.resetPersonPropertiesForFlags(t)}setGroupPropertiesForFlags(t,r=!0){var n;this.bh("posthog.setGroupPropertiesForFlags")&&((n=this.featureFlags)===null||n===void 0||n.setGroupPropertiesForFlags(t,r))}resetGroupPropertiesForFlags(t){var r;(r=this.featureFlags)===null||r===void 0||r.resetGroupPropertiesForFlags(t)}reset(t){const r=gt(t)?t:t?.resetDeviceID,n=gt(t)||t==null?void 0:t.bootstrap;this.kh(r,!1,n)}kh(t,r=!1,n){var i,s,o,a,c,u;if(j.info("reset"),!this.__loaded)return j.uninitializedWarning("posthog.reset");const l=n?.sessionID;this.config.bootstrap=n||((i=this.Lu)===null||i===void 0?void 0:i.bootstrap)||{},(s=this.featureFlags)===null||s===void 0||(o=s.updateConfig)===null||o===void 0||o.call(s,this.config,this.il());const h=this.get_property(fd),d=this.get_property(mc),p=this.get_property(Ki);(a=this.sessionRecording)===null||a===void 0||a.flushBeforeIdentityReset();const f=this.is_capturing();this.consent.reset(),r||!f||this.is_capturing()||console.warn("[PostHog.js]","reset() cleared the stored consent, and capturing is now off because of `opt_out_capturing_by_default`. Call opt_in_capturing() again, and prefer calling reset() before opting in rather than after.");const v=(c=this.persistence)===null||c===void 0||(u=c.Oa)===null||u===void 0?void 0:u.call(c);let g=!1;try{var m,w,S,O,R,I,C,L,q,K,X,k,ne;if((m=this.persistence)===null||m===void 0||m.clear(),(w=this.sessionPersistence)===null||w===void 0||w.clear(),this.Iu.clear(),this.mh(),M(p)||(K=this.persistence)===null||K===void 0||K.register({$session_recording_remote_config:p}),(S=this.surveys)===null||S===void 0||S.reset(),(O=this.featureFlags)===null||O===void 0||O.reset(),(R=this.conversations)===null||R===void 0||R.reset(),(I=this.logs)===null||I===void 0||I.reset(),(C=this.metrics)===null||C===void 0||C.reset(),(L=this.persistence)===null||L===void 0||L.set_property("$user_state","anonymous"),(q=this.sessionManager)===null||q===void 0||q.resetSessionId(),this.Ou=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:_c,$device_id:null},"");else{const P=this.config.get_device_id(Ft());this.register_once({distinct_id:P,$device_id:t?P:h},""),t||M(d)||this.register({[mc]:d})}if(this.register({$last_posthog_reset:new Date().toISOString()},1),n&&(n.distinctID&&!this.yu()&&((ne=this.persistence)===null||ne===void 0||ne.set_property("$user_state",n.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.distinctID})),(X=this.featureFlags)===null||X===void 0||X.initialize(),!fe(l)&&!(!((k=this.sessionManager)===null||k===void 0)&&k.setBootstrapSessionId(l,!0)))){const P=b({},n);delete P.sessionID,this.config.bootstrap=P}delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,g=!0}finally{var H,oe;v&&((H=this.persistence)===null||H===void 0||(oe=H.qa)===null||oe===void 0||oe.call(H,g))}this.reloadFeatureFlags()}shutdown(t){var r=this;return Ue(function*(){var n,i,s,o,a,c,u,l;if(r.__loaded){r.$u=!0,r.Zu().dispose(),(n=r.sessionRecording)===null||n===void 0||n.dispose(),(i=r.logs)===null||i===void 0||i.flushLogs("sendBeacon"),(s=r.metrics)===null||s===void 0||s.flush("sendBeacon"),(o=r.metrics)===null||o===void 0||o.dispose(),(a=r.qu)===null||a===void 0||a.unload(),(c=r.Bu)===null||c===void 0||c.unload();try{var h;(h=r.featureFlags)===null||h===void 0||h.destroy()}catch(d){j.error("Error while destroying feature flags",d)}(u=r.persistence)===null||u===void 0||u.destroy(),(l=r.sessionPersistence)===null||l===void 0||l.destroy()}else j.uninitializedWarning("posthog.shutdown")})()}setIdentity(t,r){var n;delete this.config.identity_claims,this.config.identity_distinct_id=t,this.config.identity_hash=r,this.alias(t),(n=this.conversations)===null||n===void 0||n.Sh()}clearIdentity(){var t;delete this.config.identity_distinct_id,delete this.config.identity_hash,delete this.config.identity_claims,(t=this.conversations)===null||t===void 0||t.xh()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var t,r;return(t=(r=this.sessionManager)===null||r===void 0?void 0:r.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&t!==void 0?t:""}get_session_replay_url(t){if(!this.sessionManager)return"";const{sessionId:r,sessionStartTimestamp:n}=this.sessionManager.checkAndGetSessionAndWindowId(!0);let i=this.requestRouter.endpointFor("ui",`/project/${this.config.token}/replay/${r}`);if(t?.withTimestamp&&n){var s;const o=(s=t.timestampLookBack)!==null&&s!==void 0?s:10;if(!n)return i;i+=`?t=${Math.max(Math.floor((new Date().getTime()-n)/1e3)-o,0)}`}return i}alias(t,r){return t===this.get_property("$people_distinct_id")?(j.critical("Attempting to create alias for existing People user - aborting."),-2):this.bh("posthog.alias")?(M(r)&&(r=this.get_distinct_id()),t!==r?(this._h(Vo,t),this.capture("$create_alias",{alias:t,distinct_id:r})):(j.warn("alias matches current distinct_id - skipping api call."),this.identify(t),-1)):void 0}set_config(t){const r=b({},this.config);if(be(t)){var n,i,s,o,a,c,u,l,h,d,p,f,v,g;ze(this.config,Tf(t));const w=this.Su();(n=this.persistence)===null||n===void 0||n.update_config(this.config,r,w),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Ac(b(b({},this.config),{},{persistence:"sessionStorage"}),w,!1);const S=this.Du(this.config.debug);var m;gt(S)&&(this.config.debug=S),gt(this.config.debug)&&(this.config.debug?(et.DEBUG=!0,ke.Et()&&ke.$t("ph_debug",!0),j.info("set_config",{config:t,oldConfig:r,newConfig:b({},this.config)})):(et.DEBUG=!1,ke.Et()&&ke.Lt("ph_debug"))),(i=this.featureFlags)===null||i===void 0||(s=i.updateConfig)===null||s===void 0||s.call(i,this.config,this.il()),(o=this.exceptionObserver)===null||o===void 0||o.onConfigChange(),(a=this.exceptions)===null||a===void 0||a.onConfigChange(),(c=this.metrics)===null||c===void 0||c.onConfigChange(),(u=this.sessionRecording)===null||u===void 0||u.startIfEnabledOrStop(),(l=this.tracingHeaders)===null||l===void 0||l.startIfEnabledOrStop(),(h=this.autocapture)===null||h===void 0||h.startIfEnabled(),(d=this.heatmaps)===null||d===void 0||d.startIfEnabled(),("capture_pageview"in t||"disable_capture_url_hashes"in t)&&((m=this.historyAutocapture)===null||m===void 0||m.startIfEnabledOrStop()),(p=this.exceptionObserver)===null||p===void 0||p.startIfEnabledOrStop(),(f=this.deadClicksAutocapture)===null||f===void 0||f.startIfEnabledOrStop(),(v=this.surveys)===null||v===void 0||v.loadIfEnabled(),this.xu(),(g=this.externalIntegrations)===null||g===void 0||g.startIfEnabledOrStop(),!r.segment&&this.config.segment&&this.persistence&&of(this,ns,!1)}}_overrideSDKInfo(t,r){et.LIB_NAME=t,et.LIB_VERSION=r}startSessionRecording(t){const r=t===!0,n={sampling:r||!!t?.sampling,linked_flag:r||!!t?.linked_flag,url_trigger:r||!!t?.url_trigger,event_trigger:r||!!t?.event_trigger};var i,s,o,a,c;Object.values(n).some(Boolean)&&((i=this.sessionManager)===null||i===void 0||i.checkAndGetSessionAndWindowId(),n.sampling&&((s=this.sessionRecording)===null||s===void 0||s.overrideSampling()),n.linked_flag&&((o=this.sessionRecording)===null||o===void 0||o.overrideLinkedFlag()),n.url_trigger&&((a=this.sessionRecording)===null||a===void 0||a.overrideTrigger("url")),n.event_trigger&&((c=this.sessionRecording)===null||c===void 0||c.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var t;return!!(!((t=this.sessionRecording)===null||t===void 0)&&t.started)}captureException(t,r){try{if(!this.exceptions)return;const n=this.exceptions.buildProperties(t,{handled:!0,syntheticException:new Error("PostHog syntheticException")});return this.exceptions.sendExceptionEvent(b(b({},n),r))}catch{return}}addExceptionStep(t,r){var n;(n=this.exceptions)===null||n===void 0||n.addExceptionStep(t,r)}captureLog(t){var r;(r=this.logs)===null||r===void 0||r.captureLog(t)}get logger(){var t,r;return(t=(r=this.logs)===null||r===void 0?void 0:r.logger)!==null&&t!==void 0?t:kr.Ch}startExceptionAutocapture(t){this.set_config({capture_exceptions:t==null||t})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(t){var r,n;return(r=(n=this.toolbar)===null||n===void 0?void 0:n.loadToolbar(t))!==null&&r!==void 0&&r}get_property(t){var r;return(r=this.persistence)===null||r===void 0?void 0:r.props[t]}getSessionProperty(t){var r;return(r=this.sessionPersistence)===null||r===void 0?void 0:r.props[t]}toString(){var t;let r=(t=this.config.name)!==null&&t!==void 0?t:ji;return r!==ji&&(r="posthog."+r),r}_isIdentified(){var t,r;return((t=this.persistence)===null||t===void 0?void 0:t.get_property("$user_state"))==="identified"||((r=this.sessionPersistence)===null||r===void 0?void 0:r.get_property("$user_state"))==="identified"}yh(){var t,r;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&bt(this.getGroups())&&!(!((t=this.persistence)===null||t===void 0||(t=t.props)===null||t===void 0)&&t.__alias)&&!(!((r=this.persistence)===null||r===void 0||(r=r.props)===null||r===void 0)&&r.$epp))}ih(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&!!this.config.capture_pageview}createPersonProfile(){this.yh()||this.bh("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.bh("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}bh(t){return this.config.person_profiles==="never"?(j.error(t+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.bu(),this._h(md,!0),!0)}Su(){if(this.config.cookieless_mode==="always")return!0;const t=this.consent.isOptedOut();return this.config.disable_persistence||t&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!=="on_reject")}xu(){var t,r;const n=this.Su();var i,s,o;return this.is_capturing()||(i=this.logs)===null||i===void 0||i.$h(),((t=this.persistence)===null||t===void 0?void 0:t.hi)!==n&&((s=this.persistence)===null||s===void 0||s.set_disabled(n)),((r=this.sessionPersistence)===null||r===void 0?void 0:r.hi)!==n&&((o=this.sessionPersistence)===null||o===void 0||o.set_disabled(n)),n&&(this.Iu.clear(),this.mh()),n}opt_in_capturing(t){var r;if(this.config.cookieless_mode!=="always"){if(this.yu()){var n,i,s,o,a,c;(n=this.sessionRecording)===null||n===void 0||n.dispose({discardBufferedEvents:!0}),this.kh(!0,!0),(i=this.sessionManager)===null||i===void 0||i.destroy(),(s=this.pageViewManager)===null||s===void 0||s.destroy(),this.sessionManager=new yf(this),this.pageViewManager=new af(this),this.persistence&&(this.sessionPropsManager=new mf(this,this.sessionManager,this.persistence));const p=(o=(a=this.config.__extensionClasses)===null||a===void 0?void 0:a.sessionRecording)!==null&&o!==void 0?o:(c=kr.__defaultExtensionClasses)===null||c===void 0?void 0:c.sessionRecording;var u,l;p&&(this.sessionRecording=this.mu(this.sessionRecording,new p(this)),this.cu&&((u=this.sessionRecording)===null||u===void 0||(l=u.onRemoteConfig)===null||l===void 0||l.call(u,this.cu)))}var h,d;this.consent.optInOut(!0),this.xu(),this.Yu(),(r=this.sessionRecording)===null||r===void 0||r.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&((h=this.surveys)===null||h===void 0||h.loadIfEnabled()),(M(t?.captureEventName)||t!=null&&t.captureEventName)&&this.capture((d=t?.captureEventName)!==null&&d!==void 0?d:"$opt_in",t?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.th()}else j.warn(Sf)}opt_out_capturing(){if(this.config.cookieless_mode==="always")return void j.warn(Sf);const t=this.config.cookieless_mode==="on_reject"?this.sessionRecording:void 0;var r,n;t?.dispose({discardBufferedEvents:!0}),this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.kh(!0,!0),this.consent.optInOut(!1),this.xu(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:_c,$device_id:null}),this.gu(t),this.sessionRecording=void 0,(r=this.sessionManager)===null||r===void 0||r.destroy(),(n=this.pageViewManager)===null||n===void 0||n.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,this.config.capture_pageview&&this.th(),this.Yu())}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){const t=this.consent.consent;return t===1?"granted":t===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.xu()}_is_bot(){return rt?d0(rt,this.config.custom_blocked_useragents):void 0}th(){D&&(D.visibilityState==="visible"?this.Ru||(this.Ru=!0,this.capture(wd,{title:D.title},{send_instantly:!0}),this.Au&&(D.removeEventListener(vs,this.Au),this.Au=null)):this.Au||(this.Au=this.th.bind(this),Ae(D,vs,this.Au)))}debug(t){t===!1?(A?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(A?.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)`."),this.set_config({debug:!0}))}il(){const t=this.Lu||{};return"advanced_disable_flags"in t?!!t.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(j.warn("Config field 'advanced_disable_decide' is deprecated. Please use 'advanced_disable_flags' instead. The old field will be removed in a future major version."),!0):(function(r,n,i,s,o){const a=n in r&&!fe(r[n]),c=i in r&&!fe(r[i]);return a?r[n]:!!c&&(o&&o.warn(`Config field '${i}' is deprecated. Please use '${n}' instead. The old field will be removed in a future major version.`),r[i])})(t,"advanced_disable_flags","advanced_disable_decide",0,j)}Os(t){var r;if(fe(this.config.before_send))return t;const n=Object.keys((r=t.properties)!==null&&r!==void 0?r:{}).filter(o$),i=ue(this.config.before_send)?this.config.before_send:[this.config.before_send];let s=t;for(const o of i)try{if(s=o(s),fe(s)){const a=`Event '${t.event}' was rejected in beforeSend function`;return s$(t.event)?j.warn(`${a}. This can cause unexpected behavior.`):j.info(a),null}s.properties&&!bt(s.properties)||j.warn(`Event '${t.event}' has no properties after beforeSend function, this is likely an error.`)}catch(a){return j.error(`Error in beforeSend function for event '${t.event}':`,a),null}for(const o of n)if(s.properties&&fe(s.properties[o]))return j.warn(`Event '${t.event}' had its '${o}' property removed in a beforeSend function. This property is required for ingestion, so the event will be dropped.`),null;return s}getPageViewId(){var t;return(t=this.pageViewManager.Wo)===null||t===void 0?void 0:t.pageViewId}captureTraceFeedback(t,r){this.capture("$ai_feedback",{$ai_trace_id:String(t),$ai_feedback_text:r})}captureTraceMetric(t,r,n){this.capture("$ai_metric",{$ai_trace_id:String(t),$ai_metric_name:r,$ai_metric_value:String(n)})}Du(t){const r=gt(t)&&!t,n=ke.Et()&&ke.Ot("ph_debug")==="true";return!r&&(!!n||t)}};is.__defaultExtensionClasses={},is.Ch=(()=>{const e=()=>{};return{trace:e,debug:e,info:e,warn:e,error:e,fatal:e}})(),(function(e,t){for(let r=0;t.length>r;r++)e.prototype[t[r]]=R1(e.prototype[t[r]])})(is,["identify"]);var _0=class{constructor(e){this.disabled=e===!1;const t=be(e)?e:{};this.thresholdPx=t.threshold_px||30,this.timeoutMs=t.timeout_ms||1e3,this.clickCount=t.click_count||3,this.clicks=[]}isRageClick(e,t,r){if(this.disabled)return!1;const n=this.clicks[this.clicks.length-1];if(n&&Math.abs(e-n.x)+Math.abs(t-n.y)<this.thresholdPx&&this.timeoutMs>r-n.timestamp){if(this.clicks.push({x:e,y:t,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:t,timestamp:r}];return!1}},Nc="$copy_autocapture",Dc=Ve("[AutoCapture]");function zc(e,t){return t.length>e?t.slice(0,e)+"...":t}function Dx(e){if(e.previousElementSibling)return e.previousElementSibling;let t=e;do t=t.previousSibling;while(t&&!tr(t));return t}function zx(e,{e:t,maskAllElementAttributes:r,maskAllText:n,elementAttributeIgnoreList:i,elementsChainAsString:s,disableCaptureUrlHashes:o}){var a,c;if(!tr(e))return{props:{}};const u=[e],l=new Set([e]);let h=e;for(;h.parentNode&&!ct(h,"body")&&1e3>u.length;){if(Ed(h.parentNode)){const I=h.parentNode.host;if(l.has(I))break;l.add(I),u.push(I),h=I;continue}if(!tr(h.parentNode)||l.has(h.parentNode))break;l.add(h.parentNode),u.push(h.parentNode),h=h.parentNode}const d=t.type==="click"&&e.namespaceURI==="http://www.w3.org/2000/svg"?u.findIndex(I=>ct(I,"button")||ct(I,"a")):-1;d>0&&(n=n||u.slice(0,d+1).some(I=>!Kn(I)||ms(I)));const p=[],f={};let v,g=!1,m=!1;if(Pe(u,I=>{const C=Kn(I);if(ct(I,"a")&&!r&&!i?.includes("href")){const L=I.getAttribute("href");g=!!(C&&L&&es(L))&&(o?Jr(L):L)}ce(ci(I),"ph-no-capture")&&(m=!0),p.push((function(L,q,K,X,k=!1){const ne=L.tagName.toLowerCase(),H={tag_name:ne};Id.indexOf(ne)>-1&&!K&&(H.$el_text=ne.toLowerCase()==="a"||ne.toLowerCase()==="button"?zc(1024,rf(L)):zc(1024,gs(L)));const oe=ci(L);q||X!=null&&X.includes("class")||0>=oe.length||(H.classes=oe.filter(function(B){return B!==""})),Pe(L.attributes,function(B){var Y;if((!ms(L)||["name","id","class","aria-label"].indexOf(B.name)!==-1)&&!X?.includes(B.name)&&!q&&es(B.value)&&(!ye(Y=B.name)||Y.substring(0,10)!=="_ngcontent"&&Y.substring(0,7)!=="_nghost")){let le=B.value;B.name==="class"&&(le=kd(le).join(" ")),H["attr__"+B.name]=zc(1024,B.name==="href"&&k?Jr(le):le)}});let P=1,ee=1,y=L;for(;y=Dx(y);)P++,y.tagName===L.tagName&&ee++;return H.nth_child=P,H.nth_of_type=ee,H})(I,r,n,i,o)),Pe((function(L){if(!Kn(L))return{};const q={};return Pe(L.attributes,function(K){if(K.name&&K.name.indexOf("data-ph-capture-attribute")===0){const X=K.name.replace("data-ph-capture-attribute-",""),k=K.value;X&&k&&es(k)&&(q[X]=k)}}),q})(I),(L,q)=>{({}).hasOwnProperty.call(f,q)||(f[q]=L)})}),m)return{props:{},explicitNoCapture:m};if(d>0&&(e=u[d],p.splice(0,d)),n||(p[0].$el_text=ct(e,"a")||ct(e,"button")?rf(e):gs(e)),g){var w,S;p[0].attr__href=g;const I=(w=_r(g))===null||w===void 0?void 0:w.host,C=A==null||(S=A.location)===null||S===void 0?void 0:S.host;I&&C&&I!==C&&(v=g)}return{props:ze((R=t.type,{$event_type:R,$ce_version:1}),s?{}:{$elements:p},{$elements_chain:(O=p,ue(O)?(function(I){return I.map(C=>{var L,q;let K="";if(C.tag_name&&(K+=C.tag_name),C.attr_class){C.attr_class.sort();for(const ne of C.attr_class)K+=`.${ne.replace(/"/g,"")}`}const X=b(b(b(b({},C.text?{text:C.text}:{}),{},{"nth-child":(L=C.nth_child)!==null&&L!==void 0?L:0,"nth-of-type":(q=C.nth_of_type)!==null&&q!==void 0?q:0},C.href?{href:C.href}:{}),C.attr_id?{attr_id:C.attr_id}:{}),C.attributes),k={};return yo(X).sort(([ne],[H])=>(function(oe,P){return P>oe?-1:oe>P?1:0})(ne,H)).forEach(([ne,H])=>k[nf(ne.toString())]=nf(H.toString())),K+=":",K+=yo(k).map(([ne,H])=>`${ne}="${H}"`).join(""),K}).join(";")})((function(I){return I.map(C=>{var L,q;const K={text:(L=C.$el_text)===null||L===void 0?void 0:L.slice(0,400),tag_name:C.tag_name,href:(q=C.attr__href)===null||q===void 0?void 0:q.slice(0,2048),attr_class:H1(C),attr_id:C.attr__id,nth_child:C.nth_child,nth_of_type:C.nth_of_type,attributes:{}};return yo(C).filter(([X])=>X.indexOf("attr__")===0).forEach(([X,k])=>K.attributes[X]=k),K})})(O)):"")},!((a=p[0])===null||a===void 0)&&a.$el_text?{$el_text:(c=p[0])===null||c===void 0?void 0:c.$el_text}:{},v&&t.type==="click"?{$external_click_url:v}:{},f),target:e};var O,R}var Ux=class{do(){this.vo=void 0,clearTimeout(this.fo),this.fo=void 0}po(e){var t;if(!Kn(e))return!0;const r=(t=this.mo().css_selector_ignorelist)!==null&&t!==void 0?t:kc,n=new Set;let i=e;for(;i;){if(n.size>=1e3||n.has(i))return!0;n.add(i);const s=i,o=ci(s);if(ce(o,"ph-no-capture")||ce(o,"ph-sensitive")||ms(s)||r.some(c=>Ku(s,c)))return!0;const a=i.parentNode;i=Ed(a)?a.host:a&&tr(a)?a:null}return!1}yo(e){if(!this.isEnabled||e.type==="pointercancel")return void this.do();if(e.type==="pointerdown"){this.do();const n=Qi(e);var t;e.isPrimary&&e.button===0&&!e.ctrlKey&&n&&tr(n)&&(this.vo={target:n,excluded:this.po(n),id:e.pointerId,x:e.clientX,y:e.clientY,released:!1,distinctId:(t=this.bo)===null||t===void 0?void 0:t.distinctId});return}const r=this.vo;r&&(e.pointerId!==r.id||Math.abs(e.clientX-r.x)>5||Math.abs(e.clientY-r.y)>5?this.do():e.type==="pointerup"&&(r.released=!0,this.fo=setTimeout(()=>this.do(),0)))}_o(e){var t;const r=this.vo;this.do();const n=Qi(e);if(r?.released&&r.target.isConnected&&r.distinctId===((t=this.bo)===null||t===void 0?void 0:t.distinctId)&&e.pointerId===r.id&&(e.detail>0||e.pointerType==="touch"||e.pointerType==="pen")&&e.button===0&&5>=Math.abs(e.clientX-r.x)&&5>=Math.abs(e.clientY-r.y)&&n&&(ct(n,"html")||ct(n,"body"))){var i;if(r.excluded)return null;const s=(i=this.mo().css_selector_ignorelist)!==null&&i!==void 0?i:kc;return[n,D?.documentElement,D?.body].some(o=>{if(!o)return!1;const a=ci(o);return ce(a,"ph-no-capture")||ce(a,"ph-sensitive")||!Kn(o)||ms(o)||s.some(c=>Ku(o,c))})?null:r.target}}constructor(e){this.wo=e,this.name="autocapture",this.ko=!1,this.So=null,this.xo=!1,this.Co=new Map,this.$o=!1,this.Ir={enabled:!1,rageclick:!1,maskAllElementAttributes:!1,maskAllText:!1,disableCaptureUrlHashes:!1,remoteRequestsDisabled:!1},this.To=!1,this.wo.refresh(this.Ir),this.rageclicks=new _0(this.Ir.rageclick),this.Io=null}setup(e){this.Mo(),this.bo=e;const t=e.onRemoteConfig(this.onRemoteConfig.bind(this));this.To?t.dispose():(this.Eo=t,this.startIfEnabled())}dispose(){var e;this.To||(this.To=!0,this.bo=void 0,(e=this.Eo)===null||e===void 0||e.dispose(),this.Eo=void 0,this.Co.clear(),this.Io=null,this.Po())}mo(){return this.wo.refresh(this.Ir),this.Ir}Mo(){var e,t;return this.mo(),this.Ir.url_allowlist=(e=this.Ir.url_allowlist)===null||e===void 0?void 0:e.map(r=>new RegExp(r)),this.Ir.url_ignorelist=(t=this.Ir.url_ignorelist)===null||t===void 0?void 0:t.map(r=>new RegExp(r)),this.Ir}Ro(){if(!this.isBrowserSupported())return void Dc.info("Disabling Automatic Event Collection because this browser is not supported");if(!A||!D)return;const e=this.Ao=t=>{t=t||A?.event;try{if(t.type==="blur")return void this.do();if(t.type.indexOf("pointer")===0)return void this.yo(t);const r=t.type==="click"?this._o(t):void 0;if(He(r))return;this.Fo(t,"$autocapture",r)}catch(r){Dc.error("Failed to capture event",r)}};if(Ae(A,"blur",e),Ae(D,"submit",e,{capture:!0}),Ae(D,"change",e,{capture:!0}),Ae(D,"click",e,{capture:!0}),Pe(["pointerdown","pointermove","pointerup","pointercancel"],t=>{Ae(D,t,e,{capture:!0})}),this.mo().capture_copied_text){const t=this.Oo=r=>{r=r||A?.event;try{this.Fo(r,Nc)}catch(n){Dc.error("Failed to capture clipboard event",n)}};Ae(D,"copy",t,{capture:!0}),Ae(D,"cut",t,{capture:!0}),Ae(D,"paste",t,{capture:!0})}}Po(){this.do(),this.Ao&&(A?.removeEventListener("blur",this.Ao),Pe(["pointerdown","pointermove","pointerup","pointercancel"],e=>{D?.removeEventListener(e,this.Ao,!0)}),D?.removeEventListener("submit",this.Ao,!0),D?.removeEventListener("change",this.Ao,!0),D?.removeEventListener("click",this.Ao,!0),this.Ao=void 0),this.Oo&&(D?.removeEventListener("copy",this.Oo,!0),D?.removeEventListener("cut",this.Oo,!0),D?.removeEventListener("paste",this.Oo,!0),this.Oo=void 0),this.ko=!1}startIfEnabled(){this.isEnabled||this.do(),!this.To&&this.bo&&this.isEnabled&&!this.ko&&(this.Ro(),this.ko=!0)}onRemoteConfig(e){if(this.To)return;if(this.xo=!0,!e.ok)return void this.startIfEnabled();const t=e.config;t.elementsChainAsString&&(this.$o=t.elementsChainAsString);const r=t.autocapture_opt_out;var n;gt(r)&&((n=this.bo)===null||n===void 0||n.kv.set("$autocapture_disabled_server_side",r),this.So=r),this.startIfEnabled()}setElementSelectors(e,t=this){if(this.To)return;e.size?this.Co.set(t,new Set(e)):this.Co.delete(t);const r=new Set;this.Co.forEach(n=>{n.forEach(i=>r.add(i))}),this.Io=r}getElementSelectors(e,t){var r;const n=[];return(r=this.Io)===null||r===void 0||r.forEach(i=>{D?.querySelectorAll(i)?.forEach(s=>{e!==s&&t!==s||ce(n,i)||n.push(i)})}),n}get isEnabled(){var e,t;if(this.To)return!1;const r=(e=this.bo)===null||e===void 0?void 0:e.kv.get(ry),n=this.So,i=this.mo();if(!i.remoteRequestsDisabled&&!this.xo)return!1;const s=i.remoteRequestsDisabled&&!this.xo;if(He(n)&&!gt(r)&&!s)return!1;const o=(t=this.So)!==null&&t!==void 0?t:!!r;return!!i.enabled&&!o}Fo(e,t="$autocapture",r){if(!this.isEnabled)return void this.do();let n=r||Qi(e);Py(n)&&(n=n.parentNode||null);const i=this.Mo();var s;t==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&i.rageclick&&(s=this.rageclicks)!==null&&s!==void 0&&s.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&xy(n,i.rageclick)&&this.Fo(e,"$rageclick",r);const o=t===Nc,a=o?b(b({},i),{},{dom_event_allowlist:void 0}):i;if(n&&(function(h,d,p,f,v,g){var m;if(!A||Ad(h)||p?.url_allowlist&&!Jp(p.url_allowlist,g)||p?.url_ignorelist&&Jp(p.url_ignorelist,g))return!1;if(p?.dom_event_allowlist){const R=p.dom_event_allowlist;if(R&&!R.some(I=>d.type===I))return!1}const{parentIsUsefulElement:w,targetElementList:S}=My(h,f);if(!(function(R,I){const C=I?.element_allowlist;if(M(C))return!0;for(const L of R)if(C.some(q=>L.tagName.toLowerCase()===q))return!0;return!1})(S,p)||!Yu(S,p?.css_selector_allowlist)||Yu(S,(m=p?.css_selector_ignorelist)!==null&&m!==void 0?m:kc))return!1;try{const R=A.getComputedStyle(h);if(R&&R.getPropertyValue("cursor")==="pointer"&&d.type==="click")return!0}catch{}const O=h.tagName.toLowerCase();switch(O){case"html":return!1;case"form":return(v||["submit"]).indexOf(d.type)>=0;case"input":case"select":case"textarea":return(v||["change","click"]).indexOf(d.type)>=0;default:return w?(v||["click"]).indexOf(d.type)>=0:(v||["click"]).indexOf(d.type)>=0&&(Id.indexOf(O)>-1||h.getAttribute("contenteditable")==="true")}})(n,e,a,o,o?["copy","cut","paste"]:void 0,{config:{get_current_url:i.getCurrentUrl}})){var c;const{props:h,explicitNoCapture:d,target:p}=zx(n,{e,maskAllElementAttributes:i.maskAllElementAttributes,maskAllText:i.maskAllText,elementAttributeIgnoreList:i.element_attribute_ignorelist,elementsChainAsString:this.$o,disableCaptureUrlHashes:i.disableCaptureUrlHashes});if(d)return!1;const f=this.getElementSelectors(n,p);if(f&&f.length>0&&(h.$element_selectors=f),t===Nc){const v=e.type||"clipboard";if(v!=="paste"){var u,l;const g=A==null||(u=A.getSelection())===null||u===void 0?void 0:u.toString(),m=Oy(g);if(!m)return!1;h.$selected_content=m,h.$clipboard_text_length=(l=g?.length)!==null&&l!==void 0?l:0}h.$copy_type=v}return(c=this.bo)===null||c===void 0||c.capture(t,h),!0}}isBrowserSupported(){return tt(D?.querySelectorAll)}},Fx=class{constructor(e){this._instance=e}refresh(e){const t=this._instance.config,r=be(t.autocapture)?t.autocapture:void 0;e.enabled=!!t.autocapture,e.rageclick=t.rageclick,e.maskAllElementAttributes=t.mask_all_element_attributes,e.maskAllText=t.mask_all_text,e.disableCaptureUrlHashes=t.disable_capture_url_hashes,e.getCurrentUrl=t.get_current_url,e.remoteRequestsDisabled=this._instance.il(),e.url_allowlist=r?.url_allowlist,e.url_ignorelist=r?.url_ignorelist,e.dom_event_allowlist=r?.dom_event_allowlist,e.element_allowlist=r?.element_allowlist,e.css_selector_allowlist=r?.css_selector_allowlist,e.css_selector_ignorelist=r?.css_selector_ignorelist,e.element_attribute_ignorelist=r?.element_attribute_ignorelist,e.capture_copied_text=r?.capture_copied_text}},Li=Ve("[ExceptionAutocapture]"),Rf=()=>{},Pf=e=>{var t;if(tt(e))return(t=e.__posthog_layer__)!==null&&t!==void 0?t:e.__rrweb_layer__};function bs(e,t,r){try{if(!(t in e))return Rf;const n={next:e[t]},i=r(function(...s){return n.next.apply(this,s)});return tt(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0},__posthog_layer__:{enumerable:!1,value:n}})),e[t]=i,()=>{if(e[t]===i)return void(e[t]=n.next);let s=e[t],o=Pf(s);for(;o;){if(o.next===i)return void(o.next=n.next);s=o.next,o=Pf(s)}}}catch{return Rf}}var qx=Ve("[TracingHeaders]"),rn=Ve("[Web Vitals]"),Of=9e5,Cf=["CLS","FCP","INP","LCP"],jx=["INP","LCP"],Hx=["interactionTarget","interactionType","inputDelay","processingDuration","presentationDelay","loadState","target","url","timeToFirstByte","resourceLoadDelay","resourceLoadDuration","elementRenderDelay","largestShiftTarget","largestShiftTime","largestShiftValue","firstByteToFCP"],Uc="disabled",$f="lazy_loading",or=Ve("[SessionRecording]"),Bx=[_d,yd,gy,my,_y,yy,by,wy,Sy],Vx=Ve("[Heatmaps]");function Fc(e){return be(e)&&"clientX"in e&&"clientY"in e&&Ze(e.clientX)&&Ze(e.clientY)}var Ys=Ve("[Product Tours]"),qc=e=>{var t;return!e.config.disable_product_tours&&!!(!((t=e.persistence)===null||t===void 0)&&t.get_property(gd))},Gx=["$set_once","$set"],Gt=Ve("[SiteApps]"),xf="Error while initializing PostHog app with config id ",y0=(e,t)=>e?.then?e.then(t):t(e),Mn="SDK is not enabled or survey functionality is not yet loaded",Mf="Disabled. Not loading surveys.",Zx=class{constructor(e,t){this.wo=e,this.Th=t,this.name="surveys",this._surveyEventReceiver=null,this._surveyManager=null,this.Ih=!1,this.Mh=!1,this.Eh=[],this.Ph=[],this.Rh=null,this.Ah=null,this.To=!1,this.Fh=new Set,this.onRemoteConfig=r=>{if(this.To||this.Ir.disableSurveys)return;if(!r.ok)return this.Mh=!0,this.Oh({isLoaded:!1,error:"Remote config unavailable. Not loading surveys."}),Re.warn("Remote config unavailable. Not loading surveys.");const n=r.config.surveys;if(fe(n))return Re.warn("Flags not loaded yet. Not loading surveys.");this.Dh=gt(n)?n:n.length>0,Re.info(`flags response received, isSurveysEnabled: ${this.Dh}`),this.loadIfEnabled()},this.Oh=r=>{this.Ph.slice().forEach(n=>this.Lh(n,r))}}setup(e){if(!this.To)return this.Nh=e,y0(e.kv.initialize(),()=>{if(this.Nh!==e||this.To)return;this.Nh=void 0,this.bo=e;const t=e.onRemoteConfig(this.onRemoteConfig);this.To?t.dispose():(this.Eo=t,this.loadIfEnabled())})}dispose(){var e,t,r,n,i;this.To||(this.To=!0,this.Nh=void 0,this.bo=void 0,(e=this.Eo)===null||e===void 0||e.dispose(),this.Eo=void 0,(t=this._surveyEventReceiver)===null||t===void 0||t.dispose(),this._surveyEventReceiver=null,(r=this._surveyManager)===null||r===void 0||(n=r.dispose)===null||n===void 0||n.call(r),this._surveyManager=null,this.Eh=[],this.Ph.forEach(s=>{s.active=!1}),this.Ph=[],(i=this.qh)===null||i===void 0||i.call(this),this.qh=void 0,this.Rh=null,this.Fh.forEach(s=>clearTimeout(s)),this.Fh.clear())}get Ir(){return this.wo.get()}initialize(){this.loadIfEnabled()}reset(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.clearInMemoryInProgressSurveyState)===null||t===void 0||t.call(e);try{var r;(r=this._surveyEventReceiver)===null||r===void 0||r.reset(),localStorage.removeItem("lastSeenSurveyDate");const n=[];for(let i=0;i<localStorage.length;i++){const s=localStorage.key(i);(s!=null&&s.startsWith("seenSurvey_")||s!=null&&s.startsWith("inProgressSurvey_"))&&n.push(s)}n.forEach(i=>localStorage.removeItem(i))}catch{}this.Oh()}loadIfEnabled(){if(this.To||!this.bo)return;const e=this.Ir;if(this._surveyManager)return;if(this.Ih)return void Re.info("Already initializing surveys, skipping...");if(e.disableSurveys)return void Re.info(Mf);if(e.cookielessMode&&this.wo.isOptedOut())return void Re.info("Not loading surveys in cookieless mode without consent.");const t=this.wo.getExtensions();if(!t)return void this.jh("PostHog Extensions not found.");if(M(this.Dh)&&!e.advancedEnableSurveys)return;const r=this.Dh||e.advancedEnableSurveys;this.Ih=!0,this.Mh=!1;try{const n=t.generateSurveys;if(n)return this.Bh(n,r),void(this.Ih=!1);const i=t.loadExternalDependency;if(!i)return this.jh(bd),void(this.Ih=!1);i(s=>{try{if(this.To)return;const o=this.wo.getExtensions();s||!o?.generateSurveys?this.jh("Could not load surveys script",s):this.Bh(o.generateSurveys,r)}finally{this.Ih=!1}})}catch(n){throw this.Ih=!1,this.jh("Error initializing surveys",n),n}}Bh(e,t){var r,n;if(this.To)return;this._surveyManager=e(t),this._surveyEventReceiver=this.wo.createEventReceiver(this.Oh);const i=(r=(n=this.bo)!==null&&n!==void 0?n:this.Th)===null||r===void 0?void 0:r.kv.get(Fi);i&&this.Hh(i),Re.info("Surveys loaded successfully"),this.zh(),this.Oh(),this.Uh({isLoaded:!0})}jh(e,t){this.Mh=!0,Re.error(e,t),this.Oh({isLoaded:!1,error:e}),this.Uh({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.Eh.push(e),this._surveyManager&&this.Uh({isLoaded:!0}),()=>{this.Eh=this.Eh.filter(t=>t!==e)}}getSurveys(e,t=!1){var r;const n=(r=this.bo)!==null&&r!==void 0?r:this.Th;if(!n||this.To)return;if(this.Ir.disableSurveys)return Re.info(Mf),e([]);const i=n.kv.get(Fi);if(i&&!t)return e(i,{isLoaded:!0}),void(this.Wh()&&this.getSurveys(()=>{},!0));if(this.Rh)return void this.Rh.then(({surveys:a,context:c})=>{this.To||e(a,c)}).catch(a=>Re.error("Error in survey callback",a));const s=this.Vh("/api/surveys/",{method:"GET",query:{token:n.projectToken},sentAt:"query",timeoutMs:this.Ir.requestTimeoutMs}).then(a=>{try{return this.Gh(n,a)}catch(c){return Re.error("Error processing surveys response",c),this.Gh(n,{statusCode:0,error:c})}},a=>this.Gh(n,{statusCode:0,error:a}));this.Rh=s;const o=()=>{this.Rh===s&&(this.Rh=null)};s.then(a=>{o(),this.To||(this.Oh(a.context),e(a.surveys,a.context))},o).catch(a=>Re.error("Error in survey callback",a))}Vh(e,t){const r=this.bo;return r?r.sendRequest(e,t):new Promise(n=>n({statusCode:0,error:new Error(Mn)}))}Gh(e,t){if(this.To)return{surveys:[],context:{isLoaded:!1,error:Mn}};const r=t.statusCode;if(r!==200||!t.json){const i=`Surveys API could not be loaded, status: ${r}`;return r!==0?Re.error(i):t.error||Re.warn(i),this.Ah=Date.now(),{surveys:[],context:{isLoaded:!1,error:i}}}this.Ah=null;const n=t.json.surveys||[];return e.kv.set({[Fi]:n,[Go]:Date.now()}),this.Hh(n),{surveys:n,context:{isLoaded:!0}}}Hh(e){var t;const r=e.filter(n=>(function(i){return!(!i.start_date||i.end_date)})(n)&&(p0(n)||(function(i){var s;return!!(!((s=i.conditions)===null||s===void 0||(s=s.actions)===null||s===void 0||(s=s.values)===null||s===void 0)&&s.length)})(n)));(t=this._surveyEventReceiver)===null||t===void 0||t.replace(r)}Wh(){return this.Zh()&&!this.Rh&&!this.Qh()}Zh(){var e,t;const r=(e=(t=this.bo)!==null&&t!==void 0?t:this.Th)===null||e===void 0?void 0:e.kv.get(Go);return Ze(r)&&Date.now()-r>3e5}Qh(){return Ze(this.Ah)&&3e5>Date.now()-this.Ah}markSurveyAsSeen(e,t){var r;const n={id:e,current_iteration:(r=t?.iteration)!==null&&r!==void 0?r:null};g0(n);try{localStorage.setItem("lastSeenSurveyDate",new Date().toISOString())}catch{}this.Oh()}Uh(e){for(const t of this.Eh)try{if(!e.isLoaded)return t([],e);this.getSurveys(t)}catch(r){Re.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,t=!1){if(!fe(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,t);Re.warn("init was not called")}onActiveMatchingSurveysChanged(e){var t,r;if(this.To)return()=>{};const n={callback:e,active:!0,revision:0};this.Ph.push(n),this.zh();const i=(t=(r=this.bo)!==null&&r!==void 0?r:this.Th)===null||t===void 0?void 0:t.kv.get(Fi);return this.Ir.disableSurveys||!this._surveyManager&&this.Mh&&!this.Ih||!i&&!fe(this.Ah)&&!this.Rh?this.Lh(n,{isLoaded:!1}):this._surveyManager&&this.Lh(n),()=>{var s;n.active=!1,this.Ph=this.Ph.filter(o=>o!==n),this.Ph.length===0&&((s=this.qh)===null||s===void 0||s.call(this),this.qh=void 0)}}zh(){var e,t,r;this._surveyManager&&this.Ph.length>0&&((e=this.qh)!==null&&e!==void 0||(this.qh=(t=(r=this.wo).onMatchingConditionsChanged)===null||t===void 0?void 0:t.call(r,this.Oh)))}Lh(e,t){if(this.To||!e.active)return;const r=++e.revision,n=i=>{if(!this.To&&e.active&&r===e.revision)try{const s=t??{isLoaded:!0},o=JSON.stringify([i,s]);if(o===e.lastResult)return;e.lastResult=o,e.callback(i,s)}catch(s){Re.error("Error in active matching surveys callback",s)}};try{t&&!t.isLoaded?n([]):this.getActiveMatchingSurveys(n)}catch(i){Re.error("Error in active matching surveys callback",i)}}Jh(e){let t=null;return this.getSurveys(r=>{var n;t=(n=r.find(i=>i.id===e))!==null&&n!==void 0?n:null}),t}Kh(e){if(fe(this._surveyManager))return{eligible:!1,reason:Mn};const t=typeof e=="string"?this.Jh(e):e;return t?this._surveyManager.checkSurveyEligibility(t):{eligible:!1,reason:"Survey not found"}}Xh(e){if(!this.wo.isCapturing())return{eligible:!1,reason:"PostHog is not capturing, so a survey response cannot be recorded"};if(fe(this._surveyManager))return{eligible:!1,reason:Mn};const t=typeof e=="string"?this.Jh(e):e;return t?this._surveyManager.checkSurveyRenderability(t):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(fe(this._surveyManager))return Re.warn("init was not called"),{visible:!1,disabledReason:Mn};const t=this.Xh(e);return{visible:t.eligible,disabledReason:t.reason}}canRenderSurveyAsync(e,t){return fe(this._surveyManager)?(Re.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Mn})):new Promise(r=>{this.getSurveys(n=>{var i;const s=(i=n.find(o=>o.id===e))!==null&&i!==void 0?i:null;if(s){const o=this.Xh(s);r({visible:o.eligible,disabledReason:o.reason})}else r({visible:!1,disabledReason:"Survey not found"})},t)})}renderSurvey(e,t,r){var n;if(!this.wo.isCapturing())return;if(fe(this._surveyManager))return void Re.warn("init was not called");const i=typeof e=="string"?this.Jh(e):e;if(!i?.id)return void Re.warn("Survey not found");if(!Sx.includes(i.type))return void Re.warn(`Surveys of type ${i.type} cannot be rendered in the app`);const s=D?.querySelector(t);if(s){if(!((n=i.appearance)===null||n===void 0)&&n.surveyPopupDelaySeconds){Re.info(`Rendering survey ${i.id} with delay of ${i.appearance.surveyPopupDelaySeconds} seconds`);const o=setTimeout(()=>{var a,c;this.Fh.delete(o),!this.To&&this.wo.isCapturing()&&(Re.info(`Rendering survey ${i.id} with delay of ${(a=i.appearance)===null||a===void 0?void 0:a.surveyPopupDelaySeconds} seconds`),(c=this._surveyManager)===null||c===void 0||c.renderSurvey(i,s,r),Re.info(`Survey ${i.id} rendered`))},1e3*i.appearance.surveyPopupDelaySeconds);this.Fh.add(o);return}this._surveyManager.renderSurvey(i,s,r)}else Re.warn("Survey element not found")}displaySurvey(e,t){var r;if(!this.wo.isCapturing())return;if(fe(this._surveyManager))return void Re.warn("init was not called");const n=this.Jh(e);if(!n)return void Re.warn("Survey not found");let i=n;if((r=n.appearance)!==null&&r!==void 0&&r.surveyPopupDelaySeconds&&t.ignoreDelay&&(i=b(b({},n),{},{appearance:b(b({},n.appearance),{},{surveyPopupDelaySeconds:0})})),t.displayType!==Xu.Popover&&t.initialResponses&&Re.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),t.ignoreConditions===!1){const s=this.Kh(n);if(!s.eligible)return void Re.warn("Survey is not eligible to be displayed: ",s.reason)}t.displayType!==Xu.Inline?this._surveyManager.handlePopoverSurvey(i,t):this.renderSurvey(i,t.selector,t.properties)}cancelPendingSurvey(e){fe(this._surveyManager)?Re.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e,t;(e=this._surveyManager)===null||e===void 0||(t=e.handlePageUnload)===null||t===void 0||t.call(e)}};function Ln(e,t,r){if(fe(e))return!1;switch(r){case"exact":return e===t;case"contains":{const n=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(n,"i").test(e)}case"regex":try{return new RegExp(t).test(e)}catch{return!1}default:return!1}}var Wx=class{constructor(e){this._instance=e,this.Yh=new Set,this.tc=new Set,this.ec=new Xo,this.nc=(t,r)=>this.sc(t,r)&&this.rc(t,r)&&this.oc(t,r)&&this.ac(t,r),this.sc=(t,r)=>!r?.event||t?.event===r?.event}init(){var e,t;M((e=this._instance)===null||e===void 0?void 0:e._addCaptureHook)||(this.lc=(t=this._instance)===null||t===void 0?void 0:t._addCaptureHook((r,n)=>{this.on(r,n)}))}dispose(){var e,t;(e=this.lc)===null||e===void 0||e.call(this),this.lc=void 0,(t=this._instance)===null||t===void 0||(t=t.autocapture)===null||t===void 0||t.setElementSelectors(new Set,this),this.ec=new Xo}register(e){var t,r;if(!M((t=this._instance)===null||t===void 0?void 0:t._addCaptureHook)&&(e.forEach(n=>{var i;this.Yh.add(n),(i=n.steps)===null||i===void 0||i.forEach(s=>{this.tc.add(s?.event||"")})}),(r=this._instance)===null||r===void 0?void 0:r.autocapture)){const n=new Set;this.Yh.forEach(i=>{var s;(s=i.steps)===null||s===void 0||s.forEach(o=>{o!=null&&o.selector&&n.add(o.selector)})}),this._instance.autocapture.setElementSelectors(n,this)}}replace(e){this.Yh.clear(),this.tc.clear(),this.register(e)}on(e,t){t!=null&&e.length!=0&&(this.tc.has(e)||this.tc.has(t.event))&&this.Yh.forEach(r=>{this.uc(t,r)&&this.ec.emit("actionCaptured",r.name)})}hc(e){this.onAction("actionCaptured",t=>e(t))}uc(e,t){if(t?.steps==null)return!1;for(const r of t.steps)if(this.nc(e,r))return!0;return!1}onAction(e,t){return this.ec.on(e,t)}rc(e,t){if(t?.url){var r;const n=e==null||(r=e.properties)===null||r===void 0?void 0:r.$current_url;if(!n||typeof n!="string"||!Ln(n,t.url,t.url_matching||"contains"))return!1}return!0}oc(e,t){return!!this.cc(e,t)&&!!this.dc(e,t)&&!!this.vc(e,t)}cc(e,t){var r;if(!t?.href)return!0;const n=this.fc(e);if(n.length>0)return n.some(s=>Ln(s.href,t.href,t.href_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&Ln((function(s){const o=s.match(/(?::|")href="(.*?)"/);return o?o[1]:""})(i),t.href,t.href_matching||"exact")}dc(e,t){var r;if(!t?.text)return!0;const n=this.fc(e);if(n.length>0)return n.some(c=>Ln(c.text,t.text,t.text_matching||"exact")||Ln(c.$el_text,t.text,t.text_matching||"exact"));const i=(e==null||(r=e.properties)===null||r===void 0?void 0:r.$elements_chain)||"";return!!i&&(s=(function(c){const u=[],l=/(?::|")text="(.*?)"/g;let h;for(;!fe(h=l.exec(c));)u.includes(h[1])||u.push(h[1]);return u})(i),o=t.text,a=t.text_matching||"exact",s.some(c=>Ln(c,o,a)));var s,o,a}vc(e,t){var r,n;if(!t?.selector)return!0;const i=e==null||(r=e.properties)===null||r===void 0?void 0:r.$element_selectors;if(i?.includes(t.selector))return!0;const s=(e==null||(n=e.properties)===null||n===void 0?void 0:n.$elements_chain)||"";if(t.selector_regex&&s)try{return new RegExp(t.selector_regex).test(s)}catch{return!1}return!1}fc(e){var t;return(e==null||(t=e.properties)===null||t===void 0?void 0:t.$elements)==null?[]:e?.properties.$elements}ac(e,t){return!t?.properties||t.properties.length===0||v0(t.properties.reduce((r,n)=>{const i=ue(n.value)?n.value.map(String):n.value!=null?[String(n.value)]:[];return r[n.key]={values:i,operator:n.operator||"exact"},r},{}),e?.properties)}},Jx=class{constructor(e,t){var r,n;this.gc=[],this._instance=e,this.mc=t,this.yc=new Map,this.bc=new Map,this._c=new Map,this.wc=(r=this._instance)===null||r===void 0||(n=r.onSessionId)===null||n===void 0?void 0:n.call(r,i=>this.kc(i))}Sc(e){return!1}xc(){return null}Cc(e){}$c(){}Tc(e,t){return!!e&&v0(e.propertyFilters,t?.properties)}Ic(e,t){const r=new Map;return e.forEach(n=>{var i;(i=n.conditions)===null||i===void 0||(i=i[t])===null||i===void 0||(i=i.values)===null||i===void 0||i.forEach(s=>{if(s?.name){const o=r.get(s.name)||[];o.push(n.id),r.set(s.name,o)}})}),r}Mc(e,t,r){const n=(r===$i.Activation?this.yc:this.bc).get(e);let i=[];return this.Ec(s=>{i=s.filter(o=>n?.includes(o.id))}),i.filter(s=>{var o;const a=(o=s.conditions)===null||o===void 0||(o=o[r])===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.find(c=>c.name===e);return this.Tc(a,t)})}register(e){this.Pc(e,!1)}replace(e){this.Pc(e,!0)}Pc(e,t){var r;M((r=this._instance)===null||r===void 0?void 0:r._addCaptureHook)||(this.Rc(e,t),this.Ac(e,t))}Ac(e,t){const r=e.filter(s=>{var o;return(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||(o=o.values)===null||o===void 0?void 0:o.length});var n;if(t&&this._c.clear(),r.length===0)return void(t&&((n=this.Fc)===null||n===void 0||n.replace([])));this.Fc||(this.Fc=new Wx(this._instance),this.Fc.init(),this.Fc.hc(s=>this.onAction(s)));const i=[];r.forEach(s=>{var o;(o=s.conditions)===null||o===void 0||(o=o.actions)===null||o===void 0||o.values.forEach(a=>{if(i.push(a),a.name){var c;const u=(c=this._c.get(a.name))!==null&&c!==void 0?c:[];u.includes(s.id)||u.push(s.id),this._c.set(a.name,u)}})}),t?this.Fc.replace(i):this.Fc.register(i)}Oc(e,t){t.forEach((r,n)=>{var i;const s=(i=e.get(n))!==null&&i!==void 0?i:[];r.forEach(o=>{s.includes(o)||s.push(o)}),e.set(n,s)})}Rc(e,t){var r,n;const i=e.filter(c=>{var u,l;return((u=c.conditions)===null||u===void 0?void 0:u.events)&&((l=c.conditions)===null||l===void 0||(l=l.events)===null||l===void 0||(l=l.values)===null||l===void 0?void 0:l.length)>0}),s=e.filter(c=>{var u,l;return((u=c.conditions)===null||u===void 0?void 0:u.cancelEvents)&&((l=c.conditions)===null||l===void 0||(l=l.cancelEvents)===null||l===void 0||(l=l.values)===null||l===void 0?void 0:l.length)>0}),o=this.Ic(e,$i.Activation),a=this.Ic(e,$i.Cancellation);t?(this.yc=o,this.bc=a):(this.Oc(this.yc,o),this.Oc(this.bc,a)),(i.length!==0||s.length!==0||e.some(c=>{var u;return(u=c.conditions)===null||u===void 0||(u=u.actions)===null||u===void 0||(u=u.values)===null||u===void 0?void 0:u.length}))&&((r=this.lc)!==null&&r!==void 0||(this.lc=(n=this._instance)===null||n===void 0?void 0:n._addCaptureHook((c,u)=>{this.onEvent(c,u)})))}onEvent(e,t){var r,n;const i=this.Dc(),s=(t==null||(r=t.properties)===null||r===void 0?void 0:r.$survey_id)||(t==null||(n=t.properties)===null||n===void 0?void 0:n.$product_tour_id);if(s&&this.getActivatedIds().includes(s)){const a=this.Lc(e,s,t);if(a==="consume")return i.info("event consumed activated item, removing it",{event:e,itemId:s}),void this.Nc([s]);if(a==="persist")return i.info("shown item promoted to persisted activation",{event:e,itemId:s}),this.qc(s),void this.jc([s])}if(this.bc.has(e)){const a=this.Mc(e,t,$i.Cancellation);a.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:a.map(c=>c.id)}),this.Nc(a.map(c=>c.id)),a.forEach(c=>this.Bc(c.id)))}if(!this.yc.has(e))return;i.info("event name matched",{event:e,eventPayload:t,items:this.yc.get(e)});const o=this.Mc(e,t,$i.Activation);this.Hc(o.map(a=>a.id))}onAction(e){this._c.has(e)&&this.Hc(this._c.get(e)||[])}Hc(e){var t,r;if(e.length===0)return;const n=!!(!((t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0)&&r.call(t)),i=[];for(const s of e)n&&this.Sc(s)?this.qc(s)&&this.zc(s):i.push(s);i.length>0&&(this.gc=[...new Set([...this.gc,...i])]),this.Dc().info("updating activated items",{activatedItems:this.getActivatedIds()}),this.Uc()}qc(e){this.gc=this.gc.filter(r=>r!==e);const t=this.Wc();return!t.includes(e)&&(this.Vc([...t,e]),this.Gc(),!0)}Nc(e){const t=new Set(e);this.gc=this.gc.filter(i=>!t.has(i));const r=this.Zc(),n=r.filter(i=>!t.has(i));n.length!==r.length&&(this.Vc(n),n.length===0&&this.Qc()),this.jc(e),this.Uc()}Uc(){try{var e;(e=this.mc)===null||e===void 0||e.call(this)}catch(t){this.Dc().error("Error while handling activated items change",t)}}Jc(){var e;const t=this.xc();if(!t)return{};const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t];return r&&typeof r=="object"?r:{}}zc(e){if(!this.xc())return;const t=this.Jc();this.Cc(b(b({},t),{},{[e]:Date.now()}))}jc(e){if(!this.xc())return;const t=this.Jc(),r={};let n=!1;for(const[i,s]of Object.entries(t))e.includes(i)?n=!0:r[i]=s;n&&(bt(r)?this.$c():this.Cc(r))}Kc(){this.xc()&&this.$c()}getActivationTimestamp(e){if(!this.Wc().includes(e))return;const t=this.Jc()[e];return Ze(t)?t:void 0}Zc(){var e;const t=this.Xc();return((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[t])||[]}Wc(){var e,t,r;const n=this.Zc();if(n.length===0)return[];const i=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.props[this.Yc()],s=(t=this._instance)===null||t===void 0||(r=t.get_session_id)===null||r===void 0?void 0:r.call(t);return s&&i===s?n:[]}Gc(){var e,t;const r=(e=this._instance)===null||e===void 0||(t=e.get_session_id)===null||t===void 0?void 0:t.call(e);r&&this.td(r)}Qc(){this.ed()}kc(e){var t;const r=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.props[this.Yc()];if(r&&r!==e){const n=this.Zc(),i=this.Jc();n.length>0&&(this.Vc([]),n.filter(s=>Ze(i[s])).forEach(s=>this.Bc(s))),this.Qc(),this.Kc(),n.length>0&&this.Uc()}}getActivatedIds(){return[...new Set([...this.Wc(),...this.gc])].filter(e=>!this.nd(e))}dispose(){var e,t,r;(e=this.wc)===null||e===void 0||e.call(this),this.wc=void 0,(t=this.lc)===null||t===void 0||t.call(this),this.lc=void 0,(r=this.Fc)===null||r===void 0||r.dispose(),this.Fc=void 0}reset(){this.gc=[],this.Zc().length>0&&this.Vc([]),this.Qc(),this.Kc(),this.Uc()}getEventToItemsMap(){return this.yc}sd(){return this.Fc}},Kx=class extends Jx{constructor(e,t){super(e,t)}Xc(){return cy}Yc(){return uy}xc(){return ly}Cc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_timestamps:e})}$c(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_timestamps")}Sc(e){var t;let r;this.Ec(i=>{r=i.find(s=>s.id===e)});const n=r==null||(t=r.appearance)===null||t===void 0?void 0:t.surveyPopupDelaySeconds;return Ze(n)&&n>0}rd(){return Et.SHOWN}Ec(e){var t;(t=this._instance)===null||t===void 0||t.getSurveys(e)}Bc(e){var t;(t=this._instance)===null||t===void 0||t.cancelPendingSurvey(e)}Dc(){return Re}Vc(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated:e})}td(e){var t;(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0||t.register({$surveys_activated_session:e})}ed(){var e;(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||e.unregister("$surveys_activated_session")}nd(){return!1}Lc(e,t,r){var n;if(e===Et.SENT&&(r==null||(n=r.properties)===null||n===void 0?void 0:n.$survey_completed)===!1)return"ignore";let i;return this.Ec(s=>{i=s.find(o=>o.id===t)}),!i||(function(s){var o;return p0(s)&&!!(!((o=s.conditions)===null||o===void 0||(o=o.events)===null||o===void 0)&&o.repeatedActivation)||s.schedule==="always"})(i)?e===Et.SHOWN?"consume":"ignore":e===Et.SHOWN?"persist":e===Et.DISMISSED||e===Et.SENT?"consume":"ignore"}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}},Yx=class{constructor(e){this._instance=e}initialize(){}get(e){if(typeof e=="string")return this._instance.get_property(e);const t={};for(const r of e){const n=this._instance.get_property(r);M(n)||(t[r]=n)}return t}set(e,t){this._instance.register(typeof e=="string"?{[e]:t}:e)}remove(e){typeof e!="string"?e.forEach(t=>this._instance.unregister(t)):this._instance.unregister(e)}},Xx=class{constructor(e){this._instance=e}get(){const e=this._instance.config;return{disableSurveys:e.disable_surveys,cookielessMode:!!e.cookieless_mode,advancedEnableSurveys:e.advanced_enable_surveys,requestTimeoutMs:e.surveys_request_timeout_ms}}isOptedOut(){return this._instance.consent.isOptedOut()}isCapturing(){return this._instance.is_capturing()}getExtensions(){const e=re?.__PosthogExtensions__;if(!e)return;const{generateSurveys:t,loadExternalDependency:r}=e;return{generateSurveys:t?n=>t(this._instance,n):void 0,loadExternalDependency:r?n=>r(this._instance,"surveys",n):void 0}}createEventReceiver(e){return new Kx(this._instance,e)}onMatchingConditionsChanged(e){const t=this._instance._addCaptureHook(s=>{s!=="$pageview"&&s!==Et.SHOWN&&s!==Et.DISMISSED&&s!==Et.SENT||e()}),r=()=>e();Ae(A,"PHSurveyShown",r);let n=!1;const i=this._instance.onFeatureFlags(()=>{n&&e()});return n=!0,()=>{n=!1,t(),i(),A?.removeEventListener("PHSurveyShown",r)}}},Qx=A?.location?Jo(A.location.hash,"__posthog")||Jo(location.hash,"state"):null,Lf="_postHogToolbarParams",Nf=Ve("[Toolbar]"),Df=Ve("[FeatureFlags]"),eM=class{constructor(e,t=!1){this.od=!1,this.update(e,t)}update(e,t){this.ad=((r,n)=>{var i,s,o,a,c,u,l,h;return{bootstrap:{featureFlags:(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlags)!==null&&i!==void 0?i:void 0,featureFlagPayloads:(o=(a=r.bootstrap)===null||a===void 0?void 0:a.featureFlagPayloads)!==null&&o!==void 0?o:void 0},remoteRequestsDisabled:n,featureFlagsDisabled:!!r.advanced_disable_feature_flags,onlyEvaluateSurveyFeatureFlags:!!r.advanced_only_evaluate_survey_feature_flags,deduplicateCallsPerSession:!!r.advanced_feature_flags_dedup_per_session,cacheTtlMs:r.feature_flag_cache_ttl_ms,refreshIntervalMs:(c=r.remote_config_refresh_interval_ms)!==null&&c!==void 0?c:3e5,idleRefreshBackoff:M(r.remote_config_refresh_interval_ms),requestTimeoutMs:r.feature_flag_request_timeout_ms,requestMaxRetries:Math.max(0,(u=r.feature_flag_request_max_retries)!==null&&u!==void 0?u:1),compression:r.disable_compression?void 0:"best-available",evaluationContexts:(l=(h=r.evaluation_contexts)!==null&&h!==void 0?h:r.evaluation_environments)!==null&&l!==void 0?l:[],flagKeys:ue(r.flag_keys)?r.flag_keys:void 0}})(e,t),!e.evaluation_environments||e.evaluation_contexts||this.od||(Df.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.od=!0),M(e.flag_keys)||ue(e.flag_keys)||Df.error("Invalid flag_keys found:",e.flag_keys,"Expected array of non-empty strings")}get(){return this.ad}},zf=Ve("[FeatureFlags]"),nn=Ve("[FeatureFlags]",{debugEnabled:!0}),jc=`" failed. Feature flags didn't load in time.`,tM=[502,504],Uf=["click","keydown","wheel","touchstart","pointerdown"],Ff="connection_error",qf=e=>{const t={};for(let r=0;e.length>r;r++)t[e[r]]=!0;return t},jf=e=>{const t={};for(const[r,n]of yo(e||{}))n&&(t[r]=n);return t},Hf=e=>yi(e)&&(e.name==="RangeError"&&e.message.indexOf("Maximum call stack size exceeded")===0||e.name==="InternalError"&&e.message==="too much recursion"),Lt=Ve("[Error tracking]"),il="webkit-masked-url:",rM=[{value:"isolatedAPI.contexts.topHostname",exact:!1},{value:"No response from target",exact:!0}],nM=["chrome-extension://","moz-extension://","safari-extension:","safari-web-extension:",il],iM=["__firefox__","__gCrWeb"],Bf="Refusing to render web experiment since the viewer is a likely bot",sM={icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())>-1,not_icontains:(e,t)=>t.toLowerCase().indexOf(e.toLowerCase())===-1,regex:(e,t)=>Qo(t,e),not_regex:(e,t)=>!Qo(t,e),exact:(e,t)=>t===e,is_not:(e,t)=>t!==e},Rt=Ve("[Conversations]"),sn="Conversations not available yet.";function Vf(e,t){var r,n,i,s,o,a,c;const u=(r=e?.flushIntervalMs)!==null&&r!==void 0?r:3e3,l=(n=e?.maxBufferSize)!==null&&n!==void 0?n:100,h=t?.consoleCapture?void 0:(i=e?.maxLogsPerInterval)!==null&&i!==void 0?i:1e3,d=M(h)?Math.max(l,2048):Math.max(l,h),p=b(b({},(function(){let f="",v="";try{const g=rt?.userAgent;g&&([f,v]=x_(g))}catch{}return(function(g,m){const w=(function(S){if(S)return{}.hasOwnProperty.call(Dp,S)?Dp[S]:S})(g);return b(b({},w?{"os.name":w}:{}),m?{"os.version":m}:{})})(f,v)})()),e?.resourceAttributes);return{serviceName:(s=(o=p?.["service.name"])!==null&&o!==void 0?o:e?.serviceName)!==null&&s!==void 0?s:t?.serviceNameDefault,serviceVersion:(a=p?.["service.version"])!==null&&a!==void 0?a:e?.serviceVersion,environment:(c=p?.["deployment.environment"])!==null&&c!==void 0?c:e?.environment,resourceAttributes:p,beforeSend:e?.beforeSend,flushIntervalMs:u,maxBufferSize:l,maxQueueSize:d,maxBatchRecordsPerPost:100,rateCapWindowMs:u,maxLogsPerInterval:h,backgroundFlushBudgetMs:0,terminationFlushBudgetMs:0}}var oM=["debug","log","warn","error","info"],aM=e=>{for(;e?.__rrweb_original__;)e=e.__rrweb_original__;return e},Gf="console",b0="__posthogHandledLogsRequestError",Hc=(e,t)=>{const r=e instanceof Error?e:new Error(t);return r[b0]=!0,r},Zf=e=>!!e&&typeof e=="object"&&e[b0]===!0,ea=Ve("[NetworkMetrics]"),Pd=()=>{var e;return!(A==null||(e=A.performance)===null||e===void 0)&&e.now?A.performance.now():Date.now()},cM={"http:":80,"https:":443},uM=new Set(["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"]),w0=(e,t)=>{var r;const n=String(t);return{method:String(e).toUpperCase(),url:((r=_r(n))===null||r===void 0?void 0:r.href)||n}},sl=(e,t,r,n,i,s,o=!1)=>{try{var a,c;const u=i();if(!u)return;const l=r||void 0,h=Pd()-n,d=_r(t.url);if(d&&d.protocol!=="http:"&&d.protocol!=="https:")return;const p={url:d?.href||t.url,method:t.method},f=tt(u.name)?u.name(p):ye(u.name)?u.name:"http.client.request.duration";if(!f)return;const v=o&&!l?void 0:((m,w)=>m?400>m?void 0:String(m):w?.name||"_OTHER")(l,s),g=b(b(b(b(b({},(m=>{const w=uM.has(m)?m:"_OTHER";return b({"http.request.method":w},w==="_OTHER"&&m!==w?{"http.request.method_original":m}:{})})(p.method)),d?(m=>{return{"server.address":m.hostname.startsWith("[")&&m.hostname.endsWith("]")?m.hostname.slice(1,-1):m.hostname,"server.port":Number(m.port)||cM[m.protocol],"url.scheme":m.protocol.slice(0,-1),"url.template":(w=m.pathname,w.split("/").map(S=>(O=>/^\d+$/.test(O)||O.length>=8&&/^[0-9a-f-]*\d[0-9a-f-]*$/i.test(O))(S)?":id":S).join("/"))};var w})(d):{}),l?{"http.response.status_code":l}:{}),v?{"error.type":v}:{}),(a=u.attributes)===null||a===void 0?void 0:a.call(u,p,{status:l,durationMs:h}));(c=e.metrics)===null||c===void 0||c.histogram(f,h,{unit:"ms",attributes:g})}catch(u){ea.error("Failed to record network metric",u)}},S0=()=>{},lM=(e,t)=>tt(A?.fetch)?bs(A,"fetch",r=>function(...n){const i=Pd(),s=r.apply(this,n);if(!t())return s;try{var o,a,c;const[u,l]=n,h=w0((o=(a=l?.method)!==null&&a!==void 0?a:u?.method)!==null&&o!==void 0?o:"GET",(c=u?.url)!==null&&c!==void 0?c:u);return s.then(d=>(sl(e,h,d?.status,i,t,void 0,!0),d),d=>{throw sl(e,h,void 0,i,t,d),d})}catch(u){return ea.error("Failed to observe fetch",u),s}}):S0,dM=(e,t)=>{var r;const n=A==null||(r=A.XMLHttpRequest)===null||r===void 0?void 0:r.prototype;if(!n)return S0;const i=new WeakMap,s=bs(n,"open",a=>function(...c){try{e0.has(this)||i.set(this,w0(c[0],c[1]))}catch(u){ea.error("Failed to observe XHR open",u)}return a.apply(this,c)}),o=bs(n,"send",a=>function(...c){let u;try{const l=i.get(this);if(l&&t()){const h=Pd();u=()=>{this.removeEventListener("loadend",u),sl(e,l,this.status,h,t)},Ae(this,"loadend",u)}}catch(l){ea.error("Failed to observe XHR send",l)}try{return a.apply(this,c)}catch(l){throw u&&this.removeEventListener("loadend",u),l}});return()=>{s(),o()}},ja={featureFlags:class{constructor(e){this.name="featureFlags",this.ld=!1,this.featureFlagEventHandlers=[],this.A=zf,this.ud={},this.hd={},this.dd=[],this.vd=!1,this.fd=!1,this.pd=0,this.gd=!1,this.md=!1,this.yd=!1,this.bd=!1,this._d=0,this.wd=!1,this.rn=()=>{const t=this.kd();this._d=0,t&&this.reloadFeatureFlags()},this.Sd=()=>{var t,r;const n=this.xd,i=(t=this.Cd)!==null&&t!==void 0?t:n;M(n)||M(i)||this.Ir.remoteRequestsDisabled||!D||D.visibilityState==="hidden"||Date.now()-((r=this.$d)!==null&&r!==void 0?r:0)<i||(this.Cd=this.wd||!this.Ir.idleRefreshBackoff?n:Math.min(2*i,36e5),this.wd=!1,this.reloadFeatureFlags(),this.Td())},this.Id=()=>{this.wd&&this.Cd===this.xd||this.Md()},this.sn=()=>{D?.visibilityState==="visible"&&this.Md()},"get"in e?this.wo=e:(this._instance=e,this.Ed=new eM(e.config,e.il()),this.wo=this.Ed)}updateConfig(e,t){var r;(r=this.Ed)===null||r===void 0||r.update(e,t),this.bo&&this.Pd()}setup(e){return this.Nh=e,this.A=e.logger.createLogger("[FeatureFlags]"),y0(e.kv.initialize(),()=>{this.Nh===e&&(this.Nh=void 0,this.bo=e,this.Rd(e))})}Rd(e){var t;if(this.bo===e)return A&&Ae(A,"online",this.rn),this.Pd(),this.Ad=e.registerDynamicEventProperties(()=>this.Fd()?this.ud:this.hd),this.Od=(t=this._instance)===null||t===void 0||(t=t.persistence)===null||t===void 0?void 0:t.onCrossTabFeatureFlagChange(()=>{this.Dd(),this.Ld(),this.Nd()}),this.Ld(),this.initialize()}Md(){this.wd=!0,this.Cd=this.xd,this.Sd()}Pd(){const e=this.Ir.refreshIntervalMs,t=!this.Ir.remoteRequestsDisabled&&D&&!M(e)&&e>0?e:void 0;this.Ir.idleRefreshBackoff||(this.Cd=t),t!==this.xd&&(this.qd(),M(t)||(this.xd=t,this.Cd=t,this.Td(),D!=null&&D.addEventListener&&(Ae(D,vs,this.sn),Vn(Uf,r=>{Ae(D,r,this.Id,{capture:!0})}))))}Td(){M(this.xd)||(M(this.jd)||clearInterval(this.jd),this.$d=Date.now(),this.jd=setInterval(this.Sd,this.xd))}qd(){var e;M(this.jd)||(clearInterval(this.jd),this.jd=void 0,D==null||(e=D.removeEventListener)===null||e===void 0||e.call(D,"visibilitychange",this.sn),Vn(Uf,t=>{var r;D==null||(r=D.removeEventListener)===null||r===void 0||r.call(D,t,this.Id,{capture:!0})})),this.xd=void 0,this.Cd=void 0,this.wd=!1,this.$d=void 0}destroy(){this.Bd()}dispose(){this.Bd()}Bd(){var e,t;this.qd(),this.pd++,this.md=!1,this.Nh=void 0,this.bo&&(this.Hd(),(e=this.Ad)===null||e===void 0||e.dispose(),this.Ad=void 0,(t=this.Od)===null||t===void 0||t.call(this),this.Od=void 0,this.dd=[],A?.removeEventListener("online",this.rn),this.bo=void 0)}get Ir(){return this.wo.get()}zd(e){var t;return this.Ud&&e in this.Ud?this.Ud[e]:(t=this.bo)===null||t===void 0?void 0:t.kv.get(e)}Dd(){return!!this.Ud&&(this.Ud=void 0,!0)}Wd(){var e;return!M((e=this.bo)===null||e===void 0?void 0:e.kv.get("$enabled_feature_flags"))&&this.Dd()}$t(e){this.Vd(()=>{var t;return(t=this.bo)===null||t===void 0?void 0:t.kv.set(e)})}Gd(e,t,r){var n;if(!(!((n=this._instance)===null||n===void 0)&&n.persistence)||!e.$enabled_feature_flags)return;const i=this.zd("$enabled_feature_flags")||{},s=e.$enabled_feature_flags||{},o=t.flags||t.featureFlags,a=t.flags?Object.entries(t.flags).filter(([,m])=>!m?.failed).map(([m])=>m):[],c=!!t.errorsWhileComputingFlags&&!!t.flags,u=c?a:r&&!ue(o)?Object.keys(o||{}):Array.from(new Set([...Object.keys(i),...Object.keys(s)])),l=this.zd("$feature_flag_payloads")||{},h=e.$feature_flag_payloads||{},d=c||r?u:Array.from(new Set([...Object.keys(l),...Object.keys(h)])),p=!c&&!r,f=!!p||u,v=!!p||d,g={[hr]:f,[Ut]:f,[Cr]:v};e.$feature_flag_details&&(g[_n]=f);for(const m of[yn,Ur,Yi])M(e[m])||(g[m]=!0);this._instance.persistence.markCrossTabFeatureFlagChanges(g)}Lt(e){this.Vd(()=>{var t;return(t=this.bo)===null||t===void 0?void 0:t.kv.remove(e)})}Vd(e){try{e()}catch(t){this.A.error("Failed to update feature flag persistence",t)}}Ld(){const e={};for(const n of[hr,Cr,yn,Zt]){const i=this.zd(n);M(i)||(e[n]=i)}this.ud=e;const t=b({},e),r=this.zd(Ut);if(r)for(const[n,i]of Object.entries(r))t[`$feature/${n}`]=i;this.hd=t}Fd(){const e=this.Ir.cacheTtlMs;if(!e||0>=e)return!1;const t=this.zd(Ur);return typeof t!="number"||Date.now()-t>e}Zd(){return!!this.Fd()&&(this.bd||this.fd||(this.bd=!0,this.A.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}Qd(){const e=this.Ir.evaluationContexts;return e?.length?e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.A.error("Invalid evaluation context found:",t,"Expected non-empty string"),r}):[]}Jd(){const e=this.Ir.flagKeys;if(!M(e))return e.filter(t=>{const r=t&&typeof t=="string"&&t.trim().length>0;return r||this.A.error("Invalid flag key found:",t,"Expected non-empty string"),r})}initialize(){var e,t;const r=this.Ir,n=(e=(t=r.bootstrap)===null||t===void 0?void 0:t.featureFlags)!==null&&e!==void 0?e:{};if(Object.keys(n).length){var i,s;const o=(i=(s=r.bootstrap)===null||s===void 0?void 0:s.featureFlagPayloads)!==null&&i!==void 0?i:{},a=Object.keys(n).filter(u=>!M(n[u])).reduce((u,l)=>(u[l]=n[l],u),{}),c=Object.keys(o).filter(u=>a[u]).reduce((u,l)=>(u[l]=o[l],u),{});return this.Kd({featureFlags:a,featureFlagPayloads:c},void 0,{persist:!1})}}updateFlags(e,t,r){var n,i;const s=r?.merge&&(n=this.zd("$enabled_feature_flags"))!==null&&n!==void 0?n:{},o=r?.merge&&(i=this.zd("$feature_flag_payloads"))!==null&&i!==void 0?i:{},a=b(b({},s),e),c=b(b({},o),t),u={};for(const[l,h]of Object.entries(a))u[l]={key:l,enabled:$p(h),variant:xp(h),reason:void 0,metadata:M(c?.[l])?void 0:{id:0,version:void 0,description:void 0,payload:c[l]}};this.Kd({flags:u})}get hasLoadedFlags(){return this.vd}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){const e=this.zd(_n),t=this.zd(Zt),r=this.zd(ln);if(!r&&!t)return e||{};const n=ze({},e||{}),i=[...new Set([...Object.keys(r||{}),...Object.keys(t||{})])];for(const a of i){var s;const c=n[a],u=t?.[a],l=M(u)?(s=c?.enabled)!==null&&s!==void 0&&s:!!u,h=M(u)?c?.variant:typeof u=="string"?u:void 0,d=r?.[a],p=b(b({},c),{},{enabled:l,variant:l?h??c?.variant:void 0});var o;l!==c?.enabled&&(p.original_enabled=c?.enabled),h!==c?.variant&&(p.original_variant=c?.variant),d&&(p.metadata=b(b({},c?.metadata),{},{payload:d,original_payload:c==null||(o=c.metadata)===null||o===void 0?void 0:o.payload})),n[a]=p}return this.ld||(this.A.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:n}),this.ld=!0),n}getAllFeatureFlags(){const e=this.getFlagVariants(),t=this.getFlagPayloads();return Object.keys(e).map(r=>{const n=e[r];return{key:r,enabled:$p(n),variant:xp(n),payload:Cp(t[r])}})}getFlagVariants(){const e=this.zd(Ut),t=this.zd(Zt);if(!t)return e||{};const r=ze({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.ld||(this.A.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:t,finalFlags:r}),this.ld=!0),r}getFlagPayloads(){const e=this.zd(Cr),t=this.zd(ln);if(!t)return e||{};const r=ze({},e||{}),n=Object.keys(t);for(let i=0;n.length>i;i++)r[n[i]]=t[n[i]];return this.ld||(this.A.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:t,finalPayloads:r}),this.ld=!0),r}reloadFeatureFlags(){this.gd||this.Ir.featureFlagsDisabled||this.kd()||(this.fd&&(this.md=!0),this.Xd||(this.dd.slice().forEach(e=>{try{e()}catch(t){this.A.error("Error while running feature flags reloading callback",t)}}),this.Xd=setTimeout(()=>{this.Yd()},5)))}Hd(){clearTimeout(this.Xd),this.Xd=void 0}onReloading(e){return this.dd.push(e),()=>{this.dd=this.dd.filter(t=>t!==e)}}ensureFlagsLoaded(){this.vd||this.fd||this.Xd||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.gd=e}resetFlagCallReported(){this.Lt(Mr)}Yd(e){this.Hd();const t=this.bo;if(!t||this.Ir.remoteRequestsDisabled||this.kd())return;if(this.fd)return void(this.md=!0);const r={token:t.projectToken,distinct_id:t.distinctId,groups:t.groups,$anon_distinct_id:this.$anon_distinct_id,person_properties:b(b(b({},t.initialPersonProperties),this.zd("$stored_person_properties")||{}),{},{$lib:t.library.name,$lib_version:t.library.version}),group_properties:this.zd(xr),timezone:Zy()};M(t.deviceId)||(r.$device_id=t.deviceId),(e!=null&&e.disableFlags||this.Ir.featureFlagsDisabled)&&(r.disable_flags=!0);const n=this.Qd();n.length&&(r.evaluation_contexts=n);const i=this.Jd();M(i)||(r.flag_keys=i);const s=this.Ir.onlyEvaluateSurveyFeatureFlags,o="/flags/?v=2"+(s?"&only_evaluate_survey_feature_flags=true":""),a=this.pd;this.fd=!0;const c=()=>{this.md&&(this.md=!1,this.Yd())},u=f=>{var v,g;const m=(v=f.json)!==null&&v!==void 0?v:{},w=f.statusCode!==200;if(this.fd=!1,a!==this.pd)return void c();if(this.tv(f.statusCode),w||this.md||(this.$anon_distinct_id=void 0),r.disable_flags&&!this.md)return;this.yd=!w;const S=[];f.error?S.push(f.error instanceof Error&&f.error.name==="AbortError"?"timeout":f.error instanceof Error?Ff:"unknown_error"):f.statusCode!==200&&S.push(`api_error_${f.statusCode}`),m.errorsWhileComputingFlags&&S.push("errors_while_computing_flags");const O=!!(!((g=m.quotaLimited)===null||g===void 0)&&g.includes("feature_flags"));O&&S.push("quota_limited"),this.$t({[fs]:S}),O?this.A.warn("You have hit your feature flags quota limit, and will not be able to load feature flags until the quota is reset. Please visit https://posthog.com/docs/billing/limits-alerts to learn more."):r.disable_flags||this.Kd(m,w,{partialResponse:s}),c()},l=f=>{this.fd=!1,a===this.pd&&(this.$t({[fs]:[Ff]}),this.A.error("Feature flag request failed",f),this.Wd()&&this.Nd(!0)),c()};let h=this.Ir.requestMaxRetries;const d=()=>h>0&&a===this.pd,p=()=>{if(a!==this.pd||!this.bo||this.Ir.remoteRequestsDisabled)return this.fd=!1,void c();try{t.sendRequest(o,{target:"flags",method:"POST",body:r,compression:this.Ir.compression,sentAt:"body",timeoutMs:this.Ir.requestTimeoutMs}).then(f=>{if((v=>tM.includes(v.statusCode)||(g=>g.statusCode===0&&g.error instanceof Error&&g.error.name==="AbortError")(v))(f)&&d())return h--,void setTimeout(p,500);u(f)}).catch(l)}catch(f){l(f)}};p()}kd(){return zy(this._d,3)}tv(e){this._d=Uy(e,this._d,3,()=>this.A.warn("Feature flag requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped refreshing feature flags; will try again when connectivity changes."))}getFeatureFlag(e,t={}){var r;if(t.fresh&&!this.yd)return;if(!(this.vd||this.getFlags()&&this.getFlags().length>0))return void this.A.warn('getFeatureFlag for key "'+e+jc);if(this.Zd())return;const n=this.getFeatureFlagResult(e,t);return(r=n?.variant)!==null&&r!==void 0?r:n?.enabled}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){const t=this.getFeatureFlagResult(e,{send_event:!1});return t?.payload}getFeatureFlagResult(e,t={}){if(t.fresh&&!this.yd)return;if(!(this.vd||this.getFlags()&&this.getFlags().length>0))return void this.A.warn('getFeatureFlagResult for key "'+e+jc);if(this.Zd())return;const r=this.getFlagVariants(),n=e in r,i=r[e],s=this.getFlagPayloads()[e],o=String(i),a=this.zd("$feature_flag_request_id")||void 0,c=this.zd("$feature_flag_evaluated_at")||void 0;let u,l=this.zd("$flag_call_reported")||{};if(this.Ir.deduplicateCallsPerSession){var h;const q=(h=this.bo)===null||h===void 0?void 0:h.session.sessionId,K=this.zd(qi);q&&q!==K&&(l={},u=q)}if(t.send_event||!("send_event"in t))if(e in l&&l[e].includes(o))u&&this.$t({[Mr]:l,[qi]:u});else{var d,p,f,v,g,m,w,S,O,R,I,C;ue(l[e])?l[e].push(o):l[e]=[o],this.$t(b({[Mr]:l},u?{[qi]:u}:{}));const q=this.getFeatureFlagDetails(e),K=[...(d=this.zd("$feature_flag_errors"))!==null&&d!==void 0?d:[]];M(i)&&K.push("flag_missing");const X={$feature_flag:e,$feature_flag_response:i,$feature_flag_payload:s??null,$feature_flag_request_id:a,$feature_flag_evaluated_at:c,$feature_flag_bootstrapped_response:(p=(f=this.Ir.bootstrap)===null||f===void 0||(f=f.featureFlags)===null||f===void 0?void 0:f[e])!==null&&p!==void 0?p:null,$feature_flag_bootstrapped_payload:(v=(g=this.Ir.bootstrap)===null||g===void 0||(g=g.featureFlagPayloads)===null||g===void 0?void 0:g[e])!==null&&v!==void 0?v:null,$used_bootstrap_value:!this.yd};M(q==null||(m=q.metadata)===null||m===void 0?void 0:m.has_experiment)||(X.$feature_flag_has_experiment=q.metadata.has_experiment),M(q==null||(w=q.metadata)===null||w===void 0?void 0:w.version)||(X.$feature_flag_version=q.metadata.version);const k=(S=q==null||(O=q.reason)===null||O===void 0?void 0:O.description)!==null&&S!==void 0?S:q==null||(R=q.reason)===null||R===void 0?void 0:R.code;var L;k&&(X.$feature_flag_reason=k),q!=null&&(I=q.metadata)!==null&&I!==void 0&&I.id&&(X.$feature_flag_id=q.metadata.id),M(q?.original_variant)&&M(q?.original_enabled)||(X.$feature_flag_original_response=M(q.original_variant)?q.original_enabled:q.original_variant),q!=null&&(C=q.metadata)!==null&&C!==void 0&&C.original_payload&&(X.$feature_flag_original_payload=q==null||(L=q.metadata)===null||L===void 0?void 0:L.original_payload),K.length&&(X.$feature_flag_error=K.join(",")),this.ev(X)}else u&&this.$t({[Mr]:l,[qi]:u});return n?{key:e,enabled:!!i,variant:typeof i=="string"?i:void 0,payload:Cp(s)}:void 0}ev(e){try{var t;(t=this.bo)===null||t===void 0||t.capture("$feature_flag_called",e)}catch(r){this.A.error("Failed to capture feature flag call",r)}}getRemoteConfigPayload(e,t){this.iv(e,t)}iv(e,t){var r=this;return Ue(function*(){const n=r.bo;if(!n)return;const i={distinct_id:n.distinctId,token:n.projectToken,person_properties:{$lib:n.library.name,$lib_version:n.library.version}},s=r.Qd();s.length&&(i.evaluation_contexts=s);const o=r.Jd();let a;M(o)||(i.flag_keys=o);try{var c;const u=(c=(yield n.sendRequest("/flags/?v=2",{target:"flags",method:"POST",body:i,compression:r.Ir.compression,sentAt:"body",timeoutMs:r.Ir.requestTimeoutMs})).json)===null||c===void 0?void 0:c.featureFlagPayloads;a=u?.[e]||void 0}catch(u){r.A.error("Remote config feature flag request failed",u);return}try{t(a)}catch(u){r.A.error("Remote config feature flag callback failed",u)}})()}isFeatureEnabled(e,t={}){if(t.fresh&&!this.yd)return t.defaultValue;if(!(this.vd||this.getFlags()&&this.getFlags().length>0))return this.A.warn('isFeatureEnabled for key "'+e+jc),t.defaultValue;const r=this.getFeatureFlag(e,t);return M(r)?t.defaultValue:!!r}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(t=>t!==e)}receivedFeatureFlags(e,t,r){this.Kd(e,t,r)}Kd(e,t,r){if(!this.bo)return;this.vd=!0;const n=((i,s={},o={},a={},c,u=zf)=>{const l=((S,O)=>{const R=S.flags;if(R){const I=Object.fromEntries(Object.keys(R).map(L=>{var q;return[L,(q=R[L].variant)!==null&&q!==void 0?q:R[L].enabled]})),C=Object.fromEntries(Object.keys(R).filter(L=>R[L].enabled).filter(L=>{var q;return!M((q=R[L].metadata)===null||q===void 0?void 0:q.payload)}).map(L=>{var q;return[L,(q=R[L].metadata)===null||q===void 0?void 0:q.payload]}));return b(b({},S),{},{featureFlags:I,featureFlagPayloads:C})}return S.featureFlags&&O.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),S})(i,u),h=l.flags,d=l.featureFlags,p=l.featureFlagPayloads;if(!d)return;const f=i.requestId,v=i.evaluatedAt;if(ue(d)){u.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");const S={};if(d)for(let O=0;d.length>O;O++)S[d[O]]=!0;return{[hr]:d,[Ut]:S,[Yi]:!1}}let g=d,m=p,w=h;if(c?.partialResponse){const S=Object.keys(g),O=m||{};g=b(b({},s),g),m=b(b({},o),O),S.forEach(R=>{R in O||m==null||delete m[R]}),w=b(b({},a),w)}else if(i.errorsWhileComputingFlags)if(h){const S=new Set(Object.keys(h).filter(R=>{var I;return!(!((I=h[R])===null||I===void 0)&&I.failed)}));g=b(b({},s),Object.fromEntries(Object.entries(g).filter(([R])=>S.has(R))));const O=Object.fromEntries(Object.entries(m||{}).filter(([R])=>S.has(R)));m=b(b({},o),O),S.forEach(R=>{R in O||m==null||delete m[R]}),w=b(b({},a),Object.fromEntries(Object.entries(w||{}).filter(([R])=>S.has(R))))}else g=b(b({},s),g),m=b(b({},o),m),w=b(b({},a),w);return b(b({[hr]:Object.keys(jf(g)),[Ut]:g||{},[Cr]:m||{},[_n]:w||{},[Yi]:i.minimalFlagCalledEvents===!0},f?{[yn]:f}:{}),v?{[Ur]:v}:{})})(e,this.getFlagVariants(),this.getFlagPayloads(),this.getFlagsWithDetails(),r,this.A);if(n)if(r?.persist===!1){const i=!M(this.bo.kv.get(Ut));this.Ud=n,i||this.$t(n)}else this.Dd(),this.Gd(n,e,!!r?.partialResponse),this.$t(n);else t&&this.Wd();t||(this.bd=!1),this.Nd(t)}override(e,t=!1){this.A.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:t})}overrideFeatureFlags(e){this.nv(e)}nv(e){if(this.bo){if(e===!1)return this.Lt([Zt,ln]),this.Nd(),void nn.info("All overrides cleared");if(ue(e))return this.$t({[Zt]:qf(e)}),this.Nd(),void nn.info("Flag overrides set",{flags:e});if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var t;const r=e;this.ld=!!((t=r.suppressWarning)!==null&&t!==void 0&&t);const n={},i=r.flags,s=r.payloads;i&&(n[Zt]=ue(i)?qf(i):i),s&&(n[ln]=s),Object.keys(n).length&&this.$t(n),i===!1&&s===!1?this.Lt([Zt,ln]):i===!1?this.Lt(Zt):s===!1&&this.Lt(ln),this.Nd(),i===!1?nn.info("Flag overrides cleared"):i&&nn.info("Flag overrides set",{flags:i}),s===!1?nn.info("Payload overrides cleared"):s&&nn.info("Payload overrides set",{payloads:s});return}if(e&&typeof e=="object")return this.$t({[Zt]:e}),this.Nd(),void nn.info("Flag overrides set",{flags:e});this.A.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:e})}else this.A.warn("posthog.featureFlags.overrideFeatureFlags called before feature flags were ready")}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.vd){const{flags:t,flagVariants:r}=this.sv();try{e(t,r)}catch(n){this.A.error("Error while running feature flags callback",n)}}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,t,r){var n;const i=(this.zd("$early_access_features")||[]).find(u=>u.flagKey===e),s={[`$feature_enrollment/${e}`]:t},o={$feature_flag:e,$feature_enrollment:t,$set:s};i&&(o.$early_access_feature_name=i.name),r&&(o.$feature_enrollment_stage=r);const a=b(b({},this.getFlagVariants()),{},{[e]:t});(n=this._instance)===null||n===void 0||(n=n.persistence)===null||n===void 0||n.markCrossTabFeatureFlagChanges({$active_feature_flags:[e],$enabled_feature_flags:[e],$stored_person_properties:Object.keys(s)}),this.$t({[hr]:Object.keys(jf(a)),[Ut]:a,[$r]:b(b({},this.zd("$stored_person_properties")||{}),s)}),this.Nd();try{var c;(c=this.bo)===null||c===void 0||c.capture("$feature_enrollment_update",o)}catch(u){this.A.error("Failed to capture early access feature enrollment",u)}}getEarlyAccessFeatures(e,t=!1,r){const n=this.zd(Bu);!n||t?this.rv(e,r):e(n)}rv(e,t){var r=this;return Ue(function*(){const n=r.bo;if(!n)return;const i=t?`&${t.map(o=>`stage=${o}`).join("&")}`:"";let s;try{const o=yield n.sendRequest(`/api/early_access_features/?token=${n.projectToken}${i}`,{target:"api",method:"GET",sentAt:"query"});if(!o.json)return;s=o.json.earlyAccessFeatures,r.$t({[Bu]:s})}catch(o){r.A.error("Early access feature request failed",o);return}try{e(s)}catch(o){r.A.error("Early access feature callback failed",o)}})()}sv(){const e=this.getFlags(),t=this.getFlagVariants();return{flags:e.filter(r=>t[r]),flagVariants:Object.keys(t).filter(r=>t[r]).reduce((r,n)=>(r[n]=t[n],r),{})}}Nd(e){this.Ld();const{flags:t,flagVariants:r}=this.sv();this.featureFlagEventHandlers.forEach(n=>{try{n(t,r,{errorsLoading:e})}catch(i){this.A.error("Error while running feature flags callback",i)}})}setPersonPropertiesForFlags(e,t=!0){this.ov(e,t)}ov(e,t=!0){const r=this.zd("$stored_person_properties")||{},n=e?.$set||(e?.$set_once?{}:e),i=e?.$set_once,s={};if(i)for(const o in i)({}).hasOwnProperty.call(i,o)&&(o in r||(s[o]=i[o]));this.$t({[$r]:b(b(b({},r),s),n)}),t&&this.reloadFeatureFlags()}unsetPersonPropertiesForFlags(e,t=!0){const r=b({},this.zd("$stored_person_properties")||{});e.forEach(n=>{delete r[n]}),this.$t({[$r]:r}),t&&this.reloadFeatureFlags()}resetPersonPropertiesForFlags(e=!0){this.Lt($r),e&&this.reloadFeatureFlags()}setGroupPropertiesForFlags(e,t=!0){const r=this.zd("$stored_group_properties")||{},n=b({},r);for(const i of Object.keys(e))n[i]=b(b({},r[i]),e[i]);this.$t({[xr]:n}),t&&this.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){const t=this.zd("$stored_group_properties")||{};this.$t({[xr]:b(b({},t),{},{[e]:{}})})}else this.Lt(xr)}reset(){this.pd++,this.md=!1,this.ud={},this.hd={},this.Ud=void 0,this.vd=!1,this.gd=!1,this.yd=!1,this.$anon_distinct_id=void 0,this.Hd(),this.ld=!1,this._d=0}}},hM={sessionRecording:class{get Ir(){return this._instance.config}get Il(){return this._instance.persistence}get started(){var e;return!!(!((e=this.av)===null||e===void 0)&&e.isStarted)}get status(){var e,t;return this.lv==="awaiting_config"||this.lv==="missing_config"?this.lv:(e=(t=this.av)===null||t===void 0?void 0:t.status)!==null&&e!==void 0?e:this.lv}constructor(e){if(this._instance=e,this._forceAllowLocalhostNetworkCapture=!1,this.lv=Uc,this.uv=void 0,this.hv=!1,this.Je=(()=>{var t,r;if(!D?.visibilityState||D.visibilityState==="visible")return!0;const n=A==null||(t=A.performance)===null||t===void 0||(r=t.getEntriesByType)===null||r===void 0?void 0:r.call(t,"visibility-state");return!n?.length||n.some(i=>i.name==="visible")})(),this.sn=()=>{var t,r;D?.visibilityState==="visible"&&(this.Je=!0,(t=this.av)===null||t===void 0||(r=t.setDocumentWasEverVisible)===null||r===void 0||r.call(t,!0))},!this._instance.sessionManager)throw or.error("started without valid sessionManager"),new Error("[SessionRecording] started without valid sessionManager. This is a bug.");if(this.Ir.cookieless_mode==="always")throw new Error('[SessionRecording] cannot be used with cookieless_mode="always"');D!=null&&D.addEventListener&&Ae(D,"visibilitychange",this.sn)}initialize(){this.startIfEnabledOrStop()}dispose({discardBufferedEvents:e=!1}={}){var t;this.hv=!0,D==null||(t=D.removeEventListener)===null||t===void 0||t.call(D,"visibilitychange",this.sn),e?this.dv(!0):this.stopRecording()}get vv(){var e;const t=!!(!((e=this._instance.get_property("$session_recording_remote_config"))===null||e===void 0)&&e.enabled),r=!this.Ir.disable_session_recording,n=this.Ir.disable_session_recording||this._instance.consent.isOptedOut();return A&&t&&r&&!n}startIfEnabledOrStop(e){var t;if(this.hv||this.vv&&(!((t=this.av)===null||t===void 0)&&t.isStarted))return;const r=!M(Object.assign)&&!M(Array.from);this.vv&&r?(this.fv(e),or.info("starting")):(this.lv=Uc,this.stopRecording())}fv(e){var t,r;if(this.vv)if(this.lv!=="awaiting_config"&&this.lv!=="missing_config"&&(this.lv=$f),(re==null||(t=re.__PosthogExtensions__)===null||t===void 0||(t=t.rrweb)===null||t===void 0?void 0:t.record)&&((r=re.__PosthogExtensions__)===null||r===void 0?void 0:r.initSessionRecording))this.pv(e);else{var n,i;const s=this._instance.sessionManager;(n=re.__PosthogExtensions__)===null||n===void 0||(i=n.loadExternalDependency)===null||i===void 0||i.call(n,this._instance,this.gv,o=>{if(!this.hv&&this.vv&&this._instance.sessionManager===s)return o?(this._instance.register_for_session({$sdk_debug_recording_script_not_loaded:!0}),or.error("could not load recorder",o)):void this.pv(e);this.lv="disabled"})}}stopRecording(){var e,t;(e=this.uv)===null||e===void 0||e.call(this),this.uv=void 0,(t=this.av)===null||t===void 0||t.stop()}dv(e=!1){var t,r;(t=this.uv)===null||t===void 0||t.call(this),this.uv=void 0,(r=this.av)===null||r===void 0||r.discard({discardProducerEvents:e})}mv(){var e,t;(e=this.Il)===null||e===void 0||e.unregister("$session_is_sampled"),(t=this.Il)===null||t===void 0||t.unregister("$replay_sample_rate")}yv(e,t){if(fe(e))return null;const r=Ze(e)?e:parseFloat(e);return typeof(n=r)!="number"||!Number.isFinite(n)||0>n||n>1?(or.warn(`${t} must be between 0 and 1. Ignoring invalid value:`,e),null):r;var n}bv(e){if(this.Il){var t,r;const n=this.Il,i=()=>{var s;const o=e.sessionRecording===!1?void 0:e.sessionRecording,a=this.yv((s=this.Ir.session_recording)===null||s===void 0?void 0:s.sampleRate,"session_recording.sampleRate"),c=this.yv(o?.sampleRate,"remote config sampleRate"),u=a??c;fe(u)&&this.mv();const l=o?.minimumDurationMilliseconds;n.register({[Ki]:b(b({cache_timestamp:Date.now(),enabled:!!o},o),{},{networkPayloadCapture:b({capturePerformance:e.capturePerformance},o?.networkPayloadCapture),canvasRecording:{enabled:o?.recordCanvas,fps:o?.canvasFps,quality:o?.canvasQuality},sampleRate:u,minimumDurationMilliseconds:M(l)?null:l,endpoint:o?.endpoint,triggerMatchType:o?.triggerMatchType,masking:o?.masking,urlTriggers:o?.urlTriggers,version:o?.version,triggerGroups:o?.triggerGroups})})};i(),(t=this.uv)===null||t===void 0||t.call(this),this.uv=(r=this._instance.sessionManager)===null||r===void 0?void 0:r.onSessionId(i)}}onRemoteConfig(e){const t=e.ok?e.config:void 0;t&&"sessionRecording"in t?t.sessionRecording===!1?(this.bv(t),this.dv()):(this.bv(t),this.startIfEnabledOrStop()):(this.lv==="awaiting_config"&&(this.lv="missing_config",this._instance.register_for_session({[yd]:!0}),or.warn("config refresh failed, recording will not start until page reload")),this.startIfEnabledOrStop())}log(e,t="log"){var r;!((r=this.av)===null||r===void 0)&&r.log?this.av.log(e,t):or.warn("log called before recorder was ready")}get gv(){var e,t;const r=(e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0?void 0:e.get_property(Ki);return(r==null||(t=r.scriptConfig)===null||t===void 0?void 0:t.script)||"lazy-recorder"}_v(){const e=this._instance.get_property(Ki);if(!e)return!1;let t;try{t=typeof e=="object"?e:JSON.parse(e)}catch(r){return or.warn("persisted remote config for session recording is invalid and will be ignored",r),!1}return!fe(t.cache_timestamp)&&36e5>=Date.now()-t.cache_timestamp}pv(e){var t,r,n;if(!this.hv&&this.vv&&this._instance.sessionManager){if(!(!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.initSessionRecording))return or.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[_d]:!0});var i;if(this.av||(this.av=(i=re.__PosthogExtensions__)===null||i===void 0?void 0:i.initSessionRecording(this._instance,this.Je),this.av._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this._v()){if(this.lv==="missing_config"||this.lv==="awaiting_config")return;this.lv="awaiting_config",or.info("persisted remote config is stale, requesting fresh config before starting"),new Jy(this._instance).load();return}this.lv=$f,(r=(n=this.av).setDocumentWasEverVisible)===null||r===void 0||r.call(n,this.Je),this.av.start(e)}else this.lv=Uc}onRRwebEmit(e){var t,r;(t=this.av)===null||t===void 0||(r=t.onRRwebEmit)===null||r===void 0||r.call(t,e)}overrideLinkedFlag(){var e,t;this.av||(t=this.Il)===null||t===void 0||t.register({$replay_override_linked_flag:!0}),(e=this.av)===null||e===void 0||e.overrideLinkedFlag()}overrideSampling(){var e,t;this.av||(t=this.Il)===null||t===void 0||t.register({$replay_override_sampling:!0}),(e=this.av)===null||e===void 0||e.overrideSampling()}overrideTrigger(e){var t,r;this.av||(r=this.Il)===null||r===void 0||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(t=this.av)===null||t===void 0||t.overrideTrigger(e)}get sdkDebugProperties(){var e;const t={};for(const n of Bx){var r;const i=(r=this._instance.sessionPersistence)===null||r===void 0?void 0:r.get_property(n);M(i)||(t[n]=i)}return b(b({},t),((e=this.av)===null||e===void 0?void 0:e.sdkDebugProperties)||{$recording_status:this.status})}tryAddCustomEvent(e,t){var r;return!!(!((r=this.av)===null||r===void 0)&&r.tryAddCustomEvent(e,t))}flushBeforeIdentityReset(){var e,t;(e=this.av)===null||e===void 0||(t=e.flushBeforeIdentityReset)===null||t===void 0||t.call(e)}}},pM={autocapture:class extends Ux{constructor(e){super(new Fx(e)),this.instance=e}},historyAutocapture:class{constructor(e){this.wv=!1,this._instance=e,this.Sv=this.xv()}initialize(){this.startIfEnabled()}get isEnabled(){const e=this.Cv();return!!(e.path||e.search||this.$v(e))}startIfEnabled(){this.isEnabled&&(j.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}startIfEnabledOrStop(){this.stop(),this.Sv=this.xv(),this.startIfEnabled()}stop(){this.Tv&&this.Tv(),this.Tv=void 0,this.Iv&&this.Iv(),this.Iv=void 0,j.info("History API monitoring stopped")}monitorHistoryChanges(){A&&A.history&&(this.Mv("pushState"),this.Mv("replaceState"),this.Ev(),this.$v()&&this.Pv())}Mv(e){var t;if(!A||!((t=A.history[e])===null||t===void 0)&&t.__posthog_wrapped__)return;const r=this;bs(A.history,e,n=>function(i,s,o){var a;r.Rv(o)&&r.Av(),n.call(this,i,s,o),r.Fv(e,!r.wv&&(A==null||(a=A.event)===null||a===void 0?void 0:a.type)!=="popstate")})}xv(){const e=A?.location;if(e?.pathname)return{pathname:e.pathname,search:e.search,hash:e.hash}}Cv(){const e=this._instance.config.capture_pageview;return e==="history_change"?{path:!0}:be(e)?e:{}}$v(e=this.Cv()){return!!e.hash&&!this._instance.config.disable_capture_url_hashes}Ov(e){const t=this.Cv(),r=this.Sv;return!(!r||!(t.path&&e.pathname!==r.pathname||t.search&&e.search!==r.search||this.$v(t)&&e.hash!==r.hash))}Fv(e,t=!1){try{t||this.Av();const r=this.xv();if(!r)return;if(this.Ov(r)){const n=()=>this._instance.capture(wd,{navigation_type:e});t?(this.Dv=n,Promise.resolve().then(()=>this.Av())):n()}this.Sv=r}catch(r){j.error(`Error capturing ${e} pageview`,r)}}Rv(e){var t,r;return!(fe(e)||!A)&&((t=_r(String(e)))===null||t===void 0?void 0:t.href)!==((r=A.location)===null||r===void 0?void 0:r.href)}Av(){const e=this.Dv;if(e){this.Dv=void 0,this.wv=!0;try{e()}catch(t){j.error("Error capturing deferred pageview",t)}finally{this.wv=!1}this.Sv=this.xv()}}Ev(){if(this.Tv)return;const e=()=>{this.Fv("popstate")};Ae(A,"popstate",e),this.Tv=()=>{A&&A.removeEventListener("popstate",e)}}Pv(){if(this.Iv)return;const e=()=>{this.Fv("hashchange")};Ae(A,"hashchange",e),this.Iv=()=>{A&&A.removeEventListener("hashchange",e)}}},heatmaps:class{get Ir(){return this.instance.config}constructor(e){var t;this.Lv=!1,this.ko=!1,this.Nv=null,this.instance=e,this.Lv=!!(!((t=this.instance.persistence)===null||t===void 0)&&t.props[Fu]),this.rageclicks=new _0(e.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){let e=5e3;return be(this.Ir.capture_heatmaps)&&this.Ir.capture_heatmaps.flush_interval_milliseconds&&(e=this.Ir.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return fe(this.Ir.capture_heatmaps)?fe(this.Ir.enable_heatmaps)?this.Lv:this.Ir.enable_heatmaps:this.Ir.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.ko)return;Vx.info("starting..."),this.qv(),this.sn()}else{var e;clearInterval((e=this.Nv)!==null&&e!==void 0?e:void 0),this.jv(),this.getAndClearBuffer()}}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("heatmaps"in t))return;const r=!!t.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Fu]:r}),this.Lv=r,this.startIfEnabled()}getAndClearBuffer(){const e=this.Rt;return this.Rt=void 0,e}Bv(e){Fc(e.originalEvent)&&this.Mr(e.originalEvent,"deadclick")}sn(){this.Nv&&clearInterval(this.Nv),this.Nv=D?.visibilityState==="visible"?setInterval(this.yl.bind(this),this.flushIntervalMilliseconds):null}qv(){A&&D&&(this.Hv=this.yl.bind(this),Ae(A,Zo,this.Hv),this.zv=e=>this.Mr(e||A?.event),Ae(D,"click",this.zv,{capture:!0}),this.Uv=e=>this.Wv(e||A?.event),Ae(D,"mousemove",this.Uv,{capture:!0}),this.Vv=new sf(this.instance,B1,this.Bv.bind(this)),this.Vv.startIfEnabledOrStop(),this.Gv=this.sn.bind(this),Ae(D,vs,this.Gv),this.ko=!0)}jv(){var e;A&&D&&(this.Hv&&A.removeEventListener(Zo,this.Hv),this.zv&&D.removeEventListener("click",this.zv,{capture:!0}),this.Uv&&D.removeEventListener("mousemove",this.Uv,{capture:!0}),this.Gv&&D.removeEventListener(vs,this.Gv),clearTimeout(this.Zv),(e=this.Vv)===null||e===void 0||e.stop(),this.ko=!1)}Qv(e,t){const r=this.instance.scrollManager.scrollY(),n=this.instance.scrollManager.scrollX(),i=this.instance.scrollManager.scrollElement(),s=(function(o,a,c){let u=o;for(;u&&tr(u)&&!ct(u,"body");){if(u===c)return!1;let p;try{var l,h,d;p=(l=(h=(d=u.ownerDocument)===null||d===void 0?void 0:d.defaultView)!==null&&h!==void 0?h:A)===null||l===void 0?void 0:l.getComputedStyle(u).position}catch{return!1}if(ce(a,p))return!0;u=Cy(u)}return!1})(Qi(e),["fixed","sticky"],i);return{x:e.clientX+(s?0:n),y:e.clientY+(s?0:r),target_fixed:s,type:t}}Mr(e,t="click"){var r;if(Wp(e.target)||!Fc(e))return;const n=this.Qv(e,t);(r=this.rageclicks)!==null&&r!==void 0&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&xy(Qi(e),this.instance.config.rageclick)&&this.Zs(b(b({},n),{},{type:"rageclick"})),this.Zs(n)}Wv(e){!Wp(e.target)&&Fc(e)&&(clearTimeout(this.Zv),this.Zv=setTimeout(()=>{this.Zs(this.Qv(e,"mousemove"))},500))}Zs(e){if(!A)return;const t=this.Ir.disable_capture_url_hashes?Jr(A.location.href):A.location.href,r=this.Ir.custom_personal_data_properties,n=this.Ir.mask_personal_data_properties?[...li,...r||[]]:[],i=_s(t,n,ys);this.Rt=this.Rt||{},this.Rt[i]||(this.Rt[i]=[]),this.Rt[i].push(e)}yl(){this.Rt&&!bt(this.Rt)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:sf,webVitalsAutocapture:class{constructor(e){var t;this._instance=e,this.Lv=!1,this.ko=!1,this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Jv=()=>{clearTimeout(this.Kv),this.Kv=void 0,this.Rt.metrics.length!==0&&(this._instance.capture("$web_vitals",b({$current_url:this.Rt.url},this.Rt.metrics.reduce((r,n)=>b(b({},r),{},{[`$web_vitals_${n.name}_event`]:b({},n),[`$web_vitals_${n.name}_value`]:n.value}),{}))),this.Rt={navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.Xv=r=>{var n;if(this.Rt=this.Rt||{navigationKey:void 0,url:void 0,metrics:[],firstMetricTimestamp:void 0},fe(r?.name)||fe(r?.value))return void rn.error("Invalid metric received",r);const i=typeof r.navigationURL=="string"?r.navigationURL:void 0,s=this.Yv(i);if(M(s))return;const o=Ze(r.navigationId)||typeof r.navigationId=="string"?`navigation:${r.navigationId}`:`url:${s}`;if(this.tf&&r.value>=this.tf)return void rn.error("Ignoring metric with value >= "+this.tf,r);this.Rt.navigationKey!==o&&(this.Jv(),this.Kv=setTimeout(this.Jv,this.flushToCaptureTimeoutMs)),M(this.Rt.navigationKey)&&(this.Rt.navigationKey=o,this.Rt.url=s),this.Rt.firstMetricTimestamp=M(this.Rt.firstMetricTimestamp)?Date.now():this.Rt.firstMetricTimestamp;const a=(n=this._instance.sessionManager)===null||n===void 0?void 0:n.checkAndGetSessionAndWindowId(!0),c=b(b(b({},r),i?{navigationURL:s}:{}),{},{$current_url:s,timestamp:Date.now()});if(delete c.entries,be(r.attribution)&&this.attributionMetrics.indexOf(r.name)>-1){const u={};for(const l of Hx){const h=l==="url"&&typeof r.attribution[l]=="string"?this.Yv(r.attribution[l]):r.attribution[l];M(h)||(u[l]=h)}c.attribution=u}else delete c.attribution;M(a)||(c.$session_id=a.sessionId,c.$window_id=a.windowId),this.Rt.metrics.push(c),this.Rt.metrics.length===this.allowedMetrics.length&&this.Jv()},this.ef=()=>{if(this.ko)return;let r,n,i,s,o=!1;const a=re.__PosthogExtensions__,c=a?.postHogWebVitalsCallbacksByFlavor,u=c?.[this.if]||(this.if==="web-vitals"&&M(c)?a?.postHogWebVitalsCallbacks:void 0);if(!M(u)){const d=u.withoutAttribution,p=this.attributionMetrics;o=!M(d),r=p.indexOf("LCP")>-1?u.onLCP:d?.onLCP||u.onLCP,n=p.indexOf("CLS")>-1?u.onCLS:d?.onCLS||u.onCLS,i=p.indexOf("FCP")>-1?u.onFCP:d?.onFCP||u.onFCP,s=p.indexOf("INP")>-1?u.onINP:d?.onINP||u.onINP}if(!(r&&n&&i&&s))return void rn.error("web vitals callbacks not loaded - not starting");const l={reportSoftNavs:this.useSoftNavs},h=o&&this.attributionMetrics.indexOf("INP")>-1?b(b({},l),{},{includeProcessedEventEntries:!1}):l;this.allowedMetrics.indexOf("LCP")>-1&&r(this.Xv.bind(this),l),this.allowedMetrics.indexOf("CLS")>-1&&n(this.Xv.bind(this),l),this.allowedMetrics.indexOf("FCP")>-1&&i(this.Xv.bind(this),l),this.allowedMetrics.indexOf("INP")>-1&&s(this.Xv.bind(this),h),this.ko=!0},this.Lv=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[Hu]),this.startIfEnabled()}get nf(){return this._instance.config.capture_performance}get allowedMetrics(){var e,t;const r=be(this.nf)?(e=this.nf)===null||e===void 0?void 0:e.web_vitals_allowed_metrics:void 0;return fe(r)?((t=this._instance.persistence)===null||t===void 0?void 0:t.props.$web_vitals_allowed_metrics)||Cf:r}get flushToCaptureTimeoutMs(){return(be(this.nf)?this.nf.web_vitals_delayed_flush_ms:void 0)||5e3}get attributionMetrics(){const e=be(this.nf)?this.nf.web_vitals_attribution:void 0;return gt(e)?e?Cf:[]:ue(e)?e:jx}get useAttribution(){return this.attributionMetrics.length>0}get useSoftNavs(){const e=be(this.nf)?this.nf.__preview_web_vitals_soft_navs:void 0;return e!=null&&e}get tf(){const e=be(this.nf)&&Ze(this.nf.__web_vitals_max_value)?this.nf.__web_vitals_max_value:Of;return e>0&&6e4>=e?Of:e}get isEnabled(){const e=je?.protocol;if(e!=="http:"&&e!=="https:")return rn.info("Web Vitals are disabled on non-http/https protocols"),!1;const t=be(this.nf)?this.nf.web_vitals:gt(this.nf)?this.nf:void 0;return gt(t)?t:this.Lv}startIfEnabled(){this.isEnabled&&!this.ko&&(rn.info("enabled, starting..."),this.Ho(this.ef))}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if(!("capturePerformance"in t))return;const r=be(t.capturePerformance)&&!!t.capturePerformance.web_vitals,n=be(t.capturePerformance)?t.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Hu]:r}),this._instance.persistence.register({[sy]:n})),this.Lv=r,this.startIfEnabled()}get if(){return this.useSoftNavs?this.useAttribution?"web-vitals-with-attribution-soft-navs":"web-vitals-soft-navs":this.useAttribution?"web-vitals-with-attribution":"web-vitals"}Ho(e){var t;const r=re.__PosthogExtensions__,n=this.if,i=r?.postHogWebVitalsCallbacksByFlavor;i?.[n]||n==="web-vitals"&&M(i)&&r?.postHogWebVitalsCallbacks?e():r==null||(t=r.loadExternalDependency)===null||t===void 0||t.call(r,this._instance,n,s=>{s?rn.error("failed to load script",s):e()})}Yv(e){const t=e||A?.location.href;if(!t)return void rn.error("Could not determine current URL");const r=this._instance.config.disable_capture_url_hashes?Jr(t):t,n=this._instance.config.custom_personal_data_properties,i=this._instance.config.mask_personal_data_properties?[...li,...n||[]]:[];return _s(r,i,ys)}}},fM={exceptionObserver:class{constructor(e){var t;this.ef=()=>{var r;if(!A||!this.isEnabled||!(!((r=re.__PosthogExtensions__)===null||r===void 0)&&r.errorWrappingFunctions))return;const n=re.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,i=re.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,s=re.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.sf&&this.Ir.capture_unhandled_errors&&(this.sf=n(this.captureException.bind(this))),!this.rf&&this.Ir.capture_unhandled_rejections&&(this.rf=i(this.captureException.bind(this))),!this.af&&this.Ir.capture_console_errors&&(this.af=s(this.captureException.bind(this)))}catch(o){Li.error("failed to start",o),this.lf()}},this._instance=e,this.uf=!!(!((t=this._instance.persistence)===null||t===void 0)&&t.props[qu]),this.wt=new l$(b(b({},(function(r={}){var n,i,s,o;return{refillRate:(n=(i=r.exceptionRateLimiterRefillRate)!==null&&i!==void 0?i:r.__exceptionRateLimiterRefillRate)!==null&&n!==void 0?n:1,bucketSize:(s=(o=r.exceptionRateLimiterBucketSize)!==null&&o!==void 0?o:r.__exceptionRateLimiterBucketSize)!==null&&s!==void 0?s:10}})(this._instance.config.error_tracking)),{},{refillInterval:1e4,A:Li})),this.Ir=this.hf(),this.startIfEnabledOrStop()}hf(){const e=this._instance.config.capture_exceptions;let t={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return be(e)?t=b(b({},t),e):(M(e)?this.uf:e)&&(t=b(b({},t),{},{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),t}get isEnabled(){return this.Ir.capture_console_errors||this.Ir.capture_unhandled_errors||this.Ir.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Li.info("enabled"),this.lf(),this.Ho(this.ef)):this.lf()}Ho(e){var t,r,n;!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.errorWrappingFunctions?e():(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"exception-autocapture",i=>{if(i)return Li.error("failed to load script",i);e()})}lf(){var e,t,r;(e=this.sf)===null||e===void 0||e.call(this),this.sf=void 0,(t=this.rf)===null||t===void 0||t.call(this),this.rf=void 0,(r=this.af)===null||r===void 0||r.call(this),this.af=void 0}onRemoteConfig(e){if(!e.ok)return;const t=e.config;"autocaptureExceptions"in t&&(this.uf=!!t.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[qu]:this.uf}),this.Ir=this.hf(),this.startIfEnabledOrStop())}onConfigChange(){this.Ir=this.hf()}captureException(e){try{var t,r,n;const i=(t=e==null||(r=e.$exception_list)===null||r===void 0||(r=r[0])===null||r===void 0?void 0:r.type)!==null&&t!==void 0?t:"Exception";if(this.wt.consumeRateLimit(i))return void Li.info("Skipping exception capture because of client rate limiting.",{exception:i});(n=this._instance.exceptions)===null||n===void 0||n.sendExceptionEvent(e)}catch{}}},exceptions:class{constructor(e){var t,r;this.cf=[],this.df=new S$([new D$,new G$,new U$,new z$,new B$,new H$,new q$,new V$],(function(n,...i){return(s,o=0)=>{const a=[],c=s.split(`
|
|
114
|
+
`),u=Math.min(c.length,o+1e3),l=[];for(let p=o;u>p;p++){const f=c[p];if(f.length>1024)continue;const v=Op.test(f)?f.replace(Op,"$1"):f;if(!v.match(/\S*Error: /)){for(const g of i){const m=g(v,n);if(m){a.push(m);const w=x$(a);if(w){for(let S=l.length-1;S>=0;S--){const O=l[S];if(w.start>=O.start+O.length)break;l.pop()}l.push(w)}break}}if(L$(a,l)>=50)break}}const h=[...l].sort((p,f)=>f.start-p.start),d=h[h.length-1];if(d){const p=q_(a,d);a.splice(d.start-p,p);for(const f of h)f.start-=p}for(const p of h)M$(a,p);return l.some(p=>p.start===0&&a.length===p.length)&&(function(p){const f=p.map(g=>`${g.function}|${g.filename}|${g.lineno}|${g.colno}|${g.module}`);let v=0;for(let g=1;f.length>g;g++)N$(f,g,v)&&(v=g);p.push(...p.splice(0,v))})(a),(function(p){if(!p.length)return[];const f=Array.from(p);return f.reverse(),f.slice(0,50).map(v=>{return b(b({},v),{},{filename:v.filename||(g=f,g[g.length-1]||{}).filename,function:v.function||"?"});var g})})(a)}})("web:javascript",P$,$$)),this._instance=e,this.cf=(t=(r=this._instance.persistence)===null||r===void 0?void 0:r.get_property("$error_tracking_suppression_rules"))!==null&&t!==void 0?t:[],this.vf=jo(this.ff()),this.pf=new W$(this.vf)}onConfigChange(){this.vf=jo(this.ff()),this.pf.setConfig(this.vf)}onRemoteConfig(e){var t,r,n;if(!e.ok)return;const i=e.config;if(!("errorTracking"in i))return;const s=(t=(r=i.errorTracking)===null||r===void 0?void 0:r.suppressionRules)!==null&&t!==void 0?t:[],o=(n=i.errorTracking)===null||n===void 0?void 0:n.captureExtensionExceptions;this.cf=s,this._instance.persistence&&this._instance.persistence.register({[ny]:this.cf,[ju]:o})}get gf(){var e;const t=!!this._instance.get_property(ju),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r??t)!==null&&e!==void 0&&e}buildProperties(e,t){return this.df.buildFromUnknown(e,{syntheticException:t?.syntheticException,mechanism:{handled:t?.handled}})}addExceptionStep(e,t){if(this.vf.enabled)try{if(!ye(e)||e.trim().length===0)return void Lt.warn("Ignoring exception step because message must be a non-empty string");const{sanitizedProperties:r,droppedKeys:n}=(function(i){if(!i)return{sanitizedProperties:{},droppedKeys:[]};const s=[];return{sanitizedProperties:Object.keys(i).reduce((o,a)=>Z$.has(a)?(s.push(a),o):(o[a]=i[a],o),{}),droppedKeys:s}})(this.mf(t));n.length>0&&Lt.warn("Ignoring reserved exception step fields",{droppedKeys:n}),this.pf.add(b({[Fo]:e,[qo]:new Date().toISOString()},r))}catch(r){Lt.error("Failed to add exception step. Ignoring breadcrumb.",r)}}sendExceptionEvent(e){try{const t=e.$exception_list;if(this.yf(t)){if(this.bf(t))return this._f("Exception dropped: matched a suppression rule"),void Lt.info("Skipping exception capture because a suppression rule matched");if(!this.gf&&this.wf(t))return this._f("Exception dropped: thrown by a browser extension"),void Lt.info("Skipping exception capture because it was thrown by an extension");if(!this.gf&&this.kf(t))return this._f("Exception dropped: thrown by an injected browser script"),void Lt.info("Skipping exception capture because it was thrown by an injected browser script");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.Sf(t))return this._f("Exception dropped: thrown by the PostHog SDK"),void Lt.info("Skipping exception capture because it was thrown by the PostHog SDK")}const r=this.vf.enabled&&fe(e.$exception_steps)?this.xf(e):e,n=(function(){const i=globalThis._posthogReleaseId;return typeof i=="string"&&i.length>0?i:void 0})();n&&(r.$release_id=n);try{const i=this._instance.capture("$exception",r,{_noTruncate:!0,_batchKey:"exceptionEvent",fh:!0});return i&&this.pf.clear(),i}catch(i){Hf(i)||Lt.error("Failed to capture exception event. Dropping this exception.",i),this.pf.clear();return}}catch(t){Hf(t)||Lt.error("Failed to process exception event. Ignoring this exception.",t);return}}xf(e){try{const t=this.pf.getAttachable();return t.length===0?e:b(b({},e),{},{$exception_steps:t})}catch(t){return Lt.error("Failed to read buffered exception steps. Capturing exception without steps.",t),e}}_f(e){this.vf.enabled&&this.pf.add({[Fo]:e,[qo]:new Date().toISOString()})}mf(e){return be(e)?b({},e):{}}ff(){var e,t;return(e=(t=this._instance.config.error_tracking)===null||t===void 0?void 0:t.exception_steps)!==null&&e!==void 0?e:{}}bf(e){if(e.length===0)return!1;try{const t=e.reduce((r,{type:n,value:i})=>(ye(n)&&n.length>0&&r.$exception_types.push(n),ye(i)&&i.length>0&&r.$exception_values.push(i),r),{$exception_types:[],$exception_values:[]});return this.cf.some(r=>{const n=r.values.map(i=>{const s=f0[i.operator],o=t[i.key];if(!s||!o)return!1;const a=ue(i.value)?i.value:[i.value];return a.length>0&&s(a,o)});return r.type==="OR"?n.some(Boolean):n.every(Boolean)})}catch(t){return Lt.warn("Failed to evaluate suppression rules. Capturing the exception.",t),!1}}wf(e){const t=e.flatMap(n=>{var i,s;return(i=(s=n.stacktrace)===null||s===void 0?void 0:s.frames)!==null&&i!==void 0?i:[]}),r=t.filter(({filename:n})=>!!n&&nM.some(i=>n.startsWith(i)));return r.length!==0&&(!r.every(({filename:n})=>!!n&&n.startsWith(il))||e.some(({type:n,value:i})=>n==="NoResponse"||ye(i)&&rM.some(({value:s,exact:o})=>o?i===s:i.includes(s)))&&!t.some(({in_app:n,filename:i})=>n&&!i?.startsWith(il)))}kf(e){return e.some(({value:t})=>ye(t)&&iM.some(r=>t.includes(r)))}Sf(e){if(e.length>0){var t,r,n,i;const s=(t=(r=e[0].stacktrace)===null||r===void 0?void 0:r.frames)!==null&&t!==void 0?t:[],o=s[s.length-1];return(n=o==null||(i=o.filename)===null||i===void 0?void 0:i.includes("posthog.com/static"))!==null&&n!==void 0&&n}return!1}yf(e){return!fe(e)&&ue(e)}}},vM=b({productTours:class{get Il(){return this._instance.persistence}constructor(e){this.Cf=null,this.$f=null,this._instance=e}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(!e.ok)return;const t=e.config;if("productTours"in t){var r,n;if(this.Il&&this.Il.register({[gd]:!!t.productTours}),!qc(this._instance))return!this.Cf&&fe((r=this.Il)===null||r===void 0?void 0:r.props.ph_product_tours)||Ys.info("product tours disabled; stopping and clearing cached tours"),(n=this.Cf)===null||n===void 0||n.stop(),this.Cf=null,void this.clearCache();this.loadIfEnabled()}}loadIfEnabled(){!this.Cf&&qc(this._instance)&&this.Ho(()=>this.Tf())}Ho(e){var t,r,n;!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.generateProductTours?e():(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"product-tours",i=>{i?Ys.error("Could not load product tours script",i):e()})}Tf(){var e;!this.Cf&&(e=re.__PosthogExtensions__)!==null&&e!==void 0&&e.generateProductTours&&(this.Cf=re.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,t=!1){if(ue(this.$f)&&!t)return void e(this.$f,{isLoaded:!0});const r=this.Il;if(r){const n=r.props[Vu];if(ue(n)&&!t)return this.$f=n,void e(n,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/product_tours/?token=${this._instance.config.token}`),method:"GET",timestampMode:"query",callback:n=>{if(!qc(this._instance))return void e([],{isLoaded:!0});const i=n.statusCode;if(i!==200||!n.json){const o=`Product Tours API could not be loaded, status: ${i}`;i===0?n.error||Ys.warn(o):Ys.error(o),e([],{isLoaded:!1,error:o});return}const s=ue(n.json.product_tours)?n.json.product_tours:[];this.$f=s,r&&r.register({[Vu]:s}),e(s,{isLoaded:!0})}})}getActiveProductTours(e){fe(this.Cf)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Cf.getActiveProductTours(e)}showProductTour(e){var t;(t=this.Cf)===null||t===void 0||t.showTourById(e)}previewTour(e){this.Cf?this.Cf.previewTour(e):this.Ho(()=>{var t;this.Tf(),(t=this.Cf)===null||t===void 0||t.previewTour(e)})}dismissProductTour(){var e;(e=this.Cf)===null||e===void 0||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Cf)===null||e===void 0||e.nextStep()}previousStep(){var e;(e=this.Cf)===null||e===void 0||e.previousStep()}clearCache(){var e;this.$f=null,(e=this.Il)===null||e===void 0||e.unregister("ph_product_tours")}resetTour(e){var t;(t=this.Cf)===null||t===void 0||t.resetTour(e)}resetAllTours(){var e;(e=this.Cf)===null||e===void 0||e.resetAllTours()}cancelPendingTour(e){var t;(t=this.Cf)===null||t===void 0||t.cancelPendingTour(e)}}},ja),gM={siteApps:class{constructor(e){this._instance=e,this.If=0,this.Mf=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Ef(e,t){if(!t)return;const r=this.globalsForEvent(t);this.Mf.push(r),this.Mf.length>1e3&&(this.Mf=this.Mf.slice(10))}get siteAppLoaders(){var e;return(e=re._POSTHOG_REMOTE_CONFIG)===null||e===void 0||(e=e[this._instance.config.token])===null||e===void 0?void 0:e.siteApps}initialize(){if(this.isEnabled){const e=this._instance._addCaptureHook(this.Ef.bind(this));this.Pf=()=>{e(),this.Mf=[],this.Pf=void 0}}}globalsForEvent(e){var t,r,n,i,s,o,a;if(!e)throw new Error("Event payload is required");const c={},u=this._instance.get_property("$groups")||[],l=this._instance.get_property("$stored_group_properties")||{};for(const[p,f]of Object.entries(l))c[p]={id:u[p],type:p,properties:f};const{$set_once:h,$set:d}=e;return{event:b(b({},V_(e,Gx)),{},{properties:b(b(b({},e.properties),d?{$set:b(b({},(t=(r=e.properties)===null||r===void 0?void 0:r.$set)!==null&&t!==void 0?t:{}),d)}:{}),h?{$set_once:b(b({},(n=(i=e.properties)===null||i===void 0?void 0:i.$set_once)!==null&&n!==void 0?n:{}),h)}:{}),elements_chain:(s=(o=e.properties)===null||o===void 0?void 0:o.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(a=e.properties)===null||a===void 0?void 0:a.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}Rf(e){var t;const r=(t=e.tagName)===null||t===void 0?void 0:t.toLowerCase();return r==="style"&&this._instance.config.prepare_external_dependency_stylesheet?this._instance.config.prepare_external_dependency_stylesheet(e)||(Gt.error("prepare_external_dependency_stylesheet returned null"),null):r==="script"&&this._instance.config.prepare_external_dependency_script?this._instance.config.prepare_external_dependency_script(e)||(Gt.error("prepare_external_dependency_script returned null"),null):e}Af(){var e,t,r,n,i,s,o,a;if(!this._instance.config.prepare_external_dependency_stylesheet&&!this._instance.config.prepare_external_dependency_script)return()=>{};const c=D?.defaultView,u=c==null||(e=c.Node)===null||e===void 0?void 0:e.prototype;if(!c||!u)return()=>{};if(this.If++,this.Ff)return this.Of();const l=[],h=this,d=new WeakSet,p=(g,m,w)=>{if(!g?.[m])return;const S=g[m];g[m]=w(S),l.push(()=>{g[m]=S})},f=g=>{if(d.has(g))return g;const m=h.Rf(g);return m&&d.add(m),m},v=g=>g.map(m=>typeof m=="string"?m:f(m)).filter(m=>!He(m));return p(u,"appendChild",g=>function(m){const w=f(m);return w?g.call(this,w):m}),p(u,"insertBefore",g=>function(m,w){const S=f(m);return S?g.call(this,S,w):m}),p(u,"replaceChild",g=>function(m,w){const S=f(m);return S?g.call(this,S,w):w}),[(t=c.Element)===null||t===void 0?void 0:t.prototype,(r=c.Document)===null||r===void 0?void 0:r.prototype,(n=c.DocumentFragment)===null||n===void 0?void 0:n.prototype].forEach(g=>{p(g,"append",m=>function(...w){return m.apply(this,v(w))}),p(g,"prepend",m=>function(...w){return m.apply(this,v(w))})}),[(i=c.Element)===null||i===void 0?void 0:i.prototype,(s=c.CharacterData)===null||s===void 0?void 0:s.prototype,(o=c.DocumentType)===null||o===void 0?void 0:o.prototype].forEach(g=>{p(g,"before",m=>function(...w){return m.apply(this,v(w))}),p(g,"after",m=>function(...w){return m.apply(this,v(w))}),p(g,"replaceWith",m=>function(...w){const S=v(w);return w.length&&!S.length?void 0:m.apply(this,S)})}),p((a=c.Element)===null||a===void 0?void 0:a.prototype,"insertAdjacentElement",g=>function(m,w){const S=f(w);return S?g.call(this,m,S):null}),this.Ff=()=>{l.forEach(g=>g()),this.Ff=void 0},this.Of()}Of(){let e=!1;return()=>{var t;e||(e=!0,this.If--,this.If===0&&((t=this.Ff)===null||t===void 0||t.call(this)))}}Df(e,t=!0){const r=this.Af();try{const n=e(r);return t&&r(),n}catch(n){throw r(),n}}setupSiteApp(e){const t=this.apps[e.id],r=()=>{var s;!t.errored&&this.Mf.length&&(Gt.info(`Processing ${this.Mf.length} events for site app with id ${e.id}`),this.Mf.forEach(o=>this.Df(()=>{var a;return(a=t.processEvent)===null||a===void 0?void 0:a.call(t,o)})),t.processedBuffer=!0),Object.values(this.apps).every(o=>o.processedBuffer||o.errored)&&((s=this.Pf)===null||s===void 0||s.call(this))};let n=!1;const i=s=>{t.errored=!s,t.loaded=!0,Gt.info(`Site app with id ${e.id} ${s?"loaded":"errored"}`),n&&r()};try{const{processEvent:s}=this.Df(o=>e.init({posthog:this._instance,callback(a){o(),i(a)}}),!1);s&&(t.processEvent=s),n=!0}catch(s){Gt.error(xf+e.id,s),i(!1)}if(n&&t.loaded)try{r()}catch(s){Gt.error(`Error while processing buffered events PostHog app with config id ${e.id}`,s),t.errored=!0}}Lf(){const e=this.siteAppLoaders||[];for(const t of e)this.apps[t.id]={id:t.id,loaded:!1,errored:!1,processedBuffer:!1};for(const t of e)this.setupSiteApp(t)}Nf(e){if(Object.keys(this.apps).length===0)return;const t=this.globalsForEvent(e);for(const r of Object.values(this.apps))try{this.Df(()=>{var n;return(n=r.processEvent)===null||n===void 0?void 0:n.call(r,t)})}catch(n){Gt.error(`Error while processing event ${e.event} for site app ${r.id}`,n)}}onRemoteConfig(e){var t,r,n;if(!((t=this.siteAppLoaders)===null||t===void 0)&&t.length)return this.isEnabled?(this.Lf(),void this._instance.on("eventCaptured",a=>this.Nf(a))):void Gt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.Pf)===null||r===void 0||r.call(this),!e.ok)return;const i=e.config;if(!((n=i.siteApps)===null||n===void 0)&&n.length)if(this.isEnabled)for(const{id:a,url:c}of i.siteApps){var s,o;re[`__$$ph_site_app_${a}`]=this._instance,(s=re.__PosthogExtensions__)===null||s===void 0||(o=s.loadSiteApp)===null||o===void 0||o.call(s,this._instance,c,u=>{if(u)return Gt.error(xf+a,u)})}else Gt.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},mM={tracingHeaders:class{constructor(e){this._instance=e,this.qf=void 0,this.jf=void 0,this.Bf=void 0,this.ef=()=>{const t=this.Hf();var r,n;t?(M(this.qf)&&(this.qf=(r=re.__PosthogExtensions__)===null||r===void 0||(r=r.tracingHeadersPatchFns)===null||r===void 0?void 0:r._patchXHR(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager)),M(this.jf)&&(this.jf=(n=re.__PosthogExtensions__)===null||n===void 0||(n=n.tracingHeadersPatchFns)===null||n===void 0?void 0:n._patchFetch(t,()=>this._instance.get_distinct_id(),this._instance.sessionManager))):this.lf()}}initialize(){this.startIfEnabledOrStop()}Ho(e){var t,r,n;!((t=re.__PosthogExtensions__)===null||t===void 0)&&t.tracingHeadersPatchFns?e():(r=re.__PosthogExtensions__)===null||r===void 0||(n=r.loadExternalDependency)===null||n===void 0||n.call(r,this._instance,"tracing-headers",i=>{if(i)return qx.error("failed to load script",i);e()})}zf(){var e,t;return(e=(t=this._instance.config.tracing_headers)!==null&&t!==void 0?t:this._instance.config.addTracingHeaders)!==null&&e!==void 0?e:this._instance.config.__add_tracing_headers}Hf(){const e=this.zf();return ue(e)?(ue(this.Bf)?this.Bf.splice(0,this.Bf.length,...e):this.Bf=[...e],e.length>0?this.Bf:void 0):(ue(this.Bf)&&this.Bf.splice(0),this.Bf=e||void 0,this.Bf)}lf(){var e,t;(e=this.qf)===null||e===void 0||e.call(this),(t=this.jf)===null||t===void 0||t.call(this),this.qf=void 0,this.jf=void 0}startIfEnabledOrStop(){this.Hf()?this.Ho(this.ef):this.lf()}}},_M=b({surveys:class extends Zx{constructor(e){var t;super(new Xx(e),(t=e,{get projectToken(){return t.config.token},kv:new Yx(t)})),this._instance=e}Vh(e,t){const r=t.query?Ts(e,t.query):e;return new Promise(n=>{var i;this._instance._send_request({method:t.method,url:this._instance.requestRouter.endpointFor((i=t.target)!==null&&i!==void 0?i:"api",r),data:t.body,headers:t.headers,timeout:t.timeoutMs,fireCallbackOnDrop:!0,transport:t.transport,compression:t.compression,timestampMode:t.sentAt,callback:n})})}}},ja),yM={toolbar:class{constructor(e){this.instance=e}Uf(e){re.ph_toolbar_state=e}Wf(){var e;return(e=re.ph_toolbar_state)!==null&&e!==void 0?e:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(e=void 0,t=void 0,r=void 0){var n,i;if(Zu(this.instance.config)||!A||!D)return!1;e=(n=e)!==null&&n!==void 0?n:A.location,r=(i=r)!==null&&i!==void 0?i:A.history;try{if(!t){try{A.localStorage.setItem("test","test"),A.localStorage.removeItem("test")}catch{return!1}t=A?.localStorage}const s=Qx||Jo(e.hash,"__posthog")||Jo(e.hash,"state");let o;const a=s?Ap(()=>JSON.parse(atob(decodeURIComponent(s))))||Ap(()=>JSON.parse(decodeURIComponent(s))):null;return a&&a.action==="ph_authorize"?(o=a,o.source="url",o&&Object.keys(o).length>0&&(a.desiredHash?e.hash=a.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):(o=JSON.parse(t.getItem(Lf)||"{}"),o.source="localstorage",delete o.userIntent),!(!o.token||this.instance.config.token!==o.token||(this.loadToolbar(o),0))}catch{return!1}}Vf(e){const t=re.ph_load_toolbar||re.ph_load_editor;!fe(t)&&tt(t)?t(e,this.instance):Nf.warn("No toolbar load function found")}loadToolbar(e){const t=!!D?.getElementById("__POSTHOG_TOOLBAR__");if(!A||t)return!1;const r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,n=b(b({token:this.instance.config.token},e),{},{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(A.localStorage.setItem(Lf,JSON.stringify(b(b({},n),{},{source:void 0}))),this.Wf()===2)this.Vf(n);else if(this.Wf()===0){var i,s;this.Uf(1),(i=re.__PosthogExtensions__)===null||i===void 0||(s=i.loadExternalDependency)===null||s===void 0||s.call(i,this.instance,"toolbar",o=>{if(o)return Nf.error("[Toolbar] Failed to load",o),void this.Uf(0);this.Uf(2),this.Vf(n)}),Ae(A,"turbolinks:load",()=>{this.Uf(0),this.loadToolbar(n)})}return!0}Gf(e){return this.loadToolbar(e)}maybeLoadEditor(e=void 0,t=void 0,r=void 0){return this.maybeLoadToolbar(e,t,r)}}},bM=b({experiments:class pt{get Ir(){return this._instance.config}constructor(t){this._instance=t,this.getWebExperimentsAndEvaluateDisplayLogic=(r=!1)=>{this.getWebExperiments(n=>{pt.Zf("retrieved web experiments from the server"),this.Qf=new Map,n.forEach(i=>{if(i.feature_flag_key){var s;this.Qf&&(pt.Zf("setting flag key ",i.feature_flag_key," to web experiment ",i),(s=this.Qf)===null||s===void 0||s.set(i.feature_flag_key,i));const o=this._instance.getFeatureFlag(i.feature_flag_key);ye(o)&&i.variants[o]&&this.Jf(i.name,o,i.variants[o].transforms)}else if(i.variants)for(const o in i.variants){const a=i.variants[o];pt.Kf(a,this._instance)&&this.Jf(i.name,o,a.transforms)}})},r)},this._instance.onFeatureFlags(r=>{this.onFeatureFlags(r)})}initialize(){}onFeatureFlags(t){if(this._is_bot())pt.Zf(Bf);else if(!this.Ir.disable_web_experiments){if(fe(this.Qf))return this.Qf=new Map,this.loadIfEnabled(),void this.previewWebExperiment();pt.Zf("applying feature flags",t),t.forEach(r=>{var n;if(this.Qf&&(!((n=this.Qf)===null||n===void 0)&&n.has(r))){var i;const s=this._instance.getFeatureFlag(r),o=(i=this.Qf)===null||i===void 0?void 0:i.get(r);s&&o!=null&&o.variants[s]&&this.Jf(o.name,s,o.variants[s].transforms)}})}}previewWebExperiment(){const t=pt.getWindowLocation();if(t?.search){const r=ui(t?.search,"__experiment_id"),n=ui(t?.search,"__experiment_variant");r&&n&&(pt.Zf(`previewing web experiments ${r} && ${n}`),this.getWebExperiments(i=>{this.Xf(parseInt(r),n,i)},!1,!0))}}loadIfEnabled(){this.Ir.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(t,r,n){if(this.Ir.disable_web_experiments&&!n)return t([]);const i=this._instance.get_property("$web_experiments");if(i&&!r)return t(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api",`/api/web_experiments/?token=${this.Ir.token}`),method:"GET",timestampMode:"query",callback:s=>t(s.statusCode===200&&s.json&&s.json.experiments||[])})}Xf(t,r,n){const i=n.filter(s=>s.id===t);i&&i.length>0&&(pt.Zf(`Previewing web experiment [${i[0].name}] with variant [${r}]`),this.Jf(i[0].name,r,i[0].variants[r].transforms))}static Kf(t,r){return!fe(t.conditions)&&pt.Yf(t,r)&&pt.tp(t)}static Yf(t,r){var n;if(fe(t.conditions)||fe((n=t.conditions)===null||n===void 0?void 0:n.url))return!0;const i=pt.getWindowLocation();if(i){var s,o,a;const c=Ry(r,i.href);return!(!((s=t.conditions)===null||s===void 0)&&s.url)||sM[(o=(a=t.conditions)===null||a===void 0?void 0:a.urlMatchType)!==null&&o!==void 0?o:"icontains"](t.conditions.url,c)}return!1}static getWindowLocation(){return A?.location}static tp(t){var r;if(fe(t.conditions)||fe((r=t.conditions)===null||r===void 0?void 0:r.utm))return!0;const n=Fy();if(n.utm_source){var i,s,o,a,c,u,l,h;const d=!(!((i=t.conditions)===null||i===void 0||(i=i.utm)===null||i===void 0)&&i.utm_campaign)||((s=t.conditions)===null||s===void 0||(s=s.utm)===null||s===void 0?void 0:s.utm_campaign)==n.utm_campaign,p=!(!((o=t.conditions)===null||o===void 0||(o=o.utm)===null||o===void 0)&&o.utm_source)||((a=t.conditions)===null||a===void 0||(a=a.utm)===null||a===void 0?void 0:a.utm_source)==n.utm_source,f=!(!((c=t.conditions)===null||c===void 0||(c=c.utm)===null||c===void 0)&&c.utm_medium)||((u=t.conditions)===null||u===void 0||(u=u.utm)===null||u===void 0?void 0:u.utm_medium)==n.utm_medium,v=!(!((l=t.conditions)===null||l===void 0||(l=l.utm)===null||l===void 0)&&l.utm_term)||((h=t.conditions)===null||h===void 0||(h=h.utm)===null||h===void 0?void 0:h.utm_term)==n.utm_term;return d&&f&&v&&p}return!1}static Zf(t,...r){j.info(`[WebExperiments] ${t}`,r)}Jf(t,r,n){this._is_bot()?pt.Zf(Bf):r!=="control"?n.forEach(i=>{if(i.selector){var s;pt.Zf(`applying transform of variant ${r} for experiment ${t} `,i),((s=document)===null||s===void 0?void 0:s.querySelectorAll(i.selector))?.forEach(o=>{const a=o;i.html&&(a.innerHTML=i.html),i.css&&a.setAttribute("style",i.css)})}}):pt.Zf("Control variants leave the page unmodified.")}_is_bot(){return rt&&this._instance?d0(rt,this.Ir.custom_blocked_useragents):void 0}}},ja),wM={conversations:class{constructor(e){this._instance=e,this.ep=void 0,this._conversationsManager=null,this.np=!1,this.ne=null,this.sp=!1}initialize(){this.loadIfEnabled()}onRemoteConfig(e){if(this._instance.config.disable_conversations||(this.rp=e.ok,!e.ok))return;const t=e.config.conversations;fe(t)||(gt(t)?this.ep=t:(this.ep=t.enabled,this.ne=t),this.loadIfEnabled())}reset(){var e;(e=this._conversationsManager)===null||e===void 0||e.reset(),this._conversationsManager=null,this.ep=void 0,this.ne=null,this.rp=void 0,this.sp=!1}loadIfEnabled(){if(this._conversationsManager||this.np||this._instance.config.disable_conversations||Zu(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())return;const e=re?.__PosthogExtensions__;if(e&&!M(this.ep)&&this.ep)if(this.ne&&this.ne.token){this.np=!0;try{const t=e.initConversations;if(t)return this.op(t),void(this.np=!1);const r=e.loadExternalDependency;if(!r)return void this.ap(bd);r(this._instance,"conversations",n=>{n||!e.initConversations?this.ap("Could not load conversations script",n):this.op(e.initConversations),this.np=!1})}catch(t){this.ap("Error initializing conversations",t),this.np=!1}}else Rt.error("Conversations enabled but missing token in remote config.")}op(e){if(this.ne)try{this._conversationsManager=e(this.ne,this._instance),this.sp=!1,Rt.info("Conversations loaded successfully")}catch(t){this.ap("Error completing conversations initialization",t)}else Rt.error("Cannot complete initialization: remote config is null")}ap(e,t){Rt.error(e,t),this._conversationsManager=null,this.np=!1,this.sp=!0}show(){this._conversationsManager?this._conversationsManager.show():Rt.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.ep===!0&&!He(this._conversationsManager)}getUnavailableReason(){return this.isAvailable()?null:this._instance.config.disable_conversations?"disabled_by_config":Zu(this._instance.config)?"disabled_for_toolbar":this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut()?"consent_opted_out":this.rp===!1?"remote_config_failed":M(this.ep)?this.rp?"disabled_in_project":"remote_config_pending":this.ep?fe(this.ne)||!this.ne.token?"missing_token":re?.__PosthogExtensions__?this.np?"initializing":this.sp?"load_failed":"not_loaded":"extensions_unavailable":"disabled_in_project"}isVisible(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.isVisible())!==null&&e!==void 0&&e}sendMessage(e,t,r){var n=this;return Ue(function*(){return n._conversationsManager?n._conversationsManager.sendMessage(e,t,r):(Rt.warn(sn),null)})()}getMessages(e,t){var r=this;return Ue(function*(){return r._conversationsManager?r._conversationsManager.getMessages(e,t):(Rt.warn(sn),null)})()}markAsRead(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.markAsRead(e):(Rt.warn(sn),null)})()}getTickets(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.getTickets(e):(Rt.warn(sn),null)})()}requestRestoreLink(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.requestRestoreLink(e):(Rt.warn(sn),null)})()}restoreFromToken(e){var t=this;return Ue(function*(){return t._conversationsManager?t._conversationsManager.restoreFromToken(e):(Rt.warn(sn),null)})()}restoreFromUrlToken(){var e=this;return Ue(function*(){return e._conversationsManager?e._conversationsManager.restoreFromUrlToken():(Rt.warn(sn),null)})()}getCurrentTicketId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getCurrentTicketId())!==null&&e!==void 0?e:null}getWidgetSessionId(){var e,t;return(e=(t=this._conversationsManager)===null||t===void 0?void 0:t.getWidgetSessionId())!==null&&e!==void 0?e:null}Sh(){var e;(e=this._conversationsManager)===null||e===void 0||e.setIdentity()}xh(){var e;(e=this._conversationsManager)===null||e===void 0||e.clearIdentity()}}},SM={logs:class{constructor(e){var t;this._instance=e,this.name="logs",this.lp=!1,this.up=!1,this.hp=!1,this.A=Ve("[logs]"),this.cp=b(b({},this.A),{},{error:(...r)=>{r.some(Zf)||this.A.error(...r)}}),this.ol=[],this.dp=[],this._d=0,this.To=!1,this.vp=[],this.fp=[],this.pp=!1,this.gp=!1,this.mp=()=>{var r,n;this.To||(this._d=0,(r=this.yp)===null||r===void 0||r.onReconnect(),(n=this.bp)===null||n===void 0||n.onReconnect())},this._instance&&(t=this._instance.config.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.lp=!0),A&&Ae(A,"online",this.mp)}_p(e,t,r,n){var i;const s=Vf((i=this._instance)===null||i===void 0||(i=i.config)===null||i===void 0?void 0:i.logs,r);return[new i1(this.wp(e,t),s,this.cp,()=>this.kp(),o=>o(),void 0,n),s]}Sp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.yp&&this.xp===t||((r=this.yp)===null||r===void 0||r.reset(),this.xp=t,[this.yp,this.Cp]=this._p(()=>this.ol,n=>{this.ol=n})),this.yp}$p(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs;var r;return this.bp&&this.Tp===t||((r=this.bp)===null||r===void 0||r.reset(),this.Tp=t,[this.bp,this.Ip]=this._p(()=>this.dp,n=>{this.dp=n},{serviceNameDefault:"posthog-browser-logs",consoleCapture:!0},Gf)),this.bp}setup(e){var t;if(this.To)return;this.bo=e,(t=this._instance)!==null&&t!==void 0&&(t=t.config)!==null&&t!==void 0&&(t=t.logs)!==null&&t!==void 0&&t.captureConsoleLogs&&(this.lp=!0),(this.lp||this.Mp()&&this.Ep())&&this.Pp();let r=!1;const n=e.onRemoteConfig(i=>{var s;r=i.ok&&((s=i.config.logs)===null||s===void 0?void 0:s.captureConsoleLogs)===!0,this.onRemoteConfig(i)});this.To?n.dispose():(this.Eo=n,r||this.loadIfEnabled())}dispose(){var e,t,r,n;this.To||(this.To=!0,this.Rp(),(e=this.Eo)===null||e===void 0||e.dispose(),this.Eo=void 0,this.bo=void 0,this.hp=!1,A?.removeEventListener("online",this.mp),(t=this.Ap)===null||t===void 0||t.call(this),this.Ap=void 0,(r=this.yp)===null||r===void 0||r.reset(),(n=this.bp)===null||n===void 0||n.reset())}onRemoteConfig(e){var t,r;if(this.To)return;const n=e.ok?(t=e.config.logs)===null||t===void 0?void 0:t.captureConsoleLogs:void 0;fe(n)?this.Fp():((r=this._instance)===null||r===void 0||(r=r.persistence)===null||r===void 0||r.register({$logs_capture_enabled_server_side:!!n}),n?(this.lp=!0,this.up||this.Pp(),this.loadIfEnabled()):this.Fp())}reset(){var e,t,r,n;this.Rp(),(e=this.yp)===null||e===void 0||e.clearQueue(),this.ol=[],(t=this.yp)===null||t===void 0||t.reset(),(r=this.bp)===null||r===void 0||r.clearQueue(),this.dp=[],(n=this.bp)===null||n===void 0||n.reset(),this._d=0}captureLog(e){this.To||this.Sp().captureLog(e)}captureConsoleLog(e){this.To||this.$p().captureLog(e)}captureBufferedConsoleLog(e,t,r){this.To||this.$p().captureLog(e,{context:t,occurredAtMs:r})}Ep(){var e;return!!(!((e=this._instance)===null||e===void 0||(e=e.persistence)===null||e===void 0||(e=e.props)===null||e===void 0)&&e[iy])}Mp(){var e,t,r;return!(!((e=this._instance)===null||e===void 0||(t=e.il)===null||t===void 0)&&t.call(e))||!!(!((r=re._POSTHOG_REMOTE_CONFIG)===null||r===void 0||(r=r[this._instance.config.token])===null||r===void 0)&&r.config)}$h(){var e;this.Rp(),(e=this.bp)===null||e===void 0||e.clearQueue(),this.dp=[]}Fp(){this.lp||this.Rp()}Pp(){var e;if(this.pp||!re?.console)return;const t=Vf((e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.logs).maxBufferSize;let r=!0;this.fp.push(()=>{r=!1});for(const n of oM){let i;try{i=aM(re.console[n])}catch{continue}i&&this.fp.push(bs(re.console,n,s=>{const o=(...a)=>{try{r&&this.Op(n,a,t)}catch{}return s.apply(re.console,a)};return o.__rrweb_original__=i,o}))}this.pp=!0,this.Dp=setTimeout(()=>{this.Rp()},3e4)}Op(e,t,r){var n;if(this.pp&&!this.gp&&t.length!==0)if(!((n=this._instance)===null||n===void 0)&&n.is_capturing()){if(r>this.vp.length){this.gp=!0;try{this.vp.push({level:e,args:t,occurredAtMs:Date.now(),context:this.kp()})}finally{this.gp=!1}}}else this.Rp()}Rp(){if(this.vp=[],this.pp){this.pp=!1,this.Dp&&(clearTimeout(this.Dp),this.Dp=void 0);for(const e of this.fp)e();this.fp=[]}}Lp(){const e=this.vp;return this.Rp(),e}get logger(){return this.Np||(this.Np={trace:(e,t)=>this.captureLog({body:e,level:"trace",attributes:t}),debug:(e,t)=>this.captureLog({body:e,level:"debug",attributes:t}),info:(e,t)=>this.captureLog({body:e,level:"info",attributes:t}),warn:(e,t)=>this.captureLog({body:e,level:"warn",attributes:t}),error:(e,t)=>this.captureLog({body:e,level:"error",attributes:t}),fatal:(e,t)=>this.captureLog({body:e,level:"fatal",attributes:t})}),this.Np}flushLogs(e){e?this.qp(e):(this.yp&&this.yp.flush().catch(t=>this.jp(t)),this.bp&&this.bp.flush().catch(t=>this.jp(t)))}jp(e){Zf(e)||this.A.error("PostHog logs flush failed:",e)}loadIfEnabled(){if(this.To||!this.lp||this.up||this.hp)return;const e=re?.__PosthogExtensions__;if(!e)return this.A.error("PostHog Extensions not found."),void this.Rp();const t=e.loadExternalDependency;if(!t)return this.A.error(bd),void this.Rp();this.hp=!0;try{t(this._instance,"logs",r=>{if(this.hp=!1,this.To||!this.lp)return;const n=e.logs;if(r||!n?.initializeLogs)this.A.error("Could not load logs script",r),this.Rp();else{var i;const a=this.Lp();var s,o;this.Ap=n.initializeLogs((i=this.bo)!==null&&i!==void 0?i:this._instance),this.up=!0,a.length>0&&((s=n.replayConsoleBuffer)===null||s===void 0||s.call(n,(o=this.bo)!==null&&o!==void 0?o:this._instance,a))}})}catch(r){throw this.hp=!1,r}}wp(e,t){const r=this._instance;return{get isDisabled(){return!1},get optedOut(){return!r.is_capturing()},getPersistedProperty:n=>n===Jt.LogsQueue?e():void 0,setPersistedProperty(n,i){var s;n===Jt.LogsQueue&&t((s=i)!==null&&s!==void 0?s:[])},js:n=>this.js(n),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}js(e){return new Promise(t=>{if(zy(this._d,3))return void t({kind:"fatal",error:Hc(void 0,"logs endpoint is unreachable, dropping batch")});let r=!1;const n=s=>{r||(r=!0,clearTimeout(i),t(s))},i=setTimeout(()=>{this.A.warn("Logs request timed out before receiving a response"),n({kind:"retry-later",error:Hc(void 0,"logs request timed out")})},9e4);this._instance._send_request({method:"POST",url:this.Bp(),data:e,compression:"best-available",batchKey:"logs",fireCallbackOnDrop:!0,callback:s=>{const o=s.statusCode;if(this.Hp(o),o>=200&&300>o)n({kind:"ok"});else if(o===413)n({kind:"too-large"});else if(o!==0&&o!==408&&o!==429&&500>o)n({kind:"fatal",error:new Error(`logs request failed with status ${o}`)});else{var a;o===0?(s.error||this.A.warn("Logs request failed before receiving an HTTP response"),n({kind:"retry-later",error:Hc(s.error,"logs request failed before receiving an HTTP response")})):n({kind:"retry-later",error:(a=s.error)!==null&&a!==void 0?a:new Error(`logs request failed with status ${o}`)})}}})})}Hp(e){(e!==0||this._instance.__loaded)&&(this._d=Uy(e,this._d,3,()=>this.A.warn("Log requests are failing before receiving an HTTP response; this can happen due to network issues, CORS, browser blocking, or ad blockers. Stopped sending logs; will try again when connectivity changes.")))}qp(e){this.ol.length>0&&this.zp(e,this.ol,this.Cp,et.LIB_NAME,t=>{this.ol=t}),this.dp.length>0&&this.zp(e,this.dp,this.Ip,Gf,t=>{this.dp=t})}zp(e,t,r,n,i){if(t.length===0)return;const s=t.map(a=>a.record);i([]);const o=Y_(s,K_(r,et.LIB_NAME,et.LIB_VERSION),n,et.LIB_VERSION);this._instance._send_request({method:"POST",url:this.Bp(),data:o,compression:"best-available",batchKey:"logs",transport:e})}Bp(){return this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token)}kp(){var e;const t={};if(t.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){const{sessionId:r,windowId:n,sessionStartTimestamp:i,lastActivityTimestamp:s}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);t.sessionId=r,t.windowId=n,fe(i)||(t.sessionStartTimestamp=i),fe(s)||(t.lastActivityTimestamp=s)}if(re!=null&&(e=re.location)!==null&&e!==void 0&&e.href&&(t.currentUrl=this._instance.config.disable_capture_url_hashes?Jr(re.location.href):re.location.href),this._instance.featureFlags){const r=this._instance.featureFlags.getFlags();r&&r.length>0&&(t.activeFeatureFlags=r)}return t}}},EM={metrics:class{constructor(e){this._instance=e,this.A=Ve("[metrics]"),this.To=!1}initialize(){this.onConfigChange()}onConfigChange(){var e;if(this.To)return;const t=!!(!((e=this._instance.config.metrics)===null||e===void 0)&&e.network);t&&!this.Up?this.Up=(r=>{let n=!0;const i=()=>n?(a=>{var c;const u=(c=a.config.metrics)===null||c===void 0?void 0:c.network;return u===!0?{}:u||void 0})(r):void 0,s=lM(r,i),o=dM(r,i);return()=>{n=!1,s(),o()}})(this._instance):!t&&this.Up&&(this.Up(),this.Up=void 0)}Sp(){var e;const t=(e=this._instance)===null||e===void 0||(e=e.config)===null||e===void 0?void 0:e.metrics;var r;return this.yp&&this.xp===t||((r=this.yp)===null||r===void 0||r.reset(),this.xp=t,this.yp=new s1(this.wp(),(function(n){var i,s,o,a,c;const u=n?.resourceAttributes;return{serviceName:(i=u?.["service.name"])!==null&&i!==void 0?i:n?.serviceName,serviceVersion:(s=u?.["service.version"])!==null&&s!==void 0?s:n?.serviceVersion,environment:(o=u?.["deployment.environment"])!==null&&o!==void 0?o:n?.environment,resourceAttributes:u,beforeSend:n?.beforeSend,flushIntervalMs:(a=n?.flushIntervalMs)!==null&&a!==void 0?a:1e4,maxSeriesPerFlush:(c=n?.maxSeriesPerFlush)!==null&&c!==void 0?c:1e3}})(t),this.A)),this.yp}count(e,t=1,r){this.Sp().count(e,t,r)}gauge(e,t,r){this.Sp().gauge(e,t,r)}histogram(e,t,r){this.Sp().histogram(e,t,r)}flush(e){if(!this.yp)return Promise.resolve();if(e){const t=this.yp.drainWindow();return t&&this.Ys(t,e),Promise.resolve()}return this.yp.flush().catch(t=>this.A.error("PostHog metrics flush failed:",t))}reset(){var e;(e=this.yp)===null||e===void 0||e.reset()}dispose(){var e,t;this.To=!0,(e=this.Up)===null||e===void 0||e.call(this),this.Up=void 0,(t=this.yp)===null||t===void 0||t.reset()}wp(){const e=this._instance,t=this;return{get isDisabled(){return!1},get optedOut(){return!e.is_capturing()},Ys:r=>t.Ys(r),getLibraryId:()=>et.LIB_NAME,getLibraryVersion:()=>et.LIB_VERSION}}Ys(e,t){return new Promise(r=>{let n=!1;const i=o=>{n||(n=!0,clearTimeout(s),r(o))},s=setTimeout(()=>i({kind:"retry-later",error:new Error("metrics request timed out")}),9e4);this._instance._send_request(b(b({method:"POST",url:this.Wp(),data:e,compression:"best-available",batchKey:"metrics"},t&&{transport:t}),{},{fireCallbackOnDrop:!0,callback(o){const a=o.statusCode;if(a>=200&&300>a)i({kind:"ok"});else if(a===413)i({kind:"too-large"});else if(a!==0&&a!==408&&a!==429&&500>a)i({kind:"fatal",error:new Error(`metrics request failed with status ${a}`)});else{var c;i({kind:"retry-later",error:(c=o.error)!==null&&c!==void 0?c:new Error(`metrics request failed with status ${a}`)})}}}))})}Wp(){return this._instance.requestRouter.endpointFor("api","/i/v1/metrics")+"?token="+encodeURIComponent(this._instance.config.token)}}};is.__defaultExtensionClasses=b({},b(b(b(b(b(b(b(b(b(b(b(b(b({},ja),hM),pM),fM),vM),gM),_M),mM),yM),bM),wM),SM),EM));var kM=(function(){et.SDK_DIST_CHANNEL="npm";const e=rs[ji]=new is;return(function(){function t(){t.done||(t.done=!0,u0=!1,Pe(rs,function(r){r._dom_loaded()}))}D?.addEventListener?D.readyState==="complete"?t():Ae(D,"DOMContentLoaded",t,{capture:!1}):A&&j.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),e})(),IM=kM,AM=/\.[cm]?[jt]sx?$/,TM=/^(?:[a-z][a-z0-9+.-]*:\/\/|\/)/i;function RM(e,t){if(typeof e!="string"||!TM.test(e))return!1;let r;try{r=new URL(e,t)}catch{return!1}return r.origin!==t?!1:!AM.test(r.pathname)}function PM(e,t){return e.length===0?!1:e.every(r=>RM(r,t))}function OM(e,t){return e.length===0?!1:e.every(r=>PM(r,t))}var E0=new Set(["caniuse.dev","www.caniuse.dev"]),CM=new Set(["score.mcpjam.com","www.score.mcpjam.com"]),$M=new Set([...E0,...CM]),Xz="https://app.mcpjam.com";function xM(e){return E0.has(e.toLowerCase())}function Qz(e=typeof window>"u"?void 0:window.location.hostname){return!!e&&xM(e)}var MM="phc_dTOPniyUNU2kD8Jx8yHMXSqiZHM8I91uWopTMX6EBE9",LM="https://us.i.posthog.com";function NM(){return typeof window<"u"&&window.location?.origin?.startsWith("http")?`${window.location.origin}/tlm`:LM}function k0(e){const t=Xc()?.guestId,r=e&&Object.keys(e).length>0?e:void 0;return!t&&!r?{}:{bootstrap:{...t?{distinctID:t,isIdentifiedID:!1}:{},...r?{featureFlags:r}:{}}}}var DM={advanced_disable_feature_flags:!0,advanced_disable_feature_flags_on_first_load:!0},zM=["/results/","/conformance/shared/","/evals/shared/"];function I0(e){let t=e;for(const r of zM){const n=r.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&");t=t.replace(new RegExp(`(${n})[^/?#]+`,"g"),"$1[redacted]")}return t=t.replace(/(\/organizations\/)[^/?#]+/g,"$1[redacted]"),t}var UM=new Set(["Load failed","Failed to fetch","NetworkError when attempting to fetch resource."]),FM=/^'TypeError' captured as exception with message: '([\s\S]*)'$/;function qM(e){const t=FM.exec(e.value),r=t?t[1]:e.type==="TypeError"?e.value:void 0;return r===void 0?!1:UM.has(r)||r.startsWith("Failed to fetch (")&&r.endsWith(")")}var jM=1e4;function HM(e){const t=e.$exception_list;if(!(Array.isArray(t)&&t.some(i=>typeof i?.value=="string"&&qM(i))))return;const r=J0();if(!r)return;const n=Date.now()-r.at;n>jM||(e.failed_request=`${r.method} ${I0(r.target)}`,e.failed_request_age_ms=n)}function BM(e,t){for(const r of["$current_url","$referrer","$pathname","$session_entry_url","$session_entry_pathname","$session_entry_referrer","$initial_current_url","$initial_pathname","$initial_referrer"])typeof e[r]=="string"&&(e[r]=I0(e[r]));return t==="$exception"&&HM(e),e}function VM(e){if(e?.event!=="$exception"||typeof window>"u")return e;const t=e.properties?.$exception_list;if(!Array.isArray(t))return e;const r=t.map(n=>{const i=n?.stacktrace?.frames;return Array.isArray(i)?i.map(s=>s?.filename):[]});return OM(r,window.location.origin)?null:e}var GM=$M;function Rs(){return ZM()}function ZM(){return typeof window<"u"&&window.isElectron===!0}var WM="data-ph-no-capture",JM={maskAllInputs:!0,maskInputOptions:{password:!0},maskTextSelector:`[${WM}]`};function Od(e=typeof window>"u"?void 0:window.location?.pathname){return!!e&&(e.startsWith("/results/")||e.startsWith("/conformance/shared/")||e.startsWith("/evals/shared/"))}function KM(){return Rs()&&!Od()}var Bc=!1;function eU(e,t){try{if(!Rs())return;if(Od(t)){e.sessionRecordingStarted?.()&&(Bc=!0),e.stopSessionRecording?.();return}Bc&&(Bc=!1,e.startSessionRecording?.())}catch{}}function YM(e=typeof window>"u"?void 0:window.location?.hostname){const t=!!e&&GM.has(e.toLowerCase());return{capture_pageview:t?"history_change":!1,capture_pageleave:t}}var Wf={api_host:NM(),ui_host:"https://us.posthog.com",...k0(),...YM(),...DM,person_profiles:"always",sanitize_properties:BM,before_send:VM,capture_dead_clicks:!0,get capture_exceptions(){return Rs()},get disable_session_recording(){return!KM()},session_recording:JM,loaded:e=>{e.register({environment:"production",platform:ol(),version:"3.13.0",deployment:"self_hosted",source:"client"}),e.setPersonPropertiesForFlags?.({local_browser_security_version:"1",deployment:"self_hosted",platform:ol()})}};function XM(e){const t=k0(e);return"bootstrap"in t?Object.defineProperties({},{...Object.getOwnPropertyDescriptors(Wf),bootstrap:{value:t.bootstrap,enumerable:!0,configurable:!0,writable:!0}}):Wf}var tU=()=>MM,rU=e=>XM(e);function ol(){if(window?.isElectron){const e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("darwin")?"mac":e.includes("win")?"win":"electron"}return"npm"}function QM(){return"production"}function nU(e){const t=QM();return{location:e,platform:ol(),...t!==void 0?{environment:t}:{}}}var Jf=e=>{let t;const r=new Set,n=(u,l)=>{const h=typeof u=="function"?u(t):u;if(!Object.is(h,t)){const d=t;t=l??(typeof h!="object"||h===null)?h:Object.assign({},t,h),r.forEach(p=>p(t,d))}},i=()=>t,a={setState:n,getState:i,getInitialState:()=>c,subscribe:u=>(r.add(u),()=>r.delete(u))},c=t=e(n,i,a);return a},eL=(e=>e?Jf(e):Jf),tL=e=>e;function rL(e,t=tL){const r=Cs.useSyncExternalStore(e.subscribe,Cs.useCallback(()=>t(e.getState()),[e,t]),Cs.useCallback(()=>t(e.getInitialState()),[e,t]));return Cs.useDebugValue(r),r}var Kf=e=>{const t=eL(e),r=n=>rL(t,n);return Object.assign(r,t),r},nL=(e=>e?Kf(e):Kf),Kt=[],Ot=[],iL=Uint8Array,Vc="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var Nn=0,sL=Vc.length;Nn<sL;++Nn)Kt[Nn]=Vc[Nn],Ot[Vc.charCodeAt(Nn)]=Nn;Ot[45]=62;Ot[95]=63;function oL(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function aL(e,t,r){return(t+r)*3/4-r}function ta(e){for(var t,r=oL(e),n=r[0],i=r[1],s=new iL(aL(e,n,i)),o=0,a=i>0?n-4:n,c=0;c<a;c+=4)t=Ot[e.charCodeAt(c)]<<18|Ot[e.charCodeAt(c+1)]<<12|Ot[e.charCodeAt(c+2)]<<6|Ot[e.charCodeAt(c+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=Ot[e.charCodeAt(c)]<<2|Ot[e.charCodeAt(c+1)]>>4,s[o++]=t&255),i===1&&(t=Ot[e.charCodeAt(c)]<<10|Ot[e.charCodeAt(c+1)]<<4|Ot[e.charCodeAt(c+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function cL(e){return Kt[e>>18&63]+Kt[e>>12&63]+Kt[e>>6&63]+Kt[e&63]}function uL(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(cL(n));return i.join("")}function ra(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(uL(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(Kt[t>>2]+Kt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(Kt[t>>10]+Kt[t>>4&63]+Kt[t<<2&63]+"=")),i.join("")}function iU(e){if(e===void 0)return{};if(!A0(e))throw new Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function sU(e){if(typeof e>"u")throw new Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if(typeof e!="string")throw new Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw new Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw new Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw new Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function A0(e){const t=typeof e=="object",r=Object.getPrototypeOf(e),n=r===null||r===Object.prototype||r?.constructor?.name==="Object";return t&&n}var T0=!0,hi=BigInt("-9223372036854775808"),Cd=BigInt("9223372036854775807"),al=BigInt("0"),lL=BigInt("8"),dL=BigInt("256"),Gc="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.",R0=class{[Symbol.toPrimitive](e){if(e==="string")return this.toString();throw new Error(Gc)}valueOf(){throw new Error(Gc)}toJSON(){throw new Error(Gc)}toString(){return"[unresolved commit timestamp]"}},hL=new R0;function P0(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function pL(e){e<al&&(e-=hi+hi);let t=e.toString(16);t.length%2===1&&(t="0"+t);const r=new Uint8Array(new ArrayBuffer(8));let n=0;for(const i of t.match(/.{2}/g).reverse())r.set([parseInt(i,16)],n++),e>>=lL;return ra(r)}function fL(e){const t=ta(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let r=al,n=al;for(const i of t)r+=BigInt(i)*dL**n,n++;return r>Cd&&(r+=hi+hi),r}function vL(e){if(e<hi||Cd<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);const t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),ra(new Uint8Array(t))}function gL(e){const t=ta(e);if(t.byteLength!==8)throw new Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}var mL=DataView.prototype.setBigInt64?vL:pL,_L=DataView.prototype.getBigInt64?gL:fL,Yf=1024;function cl(e){if(e.length>Yf)throw new Error(`Field name ${e} exceeds maximum field name length ${Yf}.`);if(e.startsWith("$"))throw new Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){const r=e.charCodeAt(t);if(r<32||r>=127)throw new Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function Xf(e){if(e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string")return e;if(Array.isArray(e))return e.map(n=>Xf(n));if(typeof e!="object")throw new Error(`Unexpected type of ${e}`);const t=Object.entries(e);if(t.length===1){const n=t[0][0];if(n==="$bytes"){if(typeof e.$bytes!="string")throw new Error(`Malformed $bytes field on ${e}`);return ta(e.$bytes).buffer}if(n==="$integer"){if(typeof e.$integer!="string")throw new Error(`Malformed $integer field on ${e}`);return _L(e.$integer)}if(n==="$float"){if(typeof e.$float!="string")throw new Error(`Malformed $float field on ${e}`);const i=ta(e.$float);if(i.byteLength!==8)throw new Error(`Received ${i.byteLength} bytes, expected 8 for $float`);const s=new DataView(i.buffer).getFloat64(0,T0);if(!P0(s))throw new Error(`Float ${s} should be encoded as a number`);return s}if(n==="$commitTs"){if(e.$commitTs!==null)throw new Error(`Malformed $commitTs field on ${e}`);return hL}if(n==="$set")throw new Error("Received a Set which is no longer supported as a Convex type.");if(n==="$map")throw new Error("Received a Map which is no longer supported as a Convex type.")}const r={};for(const[n,i]of Object.entries(e))cl(n),r[n]=Xf(i);return r}var yL=16384;function Yn(e){const t=JSON.stringify(e,(r,n)=>n===void 0?"undefined":typeof n=="bigint"?`${n.toString()}n`:n);if(t.length>yL){const r="[...truncated]";let n=16370;const i=t.codePointAt(n-1);return i!==void 0&&i>65535&&(n-=1),t.substring(0,n)+r}return t}function na(e,t,r,n){if(e===void 0){const o=r&&` (present at path ${r} in original object ${Yn(t)})`;throw new Error(`undefined is not a valid Convex value${o}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e=="bigint"){if(e<hi||Cd<e)throw new Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:mL(e)}}if(typeof e=="number")if(P0(e)){const o=new ArrayBuffer(8);return new DataView(o).setFloat64(0,e,T0),{$float:ra(new Uint8Array(o))}}else return e;if(typeof e=="boolean"||typeof e=="string")return e;if(e instanceof ArrayBuffer)return{$bytes:ra(new Uint8Array(e))};if(e instanceof R0)return{$commitTs:null};if(Array.isArray(e))return e.map((o,a)=>na(o,t,r+`[${a}]`,!1));if(e instanceof Set)throw new Error(Zc(r,"Set",[...e],t));if(e instanceof Map)throw new Error(Zc(r,"Map",[...e],t));if(!A0(e)){const o=e?.constructor?.name,a=o?`${o} `:"";throw new Error(Zc(r,a,e,t))}const i={},s=Object.entries(e);s.sort(([o,a],[c,u])=>o===c?0:o<c?-1:1);for(const[o,a]of s)a!==void 0?(cl(o),i[o]=na(a,t,r+`.${o}`,!1)):n&&(cl(o),i[o]=bL(a,t,r+`.${o}`));return i}function Zc(e,t,r,n){return e?`${t}${Yn(r)} is not a supported Convex type (present at path ${e} in original object ${Yn(n)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${Yn(r)} is not a supported Convex type.`}function bL(e,t,r){if(e===void 0)return{$undefined:null};if(t===void 0)throw new Error(`Programming error. Current value is ${Yn(e)} but original value is undefined`);return na(e,t,r,!1)}function oU(e){return na(e,e,"",!1)}var wL=Object.defineProperty,SL=(e,t,r)=>t in e?wL(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Wc=(e,t,r)=>SL(e,typeof t!="symbol"?t+"":t,r),Qf,ev,EL=Symbol.for("ConvexError"),kL=class extends(ev=Error,Qf=EL,ev){constructor(e){super(typeof e=="string"?e:Yn(e)),Wc(this,"name","ConvexError"),Wc(this,"data"),Wc(this,Qf,!0),this.data=e}};var aU=5e3,So=null;function cU(e=Date.now()){So=e}function IL(e=Date.now()){if(So===null)return!1;const t=e-So;return t<0||t>1e4?(So=null,!1):!0}var AL=nL((e,t)=>({status:"idle",kind:null,retryNonce:0,queriesPaused:!1,authConfirmed:!1,recoveryId:null,recoveryAt:0,pauseQueries:()=>e({queriesPaused:!0}),resumeQueries:()=>{t().authConfirmed&&e({queriesPaused:!1})},notifyFailure:r=>{if(IL()){e({status:"idle",kind:null});return}if(t().kind==="signed_out"){e({status:"failed"});return}e({status:"failed",kind:r})},retry:()=>e(r=>({status:"retrying",retryNonce:r.retryNonce+1})),clear:()=>e({status:"idle",kind:null})}));function $d(e){return Ld(e,"forbidden")}function xd(e){return Ld(e,"session_revoked")}function Md(e){return Ld(e,"unauthenticated")}function Ld(e,t){if(!(e instanceof kL))return!1;const r=e.data;return typeof r=="object"&&r!==null&&r.kind===t}var ia;function uU(e){try{ia=new URL(e).hostname}catch{ia=void 0}}function ul(e){try{const t=new URL(e);if(!/^https?:$/.test(t.protocol))return;const r=t.pathname.replace(/(\/(?:results|conformance\/shared|evals\/shared|organizations)\/)[^/]+/g,"$1[redacted]").replace(/(\/(?:user-testing|chatbox)\/[^/]+\/)[^/]+/g,"$1[redacted]");return`${t.origin}${r}`}catch{return}}function ss(e){const t=/^\[CONVEX Q\(([\w/.-]+:[\w.-]+)\)\]/.exec(e);if(!t)return;const r=/\[Request ID: ([a-f\d]+)\]/i.exec(e)?.[1],n=`${t[0]}${r?` [Request ID: ${r}]`:""} ${/\bServer Error\b/.test(e)?"Server Error":"Query failed"}`;return{functionName:t[1],requestId:r,safeMessage:n}}function O0(e){const t=ss(e);if(t)return{convex_function:t.functionName,...t.requestId?{request_id:t.requestId}:{},...ia?{convex_backend:ia}:{}}}function TL(e){const t=ss(e.message);if(!t)return e;const r=new Error(t.safeMessage);if(r.name=e.name,e.stack){const n=e.stack.split(`
|
|
115
|
+
`).filter(i=>/^(\s+at |[^@]*@(?:https?|file|webpack|vite):)/.test(i));r.stack=`${r.name}: ${r.message}
|
|
116
|
+
${n.join(`
|
|
117
|
+
`)}`}return r}function C0(e=500){const t=new Set;return(r,n)=>{if(!r||!n)return!1;const i=`${r}:${n}`;return t.has(i)?!0:(t.add(i),t.size>e&&t.delete(t.values().next().value),!1)}}function lU(e=500){const t=C0(e);return(r,n={})=>{try{const i=r.exception?.values,s=i?.find(l=>ss(l.value??"")),o=ss(s?.value??"");if(!o)return r;if($d(n.originalException)||xd(n.originalException)||Md(n.originalException))return null;const a=O0(s.value),c=typeof r.tags?.convex_backend=="string"?r.tags.convex_backend:a.convex_backend;if(t(c,o.requestId))return null;s.value=o.safeMessage,r.message&&(r.message=o.safeMessage),r.tags={...r.tags,...a,...c?{convex_backend:c}:{}};const u=ul((typeof r.extra?.page_location=="string"?r.extra.page_location:void 0)??r.request?.url??(typeof window<"u"?window.location.href:""));r.request=u?{url:u}:void 0,r.breadcrumbs=void 0,r.extra={...typeof r.extra?.boundary=="string"?{boundary:r.extra.boundary}:{},...typeof r.extra?.componentStack=="string"?{componentStack:r.extra.componentStack}:{},...u?{page_location:u}:{}};for(const l of i??[])if(l!==s&&l.value&&(l.value=ss(l.value)?.safeMessage??"Query failure cause"),l.stacktrace)for(const h of l.stacktrace.frames??[])delete h.vars;return r.transaction?.includes("/")&&(r.transaction=ul(`https://route.invalid${r.transaction}`)?.replace("https://route.invalid","")),r}catch{return null}}}var RL=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,$0="8.55.0",xt=globalThis;function Ha(e,t,r){const n=r||xt,i=n.__SENTRY__=n.__SENTRY__||{},s=i[$0]=i["8.55.0"]||{};return s[e]||(s[e]=t())}var Ba=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,PL="Sentry Logger ",tv=["debug","info","warn","error","log","assert","trace"],rv={};function x0(e){if(!("console"in xt))return e();const t=xt.console,r={},n=Object.keys(rv);n.forEach(i=>{const s=rv[i];r[i]=t[i],t[i]=s});try{return e()}finally{n.forEach(i=>{t[i]=r[i]})}}function OL(){let e=!1;const t={enable:()=>{e=!0},disable:()=>{e=!1},isEnabled:()=>e};return Ba?tv.forEach(r=>{t[r]=(...n)=>{e&&x0(()=>{xt.console[r](`${PL}[${r}]:`,...n)})}}):tv.forEach(r=>{t[r]=()=>{}}),t}var bn=Ha("logger",OL),M0=50;var nv=/\(error: (.*)\)/,iv=/captureMessage|captureException/;function CL(...e){const t=e.sort((r,n)=>r[0]-n[0]).map(r=>r[1]);return(r,n=0,i=0)=>{const s=[],o=r.split(`
|
|
118
|
+
`);for(let a=n;a<o.length;a++){const c=o[a];if(c.length>1024)continue;const u=nv.test(c)?c.replace(nv,"$1"):c;if(!u.match(/\S*Error: /)){for(const l of t){const h=l(u);if(h){s.push(h);break}}if(s.length>=M0+i)break}}return $L(s.slice(i))}}function dU(e){return Array.isArray(e)?CL(...e):e}function $L(e){if(!e.length)return[];const t=Array.from(e);return/sentryWrapped/.test(Xs(t).function||"")&&t.pop(),t.reverse(),iv.test(Xs(t).function||"")&&(t.pop(),iv.test(Xs(t).function||"")&&t.pop()),t.slice(0,M0).map(r=>({...r,filename:r.filename||Xs(t).filename,function:r.function||"?"}))}function Xs(e){return e[e.length-1]||{}}var Jc="<anonymous>";function xL(e){try{return!e||typeof e!="function"?Jc:e.name||Jc}catch{return Jc}}function hU(e){const t=e.exception;if(t){const r=[];try{return t.values.forEach(n=>{n.stacktrace.frames&&r.push(...n.stacktrace.frames)}),r}catch{return}}}function Ps(){return Nd(xt),xt}function Nd(e){const t=e.__SENTRY__=e.__SENTRY__||{};return t.version=t.version||"8.55.0",t[$0]=t["8.55.0"]||{}}var L0=Object.prototype.toString;function ML(e){switch(L0.call(e)){case"[object Error]":case"[object Exception]":case"[object DOMException]":case"[object WebAssembly.Exception]":return!0;default:return Va(e,Error)}}function bi(e,t){return L0.call(e)===`[object ${t}]`}function pU(e){return bi(e,"ErrorEvent")}function fU(e){return bi(e,"DOMError")}function vU(e){return bi(e,"DOMException")}function sa(e){return bi(e,"String")}function LL(e){return typeof e=="object"&&e!==null&&"__sentry_template_string__"in e&&"__sentry_template_values__"in e}function gU(e){return e===null||LL(e)||typeof e!="object"&&typeof e!="function"}function Dd(e){return bi(e,"Object")}function NL(e){return typeof Event<"u"&&Va(e,Event)}function DL(e){return typeof Element<"u"&&Va(e,Element)}function zL(e){return bi(e,"RegExp")}function zd(e){return!!(e&&e.then&&typeof e.then=="function")}function UL(e){return Dd(e)&&"nativeEvent"in e&&"preventDefault"in e&&"stopPropagation"in e}function Va(e,t){try{return e instanceof t}catch{return!1}}function N0(e){return!!(typeof e=="object"&&e!==null&&(e.__isVue||e._isVue))}var Xn=xt,FL=80;function qL(e,t={}){if(!e)return"<unknown>";try{let r=e;const n=5,i=[];let s=0,o=0;const a=" > ",c=3;let u;const l=Array.isArray(t)?t:t.keyAttrs,h=!Array.isArray(t)&&t.maxStringLength||FL;for(;r&&s++<n&&(u=jL(r,l),!(u==="html"||s>1&&o+i.length*c+u.length>=h));)i.push(u),o+=u.length,r=r.parentNode;return i.reverse().join(a)}catch{return"<unknown>"}}function jL(e,t){const r=e,n=[];if(!r||!r.tagName)return"";if(Xn.HTMLElement&&r instanceof HTMLElement&&r.dataset){if(r.dataset.sentryComponent)return r.dataset.sentryComponent;if(r.dataset.sentryElement)return r.dataset.sentryElement}n.push(r.tagName.toLowerCase());const i=t&&t.length?t.filter(s=>r.getAttribute(s)).map(s=>[s,r.getAttribute(s)]):null;if(i&&i.length)i.forEach(s=>{n.push(`[${s[0]}="${s[1]}"]`)});else{r.id&&n.push(`#${r.id}`);const s=r.className;if(s&&sa(s)){const o=s.split(/\s+/);for(const a of o)n.push(`.${a}`)}}for(const s of["aria-label","type","name","title","alt"]){const o=r.getAttribute(s);o&&n.push(`[${s}="${o}"]`)}return n.join("")}function mU(){try{return Xn.document.location.href}catch{return""}}function _U(e){return Xn.document&&Xn.document.querySelector?Xn.document.querySelector(e):null}function yU(e){if(!Xn.HTMLElement)return null;let t=e;const r=5;for(let n=0;n<r;n++){if(!t)return null;if(t instanceof HTMLElement){if(t.dataset.sentryComponent)return t.dataset.sentryComponent;if(t.dataset.sentryElement)return t.dataset.sentryElement}t=t.parentNode}return null}function os(e,t=0){return typeof e!="string"||t===0||e.length<=t?e:`${e.slice(0,t)}...`}function bU(e,t){if(!Array.isArray(e))return"";const r=[];for(let n=0;n<e.length;n++){const i=e[n];try{N0(i)?r.push("[VueViewModel]"):r.push(String(i))}catch{r.push("[value cannot be serialized]")}}return r.join(t)}function HL(e,t,r=!1){return sa(e)?zL(t)?t.test(e):sa(t)?r?e===t:e.includes(t):!1:!1}function wU(e,t=[],r=!1){return t.some(n=>HL(e,n,r))}function SU(e,t,r){if(!(t in e))return;const n=e[t],i=r(n);typeof i=="function"&&BL(i,n);try{e[t]=i}catch{Ba&&bn.log(`Failed to replace method "${t}" in object`,e)}}function pi(e,t,r){try{Object.defineProperty(e,t,{value:r,writable:!0,configurable:!0})}catch{Ba&&bn.log(`Failed to add non-enumerable property "${t}" to object`,e)}}function BL(e,t){try{e.prototype=t.prototype=t.prototype||{},pi(e,"__sentry_original__",t)}catch{}}function EU(e){return e.__sentry_original__}function D0(e){if(ML(e))return{message:e.message,name:e.name,stack:e.stack,...ov(e)};if(NL(e)){const t={type:e.type,target:sv(e.target),currentTarget:sv(e.currentTarget),...ov(e)};return typeof CustomEvent<"u"&&Va(e,CustomEvent)&&(t.detail=e.detail),t}else return e}function sv(e){try{return DL(e)?qL(e):Object.prototype.toString.call(e)}catch{return"<unknown>"}}function ov(e){if(typeof e=="object"&&e!==null){const t={};for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}else return{}}function kU(e,t=40){const r=Object.keys(D0(e));r.sort();const n=r[0];if(!n)return"[object has no keys]";if(n.length>=t)return os(n,t);for(let i=r.length;i>0;i--){const s=r.slice(0,i).join(", ");if(!(s.length>t))return i===r.length?s:os(s,t)}return""}function Ht(e){return ll(e,new Map)}function ll(e,t){if(VL(e)){const r=t.get(e);if(r!==void 0)return r;const n={};t.set(e,n);for(const i of Object.getOwnPropertyNames(e))typeof e[i]<"u"&&(n[i]=ll(e[i],t));return n}if(Array.isArray(e)){const r=t.get(e);if(r!==void 0)return r;const n=[];return t.set(e,n),e.forEach(i=>{n.push(ll(i,t))}),n}return e}function VL(e){if(!Dd(e))return!1;try{const t=Object.getPrototypeOf(e).constructor.name;return!t||t==="Object"}catch{return!0}}var z0=1e3;function Ud(){return Date.now()/z0}function GL(){const{performance:e}=xt;if(!e||!e.now)return Ud;const t=Date.now()-e.now(),r=e.timeOrigin==null?t:e.timeOrigin;return()=>(r+e.now())/z0}var Fd=GL(),Qs,IU=(()=>{const{performance:e}=xt;if(!e||!e.now){Qs="none";return}const t=36e5,r=e.now(),n=Date.now(),i=e.timeOrigin?Math.abs(e.timeOrigin+r-n):t,s=i<t,o=e.timing&&e.timing.navigationStart,a=typeof o=="number"?Math.abs(o+r-n):t;return s||a<t?i<=a?(Qs="timeOrigin",e.timeOrigin):(Qs="navigationStart",o):(Qs="dateNow",n)})();function Fr(){const e=xt,t=e.crypto||e.msCrypto;let r=()=>Math.random()*16;try{if(t&&t.randomUUID)return t.randomUUID().replace(/-/g,"");t&&t.getRandomValues&&(r=()=>{const n=new Uint8Array(1);return t.getRandomValues(n),n[0]})}catch{}return"10000000100040008000100000000000".replace(/[018]/g,n=>(n^(r()&15)>>n/4).toString(16))}function U0(e){return e.exception&&e.exception.values?e.exception.values[0]:void 0}function AU(e){const{message:t,event_id:r}=e;if(t)return t;const n=U0(e);return n?n.type&&n.value?`${n.type}: ${n.value}`:n.type||n.value||r||"<unknown>":r||"<unknown>"}function TU(e,t,r){const n=e.exception=e.exception||{},i=n.values=n.values||[],s=i[0]=i[0]||{};s.value||(s.value=t||""),s.type||(s.type=r||"Error")}function ZL(e,t){const r=U0(e);if(!r)return;const n={type:"generic",handled:!0},i=r.mechanism;if(r.mechanism={...n,...i,...t},t&&"data"in t){const s={...i&&i.data,...t.data};r.mechanism.data=s}}function RU(e){if(WL(e))return!0;try{pi(e,"__sentry_captured__",!0)}catch{}return!1}function WL(e){try{return e.__sentry_captured__}catch{}}var dr;(function(e){e[e.PENDING=0]="PENDING";const r=1;e[e.RESOLVED=r]="RESOLVED";const n=2;e[e.REJECTED=n]="REJECTED"})(dr||(dr={}));function PU(e){return new qd(t=>{t(e)})}function OU(e){return new qd((t,r)=>{r(e)})}var qd=class hn{constructor(t){hn.prototype.__init.call(this),hn.prototype.__init2.call(this),hn.prototype.__init3.call(this),hn.prototype.__init4.call(this),this._state=dr.PENDING,this._handlers=[];try{t(this._resolve,this._reject)}catch(r){this._reject(r)}}then(t,r){return new hn((n,i)=>{this._handlers.push([!1,s=>{if(!t)n(s);else try{n(t(s))}catch(o){i(o)}},s=>{if(!r)i(s);else try{n(r(s))}catch(o){i(o)}}]),this._executeHandlers()})}catch(t){return this.then(r=>r,t)}finally(t){return new hn((r,n)=>{let i,s;return this.then(o=>{s=!1,i=o,t&&t()},o=>{s=!0,i=o,t&&t()}).then(()=>{if(s){n(i);return}r(i)})})}__init(){this._resolve=t=>{this._setResult(dr.RESOLVED,t)}}__init2(){this._reject=t=>{this._setResult(dr.REJECTED,t)}}__init3(){this._setResult=(t,r)=>{if(this._state===dr.PENDING){if(zd(r)){r.then(this._resolve,this._reject);return}this._state=t,this._value=r,this._executeHandlers()}}}__init4(){this._executeHandlers=()=>{if(this._state===dr.PENDING)return;const t=this._handlers.slice();this._handlers=[],t.forEach(r=>{r[0]||(this._state===dr.RESOLVED&&r[1](this._value),this._state===dr.REJECTED&&r[2](this._value),r[0]=!0)})}}};function JL(e){const t=Fd(),r={sid:Fr(),init:!0,timestamp:t,started:t,duration:0,status:"ok",errors:0,ignoreDuration:!1,toJSON:()=>YL(r)};return e&&Ga(r,e),r}function Ga(e,t={}){if(t.user&&(!e.ipAddress&&t.user.ip_address&&(e.ipAddress=t.user.ip_address),!e.did&&!t.did&&(e.did=t.user.id||t.user.email||t.user.username)),e.timestamp=t.timestamp||Fd(),t.abnormal_mechanism&&(e.abnormal_mechanism=t.abnormal_mechanism),t.ignoreDuration&&(e.ignoreDuration=t.ignoreDuration),t.sid&&(e.sid=t.sid.length===32?t.sid:Fr()),t.init!==void 0&&(e.init=t.init),!e.did&&t.did&&(e.did=`${t.did}`),typeof t.started=="number"&&(e.started=t.started),e.ignoreDuration)e.duration=void 0;else if(typeof t.duration=="number")e.duration=t.duration;else{const r=e.timestamp-e.started;e.duration=r>=0?r:0}t.release&&(e.release=t.release),t.environment&&(e.environment=t.environment),!e.ipAddress&&t.ipAddress&&(e.ipAddress=t.ipAddress),!e.userAgent&&t.userAgent&&(e.userAgent=t.userAgent),typeof t.errors=="number"&&(e.errors=t.errors),t.status&&(e.status=t.status)}function KL(e,t){let r={};t?r={status:t}:e.status==="ok"&&(r={status:"exited"}),Ga(e,r)}function YL(e){return Ht({sid:`${e.sid}`,init:e.init,started:new Date(e.started*1e3).toISOString(),timestamp:new Date(e.timestamp*1e3).toISOString(),status:e.status,errors:e.errors,did:typeof e.did=="number"||typeof e.did=="string"?`${e.did}`:void 0,duration:e.duration,abnormal_mechanism:e.abnormal_mechanism,attrs:{release:e.release,environment:e.environment,ip_address:e.ipAddress,user_agent:e.userAgent}})}function oa(){return Fr()}function fi(){return Fr().substring(16)}function Za(e,t,r=2){if(!t||typeof t!="object"||r<=0)return t;if(e&&t&&Object.keys(t).length===0)return e;const n={...e};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=Za(n[i],t[i],r-1));return n}var dl="_sentrySpan";function av(e,t){t?pi(e,dl,t):delete e[dl]}function hl(e){return e[dl]}var XL=100,QL=class F0{constructor(){this._notifyingListeners=!1,this._scopeListeners=[],this._eventProcessors=[],this._breadcrumbs=[],this._attachments=[],this._user={},this._tags={},this._extra={},this._contexts={},this._sdkProcessingMetadata={},this._propagationContext={traceId:oa(),spanId:fi()}}clone(){const t=new F0;return t._breadcrumbs=[...this._breadcrumbs],t._tags={...this._tags},t._extra={...this._extra},t._contexts={...this._contexts},this._contexts.flags&&(t._contexts.flags={values:[...this._contexts.flags.values]}),t._user=this._user,t._level=this._level,t._session=this._session,t._transactionName=this._transactionName,t._fingerprint=this._fingerprint,t._eventProcessors=[...this._eventProcessors],t._requestSession=this._requestSession,t._attachments=[...this._attachments],t._sdkProcessingMetadata={...this._sdkProcessingMetadata},t._propagationContext={...this._propagationContext},t._client=this._client,t._lastEventId=this._lastEventId,av(t,hl(this)),t}setClient(t){this._client=t}setLastEventId(t){this._lastEventId=t}getClient(){return this._client}lastEventId(){return this._lastEventId}addScopeListener(t){this._scopeListeners.push(t)}addEventProcessor(t){return this._eventProcessors.push(t),this}setUser(t){return this._user=t||{email:void 0,id:void 0,ip_address:void 0,username:void 0},this._session&&Ga(this._session,{user:t}),this._notifyScopeListeners(),this}getUser(){return this._user}getRequestSession(){return this._requestSession}setRequestSession(t){return this._requestSession=t,this}setTags(t){return this._tags={...this._tags,...t},this._notifyScopeListeners(),this}setTag(t,r){return this._tags={...this._tags,[t]:r},this._notifyScopeListeners(),this}setExtras(t){return this._extra={...this._extra,...t},this._notifyScopeListeners(),this}setExtra(t,r){return this._extra={...this._extra,[t]:r},this._notifyScopeListeners(),this}setFingerprint(t){return this._fingerprint=t,this._notifyScopeListeners(),this}setLevel(t){return this._level=t,this._notifyScopeListeners(),this}setTransactionName(t){return this._transactionName=t,this._notifyScopeListeners(),this}setContext(t,r){return r===null?delete this._contexts[t]:this._contexts[t]=r,this._notifyScopeListeners(),this}setSession(t){return t?this._session=t:delete this._session,this._notifyScopeListeners(),this}getSession(){return this._session}update(t){if(!t)return this;const r=typeof t=="function"?t(this):t,[n,i]=r instanceof Kr?[r.getScopeData(),r.getRequestSession()]:Dd(r)?[t,t.requestSession]:[],{tags:s,extra:o,user:a,contexts:c,level:u,fingerprint:l=[],propagationContext:h}=n||{};return this._tags={...this._tags,...s},this._extra={...this._extra,...o},this._contexts={...this._contexts,...c},a&&Object.keys(a).length&&(this._user=a),u&&(this._level=u),l.length&&(this._fingerprint=l),h&&(this._propagationContext=h),i&&(this._requestSession=i),this}clear(){return this._breadcrumbs=[],this._tags={},this._extra={},this._user={},this._contexts={},this._level=void 0,this._transactionName=void 0,this._fingerprint=void 0,this._requestSession=void 0,this._session=void 0,av(this,void 0),this._attachments=[],this.setPropagationContext({traceId:oa()}),this._notifyScopeListeners(),this}addBreadcrumb(t,r){const n=typeof r=="number"?r:XL;if(n<=0)return this;const i={timestamp:Ud(),...t};return this._breadcrumbs.push(i),this._breadcrumbs.length>n&&(this._breadcrumbs=this._breadcrumbs.slice(-n),this._client&&this._client.recordDroppedEvent("buffer_overflow","log_item")),this._notifyScopeListeners(),this}getLastBreadcrumb(){return this._breadcrumbs[this._breadcrumbs.length-1]}clearBreadcrumbs(){return this._breadcrumbs=[],this._notifyScopeListeners(),this}addAttachment(t){return this._attachments.push(t),this}clearAttachments(){return this._attachments=[],this}getScopeData(){return{breadcrumbs:this._breadcrumbs,attachments:this._attachments,contexts:this._contexts,tags:this._tags,extra:this._extra,user:this._user,level:this._level,fingerprint:this._fingerprint||[],eventProcessors:this._eventProcessors,propagationContext:this._propagationContext,sdkProcessingMetadata:this._sdkProcessingMetadata,transactionName:this._transactionName,span:hl(this)}}setSDKProcessingMetadata(t){return this._sdkProcessingMetadata=Za(this._sdkProcessingMetadata,t,2),this}setPropagationContext(t){return this._propagationContext={spanId:fi(),...t},this}getPropagationContext(){return this._propagationContext}captureException(t,r){const n=r&&r.event_id?r.event_id:Fr();if(!this._client)return bn.warn("No client configured on scope - will not capture exception!"),n;const i=new Error("Sentry syntheticException");return this._client.captureException(t,{originalException:t,syntheticException:i,...r,event_id:n},this),n}captureMessage(t,r,n){const i=n&&n.event_id?n.event_id:Fr();if(!this._client)return bn.warn("No client configured on scope - will not capture message!"),i;const s=new Error(t);return this._client.captureMessage(t,r,{originalException:t,syntheticException:s,...n,event_id:i},this),i}captureEvent(t,r){const n=r&&r.event_id?r.event_id:Fr();return this._client?(this._client.captureEvent(t,{...r,event_id:n},this),n):(bn.warn("No client configured on scope - will not capture event!"),n)}_notifyScopeListeners(){this._notifyingListeners||(this._notifyingListeners=!0,this._scopeListeners.forEach(t=>{t(this)}),this._notifyingListeners=!1)}},Kr=QL;function eN(){return Ha("defaultCurrentScope",()=>new Kr)}function tN(){return Ha("defaultIsolationScope",()=>new Kr)}var rN=class{constructor(e,t){let r;e?r=e:r=new Kr;let n;t?n=t:n=new Kr,this._stack=[{scope:r}],this._isolationScope=n}withScope(e){const t=this._pushScope();let r;try{r=e(t)}catch(n){throw this._popScope(),n}return zd(r)?r.then(n=>(this._popScope(),n),n=>{throw this._popScope(),n}):(this._popScope(),r)}getClient(){return this.getStackTop().client}getScope(){return this.getStackTop().scope}getIsolationScope(){return this._isolationScope}getStackTop(){return this._stack[this._stack.length-1]}_pushScope(){const e=this.getScope().clone();return this._stack.push({client:this.getClient(),scope:e}),e}_popScope(){return this._stack.length<=1?!1:!!this._stack.pop()}};function vi(){const e=Ps(),t=Nd(e);return t.stack=t.stack||new rN(eN(),tN())}function nN(e){return vi().withScope(e)}function iN(e,t){const r=vi();return r.withScope(()=>(r.getStackTop().scope=e,t(e)))}function cv(e){return vi().withScope(()=>e(vi().getIsolationScope()))}function sN(){return{withIsolationScope:cv,withScope:nN,withSetScope:iN,withSetIsolationScope:(e,t)=>cv(t),getCurrentScope:()=>vi().getScope(),getIsolationScope:()=>vi().getIsolationScope()}}function Wa(e){const t=Nd(e);return t.acs?t.acs:sN()}function Xr(){const e=Ps();return Wa(e).getCurrentScope()}function An(){const e=Ps();return Wa(e).getIsolationScope()}function oN(){return Ha("globalScope",()=>new Kr)}function CU(...e){const t=Ps(),r=Wa(t);if(e.length===2){const[n,i]=e;return n?r.withSetScope(n,i):r.withScope(i)}return r.withScope(e[0])}function Os(){return Xr().getClient()}function $U(e){const{traceId:t,spanId:r,parentSpanId:n}=e.getPropagationContext();return Ht({trace_id:t,span_id:r,parent_span_id:n})}var aN="_sentryMetrics";function cN(e){const t=e[aN];if(!t)return;const r={};for(const[,[n,i]]of t)(r[n]||(r[n]=[])).push(Ht(i));return r}var uN="sentry.source",lN="sentry.sample_rate",dN="sentry.op",hN="sentry.origin",xU="sentry.idle_span_finish_reason",MU="sentry.measurement_unit",LU="sentry.measurement_value",NU="sentry.custom_span_name",DU="sentry.profile_id",zU="sentry.exclusive_time";function pN(e){if(e<400&&e>=100)return{code:1};if(e>=400&&e<500)switch(e){case 401:return{code:2,message:"unauthenticated"};case 403:return{code:2,message:"permission_denied"};case 404:return{code:2,message:"not_found"};case 409:return{code:2,message:"already_exists"};case 413:return{code:2,message:"failed_precondition"};case 429:return{code:2,message:"resource_exhausted"};case 499:return{code:2,message:"cancelled"};default:return{code:2,message:"invalid_argument"}}if(e>=500&&e<600)switch(e){case 501:return{code:2,message:"unimplemented"};case 503:return{code:2,message:"unavailable"};case 504:return{code:2,message:"deadline_exceeded"};default:return{code:2,message:"internal_error"}}return{code:2,message:"unknown_error"}}function UU(e,t){e.setAttribute("http.response.status_code",t);const r=pN(t);r.message!=="unknown_error"&&e.setStatus(r)}var fN="sentry-",vN=/^sentry-/;function q0(e){const t=gN(e);if(!t)return;const r=Object.entries(t).reduce((n,[i,s])=>{if(i.match(vN)){const o=i.slice(7);n[o]=s}return n},{});if(Object.keys(r).length>0)return r}function FU(e){if(e)return mN(Object.entries(e).reduce((t,[r,n])=>(n&&(t[`${fN}${r}`]=n),t),{}))}function gN(e){if(!(!e||!sa(e)&&!Array.isArray(e)))return Array.isArray(e)?e.reduce((t,r)=>{const n=uv(r);return Object.entries(n).forEach(([i,s])=>{t[i]=s}),t},{}):uv(e)}function uv(e){return e.split(",").map(t=>t.split("=").map(r=>decodeURIComponent(r.trim()))).reduce((t,[r,n])=>(r&&n&&(t[r]=n),t),{})}function mN(e){if(Object.keys(e).length!==0)return Object.entries(e).reduce((t,[r,n],i)=>{const s=`${encodeURIComponent(r)}=${encodeURIComponent(n)}`,o=i===0?s:`${t},${s}`;return o.length>8192?(Ba&&bn.warn(`Not adding key: ${r} with val: ${n} to baggage header due to exceeding baggage size limits.`),t):o},"")}var _N=new RegExp("^[ \\t]*([0-9a-f]{32})?-?([0-9a-f]{16})?-?([01])?[ \\t]*$");function yN(e){if(!e)return;const t=e.match(_N);if(!t)return;let r;return t[3]==="1"?r=!0:t[3]==="0"&&(r=!1),{traceId:t[1],parentSampled:r,parentSpanId:t[2]}}function qU(e,t){const r=yN(e),n=q0(t);if(!r||!r.traceId)return{traceId:oa(),spanId:fi()};const{traceId:i,parentSpanId:s,parentSampled:o}=r;return{traceId:i,parentSpanId:s,spanId:fi(),sampled:o,dsc:n||{}}}function bN(e=oa(),t=fi(),r){let n="";return r!==void 0&&(n=r?"-1":"-0"),`${e}-${t}${n}`}var lv=!1;function jU(e){const{spanId:t,traceId:r}=e.spanContext(),{data:n,op:i,parent_span_id:s,status:o,origin:a}=Ja(e);return Ht({parent_span_id:s,span_id:t,trace_id:r,data:n,op:i,status:o,origin:a})}function wN(e){const{spanId:t,traceId:r,isRemote:n}=e.spanContext(),i=n?t:Ja(e).parent_span_id,s=n?fi():t;return Ht({parent_span_id:i,span_id:s,trace_id:r})}function HU(e){const{traceId:t,spanId:r}=e.spanContext(),n=jd(e);return bN(t,r,n)}function dv(e){return typeof e=="number"?hv(e):Array.isArray(e)?e[0]+e[1]/1e9:e instanceof Date?hv(e.getTime()):Fd()}function hv(e){return e>9999999999?e/1e3:e}function Ja(e){if(EN(e))return e.getSpanJSON();try{const{spanId:t,traceId:r}=e.spanContext();if(SN(e)){const{attributes:n,startTime:i,name:s,endTime:o,parentSpanId:a,status:c}=e;return Ht({span_id:t,trace_id:r,data:n,description:s,parent_span_id:a,start_timestamp:dv(i),timestamp:dv(o)||void 0,status:kN(c),op:n[dN],origin:n[hN],_metrics_summary:cN(e)})}return{span_id:t,trace_id:r}}catch{return{}}}function SN(e){const t=e;return!!t.attributes&&!!t.startTime&&!!t.name&&!!t.endTime&&!!t.status}function EN(e){return typeof e.getSpanJSON=="function"}function jd(e){const{traceFlags:t}=e.spanContext();return t===1}function kN(e){if(!(!e||e.code===0))return e.code===1?"ok":e.message||"unknown_error"}var wn="_sentryChildSpans",pl="_sentryRootSpan";function BU(e,t){const r=e[pl]||e;pi(t,pl,r),e[wn]?e[wn].add(t):pi(e,wn,new Set([t]))}function VU(e,t){e[wn]&&e[wn].delete(t)}function GU(e){const t=new Set;function r(n){if(!t.has(n)&&jd(n)){t.add(n);const i=n[wn]?Array.from(n[wn]):[];for(const s of i)r(s)}}return r(e),Array.from(t)}function j0(e){return e[pl]||e}function ZU(){const e=Ps(),t=Wa(e);return t.getActiveSpan?t.getActiveSpan():hl(Xr())}function WU(){lv||(x0(()=>{console.warn("[Sentry] Deprecation warning: Returning null from `beforeSendSpan` will be disallowed from SDK version 9.0.0 onwards. The callback will only support mutating spans. To drop certain spans, configure the respective integrations directly.")}),lv=!0)}function IN(e){if(typeof __SENTRY_TRACING__=="boolean"&&!__SENTRY_TRACING__)return!1;const t=Os(),r=e||t&&t.getOptions();return!!r&&(r.enableTracing||"tracesSampleRate"in r||"tracesSampler"in r)}var AN="production",H0="_frozenDsc";function JU(e,t){pi(e,H0,t)}function B0(e,t){const r=t.getOptions(),{publicKey:n}=t.getDsn()||{},i=Ht({environment:r.environment||"production",release:r.release,public_key:n,trace_id:e});return t.emit("createDsc",i),i}function KU(e,t){const r=t.getPropagationContext();return r.dsc||B0(r.traceId,e)}function TN(e){const t=Os();if(!t)return{};const r=j0(e),n=r[H0];if(n)return n;const i=r.spanContext().traceState,s=i&&i.get("sentry.dsc"),o=s&&q0(s);if(o)return o;const a=B0(e.spanContext().traceId,t),c=Ja(r),u=c.data||{},l=u[lN];l!=null&&(a.sample_rate=`${l}`);const h=u[uN],d=c.description;return h!=="url"&&d&&(a.transaction=d),IN()&&(a.sampled=String(jd(r))),t.emit("createDsc",a,r),a}function RN(){const e=typeof WeakSet=="function",t=e?new WeakSet:[];function r(i){if(e)return t.has(i)?!0:(t.add(i),!1);for(let s=0;s<t.length;s++)if(t[s]===i)return!0;return t.push(i),!1}function n(i){if(e)t.delete(i);else for(let s=0;s<t.length;s++)if(t[s]===i){t.splice(s,1);break}}return[r,n]}function Ir(e,t=100,r=1/0){try{return fl("",e,t,r)}catch(n){return{ERROR:`**non-serializable** (${n})`}}}function PN(e,t=3,r=102400){const n=Ir(e,t);return xN(n)>r?PN(e,t-1,r):n}function fl(e,t,r=1/0,n=1/0,i=RN()){const[s,o]=i;if(t==null||["boolean","string"].includes(typeof t)||typeof t=="number"&&Number.isFinite(t))return t;const a=ON(e,t);if(!a.startsWith("[object "))return a;if(t.__sentry_skip_normalization__)return t;const c=typeof t.__sentry_override_normalization_depth__=="number"?t.__sentry_override_normalization_depth__:r;if(c===0)return a.replace("object ","");if(s(t))return"[Circular ~]";const u=t;if(u&&typeof u.toJSON=="function")try{return fl("",u.toJSON(),c-1,n,i)}catch{}const l=Array.isArray(t)?[]:{};let h=0;const d=D0(t);for(const p in d){if(!Object.prototype.hasOwnProperty.call(d,p))continue;if(h>=n){l[p]="[MaxProperties ~]";break}const f=d[p];l[p]=fl(p,f,c-1,n,i),h++}return o(t),l}function ON(e,t){try{if(e==="domain"&&t&&typeof t=="object"&&t._events)return"[Domain]";if(e==="domainEmitter")return"[DomainEmitter]";if(typeof global<"u"&&t===global)return"[Global]";if(typeof window<"u"&&t===window)return"[Window]";if(typeof document<"u"&&t===document)return"[Document]";if(N0(t))return"[VueViewModel]";if(UL(t))return"[SyntheticEvent]";if(typeof t=="number"&&!Number.isFinite(t))return`[${t}]`;if(typeof t=="function")return`[Function: ${xL(t)}]`;if(typeof t=="symbol")return`[${String(t)}]`;if(typeof t=="bigint")return`[BigInt: ${String(t)}]`;const r=CN(t);return/^HTML(\w*)Element$/.test(r)?`[HTMLElement: ${r}]`:`[object ${r}]`}catch(r){return`**non-serializable** (${r})`}}function CN(e){const t=Object.getPrototypeOf(e);return t?t.constructor.name:"null prototype"}function $N(e){return~-encodeURI(e).split(/%..|./).length}function xN(e){return $N(JSON.stringify(e))}function vl(e,t,r,n=0){return new qd((i,s)=>{const o=e[n];if(t===null||typeof o!="function")i(t);else{const a=o({...t},r);RL&&o.id&&a===null&&bn.log(`Event processor "${o.id}" dropped event`),zd(a)?a.then(c=>vl(e,c,r,n+1).then(i)).then(null,s):vl(e,a,r,n+1).then(i).then(null,s)}})}var eo,pv,to;function MN(e){const t=xt._sentryDebugIds;if(!t)return{};const r=Object.keys(t);return to&&r.length===pv||(pv=r.length,to=r.reduce((n,i)=>{eo||(eo={});const s=eo[i];if(s)n[s[0]]=s[1];else{const o=e(i);for(let a=o.length-1;a>=0;a--){const c=o[a],u=c&&c.filename,l=t[i];if(u&&l){n[u]=l,eo[i]=[u,l];break}}}return n},{})),to}function LN(e,t){const{fingerprint:r,span:n,breadcrumbs:i,sdkProcessingMetadata:s}=t;NN(e,t),n&&UN(e,n),FN(e,r),DN(e,i),zN(e,s)}function fv(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,sdkProcessingMetadata:a,breadcrumbs:c,fingerprint:u,eventProcessors:l,attachments:h,propagationContext:d,transactionName:p,span:f}=t;ro(e,"extra",r),ro(e,"tags",n),ro(e,"user",i),ro(e,"contexts",s),e.sdkProcessingMetadata=Za(e.sdkProcessingMetadata,a,2),o&&(e.level=o),p&&(e.transactionName=p),f&&(e.span=f),c.length&&(e.breadcrumbs=[...e.breadcrumbs,...c]),u.length&&(e.fingerprint=[...e.fingerprint,...u]),l.length&&(e.eventProcessors=[...e.eventProcessors,...l]),h.length&&(e.attachments=[...e.attachments,...h]),e.propagationContext={...e.propagationContext,...d}}function ro(e,t,r){e[t]=Za(e[t],r,1)}function NN(e,t){const{extra:r,tags:n,user:i,contexts:s,level:o,transactionName:a}=t,c=Ht(r);c&&Object.keys(c).length&&(e.extra={...c,...e.extra});const u=Ht(n);u&&Object.keys(u).length&&(e.tags={...u,...e.tags});const l=Ht(i);l&&Object.keys(l).length&&(e.user={...l,...e.user});const h=Ht(s);h&&Object.keys(h).length&&(e.contexts={...h,...e.contexts}),o&&(e.level=o),a&&e.type!=="transaction"&&(e.transaction=a)}function DN(e,t){const r=[...e.breadcrumbs||[],...t];e.breadcrumbs=r.length?r:void 0}function zN(e,t){e.sdkProcessingMetadata={...e.sdkProcessingMetadata,...t}}function UN(e,t){e.contexts={trace:wN(t),...e.contexts},e.sdkProcessingMetadata={dynamicSamplingContext:TN(t),...e.sdkProcessingMetadata};const r=j0(t),n=Ja(r).description;n&&!e.transaction&&e.type==="transaction"&&(e.transaction=n)}function FN(e,t){e.fingerprint=e.fingerprint?Array.isArray(e.fingerprint)?e.fingerprint:[e.fingerprint]:[],t&&(e.fingerprint=e.fingerprint.concat(t)),e.fingerprint&&!e.fingerprint.length&&delete e.fingerprint}function YU(e,t,r,n,i,s){const{normalizeDepth:o=3,normalizeMaxBreadth:a=1e3}=e,c={...t,event_id:t.event_id||r.event_id||Fr(),timestamp:t.timestamp||Ud()},u=r.integrations||e.integrations.map(v=>v.name);qN(c,e),BN(c,u),i&&i.emit("applyFrameMetadata",t),t.type===void 0&&jN(c,e.stackParser);const l=GN(n,r.captureContext);r.mechanism&&ZL(c,r.mechanism);const h=i?i.getEventProcessors():[],d=oN().getScopeData();if(s){const v=s.getScopeData();fv(d,v)}if(l){const v=l.getScopeData();fv(d,v)}const p=[...r.attachments||[],...d.attachments];p.length&&(r.attachments=p),LN(c,d);const f=[...h,...d.eventProcessors];return vl(f,c,r).then(v=>(v&&HN(v),typeof o=="number"&&o>0?VN(v,o,a):v))}function qN(e,t){const{environment:r,release:n,dist:i,maxValueLength:s=250}=t;e.environment=e.environment||r||"production",!e.release&&n&&(e.release=n),!e.dist&&i&&(e.dist=i),e.message&&(e.message=os(e.message,s));const o=e.exception&&e.exception.values&&e.exception.values[0];o&&o.value&&(o.value=os(o.value,s));const a=e.request;a&&a.url&&(a.url=os(a.url,s))}function jN(e,t){const r=MN(t);try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{r&&i.filename&&(i.debug_id=r[i.filename])})})}catch{}}function HN(e){const t={};try{e.exception.values.forEach(n=>{n.stacktrace.frames.forEach(i=>{i.debug_id&&(i.abs_path?t[i.abs_path]=i.debug_id:i.filename&&(t[i.filename]=i.debug_id),delete i.debug_id)})})}catch{}if(Object.keys(t).length===0)return;e.debug_meta=e.debug_meta||{},e.debug_meta.images=e.debug_meta.images||[];const r=e.debug_meta.images;Object.entries(t).forEach(([n,i])=>{r.push({type:"sourcemap",code_file:n,debug_id:i})})}function BN(e,t){t.length>0&&(e.sdk=e.sdk||{},e.sdk.integrations=[...e.sdk.integrations||[],...t])}function VN(e,t,r){if(!e)return null;const n={...e,...e.breadcrumbs&&{breadcrumbs:e.breadcrumbs.map(i=>({...i,...i.data&&{data:Ir(i.data,t,r)}}))},...e.user&&{user:Ir(e.user,t,r)},...e.contexts&&{contexts:Ir(e.contexts,t,r)},...e.extra&&{extra:Ir(e.extra,t,r)}};return e.contexts&&e.contexts.trace&&n.contexts&&(n.contexts.trace=e.contexts.trace,e.contexts.trace.data&&(n.contexts.trace.data=Ir(e.contexts.trace.data,t,r))),e.spans&&(n.spans=e.spans.map(i=>({...i,...i.data&&{data:Ir(i.data,t,r)}}))),e.contexts&&e.contexts.flags&&n.contexts&&(n.contexts.flags=Ir(e.contexts.flags,3,r)),n}function GN(e,t){if(!t)return e;const r=e?e.clone():new Kr;return r.update(t),r}function ZN(e){if(e)return WN(e)?{captureContext:e}:KN(e)?{captureContext:e}:e}function WN(e){return e instanceof Kr||typeof e=="function"}var JN=["user","level","extra","contexts","tags","fingerprint","requestSession","propagationContext"];function KN(e){return Object.keys(e).some(t=>JN.includes(t))}function YN(e,t){return Xr().captureException(e,ZN(t))}function XU(e,t){const r=typeof t=="string"?t:void 0,n=typeof t!="string"?{captureContext:t}:void 0;return Xr().captureMessage(e,r,n)}function QU(e,t){return Xr().captureEvent(e,t)}function eF(e,t){An().setContext(e,t)}function tF(e,t){An().setTag(e,t)}function rF(e){An().setUser(e)}function nF(){const e=Os();return!!e&&e.getOptions().enabled!==!1&&!!e.getTransport()}function iF(e){An().addEventProcessor(e)}function sF(e){const t=Os(),r=An(),n=Xr(),{release:i,environment:s=AN}=t&&t.getOptions()||{},{userAgent:o}=xt.navigator||{},a=JL({release:i,environment:s,user:n.getUser()||r.getUser(),...o&&{userAgent:o},...e}),c=r.getSession();return c&&c.status==="ok"&&Ga(c,{status:"exited"}),V0(),r.setSession(a),n.setSession(a),a}function V0(){const e=An(),t=Xr(),r=t.getSession()||e.getSession();r&&KL(r),G0(),e.setSession(),t.setSession()}function G0(){const e=An(),t=Xr(),r=Os(),n=t.getSession()||e.getSession();n&&r&&r.captureSession(n)}function oF(e=!1){if(e){V0();return}G0()}function XN(e){try{if(typeof e!="object"||e===null)return;const t=e.normalized;return kR(t)?t:void 0}catch{return}}function aF(e,t){try{if(!Rs()||$d(e)||xd(e)||Md(e))return!1;const r=XN(e)??KR(e),n=WR(r);return n!=="mcpjam"?!1:(Z0(e,{...t,extra:{...t.extra??{},slug:r.slug,origin:n}}),!0)}catch{return!1}}var QN=C0();function eD(e){if(e instanceof Error)return e;try{return new Error(typeof e=="string"?e:JSON.stringify(e))}catch{return new Error(String(e))}}function Z0(e,t){if($d(e)||xd(e)||Md(e))return;const r=TL(eD(e)),n=O0(r.message);if(n&&t.queryBackend&&(n.convex_backend=t.queryBackend),n&&QN(n.convex_backend,n.request_id))return;const i=n&&typeof window<"u"?ul(window.location.href):void 0,s=AL.getState(),o=s.recoveryId&&Date.now()-s.recoveryAt<3e5?{auth_recovery_id:s.recoveryId}:{};try{YN(r,{level:t.level??"error",tags:{...t.tags??{},source:t.source,...n,...o},...t.fingerprint?{fingerprint:t.fingerprint}:{},...n?{extra:{boundary:t.extra?.boundary,componentStack:t.extra?.componentStack,page_location:i}}:t.extra?{extra:t.extra}:{}})}catch{}try{Rs()&&!Od()&&IM.captureException(r,{source:t.source,level:t.level??"error",...n?{...n,page_location:i}:t.extra??{}})}catch{}}function cF(e,t,r){Z0(e,{source:r?`react_boundary:${r}`:"react_boundary",extra:{componentStack:t?.componentStack??void 0,boundary:r??"unnamed"}})}export{$U as $,mD as $i,qO as $n,_z as $r,$0 as $t,Ja as A,FD as Ai,eU as An,Az as Ar,qL as At,DU as B,jD as Bi,Jz as Bn,kR as Br,sa as Bt,j0 as C,Or as Ci,tU as Cn,Rz as Cr,BL as Ct,WU as D,xD as Di,I0 as Dn,Tz as Dr,yU as Dt,VU as E,CD as Ei,Rs as En,Ne as Er,os as Et,qU as F,LD as Fi,Kz as Fn,Ez as Fr,NL as Ft,dN as G,JI as Gi,Zz as Gn,mm as Gr,xL as Gt,xU as H,MD as Hi,Bz as Hn,WR as Hr,Ps as Ht,fN as I,Dg as Ii,VC as In,Sz as Ir,Va as It,uN as J,OD as Ji,qz as Jn,Qt as Jr,x0 as Jt,hN as K,au as Ki,_C as Kn,aR as Kr,dU as Kt,FU as L,Co as Li,e_ as Ln,kz as Lr,LL as Lt,jU as M,XI as Mi,Qz as Mn,Iu as Mr,vU as Mt,_N as N,UD as Ni,OM as Nn,Iz as Nr,ML as Nt,jd as O,Dt as Oi,KM as On,wa as Or,_U as Ot,bN as P,zD as Pi,IM as Pn,eP as Pr,pU as Pt,An as Q,Rb as Qi,op as Qn,mz as Qr,xt as Qt,UU as R,vn as Ri,EC as Rn,wz as Rr,Dd as Rt,ZU as S,yI as Si,ol as Sn,Pa as Sr,EU as St,kN as T,$D as Ti,Od as Tn,_P as Tr,wU as Tt,MU as U,Le as Ui,Vz as Un,hR as Ur,CL as Ut,NU as V,uu as Vi,dp as Vn,XR as Vr,zd as Vt,LU as W,DD as Wi,Gz as Wn,bz as Wr,hU as Wt,Os as X,PD as Xi,ap as Xn,Dr as Xr,rv as Xt,cN as Y,dk as Yi,od as Yn,Bl as Yr,bn as Yt,Xr as Z,ED as Zi,cp as Zn,gz as Zr,Ba as Zt,JU as _,sD as _a,JD as _i,ta as _n,Pz as _r,Fd as _t,QU as a,dD as aa,lz as ai,xd as an,Lz as ar,oa as at,IN as b,pT as bi,eL as bn,Ca as br,kU as bt,oF as c,nb as ca,DT as ci,aU as cn,np as cr,OU as ct,tF as d,uD as da,az as di,kL as dn,xz as dr,TU as dt,hb as ea,BT as ei,RL as en,DO as er,CU as et,rF as f,cD as fa,NT as fi,oU as fn,Cz as fr,RU as ft,PN as g,iD as ga,YD as gi,ra as gn,tO as gr,Ud as gt,Ir as h,tb as ha,KD as hi,sU as hn,Oz as hr,IU as ht,iF as i,db as ia,vz as ii,$d as in,Nz as ir,fi as it,HU as j,ND as ji,Xz as jn,oP as jr,fU as jt,dv as k,an as ki,nU as kn,fP as kr,mU as kt,nF as l,lb as la,uz as li,IL as ln,gO as lr,PU as lt,YU as m,aD as ma,XD as mi,iU as mn,sO as mr,Fr as mt,Z0 as n,pb as na,VT as ni,lU as nn,Dz as nr,hl as nt,YN as o,lD as oa,dz as oi,Md as on,TO as or,Ga as ot,sF as p,hD as pa,_a as pi,Xf as pn,uO as pr,AU as pt,lN as q,cI as qi,jz as qn,zh as qr,tv as qt,aF as r,Xc as ra,fz as ri,TL as rn,NO as rr,av as rt,XU as s,pD as sa,hz as si,AL as sn,Rr as sr,qd as st,cF as t,fD as ta,pz as ti,uU as tn,Uz as tr,Wa as tt,eF as u,ub as ua,cz as ui,cU as un,$z as ur,ZL as ut,KU as v,oD as va,vu as vi,nL as vn,Um as vr,pi as vt,GU as w,qD as wi,rU as wn,Vr as wr,bU as wt,BU as x,qs as xi,MM as xn,xa as xr,SU as xt,TN as y,hT as yi,rL as yn,Oa as yr,Ht as yt,zU as z,Oh as zi,Wz as zn,KR as zr,gU as zt};
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=error-reporting-CORfsjyM.js.map
|