@rulemetric/local 0.7.41 → 0.7.42

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.
@@ -709,7 +709,7 @@ Resources:`;for(const Ga of Aa){if(!Ga||typeof Ga!="string")throw new Error(`@su
709
709
  ${za}`}class WebAuthnError extends Error{constructor({message:$,code:ts,cause:is,name:cs}){var Kr;super($,{cause:is}),this.__isWebAuthnError=!0,this.name=(Kr=cs??(is instanceof Error?is.name:void 0))!==null&&Kr!==void 0?Kr:"Unknown Error",this.code=ts}}class WebAuthnUnknownError extends WebAuthnError{constructor($,ts){super({code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:ts,message:$}),this.name="WebAuthnUnknownError",this.originalError=ts}}function identifyRegistrationError({error:es,options:$}){var ts,is,cs;const{publicKey:Kr}=$;if(!Kr)throw Error("options was missing required publicKey property");if(es.name==="AbortError"){if($.signal instanceof AbortSignal)return new WebAuthnError({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:es})}else if(es.name==="ConstraintError"){if(((ts=Kr.authenticatorSelection)===null||ts===void 0?void 0:ts.requireResidentKey)===!0)return new WebAuthnError({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:es});if($.mediation==="conditional"&&((is=Kr.authenticatorSelection)===null||is===void 0?void 0:is.userVerification)==="required")return new WebAuthnError({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:es});if(((cs=Kr.authenticatorSelection)===null||cs===void 0?void 0:cs.userVerification)==="required")return new WebAuthnError({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:es})}else{if(es.name==="InvalidStateError")return new WebAuthnError({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:es});if(es.name==="NotAllowedError")return new WebAuthnError({message:es.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es});if(es.name==="NotSupportedError")return Kr.pubKeyCredParams.filter(Na=>Na.type==="public-key").length===0?new WebAuthnError({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:es}):new WebAuthnError({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:es});if(es.name==="SecurityError"){const Xr=window.location.hostname;if(isValidDomain(Xr)){if(Kr.rp.id!==Xr)return new WebAuthnError({message:`The RP ID "${Kr.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:es})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:es})}else if(es.name==="TypeError"){if(Kr.user.id.byteLength<1||Kr.user.id.byteLength>64)return new WebAuthnError({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:es})}else if(es.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:es})}return new WebAuthnError({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es})}function identifyAuthenticationError({error:es,options:$}){const{publicKey:ts}=$;if(!ts)throw Error("options was missing required publicKey property");if(es.name==="AbortError"){if($.signal instanceof AbortSignal)return new WebAuthnError({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:es})}else{if(es.name==="NotAllowedError")return new WebAuthnError({message:es.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es});if(es.name==="SecurityError"){const is=window.location.hostname;if(isValidDomain(is)){if(ts.rpId!==is)return new WebAuthnError({message:`The RP ID "${ts.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:es})}else return new WebAuthnError({message:`${window.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:es})}else if(es.name==="UnknownError")return new WebAuthnError({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:es})}return new WebAuthnError({message:"a Non-Webauthn related error has occurred",code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:es})}class WebAuthnAbortService{createNewAbortSignal(){if(this.controller){const ts=new Error("Cancelling existing WebAuthn API call for new one");ts.name="AbortError",this.controller.abort(ts)}const $=new AbortController;return this.controller=$,$.signal}cancelCeremony(){if(this.controller){const $=new Error("Manually cancelling existing WebAuthn API call");$.name="AbortError",this.controller.abort($),this.controller=void 0}}}const webAuthnAbortService=new WebAuthnAbortService;function deserializeCredentialCreationOptions(es){if(!es)throw new Error("Credential creation options are required");if(typeof PublicKeyCredential<"u"&&"parseCreationOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON=="function")return PublicKeyCredential.parseCreationOptionsFromJSON(es);const{challenge:$,user:ts,excludeCredentials:is}=es,cs=__rest(es,["challenge","user","excludeCredentials"]),Kr=base64UrlToUint8Array($).buffer,Xr=Object.assign(Object.assign({},ts),{id:base64UrlToUint8Array(ts.id).buffer}),Na=Object.assign(Object.assign({},cs),{challenge:Kr,user:Xr});if(is&&is.length>0){Na.excludeCredentials=new Array(is.length);for(let Ca=0;Ca<is.length;Ca++){const Aa=is[Ca];Na.excludeCredentials[Ca]=Object.assign(Object.assign({},Aa),{id:base64UrlToUint8Array(Aa.id).buffer,type:Aa.type||"public-key",transports:Aa.transports})}}return Na}function deserializeCredentialRequestOptions(es){if(!es)throw new Error("Credential request options are required");if(typeof PublicKeyCredential<"u"&&"parseRequestOptionsFromJSON"in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON=="function")return PublicKeyCredential.parseRequestOptionsFromJSON(es);const{challenge:$,allowCredentials:ts}=es,is=__rest(es,["challenge","allowCredentials"]),cs=base64UrlToUint8Array($).buffer,Kr=Object.assign(Object.assign({},is),{challenge:cs});if(ts&&ts.length>0){Kr.allowCredentials=new Array(ts.length);for(let Xr=0;Xr<ts.length;Xr++){const Na=ts[Xr];Kr.allowCredentials[Xr]=Object.assign(Object.assign({},Na),{id:base64UrlToUint8Array(Na.id).buffer,type:Na.type||"public-key",transports:Na.transports})}}return Kr}function serializeCredentialCreationResponse(es){var $;if("toJSON"in es&&typeof es.toJSON=="function")return es.toJSON();const ts=es;return{id:es.id,rawId:es.id,response:{attestationObject:bytesToBase64URL(new Uint8Array(es.response.attestationObject)),clientDataJSON:bytesToBase64URL(new Uint8Array(es.response.clientDataJSON))},type:"public-key",clientExtensionResults:es.getClientExtensionResults(),authenticatorAttachment:($=ts.authenticatorAttachment)!==null&&$!==void 0?$:void 0}}function serializeCredentialRequestResponse(es){var $;if("toJSON"in es&&typeof es.toJSON=="function")return es.toJSON();const ts=es,is=es.getClientExtensionResults(),cs=es.response;return{id:es.id,rawId:es.id,response:{authenticatorData:bytesToBase64URL(new Uint8Array(cs.authenticatorData)),clientDataJSON:bytesToBase64URL(new Uint8Array(cs.clientDataJSON)),signature:bytesToBase64URL(new Uint8Array(cs.signature)),userHandle:cs.userHandle?bytesToBase64URL(new Uint8Array(cs.userHandle)):void 0},type:"public-key",clientExtensionResults:is,authenticatorAttachment:($=ts.authenticatorAttachment)!==null&&$!==void 0?$:void 0}}function isValidDomain(es){return es==="localhost"||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(es)}function browserSupportsWebAuthn(){var es,$;return!!(isBrowser()&&"PublicKeyCredential"in window&&window.PublicKeyCredential&&"credentials"in navigator&&typeof((es=navigator==null?void 0:navigator.credentials)===null||es===void 0?void 0:es.create)=="function"&&typeof(($=navigator==null?void 0:navigator.credentials)===null||$===void 0?void 0:$.get)=="function")}async function createCredential(es){try{const $=await navigator.credentials.create(es);return $?$ instanceof PublicKeyCredential?{data:$,error:null}:{data:null,error:new WebAuthnUnknownError("Browser returned unexpected credential type",$)}:{data:null,error:new WebAuthnUnknownError("Empty credential response",$)}}catch($){return{data:null,error:identifyRegistrationError({error:$,options:es})}}}async function getCredential(es){try{const $=await navigator.credentials.get(es);return $?$ instanceof PublicKeyCredential?{data:$,error:null}:{data:null,error:new WebAuthnUnknownError("Browser returned unexpected credential type",$)}:{data:null,error:new WebAuthnUnknownError("Empty credential response",$)}}catch($){return{data:null,error:identifyAuthenticationError({error:$,options:es})}}}const DEFAULT_CREATION_OPTIONS={hints:["security-key"],authenticatorSelection:{authenticatorAttachment:"cross-platform",requireResidentKey:!1,userVerification:"preferred",residentKey:"discouraged"},attestation:"direct"},DEFAULT_REQUEST_OPTIONS={userVerification:"preferred",hints:["security-key"],attestation:"direct"};function deepMerge(...es){const $=cs=>cs!==null&&typeof cs=="object"&&!Array.isArray(cs),ts=cs=>cs instanceof ArrayBuffer||ArrayBuffer.isView(cs),is={};for(const cs of es)if(cs)for(const Kr in cs){const Xr=cs[Kr];if(Xr!==void 0)if(Array.isArray(Xr))is[Kr]=Xr;else if(ts(Xr))is[Kr]=Xr;else if($(Xr)){const Na=is[Kr];$(Na)?is[Kr]=deepMerge(Na,Xr):is[Kr]=deepMerge(Xr)}else is[Kr]=Xr}return is}function mergeCredentialCreationOptions(es,$){return deepMerge(DEFAULT_CREATION_OPTIONS,es,$||{})}function mergeCredentialRequestOptions(es,$){return deepMerge(DEFAULT_REQUEST_OPTIONS,es,$||{})}class WebAuthnApi{constructor($){this.client=$,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll($){return this.client.mfa.enroll(Object.assign(Object.assign({},$),{factorType:"webauthn"}))}async _challenge({factorId:$,webauthn:ts,friendlyName:is,signal:cs},Kr){var Xr;try{const{data:Na,error:Ca}=await this.client.mfa.challenge({factorId:$,webauthn:ts});if(!Na)return{data:null,error:Ca};const Aa=cs??webAuthnAbortService.createNewAbortSignal();if(Na.webauthn.type==="create"){const{user:Ia}=Na.webauthn.credential_options.publicKey;if(!Ia.name){const Ma=is;if(Ma)Ia.name=`${Ia.id}:${Ma}`;else{const La=(await this.client.getUser()).data.user,Fa=((Xr=La==null?void 0:La.user_metadata)===null||Xr===void 0?void 0:Xr.name)||(La==null?void 0:La.email)||(La==null?void 0:La.id)||"User";Ia.name=`${Ia.id}:${Fa}`}}Ia.displayName||(Ia.displayName=Ia.name)}switch(Na.webauthn.type){case"create":{const Ia=mergeCredentialCreationOptions(Na.webauthn.credential_options.publicKey,Kr==null?void 0:Kr.create),{data:Ma,error:Pa}=await createCredential({publicKey:Ia,signal:Aa});return Ma?{data:{factorId:$,challengeId:Na.id,webauthn:{type:Na.webauthn.type,credential_response:Ma}},error:null}:{data:null,error:Pa}}case"request":{const Ia=mergeCredentialRequestOptions(Na.webauthn.credential_options.publicKey,Kr==null?void 0:Kr.request),{data:Ma,error:Pa}=await getCredential(Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:Ia,signal:Aa}));return Ma?{data:{factorId:$,challengeId:Na.id,webauthn:{type:Na.webauthn.type,credential_response:Ma}},error:null}:{data:null,error:Pa}}}}catch(Na){return isAuthError(Na)?{data:null,error:Na}:{data:null,error:new AuthUnknownError("Unexpected error in challenge",Na)}}}async _verify({challengeId:$,factorId:ts,webauthn:is}){return this.client.mfa.verify({factorId:ts,challengeId:$,webauthn:is})}async _authenticate({factorId:$,webauthn:{rpId:ts=typeof window<"u"?window.location.hostname:void 0,rpOrigins:is=typeof window<"u"?[window.location.origin]:void 0,signal:cs}={}},Kr){if(!ts)return{data:null,error:new AuthError("rpId is required for WebAuthn authentication")};try{if(!browserSupportsWebAuthn())return{data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)};const{data:Xr,error:Na}=await this.challenge({factorId:$,webauthn:{rpId:ts,rpOrigins:is},signal:cs},{request:Kr});if(!Xr)return{data:null,error:Na};const{webauthn:Ca}=Xr;return this._verify({factorId:$,challengeId:Xr.challengeId,webauthn:{type:Ca.type,rpId:ts,rpOrigins:is,credential_response:Ca.credential_response}})}catch(Xr){return isAuthError(Xr)?{data:null,error:Xr}:{data:null,error:new AuthUnknownError("Unexpected error in authenticate",Xr)}}}async _register({friendlyName:$,webauthn:{rpId:ts=typeof window<"u"?window.location.hostname:void 0,rpOrigins:is=typeof window<"u"?[window.location.origin]:void 0,signal:cs}={}},Kr){if(!ts)return{data:null,error:new AuthError("rpId is required for WebAuthn registration")};try{if(!browserSupportsWebAuthn())return{data:null,error:new AuthUnknownError("Browser does not support WebAuthn",null)};const{data:Xr,error:Na}=await this._enroll({friendlyName:$});if(!Xr)return await this.client.mfa.listFactors().then(Ia=>{var Ma;return(Ma=Ia.data)===null||Ma===void 0?void 0:Ma.all.find(Pa=>Pa.factor_type==="webauthn"&&Pa.friendly_name===$&&Pa.status!=="unverified")}).then(Ia=>Ia?this.client.mfa.unenroll({factorId:Ia==null?void 0:Ia.id}):void 0),{data:null,error:Na};const{data:Ca,error:Aa}=await this._challenge({factorId:Xr.id,friendlyName:Xr.friendly_name,webauthn:{rpId:ts,rpOrigins:is},signal:cs},{create:Kr});return Ca?this._verify({factorId:Xr.id,challengeId:Ca.challengeId,webauthn:{rpId:ts,rpOrigins:is,type:Ca.webauthn.type,credential_response:Ca.webauthn.credential_response}}):{data:null,error:Aa}}catch(Xr){return isAuthError(Xr)?{data:null,error:Xr}:{data:null,error:new AuthUnknownError("Unexpected error in register",Xr)}}}}polyfillGlobalThis();const DEFAULT_OPTIONS={url:GOTRUE_URL,storageKey:STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:DEFAULT_HEADERS$1,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:1e4};async function lockNoOp(es,$,ts){return await ts()}const GLOBAL_JWKS={};class GoTrueClient{get jwks(){var $,ts;return(ts=($=GLOBAL_JWKS[this.storageKey])===null||$===void 0?void 0:$.jwks)!==null&&ts!==void 0?ts:{keys:[]}}set jwks($){GLOBAL_JWKS[this.storageKey]=Object.assign(Object.assign({},GLOBAL_JWKS[this.storageKey]),{jwks:$})}get jwks_cached_at(){var $,ts;return(ts=($=GLOBAL_JWKS[this.storageKey])===null||$===void 0?void 0:$.cachedAt)!==null&&ts!==void 0?ts:Number.MIN_SAFE_INTEGER}set jwks_cached_at($){GLOBAL_JWKS[this.storageKey]=Object.assign(Object.assign({},GLOBAL_JWKS[this.storageKey]),{cachedAt:$})}constructor($){var ts,is,cs;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;const Kr=Object.assign(Object.assign({},DEFAULT_OPTIONS),$);if(this.storageKey=Kr.storageKey,this.instanceID=(ts=GoTrueClient.nextInstanceID[this.storageKey])!==null&&ts!==void 0?ts:0,GoTrueClient.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!Kr.debug,typeof Kr.debug=="function"&&(this.logger=Kr.debug),this.instanceID>0&&isBrowser()){const Xr=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(Xr),this.logDebugMessages&&console.trace(Xr)}if(this.persistSession=Kr.persistSession,this.autoRefreshToken=Kr.autoRefreshToken,this.admin=new GoTrueAdminApi({url:Kr.url,headers:Kr.headers,fetch:Kr.fetch}),this.url=Kr.url,this.headers=Kr.headers,this.fetch=resolveFetch$1(Kr.fetch),this.lock=Kr.lock||lockNoOp,this.detectSessionInUrl=Kr.detectSessionInUrl,this.flowType=Kr.flowType,this.hasCustomAuthorizationHeader=Kr.hasCustomAuthorizationHeader,this.throwOnError=Kr.throwOnError,this.lockAcquireTimeout=Kr.lockAcquireTimeout,Kr.lock?this.lock=Kr.lock:this.persistSession&&isBrowser()&&(!((is=globalThis==null?void 0:globalThis.navigator)===null||is===void 0)&&is.locks)?this.lock=navigatorLock:this.lock=lockNoOp,this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=Number.MIN_SAFE_INTEGER),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new WebAuthnApi(this)},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.persistSession?(Kr.storage?this.storage=Kr.storage:supportsLocalStorage()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=memoryLocalStorageAdapter(this.memoryStorage)),Kr.userStorage&&(this.userStorage=Kr.userStorage)):(this.memoryStorage={},this.storage=memoryLocalStorageAdapter(this.memoryStorage)),isBrowser()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(Xr){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",Xr)}(cs=this.broadcastChannel)===null||cs===void 0||cs.addEventListener("message",async Xr=>{this._debug("received broadcast notification from other tab or client",Xr);try{await this._notifyAllSubscribers(Xr.data.event,Xr.data.session,!1)}catch(Na){this._debug("#broadcastChannel","error",Na)}})}this.initialize().catch(Xr=>{this._debug("#initialize()","error",Xr)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult($){if(this.throwOnError&&$&&$.error)throw $.error;return $}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${version$1}) ${new Date().toISOString()}`}_debug(...$){return this.logDebugMessages&&this.logger(this._logPrefix(),...$),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var $;try{let ts={},is="none";if(isBrowser()&&(ts=parseParametersFromURL(window.location.href),this._isImplicitGrantCallback(ts)?is="implicit":await this._isPKCECallback(ts)&&(is="pkce")),isBrowser()&&this.detectSessionInUrl&&is!=="none"){const{data:cs,error:Kr}=await this._getSessionFromURL(ts,is);if(Kr){if(this._debug("#_initialize()","error detecting session from URL",Kr),isAuthImplicitGrantRedirectError(Kr)){const Ca=($=Kr.details)===null||$===void 0?void 0:$.code;if(Ca==="identity_already_exists"||Ca==="identity_not_found"||Ca==="single_identity_not_deletable")return{error:Kr}}return{error:Kr}}const{session:Xr,redirectType:Na}=cs;return this._debug("#_initialize()","detected session in URL",Xr,"redirect type",Na),await this._saveSession(Xr),setTimeout(async()=>{Na==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",Xr):await this._notifyAllSubscribers("SIGNED_IN",Xr)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(ts){return isAuthError(ts)?this._returnResult({error:ts}):this._returnResult({error:new AuthUnknownError("Unexpected error during initialization",ts)})}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously($){var ts,is,cs;try{const Kr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(is=(ts=$==null?void 0:$.options)===null||ts===void 0?void 0:ts.data)!==null&&is!==void 0?is:{},gotrue_meta_security:{captcha_token:(cs=$==null?void 0:$.options)===null||cs===void 0?void 0:cs.captchaToken}},xform:_sessionResponse}),{data:Xr,error:Na}=Kr;if(Na||!Xr)return this._returnResult({data:{user:null,session:null},error:Na});const Ca=Xr.session,Aa=Xr.user;return Xr.session&&(await this._saveSession(Xr.session),await this._notifyAllSubscribers("SIGNED_IN",Ca)),this._returnResult({data:{user:Aa,session:Ca},error:null})}catch(Kr){if(isAuthError(Kr))return this._returnResult({data:{user:null,session:null},error:Kr});throw Kr}}async signUp($){var ts,is,cs;try{let Kr;if("email"in $){const{email:Ia,password:Ma,options:Pa}=$;let La=null,Fa=null;this.flowType==="pkce"&&([La,Fa]=await getCodeChallengeAndMethod(this.storage,this.storageKey)),Kr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:Pa==null?void 0:Pa.emailRedirectTo,body:{email:Ia,password:Ma,data:(ts=Pa==null?void 0:Pa.data)!==null&&ts!==void 0?ts:{},gotrue_meta_security:{captcha_token:Pa==null?void 0:Pa.captchaToken},code_challenge:La,code_challenge_method:Fa},xform:_sessionResponse})}else if("phone"in $){const{phone:Ia,password:Ma,options:Pa}=$;Kr=await _request(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:Ia,password:Ma,data:(is=Pa==null?void 0:Pa.data)!==null&&is!==void 0?is:{},channel:(cs=Pa==null?void 0:Pa.channel)!==null&&cs!==void 0?cs:"sms",gotrue_meta_security:{captcha_token:Pa==null?void 0:Pa.captchaToken}},xform:_sessionResponse})}else throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");const{data:Xr,error:Na}=Kr;if(Na||!Xr)return await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),this._returnResult({data:{user:null,session:null},error:Na});const Ca=Xr.session,Aa=Xr.user;return Xr.session&&(await this._saveSession(Xr.session),await this._notifyAllSubscribers("SIGNED_IN",Ca)),this._returnResult({data:{user:Aa,session:Ca},error:null})}catch(Kr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Kr))return this._returnResult({data:{user:null,session:null},error:Kr});throw Kr}}async signInWithPassword($){try{let ts;if("email"in $){const{email:Kr,password:Xr,options:Na}=$;ts=await _request(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:Kr,password:Xr,gotrue_meta_security:{captcha_token:Na==null?void 0:Na.captchaToken}},xform:_sessionResponsePassword})}else if("phone"in $){const{phone:Kr,password:Xr,options:Na}=$;ts=await _request(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:Kr,password:Xr,gotrue_meta_security:{captcha_token:Na==null?void 0:Na.captchaToken}},xform:_sessionResponsePassword})}else throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a password");const{data:is,error:cs}=ts;if(cs)return this._returnResult({data:{user:null,session:null},error:cs});if(!is||!is.session||!is.user){const Kr=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Kr})}return is.session&&(await this._saveSession(is.session),await this._notifyAllSubscribers("SIGNED_IN",is.session)),this._returnResult({data:Object.assign({user:is.user,session:is.session},is.weak_password?{weakPassword:is.weak_password}:null),error:cs})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async signInWithOAuth($){var ts,is,cs,Kr;return await this._handleProviderSignIn($.provider,{redirectTo:(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo,scopes:(is=$.options)===null||is===void 0?void 0:is.scopes,queryParams:(cs=$.options)===null||cs===void 0?void 0:cs.queryParams,skipBrowserRedirect:(Kr=$.options)===null||Kr===void 0?void 0:Kr.skipBrowserRedirect})}async exchangeCodeForSession($){return await this.initializePromise,this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession($))}async signInWithWeb3($){const{chain:ts}=$;switch(ts){case"ethereum":return await this.signInWithEthereum($);case"solana":return await this.signInWithSolana($);default:throw new Error(`@supabase/auth-js: Unsupported chain "${ts}"`)}}async signInWithEthereum($){var ts,is,cs,Kr,Xr,Na,Ca,Aa,Ia,Ma,Pa;let La,Fa;if("message"in $)La=$.message,Fa=$.signature;else{const{chain:Ba,wallet:qa,statement:za,options:Va}=$;let Ga;if(isBrowser())if(typeof qa=="object")Ga=qa;else{const sl=window;if("ethereum"in sl&&typeof sl.ethereum=="object"&&"request"in sl.ethereum&&typeof sl.ethereum.request=="function")Ga=sl.ethereum;else throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.")}else{if(typeof qa!="object"||!(Va!=null&&Va.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");Ga=qa}const Za=new URL((ts=Va==null?void 0:Va.url)!==null&&ts!==void 0?ts:window.location.href),Qa=await Ga.request({method:"eth_requestAccounts"}).then(sl=>sl).catch(()=>{throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid")});if(!Qa||Qa.length===0)throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected.");const Xa=getAddress(Qa[0]);let Ja=(is=Va==null?void 0:Va.signInWithEthereum)===null||is===void 0?void 0:is.chainId;if(!Ja){const sl=await Ga.request({method:"eth_chainId"});Ja=fromHex(sl)}const tl={domain:Za.host,address:Xa,statement:za,uri:Za.href,version:"1",chainId:Ja,nonce:(cs=Va==null?void 0:Va.signInWithEthereum)===null||cs===void 0?void 0:cs.nonce,issuedAt:(Xr=(Kr=Va==null?void 0:Va.signInWithEthereum)===null||Kr===void 0?void 0:Kr.issuedAt)!==null&&Xr!==void 0?Xr:new Date,expirationTime:(Na=Va==null?void 0:Va.signInWithEthereum)===null||Na===void 0?void 0:Na.expirationTime,notBefore:(Ca=Va==null?void 0:Va.signInWithEthereum)===null||Ca===void 0?void 0:Ca.notBefore,requestId:(Aa=Va==null?void 0:Va.signInWithEthereum)===null||Aa===void 0?void 0:Aa.requestId,resources:(Ia=Va==null?void 0:Va.signInWithEthereum)===null||Ia===void 0?void 0:Ia.resources};La=createSiweMessage(tl),Fa=await Ga.request({method:"personal_sign",params:[toHex(La),Xa]})}try{const{data:Ba,error:qa}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"ethereum",message:La,signature:Fa},!((Ma=$.options)===null||Ma===void 0)&&Ma.captchaToken?{gotrue_meta_security:{captcha_token:(Pa=$.options)===null||Pa===void 0?void 0:Pa.captchaToken}}:null),xform:_sessionResponse});if(qa)throw qa;if(!Ba||!Ba.session||!Ba.user){const za=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:za})}return Ba.session&&(await this._saveSession(Ba.session),await this._notifyAllSubscribers("SIGNED_IN",Ba.session)),this._returnResult({data:Object.assign({},Ba),error:qa})}catch(Ba){if(isAuthError(Ba))return this._returnResult({data:{user:null,session:null},error:Ba});throw Ba}}async signInWithSolana($){var ts,is,cs,Kr,Xr,Na,Ca,Aa,Ia,Ma,Pa,La;let Fa,Ba;if("message"in $)Fa=$.message,Ba=$.signature;else{const{chain:qa,wallet:za,statement:Va,options:Ga}=$;let Za;if(isBrowser())if(typeof za=="object")Za=za;else{const Xa=window;if("solana"in Xa&&typeof Xa.solana=="object"&&("signIn"in Xa.solana&&typeof Xa.solana.signIn=="function"||"signMessage"in Xa.solana&&typeof Xa.solana.signMessage=="function"))Za=Xa.solana;else throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.")}else{if(typeof za!="object"||!(Ga!=null&&Ga.url))throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments.");Za=za}const Qa=new URL((ts=Ga==null?void 0:Ga.url)!==null&&ts!==void 0?ts:window.location.href);if("signIn"in Za&&Za.signIn){const Xa=await Za.signIn(Object.assign(Object.assign(Object.assign({issuedAt:new Date().toISOString()},Ga==null?void 0:Ga.signInWithSolana),{version:"1",domain:Qa.host,uri:Qa.href}),Va?{statement:Va}:null));let Ja;if(Array.isArray(Xa)&&Xa[0]&&typeof Xa[0]=="object")Ja=Xa[0];else if(Xa&&typeof Xa=="object"&&"signedMessage"in Xa&&"signature"in Xa)Ja=Xa;else throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value");if("signedMessage"in Ja&&"signature"in Ja&&(typeof Ja.signedMessage=="string"||Ja.signedMessage instanceof Uint8Array)&&Ja.signature instanceof Uint8Array)Fa=typeof Ja.signedMessage=="string"?Ja.signedMessage:new TextDecoder().decode(Ja.signedMessage),Ba=Ja.signature;else throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields")}else{if(!("signMessage"in Za)||typeof Za.signMessage!="function"||!("publicKey"in Za)||typeof Za!="object"||!Za.publicKey||!("toBase58"in Za.publicKey)||typeof Za.publicKey.toBase58!="function")throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API");Fa=[`${Qa.host} wants you to sign in with your Solana account:`,Za.publicKey.toBase58(),...Va?["",Va,""]:[""],"Version: 1",`URI: ${Qa.href}`,`Issued At: ${(cs=(is=Ga==null?void 0:Ga.signInWithSolana)===null||is===void 0?void 0:is.issuedAt)!==null&&cs!==void 0?cs:new Date().toISOString()}`,...!((Kr=Ga==null?void 0:Ga.signInWithSolana)===null||Kr===void 0)&&Kr.notBefore?[`Not Before: ${Ga.signInWithSolana.notBefore}`]:[],...!((Xr=Ga==null?void 0:Ga.signInWithSolana)===null||Xr===void 0)&&Xr.expirationTime?[`Expiration Time: ${Ga.signInWithSolana.expirationTime}`]:[],...!((Na=Ga==null?void 0:Ga.signInWithSolana)===null||Na===void 0)&&Na.chainId?[`Chain ID: ${Ga.signInWithSolana.chainId}`]:[],...!((Ca=Ga==null?void 0:Ga.signInWithSolana)===null||Ca===void 0)&&Ca.nonce?[`Nonce: ${Ga.signInWithSolana.nonce}`]:[],...!((Aa=Ga==null?void 0:Ga.signInWithSolana)===null||Aa===void 0)&&Aa.requestId?[`Request ID: ${Ga.signInWithSolana.requestId}`]:[],...!((Ma=(Ia=Ga==null?void 0:Ga.signInWithSolana)===null||Ia===void 0?void 0:Ia.resources)===null||Ma===void 0)&&Ma.length?["Resources",...Ga.signInWithSolana.resources.map(Ja=>`- ${Ja}`)]:[]].join(`
710
710
  `);const Xa=await Za.signMessage(new TextEncoder().encode(Fa),"utf8");if(!Xa||!(Xa instanceof Uint8Array))throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value");Ba=Xa}}try{const{data:qa,error:za}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:"solana",message:Fa,signature:bytesToBase64URL(Ba)},!((Pa=$.options)===null||Pa===void 0)&&Pa.captchaToken?{gotrue_meta_security:{captcha_token:(La=$.options)===null||La===void 0?void 0:La.captchaToken}}:null),xform:_sessionResponse});if(za)throw za;if(!qa||!qa.session||!qa.user){const Va=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Va})}return qa.session&&(await this._saveSession(qa.session),await this._notifyAllSubscribers("SIGNED_IN",qa.session)),this._returnResult({data:Object.assign({},qa),error:za})}catch(qa){if(isAuthError(qa))return this._returnResult({data:{user:null,session:null},error:qa});throw qa}}async _exchangeCodeForSession($){const ts=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`),[is,cs]=(ts??"").split("/");try{if(!is&&this.flowType==="pkce")throw new AuthPKCECodeVerifierMissingError;const{data:Kr,error:Xr}=await _request(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:$,code_verifier:is},xform:_sessionResponse});if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),Xr)throw Xr;if(!Kr||!Kr.session||!Kr.user){const Na=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:Na})}return Kr.session&&(await this._saveSession(Kr.session),await this._notifyAllSubscribers("SIGNED_IN",Kr.session)),this._returnResult({data:Object.assign(Object.assign({},Kr),{redirectType:cs??null}),error:Xr})}catch(Kr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Kr))return this._returnResult({data:{user:null,session:null,redirectType:null},error:Kr});throw Kr}}async signInWithIdToken($){try{const{options:ts,provider:is,token:cs,access_token:Kr,nonce:Xr}=$,Na=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:is,id_token:cs,access_token:Kr,nonce:Xr,gotrue_meta_security:{captcha_token:ts==null?void 0:ts.captchaToken}},xform:_sessionResponse}),{data:Ca,error:Aa}=Na;if(Aa)return this._returnResult({data:{user:null,session:null},error:Aa});if(!Ca||!Ca.session||!Ca.user){const Ia=new AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:Ia})}return Ca.session&&(await this._saveSession(Ca.session),await this._notifyAllSubscribers("SIGNED_IN",Ca.session)),this._returnResult({data:Ca,error:Aa})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async signInWithOtp($){var ts,is,cs,Kr,Xr;try{if("email"in $){const{email:Na,options:Ca}=$;let Aa=null,Ia=null;this.flowType==="pkce"&&([Aa,Ia]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const{error:Ma}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:Na,data:(ts=Ca==null?void 0:Ca.data)!==null&&ts!==void 0?ts:{},create_user:(is=Ca==null?void 0:Ca.shouldCreateUser)!==null&&is!==void 0?is:!0,gotrue_meta_security:{captcha_token:Ca==null?void 0:Ca.captchaToken},code_challenge:Aa,code_challenge_method:Ia},redirectTo:Ca==null?void 0:Ca.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:Ma})}if("phone"in $){const{phone:Na,options:Ca}=$,{data:Aa,error:Ia}=await _request(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:Na,data:(cs=Ca==null?void 0:Ca.data)!==null&&cs!==void 0?cs:{},create_user:(Kr=Ca==null?void 0:Ca.shouldCreateUser)!==null&&Kr!==void 0?Kr:!0,gotrue_meta_security:{captcha_token:Ca==null?void 0:Ca.captchaToken},channel:(Xr=Ca==null?void 0:Ca.channel)!==null&&Xr!==void 0?Xr:"sms"}});return this._returnResult({data:{user:null,session:null,messageId:Aa==null?void 0:Aa.message_id},error:Ia})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number.")}catch(Na){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Na))return this._returnResult({data:{user:null,session:null},error:Na});throw Na}}async verifyOtp($){var ts,is;try{let cs,Kr;"options"in $&&(cs=(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo,Kr=(is=$.options)===null||is===void 0?void 0:is.captchaToken);const{data:Xr,error:Na}=await _request(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},$),{gotrue_meta_security:{captcha_token:Kr}}),redirectTo:cs,xform:_sessionResponse});if(Na)throw Na;if(!Xr)throw new Error("An error occurred on token verification.");const Ca=Xr.session,Aa=Xr.user;return Ca!=null&&Ca.access_token&&(await this._saveSession(Ca),await this._notifyAllSubscribers($.type=="recovery"?"PASSWORD_RECOVERY":"SIGNED_IN",Ca)),this._returnResult({data:{user:Aa,session:Ca},error:null})}catch(cs){if(isAuthError(cs))return this._returnResult({data:{user:null,session:null},error:cs});throw cs}}async signInWithSSO($){var ts,is,cs,Kr,Xr;try{let Na=null,Ca=null;this.flowType==="pkce"&&([Na,Ca]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const Aa=await _request(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in $?{provider_id:$.providerId}:null),"domain"in $?{domain:$.domain}:null),{redirect_to:(is=(ts=$.options)===null||ts===void 0?void 0:ts.redirectTo)!==null&&is!==void 0?is:void 0}),!((cs=$==null?void 0:$.options)===null||cs===void 0)&&cs.captchaToken?{gotrue_meta_security:{captcha_token:$.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:Na,code_challenge_method:Ca}),headers:this.headers,xform:_ssoResponse});return!((Kr=Aa.data)===null||Kr===void 0)&&Kr.url&&isBrowser()&&!(!((Xr=$.options)===null||Xr===void 0)&&Xr.skipBrowserRedirect)&&window.location.assign(Aa.data.url),this._returnResult(Aa)}catch(Na){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Na))return this._returnResult({data:null,error:Na});throw Na}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async $=>{const{data:{session:ts},error:is}=$;if(is)throw is;if(!ts)throw new AuthSessionMissingError;const{error:cs}=await _request(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:ts.access_token});return this._returnResult({data:{user:null,session:null},error:cs})})}catch($){if(isAuthError($))return this._returnResult({data:{user:null,session:null},error:$});throw $}}async resend($){try{const ts=`${this.url}/resend`;if("email"in $){const{email:is,type:cs,options:Kr}=$,{error:Xr}=await _request(this.fetch,"POST",ts,{headers:this.headers,body:{email:is,type:cs,gotrue_meta_security:{captcha_token:Kr==null?void 0:Kr.captchaToken}},redirectTo:Kr==null?void 0:Kr.emailRedirectTo});return this._returnResult({data:{user:null,session:null},error:Xr})}else if("phone"in $){const{phone:is,type:cs,options:Kr}=$,{data:Xr,error:Na}=await _request(this.fetch,"POST",ts,{headers:this.headers,body:{phone:is,type:cs,gotrue_meta_security:{captcha_token:Kr==null?void 0:Kr.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:Xr==null?void 0:Xr.message_id},error:Na})}throw new AuthInvalidCredentialsError("You must provide either an email or phone number and a type")}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async getSession(){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async ts=>ts))}async _acquireLock($,ts){this._debug("#_acquireLock","begin",$);try{if(this.lockAcquired){const is=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),cs=(async()=>(await is,await ts()))();return this.pendingInLock.push((async()=>{try{await cs}catch{}})()),cs}return await this.lock(`lock:${this.storageKey}`,$,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const is=ts();for(this.pendingInLock.push((async()=>{try{await is}catch{}})()),await is;this.pendingInLock.length;){const cs=[...this.pendingInLock];await Promise.all(cs),this.pendingInLock.splice(0,cs.length)}return await is}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession($){this._debug("#_useSession","begin");try{const ts=await this.__loadSession();return await $(ts)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let $=null;const ts=await getItemAsync(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",ts),ts!==null&&(this._isValidSession(ts)?$=ts:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!$)return{data:{session:null},error:null};const is=$.expires_at?$.expires_at*1e3-Date.now()<EXPIRY_MARGIN_MS:!1;if(this._debug("#__loadSession()",`session has${is?"":" not"} expired`,"expires_at",$.expires_at),!is){if(this.userStorage){const Xr=await getItemAsync(this.userStorage,this.storageKey+"-user");Xr!=null&&Xr.user?$.user=Xr.user:$.user=userNotAvailableProxy()}if(this.storage.isServer&&$.user&&!$.user.__isUserNotAvailableProxy){const Xr={value:this.suppressGetSessionWarning};$.user=insecureUserWarningProxy($.user,Xr),Xr.value&&(this.suppressGetSessionWarning=!0)}return{data:{session:$},error:null}}const{data:cs,error:Kr}=await this._callRefreshToken($.refresh_token);return Kr?this._returnResult({data:{session:null},error:Kr}):this._returnResult({data:{session:cs},error:null})}finally{this._debug("#__loadSession()","end")}}async getUser($){if($)return await this._getUser($);await this.initializePromise;const ts=await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser());return ts.data.user&&(this.suppressGetSessionWarning=!0),ts}async _getUser($){try{return $?await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:$,xform:_userResponse}):await this._useSession(async ts=>{var is,cs,Kr;const{data:Xr,error:Na}=ts;if(Na)throw Na;return!(!((is=Xr.session)===null||is===void 0)&&is.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new AuthSessionMissingError}:await _request(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:(Kr=(cs=Xr.session)===null||cs===void 0?void 0:cs.access_token)!==null&&Kr!==void 0?Kr:void 0,xform:_userResponse})})}catch(ts){if(isAuthError(ts))return isAuthSessionMissingError(ts)&&(await this._removeSession(),await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({data:{user:null},error:ts});throw ts}}async updateUser($,ts={}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser($,ts))}async _updateUser($,ts={}){try{return await this._useSession(async is=>{const{data:cs,error:Kr}=is;if(Kr)throw Kr;if(!cs.session)throw new AuthSessionMissingError;const Xr=cs.session;let Na=null,Ca=null;this.flowType==="pkce"&&$.email!=null&&([Na,Ca]=await getCodeChallengeAndMethod(this.storage,this.storageKey));const{data:Aa,error:Ia}=await _request(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:ts==null?void 0:ts.emailRedirectTo,body:Object.assign(Object.assign({},$),{code_challenge:Na,code_challenge_method:Ca}),jwt:Xr.access_token,xform:_userResponse});if(Ia)throw Ia;return Xr.user=Aa.user,await this._saveSession(Xr),await this._notifyAllSubscribers("USER_UPDATED",Xr),this._returnResult({data:{user:Xr.user},error:null})})}catch(is){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(is))return this._returnResult({data:{user:null},error:is});throw is}}async setSession($){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession($))}async _setSession($){try{if(!$.access_token||!$.refresh_token)throw new AuthSessionMissingError;const ts=Date.now()/1e3;let is=ts,cs=!0,Kr=null;const{payload:Xr}=decodeJWT($.access_token);if(Xr.exp&&(is=Xr.exp,cs=is<=ts),cs){const{data:Na,error:Ca}=await this._callRefreshToken($.refresh_token);if(Ca)return this._returnResult({data:{user:null,session:null},error:Ca});if(!Na)return{data:{user:null,session:null},error:null};Kr=Na}else{const{data:Na,error:Ca}=await this._getUser($.access_token);if(Ca)return this._returnResult({data:{user:null,session:null},error:Ca});Kr={access_token:$.access_token,refresh_token:$.refresh_token,user:Na.user,token_type:"bearer",expires_in:is-ts,expires_at:is},await this._saveSession(Kr),await this._notifyAllSubscribers("SIGNED_IN",Kr)}return this._returnResult({data:{user:Kr.user,session:Kr},error:null})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{session:null,user:null},error:ts});throw ts}}async refreshSession($){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession($))}async _refreshSession($){try{return await this._useSession(async ts=>{var is;if(!$){const{data:Xr,error:Na}=ts;if(Na)throw Na;$=(is=Xr.session)!==null&&is!==void 0?is:void 0}if(!($!=null&&$.refresh_token))throw new AuthSessionMissingError;const{data:cs,error:Kr}=await this._callRefreshToken($.refresh_token);return Kr?this._returnResult({data:{user:null,session:null},error:Kr}):cs?this._returnResult({data:{user:cs.user,session:cs},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:{user:null,session:null},error:ts});throw ts}}async _getSessionFromURL($,ts){try{if(!isBrowser())throw new AuthImplicitGrantRedirectError("No browser detected.");if($.error||$.error_description||$.error_code)throw new AuthImplicitGrantRedirectError($.error_description||"Error in URL with unspecified error_description",{error:$.error||"unspecified_error",code:$.error_code||"unspecified_code"});switch(ts){case"implicit":if(this.flowType==="pkce")throw new AuthPKCEGrantCodeExchangeError("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new AuthImplicitGrantRedirectError("Not a valid implicit grant flow url.");break;default:}if(ts==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!$.code)throw new AuthPKCEGrantCodeExchangeError("No code detected.");const{data:Va,error:Ga}=await this._exchangeCodeForSession($.code);if(Ga)throw Ga;const Za=new URL(window.location.href);return Za.searchParams.delete("code"),window.history.replaceState(window.history.state,"",Za.toString()),{data:{session:Va.session,redirectType:null},error:null}}const{provider_token:is,provider_refresh_token:cs,access_token:Kr,refresh_token:Xr,expires_in:Na,expires_at:Ca,token_type:Aa}=$;if(!Kr||!Na||!Xr||!Aa)throw new AuthImplicitGrantRedirectError("No session defined in URL");const Ia=Math.round(Date.now()/1e3),Ma=parseInt(Na);let Pa=Ia+Ma;Ca&&(Pa=parseInt(Ca));const La=Pa-Ia;La*1e3<=AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${La}s, should have been closer to ${Ma}s`);const Fa=Pa-Ma;Ia-Fa>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",Fa,Pa,Ia):Ia-Fa<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",Fa,Pa,Ia);const{data:Ba,error:qa}=await this._getUser(Kr);if(qa)throw qa;const za={provider_token:is,provider_refresh_token:cs,access_token:Kr,expires_in:Ma,expires_at:Pa,refresh_token:Xr,token_type:Aa,user:Ba.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),this._returnResult({data:{session:za,redirectType:$.type},error:null})}catch(is){if(isAuthError(is))return this._returnResult({data:{session:null,redirectType:null},error:is});throw is}}_isImplicitGrantCallback($){return typeof this.detectSessionInUrl=="function"?this.detectSessionInUrl(new URL(window.location.href),$):!!($.access_token||$.error_description)}async _isPKCECallback($){const ts=await getItemAsync(this.storage,`${this.storageKey}-code-verifier`);return!!($.code&&ts)}async signOut($={scope:"global"}){return await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut($))}async _signOut({scope:$}={scope:"global"}){return await this._useSession(async ts=>{var is;const{data:cs,error:Kr}=ts;if(Kr&&!isAuthSessionMissingError(Kr))return this._returnResult({error:Kr});const Xr=(is=cs.session)===null||is===void 0?void 0:is.access_token;if(Xr){const{error:Na}=await this.admin.signOut(Xr,$);if(Na&&!(isAuthApiError(Na)&&(Na.status===404||Na.status===401||Na.status===403)||isAuthSessionMissingError(Na)))return this._returnResult({error:Na})}return $!=="others"&&(await this._removeSession(),await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`)),this._returnResult({error:null})})}onAuthStateChange($){const ts=generateCallbackId(),is={id:ts,callback:$,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",ts),this.stateChangeEmitters.delete(ts)}};return this._debug("#onAuthStateChange()","registered callback with id",ts),this.stateChangeEmitters.set(ts,is),(async()=>(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(ts)})))(),{data:{subscription:is}}}async _emitInitialSession($){return await this._useSession(async ts=>{var is,cs;try{const{data:{session:Kr},error:Xr}=ts;if(Xr)throw Xr;await((is=this.stateChangeEmitters.get($))===null||is===void 0?void 0:is.callback("INITIAL_SESSION",Kr)),this._debug("INITIAL_SESSION","callback id",$,"session",Kr)}catch(Kr){await((cs=this.stateChangeEmitters.get($))===null||cs===void 0?void 0:cs.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",$,"error",Kr),console.error(Kr)}})}async resetPasswordForEmail($,ts={}){let is=null,cs=null;this.flowType==="pkce"&&([is,cs]=await getCodeChallengeAndMethod(this.storage,this.storageKey,!0));try{return await _request(this.fetch,"POST",`${this.url}/recover`,{body:{email:$,code_challenge:is,code_challenge_method:cs,gotrue_meta_security:{captcha_token:ts.captchaToken}},headers:this.headers,redirectTo:ts.redirectTo})}catch(Kr){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(Kr))return this._returnResult({data:null,error:Kr});throw Kr}}async getUserIdentities(){var $;try{const{data:ts,error:is}=await this.getUser();if(is)throw is;return this._returnResult({data:{identities:($=ts.user.identities)!==null&&$!==void 0?$:[]},error:null})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async linkIdentity($){return"token"in $?this.linkIdentityIdToken($):this.linkIdentityOAuth($)}async linkIdentityOAuth($){var ts;try{const{data:is,error:cs}=await this._useSession(async Kr=>{var Xr,Na,Ca,Aa,Ia;const{data:Ma,error:Pa}=Kr;if(Pa)throw Pa;const La=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,$.provider,{redirectTo:(Xr=$.options)===null||Xr===void 0?void 0:Xr.redirectTo,scopes:(Na=$.options)===null||Na===void 0?void 0:Na.scopes,queryParams:(Ca=$.options)===null||Ca===void 0?void 0:Ca.queryParams,skipBrowserRedirect:!0});return await _request(this.fetch,"GET",La,{headers:this.headers,jwt:(Ia=(Aa=Ma.session)===null||Aa===void 0?void 0:Aa.access_token)!==null&&Ia!==void 0?Ia:void 0})});if(cs)throw cs;return isBrowser()&&!(!((ts=$.options)===null||ts===void 0)&&ts.skipBrowserRedirect)&&window.location.assign(is==null?void 0:is.url),this._returnResult({data:{provider:$.provider,url:is==null?void 0:is.url},error:null})}catch(is){if(isAuthError(is))return this._returnResult({data:{provider:$.provider,url:null},error:is});throw is}}async linkIdentityIdToken($){return await this._useSession(async ts=>{var is;try{const{error:cs,data:{session:Kr}}=ts;if(cs)throw cs;const{options:Xr,provider:Na,token:Ca,access_token:Aa,nonce:Ia}=$,Ma=await _request(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:(is=Kr==null?void 0:Kr.access_token)!==null&&is!==void 0?is:void 0,body:{provider:Na,id_token:Ca,access_token:Aa,nonce:Ia,link_identity:!0,gotrue_meta_security:{captcha_token:Xr==null?void 0:Xr.captchaToken}},xform:_sessionResponse}),{data:Pa,error:La}=Ma;return La?this._returnResult({data:{user:null,session:null},error:La}):!Pa||!Pa.session||!Pa.user?this._returnResult({data:{user:null,session:null},error:new AuthInvalidTokenResponseError}):(Pa.session&&(await this._saveSession(Pa.session),await this._notifyAllSubscribers("USER_UPDATED",Pa.session)),this._returnResult({data:Pa,error:La}))}catch(cs){if(await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`),isAuthError(cs))return this._returnResult({data:{user:null,session:null},error:cs});throw cs}})}async unlinkIdentity($){try{return await this._useSession(async ts=>{var is,cs;const{data:Kr,error:Xr}=ts;if(Xr)throw Xr;return await _request(this.fetch,"DELETE",`${this.url}/user/identities/${$.identity_id}`,{headers:this.headers,jwt:(cs=(is=Kr.session)===null||is===void 0?void 0:is.access_token)!==null&&cs!==void 0?cs:void 0})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _refreshAccessToken($){const ts=`#_refreshAccessToken(${$.substring(0,5)}...)`;this._debug(ts,"begin");try{const is=Date.now();return await retryable(async cs=>(cs>0&&await sleep(200*Math.pow(2,cs-1)),this._debug(ts,"refreshing attempt",cs),await _request(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:$},headers:this.headers,xform:_sessionResponse})),(cs,Kr)=>{const Xr=200*Math.pow(2,cs);return Kr&&isAuthRetryableFetchError(Kr)&&Date.now()+Xr-is<AUTO_REFRESH_TICK_DURATION_MS})}catch(is){if(this._debug(ts,"error",is),isAuthError(is))return this._returnResult({data:{session:null,user:null},error:is});throw is}finally{this._debug(ts,"end")}}_isValidSession($){return typeof $=="object"&&$!==null&&"access_token"in $&&"refresh_token"in $&&"expires_at"in $}async _handleProviderSignIn($,ts){const is=await this._getUrlForProvider(`${this.url}/authorize`,$,{redirectTo:ts.redirectTo,scopes:ts.scopes,queryParams:ts.queryParams});return this._debug("#_handleProviderSignIn()","provider",$,"options",ts,"url",is),isBrowser()&&!ts.skipBrowserRedirect&&window.location.assign(is),{data:{provider:$,url:is},error:null}}async _recoverAndRefresh(){var $,ts;const is="#_recoverAndRefresh()";this._debug(is,"begin");try{const cs=await getItemAsync(this.storage,this.storageKey);if(cs&&this.userStorage){let Xr=await getItemAsync(this.userStorage,this.storageKey+"-user");!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!Xr&&(Xr={user:cs.user},await setItemAsync(this.userStorage,this.storageKey+"-user",Xr)),cs.user=($=Xr==null?void 0:Xr.user)!==null&&$!==void 0?$:userNotAvailableProxy()}else if(cs&&!cs.user&&!cs.user){const Xr=await getItemAsync(this.storage,this.storageKey+"-user");Xr&&(Xr!=null&&Xr.user)?(cs.user=Xr.user,await removeItemAsync(this.storage,this.storageKey+"-user"),await setItemAsync(this.storage,this.storageKey,cs)):cs.user=userNotAvailableProxy()}if(this._debug(is,"session from storage",cs),!this._isValidSession(cs)){this._debug(is,"session is not valid"),cs!==null&&await this._removeSession();return}const Kr=((ts=cs.expires_at)!==null&&ts!==void 0?ts:1/0)*1e3-Date.now()<EXPIRY_MARGIN_MS;if(this._debug(is,`session has${Kr?"":" not"} expired with margin of ${EXPIRY_MARGIN_MS}s`),Kr){if(this.autoRefreshToken&&cs.refresh_token){const{error:Xr}=await this._callRefreshToken(cs.refresh_token);Xr&&(console.error(Xr),isAuthRetryableFetchError(Xr)||(this._debug(is,"refresh failed with a non-retryable error, removing the session",Xr),await this._removeSession()))}}else if(cs.user&&cs.user.__isUserNotAvailableProxy===!0)try{const{data:Xr,error:Na}=await this._getUser(cs.access_token);!Na&&(Xr!=null&&Xr.user)?(cs.user=Xr.user,await this._saveSession(cs),await this._notifyAllSubscribers("SIGNED_IN",cs)):this._debug(is,"could not get user data, skipping SIGNED_IN notification")}catch(Xr){console.error("Error getting user data:",Xr),this._debug(is,"error getting user data, skipping SIGNED_IN notification",Xr)}else await this._notifyAllSubscribers("SIGNED_IN",cs)}catch(cs){this._debug(is,"error",cs),console.error(cs);return}finally{this._debug(is,"end")}}async _callRefreshToken($){var ts,is;if(!$)throw new AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;const cs=`#_callRefreshToken(${$.substring(0,5)}...)`;this._debug(cs,"begin");try{this.refreshingDeferred=new Deferred;const{data:Kr,error:Xr}=await this._refreshAccessToken($);if(Xr)throw Xr;if(!Kr.session)throw new AuthSessionMissingError;await this._saveSession(Kr.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",Kr.session);const Na={data:Kr.session,error:null};return this.refreshingDeferred.resolve(Na),Na}catch(Kr){if(this._debug(cs,"error",Kr),isAuthError(Kr)){const Xr={data:null,error:Kr};return isAuthRetryableFetchError(Kr)||await this._removeSession(),(ts=this.refreshingDeferred)===null||ts===void 0||ts.resolve(Xr),Xr}throw(is=this.refreshingDeferred)===null||is===void 0||is.reject(Kr),Kr}finally{this.refreshingDeferred=null,this._debug(cs,"end")}}async _notifyAllSubscribers($,ts,is=!0){const cs=`#_notifyAllSubscribers(${$})`;this._debug(cs,"begin",ts,`broadcast = ${is}`);try{this.broadcastChannel&&is&&this.broadcastChannel.postMessage({event:$,session:ts});const Kr=[],Xr=Array.from(this.stateChangeEmitters.values()).map(async Na=>{try{await Na.callback($,ts)}catch(Ca){Kr.push(Ca)}});if(await Promise.all(Xr),Kr.length>0){for(let Na=0;Na<Kr.length;Na+=1)console.error(Kr[Na]);throw Kr[0]}}finally{this._debug(cs,"end")}}async _saveSession($){this._debug("#_saveSession()",$),this.suppressGetSessionWarning=!0,await removeItemAsync(this.storage,`${this.storageKey}-code-verifier`);const ts=Object.assign({},$),is=ts.user&&ts.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!is&&ts.user&&await setItemAsync(this.userStorage,this.storageKey+"-user",{user:ts.user});const cs=Object.assign({},ts);delete cs.user;const Kr=deepClone(cs);await setItemAsync(this.storage,this.storageKey,Kr)}else{const cs=deepClone(ts);await setItemAsync(this.storage,this.storageKey,cs)}}async _removeSession(){this._debug("#_removeSession()"),this.suppressGetSessionWarning=!1,await removeItemAsync(this.storage,this.storageKey),await removeItemAsync(this.storage,this.storageKey+"-code-verifier"),await removeItemAsync(this.storage,this.storageKey+"-user"),this.userStorage&&await removeItemAsync(this.userStorage,this.storageKey+"-user"),await this._notifyAllSubscribers("SIGNED_OUT",null)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");const $=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{$&&isBrowser()&&(window!=null&&window.removeEventListener)&&window.removeEventListener("visibilitychange",$)}catch(ts){console.error("removing visibilitychange callback failed",ts)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");const $=setInterval(()=>this._autoRefreshTokenTick(),AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=$,$&&typeof $=="object"&&typeof $.unref=="function"?$.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer($);const ts=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=ts,ts&&typeof ts=="object"&&typeof ts.unref=="function"?ts.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(ts)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const $=this.autoRefreshTicker;this.autoRefreshTicker=null,$&&clearInterval($);const ts=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,ts&&clearTimeout(ts)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const $=Date.now();try{return await this._useSession(async ts=>{const{data:{session:is}}=ts;if(!is||!is.refresh_token||!is.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const cs=Math.floor((is.expires_at*1e3-$)/AUTO_REFRESH_TICK_DURATION_MS);this._debug("#_autoRefreshTokenTick()",`access token expires in ${cs} ticks, a tick lasts ${AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${AUTO_REFRESH_TICK_THRESHOLD} ticks`),cs<=AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(is.refresh_token)})}catch(ts){console.error("Auto refresh tick failed with error. This is likely a transient error.",ts)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch($){if($.isAcquireTimeout||$ instanceof LockAcquireTimeoutError)this._debug("auto refresh token tick lock not available");else throw $}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!isBrowser()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch($){this._debug("#visibilityChangedCallback","error",$)}},window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch($){console.error("_handleVisibilityChange",$)}}async _onVisibilityChanged($){const ts=`#_onVisibilityChanged(${$})`;this._debug(ts,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),$||(await this.initializePromise,await this._acquireLock(this.lockAcquireTimeout,async()=>{if(document.visibilityState!=="visible"){this._debug(ts,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider($,ts,is){const cs=[`provider=${encodeURIComponent(ts)}`];if(is!=null&&is.redirectTo&&cs.push(`redirect_to=${encodeURIComponent(is.redirectTo)}`),is!=null&&is.scopes&&cs.push(`scopes=${encodeURIComponent(is.scopes)}`),this.flowType==="pkce"){const[Kr,Xr]=await getCodeChallengeAndMethod(this.storage,this.storageKey),Na=new URLSearchParams({code_challenge:`${encodeURIComponent(Kr)}`,code_challenge_method:`${encodeURIComponent(Xr)}`});cs.push(Na.toString())}if(is!=null&&is.queryParams){const Kr=new URLSearchParams(is.queryParams);cs.push(Kr.toString())}return is!=null&&is.skipBrowserRedirect&&cs.push(`skip_http_redirect=${is.skipBrowserRedirect}`),`${$}?${cs.join("&")}`}async _unenroll($){try{return await this._useSession(async ts=>{var is;const{data:cs,error:Kr}=ts;return Kr?this._returnResult({data:null,error:Kr}):await _request(this.fetch,"DELETE",`${this.url}/factors/${$.factorId}`,{headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _enroll($){try{return await this._useSession(async ts=>{var is,cs;const{data:Kr,error:Xr}=ts;if(Xr)return this._returnResult({data:null,error:Xr});const Na=Object.assign({friendly_name:$.friendlyName,factor_type:$.factorType},$.factorType==="phone"?{phone:$.phone}:$.factorType==="totp"?{issuer:$.issuer}:{}),{data:Ca,error:Aa}=await _request(this.fetch,"POST",`${this.url}/factors`,{body:Na,headers:this.headers,jwt:(is=Kr==null?void 0:Kr.session)===null||is===void 0?void 0:is.access_token});return Aa?this._returnResult({data:null,error:Aa}):($.factorType==="totp"&&Ca.type==="totp"&&(!((cs=Ca==null?void 0:Ca.totp)===null||cs===void 0)&&cs.qr_code)&&(Ca.totp.qr_code=`data:image/svg+xml;utf-8,${Ca.totp.qr_code}`),this._returnResult({data:Ca,error:null}))})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _verify($){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async ts=>{var is;const{data:cs,error:Kr}=ts;if(Kr)return this._returnResult({data:null,error:Kr});const Xr=Object.assign({challenge_id:$.challengeId},"webauthn"in $?{webauthn:Object.assign(Object.assign({},$.webauthn),{credential_response:$.webauthn.type==="create"?serializeCredentialCreationResponse($.webauthn.credential_response):serializeCredentialRequestResponse($.webauthn.credential_response)})}:{code:$.code}),{data:Na,error:Ca}=await _request(this.fetch,"POST",`${this.url}/factors/${$.factorId}/verify`,{body:Xr,headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token});return Ca?this._returnResult({data:null,error:Ca}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+Na.expires_in},Na)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",Na),this._returnResult({data:Na,error:Ca}))})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}})}async _challenge($){return this._acquireLock(this.lockAcquireTimeout,async()=>{try{return await this._useSession(async ts=>{var is;const{data:cs,error:Kr}=ts;if(Kr)return this._returnResult({data:null,error:Kr});const Xr=await _request(this.fetch,"POST",`${this.url}/factors/${$.factorId}/challenge`,{body:$,headers:this.headers,jwt:(is=cs==null?void 0:cs.session)===null||is===void 0?void 0:is.access_token});if(Xr.error)return Xr;const{data:Na}=Xr;if(Na.type!=="webauthn")return{data:Na,error:null};switch(Na.webauthn.type){case"create":return{data:Object.assign(Object.assign({},Na),{webauthn:Object.assign(Object.assign({},Na.webauthn),{credential_options:Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:deserializeCredentialCreationOptions(Na.webauthn.credential_options.publicKey)})})}),error:null};case"request":return{data:Object.assign(Object.assign({},Na),{webauthn:Object.assign(Object.assign({},Na.webauthn),{credential_options:Object.assign(Object.assign({},Na.webauthn.credential_options),{publicKey:deserializeCredentialRequestOptions(Na.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}})}async _challengeAndVerify($){const{data:ts,error:is}=await this._challenge({factorId:$.factorId});return is?this._returnResult({data:null,error:is}):await this._verify({factorId:$.factorId,challengeId:ts.id,code:$.code})}async _listFactors(){var $;const{data:{user:ts},error:is}=await this.getUser();if(is)return{data:null,error:is};const cs={all:[],phone:[],totp:[],webauthn:[]};for(const Kr of($=ts==null?void 0:ts.factors)!==null&&$!==void 0?$:[])cs.all.push(Kr),Kr.status==="verified"&&cs[Kr.factor_type].push(Kr);return{data:cs,error:null}}async _getAuthenticatorAssuranceLevel($){var ts,is,cs,Kr;if($)try{const{payload:La}=decodeJWT($);let Fa=null;La.aal&&(Fa=La.aal);let Ba=Fa;const{data:{user:qa},error:za}=await this.getUser($);if(za)return this._returnResult({data:null,error:za});((is=(ts=qa==null?void 0:qa.factors)===null||ts===void 0?void 0:ts.filter(Za=>Za.status==="verified"))!==null&&is!==void 0?is:[]).length>0&&(Ba="aal2");const Ga=La.amr||[];return{data:{currentLevel:Fa,nextLevel:Ba,currentAuthenticationMethods:Ga},error:null}}catch(La){if(isAuthError(La))return this._returnResult({data:null,error:La});throw La}const{data:{session:Xr},error:Na}=await this.getSession();if(Na)return this._returnResult({data:null,error:Na});if(!Xr)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:Ca}=decodeJWT(Xr.access_token);let Aa=null;Ca.aal&&(Aa=Ca.aal);let Ia=Aa;((Kr=(cs=Xr.user.factors)===null||cs===void 0?void 0:cs.filter(La=>La.status==="verified"))!==null&&Kr!==void 0?Kr:[]).length>0&&(Ia="aal2");const Pa=Ca.amr||[];return{data:{currentLevel:Aa,nextLevel:Ia,currentAuthenticationMethods:Pa},error:null}}async _getAuthorizationDetails($){try{return await this._useSession(async ts=>{const{data:{session:is},error:cs}=ts;return cs?this._returnResult({data:null,error:cs}):is?await _request(this.fetch,"GET",`${this.url}/oauth/authorizations/${$}`,{headers:this.headers,jwt:is.access_token,xform:Kr=>({data:Kr,error:null})}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async _approveAuthorization($,ts){try{return await this._useSession(async is=>{const{data:{session:cs},error:Kr}=is;if(Kr)return this._returnResult({data:null,error:Kr});if(!cs)return this._returnResult({data:null,error:new AuthSessionMissingError});const Xr=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${$}/consent`,{headers:this.headers,jwt:cs.access_token,body:{action:"approve"},xform:Na=>({data:Na,error:null})});return Xr.data&&Xr.data.redirect_url&&isBrowser()&&!(ts!=null&&ts.skipBrowserRedirect)&&window.location.assign(Xr.data.redirect_url),Xr})}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}async _denyAuthorization($,ts){try{return await this._useSession(async is=>{const{data:{session:cs},error:Kr}=is;if(Kr)return this._returnResult({data:null,error:Kr});if(!cs)return this._returnResult({data:null,error:new AuthSessionMissingError});const Xr=await _request(this.fetch,"POST",`${this.url}/oauth/authorizations/${$}/consent`,{headers:this.headers,jwt:cs.access_token,body:{action:"deny"},xform:Na=>({data:Na,error:null})});return Xr.data&&Xr.data.redirect_url&&isBrowser()&&!(ts!=null&&ts.skipBrowserRedirect)&&window.location.assign(Xr.data.redirect_url),Xr})}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}async _listOAuthGrants(){try{return await this._useSession(async $=>{const{data:{session:ts},error:is}=$;return is?this._returnResult({data:null,error:is}):ts?await _request(this.fetch,"GET",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:ts.access_token,xform:cs=>({data:cs,error:null})}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch($){if(isAuthError($))return this._returnResult({data:null,error:$});throw $}}async _revokeOAuthGrant($){try{return await this._useSession(async ts=>{const{data:{session:is},error:cs}=ts;return cs?this._returnResult({data:null,error:cs}):is?(await _request(this.fetch,"DELETE",`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:is.access_token,query:{client_id:$.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new AuthSessionMissingError})})}catch(ts){if(isAuthError(ts))return this._returnResult({data:null,error:ts});throw ts}}async fetchJwk($,ts={keys:[]}){let is=ts.keys.find(Na=>Na.kid===$);if(is)return is;const cs=Date.now();if(is=this.jwks.keys.find(Na=>Na.kid===$),is&&this.jwks_cached_at+JWKS_TTL>cs)return is;const{data:Kr,error:Xr}=await _request(this.fetch,"GET",`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(Xr)throw Xr;return!Kr.keys||Kr.keys.length===0||(this.jwks=Kr,this.jwks_cached_at=cs,is=Kr.keys.find(Na=>Na.kid===$),!is)?null:is}async getClaims($,ts={}){try{let is=$;if(!is){const{data:La,error:Fa}=await this.getSession();if(Fa||!La.session)return this._returnResult({data:null,error:Fa});is=La.session.access_token}const{header:cs,payload:Kr,signature:Xr,raw:{header:Na,payload:Ca}}=decodeJWT(is);ts!=null&&ts.allowExpired||validateExp(Kr.exp);const Aa=!cs.alg||cs.alg.startsWith("HS")||!cs.kid||!("crypto"in globalThis&&"subtle"in globalThis.crypto)?null:await this.fetchJwk(cs.kid,ts!=null&&ts.keys?{keys:ts.keys}:ts==null?void 0:ts.jwks);if(!Aa){const{error:La}=await this.getUser(is);if(La)throw La;return{data:{claims:Kr,header:cs,signature:Xr},error:null}}const Ia=getAlgorithm(cs.alg),Ma=await crypto.subtle.importKey("jwk",Aa,Ia,!0,["verify"]);if(!await crypto.subtle.verify(Ia,Ma,Xr,stringToUint8Array(`${Na}.${Ca}`)))throw new AuthInvalidJwtError("Invalid JWT signature");return{data:{claims:Kr,header:cs,signature:Xr},error:null}}catch(is){if(isAuthError(is))return this._returnResult({data:null,error:is});throw is}}}GoTrueClient.nextInstanceID={};const AuthClient=GoTrueClient,version="2.95.3";let JS_ENV="";typeof Deno<"u"?JS_ENV="deno":typeof document<"u"?JS_ENV="web":typeof navigator<"u"&&navigator.product==="ReactNative"?JS_ENV="react-native":JS_ENV="node";const DEFAULT_HEADERS={"X-Client-Info":`supabase-js-${JS_ENV}/${version}`},DEFAULT_GLOBAL_OPTIONS={headers:DEFAULT_HEADERS},DEFAULT_DB_OPTIONS={schema:"public"},DEFAULT_AUTH_OPTIONS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},DEFAULT_REALTIME_OPTIONS={};function _typeof(es){"@babel/helpers - typeof";return _typeof=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function($){return typeof $}:function($){return $&&typeof Symbol=="function"&&$.constructor===Symbol&&$!==Symbol.prototype?"symbol":typeof $},_typeof(es)}function toPrimitive(es,$){if(_typeof(es)!="object"||!es)return es;var ts=es[Symbol.toPrimitive];if(ts!==void 0){var is=ts.call(es,$);if(_typeof(is)!="object")return is;throw new TypeError("@@toPrimitive must return a primitive value.")}return($==="string"?String:Number)(es)}function toPropertyKey(es){var $=toPrimitive(es,"string");return _typeof($)=="symbol"?$:$+""}function _defineProperty(es,$,ts){return($=toPropertyKey($))in es?Object.defineProperty(es,$,{value:ts,enumerable:!0,configurable:!0,writable:!0}):es[$]=ts,es}function ownKeys(es,$){var ts=Object.keys(es);if(Object.getOwnPropertySymbols){var is=Object.getOwnPropertySymbols(es);$&&(is=is.filter(function(cs){return Object.getOwnPropertyDescriptor(es,cs).enumerable})),ts.push.apply(ts,is)}return ts}function _objectSpread2(es){for(var $=1;$<arguments.length;$++){var ts=arguments[$]!=null?arguments[$]:{};$%2?ownKeys(Object(ts),!0).forEach(function(is){_defineProperty(es,is,ts[is])}):Object.getOwnPropertyDescriptors?Object.defineProperties(es,Object.getOwnPropertyDescriptors(ts)):ownKeys(Object(ts)).forEach(function(is){Object.defineProperty(es,is,Object.getOwnPropertyDescriptor(ts,is))})}return es}const resolveFetch=es=>es?(...$)=>es(...$):(...$)=>fetch(...$),resolveHeadersConstructor=()=>Headers,fetchWithAuth=(es,$,ts)=>{const is=resolveFetch(ts),cs=resolveHeadersConstructor();return async(Kr,Xr)=>{var Na;const Ca=(Na=await $())!==null&&Na!==void 0?Na:es;let Aa=new cs(Xr==null?void 0:Xr.headers);return Aa.has("apikey")||Aa.set("apikey",es),Aa.has("Authorization")||Aa.set("Authorization",`Bearer ${Ca}`),is(Kr,_objectSpread2(_objectSpread2({},Xr),{},{headers:Aa}))}};function ensureTrailingSlash(es){return es.endsWith("/")?es:es+"/"}function applySettingDefaults(es,$){var ts,is;const{db:cs,auth:Kr,realtime:Xr,global:Na}=es,{db:Ca,auth:Aa,realtime:Ia,global:Ma}=$,Pa={db:_objectSpread2(_objectSpread2({},Ca),cs),auth:_objectSpread2(_objectSpread2({},Aa),Kr),realtime:_objectSpread2(_objectSpread2({},Ia),Xr),storage:{},global:_objectSpread2(_objectSpread2(_objectSpread2({},Ma),Na),{},{headers:_objectSpread2(_objectSpread2({},(ts=Ma==null?void 0:Ma.headers)!==null&&ts!==void 0?ts:{}),(is=Na==null?void 0:Na.headers)!==null&&is!==void 0?is:{})}),accessToken:async()=>""};return es.accessToken?Pa.accessToken=es.accessToken:delete Pa.accessToken,Pa}function validateSupabaseUrl(es){const $=es==null?void 0:es.trim();if(!$)throw new Error("supabaseUrl is required.");if(!$.match(/^https?:\/\//i))throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.");try{return new URL(ensureTrailingSlash($))}catch{throw Error("Invalid supabaseUrl: Provided URL is malformed.")}}var SupabaseAuthClient=class extends AuthClient{constructor(es){super(es)}},SupabaseClient=class{constructor(es,$,ts){var is,cs;this.supabaseUrl=es,this.supabaseKey=$;const Kr=validateSupabaseUrl(es);if(!$)throw new Error("supabaseKey is required.");this.realtimeUrl=new URL("realtime/v1",Kr),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",Kr),this.storageUrl=new URL("storage/v1",Kr),this.functionsUrl=new URL("functions/v1",Kr);const Xr=`sb-${Kr.hostname.split(".")[0]}-auth-token`,Na={db:DEFAULT_DB_OPTIONS,realtime:DEFAULT_REALTIME_OPTIONS,auth:_objectSpread2(_objectSpread2({},DEFAULT_AUTH_OPTIONS),{},{storageKey:Xr}),global:DEFAULT_GLOBAL_OPTIONS},Ca=applySettingDefaults(ts??{},Na);if(this.storageKey=(is=Ca.auth.storageKey)!==null&&is!==void 0?is:"",this.headers=(cs=Ca.global.headers)!==null&&cs!==void 0?cs:{},Ca.accessToken)this.accessToken=Ca.accessToken,this.auth=new Proxy({},{get:(Ia,Ma)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(Ma)} is not possible`)}});else{var Aa;this.auth=this._initSupabaseAuthClient((Aa=Ca.auth)!==null&&Aa!==void 0?Aa:{},this.headers,Ca.global.fetch)}this.fetch=fetchWithAuth($,this._getAccessToken.bind(this),Ca.global.fetch),this.realtime=this._initRealtimeClient(_objectSpread2({headers:this.headers,accessToken:this._getAccessToken.bind(this)},Ca.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(Ia=>this.realtime.setAuth(Ia)).catch(Ia=>console.warn("Failed to set initial Realtime auth token:",Ia)),this.rest=new PostgrestClient(new URL("rest/v1",Kr).href,{headers:this.headers,schema:Ca.db.schema,fetch:this.fetch,timeout:Ca.db.timeout,urlLengthLimit:Ca.db.urlLengthLimit}),this.storage=new StorageClient(this.storageUrl.href,this.headers,this.fetch,ts==null?void 0:ts.storage),Ca.accessToken||this._listenForAuthEvents()}get functions(){return new FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}from(es){return this.rest.from(es)}schema(es){return this.rest.schema(es)}rpc(es,$={},ts={head:!1,get:!1,count:void 0}){return this.rest.rpc(es,$,ts)}channel(es,$={config:{}}){return this.realtime.channel(es,$)}getChannels(){return this.realtime.getChannels()}removeChannel(es){return this.realtime.removeChannel(es)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getAccessToken(){var es=this,$,ts;if(es.accessToken)return await es.accessToken();const{data:is}=await es.auth.getSession();return($=(ts=is.session)===null||ts===void 0?void 0:ts.access_token)!==null&&$!==void 0?$:es.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:es,persistSession:$,detectSessionInUrl:ts,storage:is,userStorage:cs,storageKey:Kr,flowType:Xr,lock:Na,debug:Ca,throwOnError:Aa},Ia,Ma){const Pa={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new SupabaseAuthClient({url:this.authUrl.href,headers:_objectSpread2(_objectSpread2({},Pa),Ia),storageKey:Kr,autoRefreshToken:es,persistSession:$,detectSessionInUrl:ts,storage:is,userStorage:cs,flowType:Xr,lock:Na,debug:Ca,throwOnError:Aa,fetch:Ma,hasCustomAuthorizationHeader:Object.keys(this.headers).some(La=>La.toLowerCase()==="authorization")})}_initRealtimeClient(es){return new RealtimeClient(this.realtimeUrl.href,_objectSpread2(_objectSpread2({},es),{},{params:_objectSpread2(_objectSpread2({},{apikey:this.supabaseKey}),es==null?void 0:es.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((es,$)=>{this._handleTokenChanged(es,"CLIENT",$==null?void 0:$.access_token)})}_handleTokenChanged(es,$,ts){(es==="TOKEN_REFRESHED"||es==="SIGNED_IN")&&this.changedAccessToken!==ts?(this.changedAccessToken=ts,this.realtime.setAuth(ts)):es==="SIGNED_OUT"&&(this.realtime.setAuth(),$=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}};const createClient=(es,$,ts)=>new SupabaseClient(es,$,ts);function shouldShowDeprecationWarning(){if(typeof window<"u")return!1;const es=globalThis.process;if(!es)return!1;const $=es.version;if($==null)return!1;const ts=$.match(/^v(\d+)\./);return ts?parseInt(ts[1],10)<=18:!1}shouldShowDeprecationWarning()&&console.warn("⚠️ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217");const RING_LIMIT=200,ring=[],counts={};function callerFromStack(){var $;const es=(($=new Error().stack)==null?void 0:$.split(`
711
711
  `))??[];for(let ts=2;ts<es.length;ts++){const is=es[ts];if(is&&!is.includes("auth-log.ts")&&!is.includes("supabase.ts"))return is.trim()}}function authLog(es,$,ts){const is={ts:Date.now(),method:es,caller:callerFromStack(),detail:$};ring.push(is),ring.length>RING_LIMIT&&ring.shift(),counts[es]=(counts[es]??0)+1,console.log(`[auth] ${es}${$?` ${$}`:""}${is.caller?` ← ${is.caller}`:""}`)}const ROLLUP_MS=6e4;let lastRollup=Date.now();setInterval(()=>{const es=Date.now(),$=ring.filter(is=>es-is.ts<ROLLUP_MS);if($.length===0)return;const ts={};for(const is of $)ts[is.method]=(ts[is.method]??0)+1;console.log(`[auth] rollup last 60s: ${$.length} calls`,ts,`(total since load: ${Object.values(counts).reduce((is,cs)=>is+cs,0)})`),lastRollup=es},3e4);typeof window<"u"&&(window.__authLog={ring:()=>ring.slice(),counts:()=>({...counts}),sinceRollup:()=>Date.now()-lastRollup});function readRuntimeConfig(es=globalThis){const $=es.__RM_CONFIG;if(!$||typeof $!="object")return;const{supabaseUrl:ts,supabaseAnonKey:is}=$;return{supabaseUrl:typeof ts=="string"&&ts?ts:void 0,supabaseAnonKey:typeof is=="string"&&is?is:void 0}}function resolveSupabaseConfig(es,$){return{url:(es==null?void 0:es.supabaseUrl)??$.url,anonKey:(es==null?void 0:es.supabaseAnonKey)??$.anonKey}}const runtimeConfig=Object.freeze(Object.defineProperty({__proto__:null,readRuntimeConfig,resolveSupabaseConfig},Symbol.toStringTag,{value:"Module"})),{url:supabaseUrl,anonKey:supabaseAnonKey}=resolveSupabaseConfig(readRuntimeConfig(),{url:void 0,anonKey:void 0});if(!supabaseUrl||!supabaseAnonKey)throw new Error("Missing Supabase config: no window.__RM_CONFIG stamped by the server and no VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY baked at build time.");const g$1=globalThis;function maskJwt(es){return es?`${es.slice(0,6)}…${es.slice(-4)} (len=${es.length})`:"<none>"}let cachedToken=null;const EXPIRY_MARGIN_S=60;function getCachedAccessToken(){if(!cachedToken)return null;const es=Math.floor(Date.now()/1e3);return cachedToken.expiresAt-es<=EXPIRY_MARGIN_S?null:cachedToken.accessToken}function buildClient(){const es=createClient(supabaseUrl,supabaseAnonKey,{auth:{flowType:"implicit"}});return g$1.__rmSupabaseAuthSubscribed||(g$1.__rmSupabaseAuthSubscribed=!0,es.auth.onAuthStateChange(($,ts)=>{ts!=null&&ts.access_token&&ts.expires_at?cachedToken={accessToken:ts.access_token,expiresAt:ts.expires_at}:cachedToken=null,authLog("onAuthStateChange:event",`${$} access=${maskJwt(ts==null?void 0:ts.access_token)} expires_at=${(ts==null?void 0:ts.expires_at)??"n/a"}`)})),es}const realClient=g$1.__rmSupabaseClient??(g$1.__rmSupabaseClient=buildClient()),realAuth=realClient.auth,watched=new Set(["getSession","refreshSession","signInWithPassword","signInWithOAuth","signUp","signOut","resetPasswordForEmail","updateUser","getUser"]);let currentDetail;function withAuthContext(es,$){const ts=currentDetail;currentDetail=es;try{return $()}finally{currentDetail=ts}}const wrappedAuth=new Proxy(realAuth,{get(es,$,ts){const is=Reflect.get(es,$,ts);return typeof is!="function"||!watched.has(String($))?is:(...cs)=>(authLog(String($),currentDetail),is.apply(es,cs))}}),supabase=new Proxy(realClient,{get(es,$,ts){return $==="auth"?wrappedAuth:Reflect.get(es,$,ts)}}),scriptRel="modulepreload",assetsURL=function(es){return"/"+es},seen={},__vitePreload=function($,ts,is){let cs=Promise.resolve();if(ts&&ts.length>0){let Xr=function(Aa){return Promise.all(Aa.map(Ia=>Promise.resolve(Ia).then(Ma=>({status:"fulfilled",value:Ma}),Ma=>({status:"rejected",reason:Ma}))))};document.getElementsByTagName("link");const Na=document.querySelector("meta[property=csp-nonce]"),Ca=(Na==null?void 0:Na.nonce)||(Na==null?void 0:Na.getAttribute("nonce"));cs=Xr(ts.map(Aa=>{if(Aa=assetsURL(Aa),Aa in seen)return;seen[Aa]=!0;const Ia=Aa.endsWith(".css"),Ma=Ia?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${Aa}"]${Ma}`))return;const Pa=document.createElement("link");if(Pa.rel=Ia?"stylesheet":scriptRel,Ia||(Pa.as="script"),Pa.crossOrigin="",Pa.href=Aa,Ca&&Pa.setAttribute("nonce",Ca),document.head.appendChild(Pa),Ia)return new Promise((La,Fa)=>{Pa.addEventListener("load",La),Pa.addEventListener("error",()=>Fa(new Error(`Unable to preload CSS for ${Aa}`)))})}))}function Kr(Xr){const Na=new Event("vite:preloadError",{cancelable:!0});if(Na.payload=Xr,window.dispatchEvent(Na),!Na.defaultPrevented)throw Xr}return cs.then(Xr=>{for(const Na of Xr||[])Na.status==="rejected"&&Kr(Na.reason);return $().catch(Kr)})},SOCIAL_AUTH_PROVIDERS=[{id:"google",label:"Google"},{id:"github",label:"GitHub"}];function safeNext(es){return!es||!es.startsWith("/")||es.startsWith("//")?null:es}function buildAuthConfirmUrl(es,$){const ts=new URL("/auth/confirm",es),is=safeNext($);return is&&ts.searchParams.set("next",is),ts.toString()}function parseEnabledSocialAuthProviders(es){if(!es||typeof es!="object")return[];const $=es.external;if(!$||typeof $!="object")return[];const ts=$;return SOCIAL_AUTH_PROVIDERS.filter(({id:is})=>ts[is]===!0).map(({id:is})=>is)}async function fetchEnabledSocialAuthProviders(es){const{readRuntimeConfig:$,resolveSupabaseConfig:ts}=await __vitePreload(async()=>{const{readRuntimeConfig:Kr,resolveSupabaseConfig:Xr}=await Promise.resolve().then(()=>runtimeConfig);return{readRuntimeConfig:Kr,resolveSupabaseConfig:Xr}},[]),{url:is,anonKey:cs}=ts($(),{url:void 0,anonKey:void 0});if(!is||!cs)return[];try{const Kr=await fetch(`${is.replace(/\/$/,"")}/auth/v1/settings`,{headers:{apikey:cs},signal:es});return Kr.ok?parseEnabledSocialAuthProviders(await Kr.json()):[]}catch{return[]}}function oauthCallbackError(es){if(!es)return null;const $=new URLSearchParams(es.startsWith("#")?es.slice(1):es),ts=$.get("error_code")??$.get("error");return ts?ts==="access_denied"?"Sign-in was cancelled.":ts.includes("email")?"The provider did not return a verified email address. Verify an email with the provider and try again.":"Social sign-in could not be completed. Please try again.":null}async function signInWithSocialProvider(es,$,ts,is){const{error:cs}=await es.signInWithOAuth({provider:$,options:{redirectTo:buildAuthConfirmUrl(ts,is)}});if(cs)throw cs}const AuthContext=reactExports.createContext(null);function AuthProvider({children:es}){const[$,ts]=reactExports.useState(null),[is,cs]=reactExports.useState(null),[Kr,Xr]=reactExports.useState(!0);reactExports.useEffect(()=>{supabase.auth.getSession().then(({data:{session:Fa}})=>{cs(Fa),ts((Fa==null?void 0:Fa.user)??null),Fa!=null&&Fa.access_token&&supabase.realtime.setAuth(Fa.access_token),Xr(!1)});const{data:{subscription:La}}=supabase.auth.onAuthStateChange((Fa,Ba)=>{cs(Ba),ts((Ba==null?void 0:Ba.user)??null),Ba!=null&&Ba.access_token&&supabase.realtime.setAuth(Ba.access_token)});return()=>La.unsubscribe()},[]);const Na=reactExports.useCallback(async(La,Fa)=>{const{error:Ba}=await supabase.auth.signInWithPassword({email:La,password:Fa});if(Ba)throw Ba},[]),Ca=reactExports.useCallback(async(La,Fa)=>{await signInWithSocialProvider(supabase.auth,La,window.location.origin,Fa)},[]),Aa=reactExports.useCallback(async(La,Fa,Ba)=>{const qa=buildAuthConfirmUrl(window.location.origin,Ba),{data:za,error:Va}=await supabase.auth.signUp({email:La,password:Fa,options:{emailRedirectTo:qa}});if(Va)throw Va;const Ga=!za.session&&!!za.user&&Array.isArray(za.user.identities)&&za.user.identities.length===0;return{needsConfirmation:!za.session&&!Ga,alreadyRegistered:Ga}},[]),Ia=reactExports.useCallback(async()=>{const{error:La}=await supabase.auth.signOut();if(La)throw La},[]),Ma=reactExports.useCallback(async La=>{const{error:Fa}=await supabase.auth.resetPasswordForEmail(La,{redirectTo:`${window.location.origin}/auth/confirm`});if(Fa)throw Fa},[]),Pa=reactExports.useCallback(async La=>{const{error:Fa}=await supabase.auth.updateUser({password:La});if(Fa)throw Fa},[]);return reactExports.createElement(AuthContext.Provider,{value:{user:$,session:is,loading:Kr,signIn:Na,signInWithProvider:Ca,signUp:Aa,signOut:Ia,resetPassword:Ma,updatePassword:Pa}},es)}function useAuth(){const es=reactExports.useContext(AuthContext);if(!es)throw new Error("useAuth must be used within AuthProvider");return es}function Skeleton({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"skeleton",className:cn$1("bg-accent animate-pulse rounded-md",es),...$})}function AuthGuard(){const{session:es,loading:$}=useAuth();return $?jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-1/2"})]})}):es?jsxRuntimeExports.jsx(Outlet,{}):jsxRuntimeExports.jsx(Navigate,{to:"/login",replace:!0})}class ApiError extends Error{constructor($,ts,is){super(ts),this.statusCode=$,this.code=is,this.name="ApiError"}}const DEFAULT_TIMEOUT_MS=2e4;function getBaseUrl(){return""}async function api(es,$={}){const is=`${getBaseUrl()}${es}`,cs={"Content-Type":"application/json",...$.headers};let Kr=getCachedAccessToken();if(!Kr){const{data:{session:Pa}}=await withAuthContext(`for ${$.method??"GET"} ${es}`,()=>supabase.auth.getSession());Kr=(Pa==null?void 0:Pa.access_token)??null}Kr&&(cs.Authorization=`Bearer ${Kr}`);const Xr=$.timeoutMs??DEFAULT_TIMEOUT_MS,Na=Xr>0?new AbortController:null,Ca=Na!=null?setTimeout(()=>Na.abort(),Xr):null;let Aa;try{Aa=await fetch(is,{method:$.method??"GET",headers:cs,body:$.body?JSON.stringify($.body):void 0,signal:Na==null?void 0:Na.signal})}catch(Pa){throw Na!=null&&Na.signal.aborted?new ApiError(0,`Request timed out after ${Xr}ms: ${$.method??"GET"} ${es}`,"TIMEOUT"):Pa}finally{Ca!=null&&clearTimeout(Ca)}if(Aa.status===401)throw await supabase.auth.signOut(),new ApiError(401,"Session expired");let Ia;const Ma=Aa.headers.get("content-type");if(Ma!=null&&Ma.includes("application/json")?Ia=await Aa.json():Ia=await Aa.text(),!Aa.ok){const Pa=Ia&&typeof Ia=="object"?Ia:null,La=Pa!=null&&Pa.error?typeof Pa.error=="string"?Pa.error:JSON.stringify(Pa.error):`HTTP ${Aa.status}`,Fa=Pa!=null&&Pa.code&&typeof Pa.code=="string"?Pa.code:void 0;throw new ApiError(Aa.status,La,Fa)}return Ia}const apiGet=es=>api(es),apiPost=(es,$)=>api(es,{method:"POST",body:$}),apiPut=(es,$)=>api(es,{method:"PUT",body:$}),apiPatch=(es,$)=>api(es,{method:"PATCH",body:$}),apiDelete=es=>api(es,{method:"DELETE"});function getOrgs(){return apiGet("/api/orgs")}function getOrg(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}`)}function getProfile(){return apiGet("/api/profile")}async function setActiveOrg(es){return await apiPatch("/api/profile",{activeOrgId:es}),getProfile()}function createOrg(es){return apiPost("/api/orgs",es)}function updateOrg(es,$){return apiPatch(`/api/orgs/${encodeURIComponent(es)}`,$)}function listMembers(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/members`)}function updateMemberRole(es,$,ts){return apiPatch(`/api/orgs/${encodeURIComponent(es)}/members/${encodeURIComponent($)}`,{role:ts})}function removeMember(es,$){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/members/${encodeURIComponent($)}`)}function transferOwnership(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/transfer`,{newOwnerId:$})}function listTeams(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/teams`)}function createTeam(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/teams`,$)}function updateTeam(es,$,ts){return apiPatch(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}`,ts)}function deleteTeam(es,$){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}`)}function addTeamMember(es,$,ts){return apiPost(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/members`,{userId:ts})}function removeTeamMember(es,$,ts){return apiDelete(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/members/${encodeURIComponent(ts)}`)}function listInvitations(es){return apiGet(`/api/orgs/${encodeURIComponent(es)}/invitations`)}function createInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations`,$)}function revokeInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations/${encodeURIComponent($)}/revoke`,{})}function resendInvitation(es,$){return apiPost(`/api/orgs/${encodeURIComponent(es)}/invitations/${encodeURIComponent($)}/resend`,{})}function previewInvitation(es){return apiGet(`/api/invitations/${encodeURIComponent(es)}`)}function acceptInvitation(es){return apiPost("/api/invitations/accept",es)}function getOrgActivity(es,$="7d"){return apiGet(`/api/orgs/${encodeURIComponent(es)}/activity?range=${encodeURIComponent($)}`)}function getTeamActivity(es,$,ts="7d"){return apiGet(`/api/orgs/${encodeURIComponent(es)}/teams/${encodeURIComponent($)}/activity?range=${encodeURIComponent(ts)}`)}function deleteOrg(es){return apiDelete(`/api/orgs/${encodeURIComponent(es)}`)}function useActiveOrg(){const{session:es}=useAuth(),$=!!es,ts=useQuery({queryKey:["profile"],queryFn:getProfile,enabled:$}),is=useQuery({queryKey:["orgs"],queryFn:getOrgs,enabled:$});return{activeOrg:reactExports.useMemo(()=>{var Na;const Kr=(Na=ts.data)==null?void 0:Na.activeOrgId;return Kr?(is.data??[]).find(Ca=>Ca.id===Kr)??null:null},[ts.data,is.data]),orgs:is.data??[],profile:ts.data??null,isLoading:ts.isLoading||is.isLoading,error:ts.error??is.error??null}}function useSetActiveOrg(){const es=useQueryClient();return useMutation({mutationFn:$=>setActiveOrg($),onSuccess:()=>{es.invalidateQueries({queryKey:["profile"]}),es.invalidateQueries({queryKey:["orgs"]}),es.invalidateQueries({queryKey:["sessions"]}),es.invalidateQueries({queryKey:["insights"]}),es.invalidateQueries({queryKey:["projects"]}),es.invalidateQueries({queryKey:["activity"]}),es.invalidateQueries({queryKey:["analytics"]})}})}function OrgAdminGuard({children:es}){return useActiveOrg(),jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}var t=typeof window<"u"?window:void 0,e=typeof globalThis<"u"?globalThis:t;typeof self>"u"&&(e.self=e),typeof File>"u"&&(e.File=function(){});var i=e==null?void 0:e.navigator,r=e==null?void 0:e.document,s=e==null?void 0:e.location,n=e==null?void 0:e.fetch,o=e!=null&&e.XMLHttpRequest&&"withCredentials"in new e.XMLHttpRequest?e.XMLHttpRequest:void 0,a=e==null?void 0:e.AbortController,l=e==null?void 0:e.CompressionStream,u=i==null?void 0:i.userAgent,h=t??{},d="1.372.5",v={DEBUG:!1,LIB_VERSION:d,LIB_NAME:"web",JS_SDK_VERSION:d};function c(es,$,ts,is,cs,Kr,Xr){try{var Na=es[Kr](Xr),Ca=Na.value}catch(Aa){return void ts(Aa)}Na.done?$(Ca):Promise.resolve(Ca).then(is,cs)}function p(es){return function(){var $=this,ts=arguments;return new Promise((function(is,cs){var Kr=es.apply($,ts);function Xr(Ca){c(Kr,is,cs,Xr,Na,"next",Ca)}function Na(Ca){c(Kr,is,cs,Xr,Na,"throw",Ca)}Xr(void 0)}))}}function f(){return f=Object.assign?Object.assign.bind():function(es){for(var $=1;arguments.length>$;$++){var ts=arguments[$];for(var is in ts)({}).hasOwnProperty.call(ts,is)&&(es[is]=ts[is])}return es},f.apply(null,arguments)}function _(es,$){if(es==null)return{};var ts={};for(var is in es)if({}.hasOwnProperty.call(es,is)){if($.indexOf(is)!==-1)continue;ts[is]=es[is]}return ts}function g(){return g=p((function*(es,$,ts){$===void 0&&($=!0);try{var is=new CompressionStream("gzip"),cs=is.writable.getWriter(),Kr=cs.write(new TextEncoder().encode(es)).then((()=>cs.close())).catch((function(){var Ca=p((function*(Aa){try{yield cs.abort(Aa)}catch{}throw Aa}));return function(Aa){return Ca.apply(this,arguments)}})()),Xr=new Response(is.readable).blob(),[Na]=yield Promise.all([Xr,Kr]);return Na}catch(Ca){if(ts!=null&&ts.rethrow)throw Ca;return $&&console.error("Failed to gzip compress data",Ca),null}})),g.apply(this,arguments)}var m=["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","pinterest","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"],b=function(es,$){if($===void 0&&($=[]),!es)return!1;var ts=es.toLowerCase();return m.concat($).some((is=>{var cs=is.toLowerCase();return ts.indexOf(cs)!==-1}))},y=["$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"];function w(es,$){return es.indexOf($)!==-1}var x=function(es){return es.trim()},E=function(es){return es.replace(/^\$/,"")},S=Object.prototype,T=S.hasOwnProperty,k=S.toString,R=Array.isArray||function(es){return k.call(es)==="[object Array]"},P=es=>typeof es=="function",O=es=>es===Object(es)&&!R(es),I=es=>{if(O(es)){for(var $ in es)if(T.call(es,$))return!1;return!0}return!1},C=es=>es===void 0,F=es=>k.call(es)=="[object String]",A=es=>F(es)&&es.trim().length===0,M=es=>es===null,D=es=>C(es)||M(es),L=es=>k.call(es)=="[object Number]"&&es==es,U=es=>L(es)&&es>0,N=es=>k.call(es)==="[object Boolean]",j=es=>es instanceof FormData,z=es=>w(y,es);function B(es){return es===null||typeof es!="object"}function H(es,$){return{}.toString.call(es)==="[object "+$+"]"}function q(es){return typeof Event<"u"&&(function($,ts){try{return $ instanceof ts}catch{return!1}})(es,Event)}var V=[!0,"true",1,"1","yes"],W=es=>w(V,es),G=[!1,"false",0,"0","no"];function Y(es,$,ts,is,cs){return $>ts&&(is.warn("min cannot be greater than max."),$=ts),L(es)?es>ts?(is.warn(" cannot be greater than max: "+ts+". Using max value instead."),ts):$>es?(is.warn(" cannot be less than min: "+$+". Using min value instead."),$):es:(is.warn(" must be a number. using max or fallback. max: "+ts+", fallback: "+cs),Y(cs||ts,$,ts,is))}class J{constructor($){this.$t={},this.zt=$.zt,this.Ut=Y($.bucketSize,0,100,$.Gt),this.Wt=Y($.refillRate,0,this.Ut,$.Gt),this.Xt=Y($.refillInterval,0,864e5,$.Gt)}Jt($,ts){var is=Math.floor((ts-$.lastAccess)/this.Xt);is>0&&($.tokens=Math.min($.tokens+is*this.Wt,this.Ut),$.lastAccess=$.lastAccess+is*this.Xt)}consumeRateLimit($){var ts,is=Date.now(),cs=String($),Kr=this.$t[cs];return Kr?this.Jt(Kr,is):this.$t[cs]=Kr={tokens:this.Ut,lastAccess:is},Kr.tokens===0||(Kr.tokens--,Kr.tokens===0&&((ts=this.zt)==null||ts.call(this,$)),Kr.tokens===0)}stop(){this.$t={}}}var K,X,Q,Z="Mobile",tt="iOS",et="Android",it="Tablet",rt=et+" "+it,st="iPad",nt="Apple",ot=nt+" Watch",at="Safari",lt="BlackBerry",ut="Samsung",ht=ut+"Browser",dt=ut+" Internet",vt="Chrome",ct=vt+" OS",pt=vt+" "+tt,ft="Internet Explorer",_t=ft+" "+Z,gt="Opera",mt=gt+" Mini",bt="Edge",yt="Microsoft "+bt,wt="Firefox",xt=wt+" "+tt,Et="Nintendo",St="PlayStation",$t="Xbox",Tt=et+" "+Z,kt=Z+" "+at,Rt="Windows",Pt=Rt+" Phone",Ot="Nokia",It="Ouya",Ct="Generic",Ft=Ct+" "+Z.toLowerCase(),At=Ct+" "+it.toLowerCase(),Mt="Konqueror",Dt="(\\d+(\\.\\d+)?)",Lt=new RegExp("Version/"+Dt),Ut=new RegExp($t,"i"),Nt=new RegExp(St+" \\w+","i"),jt=new RegExp(Et+" \\w+","i"),zt=new RegExp(lt+"|PlayBook|BB10","i"),Bt={"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"},Ht=function(es,$){return $=$||"",w(es," OPR/")&&w(es,"Mini")?mt:w(es," OPR/")?gt:zt.test(es)?lt:w(es,"IE"+Z)||w(es,"WPDesktop")?_t:w(es,ht)?dt:w(es,bt)||w(es,"Edg/")?yt:w(es,"FBIOS")?"Facebook "+Z:w(es,"UCWEB")||w(es,"UCBrowser")?"UC Browser":w(es,"CriOS")?pt:w(es,"CrMo")||w(es,vt)?vt:w(es,et)&&w(es,at)?Tt:w(es,"FxiOS")?xt:w(es.toLowerCase(),Mt.toLowerCase())?Mt:((ts,is)=>is&&w(is,nt)||(function(cs){return w(cs,at)&&!w(cs,vt)&&!w(cs,et)})(ts))(es,$)?w(es,Z)?kt:at:w(es,wt)?wt:w(es,"MSIE")||w(es,"Trident/")?ft:w(es,"Gecko")?wt:""},qt={[_t]:[new RegExp("rv:"+Dt)],[yt]:[new RegExp(bt+"?\\/"+Dt)],[vt]:[new RegExp("("+vt+"|CrMo)\\/"+Dt)],[pt]:[new RegExp("CriOS\\/"+Dt)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Dt)],[at]:[Lt],[kt]:[Lt],[gt]:[new RegExp("(Opera|OPR)\\/"+Dt)],[wt]:[new RegExp(wt+"\\/"+Dt)],[xt]:[new RegExp("FxiOS\\/"+Dt)],[Mt]:[new RegExp("Konqueror[:/]?"+Dt,"i")],[lt]:[new RegExp(lt+" "+Dt),Lt],[Tt]:[new RegExp("android\\s"+Dt,"i")],[dt]:[new RegExp(ht+"\\/"+Dt)],[ft]:[new RegExp("(rv:|MSIE )"+Dt)],Mozilla:[new RegExp("rv:"+Dt)]},Vt=function(es,$){var ts=Ht(es,$),is=qt[ts];if(C(is))return null;for(var cs=0;is.length>cs;cs++){var Kr=es.match(is[cs]);if(Kr)return parseFloat(Kr[Kr.length-2])}return null},Wt=[[new RegExp($t+"; "+$t+" (.*?)[);]","i"),es=>[$t,es&&es[1]||""]],[new RegExp(Et,"i"),[Et,""]],[new RegExp(St,"i"),[St,""]],[zt,[lt,""]],[new RegExp(Rt,"i"),(es,$)=>{if(/Phone/.test($)||/WPDesktop/.test($))return[Pt,""];if(new RegExp(Z).test($)&&!/IEMobile\b/.test($))return[Rt+" "+Z,""];var ts=/Windows NT ([0-9.]+)/i.exec($);if(ts&&ts[1]){var is=Bt[ts[1]]||"";return/arm/i.test($)&&(is="RT"),[Rt,is]}return[Rt,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,es=>es&&es[3]?[tt,[es[3],es[4],es[5]||"0"].join(".")]:[tt,""]],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,es=>{var $="";return es&&es.length>=3&&($=C(es[2])?es[3]:es[2]),["watchOS",$]}],[new RegExp("("+et+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+et+")","i"),es=>es&&es[2]?[et,[es[2],es[3],es[4]||"0"].join(".")]:[et,""]],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,es=>{var $=["Mac OS X",""];return es&&es[1]&&($[1]=[es[1],es[2],es[3]||"0"].join(".")),$}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[ct,""]],[/Linux|debian/i,["Linux",""]]],Gt=function(es){return jt.test(es)?Et:Nt.test(es)?St:Ut.test(es)?$t:new RegExp(It,"i").test(es)?It:new RegExp("("+Pt+"|WPDesktop)","i").test(es)?Pt:/iPad/.test(es)?st:/iPod/.test(es)?"iPod Touch":/iPhone/.test(es)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(es)?ot:zt.test(es)?lt:/(kobo)\s(ereader|touch)/i.test(es)?"Kobo":new RegExp(Ot,"i").test(es)?Ot:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(es)||/(kf[a-z]+)( bui|\)).+silk\//i.test(es)?"Kindle Fire":/(Android|ZTE)/i.test(es)?new RegExp(Z).test(es)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(es)||/pixel[\daxl ]{1,6}/i.test(es)&&!/pixel c/i.test(es)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(es)||/lmy47v/i.test(es)&&!/QTAQZ3/i.test(es)?et:rt:new RegExp("(pda|"+Z+")","i").test(es)?Ft:new RegExp(it,"i").test(es)&&!new RegExp(it+" pc","i").test(es)?At:""},Yt=es=>es instanceof Error,Jt={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}},Kt=Jt.info;function Xt(es){if(N(es))return{boolValue:es};if(typeof es=="number")return Number.isFinite(es)?Number.isInteger(es)?{intValue:es}:{doubleValue:es}:{stringValue:String(es)};if(typeof es=="string")return{stringValue:es};if(R(es))return{arrayValue:{values:es.map(($=>Xt($)))}};try{return{stringValue:JSON.stringify(es)}}catch{return{stringValue:String(es)}}}function Qt(es){var $=[];for(var ts in es){var is=es[ts];M(is)||C(is)||$.push({key:ts,value:Xt(is)})}return $}function Zt(es){var $=globalThis._posthogChunkIds;if($){var ts=Object.keys($);return Q&&ts.length===X||(X=ts.length,Q=ts.reduce(((is,cs)=>{K||(K={});var Kr=K[cs];if(Kr)is[Kr[0]]=Kr[1];else for(var Xr=es(cs),Na=Xr.length-1;Na>=0;Na--){var Ca=Xr[Na],Aa=Ca==null?void 0:Ca.filename,Ia=$[cs];if(Aa&&Ia){is[Aa]=Ia,K[cs]=[Aa,Ia];break}}return is}),{})),Q}}class te{constructor($,ts,is){is===void 0&&(is=[]),this.coercers=$,this.stackParser=ts,this.modifiers=is}buildFromUnknown($,ts){ts===void 0&&(ts={});var is=ts&&ts.mechanism||{handled:!0,type:"generic"},cs=this.buildCoercingContext(is,ts,0).apply($),Kr=this.buildParsingContext(ts),Xr=this.parseStacktrace(cs,Kr);return{$exception_list:this.convertToExceptionList(Xr,is),$exception_level:"error"}}modifyFrames($){var ts=this;return p((function*(){for(var is of $)is.stacktrace&&is.stacktrace.frames&&R(is.stacktrace.frames)&&(is.stacktrace.frames=yield ts.applyModifiers(is.stacktrace.frames));return $}))()}coerceFallback($){var ts;return{type:"Error",value:"Unknown error",stack:(ts=$.syntheticException)==null?void 0:ts.stack,synthetic:!0}}parseStacktrace($,ts){var is,cs;return $.cause!=null&&(is=this.parseStacktrace($.cause,ts)),$.stack!=""&&$.stack!=null&&(cs=this.applyChunkIds(this.stackParser($.stack,$.synthetic?ts.skipFirstLines:0),ts.chunkIdMap)),f({},$,{cause:is,stack:cs})}applyChunkIds($,ts){return $.map((is=>(is.filename&&ts&&(is.chunk_id=ts[is.filename]),is)))}applyCoercers($,ts){for(var is of this.coercers)if(is.match($))return is.coerce($,ts);return this.coerceFallback(ts)}applyModifiers($){var ts=this;return p((function*(){var is=$;for(var cs of ts.modifiers)is=yield cs(is);return is}))()}convertToExceptionList($,ts){var is,cs,Kr,Xr={type:$.type,value:$.value,mechanism:{type:(is=ts.type)!==null&&is!==void 0?is:"generic",handled:(cs=ts.handled)===null||cs===void 0||cs,synthetic:(Kr=$.synthetic)!==null&&Kr!==void 0&&Kr}};$.stack&&(Xr.stacktrace={type:"raw",frames:$.stack});var Na=[Xr];return $.cause!=null&&Na.push(...this.convertToExceptionList($.cause,f({},ts,{handled:!0}))),Na}buildParsingContext($){var ts;return{chunkIdMap:Zt(this.stackParser),skipFirstLines:(ts=$.skipFirstLines)!==null&&ts!==void 0?ts:1}}buildCoercingContext($,ts,is){is===void 0&&(is=0);var cs=(Kr,Xr)=>{if(4>=Xr){var Na=this.buildCoercingContext($,ts,Xr);return this.applyCoercers(Kr,Na)}};return f({},ts,{syntheticException:is==0?ts.syntheticException:void 0,mechanism:$,apply:Kr=>cs(Kr,is),next:Kr=>cs(Kr,is+1)})}}var ee="?";function ie(es,$,ts,is,cs){var Kr={platform:es,filename:$,function:ts==="<anonymous>"?ee:ts,in_app:!0};return C(is)||(Kr.lineno=is),C(cs)||(Kr.colno=cs),Kr}var re=(es,$)=>{var ts=es.indexOf("safari-extension")!==-1,is=es.indexOf("safari-web-extension")!==-1;return ts||is?[es.indexOf("@")!==-1?es.split("@")[0]:ee,ts?"safari-extension:"+$:"safari-web-extension:"+$]:[es,$]},se=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ne=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,oe=/\((\S*)(?::(\d+))(?::(\d+))\)/,ae=(es,$)=>{var ts=se.exec(es);if(ts){var[,is,cs,Kr]=ts;return ie($,is,ee,+cs,+Kr)}var Xr=ne.exec(es);if(Xr){if(Xr[2]&&Xr[2].indexOf("eval")===0){var Na=oe.exec(Xr[2]);Na&&(Xr[2]=Na[1],Xr[3]=Na[2],Xr[4]=Na[3])}var[Ca,Aa]=re(Xr[1]||ee,Xr[2]);return ie($,Aa,Ca,Xr[3]?+Xr[3]:void 0,Xr[4]?+Xr[4]:void 0)}},le=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ue=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,he=(es,$)=>{var ts=le.exec(es);if(ts){if(ts[3]&&ts[3].indexOf(" > eval")>-1){var is=ue.exec(ts[3]);is&&(ts[1]=ts[1]||"eval",ts[3]=is[1],ts[4]=is[2],ts[5]="")}var cs=ts[3],Kr=ts[1]||ee;return[Kr,cs]=re(Kr,cs),ie($,cs,Kr,ts[4]?+ts[4]:void 0,ts[5]?+ts[5]:void 0)}},de=/\(error: (.*)\)/;class ve{match($){return this.isDOMException($)||this.isDOMError($)}coerce($,ts){var is=F($.stack);return{type:this.getType($),value:this.getValue($),stack:is?$.stack:void 0,cause:$.cause?ts.next($.cause):void 0,synthetic:!1}}getType($){return this.isDOMError($)?"DOMError":"DOMException"}getValue($){var ts=$.name||(this.isDOMError($)?"DOMError":"DOMException");return $.message?ts+": "+$.message:ts}isDOMException($){return H($,"DOMException")}isDOMError($){return H($,"DOMError")}}class ce{match($){return(ts=>ts instanceof Error)($)}coerce($,ts){return{type:this.getType($),value:this.getMessage($,ts),stack:this.getStack($),cause:$.cause?ts.next($.cause):void 0,synthetic:!1}}getType($){return $.name||$.constructor.name}getMessage($,ts){var is=$.message;return String(is.error&&typeof is.error.message=="string"?is.error.message:is)}getStack($){return $.stacktrace||$.stack||void 0}}class pe{constructor(){}match($){return H($,"ErrorEvent")&&$.error!=null}coerce($,ts){var is;return ts.apply($.error)||{type:"ErrorEvent",value:$.message,stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}var fe=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class _e{match($){return typeof $=="string"}coerce($,ts){var is,[cs,Kr]=this.getInfos($);return{type:cs??"Error",value:Kr??$,stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}getInfos($){var ts="Error",is=$,cs=$.match(fe);return cs&&(ts=cs[1],is=cs[2]),[ts,is]}}var ge=["fatal","error","warning","log","info","debug"];function me(es,$){$===void 0&&($=40);var ts=Object.keys(es);if(ts.sort(),!ts.length)return"[object has no keys]";for(var is=ts.length;is>0;is--){var cs=ts.slice(0,is).join(", ");if($>=cs.length)return is===ts.length?cs:cs.length>$?cs.slice(0,$)+"...":cs}return""}class be{match($){return typeof $=="object"&&$!==null}coerce($,ts){var is,cs=this.getErrorPropertyFromObject($);return cs?ts.apply(cs):{type:this.getType($),value:this.getValue($),stack:(is=ts.syntheticException)==null?void 0:is.stack,level:this.isSeverityLevel($.level)?$.level:"error",synthetic:!0}}getType($){return q($)?$.constructor.name:"Error"}getValue($){if("name"in $&&typeof $.name=="string"){var ts="'"+$.name+"' captured as exception";return"message"in $&&typeof $.message=="string"&&(ts+=" with message: '"+$.message+"'"),ts}if("message"in $&&typeof $.message=="string")return $.message;var is=this.getObjectClassName($);return(is&&is!=="Object"?"'"+is+"'":"Object")+" captured as exception with keys: "+me($)}isSeverityLevel($){return F($)&&!A($)&&ge.indexOf($)>=0}getErrorPropertyFromObject($){for(var ts in $)if({}.hasOwnProperty.call($,ts)){var is=$[ts];if(Yt(is))return is}}getObjectClassName($){try{var ts=Object.getPrototypeOf($);return ts?ts.constructor.name:void 0}catch{return}}}class ye{match($){return q($)}coerce($,ts){var is,cs=$.constructor.name;return{type:cs,value:cs+" captured as exception with keys: "+me($),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}class we{match($){return B($)}coerce($,ts){var is;return{type:"Error",value:"Primitive value captured as exception: "+String($),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}}}class xe{match($){return H($,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection($)}isCustomEventWrappingRejection($){if(!q($))return!1;try{var ts=$.detail;return ts!=null&&typeof ts=="object"&&"reason"in ts}catch{return!1}}coerce($,ts){var is,cs=this.getUnhandledRejectionReason($);return B(cs)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(cs),stack:(is=ts.syntheticException)==null?void 0:is.stack,synthetic:!0}:ts.apply(cs)}getUnhandledRejectionReason($){try{if("reason"in $)return $.reason;if("detail"in $&&$.detail!=null&&typeof $.detail=="object"&&"reason"in $.detail)return $.detail.reason}catch{}return $}}var Ee="$message",Se="$timestamp",$e=new Set([Ee,Se]),Te={enabled:!0,max_bytes:32768};function ke(es){var $;return es?{enabled:($=es.enabled)!==null&&$!==void 0?$:Te.enabled,max_bytes:Pe(es.max_bytes,Te.max_bytes)}:f({},Te)}class Re{constructor($){this.Kt=[],this.Qt=0,this.Bt=ke($)}setConfig($){this.Bt=ke($),this.er()}add($){var ts=(function(cs){var Kr=(function(Ia){var Ma=new WeakSet;try{return JSON.stringify(Ia,((Pa,La)=>{if(typeof La=="bigint")return La.toString();if(typeof La!="function"&&typeof La!="symbol"){if(La instanceof Date)return La.toISOString();if(La instanceof Error)return{name:La.name,message:La.message,stack:La.stack};if(La&&typeof La=="object"){if(Ma.has(La))return"[Circular]";Ma.add(La)}return La}}))}catch{return}})(cs);if(Kr)try{var Xr=JSON.parse(Kr);if(!O(Xr))return;var Na=Xr,Ca=Na[Ee],Aa=Na[Se];return!F(Ca)||Ca.trim().length===0||!F(Aa)&&!L(Aa)?void 0:{step:Na,json:Kr}}catch{return}})($);if(ts){var is=(function(cs){if(typeof TextEncoder<"u")return new TextEncoder().encode(cs).length;for(var Kr=encodeURIComponent(cs),Xr=0,Na=0;Kr.length>Na;Na++)Kr[Na]==="%"?(Xr+=1,Na+=2):Xr+=1;return Xr})(ts.json);is>this.Bt.max_bytes||(this.Kt.push({step:ts.step,bytes:is}),this.Qt+=is,this.er())}}getAttachable(){return this.Kt.map(($=>$.step))}clear(){this.Kt=[],this.Qt=0}size(){return this.Kt.length}er(){for(;this.Qt>this.Bt.max_bytes&&this.Kt.length>0;){var $=this.Kt.shift();$&&(this.Qt-=$.bytes)}}}function Pe(es,$){if(!L(es)||es===1/0||es===-1/0)return $;var ts=Math.floor(es);return 0>ts?$:ts}var Oe=function(es,$){var{debugEnabled:ts}=$===void 0?{}:$,is={C(cs){if(t&&(v.DEBUG||h.POSTHOG_DEBUG||ts)&&!C(t.console)&&t.console){for(var Kr=("__rrweb_original__"in t.console[cs])?t.console[cs].__rrweb_original__:t.console[cs],Xr=arguments.length,Na=new Array(Xr>1?Xr-1:0),Ca=1;Xr>Ca;Ca++)Na[Ca-1]=arguments[Ca];Kr(es,...Na)}},info(){for(var cs=arguments.length,Kr=new Array(cs),Xr=0;cs>Xr;Xr++)Kr[Xr]=arguments[Xr];is.C("log",...Kr)},warn(){for(var cs=arguments.length,Kr=new Array(cs),Xr=0;cs>Xr;Xr++)Kr[Xr]=arguments[Xr];is.C("warn",...Kr)},error(){for(var cs=arguments.length,Kr=new Array(cs),Xr=0;cs>Xr;Xr++)Kr[Xr]=arguments[Xr];is.C("error",...Kr)},critical(){for(var cs=arguments.length,Kr=new Array(cs),Xr=0;cs>Xr;Xr++)Kr[Xr]=arguments[Xr];console.error(es,...Kr)},uninitializedWarning(cs){is.error("You must initialize PostHog before calling "+cs)},createLogger:(cs,Kr)=>Oe(es+" "+cs,Kr)};return is},Ie=Oe("[PostHog.js]"),Ce=Ie.createLogger,Fe=Ce("[ExternalScriptsLoader]"),Ae=(es,$,ts)=>{if(es.config.disable_external_dependency_loading)return Fe.warn($+" was requested but loading of external scripts is disabled."),ts("Loading of external scripts is disabled");var is=r==null?void 0:r.querySelectorAll("script");if(is){for(var cs,Kr=function(){if(is[Xr].src===$){var Ca=is[Xr];return Ca.__posthog_loading_callback_fired?{v:ts()}:(Ca.addEventListener("load",(Aa=>{Ca.__posthog_loading_callback_fired=!0,ts(void 0,Aa)})),Ca.onerror=Aa=>ts(Aa),{v:void 0})}},Xr=0;is.length>Xr;Xr++)if(cs=Kr())return cs.v}var Na=()=>{if(!r)return ts("document not found");var Ca=r.createElement("script");if(Ca.type="text/javascript",Ca.crossOrigin="anonymous",Ca.src=$,Ca.onload=Ma=>{Ca.__posthog_loading_callback_fired=!0,ts(void 0,Ma)},Ca.onerror=Ma=>ts(Ma),es.config.prepare_external_dependency_script&&(Ca=es.config.prepare_external_dependency_script(Ca)),!Ca)return ts("prepare_external_dependency_script returned null");if(es.config.external_scripts_inject_target==="head")r.head.appendChild(Ca);else{var Aa,Ia=r.querySelectorAll("body > script");Ia.length>0?(Aa=Ia[0].parentNode)==null||Aa.insertBefore(Ca,Ia[0]):r.body.appendChild(Ca)}};r!=null&&r.body?Na():r==null||r.addEventListener("DOMContentLoaded",Na)};h.__PosthogExtensions__=h.__PosthogExtensions__||{},h.__PosthogExtensions__.loadExternalDependency=(es,$,ts)=>{if($!=="remote-config"){var is;if(es.config.__preview_external_dependency_versioned_paths)is=es.requestRouter.endpointFor("assets","/static/"+es.version+"/"+$+".js");else{var cs="/static/"+$+".js?v="+es.version;if($==="toolbar"){var Kr=3e5;cs=cs+"&t="+Math.floor(Date.now()/Kr)*Kr}is=es.requestRouter.endpointFor("assets",cs)}Ae(es,is,ts)}else{var Xr=es.requestRouter.endpointFor("assets","/array/"+es.config.token+"/config.js");Ae(es,Xr,ts)}},h.__PosthogExtensions__.loadSiteApp=(es,$,ts)=>{var is=es.requestRouter.endpointFor("api",$);Ae(es,is,ts)};var Me="$people_distinct_id",De="$device_id",Le="__alias",Ue="__timers",Ne="$autocapture_disabled_server_side",je="$heatmaps_enabled_server_side",ze="$exception_capture_enabled_server_side",Be="$error_tracking_suppression_rules",He="$error_tracking_capture_extension_exceptions",qe="$web_vitals_enabled_server_side",Ve="$dead_clicks_enabled_server_side",We="$product_tours_enabled_server_side",Ge="$web_vitals_allowed_metrics",Ye="$session_recording_remote_config",Je="$replay_override_sampling",Ke="$replay_override_linked_flag",Xe="$replay_override_url_trigger",Qe="$replay_override_event_trigger",Ze="$sesid",ti="$session_is_sampled",ei="$enabled_feature_flags",ii="$active_feature_flags",ri="$early_access_features",si="$feature_flag_details",ni="$feature_flag_payloads",oi="$feature_flag_request_id",ai="$override_feature_flags",li="$override_feature_flag_payloads",ui="$stored_person_properties",hi="$stored_group_properties",di="$surveys",vi="$surveys_activated",ci="ph_product_tours",pi="$flag_call_reported",fi="$flag_call_reported_session_id",_i="$feature_flag_errors",gi="$feature_flag_evaluated_at",mi="$user_state",bi="$client_session_props",yi="$capture_rate_limit",wi="$initial_campaign_params",xi="$initial_referrer_info",Ei="$initial_person_info",Si="$epp",$i="__POSTHOG_TOOLBAR__",Ti="$posthog_cookieless",ki="$sdk_debug_extensions_init_method",Ri="$sdk_debug_extensions_init_time_ms",Pi="$sdk_debug_recording_script_not_loaded",Oi="PostHog loadExternalDependency extension not found.",Ii="on_reject",Ci="always",Fi="anonymous",Ai="identified",Mi="identified_only",Di="visibilitychange",Li="beforeunload",Ui="$pageview",Ni="$pageleave",ji="$identify",zi="$groupidentify";function Bi(es,$){R(es)&&es.forEach($)}function Hi(es,$){if(!D(es))if(R(es))es.forEach($);else if(j(es))es.forEach(((is,cs)=>$(is,cs)));else for(var ts in es)T.call(es,ts)&&$(es[ts],ts)}var qi=function(es){for(var $=arguments.length,ts=new Array($>1?$-1:0),is=1;$>is;is++)ts[is-1]=arguments[is];for(var cs of ts)for(var Kr in cs)cs[Kr]!==void 0&&(es[Kr]=cs[Kr]);return es};function Vi(es){for(var $=Object.keys(es),ts=$.length,is=new Array(ts);ts--;)is[ts]=[$[ts],es[$[ts]]];return is}var Wi=function(es){try{return es()}catch{return}},Gi=function(es){return function(){try{for(var $=arguments.length,ts=new Array($),is=0;$>is;is++)ts[is]=arguments[is];return es.apply(this,ts)}catch(cs){Ie.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Ie.critical(cs)}}},Yi=function(es){var $={};return Hi(es,(function(ts,is){(F(ts)&&ts.length>0||L(ts))&&($[is]=ts)})),$},Ji=["herokuapp.com","vercel.app","netlify.app"];function Ki(es){var $=es==null?void 0:es.hostname;if(!F($))return!1;var ts=$.split(".").slice(-2).join(".");for(var is of Ji)if(ts===is)return!1;return!0}function Xi(es,$,ts,is){var{capture:cs=!1,passive:Kr=!0}=is??{};es==null||es.addEventListener($,ts,{capture:cs,passive:Kr})}function Qi(es){return es.name==="ph_toolbar_internal"}Math.trunc||(Math.trunc=function(es){return 0>es?Math.ceil(es):Math.floor(es)}),Number.isInteger||(Number.isInteger=function(es){return L(es)&&isFinite(es)&&Math.floor(es)===es});class Zi{constructor($){if(this.bytes=$,$.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7($,ts,is,cs){if(!Number.isInteger($)||!Number.isInteger(ts)||!Number.isInteger(is)||!Number.isInteger(cs)||0>$||0>ts||0>is||0>cs||$>0xffffffffffff||ts>4095||is>1073741823||cs>4294967295)throw new RangeError("invalid field value");var Kr=new Uint8Array(16);return Kr[0]=$/Math.pow(2,40),Kr[1]=$/Math.pow(2,32),Kr[2]=$/Math.pow(2,24),Kr[3]=$/Math.pow(2,16),Kr[4]=$/Math.pow(2,8),Kr[5]=$,Kr[6]=112|ts>>>8,Kr[7]=ts,Kr[8]=128|is>>>24,Kr[9]=is>>>16,Kr[10]=is>>>8,Kr[11]=is,Kr[12]=cs>>>24,Kr[13]=cs>>>16,Kr[14]=cs>>>8,Kr[15]=cs,new Zi(Kr)}toString(){for(var $="",ts=0;this.bytes.length>ts;ts++)$=$+(this.bytes[ts]>>>4).toString(16)+(15&this.bytes[ts]).toString(16),ts!==3&&ts!==5&&ts!==7&&ts!==9||($+="-");if($.length!==36)throw new Error("Invalid UUIDv7 was generated");return $}clone(){return new Zi(this.bytes.slice(0))}equals($){return this.compareTo($)===0}compareTo($){for(var ts=0;16>ts;ts++){var is=this.bytes[ts]-$.bytes[ts];if(is!==0)return Math.sign(is)}return 0}}class tr{constructor(){this.I=0,this.S=0,this.k=new rr}generate(){var $=this.generateOrAbort();if(C($)){this.I=0;var ts=this.generateOrAbort();if(C(ts))throw new Error("Could not generate UUID after timestamp reset");return ts}return $}generateOrAbort(){var $=Date.now();if($>this.I)this.I=$,this.A();else{if(this.I>=$+1e4)return;this.S++,this.S>4398046511103&&(this.I++,this.A())}return Zi.fromFieldsV7(this.I,Math.trunc(this.S/Math.pow(2,30)),this.S&Math.pow(2,30)-1,this.k.nextUint32())}A(){this.S=1024*this.k.nextUint32()+(1023&this.k.nextUint32())}}var er,ir=es=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var $=0;es.length>$;$++)es[$]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return es};t&&!C(t.crypto)&&crypto.getRandomValues&&(ir=es=>crypto.getRandomValues(es));class rr{constructor(){this.T=new Uint32Array(8),this.N=1/0}nextUint32(){return this.T.length>this.N||(ir(this.T),this.N=0),this.T[this.N++]}}var sr=()=>nr().toString(),nr=()=>(er||(er=new tr)).generate(),or="",ar=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i,lr={R:()=>!!r,B(es){Ie.error("cookieStore error: "+es)},O(es){if(r){try{for(var $=es+"=",ts=r.cookie.split(";").filter((Kr=>Kr.length)),is=0;ts.length>is;is++){for(var cs=ts[is];cs.charAt(0)==" ";)cs=cs.substring(1,cs.length);if(cs.indexOf($)===0)return decodeURIComponent(cs.substring($.length,cs.length))}}catch{}return null}},Z(es){var $;try{$=JSON.parse(lr.O(es))||{}}catch{}return $},M(es,$,ts,is,cs){if(r)try{var Kr="",Xr="",Na=(function(Ia,Ma){if(Ma){var Pa=(function(Fa,Ba){if(Ba===void 0&&(Ba=r),or)return or;if(!Ba||["localhost","127.0.0.1"].includes(Fa))return"";for(var qa=Fa.split("."),za=Math.min(qa.length,8),Va="dmn_chk_"+sr();!or&&za--;){var Ga=qa.slice(za).join("."),Za=Va+"=1;domain=."+Ga+";path=/";Ba.cookie=Za+";max-age=3",Ba.cookie.includes(Va)&&(Ba.cookie=Za+";max-age=0",or=Ga)}return or})(Ia);if(!Pa){var La=(Fa=>{var Ba=Fa.match(ar);return Ba?Ba[0]:""})(Ia);La!==Pa&&Ie.info("Warning: cookie subdomain discovery mismatch",La,Pa),Pa=La}return Pa?"; domain=."+Pa:""}return""})(r.location.hostname,is);if(ts){var Ca=new Date;Ca.setTime(Ca.getTime()+864e5*ts),Kr="; expires="+Ca.toUTCString()}cs&&(Xr="; secure");var Aa=es+"="+encodeURIComponent(JSON.stringify($))+Kr+"; SameSite=Lax; path=/"+Na+Xr;return Aa.length>3686.4&&Ie.warn("cookieStore warning: large cookie, len="+Aa.length),r.cookie=Aa,Aa}catch{return}},F(es,$){if(r!=null&&r.cookie)try{lr.M(es,"",-1,$)}catch{return}}},ur=null,hr={R(){if(!M(ur))return ur;var es=!0;if(C(t))es=!1;else try{var $="__mplssupport__";hr.M($,"xyz"),hr.O($)!=='"xyz"'&&(es=!1),hr.F($)}catch{es=!1}return es||Ie.error("localStorage unsupported; falling back to cookie store"),ur=es,es},B(es){Ie.error("localStorage error: "+es)},O(es){try{return t==null?void 0:t.localStorage.getItem(es)}catch($){hr.B($)}return null},Z(es){try{return JSON.parse(hr.O(es))||{}}catch{}return null},M(es,$){try{t==null||t.localStorage.setItem(es,JSON.stringify($))}catch(ts){hr.B(ts)}},F(es){try{t==null||t.localStorage.removeItem(es)}catch($){hr.B($)}}},dr=[De,"distinct_id",Ze,ti,Si,Ei,mi],vr={},cr={R:()=>!0,B(es){Ie.error("memoryStorage error: "+es)},O:es=>vr[es]||null,Z:es=>vr[es]||null,M(es,$){vr[es]=$},F(es){delete vr[es]}},pr=null,fr={R(){if(!M(pr))return pr;if(pr=!0,C(t))pr=!1;else try{var es="__support__";fr.M(es,"xyz"),fr.O(es)!=='"xyz"'&&(pr=!1),fr.F(es)}catch{pr=!1}return pr},B(es){Ie.error("sessionStorage error: ",es)},O(es){try{return t==null?void 0:t.sessionStorage.getItem(es)}catch($){fr.B($)}return null},Z(es){try{return JSON.parse(fr.O(es))||null}catch{}return null},M(es,$){try{t==null||t.sessionStorage.setItem(es,JSON.stringify($))}catch(ts){fr.B(ts)}},F(es){try{t==null||t.sessionStorage.removeItem(es)}catch($){fr.B($)}}};class _r{constructor($){this._instance=$}get Bt(){return this._instance.config}get consent(){return this.rr()?0:this.ir}isOptedOut(){return this.Bt.cookieless_mode===Ci||this.isRejected()||this.consent===-1&&this.Bt.cookieless_mode===Ii}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===0}isRejected(){return this.consent===0||this.consent===-1&&this.Bt.opt_out_capturing_by_default}optInOut($){this.nr.M(this.sr,$?1:0,this.Bt.cookie_expiration,this.Bt.cross_subdomain_cookie,this.Bt.secure_cookie)}reset(){this.nr.F(this.sr,this.Bt.cross_subdomain_cookie)}get sr(){var{token:$,opt_out_capturing_cookie_prefix:ts,consent_persistence_name:is}=this._instance.config;return is||(ts?ts+$:"__ph_opt_in_out_"+$)}get ir(){var $=this.nr.O(this.sr);return W($)?1:w(G,$)?0:-1}get nr(){var $=this.Bt.opt_out_capturing_persistence_type,ts=$==="localStorage"?hr:lr;if(!this.ar||this.ar!==ts){this.ar=ts;var is=$==="localStorage"?lr:hr;is.O(this.sr)&&(this.ar.O(this.sr)||this.optInOut(W(is.O(this.sr))),is.F(this.sr,this.Bt.cross_subdomain_cookie))}return this.ar}rr(){return!!this.Bt.respect_dnt&&[i==null?void 0:i.doNotTrack,i==null?void 0:i.msDoNotTrack,h.doNotTrack].some(($=>W($)))}}var gr=Ce("[Dead Clicks]"),mr=()=>!0,br=es=>{var $,ts=!(($=es.instance.persistence)==null||!$.get_property(Ve)),is=es.instance.config.capture_dead_clicks;return N(is)?is:!!O(is)||ts};class yr{get lazyLoadedDeadClicksAutocapture(){return this.lr}constructor($,ts,is){this.instance=$,this.isEnabled=ts,this.onCapture=is,this.startIfEnabledOrStop()}onRemoteConfig($){"captureDeadClicks"in $&&(this.instance.persistence&&this.instance.persistence.register({[Ve]:$.captureDeadClicks}),this.startIfEnabledOrStop())}startIfEnabledOrStop(){this.isEnabled(this)?this.ur((()=>{this.hr()})):this.stop()}ur($){var ts,is;(ts=h.__PosthogExtensions__)!=null&&ts.initDeadClicksAutocapture&&$(),(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this.instance,"dead-clicks-autocapture",(cs=>{cs?gr.error("failed to load script",cs):$()}))}hr(){var $;if(r){if(!this.lr&&($=h.__PosthogExtensions__)!=null&&$.initDeadClicksAutocapture){var ts=O(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};ts.__onCapture=this.onCapture,this.lr=h.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,ts),this.lr.start(r),gr.info("starting...")}}else gr.error("`document` not found. Cannot start.")}stop(){this.lr&&(this.lr.stop(),this.lr=void 0,gr.info("stopping..."))}}var wr=Ce("[SegmentIntegration]"),xr="posthog-js";function Er(es,$){var{organization:ts,projectId:is,prefix:cs,severityAllowList:Kr=["error"],sendExceptionsToPostHog:Xr=!0}=$===void 0?{}:$;return Na=>{var Ca,Aa,Ia,Ma,Pa;if(Kr!=="*"&&!Kr.includes(Na.level)||!es.__loaded)return Na;Na.tags||(Na.tags={});var La=es.requestRouter.endpointFor("ui","/project/"+es.config.token+"/person/"+es.get_distinct_id());Na.tags["PostHog Person URL"]=La,es.sessionRecordingStarted()&&(Na.tags["PostHog Recording URL"]=es.get_session_replay_url({withTimestamp:!0}));var Fa,Ba=((Ca=Na.exception)==null?void 0:Ca.values)||[],qa=Ba.map((Va=>f({},Va,{stacktrace:Va.stacktrace?f({},Va.stacktrace,{type:"raw",frames:(Va.stacktrace.frames||[]).map((Ga=>f({},Ga,{platform:"web:javascript"})))}):void 0}))),za={$exception_message:((Aa=Ba[0])==null?void 0:Aa.value)||Na.message,$exception_type:(Ia=Ba[0])==null?void 0:Ia.type,$exception_level:Na.level,$exception_list:qa,$sentry_event_id:Na.event_id,$sentry_exception:Na.exception,$sentry_exception_message:((Ma=Ba[0])==null?void 0:Ma.value)||Na.message,$sentry_exception_type:(Pa=Ba[0])==null?void 0:Pa.type,$sentry_tags:Na.tags};return ts&&is&&(za.$sentry_url=(cs||"https://sentry.io/organizations/")+ts+"/issues/?project="+is+"&query="+Na.event_id),Xr&&((Fa=es.exceptions)==null||Fa.sendExceptionEvent(za)),Na}}class Sr{constructor($,ts,is,cs,Kr,Xr){this.name=xr,this.setupOnce=function(Na){Na(Er($,{organization:ts,projectId:is,prefix:cs,severityAllowList:Kr,sendExceptionsToPostHog:Xr==null||Xr}))}}}class $r{constructor($){this.cr=(ts,is,cs)=>{cs&&(cs.noSessionId||cs.activityTimeout||cs.sessionPastMaximumLength)&&(Ie.info("[PageViewManager] Session rotated, clearing pageview state",{sessionId:ts,changeReason:cs}),this.dr=void 0,this._instance.scrollManager.resetContext())},this._instance=$,this.vr()}vr(){var $;this.pr=($=this._instance.sessionManager)==null?void 0:$.onSessionId(this.cr)}destroy(){var $;($=this.pr)==null||$.call(this),this.pr=void 0}doPageView($,ts){var is,cs=this.gr($,ts);return this.dr={pathname:(is=t==null?void 0:t.location.pathname)!==null&&is!==void 0?is:"",pageViewId:ts,timestamp:$},this._instance.scrollManager.resetContext(),cs}doPageLeave($){var ts;return this.gr($,(ts=this.dr)==null?void 0:ts.pageViewId)}doEvent(){var $;return{$pageview_id:($=this.dr)==null?void 0:$.pageViewId}}gr($,ts){var is=this.dr;if(!is)return{$pageview_id:ts};var cs={$pageview_id:ts,$prev_pageview_id:is.pageViewId},Kr=this._instance.scrollManager.getContext();if(Kr&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:Xr,lastScrollY:Na,maxScrollY:Ca,maxContentHeight:Aa,lastContentY:Ia,maxContentY:Ma}=Kr;if(!(C(Xr)||C(Na)||C(Ca)||C(Aa)||C(Ia)||C(Ma))){Xr=Math.ceil(Xr),Na=Math.ceil(Na),Ca=Math.ceil(Ca),Aa=Math.ceil(Aa),Ia=Math.ceil(Ia),Ma=Math.ceil(Ma);var Pa=Xr>1?Y(Na/Xr,0,1,Ie):1,La=Xr>1?Y(Ca/Xr,0,1,Ie):1,Fa=Aa>1?Y(Ia/Aa,0,1,Ie):1,Ba=Aa>1?Y(Ma/Aa,0,1,Ie):1;cs=qi(cs,{$prev_pageview_last_scroll:Na,$prev_pageview_last_scroll_percentage:Pa,$prev_pageview_max_scroll:Ca,$prev_pageview_max_scroll_percentage:La,$prev_pageview_last_content:Ia,$prev_pageview_last_content_percentage:Fa,$prev_pageview_max_content:Ma,$prev_pageview_max_content_percentage:Ba})}}return is.pathname&&(cs.$prev_pageview_pathname=is.pathname),is.timestamp&&(cs.$prev_pageview_duration=($.getTime()-is.timestamp.getTime())/1e3),cs}}var Tr={[Me]:{exposure:"hidden"},[Le]:{exposure:"hidden"},__cmpns:{exposure:"hidden"},[Ue]:{exposure:"hidden"},[Ne]:{exposure:"event"},[je]:{exposure:"hidden"},[ze]:{exposure:"event"},[Be]:{exposure:"hidden"},[He]:{exposure:"event"},[qe]:{exposure:"event"},[Ve]:{exposure:"event"},[We]:{exposure:"hidden"},[Ge]:{exposure:"event"},[Ye]:{exposure:"hidden"},$session_recording_enabled_server_side:{exposure:"hidden"},[Ze]:{exposure:"hidden"},[ti]:{exposure:"event"},$session_past_minimum_duration:{exposure:"event"},$session_recording_url_trigger_activated_session:{exposure:"event"},$session_recording_event_trigger_activated_session:{exposure:"event"},$debug_first_full_snapshot_timestamp:{exposure:"event"},[ei]:{exposure:"derived",shouldSkipFromEventProperties:(es,$)=>$(),transformToEventProperties(es){if(!O(es))return{};for(var $={},ts=Object.keys(es),is=0;ts.length>is;is++)$["$feature/"+ts[is]]=es[ts[is]];return $}},[ii]:{exposure:"event"},[ri]:{exposure:"hidden"},[si]:{exposure:"hidden"},[ni]:{exposure:"event"},[oi]:{exposure:"event"},[ai]:{exposure:"event"},[li]:{exposure:"hidden"},[ui]:{exposure:"hidden"},[hi]:{exposure:"hidden"},[di]:{exposure:"hidden"},[vi]:{exposure:"event"},[ci]:{exposure:"hidden"},$product_tours_activated:{exposure:"hidden"},$conversations_widget_session_id:{exposure:"event"},$conversations_ticket_id:{exposure:"event"},$conversations_widget_state:{exposure:"event"},$conversations_user_traits:{exposure:"event"},[pi]:{exposure:"hidden"},[fi]:{exposure:"hidden"},[_i]:{exposure:"hidden"},[gi]:{exposure:"hidden"},[mi]:{exposure:"hidden"},[bi]:{exposure:"hidden"},[yi]:{exposure:"hidden"},[wi]:{exposure:"hidden"},[xi]:{exposure:"hidden"},[Ei]:{exposure:"hidden"},[Si]:{exposure:"hidden"},[Je]:{exposure:"event"},[Ke]:{exposure:"event"},[Xe]:{exposure:"event"},[Qe]:{exposure:"event"},[ki]:{exposure:"event"},[Ri]:{exposure:"event"},[Pi]:{exposure:"event"},$sdk_debug_replay_event_trigger_status:{exposure:"event"},$sdk_debug_replay_linked_flag_trigger_status:{exposure:"event"},$sdk_debug_replay_matched_recording_trigger_groups:{exposure:"event"},$sdk_debug_replay_remote_trigger_matching_config:{exposure:"event"},$sdk_debug_replay_trigger_groups_count:{exposure:"event"},$sdk_debug_replay_url_trigger_status:{exposure:"event"},$session_recording_start_reason:{exposure:"event"}},kr=[["$posthog_sr_group_event_trigger_",{exposure:"hidden"}],["$posthog_sr_group_url_trigger_",{exposure:"hidden"}],["$posthog_sr_group_sampling_",{exposure:"hidden"}]],Rr=es=>{var $=r==null?void 0:r.createElement("a");return C($)?null:($.href=es,$)},Pr=function(es,$){for(var ts,is=((es.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),cs=0;is.length>cs;cs++){var Kr=is[cs].split("=");if(Kr[0]===$){ts=Kr;break}}if(!R(ts)||2>ts.length)return"";var Xr=ts[1];try{Xr=decodeURIComponent(Xr)}catch{Ie.error("Skipping decoding for malformed query param: "+Xr)}return Xr.replace(/\+/g," ")},Or=function(es,$,ts){if(!es||!$||!$.length)return es;for(var is=es.split("#"),cs=is[1],Kr=(is[0]||"").split("?"),Xr=Kr[1],Na=Kr[0],Ca=(Xr||"").split("&"),Aa=[],Ia=0;Ca.length>Ia;Ia++){var Ma=Ca[Ia].split("=");R(Ma)&&($.includes(Ma[0])?Aa.push(Ma[0]+"="+ts):Aa.push(Ca[Ia]))}var Pa=Na;return Xr!=null&&(Pa+="?"+Aa.join("&")),cs!=null&&(Pa+="#"+cs),Pa},Ir=function(es,$){var ts=es.match(new RegExp($+"=([^&]*)"));return ts?ts[1]:null},Cr="https?://(.*)",Fr=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],Ar=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid",...Fr],Mr="<masked>",Dr=["li_fat_id"];function Lr(es,$,ts){if(!r)return{};var is,cs=$?[...Fr,...ts||[]]:[],Kr=Ur(Or(r.URL,cs,Mr),es),Xr=(is={},Hi(Dr,(function(Na){var Ca=lr.O(Na);is[Na]=Ca||null})),is);return qi(Xr,Kr)}function Ur(es,$){var ts=Ar.concat($||[]),is={};return Hi(ts,(function(cs){var Kr=Pr(es,cs);is[cs]=Kr||null})),is}function Nr(es){var $=(function(Kr){return Kr?Kr.search(Cr+"google.([^/?]*)")===0?"google":Kr.search(Cr+"bing.com")===0?"bing":Kr.search(Cr+"yahoo.com")===0?"yahoo":Kr.search(Cr+"duckduckgo.com")===0?"duckduckgo":null:null})(es),ts=$!="yahoo"?"q":"p",is={};if(!M($)){is.$search_engine=$;var cs=r?Pr(r.referrer,ts):"";cs.length&&(is.ph_keyword=cs)}return is}function jr(){return navigator.language||navigator.userLanguage}var zr="$direct";function Br(){return(r==null?void 0:r.referrer)||zr}function Hr(es,$){var ts=es?[...Fr,...$||[]]:[],is=s==null?void 0:s.href.substring(0,1e3);return{r:Br().substring(0,1e3),u:is?Or(is,ts,Mr):void 0}}function qr(es){var $,{r:ts,u:is}=es,cs={$referrer:ts,$referring_domain:ts==null?void 0:ts==zr?zr:($=Rr(ts))==null?void 0:$.host};if(is){cs.$current_url=is;var Kr=Rr(is);cs.$host=Kr==null?void 0:Kr.host,cs.$pathname=Kr==null?void 0:Kr.pathname;var Xr=Ur(is);qi(cs,Xr)}if(ts){var Na=Nr(ts);qi(cs,Na)}return cs}function Vr(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function Wr(){try{return new Date().getTimezoneOffset()}catch{return}}var Gr=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Yr{constructor($,ts){this.Bt=$,this.props={},this.mr=!1,this.yr=(is=>{var cs="";return is.token&&(cs=is.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),is.persistence_name?"ph_"+is.persistence_name:"ph_"+cs+"_posthog"})($),this.nr=this.br($),this.load(),$.debug&&Ie.info("Persistence loaded",$.persistence,f({},this.props)),this.update_config($,$,ts),this.save()}isDisabled(){return!!this._r}br($){Gr.indexOf($.persistence.toLowerCase())===-1&&(Ie.critical("Unknown persistence type "+$.persistence+"; falling back to localStorage+cookie"),$.persistence="localStorage+cookie");var ts=(function(cs){cs===void 0&&(cs=[]);var Kr=[...dr,...cs];return f({},hr,{Z(Xr){try{var Na={};try{Na=lr.Z(Xr)||{}}catch{}var Ca=qi(Na,JSON.parse(hr.O(Xr)||"{}"));return hr.M(Xr,Ca),Ca}catch{}return null},M(Xr,Na,Ca,Aa,Ia,Ma){try{hr.M(Xr,Na,void 0,void 0,Ma);var Pa={};Kr.forEach((La=>{Na[La]&&(Pa[La]=Na[La])})),Object.keys(Pa).length&&lr.M(Xr,Pa,Ca,Aa,Ia,Ma)}catch(La){hr.B(La)}},F(Xr,Na){try{t==null||t.localStorage.removeItem(Xr),lr.F(Xr,Na)}catch(Ca){hr.B(Ca)}}})})($.cookie_persisted_properties||[]),is=$.persistence.toLowerCase();return is==="localstorage"&&hr.R()?hr:is==="localstorage+cookie"&&ts.R()?ts:is==="sessionstorage"&&fr.R()?fr:is==="memory"?cr:is==="cookie"?lr:ts.R()?ts:lr}wr($){var ts=$??this.Bt.feature_flag_cache_ttl_ms;if(!ts||0>=ts)return!1;var is=this.props[gi];return!is||typeof is!="number"||Date.now()-is>ts}properties(){var $={};return Hi(this.props,((ts,is)=>{var cs=(Kr=>{var Xr=Tr[Kr];if(Xr)return Xr;for(var[Na,Ca]of kr)if(Kr.indexOf(Na)===0)return Ca})(is);if((cs==null?void 0:cs.exposure)==="derived"){if(cs.shouldSkipFromEventProperties!=null&&cs.shouldSkipFromEventProperties(ts,is===ei?()=>this.wr():()=>!1))return;cs.transformToEventProperties&&qi($,cs.transformToEventProperties(ts))}else cs&&cs.exposure!=="event"||($[is]=ts)})),$}load(){if(!this._r){var $=this.nr.Z(this.yr);$&&(this.props=qi({},$))}}save(){this._r||this.nr.M(this.yr,this.props,this.Ir,this.Cr,this.Sr,this.Bt.debug)}remove(){this.nr.F(this.yr,!1),this.nr.F(this.yr,!0)}clear(){this.remove(),this.props={}}register_once($,ts,is){if(O($)){C(ts)&&(ts="None"),this.Ir=C(is)?this.kr:is;var cs=!1;if(Hi($,((Kr,Xr)=>{this.props.hasOwnProperty(Xr)&&this.props[Xr]!==ts||(this.Tr(Xr,Kr),cs=!0)})),cs)return this.save(),!0}return!1}register($,ts){if(O($)){this.Ir=C(ts)?this.kr:ts;var is=!1;if(Hi($,((cs,Kr)=>{$.hasOwnProperty(Kr)&&this.props[Kr]!==cs&&(this.Tr(Kr,cs),is=!0)})),is)return this.save(),!0}return!1}unregister($){$ in this.props&&(this.Ar($),this.save())}update_campaign_params(){if(!this.mr){var $=Lr(this.Bt.custom_campaign_params,this.Bt.mask_personal_data_properties,this.Bt.custom_personal_data_properties);I(Yi($))||this.register($),this.mr=!0}}update_search_keyword(){var $;this.register(($=r==null?void 0:r.referrer)?Nr($):{})}update_referrer_info(){var $;this.register_once({$referrer:Br(),$referring_domain:r!=null&&r.referrer&&(($=Rr(r.referrer))==null?void 0:$.host)||zr},void 0)}set_initial_person_info(){this.props[wi]||this.props[xi]||this.register_once({[Ei]:Hr(this.Bt.mask_personal_data_properties,this.Bt.custom_personal_data_properties)},void 0)}get_initial_props(){var $={};Hi([xi,wi],(Xr=>{var Na=this.props[Xr];Na&&Hi(Na,(function(Ca,Aa){$["$initial_"+E(Aa)]=Ca}))}));var ts,is,cs=this.props[Ei];if(cs){var Kr=(ts=qr(cs),is={},Hi(ts,(function(Xr,Na){is["$initial_"+E(Na)]=Xr})),is);qi($,Kr)}return $}safe_merge($){return Hi(this.props,(function(ts,is){is in $||($[is]=ts)})),$}update_config($,ts,is){if(this.kr=this.Ir=$.cookie_expiration,this.set_disabled($.disable_persistence||!!is),this.set_cross_subdomain($.cross_subdomain_cookie),this.set_secure($.secure_cookie),$.persistence!==ts.persistence||!((Xr,Na)=>{if(Xr.length!==Na.length)return!1;var Ca=[...Xr].sort(),Aa=[...Na].sort();return Ca.every(((Ia,Ma)=>Ia===Aa[Ma]))})($.cookie_persisted_properties||[],ts.cookie_persisted_properties||[])){var cs=this.br($),Kr=this.props;this.clear(),this.nr=cs,this.props=Kr,this.save()}}set_disabled($){this._r=$,this._r?this.remove():this.save()}set_cross_subdomain($){$!==this.Cr&&(this.Cr=$,this.remove(),this.save())}set_secure($){$!==this.Sr&&(this.Sr=$,this.remove(),this.save())}set_event_timer($,ts){var is=this.props[Ue]||{};is[$]=ts,this.Tr(Ue,is),this.save()}remove_event_timer($){var ts=this.props[Ue]||{},is=ts[$];return C(is)||(delete ts[$],this.Tr(Ue,ts),this.save()),is}get_property($){return this.props[$]}set_property($,ts){this.Tr($,ts),this.save()}Tr($,ts){this.props[$]=ts}Ar($){delete this.props[$]}}var Jr={Activation:"events",Cancellation:"cancelEvents"},Zr={Popover:"popover",API:"api",Widget:"widget"},rs={SHOWN:"survey shown",DISMISSED:"survey dismissed",SENT:"survey sent"},ss={SURVEY_ID:"$survey_id",SURVEY_ITERATION:"$survey_iteration",SURVEY_LAST_SEEN_DATE:"$survey_last_seen_date"},ns={Popover:"popover",Inline:"inline"},as={SHOWN:"product tour shown"},ls={TOUR_LAST_SEEN_DATE:"$product_tour_last_seen_date",TOUR_TYPE:"$product_tour_type"},us=Ce("[RateLimiter]");class hs{constructor($){this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=ts=>{var is=ts.text;if(is&&is.length)try{(JSON.parse(is).quota_limited||[]).forEach((cs=>{us.info((cs||"events")+" is quota limited."),this.serverLimits[cs]=new Date().getTime()+6e4}))}catch(cs){return void us.warn('could not rate limit - continuing. Error: "'+(cs==null?void 0:cs.message)+'"',{text:is})}},this.instance=$,this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}get captureEventsPerSecond(){var $;return(($=this.instance.config.rate_limiting)==null?void 0:$.events_per_second)||10}get captureEventsBurstLimit(){var $;return Math.max((($=this.instance.config.rate_limiting)==null?void 0:$.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond)}clientRateLimitContext($){var ts,is,cs;$===void 0&&($=!1);var{captureEventsBurstLimit:Kr,captureEventsPerSecond:Xr}=this,Na=new Date().getTime(),Ca=(ts=(is=this.instance.persistence)==null?void 0:is.get_property(yi))!==null&&ts!==void 0?ts:{tokens:Kr,last:Na};Ca.tokens+=(Na-Ca.last)/1e3*Xr,Ca.last=Na,Ca.tokens>Kr&&(Ca.tokens=Kr);var Aa=1>Ca.tokens;return Aa||$||(Ca.tokens=Math.max(0,Ca.tokens-1)),!Aa||this.lastEventRateLimited||$||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+Xr+" events per second and "+Kr+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=Aa,(cs=this.instance.persistence)==null||cs.set_property(yi,Ca),{isRateLimited:Aa,remainingTokens:Ca.tokens}}isServerRateLimited($){var ts=this.serverLimits[$||"events"]||!1;return ts!==!1&&new Date().getTime()<ts}}var ds=Ce("[RemoteConfig]");class vs{constructor($){this._instance=$}get remoteConfig(){var $;return($=h._POSTHOG_REMOTE_CONFIG)==null||($=$[this._instance.config.token])==null?void 0:$.config}Er($){var ts,is;(ts=h.__PosthogExtensions__)!=null&&ts.loadExternalDependency?(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,"remote-config",(()=>$(this.remoteConfig))):$()}Rr($){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback(ts){$(ts.json)}})}load(){try{if(this.remoteConfig)return ds.info("Using preloaded remote config",this.remoteConfig),this.Nr(this.remoteConfig),void this.Mr();if(this._instance.Fr())return void ds.warn("Remote config is disabled. Falling back to local config.");this.Er(($=>{if(!$)return ds.info("No config found after loading remote JS config. Falling back to JSON."),void this.Rr((ts=>{this.Nr(ts),this.Mr()}));this.Nr($),this.Mr()}))}catch($){ds.error("Error loading remote config",$)}}stop(){this.Or&&(clearInterval(this.Or),this.Or=void 0)}refresh(){this._instance.Fr()||(r==null?void 0:r.visibilityState)==="hidden"||this._instance.reloadFeatureFlags()}Mr(){var $;if(!this.Or){var ts=($=this._instance.config.remote_config_refresh_interval_ms)!==null&&$!==void 0?$:3e5;ts!==0&&(this.Or=setInterval((()=>{this.refresh()}),ts))}}Nr($){var ts;$||ds.error("Failed to fetch remote config from PostHog."),this._instance.Nr($??{}),($==null?void 0:$.hasFeatureFlags)!==!1&&(this._instance.config.advanced_disable_feature_flags_on_first_load||(ts=this._instance.featureFlags)==null||ts.ensureFlagsLoaded())}}var ps={GZipJS:"gzip-js",Base64:"base64"},fs=Uint8Array,_s=Uint16Array,gs=Uint32Array,ms=new fs([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]),bs=new fs([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]),ys=new fs([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),ws=function(es,$){for(var ts=new _s(31),is=0;31>is;++is)ts[is]=$+=1<<es[is-1];var cs=new gs(ts[30]);for(is=1;30>is;++is)for(var Kr=ts[is];ts[is+1]>Kr;++Kr)cs[Kr]=Kr-ts[is]<<5|is;return[ts,cs]},xs=ws(ms,2),Es=xs[1];xs[0][28]=258,Es[258]=28;for(var Ss=ws(bs,0)[1],$s=new _s(32768),Ts=0;32768>Ts;++Ts){var ks=(43690&Ts)>>>1|(21845&Ts)<<1;$s[Ts]=((65280&(ks=(61680&(ks=(52428&ks)>>>2|(13107&ks)<<2))>>>4|(3855&ks)<<4))>>>8|(255&ks)<<8)>>>1}var Rs=function(es,$,ts){for(var is=es.length,cs=0,Kr=new _s($);is>cs;++cs)++Kr[es[cs]-1];var Xr,Na=new _s($);for(cs=0;$>cs;++cs)Na[cs]=Na[cs-1]+Kr[cs-1]<<1;for(Xr=new _s(is),cs=0;is>cs;++cs)Xr[cs]=$s[Na[es[cs]-1]++]>>>15-es[cs];return Xr},Ps=new fs(288);for(Ts=0;144>Ts;++Ts)Ps[Ts]=8;for(Ts=144;256>Ts;++Ts)Ps[Ts]=9;for(Ts=256;280>Ts;++Ts)Ps[Ts]=7;for(Ts=280;288>Ts;++Ts)Ps[Ts]=8;var Os=new fs(32);for(Ts=0;32>Ts;++Ts)Os[Ts]=5;var Is=Rs(Ps,9),Cs=Rs(Os,5),Fs=function(es){return(es/8>>0)+(7&es&&1)},As=function(es,$,ts){(ts==null||ts>es.length)&&(ts=es.length);var is=new(es instanceof _s?_s:es instanceof gs?gs:fs)(ts-$);return is.set(es.subarray($,ts)),is},Ms=function(es,$,ts){var is=$/8>>0;es[is]|=ts<<=7&$,es[is+1]|=ts>>>8},Ds=function(es,$,ts){var is=$/8>>0;es[is]|=ts<<=7&$,es[is+1]|=ts>>>8,es[is+2]|=ts>>>16},Ls=function(es,$){for(var ts=[],is=0;es.length>is;++is)es[is]&&ts.push({s:is,f:es[is]});var cs=ts.length,Kr=ts.slice();if(!cs)return[new fs(0),0];if(cs==1){var Xr=new fs(ts[0].s+1);return Xr[ts[0].s]=1,[Xr,1]}ts.sort((function(Qa,Xa){return Qa.f-Xa.f})),ts.push({s:-1,f:25001});var Na=ts[0],Ca=ts[1],Aa=0,Ia=1,Ma=2;for(ts[0]={s:-1,f:Na.f+Ca.f,l:Na,r:Ca};Ia!=cs-1;)Na=ts[ts[Ma].f>ts[Aa].f?Aa++:Ma++],Ca=ts[Aa!=Ia&&ts[Ma].f>ts[Aa].f?Aa++:Ma++],ts[Ia++]={s:-1,f:Na.f+Ca.f,l:Na,r:Ca};var Pa=Kr[0].s;for(is=1;cs>is;++is)Kr[is].s>Pa&&(Pa=Kr[is].s);var La=new _s(Pa+1),Fa=Us(ts[Ia-1],La,0);if(Fa>$){is=0;var Ba=0,qa=Fa-$,za=1<<qa;for(Kr.sort((function(Qa,Xa){return La[Xa.s]-La[Qa.s]||Qa.f-Xa.f}));cs>is;++is){var Va=Kr[is].s;if($>=La[Va])break;Ba+=za-(1<<Fa-La[Va]),La[Va]=$}for(Ba>>>=qa;Ba>0;){var Ga=Kr[is].s;$>La[Ga]?Ba-=1<<$-La[Ga]++-1:++is}for(;is>=0&&Ba;--is){var Za=Kr[is].s;La[Za]==$&&(--La[Za],++Ba)}Fa=$}return[new fs(La),Fa]},Us=function(es,$,ts){return es.s==-1?Math.max(Us(es.l,$,ts+1),Us(es.r,$,ts+1)):$[es.s]=ts},Ns=function(es){for(var $=es.length;$&&!es[--$];);for(var ts=new _s(++$),is=0,cs=es[0],Kr=1,Xr=function(Ca){ts[is++]=Ca},Na=1;$>=Na;++Na)if(es[Na]==cs&&Na!=$)++Kr;else{if(!cs&&Kr>2){for(;Kr>138;Kr-=138)Xr(32754);Kr>2&&(Xr(Kr>10?Kr-11<<5|28690:Kr-3<<5|12305),Kr=0)}else if(Kr>3){for(Xr(cs),--Kr;Kr>6;Kr-=6)Xr(8304);Kr>2&&(Xr(Kr-3<<5|8208),Kr=0)}for(;Kr--;)Xr(cs);Kr=1,cs=es[Na]}return[ts.subarray(0,is),$]},js=function(es,$){for(var ts=0,is=0;$.length>is;++is)ts+=es[is]*$[is];return ts},zs=function(es,$,ts){var is=ts.length,cs=Fs($+2);es[cs]=255&is,es[cs+1]=is>>>8,es[cs+2]=255^es[cs],es[cs+3]=255^es[cs+1];for(var Kr=0;is>Kr;++Kr)es[cs+Kr+4]=ts[Kr];return 8*(cs+4+is)},Bs=function(es,$,ts,is,cs,Kr,Xr,Na,Ca,Aa,Ia){Ms($,Ia++,ts),++cs[256];for(var Ma=Ls(cs,15),Pa=Ma[0],La=Ma[1],Fa=Ls(Kr,15),Ba=Fa[0],qa=Fa[1],za=Ns(Pa),Va=za[0],Ga=za[1],Za=Ns(Ba),Qa=Za[0],Xa=Za[1],Ja=new _s(19),tl=0;Va.length>tl;++tl)Ja[31&Va[tl]]++;for(tl=0;Qa.length>tl;++tl)Ja[31&Qa[tl]]++;for(var sl=Ls(Ja,7),ol=sl[0],ml=sl[1],rl=19;rl>4&&!ol[ys[rl-1]];--rl);var ll,dl,_l,il,hl=Aa+5<<3,ul=js(cs,Ps)+js(Kr,Os)+Xr,cl=js(cs,Pa)+js(Kr,Ba)+Xr+14+3*rl+js(Ja,ol)+(2*Ja[16]+3*Ja[17]+7*Ja[18]);if(ul>=hl&&cl>=hl)return zs($,Ia,es.subarray(Ca,Ca+Aa));if(Ms($,Ia,1+(ul>cl)),Ia+=2,ul>cl){ll=Rs(Pa,La),dl=Pa,_l=Rs(Ba,qa),il=Ba;var jl=Rs(ol,ml);for(Ms($,Ia,Ga-257),Ms($,Ia+5,Xa-1),Ms($,Ia+10,rl-4),Ia+=14,tl=0;rl>tl;++tl)Ms($,Ia+3*tl,ol[ys[tl]]);Ia+=3*rl;for(var el=[Va,Qa],pl=0;2>pl;++pl){var bl=el[pl];for(tl=0;bl.length>tl;++tl)Ms($,Ia,jl[Ol=31&bl[tl]]),Ia+=ol[Ol],Ol>15&&(Ms($,Ia,bl[tl]>>>5&127),Ia+=bl[tl]>>>12)}}else ll=Is,dl=Ps,_l=Cs,il=Os;for(tl=0;Na>tl;++tl)if(is[tl]>255){var Ol;Ds($,Ia,ll[257+(Ol=is[tl]>>>18&31)]),Ia+=dl[Ol+257],Ol>7&&(Ms($,Ia,is[tl]>>>23&31),Ia+=ms[Ol]);var Pl=31&is[tl];Ds($,Ia,_l[Pl]),Ia+=il[Pl],Pl>3&&(Ds($,Ia,is[tl]>>>5&8191),Ia+=bs[Pl])}else Ds($,Ia,ll[is[tl]]),Ia+=dl[is[tl]];return Ds($,Ia,ll[256]),Ia+dl[256]},Hs=new gs([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),qs=(function(){for(var es=new gs(256),$=0;256>$;++$){for(var ts=$,is=9;--is;)ts=(1&ts&&3988292384)^ts>>>1;es[$]=ts}return es})(),Vs=function(es,$,ts){for(;ts;++$)es[$]=ts,ts>>>=8};function Ws(es,$){$===void 0&&($={});var ts=(function(){var Ma=4294967295;return{p(Pa){for(var La=Ma,Fa=0;Pa.length>Fa;++Fa)La=qs[255&La^Pa[Fa]]^La>>>8;Ma=La},d(){return 4294967295^Ma}}})(),is=es.length;ts.p(es);var cs,Kr,Xr,Na,Ca,Aa=(Na=10+((cs=$).filename&&cs.filename.length+1||0),Ca=8,(function(Ma,Pa,La,Fa,Ba,qa){var za=Ma.length,Va=new fs(Fa+za+5*(1+Math.floor(za/7e3))+Ba),Ga=Va.subarray(Fa,Va.length-Ba),Za=0;if(!Pa||8>za)for(var Qa=0;za>=Qa;Qa+=65535){var Xa=Qa+65535;za>Xa?Za=zs(Ga,Za,Ma.subarray(Qa,Xa)):(Ga[Qa]=!0,Za=zs(Ga,Za,Ma.subarray(Qa,za)))}else{for(var Ja=Hs[Pa-1],tl=Ja>>>13,sl=8191&Ja,ol=(1<<La)-1,ml=new _s(32768),rl=new _s(ol+1),ll=Math.ceil(La/3),dl=2*ll,_l=function(Ou){return(Ma[Ou]^Ma[Ou+1]<<ll^Ma[Ou+2]<<dl)&ol},il=new gs(25e3),hl=new _s(288),ul=new _s(32),cl=0,jl=0,el=(Qa=0,0),pl=0,bl=0;za>Qa;++Qa){var Ol=_l(Qa),Pl=32767&Qa,Fl=rl[Ol];if(ml[Pl]=Fl,rl[Ol]=Pl,Qa>=pl){var Nl=za-Qa;if((cl>7e3||el>24576)&&Nl>423){Za=Bs(Ma,Ga,0,il,hl,ul,jl,el,bl,Qa-bl,Za),el=cl=jl=0,bl=Qa;for(var Kl=0;286>Kl;++Kl)hl[Kl]=0;for(Kl=0;30>Kl;++Kl)ul[Kl]=0}var wl=2,$l=0,zl=sl,Zl=Pl-Fl&32767;if(Nl>2&&Ol==_l(Qa-Zl))for(var ru=Math.min(tl,Nl)-1,ou=Math.min(32767,Qa),vu=Math.min(258,Nl);ou>=Zl&&--zl&&Pl!=Fl;){if(Ma[Qa+wl]==Ma[Qa+wl-Zl]){for(var xu=0;vu>xu&&Ma[Qa+xu]==Ma[Qa+xu-Zl];++xu);if(xu>wl){if(wl=xu,$l=Zl,xu>ru)break;var Bu=Math.min(Zl,xu-2),ku=0;for(Kl=0;Bu>Kl;++Kl){var Vl=Qa-Zl+Kl+32768&32767,iu=Vl-ml[Vl]+32768&32767;iu>ku&&(ku=iu,Fl=Vl)}}}Zl+=(Pl=Fl)-(Fl=ml[Pl])+32768&32767}if($l){il[el++]=268435456|Es[wl]<<18|Ss[$l];var bu=31&Es[wl],lc=31&Ss[$l];jl+=ms[bu]+bs[lc],++hl[257+bu],++ul[lc],pl=Qa+wl,++cl}else il[el++]=Ma[Qa],++hl[Ma[Qa]]}}Za=Bs(Ma,Ga,!0,il,hl,ul,jl,el,bl,Qa-bl,Za)}return As(Va,0,Fa+Fs(Za)+Ba)})(Kr=es,(Xr=$).level==null?6:Xr.level,Xr.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(Kr.length)))):12+Xr.mem,Na,Ca)),Ia=Aa.length;return(function(Ma,Pa){var La=Pa.filename;if(Ma[0]=31,Ma[1]=139,Ma[2]=8,Ma[8]=2>Pa.level?4:Pa.level==9?2:0,Ma[9]=3,Pa.mtime!=0&&Vs(Ma,4,Math.floor(new Date(Pa.mtime||Date.now())/1e3)),La){Ma[3]=8;for(var Fa=0;La.length>=Fa;++Fa)Ma[Fa+10]=La.charCodeAt(Fa)}})(Aa,$),Vs(Aa,Ia-8,ts.d()),Vs(Aa,Ia-4,is),Aa}var Gs=!!o||!!n,Ys="text/plain",Js=!1,Ks=function(es,$,ts){var is;ts===void 0&&(ts=!0);var[cs,Kr]=es.split("?"),Xr=f({},$),Na=(is=Kr==null?void 0:Kr.split("&").map((Aa=>{var Ia,[Ma,Pa]=Aa.split("="),La=ts&&(Ia=Xr[Ma])!==null&&Ia!==void 0?Ia:Pa;return delete Xr[Ma],Ma+"="+La})))!==null&&is!==void 0?is:[],Ca=(function(Aa,Ia){var Ma,Pa;Ia===void 0&&(Ia="&");var La=[];return Hi(Aa,(function(Fa,Ba){C(Fa)||C(Ba)||Ba==="undefined"||(Ma=encodeURIComponent((qa=>qa instanceof File)(Fa)?Fa.name:Fa.toString()),Pa=encodeURIComponent(Ba),La[La.length]=Pa+"="+Ma)})),La.join(Ia)})(Xr);return Ca&&Na.push(Ca),cs+"?"+Na.join("&")},Xs=(es,$)=>JSON.stringify(es,((ts,is)=>typeof is=="bigint"?is.toString():is),$),Qs=es=>{if(es.tr)return es.tr;var{data:$,compression:ts}=es;if($){if(ts===ps.GZipJS){var is=Ws((function(Na,Ca){var Aa=Na.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(Na);for(var Ia=new fs(Na.length+(Na.length>>>1)),Ma=0,Pa=function(qa){Ia[Ma++]=qa},La=0;Aa>La;++La){if(Ma+5>Ia.length){var Fa=new fs(Ma+8+(Aa-La<<1));Fa.set(Ia),Ia=Fa}var Ba=Na.charCodeAt(La);128>Ba?Pa(Ba):2048>Ba?(Pa(192|Ba>>>6),Pa(128|63&Ba)):Ba>55295&&57344>Ba?(Pa(240|(Ba=65536+(1047552&Ba)|1023&Na.charCodeAt(++La))>>>18),Pa(128|Ba>>>12&63),Pa(128|Ba>>>6&63),Pa(128|63&Ba)):(Pa(224|Ba>>>12),Pa(128|Ba>>>6&63),Pa(128|63&Ba))}return As(Ia,0,Ma)})(Xs($)),{mtime:0});return{contentType:Ys,body:is.buffer.slice(is.byteOffset,is.byteOffset+is.byteLength),estimatedSize:is.byteLength}}if(ts===ps.Base64){var cs=(function(Na){return Na&&btoa(encodeURIComponent(Na).replace(/%([0-9A-F]{2})/g,((Ca,Aa)=>String.fromCharCode(parseInt(Aa,16)))))})(Xs($)),Kr=(Na=>"data="+encodeURIComponent(typeof Na=="string"?Na:Xs(Na)))(cs);return{contentType:"application/x-www-form-urlencoded",body:Kr,estimatedSize:new Blob([Kr]).size}}var Xr=Xs($);return{contentType:"application/json",body:Xr,estimatedSize:new Blob([Xr]).size}}},Zs=(function(){var es=p((function*($){var ts=Xs($.data),is=yield(function(Kr,Xr,Na){return g.apply(this,arguments)})(ts,v.DEBUG,{rethrow:!0});if(!is)return $;var cs=yield is.arrayBuffer();return f({},$,{tr:{contentType:Ys,body:cs,estimatedSize:cs.byteLength}})}));return function($){return es.apply(this,arguments)}})(),tn=(es,$)=>Ks(es,{_:new Date().getTime().toString(),ver:v.JS_SDK_VERSION,compression:$}),en=[];n&&en.push({transport:"fetch",method(es){var $,ts,{contentType:is,body:cs,estimatedSize:Kr}=($=Qs(es))!==null&&$!==void 0?$:{},Xr=new Headers;Hi(es.headers,(function(Ia,Ma){Xr.append(Ma,Ia)})),is&&Xr.append("Content-Type",is);var Na=es.url,Ca=null;if(a){var Aa=new a;Ca={signal:Aa.signal,timeout:setTimeout((()=>Aa.abort()),es.timeout)}}n(Na,f({method:(es==null?void 0:es.method)||"GET",headers:Xr,keepalive:es.method==="POST"&&52428.8>(Kr||0),body:cs,signal:(ts=Ca)==null?void 0:ts.signal},es.fetchOptions)).then((Ia=>Ia.text().then((Ma=>{var Pa={statusCode:Ia.status,text:Ma};if(Ia.status===200)try{Pa.json=JSON.parse(Ma)}catch(La){Ie.error(La)}es.callback==null||es.callback(Pa)})))).catch((Ia=>{Ie.error(Ia),es.callback==null||es.callback({statusCode:0,error:Ia})})).finally((()=>Ca?clearTimeout(Ca.timeout):null))}}),o&&en.push({transport:"XHR",method(es){var $,ts=new o;ts.open(es.method||"GET",es.url,!0);var{contentType:is,body:cs}=($=Qs(es))!==null&&$!==void 0?$:{};Hi(es.headers,(function(Kr,Xr){ts.setRequestHeader(Xr,Kr)})),is&&ts.setRequestHeader("Content-Type",is),es.timeout&&(ts.timeout=es.timeout),es.disableXHRCredentials||(ts.withCredentials=!0),ts.onreadystatechange=()=>{if(ts.readyState===4){var Kr={statusCode:ts.status,text:ts.responseText};if(ts.status===200)try{Kr.json=JSON.parse(ts.responseText)}catch{}es.callback==null||es.callback(Kr)}},ts.send(cs)}}),i!=null&&i.sendBeacon&&en.push({transport:"sendBeacon",method(es){var $=Ks(es.url,{beacon:"1"});try{var ts,{contentType:is,body:cs}=(ts=Qs(es))!==null&&ts!==void 0?ts:{};if(!cs)return;var Kr=cs instanceof Blob?cs:new Blob([cs],{type:is});i.sendBeacon($,Kr)}catch{}}});var rn=3e3;class sn{constructor($,ts){this.Pr=!0,this.Lr=[],this.Dr=Y((ts==null?void 0:ts.flush_interval_ms)||rn,250,5e3,Ie.createLogger("flush interval"),rn),this.Br=$}enqueue($){this.Lr.push($),this.jr||this.$r()}unload(){this.qr();var $=this.Lr.length>0?this.Zr():{},ts=Object.values($);[...ts.filter((is=>is.url.indexOf("/e")===0)),...ts.filter((is=>is.url.indexOf("/e")!==0))].map((is=>{this.Br(f({},is,{transport:"sendBeacon"}))}))}enable(){this.Pr=!1,this.$r()}$r(){var $=this;this.Pr||(this.jr=setTimeout((()=>{if(this.qr(),this.Lr.length>0){var ts=this.Zr(),is=function(){var Kr=ts[cs],Xr=new Date().getTime();Kr.data&&R(Kr.data)&&Hi(Kr.data,(Na=>{Na.offset=Math.abs(Na.timestamp-Xr),delete Na.timestamp})),$.Br(Kr)};for(var cs in ts)is()}}),this.Dr))}qr(){clearTimeout(this.jr),this.jr=void 0}Zr(){var $={};return Hi(this.Lr,(ts=>{var is,cs=ts,Kr=(cs?cs.batchKey:null)||cs.url;C($[Kr])&&($[Kr]=f({},cs,{data:[]})),(is=$[Kr].data)==null||is.push(cs.data)})),this.Lr=[],$}}var nn=["retriesPerformedSoFar"];class on{constructor($){this.Vr=!1,this.Hr=3e3,this.Lr=[],this._instance=$,this.Lr=[],this.zr=!0,!C(t)&&"onLine"in t.navigator&&(this.zr=t.navigator.onLine,this.Ur=()=>{this.zr=!0,this.Yr()},this.Gr=()=>{this.zr=!1},Xi(t,"online",this.Ur),Xi(t,"offline",this.Gr))}get length(){return this.Lr.length}retriableRequest($){var{retriesPerformedSoFar:ts}=$,is=_($,nn);U(ts)&&(is.url=Ks(is.url,{retry_count:ts})),this._instance._send_request(f({},is,{callback:cs=>{cs.statusCode===200||cs.statusCode>=400&&500>cs.statusCode||(ts??0)>=10?is.callback==null||is.callback(cs):this.Wr(f({retriesPerformedSoFar:ts},is))}}))}Wr($){var ts=$.retriesPerformedSoFar||0;$.retriesPerformedSoFar=ts+1;var is=(function(Xr){var Na=3e3*Math.pow(2,Xr),Ca=Na/2,Aa=Math.min(18e5,Na),Ia=Math.random()-.5;return Math.ceil(Aa+Ia*(Aa-Ca))})(ts),cs=Date.now()+is;this.Lr.push({retryAt:cs,requestOptions:$});var Kr="Enqueued failed request for retry in "+is;navigator.onLine||(Kr+=" (Browser is offline)"),Ie.warn(Kr),this.Vr||(this.Vr=!0,this.Xr())}Xr(){if(this.Jr&&clearTimeout(this.Jr),this.Lr.length===0)return this.Vr=!1,void(this.Jr=void 0);this.Jr=setTimeout((()=>{this.zr&&this.Lr.length>0&&this.Yr(),this.Xr()}),this.Hr)}Yr(){var $=Date.now(),ts=[],is=this.Lr.filter((Kr=>$>Kr.retryAt||(ts.push(Kr),!1)));if(this.Lr=ts,is.length>0)for(var{requestOptions:cs}of is)this.retriableRequest(cs)}unload(){for(var{requestOptions:$}of(this.Jr&&(clearTimeout(this.Jr),this.Jr=void 0),this.Vr=!1,C(t)||(this.Ur&&(t.removeEventListener("online",this.Ur),this.Ur=void 0),this.Gr&&(t.removeEventListener("offline",this.Gr),this.Gr=void 0)),this.Lr))try{this._instance._send_request(f({},$,{transport:"sendBeacon"}))}catch(ts){Ie.error(ts)}this.Lr=[]}}class an{constructor($){this.Kr=()=>{var ts,is,cs,Kr;this.Qr||(this.Qr={});var Xr=this.scrollElement(),Na=this.scrollY(),Ca=Xr?Math.max(0,Xr.scrollHeight-Xr.clientHeight):0,Aa=Na+((Xr==null?void 0:Xr.clientHeight)||0),Ia=(Xr==null?void 0:Xr.scrollHeight)||0;this.Qr.lastScrollY=Math.ceil(Na),this.Qr.maxScrollY=Math.max(Na,(ts=this.Qr.maxScrollY)!==null&&ts!==void 0?ts:0),this.Qr.maxScrollHeight=Math.max(Ca,(is=this.Qr.maxScrollHeight)!==null&&is!==void 0?is:0),this.Qr.lastContentY=Aa,this.Qr.maxContentY=Math.max(Aa,(cs=this.Qr.maxContentY)!==null&&cs!==void 0?cs:0),this.Qr.maxContentHeight=Math.max(Ia,(Kr=this.Qr.maxContentHeight)!==null&&Kr!==void 0?Kr:0)},this._instance=$}get ei(){return this._instance.config.scroll_root_selector}getContext(){return this.Qr}resetContext(){var $=this.Qr;return setTimeout(this.Kr,0),$}startMeasuringScrollPosition(){Xi(t,"scroll",this.Kr,{capture:!0}),Xi(t,"scrollend",this.Kr,{capture:!0}),Xi(t,"resize",this.Kr)}scrollElement(){if(!this.ei)return t==null?void 0:t.document.documentElement;var $=R(this.ei)?this.ei:[this.ei];for(var ts of $){var is=t==null?void 0:t.document.querySelector(ts);if(is)return is}}scrollY(){if(this.ei){var $=this.scrollElement();return $&&$.scrollTop||0}return t&&(t.scrollY||t.pageYOffset||t.document.documentElement.scrollTop)||0}scrollX(){if(this.ei){var $=this.scrollElement();return $&&$.scrollLeft||0}return t&&(t.scrollX||t.pageXOffset||t.document.documentElement.scrollLeft)||0}}var ln=es=>Hr(es==null?void 0:es.config.mask_personal_data_properties,es==null?void 0:es.config.custom_personal_data_properties);class un{constructor($,ts,is,cs){this.ti=Kr=>{var Xr=this.ri();if(!Xr||Xr.sessionId!==Kr){var Na={sessionId:Kr,props:this.ii(this._instance)};this.ni.register({[bi]:Na})}},this._instance=$,this.si=ts,this.ni=is,this.ii=cs||ln,this.si.onSessionId(this.ti)}ri(){return this.ni.props[bi]}getSetOnceProps(){var $,ts=($=this.ri())==null?void 0:$.props;return ts?"r"in ts?qr(ts):{$referring_domain:ts.referringDomain,$pathname:ts.initialPathName,utm_source:ts.utm_source,utm_campaign:ts.utm_campaign,utm_medium:ts.utm_medium,utm_content:ts.utm_content,utm_term:ts.utm_term}:{}}getSessionProps(){var $={};return Hi(Yi(this.getSetOnceProps()),((ts,is)=>{is==="$current_url"&&(is="url"),$["$session_entry_"+E(is)]=ts})),$}}class hn{constructor(){this.oi={}}on($,ts){return this.oi[$]||(this.oi[$]=[]),this.oi[$].push(ts),()=>{this.oi[$]=this.oi[$].filter((is=>is!==ts))}}emit($,ts){for(var is of this.oi[$]||[])is(ts);for(var cs of this.oi["*"]||[])cs($,ts)}}var dn=Ce("[SessionId]");class vn{on($,ts){return this.ai.on($,ts)}constructor($,ts,is){var cs;if(this.li=[],this.ui=void 0,this.ai=new hn,this.hi=(Aa,Ia)=>!(!U(Aa)||!U(Ia))&&Math.abs(Aa-Ia)>this.sessionTimeoutMs,!$.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if($.config.cookieless_mode===Ci)throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.Bt=$.config,this.ni=$.persistence,this.ci=void 0,this.di=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.vi=ts||sr,this.fi=is||sr;var Kr=this.Bt.persistence_name||this.Bt.token;if(this._sessionTimeoutMs=1e3*Y(this.Bt.session_idle_timeout_seconds||1800,60,36e3,dn.createLogger("session_idle_timeout_seconds"),1800),$.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.pi(),this.gi="ph_"+Kr+"_window_id",this.mi="ph_"+Kr+"_primary_window_exists",this.yi()){var Xr=fr.Z(this.gi),Na=fr.Z(this.mi);Xr&&!Na?this.ci=Xr:fr.F(this.gi),fr.M(this.mi,!0)}if((cs=this.Bt.bootstrap)!=null&&cs.sessionID)try{var Ca=(Aa=>{var Ia=this.Bt.bootstrap.sessionID.replace(/-/g,"");if(Ia.length!==32)throw new Error("Not a valid UUID");if(Ia[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(Ia.substring(0,12),16)})();this.bi(this.Bt.bootstrap.sessionID,new Date().getTime(),Ca)}catch(Aa){dn.error("Invalid sessionID in bootstrap",Aa)}this.wi()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId($){return C(this.li)&&(this.li=[]),this.li.push($),this.di&&$(this.di,this.ci),()=>{this.li=this.li.filter((ts=>ts!==$))}}yi(){return this.Bt.persistence!=="memory"&&!this.ni._r&&fr.R()}Ii($){$!==this.ci&&(this.ci=$,this.yi()&&fr.M(this.gi,$))}Ci(){return this.ci?this.ci:this.yi()?fr.Z(this.gi):null}bi($,ts,is){$===this.di&&ts===this._sessionActivityTimestamp&&is===this._sessionStartTimestamp||(this._sessionStartTimestamp=is,this._sessionActivityTimestamp=ts,this.di=$,this.ni.register({[Ze]:[ts,$,is]}))}Si(){var $=this.ni.props[Ze];return R($)&&$.length===2&&$.push($[0]),$||[0,null,0]}resetSessionId(){this.bi(null,null,null)}destroy(){clearTimeout(this.xi),this.xi=void 0,this.ui&&t&&(t.removeEventListener(Li,this.ui,{capture:!1}),this.ui=void 0),this.li=[]}wi(){this.ui=()=>{this.yi()&&fr.F(this.mi)},Xi(t,Li,this.ui,{capture:!1})}checkAndGetSessionAndWindowId($,ts){if($===void 0&&($=!1),ts===void 0&&(ts=null),this.Bt.cookieless_mode===Ci)throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var is=ts||new Date().getTime(),[cs,Kr,Xr]=this.Si(),Na=this.Ci(),Ca=U(Xr)&&Math.abs(is-Xr)>864e5,Aa=!1,Ia=!Kr,Ma=!Ia&&!$&&this.hi(is,cs);Ia||Ma||Ca?(Kr=this.vi(),Na=this.fi(),dn.info("new session ID generated",{sessionId:Kr,windowId:Na,changeReason:{noSessionId:Ia,activityTimeout:Ma,sessionPastMaximumLength:Ca}}),Xr=is,Aa=!0):Na||(Na=this.fi(),Aa=!0);var Pa=U(cs)&&$&&!Ca?cs:is,La=U(Xr)?Xr:new Date().getTime();return this.Ii(Na),this.bi(Kr,Pa,La),$||this.pi(),Aa&&this.li.forEach((Fa=>Fa(Kr,Na,Aa?{noSessionId:Ia,activityTimeout:Ma,sessionPastMaximumLength:Ca}:void 0))),{sessionId:Kr,windowId:Na,sessionStartTimestamp:La,changeReason:Aa?{noSessionId:Ia,activityTimeout:Ma,sessionPastMaximumLength:Ca}:void 0,lastActivityTimestamp:cs}}pi(){clearTimeout(this.xi),this.xi=setTimeout((()=>{var[$]=this.Si();if(this.hi(new Date().getTime(),$)){var ts=this.di;this.resetSessionId(),this.ai.emit("forcedIdleReset",{idleSessionId:ts})}}),1.1*this.sessionTimeoutMs)}}var cn=function(es,$){if(!es)return!1;var ts=es.userAgent;if(ts&&b(ts,$))return!0;try{var is=es==null?void 0:es.userAgentData;if(is!=null&&is.brands&&is.brands.some((cs=>b(cs==null?void 0:cs.brand,$))))return!0}catch{}return!!es.webdriver},pn=function(es,$){if(!(function(ts){try{new RegExp(ts)}catch{return!1}return!0})($))return!1;try{return new RegExp($).test(es)}catch{return!1}};function fn(es,$,ts){return Xs({distinct_id:es,userPropertiesToSet:$,userPropertiesToSetOnce:ts})}var _n={exact:(es,$)=>$.some((ts=>es.some((is=>ts===is)))),is_not:(es,$)=>$.every((ts=>es.every((is=>ts!==is)))),regex:(es,$)=>$.some((ts=>es.some((is=>pn(ts,is))))),not_regex:(es,$)=>$.every((ts=>es.every((is=>!pn(ts,is))))),icontains:(es,$)=>$.map(gn).some((ts=>es.map(gn).some((is=>ts.includes(is))))),not_icontains:(es,$)=>$.map(gn).every((ts=>es.map(gn).every((is=>!ts.includes(is))))),gt:(es,$)=>$.some((ts=>{var is=parseFloat(ts);return!isNaN(is)&&es.some((cs=>is>parseFloat(cs)))})),lt:(es,$)=>$.some((ts=>{var is=parseFloat(ts);return!isNaN(is)&&es.some((cs=>is<parseFloat(cs)))}))},gn=es=>es.toLowerCase();function mn(es,$){return!es||Object.entries(es).every((ts=>{var[is,cs]=ts,Kr=$==null?void 0:$[is];if(C(Kr)||M(Kr))return!1;var Xr=[String(Kr)],Na=_n[cs.operator];return!!Na&&Na(cs.values,Xr)}))}var bn="custom",yn="i.posthog.com",wn=/^\/static\//;class xn{constructor($){this.ki={},this.instance=$}get apiHost(){var $=this.instance.config.api_host.trim().replace(/\/$/,"");return $==="https://app.posthog.com"?"https://us.i.posthog.com":$}get flagsApiHost(){var $=this.instance.config.flags_api_host;return $?$.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var $,ts=($=this.instance.config.ui_host)==null?void 0:$.replace(/\/$/,"");return ts||(ts=this.apiHost.replace("."+yn,".posthog.com")),ts==="https://app.posthog.com"?"https://us.posthog.com":ts}get region(){return this.ki[this.apiHost]||(this.ki[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":bn),this.ki[this.apiHost]}Ti($){var ts=this.instance.config.__preview_external_dependency_versioned_paths;if(typeof ts=="string"&&wn.test($))return ts.trim().replace(/\/$/,"")||void 0}endpointFor($,ts){if(ts===void 0&&(ts=""),ts&&(ts=ts[0]==="/"?ts:"/"+ts),$==="ui")return this.uiHost+ts;if($==="flags")return this.flagsApiHost+ts;if($==="assets"){var is=this.Ti(ts);if(is)return""+is+ts}if(this.region===bn)return this.apiHost+ts;var cs=yn+ts;switch($){case"assets":return"https://"+this.region+"-assets."+cs;case"api":return"https://"+this.region+"."+cs}}}var En=Ce("[Surveys]"),Sn="seenSurvey_",$n=[Zr.Popover,Zr.Widget,Zr.API],Tn={ignoreConditions:!1,ignoreDelay:!1,displayType:ns.Popover},kn=Ce("[PostHog ExternalIntegrations]"),Rn={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class Pn{constructor($){this._instance=$}ur($,ts){var is;(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,$,(cs=>{if(cs)return kn.error("failed to load script",cs);ts()}))}startIfEnabledOrStop(){var $=this,ts=function(Xr){var Na,Ca,Aa;!cs||(Na=h.__PosthogExtensions__)!=null&&(Na=Na.integrations)!=null&&Na[Xr]||$.ur(Rn[Xr],(()=>{var Ia;(Ia=h.__PosthogExtensions__)==null||(Ia=Ia.integrations)==null||(Ia=Ia[Xr])==null||Ia.start($._instance)})),!cs&&(Ca=h.__PosthogExtensions__)!=null&&(Ca=Ca.integrations)!=null&&Ca[Xr]&&((Aa=h.__PosthogExtensions__)==null||(Aa=Aa.integrations)==null||(Aa=Aa[Xr])==null||Aa.stop())};for(var[is,cs]of Object.entries((Kr=this._instance.config.integrations)!==null&&Kr!==void 0?Kr:{})){var Kr;ts(is)}}}var On,In={},Cn=0,Fn=()=>{},An='Consent opt in/out is not valid with cookieless_mode="always" and will be ignored',Mn="Surveys module not available",Dn="sanitize_properties is deprecated. Use before_send instead",Ln="Invalid value for property_denylist config: ",Un="posthog",Nn=!Gs&&(u==null?void 0:u.indexOf("MSIE"))===-1&&(u==null?void 0:u.indexOf("Mozilla"))===-1,jn=es=>{var $;return f({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ki(r==null?void 0:r.location),persistence:"localStorage+cookie",persistence_name:"",cookie_persisted_properties:[],loaded:Fn,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:es??"unset",__preview_deferred_init_extensions:!1,__preview_external_dependency_versioned_paths:!1,debug:s&&F(s==null?void 0:s.search)&&s.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,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(t==null||($=t.location)==null?void 0:$.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,surveys_request_timeout_ms:1e4,on_request_error(ts){Ie.error("Bad HTTP status: "+ts.statusCode+" "+ts.text)},get_device_id:ts=>ts,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:Mi,before_send:void 0,request_queue_config:{flush_interval_ms:rn},error_tracking:{},_onCapture:Fn,__preview_eager_load_replay:!1},(ts=>({rageclick:!ts||"2025-11-30">ts||{content_ignorelist:!0},capture_pageview:!ts||"2025-05-24">ts||"history_change",session_recording:ts&&ts>="2025-11-30"?{strictMinimumDuration:!0}:{},external_scripts_inject_target:ts&&ts>="2026-01-30"?"head":"body",internal_or_test_user_hostname:ts&&ts>="2026-01-30"?/^(localhost|127\.0\.0\.1)$/:void 0}))(es))},zn=[["process_person","person_profiles"],["xhr_headers","request_headers"],["cookie_name","persistence_name"],["disable_cookie","disable_persistence"],["store_google","save_campaign_params"],["verbose","debug"]],Bn=es=>{var $={};for(var[ts,is]of zn)C(es[ts])||($[is]=es[ts]);var cs=qi({},$,es);return R(es.property_blacklist)&&(C(es.property_denylist)?cs.property_denylist=es.property_blacklist:R(es.property_denylist)?cs.property_denylist=[...es.property_blacklist,...es.property_denylist]:Ie.error(Ln+es.property_denylist)),cs};class Hn{constructor(){this.__forceAllowLocalhost=!1}get Ai(){return this.__forceAllowLocalhost}set Ai($){Ie.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=$}}class qn{Ei($,ts){if($){var is=this.Ri.indexOf($);is!==-1&&this.Ri.splice(is,1)}return this.Ri.push(ts),ts.initialize==null||ts.initialize(),ts}Ni(){return this.config.cookieless_mode===Ci||this.config.cookieless_mode===Ii&&this.consent.isRejected()}get decideEndpointWasHit(){var $,ts;return($=(ts=this.featureFlags)==null?void 0:ts.hasLoadedFlags)!==null&&$!==void 0&&$}get flagsEndpointWasHit(){var $,ts;return($=(ts=this.featureFlags)==null?void 0:ts.hasLoadedFlags)!==null&&$!==void 0&&$}constructor(){var $;this.webPerformance=new Hn,this.Mi=!1,this.version=v.LIB_VERSION,this.Fi=new hn,this.Ri=[],this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=jn(),this.SentryIntegration=Sr,this.sentryIntegration=is=>(function(cs,Kr){var Xr=Er(cs,Kr);return{name:xr,processEvent:Na=>Xr(Na)}})(this,is),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Oi=!1,this.Pi=null,this.Li=null,this.Di=null,this.scrollManager=new an(this),this.pageViewManager=new $r(this),this.rateLimiter=new hs(this),this.requestRouter=new xn(this),this.consent=new _r(this),this.externalIntegrations=new Pn(this);var ts=($=qn.__defaultExtensionClasses)!==null&&$!==void 0?$:{};this.featureFlags=ts.featureFlags&&new ts.featureFlags(this),this.toolbar=ts.toolbar&&new ts.toolbar(this),this.surveys=ts.surveys&&new ts.surveys(this),this.conversations=ts.conversations&&new ts.conversations(this),this.logs=ts.logs&&new ts.logs(this),this.experiments=ts.experiments&&new ts.experiments(this),this.exceptions=ts.exceptions&&new ts.exceptions(this),this.people={set:(is,cs,Kr)=>{var Xr=F(is)?{[is]:cs}:is;this.setPersonProperties(Xr),Kr==null||Kr({})},set_once:(is,cs,Kr)=>{var Xr=F(is)?{[is]:cs}:is;this.setPersonProperties(void 0,Xr),Kr==null||Kr({})}},this.on("eventCaptured",(is=>Ie.info('send "'+(is==null?void 0:is.event)+'"',is)))}init($,ts,is){if(is&&is!==Un){var cs,Kr=(cs=In[is])!==null&&cs!==void 0?cs:new qn;return Kr._init($,ts,is),In[is]=Kr,In[Un][is]=Kr,Kr}return this._init($,ts,is)}_init($,ts,is){var cs,Kr;if(ts===void 0&&(ts={}),C($)||A($))return Ie.critical("PostHog was initialized without a token. This likely indicates a misconfiguration. Please check the first argument passed to posthog.init()"),this;if(this.__loaded)return console.warn("[PostHog.js]","You have already initialized PostHog! Re-initializing is a no-op"),this;this.__loaded=!0,this.config={},ts.debug=this.Bi(ts.debug),this.ji=ts,this.$i=[],ts.person_profiles?this.Li=ts.person_profiles:ts.process_person&&(this.Li=ts.process_person),this.set_config(qi({},jn(ts.defaults),Bn(ts),{name:is,token:$})),this.config.on_xhr_error&&Ie.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=ts.disable_compression?void 0:ps.GZipJS;var Xr=this.qi();this.persistence=new Yr(this.config,Xr),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Yr(f({},this.config,{persistence:"sessionStorage"}),Xr);var Na=f({},this.persistence.props),Ca=f({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Zi=new sn((qa=>this.Vi(qa)),this.config.request_queue_config),this.Hi=new on(this),this.__request_queue=[];var Aa=this.Ni();if(Aa||(this.sessionManager=new vn(this),this.sessionPropsManager=new un(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Ie.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.zi(Aa)}),0)):(Ie.info("Initializing extensions synchronously"),this.zi(Aa)),v.DEBUG=v.DEBUG||this.config.debug,v.DEBUG&&Ie.info("Starting in debug mode",{this:this,config:ts,thisC:f({},this.config),p:Na,s:Ca}),!this.config.identity_distinct_id||(cs=ts.bootstrap)!=null&&cs.distinctID||(ts.bootstrap=f({},ts.bootstrap,{distinctID:this.config.identity_distinct_id,isIdentifiedID:!0})),((Kr=ts.bootstrap)==null?void 0:Kr.distinctID)!==void 0){var Ia=ts.bootstrap.distinctID,Ma=this.get_distinct_id(),Pa=this.persistence.get_property(mi);if(ts.bootstrap.isIdentifiedID&&Ma!=null&&Ma!==Ia&&Pa===Fi)this.identify(Ia);else if(ts.bootstrap.isIdentifiedID&&Ma!=null&&Ma!==Ia&&Pa===Ai)Ie.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{var La=this.config.get_device_id(sr()),Fa=ts.bootstrap.isIdentifiedID?La:Ia;this.persistence.set_property(mi,ts.bootstrap.isIdentifiedID?Ai:Fi),this.register({distinct_id:Ia,$device_id:Fa})}}if(Aa)this.register_once({distinct_id:Ti,$device_id:null},"");else if(!this.get_distinct_id()){var Ba=this.config.get_device_id(sr());this.register_once({distinct_id:Ba,$device_id:Ba},""),this.persistence.set_property(mi,Fi)}return Xi(t,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),ts.segment?(function(qa,za){var Va=qa.config.segment;if(!Va)return za();(function(Ga,Za){var Qa=Ga.config.segment;if(!Qa)return Za();var Xa=tl=>{var sl=()=>tl.anonymousId()||sr();Ga.config.get_device_id=sl,tl.id()&&(Ga.register({distinct_id:tl.id(),$device_id:sl()}),Ga.persistence.set_property(mi,Ai)),Za()},Ja=Qa.user();"then"in Ja&&P(Ja.then)?Ja.then(Xa):Xa(Ja)})(qa,(()=>{Va.register((Ga=>{Promise&&Promise.resolve||wr.warn("This browser does not have Promise support, and can not use the segment integration");var Za=(Qa,Xa)=>{if(!Xa)return Qa;Qa.event.userId||Qa.event.anonymousId===Ga.get_distinct_id()||(wr.info("No userId set, resetting PostHog"),Ga.reset()),Qa.event.userId&&Qa.event.userId!==Ga.get_distinct_id()&&(wr.info("UserId set, identifying with PostHog"),Ga.identify(Qa.event.userId));var Ja=Ga.calculateEventProperties(Xa,Qa.event.properties);return Qa.event.properties=Object.assign({},Ja,Qa.event.properties),Qa};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:Qa=>Za(Qa,Qa.event.event),page:Qa=>Za(Qa,Ui),identify:Qa=>Za(Qa,ji),screen:Qa=>Za(Qa,"$screen")}})(qa)).then((()=>{za()}))}))})(this,(()=>this.Ui())):this.Ui(),P(this.config._onCapture)&&this.config._onCapture!==Fn&&(Ie.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(qa=>this.config._onCapture(qa.event,qa)))),this.config.ip&&Ie.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}zi($){var ts,is,cs,Kr,Xr,Na,Ca,Aa=performance.now(),Ia=f({},qn.__defaultExtensionClasses,this.config.__extensionClasses),Ma=[];Ia.featureFlags&&this.Ri.push(this.featureFlags=(ts=this.featureFlags)!==null&&ts!==void 0?ts:new Ia.featureFlags(this)),Ia.exceptions&&this.Ri.push(this.exceptions=(is=this.exceptions)!==null&&is!==void 0?is:new Ia.exceptions(this)),Ia.historyAutocapture&&this.Ri.push(this.historyAutocapture=new Ia.historyAutocapture(this)),Ia.tracingHeaders&&this.Ri.push(new Ia.tracingHeaders(this)),Ia.siteApps&&this.Ri.push(this.siteApps=new Ia.siteApps(this)),Ia.sessionRecording&&!$&&this.Ri.push(this.sessionRecording=new Ia.sessionRecording(this)),this.config.disable_scroll_properties||Ma.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),Ia.autocapture&&this.Ri.push(this.autocapture=new Ia.autocapture(this)),Ia.surveys&&this.Ri.push(this.surveys=(cs=this.surveys)!==null&&cs!==void 0?cs:new Ia.surveys(this)),Ia.logs&&this.Ri.push(this.logs=(Kr=this.logs)!==null&&Kr!==void 0?Kr:new Ia.logs(this)),Ia.conversations&&this.Ri.push(this.conversations=(Xr=this.conversations)!==null&&Xr!==void 0?Xr:new Ia.conversations(this)),Ia.productTours&&this.Ri.push(this.productTours=new Ia.productTours(this)),Ia.heatmaps&&this.Ri.push(this.heatmaps=new Ia.heatmaps(this)),Ia.webVitalsAutocapture&&this.Ri.push(this.webVitalsAutocapture=new Ia.webVitalsAutocapture(this)),Ia.exceptionObserver&&this.Ri.push(this.exceptionObserver=new Ia.exceptionObserver(this)),Ia.deadClicksAutocapture&&this.Ri.push(this.deadClicksAutocapture=new Ia.deadClicksAutocapture(this,br)),Ia.toolbar&&this.Ri.push(this.toolbar=(Na=this.toolbar)!==null&&Na!==void 0?Na:new Ia.toolbar(this)),Ia.experiments&&this.Ri.push(this.experiments=(Ca=this.experiments)!==null&&Ca!==void 0?Ca:new Ia.experiments(this)),this.Ri.forEach((Pa=>{Pa.initialize&&Ma.push((()=>{Pa.initialize==null||Pa.initialize()}))})),Ma.push((()=>{if(this.Yi){var Pa=this.Yi;this.Yi=void 0,this.Nr(Pa)}})),this.Gi(Ma,Aa)}Gi($,ts){for(;$.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-ts>=30&&$.length>0)return void setTimeout((()=>{this.Gi($,ts)}),0);var is=$.shift();if(is)try{is()}catch(Kr){Ie.error("Error initializing extension:",Kr)}}var cs=Math.round(performance.now()-ts);this.register_for_session({[ki]:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",[Ri]:cs}),this.config.__preview_deferred_init_extensions&&Ie.info("PostHog extensions initialized ("+cs+"ms)")}Nr($){var ts;if(!r||!r.body)return Ie.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.Nr($)}),500);this.config.__preview_deferred_init_extensions&&(this.Yi=$),this.Wi=$,this.compression=void 0,$.supportedCompression&&!this.config.disable_compression&&(this.compression=w($.supportedCompression,ps.GZipJS)?ps.GZipJS:w($.supportedCompression,ps.Base64)?ps.Base64:void 0),(ts=$.analytics)!=null&&ts.endpoint&&(this.analyticsDefaultEndpoint=$.analytics.endpoint),this.set_config({person_profiles:this.Li?this.Li:Mi}),this.Ri.forEach((is=>is.onRemoteConfig==null?void 0:is.onRemoteConfig($)))}Ui(){try{this.config.loaded(this)}catch(is){Ie.critical("`loaded` function failed",is)}if(this.Xi(),this.config.internal_or_test_user_hostname&&s!=null&&s.hostname){var $=s.hostname,ts=this.config.internal_or_test_user_hostname;(typeof ts=="string"?$===ts:ts.test($))&&this.setInternalOrTestUser()}this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.Ni())&&this.Ji()}),1),this.Ki=new vs(this),this.Ki.load()}Xi(){var $;this.is_capturing()&&this.config.request_batching&&(($=this.Zi)==null||$.enable())}_dom_loaded(){this.is_capturing()&&Bi(this.__request_queue,($=>this.Vi($))),this.__request_queue=[],this.Xi()}_handle_unload(){var $,ts,is,cs;($=this.surveys)==null||$.handlePageUnload(),this.config.request_batching?(this.Qi()&&this.capture(Ni),(ts=this.logs)==null||ts.flushLogs("sendBeacon"),(is=this.Zi)==null||is.unload(),(cs=this.Hi)==null||cs.unload()):this.Qi()&&this.capture(Ni,null,{transport:"sendBeacon"})}_send_request($){this.__loaded&&(Nn?this.__request_queue.push($):this.rateLimiter.isServerRateLimited($.batchKey)||($.transport=$.transport||this.config.api_transport,$.url=Ks($.url,{ip:this.config.ip?1:0}),$.headers=f({},this.config.request_headers,$.headers),$.compression=$.compression==="best-available"?this.compression:$.compression,$.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&($.disableTransport=["sendBeacon"]),$.fetchOptions=$.fetchOptions||this.config.fetch_options,(ts=>{var is,cs,Kr,Xr=f({},ts);Xr.timeout=Xr.timeout||6e4,Xr.url=tn(Xr.url,Xr.compression);var Na=(is=Xr.transport)!==null&&is!==void 0?is:"fetch",Ca=en.filter((Ia=>!Xr.disableTransport||!Ia.transport||!Xr.disableTransport.includes(Ia.transport))),Aa=(cs=(Kr=(function(Ia,Ma){for(var Pa=0;Ia.length>Pa;Pa++)if(Ia[Pa].transport===Na)return Ia[Pa]})(Ca))==null?void 0:Kr.method)!==null&&cs!==void 0?cs:Ca[0].method;if(!Aa)throw new Error("No available transport method");Na!=="sendBeacon"&&Xr.data&&Xr.compression===ps.GZipJS&&l&&!Js?Zs(Xr).then((Ia=>{Aa(Ia)})).catch((Ia=>{if((Ma=>!(!Ma||typeof Ma!="object")&&("name"in Ma?String(Ma.name):"")==="NotReadableError")(Ia))return Js=!0,void Aa(f({},Xr,{compression:void 0,url:tn(ts.url,void 0)}));Aa(Xr)})):Aa(Xr)})(f({},$,{callback:ts=>{var is,cs;this.rateLimiter.checkForLimiting(ts),400>ts.statusCode||(is=(cs=this.config).on_request_error)==null||is.call(cs,ts),$.callback==null||$.callback(ts)}}))))}Vi($){this.Hi?this.Hi.retriableRequest($):this._send_request($)}_execute_array($){Cn++;try{var ts,is=[],cs=[],Kr=[];Bi($,(Na=>{Na&&(R(ts=Na[0])?Kr.push(Na):P(Na)?Na.call(this):R(Na)&&ts==="alias"?is.push(Na):R(Na)&&ts.indexOf("capture")!==-1&&P(this[ts])?Kr.push(Na):cs.push(Na))}));var Xr=function(Na,Ca){Bi(Na,(function(Aa){if(R(Aa[0])){var Ia=Ca;Hi(Aa,(function(Ma){Ia=Ia[Ma[0]].apply(Ia,Ma.slice(1))}))}else Ca[Aa[0]].apply(Ca,Aa.slice(1))}))};Xr(is,this),Xr(cs,this),Xr(Kr,this)}finally{Cn--}}push($){if(Cn>0&&R($)&&F($[0])){var ts=qn.prototype[$[0]];P(ts)&&ts.apply(this,$.slice(1))}else this._execute_array([$])}capture($,ts,is){var cs,Kr,Xr,Na,Ca;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Zi){if(this.is_capturing())if(!C($)&&F($)){var Aa=!this.config.opt_out_useragent_filter&&this._is_bot();if(!Aa||this.config.__preview_capture_bot_pageviews){var Ia=is!=null&&is.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(Ia==null||!Ia.isRateLimited){ts!=null&&ts.$current_url&&!F(ts==null?void 0:ts.$current_url)&&(Ie.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),ts==null||delete ts.$current_url),$!=="$exception"||is!=null&&is.en||Ie.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&&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();var Ma=new Date,Pa=(is==null?void 0:is.timestamp)||Ma,La=sr(),Fa={uuid:La,event:$,properties:this.calculateEventProperties($,ts||{},Pa,La)};$===Ui&&this.config.__preview_capture_bot_pageviews&&Aa&&(Fa.event="$bot_pageview",Fa.properties.$browser_type="bot"),Ia&&(Fa.properties.$lib_rate_limit_remaining_tokens=Ia.remainingTokens),is!=null&&is.$set&&(Fa.$set=is==null?void 0:is.$set);var Ba,qa,za,Va=this.tn(is==null?void 0:is.$set_once,$!==zi,$===ji);if(Va&&(Fa.$set_once=Va),is!=null&&is._noTruncate||(Kr=this.config.properties_string_max_length,Xr=Fa,Na=sl=>F(sl)?sl.slice(0,Kr):sl,Ca=new Set,Fa=(function sl(ol,ml){return ol!==Object(ol)?Na?Na(ol):ol:Ca.has(ol)?void 0:(Ca.add(ol),R(ol)?(rl=[],Bi(ol,(ll=>{rl.push(sl(ll))}))):(rl={},Hi(ol,((ll,dl)=>{Ca.has(ll)||(rl[dl]=sl(ll))}))),rl);var rl})(Xr)),Fa.timestamp=Pa,C(is==null?void 0:is.timestamp)||(Fa.properties.$event_time_override_provided=!0,Fa.properties.$event_time_override_system_time=Ma),$===rs.DISMISSED||$===rs.SENT){var Ga=ts==null?void 0:ts[ss.SURVEY_ID],Za=ts==null?void 0:ts[ss.SURVEY_ITERATION];(sl=>{try{var ol=(ml=>((rl,ll)=>{var dl=""+Sn+ll.id;return ll.current_iteration&&ll.current_iteration>0&&(dl=""+Sn+ll.id+"_"+ll.current_iteration),dl})(0,ml))(sl);if(localStorage.getItem(ol))return;localStorage.setItem(ol,"true")}catch(ml){En.error("Failed to persist survey seen state",ml)}})({id:Ga,current_iteration:Za}),Fa.$set=f({},Fa.$set,{[(Ba={id:Ga,current_iteration:Za},qa=$===rs.SENT?"responded":"dismissed",za="$survey_"+qa+"/"+Ba.id,Ba.current_iteration&&Ba.current_iteration>0&&(za="$survey_"+qa+"/"+Ba.id+"/"+Ba.current_iteration),za)]:!0})}else $===rs.SHOWN&&(Fa.$set=f({},Fa.$set,{[ss.SURVEY_LAST_SEEN_DATE]:new Date().toISOString()}));if($===as.SHOWN){var Qa=ts==null?void 0:ts[ls.TOUR_TYPE];Qa&&(Fa.$set=f({},Fa.$set,{[ls.TOUR_LAST_SEEN_DATE+"/"+Qa]:new Date().toISOString()}))}var Xa=f({},Fa.properties.$set,Fa.$set);if(I(Xa)||this.setPersonPropertiesForFlags(Xa),!D(this.config.before_send)){var Ja=this.rn(Fa);if(!Ja)return;Fa=Ja}this.Fi.emit("eventCaptured",Fa);var tl={method:"POST",url:(cs=is==null?void 0:is._url)!==null&&cs!==void 0?cs:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:Fa,compression:"best-available",batchKey:is==null?void 0:is._batchKey};return!this.config.request_batching||is&&(is==null||!is._batchKey)||is!=null&&is.send_instantly?this.Vi(tl):this.Zi.enqueue(tl),Fa}Ie.critical("This capture call is ignored due to client rate limiting.")}}else Ie.error("No event name provided to posthog.capture")}else Ie.uninitializedWarning("posthog.capture")}_addCaptureHook($){return this.on("eventCaptured",(ts=>$(ts.event,ts)))}calculateEventProperties($,ts,is,cs,Kr){if(is=is||new Date,!this.persistence||!this.sessionPersistence)return ts;var Xr=Kr?void 0:this.persistence.remove_event_timer($),Na=f({},ts);if(Na.token=this.config.token,Na.$config_defaults=this.config.defaults,this.Ni()&&(Na.$cookieless_mode=!0),$==="$snapshot"){var Ca=f({},this.persistence.properties(),this.sessionPersistence.properties());return Na.distinct_id=Ca.distinct_id,(!F(Na.distinct_id)&&!L(Na.distinct_id)||A(Na.distinct_id))&&Ie.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),Na}var Aa,Ia=(function(za,Va){var Ga,Za,Qa,Xa;if(!u)return{};var Ja,tl,sl,ol,ml,rl,ll,dl,_l=za?[...Fr,...Va||[]]:[],[il,hl]=(function(ul){for(var cl=0;Wt.length>cl;cl++){var[jl,el]=Wt[cl],pl=jl.exec(ul),bl=pl&&(P(el)?el(pl,ul):el);if(bl)return bl}return["",""]})(u);return qi(Yi({$os:il,$os_version:hl,$browser:Ht(u,navigator.vendor),$device:Gt(u),$device_type:(tl=u,sl={userAgentDataPlatform:(Ga=navigator)==null||(Ga=Ga.userAgentData)==null?void 0:Ga.platform,maxTouchPoints:(Za=navigator)==null?void 0:Za.maxTouchPoints,screenWidth:t==null||(Qa=t.screen)==null?void 0:Qa.width,screenHeight:t==null||(Xa=t.screen)==null?void 0:Xa.height,devicePixelRatio:t==null?void 0:t.devicePixelRatio},dl=Gt(tl),dl===st||dl===rt||dl==="Kobo"||dl==="Kindle Fire"||dl===At?it:dl===Et||dl===$t||dl===St||dl===It?"Console":dl===ot?"Wearable":dl?Z:(sl==null?void 0:sl.userAgentDataPlatform)==="Android"&&((ol=sl==null?void 0:sl.maxTouchPoints)!==null&&ol!==void 0?ol:0)>0?600>Math.min((ml=sl==null?void 0:sl.screenWidth)!==null&&ml!==void 0?ml:0,(rl=sl==null?void 0:sl.screenHeight)!==null&&rl!==void 0?rl:0)/((ll=sl==null?void 0:sl.devicePixelRatio)!==null&&ll!==void 0?ll:1)?Z:it:"Desktop"),$timezone:Vr(),$timezone_offset:Wr()}),{$current_url:Or(s==null?void 0:s.href,_l,Mr),$host:s==null?void 0:s.host,$pathname:s==null?void 0:s.pathname,$raw_user_agent:u.length>1e3?u.substring(0,997)+"...":u,$browser_version:Vt(u,navigator.vendor),$browser_language:jr(),$browser_language_prefix:(Ja=jr(),typeof Ja=="string"?Ja.split("-")[0]:void 0),$screen_height:t==null?void 0:t.screen.height,$screen_width:t==null?void 0:t.screen.width,$viewport_height:t==null?void 0:t.innerHeight,$viewport_width:t==null?void 0:t.innerWidth,$lib:v.LIB_NAME,$lib_version:v.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})})(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:Ma,windowId:Pa}=this.sessionManager.checkAndGetSessionAndWindowId(Kr,is.getTime());Na.$session_id=Ma,Na.$window_id=Pa}this.sessionPropsManager&&qi(Na,this.sessionPropsManager.getSessionProps());try{var La;this.sessionRecording&&qi(Na,this.sessionRecording.sdkDebugProperties),Na.$sdk_debug_retry_queue_size=(La=this.Hi)==null?void 0:La.length}catch(za){Na.$sdk_debug_error_capturing_properties=String(za)}if(this.requestRouter.region===bn&&(Na.$lib_custom_api_host=this.config.api_host),Aa=$!==Ui||Kr?$!==Ni||Kr?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(is):this.pageViewManager.doPageView(is,cs),Na=qi(Na,Aa),$===Ui&&r&&(Na.title=r.title),!C(Xr)){var Fa=is.getTime()-Xr;Na.$duration=parseFloat((Fa/1e3).toFixed(3))}u&&this.config.opt_out_useragent_filter&&(Na.$browser_type=this._is_bot()?"bot":"browser"),(Na=qi({},Ia,this.persistence.properties(),this.sessionPersistence.properties(),Na)).$is_identified=this._isIdentified(),R(this.config.property_denylist)?Hi(this.config.property_denylist,(function(za){delete Na[za]})):Ie.error(Ln+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var Ba=this.config.sanitize_properties;Ba&&(Ie.error(Dn),Na=Ba(Na,$));var qa=this.nn();return Na.$process_person_profile=qa,qa&&!Kr&&this.sn("_calculate_event_properties"),Na}tn($,ts,is){var cs;if(ts===void 0&&(ts=!0),is===void 0&&(is=!1),!this.persistence||!this.nn()||this.Mi&&!is)return $;var Kr=this.persistence.get_initial_props(),Xr=(cs=this.sessionPropsManager)==null?void 0:cs.getSetOnceProps(),Na=qi({},Kr,Xr||{},$||{}),Ca=this.config.sanitize_properties;return Ca&&(Ie.error(Dn),Na=Ca(Na,"$set_once")),ts&&(this.Mi=!0),I(Na)?void 0:Na}register($,ts){var is;(is=this.persistence)==null||is.register($,ts)}register_once($,ts,is){var cs;(cs=this.persistence)==null||cs.register_once($,ts,is)}register_for_session($){var ts;(ts=this.sessionPersistence)==null||ts.register($)}unregister($){var ts;(ts=this.persistence)==null||ts.unregister($)}unregister_for_session($){var ts;(ts=this.sessionPersistence)==null||ts.unregister($)}an($,ts){this.register({[$]:ts})}getFeatureFlag($,ts){var is;return(is=this.featureFlags)==null?void 0:is.getFeatureFlag($,ts)}getFeatureFlagPayload($){var ts;return(ts=this.featureFlags)==null?void 0:ts.getFeatureFlagPayload($)}getFeatureFlagResult($,ts){var is;return(is=this.featureFlags)==null?void 0:is.getFeatureFlagResult($,ts)}isFeatureEnabled($,ts){var is;return(is=this.featureFlags)==null?void 0:is.isFeatureEnabled($,ts)}reloadFeatureFlags(){var $;($=this.featureFlags)==null||$.reloadFeatureFlags()}updateFlags($,ts,is){var cs;(cs=this.featureFlags)==null||cs.updateFlags($,ts,is)}updateEarlyAccessFeatureEnrollment($,ts,is){var cs;(cs=this.featureFlags)==null||cs.updateEarlyAccessFeatureEnrollment($,ts,is)}getEarlyAccessFeatures($,ts,is){var cs;return ts===void 0&&(ts=!1),(cs=this.featureFlags)==null?void 0:cs.getEarlyAccessFeatures($,ts,is)}on($,ts){return this.Fi.on($,ts)}onFeatureFlags($){return this.featureFlags?this.featureFlags.onFeatureFlags($):($([],{},{errorsLoading:!0}),()=>{})}onSurveysLoaded($){return this.surveys?this.surveys.onSurveysLoaded($):($([],{isLoaded:!1,error:Mn}),()=>{})}onSessionId($){var ts,is;return(ts=(is=this.sessionManager)==null?void 0:is.onSessionId($))!==null&&ts!==void 0?ts:()=>{}}getSurveys($,ts){ts===void 0&&(ts=!1),this.surveys?this.surveys.getSurveys($,ts):$([],{isLoaded:!1,error:Mn})}getActiveMatchingSurveys($,ts){ts===void 0&&(ts=!1),this.surveys?this.surveys.getActiveMatchingSurveys($,ts):$([],{isLoaded:!1,error:Mn})}renderSurvey($,ts){var is;(is=this.surveys)==null||is.renderSurvey($,ts)}displaySurvey($,ts){var is;ts===void 0&&(ts=Tn),(is=this.surveys)==null||is.displaySurvey($,ts)}cancelPendingSurvey($){var ts;(ts=this.surveys)==null||ts.cancelPendingSurvey($)}canRenderSurvey($){var ts,is;return(ts=(is=this.surveys)==null?void 0:is.canRenderSurvey($))!==null&&ts!==void 0?ts:{visible:!1,disabledReason:Mn}}canRenderSurveyAsync($,ts){var is,cs;return ts===void 0&&(ts=!1),(is=(cs=this.surveys)==null?void 0:cs.canRenderSurveyAsync($,ts))!==null&&is!==void 0?is:Promise.resolve({visible:!1,disabledReason:Mn})}ln($){return!$||A($)?(Ie.critical("Unique user id has not been set in posthog.identify"),!1):$===Ti?(Ie.critical('The string "'+$+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.'),!1):!["distinct_id","distinctid"].includes($.toLowerCase())&&!["undefined","null"].includes($.toLowerCase())||(Ie.critical('The string "'+$+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.'),!1)}identify($,ts,is){if(!this.__loaded||!this.persistence)return Ie.uninitializedWarning("posthog.identify");if(L($)&&($=$.toString(),Ie.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),this.ln($)&&this.sn("posthog.identify")){var cs=this.get_distinct_id();this.register({$user_id:$}),this.get_property(De)||this.register_once({$had_persisted_distinct_id:!0,$device_id:cs},""),$!==cs&&$!==this.get_property(Le)&&(this.unregister(Le),this.register({distinct_id:$}));var Kr,Xr=(this.persistence.get_property(mi)||Fi)===Fi;$!==cs&&Xr?(this.persistence.set_property(mi,Ai),this.setPersonPropertiesForFlags({$set:ts||{},$set_once:is||{}},!1),this.capture(ji,{distinct_id:$,$anon_distinct_id:cs},{$set:ts||{},$set_once:is||{}}),this.Di=fn($,ts,is),(Kr=this.featureFlags)==null||Kr.setAnonymousDistinctId(cs)):(ts||is)&&this.setPersonProperties(ts,is),$!==cs&&(this.reloadFeatureFlags(),this.unregister(pi))}}setPersonProperties($,ts){if(($||ts)&&this.sn("posthog.setPersonProperties")){var is=fn(this.get_distinct_id(),$,ts);this.Di!==is?(this.setPersonPropertiesForFlags({$set:$||{},$set_once:ts||{}},!0),this.capture("$set",{$set:$||{},$set_once:ts||{}}),this.Di=is):Ie.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group($,ts,is){if($&&ts){var cs=this.getGroups(),Kr=cs[$]!==ts;if(Kr&&this.resetGroupPropertiesForFlags($),this.register({$groups:f({},cs,{[$]:ts})}),Kr||is){var Xr={$group_type:$,$group_key:ts};is&&(Xr.$group_set=is),this.capture(zi,Xr)}is&&this.setGroupPropertiesForFlags({[$]:is}),Kr&&!is&&this.reloadFeatureFlags()}else Ie.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags($,ts){var is;ts===void 0&&(ts=!0),(is=this.featureFlags)==null||is.setPersonPropertiesForFlags($,ts)}resetPersonPropertiesForFlags(){var $;($=this.featureFlags)==null||$.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags($,ts){var is;ts===void 0&&(ts=!0),this.sn("posthog.setGroupPropertiesForFlags")&&((is=this.featureFlags)==null||is.setGroupPropertiesForFlags($,ts))}resetGroupPropertiesForFlags($){var ts;(ts=this.featureFlags)==null||ts.resetGroupPropertiesForFlags($)}reset($){var ts,is,cs,Kr,Xr,Na,Ca,Aa;if(Ie.info("reset"),!this.__loaded)return Ie.uninitializedWarning("posthog.reset");var Ia=this.get_property(De);if(this.consent.reset(),(ts=this.persistence)==null||ts.clear(),(is=this.sessionPersistence)==null||is.clear(),(cs=this.surveys)==null||cs.reset(),(Kr=this.Ki)==null||Kr.stop(),(Xr=this.featureFlags)==null||Xr.reset(),(Na=this.conversations)==null||Na.reset(),(Ca=this.persistence)==null||Ca.set_property(mi,Fi),(Aa=this.sessionManager)==null||Aa.resetSessionId(),this.Di=null,this.config.cookieless_mode===Ci)this.register_once({distinct_id:Ti,$device_id:null},"");else{var Ma=this.config.get_device_id(sr());this.register_once({distinct_id:Ma,$device_id:$?Ma:Ia},"")}this.register({$last_posthog_reset:new Date().toISOString()},1),delete this.config.identity_distinct_id,delete this.config.identity_hash,this.reloadFeatureFlags()}setIdentity($,ts){var is;this.config.identity_distinct_id=$,this.config.identity_hash=ts,this.alias($),(is=this.conversations)==null||is.un()}clearIdentity(){var $;delete this.config.identity_distinct_id,delete this.config.identity_hash,($=this.conversations)==null||$.hn()}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var $,ts;return($=(ts=this.sessionManager)==null?void 0:ts.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&$!==void 0?$:""}get_session_replay_url($){if(!this.sessionManager)return"";var{sessionId:ts,sessionStartTimestamp:is}=this.sessionManager.checkAndGetSessionAndWindowId(!0),cs=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+ts);if($!=null&&$.withTimestamp&&is){var Kr,Xr=(Kr=$.timestampLookBack)!==null&&Kr!==void 0?Kr:10;if(!is)return cs;cs+="?t="+Math.max(Math.floor((new Date().getTime()-is)/1e3)-Xr,0)}return cs}alias($,ts){return $===this.get_property(Me)?(Ie.critical("Attempting to create alias for existing People user - aborting."),-2):this.sn("posthog.alias")?(C(ts)&&(ts=this.get_distinct_id()),$!==ts?(this.an(Le,$),this.capture("$create_alias",{alias:$,distinct_id:ts})):(Ie.warn("alias matches current distinct_id - skipping api call."),this.identify($),-1)):void 0}set_config($){var ts=f({},this.config);if(O($)){var is,cs,Kr,Xr,Na,Ca,Aa,Ia,Ma,Pa;qi(this.config,Bn($));var La=this.qi();(is=this.persistence)==null||is.update_config(this.config,ts,La),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Yr(f({},this.config,{persistence:"sessionStorage"}),La);var Fa=this.Bi(this.config.debug);N(Fa)&&(this.config.debug=Fa),N(this.config.debug)&&(this.config.debug?(v.DEBUG=!0,hr.R()&&hr.M("ph_debug",!0),Ie.info("set_config",{config:$,oldConfig:ts,newConfig:f({},this.config)})):(v.DEBUG=!1,hr.R()&&hr.F("ph_debug"))),(cs=this.exceptionObserver)==null||cs.onConfigChange(),(Kr=this.exceptions)==null||Kr.onConfigChange(),(Xr=this.sessionRecording)==null||Xr.startIfEnabledOrStop(),(Na=this.autocapture)==null||Na.startIfEnabled(),(Ca=this.heatmaps)==null||Ca.startIfEnabled(),(Aa=this.exceptionObserver)==null||Aa.startIfEnabledOrStop(),(Ia=this.deadClicksAutocapture)==null||Ia.startIfEnabledOrStop(),(Ma=this.surveys)==null||Ma.loadIfEnabled(),this.cn(),(Pa=this.externalIntegrations)==null||Pa.startIfEnabledOrStop()}}_overrideSDKInfo($,ts){v.LIB_NAME=$,v.LIB_VERSION=ts}startSessionRecording($){var ts,is,cs,Kr,Xr,Na=$===!0,Ca={sampling:Na||!($==null||!$.sampling),linked_flag:Na||!($==null||!$.linked_flag),url_trigger:Na||!($==null||!$.url_trigger),event_trigger:Na||!($==null||!$.event_trigger)};Object.values(Ca).some(Boolean)&&((ts=this.sessionManager)==null||ts.checkAndGetSessionAndWindowId(),Ca.sampling&&((is=this.sessionRecording)==null||is.overrideSampling()),Ca.linked_flag&&((cs=this.sessionRecording)==null||cs.overrideLinkedFlag()),Ca.url_trigger&&((Kr=this.sessionRecording)==null||Kr.overrideTrigger("url")),Ca.event_trigger&&((Xr=this.sessionRecording)==null||Xr.overrideTrigger("event"))),this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var $;return!(($=this.sessionRecording)==null||!$.started)}captureException($,ts){if(this.exceptions){var is=new Error("PostHog syntheticException"),cs=this.exceptions.buildProperties($,{handled:!0,syntheticException:is});return this.exceptions.sendExceptionEvent(f({},cs,ts))}}addExceptionStep($,ts){var is;(is=this.exceptions)==null||is.addExceptionStep($,ts)}captureLog($){var ts;(ts=this.logs)==null||ts.captureLog($)}get logger(){var $,ts;return($=(ts=this.logs)==null?void 0:ts.logger)!==null&&$!==void 0?$:qn.dn}startExceptionAutocapture($){this.set_config({capture_exceptions:$==null||$})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar($){var ts,is;return(ts=(is=this.toolbar)==null?void 0:is.loadToolbar($))!==null&&ts!==void 0&&ts}get_property($){var ts;return(ts=this.persistence)==null?void 0:ts.props[$]}getSessionProperty($){var ts;return(ts=this.sessionPersistence)==null?void 0:ts.props[$]}toString(){var $,ts=($=this.config.name)!==null&&$!==void 0?$:Un;return ts!==Un&&(ts=Un+"."+ts),ts}_isIdentified(){var $,ts;return(($=this.persistence)==null?void 0:$.get_property(mi))===Ai||((ts=this.sessionPersistence)==null?void 0:ts.get_property(mi))===Ai}nn(){var $,ts;return!(this.config.person_profiles==="never"||this.config.person_profiles===Mi&&!this._isIdentified()&&I(this.getGroups())&&(($=this.persistence)==null||($=$.props)==null||!$[Le])&&((ts=this.persistence)==null||(ts=ts.props)==null||!ts[Si]))}Qi(){return this.config.capture_pageleave===!0||this.config.capture_pageleave==="if_capture_pageview"&&(this.config.capture_pageview===!0||this.config.capture_pageview==="history_change")}createPersonProfile(){this.nn()||this.sn("posthog.createPersonProfile")&&this.setPersonProperties({},{})}setInternalOrTestUser(){this.sn("posthog.setInternalOrTestUser")&&this.setPersonProperties({$internal_or_test_user:!0})}sn($){return this.config.person_profiles==="never"?(Ie.error($+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.an(Si,!0),!0)}qi(){if(this.config.cookieless_mode==="always")return!0;var $=this.consent.isOptedOut();return this.config.disable_persistence||$&&!(!this.config.opt_out_persistence_by_default&&this.config.cookieless_mode!==Ii)}cn(){var $,ts,is,cs,Kr=this.qi();return(($=this.persistence)==null?void 0:$._r)!==Kr&&((is=this.persistence)==null||is.set_disabled(Kr)),((ts=this.sessionPersistence)==null?void 0:ts._r)!==Kr&&((cs=this.sessionPersistence)==null||cs.set_disabled(Kr)),Kr}opt_in_capturing($){var ts;if(this.config.cookieless_mode!==Ci){if(this.Ni()){var is,cs,Kr,Xr,Na;this.reset(!0),(is=this.sessionManager)==null||is.destroy(),(cs=this.pageViewManager)==null||cs.destroy(),this.sessionManager=new vn(this),this.pageViewManager=new $r(this),this.persistence&&(this.sessionPropsManager=new un(this,this.sessionManager,this.persistence));var Ca,Aa=(Kr=(Xr=this.config.__extensionClasses)==null?void 0:Xr.sessionRecording)!==null&&Kr!==void 0?Kr:(Na=qn.__defaultExtensionClasses)==null?void 0:Na.sessionRecording;Aa&&(this.sessionRecording=this.Ei(this.sessionRecording,new Aa(this)),this.Wi&&((Ca=this.sessionRecording)==null||Ca.onRemoteConfig==null||Ca.onRemoteConfig(this.Wi)))}var Ia,Ma;this.consent.optInOut(!0),this.cn(),this.Xi(),(ts=this.sessionRecording)==null||ts.startIfEnabledOrStop(),this.config.cookieless_mode==Ii&&((Ia=this.surveys)==null||Ia.loadIfEnabled()),(C($==null?void 0:$.captureEventName)||$!=null&&$.captureEventName)&&this.capture((Ma=$==null?void 0:$.captureEventName)!==null&&Ma!==void 0?Ma:"$opt_in",$==null?void 0:$.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Ji()}else Ie.warn(An)}opt_out_capturing(){var $,ts,is;this.config.cookieless_mode!==Ci?(this.config.cookieless_mode===Ii&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.cn(),this.config.cookieless_mode===Ii&&(this.register({distinct_id:Ti,$device_id:null}),($=this.sessionManager)==null||$.destroy(),(ts=this.pageViewManager)==null||ts.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(is=this.sessionRecording)==null||is.stopRecording(),this.sessionRecording=void 0,this.Ji())):Ie.warn(An)}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var $=this.consent.consent;return $===1?"granted":$===0?"denied":"pending"}is_capturing(){return this.config.cookieless_mode===Ci||(this.config.cookieless_mode===Ii?this.consent.isRejected()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.cn()}_is_bot(){return i?cn(i,this.config.custom_blocked_useragents):void 0}Ji(){r&&(r.visibilityState==="visible"?this.Oi||(this.Oi=!0,this.capture(Ui,{title:r.title},{send_instantly:!0}),this.Pi&&(r.removeEventListener(Di,this.Pi),this.Pi=null)):this.Pi||(this.Pi=this.Ji.bind(this),Xi(r,Di,this.Pi)))}debug($){$===!1?(t==null||t.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(t==null||t.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}))}Fr(){var $,ts,is,cs,Kr,Xr,Na=this.ji||{};return"advanced_disable_flags"in Na?!!Na.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Ie.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):(is="advanced_disable_decide",cs=Ie,Kr=(ts="advanced_disable_flags")in($=Na)&&!D($[ts]),Xr=is in $&&!D($[is]),Kr?$[ts]:!!Xr&&(cs&&cs.warn("Config field '"+is+"' is deprecated. Please use '"+ts+"' instead. The old field will be removed in a future major version."),$[is]))}rn($){if(D(this.config.before_send))return $;var ts=R(this.config.before_send)?this.config.before_send:[this.config.before_send],is=$;for(var cs of ts){if(is=cs(is),D(is)){var Kr="Event '"+$.event+"' was rejected in beforeSend function";return z($.event)?Ie.warn(Kr+". This can cause unexpected behavior."):Ie.info(Kr),null}is.properties&&!I(is.properties)||Ie.warn("Event '"+$.event+"' has no properties after beforeSend function, this is likely an error.")}return is}getPageViewId(){var $;return($=this.pageViewManager.dr)==null?void 0:$.pageViewId}captureTraceFeedback($,ts){this.capture("$ai_feedback",{$ai_trace_id:String($),$ai_feedback_text:ts})}captureTraceMetric($,ts,is){this.capture("$ai_metric",{$ai_trace_id:String($),$ai_metric_name:ts,$ai_metric_value:String(is)})}Bi($){var ts=N($)&&!$,is=hr.R()&&hr.O("ph_debug")==="true";return!ts&&(!!is||$)}}qn.__defaultExtensionClasses={},qn.dn={trace:On=()=>{},debug:On,info:On,warn:On,error:On,fatal:On},(function(es,$){for(var ts=0;$.length>ts;ts++)es.prototype[$[ts]]=Gi(es.prototype[$[ts]])})(qn,["identify"]);var Vn=1,Wn=3,Gn=11;function Yn(es){return es instanceof Element&&(es.id===$i||!(es.closest==null||!es.closest(".toolbar-global-fade-container")))}function Jn(es){return!!es&&es.nodeType===Vn}function Kn(es,$){return!!es&&!!es.tagName&&es.tagName.toLowerCase()===$.toLowerCase()}function Xn(es){return!!es&&es.nodeType===Wn}function Qn(es){return!!es&&es.nodeType===Gn&&Jn(es.host)}function Zn(es){return es?x(es).split(/\s+/):[]}function to(es){var $=t==null?void 0:t.location.href;return!!($&&es&&es.some((ts=>$.match(ts))))}function eo(es){var $="";switch(typeof es.className){case"string":$=es.className;break;case"object":$=(es.className&&"baseVal"in es.className?es.className.baseVal:null)||es.getAttribute("class")||"";break;default:$=""}return Zn($)}function io(es){return D(es)?null:x(es).split(/(\s+)/).filter(($=>wo($))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function ro(es){var $="";return co(es)&&!po(es)&&es.childNodes&&es.childNodes.length&&Hi(es.childNodes,(function(ts){var is;Xn(ts)&&ts.textContent&&($+=(is=io(ts.textContent))!==null&&is!==void 0?is:"")})),x($)}function so(es){return C(es.target)?es.srcElement||null:($=es.target)!=null&&$.shadowRoot?es.composedPath()[0]||null:es.target||null;var $}var no=["a","button","form","input","select","textarea","label"];function oo(es,$){if(C($))return!0;var ts,is=function(Kr){if($.some((Xr=>Kr.matches(Xr))))return{v:!0}};for(var cs of es)if(ts=is(cs))return ts.v;return!1}function ao(es){var $=es.parentNode;return!(!$||!Jn($))&&$}var lo=["next","previous","prev",">","<"],uo=[".ph-no-rageclick",".ph-no-capture"],ho=es=>!es||Kn(es,"html")||!Jn(es),vo=(es,$)=>{if(!t||ho(es))return{parentIsUsefulElement:!1,targetElementList:[]};for(var ts=!1,is=[es],cs=es;cs.parentNode&&!Kn(cs,"body");)if(Qn(cs.parentNode))is.push(cs.parentNode.host),cs=cs.parentNode.host;else{var Kr=ao(cs);if(!Kr)break;if($||no.indexOf(Kr.tagName.toLowerCase())>-1)ts=!0;else{var Xr=t.getComputedStyle(Kr);Xr&&Xr.getPropertyValue("cursor")==="pointer"&&(ts=!0)}is.push(Kr),cs=Kr}return{parentIsUsefulElement:ts,targetElementList:is}};function co(es){for(var $=es;$.parentNode&&!Kn($,"body");$=$.parentNode){var ts=eo($);if(w(ts,"ph-sensitive")||w(ts,"ph-no-capture"))return!1}if(w(eo(es),"ph-include"))return!0;var is=es.type||"";if(F(is))switch(is.toLowerCase()){case"hidden":case"password":return!1}var cs=es.name||es.id||"";return!F(cs)||!/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(cs.replace(/[^a-zA-Z0-9]/g,""))}function po(es){return!!(Kn(es,"input")&&!["button","checkbox","submit","reset"].includes(es.type)||Kn(es,"select")||Kn(es,"textarea")||es.getAttribute("contenteditable")==="true")}var fo="(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})",_o=new RegExp("^(?:"+fo+")$"),go=new RegExp(fo),mo="\\d{3}-?\\d{2}-?\\d{4}",bo=new RegExp("^("+mo+")$"),yo=new RegExp("("+mo+")");function wo(es,$){return $===void 0&&($=!0),!(D(es)||F(es)&&(es=x(es),($?_o:go).test((es||"").replace(/[- ]/g,""))||($?bo:yo).test(es)))}function xo(es){var $=ro(es);return wo($=($+" "+Eo(es)).trim())?$:""}function Eo(es){var $="";return es&&es.childNodes&&es.childNodes.length&&Hi(es.childNodes,(function(ts){var is;if(ts&&((is=ts.tagName)==null?void 0:is.toLowerCase())==="span")try{var cs=ro(ts);$=($+" "+cs).trim(),ts.childNodes&&ts.childNodes.length&&($=($+" "+Eo(ts)).trim())}catch(Kr){Ie.error("[AutoCapture]",Kr)}})),$}function So(es){return es.replace(/"|\\"/g,'\\"')}function $o(es){var $=es.attr__class;return $?R($)?$:Zn($):void 0}class To{constructor($){this.disabled=$===!1;var ts=O($)?$:{};this.thresholdPx=ts.threshold_px||30,this.timeoutMs=ts.timeout_ms||1e3,this.clickCount=ts.click_count||3,this.clicks=[]}isRageClick($,ts,is){if(this.disabled)return!1;var cs=this.clicks[this.clicks.length-1];if(cs&&Math.abs($-cs.x)+Math.abs(ts-cs.y)<this.thresholdPx&&this.timeoutMs>is-cs.timestamp){if(this.clicks.push({x:$,y:ts,timestamp:is}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:$,y:ts,timestamp:is}];return!1}}var ko="$copy_autocapture",Ro=Ce("[AutoCapture]");function Po(es,$){return $.length>es?$.slice(0,es)+"...":$}function Oo(es){if(es.previousElementSibling)return es.previousElementSibling;var $=es;do $=$.previousSibling;while($&&!Jn($));return $}function Io(es,$){var ts,is,{e:cs,maskAllElementAttributes:Kr,maskAllText:Xr,elementAttributeIgnoreList:Na,elementsChainAsString:Ca}=$;if(!Jn(es))return{props:{}};for(var Aa=[es],Ia=es;Ia.parentNode&&!Kn(Ia,"body");)if(Qn(Ia.parentNode))Aa.push(Ia.parentNode.host),Ia=Ia.parentNode.host;else{if(!Jn(Ia.parentNode))break;Aa.push(Ia.parentNode),Ia=Ia.parentNode}var Ma,Pa,La=[],Fa={},Ba=!1,qa=!1;if(Hi(Aa,(Qa=>{var Xa=co(Qa);if(Kn(Qa,"a")){var Ja=Qa.getAttribute("href");Ba=Xa&&!!Ja&&wo(Ja)&&Ja}w(eo(Qa),"ph-no-capture")&&(qa=!0),La.push((function(sl,ol,ml,rl){var ll=sl.tagName.toLowerCase(),dl={tag_name:ll};no.indexOf(ll)>-1&&!ml&&(dl.$el_text=ll.toLowerCase()==="a"||ll.toLowerCase()==="button"?Po(1024,xo(sl)):Po(1024,ro(sl)));var _l=eo(sl);_l.length>0&&(dl.classes=_l.filter((function(cl){return cl!==""}))),Hi(sl.attributes,(function(cl){var jl;if((!po(sl)||["name","id","class","aria-label"].indexOf(cl.name)!==-1)&&(rl==null||!rl.includes(cl.name))&&!ol&&wo(cl.value)&&(!F(jl=cl.name)||jl.substring(0,10)!=="_ngcontent"&&jl.substring(0,7)!=="_nghost")){var el=cl.value;cl.name==="class"&&(el=Zn(el).join(" ")),dl["attr__"+cl.name]=Po(1024,el)}}));for(var il=1,hl=1,ul=sl;ul=Oo(ul);)il++,ul.tagName===sl.tagName&&hl++;return dl.nth_child=il,dl.nth_of_type=hl,dl})(Qa,Kr,Xr,Na));var tl=(function(sl){if(!co(sl))return{};var ol={};return Hi(sl.attributes,(function(ml){if(ml.name&&ml.name.indexOf("data-ph-capture-attribute")===0){var rl=ml.name.replace("data-ph-capture-attribute-",""),ll=ml.value;rl&&ll&&wo(ll)&&(ol[rl]=ll)}})),ol})(Qa);qi(Fa,tl)})),qa)return{props:{},explicitNoCapture:qa};if(Xr||(La[0].$el_text=Kn(es,"a")||Kn(es,"button")?xo(es):ro(es)),Ba){var za,Va;La[0].attr__href=Ba;var Ga=(za=Rr(Ba))==null?void 0:za.host,Za=t==null||(Va=t.location)==null?void 0:Va.host;Ga&&Za&&Ga!==Za&&(Ma=Ba)}return{props:qi({$event_type:cs.type,$ce_version:1},Ca?{}:{$elements:La},{$elements_chain:(Pa=La,(function(Qa){return Qa.map((Xa=>{var Ja,tl,sl="";if(Xa.tag_name&&(sl+=Xa.tag_name),Xa.attr_class)for(var ol of(Xa.attr_class.sort(),Xa.attr_class))sl+="."+ol.replace(/"/g,"");var ml=f({},Xa.text?{text:Xa.text}:{},{"nth-child":(Ja=Xa.nth_child)!==null&&Ja!==void 0?Ja:0,"nth-of-type":(tl=Xa.nth_of_type)!==null&&tl!==void 0?tl:0},Xa.href?{href:Xa.href}:{},Xa.attr_id?{attr_id:Xa.attr_id}:{},Xa.attributes),rl={};return Vi(ml).sort(((ll,dl)=>{var[_l]=ll,[il]=dl;return _l.localeCompare(il)})).forEach((ll=>{var[dl,_l]=ll;return rl[So(dl.toString())]=So(_l.toString())})),(sl+=":")+Vi(rl).map((ll=>{var[dl,_l]=ll;return dl+'="'+_l+'"'})).join("")})).join(";")})((function(Qa){return Qa.map((Xa=>{var Ja,tl,sl={text:(Ja=Xa.$el_text)==null?void 0:Ja.slice(0,400),tag_name:Xa.tag_name,href:(tl=Xa.attr__href)==null?void 0:tl.slice(0,2048),attr_class:$o(Xa),attr_id:Xa.attr__id,nth_child:Xa.nth_child,nth_of_type:Xa.nth_of_type,attributes:{}};return Vi(Xa).filter((ol=>{var[ml]=ol;return ml.indexOf("attr__")===0})).forEach((ol=>{var[ml,rl]=ol;return sl.attributes[ml]=rl})),sl}))})(Pa)))},(ts=La[0])!=null&&ts.$el_text?{$el_text:(is=La[0])==null?void 0:is.$el_text}:{},Ma&&cs.type==="click"?{$external_click_url:Ma}:{},Fa)}}var Co=Ce("[ExceptionAutocapture]");function Fo(es,$,ts){try{if(!($ in es))return()=>{};var is=es[$],cs=ts(is);return P(cs)&&(cs.prototype=cs.prototype||{},Object.defineProperties(cs,{__posthog_wrapped__:{enumerable:!1,value:!0}})),es[$]=cs,()=>{es[$]=is}}catch{return()=>{}}}var Ao=Ce("[TracingHeaders]"),Mo=Ce("[Web Vitals]"),Do=9e5,Lo="disabled",Uo="lazy_loading",No="awaiting_config",jo="missing_config";Ce("[SessionRecording]"),Ce("[SessionRecording]");var zo="[SessionRecording]",Bo=Ce(zo),Ho=Ce("[Heatmaps]");function qo(es){return O(es)&&"clientX"in es&&"clientY"in es&&L(es.clientX)&&L(es.clientY)}var Vo=Ce("[Product Tours]"),Wo=["$set_once","$set"],Go=Ce("[SiteApps]"),Yo="Error while initializing PostHog app with config id ";function Jo(es,$,ts){if(D(es))return!1;switch(ts){case"exact":return es===$;case"contains":var is=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(is,"i").test(es);case"regex":try{return new RegExp($).test(es)}catch{return!1}default:return!1}}class Ko{constructor($){this.vn=new hn,this.fn=(ts,is)=>this.pn(ts,is)&&this.gn(ts,is)&&this.mn(ts,is)&&this.yn(ts,is),this.pn=(ts,is)=>is==null||!is.event||(ts==null?void 0:ts.event)===(is==null?void 0:is.event),this._instance=$,this.bn=new Set,this._n=new Set}init(){var $,ts;C(($=this._instance)==null?void 0:$._addCaptureHook)||(ts=this._instance)==null||ts._addCaptureHook(((is,cs)=>{this.on(is,cs)}))}register($){var ts,is;if(!C((ts=this._instance)==null?void 0:ts._addCaptureHook)&&($.forEach((Xr=>{var Na,Ca;(Na=this._n)==null||Na.add(Xr),(Ca=Xr.steps)==null||Ca.forEach((Aa=>{var Ia;(Ia=this.bn)==null||Ia.add((Aa==null?void 0:Aa.event)||"")}))})),(is=this._instance)!=null&&is.autocapture)){var cs,Kr=new Set;$.forEach((Xr=>{var Na;(Na=Xr.steps)==null||Na.forEach((Ca=>{Ca!=null&&Ca.selector&&Kr.add(Ca==null?void 0:Ca.selector)}))})),(cs=this._instance)==null||cs.autocapture.setElementSelectors(Kr)}}on($,ts){var is;ts!=null&&$.length!=0&&(this.bn.has($)||this.bn.has(ts==null?void 0:ts.event))&&this._n&&((is=this._n)==null?void 0:is.size)>0&&this._n.forEach((cs=>{this.wn(ts,cs)&&this.vn.emit("actionCaptured",cs.name)}))}In($){this.onAction("actionCaptured",(ts=>$(ts)))}wn($,ts){if((ts==null?void 0:ts.steps)==null)return!1;for(var is of ts.steps)if(this.fn($,is))return!0;return!1}onAction($,ts){return this.vn.on($,ts)}gn($,ts){if(ts!=null&&ts.url){var is,cs=$==null||(is=$.properties)==null?void 0:is.$current_url;if(!cs||typeof cs!="string"||!Jo(cs,ts.url,ts.url_matching||"contains"))return!1}return!0}mn($,ts){return!!this.Cn($,ts)&&!!this.Sn($,ts)&&!!this.xn($,ts)}Cn($,ts){var is;if(ts==null||!ts.href)return!0;var cs=this.kn($);if(cs.length>0)return cs.some((Na=>Jo(Na.href,ts.href,ts.href_matching||"exact")));var Kr,Xr=($==null||(is=$.properties)==null?void 0:is.$elements_chain)||"";return!!Xr&&Jo((Kr=Xr.match(/(?::|")href="(.*?)"/))?Kr[1]:"",ts.href,ts.href_matching||"exact")}Sn($,ts){var is;if(ts==null||!ts.text)return!0;var cs=this.kn($);if(cs.length>0)return cs.some((Aa=>Jo(Aa.text,ts.text,ts.text_matching||"exact")||Jo(Aa.$el_text,ts.text,ts.text_matching||"exact")));var Kr,Xr,Na,Ca=($==null||(is=$.properties)==null?void 0:is.$elements_chain)||"";return!!Ca&&(Kr=(function(Aa){for(var Ia,Ma=[],Pa=/(?::|")text="(.*?)"/g;!D(Ia=Pa.exec(Aa));)Ma.includes(Ia[1])||Ma.push(Ia[1]);return Ma})(Ca),Xr=ts.text,Na=ts.text_matching||"exact",Kr.some((Aa=>Jo(Aa,Xr,Na))))}xn($,ts){var is,cs;if(ts==null||!ts.selector)return!0;var Kr=$==null||(is=$.properties)==null?void 0:is.$element_selectors;if(Kr!=null&&Kr.includes(ts.selector))return!0;var Xr=($==null||(cs=$.properties)==null?void 0:cs.$elements_chain)||"";if(ts.selector_regex&&Xr)try{return new RegExp(ts.selector_regex).test(Xr)}catch{return!1}return!1}kn($){var ts;return($==null||(ts=$.properties)==null?void 0:ts.$elements)==null?[]:$==null?void 0:$.properties.$elements}yn($,ts){return ts==null||!ts.properties||ts.properties.length===0||mn(ts.properties.reduce(((is,cs)=>{var Kr=R(cs.value)?cs.value.map(String):cs.value!=null?[String(cs.value)]:[];return is[cs.key]={values:Kr,operator:cs.operator||"exact"},is}),{}),$==null?void 0:$.properties)}}class Xo{constructor($){this._instance=$,this.Tn=new Map,this.An=new Map,this.En=new Map}Rn($,ts){return!!$&&mn($.propertyFilters,ts==null?void 0:ts.properties)}Nn($,ts){var is=new Map;return $.forEach((cs=>{var Kr;(Kr=cs.conditions)==null||(Kr=Kr[ts])==null||(Kr=Kr.values)==null||Kr.forEach((Xr=>{if(Xr!=null&&Xr.name){var Na=is.get(Xr.name)||[];Na.push(cs.id),is.set(Xr.name,Na)}}))})),is}Mn($,ts,is){var cs=(is===Jr.Activation?this.Tn:this.An).get($),Kr=[];return this.Fn((Xr=>{Kr=Xr.filter((Na=>cs==null?void 0:cs.includes(Na.id)))})),Kr.filter((Xr=>{var Na,Ca=(Na=Xr.conditions)==null||(Na=Na[is])==null||(Na=Na.values)==null?void 0:Na.find((Aa=>Aa.name===$));return this.Rn(Ca,ts)}))}register($){var ts;C((ts=this._instance)==null?void 0:ts._addCaptureHook)||(this.On($),this.Pn($))}Pn($){var ts=$.filter((is=>{var cs,Kr;return((cs=is.conditions)==null?void 0:cs.actions)&&((Kr=is.conditions)==null||(Kr=Kr.actions)==null||(Kr=Kr.values)==null?void 0:Kr.length)>0}));ts.length!==0&&(this.Ln==null&&(this.Ln=new Ko(this._instance),this.Ln.init(),this.Ln.In((is=>{this.onAction(is)}))),ts.forEach((is=>{var cs,Kr,Xr,Na,Ca;is.conditions&&(cs=is.conditions)!=null&&cs.actions&&(Kr=is.conditions)!=null&&(Kr=Kr.actions)!=null&&Kr.values&&((Xr=is.conditions)==null||(Xr=Xr.actions)==null||(Xr=Xr.values)==null?void 0:Xr.length)>0&&((Na=this.Ln)==null||Na.register(is.conditions.actions.values),(Ca=is.conditions)==null||(Ca=Ca.actions)==null||(Ca=Ca.values)==null||Ca.forEach((Aa=>{if(Aa&&Aa.name){var Ia=this.En.get(Aa.name);Ia&&Ia.push(is.id),this.En.set(Aa.name,Ia||[is.id])}})))})))}On($){var ts,is=$.filter((Kr=>{var Xr,Na;return((Xr=Kr.conditions)==null?void 0:Xr.events)&&((Na=Kr.conditions)==null||(Na=Na.events)==null||(Na=Na.values)==null?void 0:Na.length)>0})),cs=$.filter((Kr=>{var Xr,Na;return((Xr=Kr.conditions)==null?void 0:Xr.cancelEvents)&&((Na=Kr.conditions)==null||(Na=Na.cancelEvents)==null||(Na=Na.values)==null?void 0:Na.length)>0}));is.length===0&&cs.length===0||((ts=this._instance)==null||ts._addCaptureHook(((Kr,Xr)=>{this.onEvent(Kr,Xr)})),this.Tn=this.Nn($,Jr.Activation),this.An=this.Nn($,Jr.Cancellation))}onEvent($,ts){var is,cs=this.le(),Kr=this.Dn(),Xr=this.Bn(),Na=((is=this._instance)==null||(is=is.persistence)==null?void 0:is.props[Kr])||[];if(Xr===$&&ts&&Na.length>0){var Ca,Aa;cs.info("event matched, removing item from activated items",{event:$,eventPayload:ts,existingActivatedItems:Na});var Ia=(ts==null||(Ca=ts.properties)==null?void 0:Ca.$survey_id)||(ts==null||(Aa=ts.properties)==null?void 0:Aa.$product_tour_id);if(Ia){var Ma=Na.indexOf(Ia);0>Ma||(Na.splice(Ma,1),this.jn(Na))}}else{if(this.An.has($)){var Pa=this.Mn($,ts,Jr.Cancellation);Pa.length>0&&(cs.info("cancel event matched, cancelling items",{event:$,itemsToCancel:Pa.map((Fa=>Fa.id))}),Pa.forEach((Fa=>{var Ba=Na.indexOf(Fa.id);0>Ba||Na.splice(Ba,1),this.$n(Fa.id)})),this.jn(Na))}if(this.Tn.has($)){cs.info("event name matched",{event:$,eventPayload:ts,items:this.Tn.get($)});var La=this.Mn($,ts,Jr.Activation);this.jn(Na.concat(La.map((Fa=>Fa.id))||[]))}}}onAction($){var ts,is=this.Dn(),cs=((ts=this._instance)==null||(ts=ts.persistence)==null?void 0:ts.props[is])||[];this.En.has($)&&this.jn(cs.concat(this.En.get($)||[]))}jn($){var ts=this.le(),is=[...new Set($)].filter((cs=>!this.qn(cs)));ts.info("updating activated items",{activatedItems:is}),this.Zn(is)}getActivatedIds(){var $,ts=this.Dn();return(($=this._instance)==null||($=$.persistence)==null?void 0:$.props[ts])||[]}getEventToItemsMap(){return this.Tn}Vn(){return this.Ln}}class Qo extends Xo{constructor($){super($)}Dn(){return vi}Bn(){return rs.SHOWN}Fn($){var ts;(ts=this._instance)==null||ts.getSurveys($)}$n($){var ts;(ts=this._instance)==null||ts.cancelPendingSurvey($)}le(){return En}Zn($){var ts;(ts=this._instance)==null||(ts=ts.persistence)==null||ts.register({[vi]:$})}qn(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}var Zo="SDK is not enabled or survey functionality is not yet loaded",ta="Disabled. Not loading surveys.",ea=t!=null&&t.location?Ir(t.location.hash,"__posthog")||Ir(location.hash,"state"):null,ia="_postHogToolbarParams",ra=Ce("[Toolbar]"),sa=Ce("[FeatureFlags]"),na=Ce("[FeatureFlags]",{debugEnabled:!0}),oa=`" failed. Feature flags didn't load in time.`,aa=es=>{for(var $={},ts=0;es.length>ts;ts++)$[es[ts]]=!0;return $},la=es=>{var $={};for(var[ts,is]of Vi(es||{}))is&&($[ts]=is);return $},ua=Ce("[Error tracking]"),ha="Refusing to render web experiment since the viewer is a likely bot",da={icontains:(es,$)=>!!t&&$.href.toLowerCase().indexOf(es.toLowerCase())>-1,not_icontains:(es,$)=>!!t&&$.href.toLowerCase().indexOf(es.toLowerCase())===-1,regex:(es,$)=>!!t&&pn($.href,es),not_regex:(es,$)=>!!t&&!pn($.href,es),exact:(es,$)=>$.href===es,is_not:(es,$)=>$.href!==es};class va{get Bt(){return this._instance.config}constructor($){var ts=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(is){is===void 0&&(is=!1),ts.getWebExperiments((cs=>{va.Hn("retrieved web experiments from the server"),ts.zn=new Map,cs.forEach((Kr=>{if(Kr.feature_flag_key){var Xr;ts.zn&&(va.Hn("setting flag key ",Kr.feature_flag_key," to web experiment ",Kr),(Xr=ts.zn)==null||Xr.set(Kr.feature_flag_key,Kr));var Na=ts._instance.getFeatureFlag(Kr.feature_flag_key);F(Na)&&Kr.variants[Na]&&ts.Un(Kr.name,Na,Kr.variants[Na].transforms)}else if(Kr.variants)for(var Ca in Kr.variants){var Aa=Kr.variants[Ca];va.Yn(Aa)&&ts.Un(Kr.name,Ca,Aa.transforms)}}))}),is)},this._instance=$,this._instance.onFeatureFlags((is=>{this.onFeatureFlags(is)}))}initialize(){}onFeatureFlags($){if(this._is_bot())va.Hn(ha);else if(!this.Bt.disable_web_experiments){if(D(this.zn))return this.zn=new Map,this.loadIfEnabled(),void this.previewWebExperiment();va.Hn("applying feature flags",$),$.forEach((ts=>{var is;if(this.zn&&(is=this.zn)!=null&&is.has(ts)){var cs,Kr=this._instance.getFeatureFlag(ts),Xr=(cs=this.zn)==null?void 0:cs.get(ts);Kr&&Xr!=null&&Xr.variants[Kr]&&this.Un(Xr.name,Kr,Xr.variants[Kr].transforms)}}))}}previewWebExperiment(){var $=va.getWindowLocation();if($!=null&&$.search){var ts=Pr($==null?void 0:$.search,"__experiment_id"),is=Pr($==null?void 0:$.search,"__experiment_variant");ts&&is&&(va.Hn("previewing web experiments "+ts+" && "+is),this.getWebExperiments((cs=>{this.Gn(parseInt(ts),is,cs)}),!1,!0))}}loadIfEnabled(){this.Bt.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments($,ts,is){if(this.Bt.disable_web_experiments&&!is)return $([]);var cs=this._instance.get_property("$web_experiments");if(cs&&!ts)return $(cs);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this.Bt.token),method:"GET",callback:Kr=>$(Kr.statusCode===200&&Kr.json&&Kr.json.experiments||[])})}Gn($,ts,is){var cs=is.filter((Kr=>Kr.id===$));cs&&cs.length>0&&(va.Hn("Previewing web experiment ["+cs[0].name+"] with variant ["+ts+"]"),this.Un(cs[0].name,ts,cs[0].variants[ts].transforms))}static Yn($){return!D($.conditions)&&va.Wn($)&&va.Xn($)}static Wn($){var ts;if(D($.conditions)||D((ts=$.conditions)==null?void 0:ts.url))return!0;var is,cs,Kr,Xr=va.getWindowLocation();return!!Xr&&((is=$.conditions)==null||!is.url||da[(cs=(Kr=$.conditions)==null?void 0:Kr.urlMatchType)!==null&&cs!==void 0?cs:"icontains"]($.conditions.url,Xr))}static getWindowLocation(){return t==null?void 0:t.location}static Xn($){var ts;if(D($.conditions)||D((ts=$.conditions)==null?void 0:ts.utm))return!0;var is=Lr();if(is.utm_source){var cs,Kr,Xr,Na,Ca,Aa,Ia,Ma,Pa=(cs=$.conditions)==null||(cs=cs.utm)==null||!cs.utm_campaign||((Kr=$.conditions)==null||(Kr=Kr.utm)==null?void 0:Kr.utm_campaign)==is.utm_campaign,La=(Xr=$.conditions)==null||(Xr=Xr.utm)==null||!Xr.utm_source||((Na=$.conditions)==null||(Na=Na.utm)==null?void 0:Na.utm_source)==is.utm_source,Fa=(Ca=$.conditions)==null||(Ca=Ca.utm)==null||!Ca.utm_medium||((Aa=$.conditions)==null||(Aa=Aa.utm)==null?void 0:Aa.utm_medium)==is.utm_medium,Ba=(Ia=$.conditions)==null||(Ia=Ia.utm)==null||!Ia.utm_term||((Ma=$.conditions)==null||(Ma=Ma.utm)==null?void 0:Ma.utm_term)==is.utm_term;return Pa&&Fa&&Ba&&La}return!1}static Hn($){for(var ts=arguments.length,is=new Array(ts>1?ts-1:0),cs=1;ts>cs;cs++)is[cs-1]=arguments[cs];Ie.info("[WebExperiments] "+$,is)}Un($,ts,is){this._is_bot()?va.Hn(ha):ts!=="control"?is.forEach((cs=>{if(cs.selector){var Kr;va.Hn("applying transform of variant "+ts+" for experiment "+$+" ",cs);var Xr=(Kr=document)==null?void 0:Kr.querySelectorAll(cs.selector);Xr==null||Xr.forEach((Na=>{var Ca=Na;cs.html&&(Ca.innerHTML=cs.html),cs.css&&Ca.setAttribute("style",cs.css)}))}})):va.Hn("Control variants leave the page unmodified.")}_is_bot(){return i&&this._instance?cn(i,this.Bt.custom_blocked_useragents):void 0}}var ca=Ce("[Conversations]"),pa="Conversations not available yet.",fa={featureFlags:class{constructor(es){this.Jn=!1,this.Kn=!1,this.Qn=!1,this.es=!1,this.ts=!1,this.rs=!1,this.ns=!1,this.ss=!1,this._instance=es,this.featureFlagEventHandlers=[]}get Bt(){return this._instance.config}get ni(){return this._instance.persistence}os(es){return this._instance.get_property(es)}ls(){var es,$;return(es=($=this.ni)==null?void 0:$.wr(this.Bt.feature_flag_cache_ttl_ms))!==null&&es!==void 0&&es}us(){return!!this.ls()&&(this.ss||this.Qn||(this.ss=!0,sa.warn("Feature flag cache is stale, triggering refresh..."),this.reloadFeatureFlags()),!0)}hs(){var es,$=(es=this.Bt.evaluation_contexts)!==null&&es!==void 0?es:this.Bt.evaluation_environments;return!this.Bt.evaluation_environments||this.Bt.evaluation_contexts||this.ns||(sa.warn("evaluation_environments is deprecated. Use evaluation_contexts instead. evaluation_environments will be removed in a future version."),this.ns=!0),$!=null&&$.length?$.filter((ts=>{var is=ts&&typeof ts=="string"&&ts.trim().length>0;return is||sa.error("Invalid evaluation context found:",ts,"Expected non-empty string"),is})):[]}cs(){return this.hs().length>0}initialize(){var es,$,{config:ts}=this._instance,is=(es=($=ts.bootstrap)==null?void 0:$.featureFlags)!==null&&es!==void 0?es:{};if(Object.keys(is).length){var cs,Kr,Xr=(cs=(Kr=ts.bootstrap)==null?void 0:Kr.featureFlagPayloads)!==null&&cs!==void 0?cs:{},Na=Object.keys(is).filter((Aa=>!!is[Aa])).reduce(((Aa,Ia)=>(Aa[Ia]=is[Ia]||!1,Aa)),{}),Ca=Object.keys(Xr).filter((Aa=>Na[Aa])).reduce(((Aa,Ia)=>(Xr[Ia]&&(Aa[Ia]=Xr[Ia]),Aa)),{});this.receivedFeatureFlags({featureFlags:Na,featureFlagPayloads:Ca})}}updateFlags(es,$,ts){var is=ts!=null&&ts.merge?this.getFlagVariants():{},cs=ts!=null&&ts.merge?this.getFlagPayloads():{},Kr=f({},is,es),Xr=f({},cs,$),Na={};for(var[Ca,Aa]of Object.entries(Kr)){var Ia=typeof Aa=="string";Na[Ca]={key:Ca,enabled:!!Ia||!!Aa,variant:Ia?Aa:void 0,reason:void 0,metadata:C(Xr==null?void 0:Xr[Ca])?void 0:{id:0,version:void 0,description:void 0,payload:Xr[Ca]}}}this.receivedFeatureFlags({flags:Na})}get hasLoadedFlags(){return this.Kn}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var es=this.os(si),$=this.os(ai),ts=this.os(li);if(!ts&&!$)return es||{};var is=qi({},es||{}),cs=[...new Set([...Object.keys(ts||{}),...Object.keys($||{})])];for(var Kr of cs){var Xr,Na,Ca=is[Kr],Aa=$==null?void 0:$[Kr],Ia=C(Aa)?(Xr=Ca==null?void 0:Ca.enabled)!==null&&Xr!==void 0&&Xr:!!Aa,Ma=C(Aa)?Ca.variant:typeof Aa=="string"?Aa:void 0,Pa=ts==null?void 0:ts[Kr],La=f({},Ca,{enabled:Ia,variant:Ia?Ma??(Ca==null?void 0:Ca.variant):void 0});Ia!==(Ca==null?void 0:Ca.enabled)&&(La.original_enabled=Ca==null?void 0:Ca.enabled),Ma!==(Ca==null?void 0:Ca.variant)&&(La.original_variant=Ca==null?void 0:Ca.variant),Pa&&(La.metadata=f({},Ca==null?void 0:Ca.metadata,{payload:Pa,original_payload:Ca==null||(Na=Ca.metadata)==null?void 0:Na.payload})),is[Kr]=La}return this.Jn||(sa.warn(" Overriding feature flag details!",{flagDetails:es,overriddenPayloads:ts,finalDetails:is}),this.Jn=!0),is}getFlagVariants(){var es=this.os(ei),$=this.os(ai);if(!$)return es||{};for(var ts=qi({},es),is=Object.keys($),cs=0;is.length>cs;cs++)ts[is[cs]]=$[is[cs]];return this.Jn||(sa.warn(" Overriding feature flags!",{enabledFlags:es,overriddenFlags:$,finalFlags:ts}),this.Jn=!0),ts}getFlagPayloads(){var es=this.os(ni),$=this.os(li);if(!$)return es||{};for(var ts=qi({},es||{}),is=Object.keys($),cs=0;is.length>cs;cs++)ts[is[cs]]=$[is[cs]];return this.Jn||(sa.warn(" Overriding feature flag payloads!",{flagPayloads:es,overriddenPayloads:$,finalPayloads:ts}),this.Jn=!0),ts}reloadFeatureFlags(){this.es||this.Bt.advanced_disable_feature_flags||this.ds||(this._instance.Fi.emit("featureFlagsReloading",!0),this.ds=setTimeout((()=>{this.vs()}),5))}fs(){clearTimeout(this.ds),this.ds=void 0}ensureFlagsLoaded(){this.Kn||this.Qn||this.ds||this.reloadFeatureFlags()}setAnonymousDistinctId(es){this.$anon_distinct_id=es}setReloadingPaused(es){this.es=es}vs(es){var $;if(this.fs(),!this._instance.Fr())if(this.Qn)this.ts=!0;else{var ts=this.Bt.token,is=this.os(De),cs={token:ts,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:f({},(($=this.ni)==null?void 0:$.get_initial_props())||{},this.os(ui)||{}),group_properties:this.os(hi),timezone:Vr()};M(is)||C(is)||(cs.$device_id=is),(es!=null&&es.disableFlags||this.Bt.advanced_disable_feature_flags)&&(cs.disable_flags=!0),this.cs()&&(cs.evaluation_contexts=this.hs());var Kr=this._instance.requestRouter.endpointFor("flags","/flags/?v=2"+(this.Bt.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":""));this.Qn=!0,this._instance._send_request({method:"POST",url:Kr,data:cs,compression:this.Bt.disable_compression?void 0:ps.Base64,timeout:this.Bt.feature_flag_request_timeout_ms,callback:Xr=>{var Na,Ca,Aa,Ia=!0;if(Xr.statusCode===200&&(this.ts||(this.$anon_distinct_id=void 0),Ia=!1),this.Qn=!1,!cs.disable_flags||this.ts){this.rs=!Ia;var Ma=[];Xr.error?Xr.error instanceof Error?Ma.push(Xr.error.name==="AbortError"?"timeout":"connection_error"):Ma.push("unknown_error"):Xr.statusCode!==200&&Ma.push("api_error_"+Xr.statusCode),(Na=Xr.json)!=null&&Na.errorsWhileComputingFlags&&Ma.push("errors_while_computing_flags");var Pa,La=!((Ca=Xr.json)==null||(Ca=Ca.quotaLimited)==null||!Ca.includes("feature_flags"));La&&Ma.push("quota_limited"),(Aa=this.ni)==null||Aa.register({[_i]:Ma}),La?sa.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."):(cs.disable_flags||this.receivedFeatureFlags((Pa=Xr.json)!==null&&Pa!==void 0?Pa:{},Ia,{partialResponse:!!this.Bt.advanced_only_evaluate_survey_feature_flags}),this.ts&&(this.ts=!1,this.vs()))}}})}}getFeatureFlag(es,$){var ts;if($===void 0&&($={}),!$.fresh||this.rs)if(this.Kn||this.getFlags()&&this.getFlags().length>0){if(!this.us()){var is=this.getFeatureFlagResult(es,$);return(ts=is==null?void 0:is.variant)!==null&&ts!==void 0?ts:is==null?void 0:is.enabled}}else sa.warn('getFeatureFlag for key "'+es+oa)}getFeatureFlagDetails(es){return this.getFlagsWithDetails()[es]}getFeatureFlagPayload(es){var $=this.getFeatureFlagResult(es,{send_event:!1});return $==null?void 0:$.payload}getFeatureFlagResult(es,$){if($===void 0&&($={}),!$.fresh||this.rs)if(this.Kn||this.getFlags()&&this.getFlags().length>0){if(!this.us()){var ts=this.getFlagVariants(),is=es in ts,cs=ts[es],Kr=this.getFlagPayloads()[es],Xr=String(cs),Na=this.os(oi)||void 0,Ca=this.os(gi)||void 0,Aa=this.os(pi)||{};if(this.Bt.advanced_feature_flags_dedup_per_session){var Ia,Ma=this._instance.get_session_id(),Pa=this.os(fi);Ma&&Ma!==Pa&&(Aa={},(Ia=this.ni)==null||Ia.register({[pi]:Aa,[fi]:Ma}))}if(($.send_event||!("send_event"in $))&&(!(es in Aa)||!Aa[es].includes(Xr))){var La,Fa,Ba,qa,za,Va,Ga,Za,Qa,Xa;R(Aa[es])?Aa[es].push(Xr):Aa[es]=[Xr],(La=this.ni)==null||La.register({[pi]:Aa});var Ja=this.getFeatureFlagDetails(es),tl=[...(Fa=this.os(_i))!==null&&Fa!==void 0?Fa:[]];C(cs)&&tl.push("flag_missing");var sl={$feature_flag:es,$feature_flag_response:cs,$feature_flag_payload:Kr||null,$feature_flag_request_id:Na,$feature_flag_evaluated_at:Ca,$feature_flag_bootstrapped_response:((Ba=this.Bt.bootstrap)==null||(Ba=Ba.featureFlags)==null?void 0:Ba[es])||null,$feature_flag_bootstrapped_payload:((qa=this.Bt.bootstrap)==null||(qa=qa.featureFlagPayloads)==null?void 0:qa[es])||null,$used_bootstrap_value:!this.rs};C(Ja==null||(za=Ja.metadata)==null?void 0:za.version)||(sl.$feature_flag_version=Ja.metadata.version);var ol,ml=(Va=Ja==null||(Ga=Ja.reason)==null?void 0:Ga.description)!==null&&Va!==void 0?Va:Ja==null||(Za=Ja.reason)==null?void 0:Za.code;ml&&(sl.$feature_flag_reason=ml),Ja!=null&&(Qa=Ja.metadata)!=null&&Qa.id&&(sl.$feature_flag_id=Ja.metadata.id),C(Ja==null?void 0:Ja.original_variant)&&C(Ja==null?void 0:Ja.original_enabled)||(sl.$feature_flag_original_response=C(Ja.original_variant)?Ja.original_enabled:Ja.original_variant),Ja!=null&&(Xa=Ja.metadata)!=null&&Xa.original_payload&&(sl.$feature_flag_original_payload=Ja==null||(ol=Ja.metadata)==null?void 0:ol.original_payload),tl.length&&(sl.$feature_flag_error=tl.join(",")),this._instance.capture("$feature_flag_called",sl)}if(is){var rl=Kr;if(!C(Kr))try{rl=JSON.parse(Kr)}catch{}return{key:es,enabled:!!cs,variant:typeof cs=="string"?cs:void 0,payload:rl}}}}else sa.warn('getFeatureFlagResult for key "'+es+oa)}getRemoteConfigPayload(es,$){var ts=this.Bt.token,is={distinct_id:this._instance.get_distinct_id(),token:ts};this.cs()&&(is.evaluation_contexts=this.hs()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2"),data:is,compression:this.Bt.disable_compression?void 0:ps.Base64,timeout:this.Bt.feature_flag_request_timeout_ms,callback(cs){var Kr,Xr=(Kr=cs.json)==null?void 0:Kr.featureFlagPayloads;$((Xr==null?void 0:Xr[es])||void 0)}})}isFeatureEnabled(es,$){if($===void 0&&($={}),!$.fresh||this.rs){if(this.Kn||this.getFlags()&&this.getFlags().length>0){var ts=this.getFeatureFlag(es,$);return C(ts)?void 0:!!ts}sa.warn('isFeatureEnabled for key "'+es+oa)}}addFeatureFlagsHandler(es){this.featureFlagEventHandlers.push(es)}removeFeatureFlagsHandler(es){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter(($=>$!==es))}receivedFeatureFlags(es,$,ts){if(this.ni){this.Kn=!0;var is=this.getFlagVariants(),cs=this.getFlagPayloads(),Kr=this.getFlagsWithDetails();(function(Xr,Na,Ca,Aa,Ia,Ma){Ca===void 0&&(Ca={}),Aa===void 0&&(Aa={}),Ia===void 0&&(Ia={});var Pa=(tl=>{var sl=tl.flags;return sl?(tl.featureFlags=Object.fromEntries(Object.keys(sl).map((ol=>{var ml;return[ol,(ml=sl[ol].variant)!==null&&ml!==void 0?ml:sl[ol].enabled]}))),tl.featureFlagPayloads=Object.fromEntries(Object.keys(sl).filter((ol=>sl[ol].enabled)).filter((ol=>{var ml;return(ml=sl[ol].metadata)==null?void 0:ml.payload})).map((ol=>{var ml;return[ol,(ml=sl[ol].metadata)==null?void 0:ml.payload]})))):sa.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),tl})(Xr),La=Pa.flags,Fa=Pa.featureFlags,Ba=Pa.featureFlagPayloads;if(Fa){var qa=Xr.requestId,za=Xr.evaluatedAt;if(R(Fa)){sa.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var Va={};if(Fa)for(var Ga=0;Fa.length>Ga;Ga++)Va[Fa[Ga]]=!0;Na&&Na.register({[ii]:Fa,[ei]:Va})}else{var Za=Fa,Qa=Ba,Xa=La;if(Ma!=null&&Ma.partialResponse)Za=f({},Ca,Za),Qa=f({},Aa,Qa),Xa=f({},Ia,Xa);else if(Xr.errorsWhileComputingFlags)if(La){var Ja=new Set(Object.keys(La).filter((tl=>{var sl;return!((sl=La[tl])!=null&&sl.failed)})));Za=f({},Ca,Object.fromEntries(Object.entries(Za).filter((tl=>{var[sl]=tl;return Ja.has(sl)})))),Qa=f({},Aa,Object.fromEntries(Object.entries(Qa||{}).filter((tl=>{var[sl]=tl;return Ja.has(sl)})))),Xa=f({},Ia,Object.fromEntries(Object.entries(Xa||{}).filter((tl=>{var[sl]=tl;return Ja.has(sl)}))))}else Za=f({},Ca,Za),Qa=f({},Aa,Qa),Xa=f({},Ia,Xa);Na&&Na.register(f({[ii]:Object.keys(la(Za)),[ei]:Za||{},[ni]:Qa||{},[si]:Xa||{}},qa?{[oi]:qa}:{},za?{[gi]:za}:{}))}}})(es,this.ni,is,cs,Kr,ts),$||(this.ss=!1),this.ps($)}}override(es,$){$===void 0&&($=!1),sa.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:es,suppressWarning:$})}overrideFeatureFlags(es){if(!this._instance.__loaded||!this.ni)return sa.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(es===!1)return this.ni.unregister(ai),this.ni.unregister(li),this.ps(),na.info("All overrides cleared");if(R(es)){var $=aa(es);return this.ni.register({[ai]:$}),this.ps(),na.info("Flag overrides set",{flags:es})}if(es&&typeof es=="object"&&("flags"in es||"payloads"in es)){var ts,is=es;if(this.Jn=!!((ts=is.suppressWarning)!==null&&ts!==void 0&&ts),"flags"in is){if(is.flags===!1)this.ni.unregister(ai),na.info("Flag overrides cleared");else if(is.flags){if(R(is.flags)){var cs=aa(is.flags);this.ni.register({[ai]:cs})}else this.ni.register({[ai]:is.flags});na.info("Flag overrides set",{flags:is.flags})}}return"payloads"in is&&(is.payloads===!1?(this.ni.unregister(li),na.info("Payload overrides cleared")):is.payloads&&(this.ni.register({[li]:is.payloads}),na.info("Payload overrides set",{payloads:is.payloads}))),void this.ps()}if(es&&typeof es=="object")return this.ni.register({[ai]:es}),this.ps(),na.info("Flag overrides set",{flags:es});sa.warn("Invalid overrideOptions provided to overrideFeatureFlags",{overrideOptions:es})}onFeatureFlags(es){if(this.addFeatureFlagsHandler(es),this.Kn){var{flags:$,flagVariants:ts}=this.gs();es($,ts)}return()=>this.removeFeatureFlagsHandler(es)}updateEarlyAccessFeatureEnrollment(es,$,ts){var is,cs=(this.os(ri)||[]).find((Ca=>Ca.flagKey===es)),Kr={["$feature_enrollment/"+es]:$},Xr={$feature_flag:es,$feature_enrollment:$,$set:Kr};cs&&(Xr.$early_access_feature_name=cs.name),ts&&(Xr.$feature_enrollment_stage=ts),this._instance.capture("$feature_enrollment_update",Xr),this.setPersonPropertiesForFlags(Kr,!1);var Na=f({},this.getFlagVariants(),{[es]:$});(is=this.ni)==null||is.register({[ii]:Object.keys(la(Na)),[ei]:Na}),this.ps()}getEarlyAccessFeatures(es,$,ts){$===void 0&&($=!1);var is=this.os(ri),cs=ts?"&"+ts.map((Kr=>"stage="+Kr)).join("&"):"";if(is&&!$)return es(is);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this.Bt.token+cs),method:"GET",callback:Kr=>{var Xr,Na;if(Kr.json){var Ca=Kr.json.earlyAccessFeatures;return(Xr=this.ni)==null||Xr.unregister(ri),(Na=this.ni)==null||Na.register({[ri]:Ca}),es(Ca)}}})}gs(){var es=this.getFlags(),$=this.getFlagVariants();return{flags:es.filter((ts=>$[ts])),flagVariants:Object.keys($).filter((ts=>$[ts])).reduce(((ts,is)=>(ts[is]=$[is],ts)),{})}}ps(es){var{flags:$,flagVariants:ts}=this.gs();this.featureFlagEventHandlers.forEach((is=>is($,ts,{errorsLoading:es})))}setPersonPropertiesForFlags(es,$){$===void 0&&($=!0);var ts=this.os(ui)||{},is=(es==null?void 0:es.$set)||(es!=null&&es.$set_once?{}:es),cs=es==null?void 0:es.$set_once,Kr={};if(cs)for(var Xr in cs)({}).hasOwnProperty.call(cs,Xr)&&(Xr in ts||(Kr[Xr]=cs[Xr]));this._instance.register({[ui]:f({},ts,Kr,is)}),$&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(ui)}setGroupPropertiesForFlags(es,$){$===void 0&&($=!0);var ts=this.os(hi)||{};Object.keys(ts).length!==0&&Object.keys(ts).forEach((is=>{ts[is]=f({},ts[is],es[is]),delete es[is]})),this._instance.register({[hi]:f({},ts,es)}),$&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(es){if(es){var $=this.os(hi)||{};this._instance.register({[hi]:f({},$,{[es]:{}})})}else this._instance.unregister(hi)}reset(){this.Kn=!1,this.Qn=!1,this.es=!1,this.ts=!1,this.rs=!1,this.$anon_distinct_id=void 0,this.fs(),this.Jn=!1}}},_a={sessionRecording:class{get Bt(){return this._instance.config}get ni(){return this._instance.persistence}get started(){var es;return!((es=this.ys)==null||!es.isStarted)}get status(){var es,$;return this.bs===No||this.bs===jo?this.bs:(es=($=this.ys)==null?void 0:$.status)!==null&&es!==void 0?es:this.bs}constructor(es){if(this._forceAllowLocalhostNetworkCapture=!1,this.bs=Lo,this._s=void 0,this._instance=es,!this._instance.sessionManager)throw Bo.error("started without valid sessionManager"),new Error(zo+" started without valid sessionManager. This is a bug.");if(this.Bt.cookieless_mode===Ci)throw new Error(zo+' cannot be used with cookieless_mode="always"')}initialize(){this.startIfEnabledOrStop()}get ws(){var es,$=!((es=this._instance.get_property(Ye))==null||!es.enabled),ts=!this.Bt.disable_session_recording,is=this.Bt.disable_session_recording||this._instance.consent.isOptedOut();return t&&$&&ts&&!is}startIfEnabledOrStop(es){var $;if(!this.ws||($=this.ys)==null||!$.isStarted){var ts=!C(Object.assign)&&!C(Array.from);this.ws&&ts?(this.Is(es),Bo.info("starting")):(this.bs=Lo,this.stopRecording())}}Is(es){var $,ts,is;this.ws&&(this.bs!==No&&this.bs!==jo&&(this.bs=Uo),h!=null&&($=h.__PosthogExtensions__)!=null&&($=$.rrweb)!=null&&$.record&&(ts=h.__PosthogExtensions__)!=null&&ts.initSessionRecording?this.Cs(es):(is=h.__PosthogExtensions__)==null||is.loadExternalDependency==null||is.loadExternalDependency(this._instance,this.Ss,(cs=>{if(cs)return Bo.error("could not load recorder",cs);this.Cs(es)})))}stopRecording(){var es,$;(es=this._s)==null||es.call(this),this._s=void 0,($=this.ys)==null||$.stop()}xs(){var es,$;(es=this._s)==null||es.call(this),this._s=void 0,($=this.ys)==null||$.discard()}ks(){var es;(es=this.ni)==null||es.unregister(ti)}Ts(es,$){if(D(es))return null;var ts,is=L(es)?es:parseFloat(es);return typeof(ts=is)!="number"||!Number.isFinite(ts)||0>ts||ts>1?(Bo.warn($+" must be between 0 and 1. Ignoring invalid value:",es),null):is}As(es){if(this.ni){var $,ts,is=this.ni,cs=()=>{var Kr,Xr=es.sessionRecording===!1?void 0:es.sessionRecording,Na=this.Ts((Kr=this.Bt.session_recording)==null?void 0:Kr.sampleRate,"session_recording.sampleRate"),Ca=this.Ts(Xr==null?void 0:Xr.sampleRate,"remote config sampleRate"),Aa=Na??Ca;D(Aa)&&this.ks();var Ia=Xr==null?void 0:Xr.minimumDurationMilliseconds;is.register({[Ye]:f({cache_timestamp:Date.now(),enabled:!!Xr},Xr,{networkPayloadCapture:f({capturePerformance:es.capturePerformance},Xr==null?void 0:Xr.networkPayloadCapture),canvasRecording:{enabled:Xr==null?void 0:Xr.recordCanvas,fps:Xr==null?void 0:Xr.canvasFps,quality:Xr==null?void 0:Xr.canvasQuality},sampleRate:Aa,minimumDurationMilliseconds:C(Ia)?null:Ia,endpoint:Xr==null?void 0:Xr.endpoint,triggerMatchType:Xr==null?void 0:Xr.triggerMatchType,masking:Xr==null?void 0:Xr.masking,urlTriggers:Xr==null?void 0:Xr.urlTriggers,version:Xr==null?void 0:Xr.version,triggerGroups:Xr==null?void 0:Xr.triggerGroups})})};cs(),($=this._s)==null||$.call(this),this._s=(ts=this._instance.sessionManager)==null?void 0:ts.onSessionId(cs)}}onRemoteConfig(es){return"sessionRecording"in es?es.sessionRecording===!1?(this.As(es),void this.xs()):(this.As(es),void this.startIfEnabledOrStop()):(this.bs===No&&(this.bs=jo,Bo.warn("config refresh failed, recording will not start until page reload")),void this.startIfEnabledOrStop())}log(es,$){var ts;$===void 0&&($="log"),(ts=this.ys)!=null&&ts.log?this.ys.log(es,$):Bo.warn("log called before recorder was ready")}get Ss(){var es,$,ts=(es=this._instance)==null||(es=es.persistence)==null?void 0:es.get_property(Ye);return(ts==null||($=ts.scriptConfig)==null?void 0:$.script)||"lazy-recorder"}Es(){var es,$=this._instance.get_property(Ye);if(!$)return!1;var ts=(es=(typeof $=="object"?$:JSON.parse($)).cache_timestamp)!==null&&es!==void 0?es:Date.now();return 36e5>=Date.now()-ts}Cs(es){var $,ts;if(($=h.__PosthogExtensions__)==null||!$.initSessionRecording)return Bo.warn("Called on script loaded before session recording is available. This can be caused by adblockers."),void this._instance.register_for_session({[Pi]:!0});if(this.ys||(this.ys=(ts=h.__PosthogExtensions__)==null?void 0:ts.initSessionRecording(this._instance),this.ys._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),!this.Es())return this.bs===jo||this.bs===No?void 0:(this.bs=No,Bo.info("persisted remote config is stale, requesting fresh config before starting"),void new vs(this._instance).load());this.bs=Uo,this.ys.start(es)}onRRwebEmit(es){var $;($=this.ys)==null||$.onRRwebEmit==null||$.onRRwebEmit(es)}overrideLinkedFlag(){var es,$;this.ys||($=this.ni)==null||$.register({[Ke]:!0}),(es=this.ys)==null||es.overrideLinkedFlag()}overrideSampling(){var es,$;this.ys||($=this.ni)==null||$.register({[Je]:!0}),(es=this.ys)==null||es.overrideSampling()}overrideTrigger(es){var $,ts;this.ys||(ts=this.ni)==null||ts.register({[es==="url"?Xe:Qe]:!0}),($=this.ys)==null||$.overrideTrigger(es)}get sdkDebugProperties(){var es;return((es=this.ys)==null?void 0:es.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(es,$){var ts;return!((ts=this.ys)==null||!ts.tryAddCustomEvent(es,$))}}},ga={autocapture:class{constructor(es){this.Rs=!1,this.Ns=null,this.Ms=!1,this.instance=es,this.rageclicks=new To(es.config.rageclick),this.Fs=null}initialize(){this.startIfEnabled()}get Bt(){var es,$,ts=O(this.instance.config.autocapture)?this.instance.config.autocapture:{};return ts.url_allowlist=(es=ts.url_allowlist)==null?void 0:es.map((is=>new RegExp(is))),ts.url_ignorelist=($=ts.url_ignorelist)==null?void 0:$.map((is=>new RegExp(is))),ts}Os(){if(this.isBrowserSupported()){if(t&&r){var es=ts=>{ts=ts||(t==null?void 0:t.event);try{this.Ps(ts)}catch(is){Ro.error("Failed to capture event",is)}};if(Xi(r,"submit",es,{capture:!0}),Xi(r,"change",es,{capture:!0}),Xi(r,"click",es,{capture:!0}),this.Bt.capture_copied_text){var $=ts=>{ts=ts||(t==null?void 0:t.event);try{this.Ps(ts,ko)}catch(is){Ro.error("Failed to capture copy/cut event",is)}};Xi(r,"copy",$,{capture:!0}),Xi(r,"cut",$,{capture:!0})}}}else Ro.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.Rs&&(this.Os(),this.Rs=!0)}onRemoteConfig(es){es.elementsChainAsString&&(this.Ms=es.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Ne]:!!es.autocapture_opt_out}),this.Ns=!!es.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(es){this.Fs=es}getElementSelectors(es){var $,ts=[];return($=this.Fs)==null||$.forEach((is=>{var cs=r==null?void 0:r.querySelectorAll(is);cs==null||cs.forEach((Kr=>{es===Kr&&ts.push(is)}))})),ts}get isEnabled(){var es,$,ts=(es=this.instance.persistence)==null?void 0:es.props[Ne];if(M(this.Ns)&&!N(ts)&&!this.instance.Fr())return!1;var is=($=this.Ns)!==null&&$!==void 0?$:!!ts;return!!this.instance.config.autocapture&&!is}Ps(es,$){if($===void 0&&($="$autocapture"),this.isEnabled){var ts,is=so(es);Xn(is)&&(is=is.parentNode||null),$==="$autocapture"&&es.type==="click"&&es instanceof MouseEvent&&this.instance.config.rageclick&&(ts=this.rageclicks)!=null&&ts.isRageClick(es.clientX,es.clientY,es.timeStamp||new Date().getTime())&&(function(Ma,Pa){if(!t||ho(Ma))return!1;var La,Fa,Ba;if(N(Pa)?(La=!!Pa&&uo,Fa=void 0):(La=(Ba=Pa==null?void 0:Pa.css_selector_ignorelist)!==null&&Ba!==void 0?Ba:uo,Fa=Pa==null?void 0:Pa.content_ignorelist),La===!1)return!1;var{targetElementList:qa}=vo(Ma,!1);return!(function(za,Va){if(za===!1||C(za))return!1;var Ga;if(za===!0)Ga=lo;else{if(!R(za))return!1;if(za.length>10)return Ie.error("[PostHog] content_ignorelist array cannot exceed 10 items. Use css_selector_ignorelist for more complex matching."),!1;Ga=za.map((Za=>Za.toLowerCase()))}return Va.some((Za=>{var{safeText:Qa,ariaLabel:Xa}=Za;return Ga.some((Ja=>Qa.includes(Ja)||Xa.includes(Ja)))}))})(Fa,qa.map((za=>{var Va;return{safeText:ro(za).toLowerCase(),ariaLabel:((Va=za.getAttribute("aria-label"))==null?void 0:Va.toLowerCase().trim())||""}})))&&!oo(qa,La)})(is,this.instance.config.rageclick)&&this.Ps(es,"$rageclick");var cs=$===ko;if(is&&(function(Ma,Pa,La,Fa,Ba){var qa,za,Va,Ga;if(La===void 0&&(La=void 0),!t||ho(Ma)||(qa=La)!=null&&qa.url_allowlist&&!to(La.url_allowlist)||(za=La)!=null&&za.url_ignorelist&&to(La.url_ignorelist))return!1;if((Va=La)!=null&&Va.dom_event_allowlist){var Za=La.dom_event_allowlist;if(Za&&!Za.some((sl=>Pa.type===sl)))return!1}var{parentIsUsefulElement:Qa,targetElementList:Xa}=vo(Ma,Fa);if(!(function(sl,ol){var ml=ol==null?void 0:ol.element_allowlist;if(C(ml))return!0;var rl,ll=function(_l){if(ml.some((il=>_l.tagName.toLowerCase()===il)))return{v:!0}};for(var dl of sl)if(rl=ll(dl))return rl.v;return!1})(Xa,La)||!oo(Xa,(Ga=La)==null?void 0:Ga.css_selector_allowlist))return!1;var Ja=t.getComputedStyle(Ma);if(Ja&&Ja.getPropertyValue("cursor")==="pointer"&&Pa.type==="click")return!0;var tl=Ma.tagName.toLowerCase();switch(tl){case"html":return!1;case"form":return(Ba||["submit"]).indexOf(Pa.type)>=0;case"input":case"select":case"textarea":return(Ba||["change","click"]).indexOf(Pa.type)>=0;default:return Qa?(Ba||["click"]).indexOf(Pa.type)>=0:(Ba||["click"]).indexOf(Pa.type)>=0&&(no.indexOf(tl)>-1||Ma.getAttribute("contenteditable")==="true")}})(is,es,this.Bt,cs,cs?["copy","cut"]:void 0)){var{props:Kr,explicitNoCapture:Xr}=Io(is,{e:es,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.Bt.element_attribute_ignorelist,elementsChainAsString:this.Ms});if(Xr)return!1;var Na=this.getElementSelectors(is);if(Na&&Na.length>0&&(Kr.$element_selectors=Na),$===ko){var Ca,Aa=io(t==null||(Ca=t.getSelection())==null?void 0:Ca.toString()),Ia=es.type||"clipboard";if(!Aa)return!1;Kr.$selected_content=Aa,Kr.$copy_type=Ia}return this.instance.capture($,Kr),!0}}}isBrowserSupported(){return P(r==null?void 0:r.querySelectorAll)}},historyAutocapture:class{constructor(es){var $;this._instance=es,this.Ls=(t==null||($=t.location)==null?void 0:$.pathname)||""}initialize(){this.startIfEnabled()}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Ie.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.Ds&&this.Ds(),this.Ds=void 0,Ie.info("History API monitoring stopped")}monitorHistoryChanges(){var es,$;if(t&&t.history){var ts=this;(es=t.history.pushState)!=null&&es.__posthog_wrapped__||Fo(t.history,"pushState",(is=>function(cs,Kr,Xr){is.call(this,cs,Kr,Xr),ts.Bs("pushState")})),($=t.history.replaceState)!=null&&$.__posthog_wrapped__||Fo(t.history,"replaceState",(is=>function(cs,Kr,Xr){is.call(this,cs,Kr,Xr),ts.Bs("replaceState")})),this.js()}}Bs(es){try{var $,ts=t==null||($=t.location)==null?void 0:$.pathname;if(!ts)return;ts!==this.Ls&&this.isEnabled&&this._instance.capture(Ui,{navigation_type:es}),this.Ls=ts}catch(is){Ie.error("Error capturing "+es+" pageview",is)}}js(){if(!this.Ds){var es=()=>{this.Bs("popstate")};Xi(t,"popstate",es),this.Ds=()=>{t&&t.removeEventListener("popstate",es)}}}},heatmaps:class{get Bt(){return this.instance.config}constructor(es){var $;this.$s=!1,this.Rs=!1,this.qs=null,this.instance=es,this.$s=!(($=this.instance.persistence)==null||!$.props[je]),this.rageclicks=new To(es.config.rageclick)}initialize(){this.startIfEnabled()}get flushIntervalMilliseconds(){var es=5e3;return O(this.Bt.capture_heatmaps)&&this.Bt.capture_heatmaps.flush_interval_milliseconds&&(es=this.Bt.capture_heatmaps.flush_interval_milliseconds),es}get isEnabled(){return D(this.Bt.capture_heatmaps)?D(this.Bt.enable_heatmaps)?this.$s:this.Bt.enable_heatmaps:this.Bt.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.Rs)return;Ho.info("starting..."),this.Zs(),this.Ft()}else{var es;clearInterval((es=this.qs)!==null&&es!==void 0?es:void 0),this.Vs(),this.getAndClearBuffer()}}onRemoteConfig(es){if("heatmaps"in es){var $=!!es.heatmaps;this.instance.persistence&&this.instance.persistence.register({[je]:$}),this.$s=$,this.startIfEnabled()}}getAndClearBuffer(){var es=this.T;return this.T=void 0,es}Hs(es){this.Tt(es.originalEvent,"deadclick")}Ft(){this.qs&&clearInterval(this.qs),this.qs=(r==null?void 0:r.visibilityState)==="visible"?setInterval(this.Yr.bind(this),this.flushIntervalMilliseconds):null}Zs(){t&&r&&(this.zs=this.Yr.bind(this),Xi(t,Li,this.zs),this.Us=es=>this.Tt(es||(t==null?void 0:t.event)),Xi(r,"click",this.Us,{capture:!0}),this.Ys=es=>this.Gs(es||(t==null?void 0:t.event)),Xi(r,"mousemove",this.Ys,{capture:!0}),this.Ws=new yr(this.instance,mr,this.Hs.bind(this)),this.Ws.startIfEnabledOrStop(),this.Xs=this.Ft.bind(this),Xi(r,Di,this.Xs),this.Rs=!0)}Vs(){var es;t&&r&&(this.zs&&t.removeEventListener(Li,this.zs),this.Us&&r.removeEventListener("click",this.Us,{capture:!0}),this.Ys&&r.removeEventListener("mousemove",this.Ys,{capture:!0}),this.Xs&&r.removeEventListener(Di,this.Xs),clearTimeout(this.Js),(es=this.Ws)==null||es.stop(),this.Rs=!1)}Ks(es,$){var ts=this.instance.scrollManager.scrollY(),is=this.instance.scrollManager.scrollX(),cs=this.instance.scrollManager.scrollElement(),Kr=(function(Xr,Na,Ca){for(var Aa=Xr;Aa&&Jn(Aa)&&!Kn(Aa,"body");){if(Aa===Ca)return!1;if(w(Na,t==null?void 0:t.getComputedStyle(Aa).position))return!0;Aa=ao(Aa)}return!1})(so(es),["fixed","sticky"],cs);return{x:es.clientX+(Kr?0:is),y:es.clientY+(Kr?0:ts),target_fixed:Kr,type:$}}Tt(es,$){var ts;if($===void 0&&($="click"),!Yn(es.target)&&qo(es)){var is=this.Ks(es,$);(ts=this.rageclicks)!=null&&ts.isRageClick(es.clientX,es.clientY,new Date().getTime())&&this.Qs(f({},is,{type:"rageclick"})),this.Qs(is)}}Gs(es){!Yn(es.target)&&qo(es)&&(clearTimeout(this.Js),this.Js=setTimeout((()=>{this.Qs(this.Ks(es,"mousemove"))}),500))}Qs(es){if(t){var $=t.location.href,ts=this.Bt.custom_personal_data_properties,is=this.Bt.mask_personal_data_properties?[...Fr,...ts||[]]:[],cs=Or($,is,Mr);this.T=this.T||{},this.T[cs]||(this.T[cs]=[]),this.T[cs].push(es)}}Yr(){this.T&&!I(this.T)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}},deadClicksAutocapture:yr,webVitalsAutocapture:class{constructor(es){var $;this.$s=!1,this.Rs=!1,this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.eo=()=>{clearTimeout(this.ro),this.T.metrics.length!==0&&(this._instance.capture("$web_vitals",this.T.metrics.reduce(((ts,is)=>f({},ts,{["$web_vitals_"+is.name+"_event"]:f({},is),["$web_vitals_"+is.name+"_value"]:is.value})),{})),this.T={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.ht=ts=>{var is,cs=(is=this._instance.sessionManager)==null?void 0:is.checkAndGetSessionAndWindowId(!0);if(C(cs))Mo.error("Could not read session ID. Dropping metrics!");else{this.T=this.T||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var Kr=this.io();C(Kr)||(D(ts==null?void 0:ts.name)||D(ts==null?void 0:ts.value)?Mo.error("Invalid metric received",ts):!this.no||this.no>ts.value?(this.T.url!==Kr&&(this.eo(),this.ro=setTimeout(this.eo,this.flushToCaptureTimeoutMs)),C(this.T.url)&&(this.T.url=Kr),this.T.firstMetricTimestamp=C(this.T.firstMetricTimestamp)?Date.now():this.T.firstMetricTimestamp,ts.attribution&&ts.attribution.interactionTargetElement&&(ts.attribution.interactionTargetElement=void 0),this.T.metrics.push(f({},ts,{$current_url:Kr,$session_id:cs.sessionId,$window_id:cs.windowId,timestamp:Date.now()})),this.T.metrics.length===this.allowedMetrics.length&&this.eo()):Mo.error("Ignoring metric with value >= "+this.no,ts))}},this.so=()=>{if(!this.Rs){var ts,is,cs,Kr,Xr=h.__PosthogExtensions__;C(Xr)||C(Xr.postHogWebVitalsCallbacks)||({onLCP:ts,onCLS:is,onFCP:cs,onINP:Kr}=Xr.postHogWebVitalsCallbacks),ts&&is&&cs&&Kr?(this.allowedMetrics.indexOf("LCP")>-1&&ts(this.ht.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&is(this.ht.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&cs(this.ht.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&Kr(this.ht.bind(this)),this.Rs=!0):Mo.error("web vitals callbacks not loaded - not starting")}},this._instance=es,this.$s=!(($=this._instance.persistence)==null||!$.props[qe]),this.startIfEnabled()}get oo(){return this._instance.config.capture_performance}get allowedMetrics(){var es,$,ts=O(this.oo)?(es=this.oo)==null?void 0:es.web_vitals_allowed_metrics:void 0;return D(ts)?(($=this._instance.persistence)==null?void 0:$.props[Ge])||["CLS","FCP","INP","LCP"]:ts}get flushToCaptureTimeoutMs(){return(O(this.oo)?this.oo.web_vitals_delayed_flush_ms:void 0)||5e3}get useAttribution(){var es=O(this.oo)?this.oo.web_vitals_attribution:void 0;return es!=null&&es}get no(){var es=O(this.oo)&&L(this.oo.__web_vitals_max_value)?this.oo.__web_vitals_max_value:Do;return es>0&&6e4>=es?Do:es}get isEnabled(){var es=s==null?void 0:s.protocol;if(es!=="http:"&&es!=="https:")return Mo.info("Web Vitals are disabled on non-http/https protocols"),!1;var $=O(this.oo)?this.oo.web_vitals:N(this.oo)?this.oo:void 0;return N($)?$:this.$s}startIfEnabled(){this.isEnabled&&!this.Rs&&(Mo.info("enabled, starting..."),this.ur(this.so))}onRemoteConfig(es){if("capturePerformance"in es){var $=O(es.capturePerformance)&&!!es.capturePerformance.web_vitals,ts=O(es.capturePerformance)?es.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[qe]:$}),this._instance.persistence.register({[Ge]:ts})),this.$s=$,this.startIfEnabled()}}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.postHogWebVitalsCallbacks?es():(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,this.useAttribution?"web-vitals-with-attribution":"web-vitals",(is=>{is?Mo.error("failed to load script",is):es()}))}io(){var es=t?t.location.href:void 0;if(es){var $=this._instance.config.custom_personal_data_properties,ts=this._instance.config.mask_personal_data_properties?[...Fr,...$||[]]:[];return Or(es,ts,Mr)}Mo.error("Could not determine current URL")}}},ma={exceptionObserver:class{constructor(es){var $,ts,is;this.so=()=>{var cs;if(t&&this.isEnabled&&(cs=h.__PosthogExtensions__)!=null&&cs.errorWrappingFunctions){var Kr=h.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,Xr=h.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,Na=h.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.ao&&this.Bt.capture_unhandled_errors&&(this.ao=Kr(this.captureException.bind(this))),!this.lo&&this.Bt.capture_unhandled_rejections&&(this.lo=Xr(this.captureException.bind(this))),!this.uo&&this.Bt.capture_console_errors&&(this.uo=Na(this.captureException.bind(this)))}catch(Ca){Co.error("failed to start",Ca),this.ho()}}},this._instance=es,this.co=!(($=this._instance.persistence)==null||!$.props[ze]),this.do=new J({refillRate:(ts=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&ts!==void 0?ts:1,bucketSize:(is=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&is!==void 0?is:10,refillInterval:1e4,Gt:Co}),this.Bt=this.vo(),this.startIfEnabledOrStop()}vo(){var es=this._instance.config.capture_exceptions,$={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return O(es)?$=f({},$,es):(C(es)?this.co:es)&&($=f({},$,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),$}get isEnabled(){return this.Bt.capture_console_errors||this.Bt.capture_unhandled_errors||this.Bt.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(Co.info("enabled"),this.ho(),this.ur(this.so)):this.ho()}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.errorWrappingFunctions&&es(),(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"exception-autocapture",(is=>{if(is)return Co.error("failed to load script",is);es()}))}ho(){var es,$,ts;(es=this.ao)==null||es.call(this),this.ao=void 0,($=this.lo)==null||$.call(this),this.lo=void 0,(ts=this.uo)==null||ts.call(this),this.uo=void 0}onRemoteConfig(es){"autocaptureExceptions"in es&&(this.co=!!es.autocaptureExceptions||!1,this._instance.persistence&&this._instance.persistence.register({[ze]:this.co}),this.Bt=this.vo(),this.startIfEnabledOrStop())}onConfigChange(){this.Bt=this.vo()}captureException(es){var $,ts,is,cs=($=es==null||(ts=es.$exception_list)==null||(ts=ts[0])==null?void 0:ts.type)!==null&&$!==void 0?$:"Exception";this.do.consumeRateLimit(cs)?Co.info("Skipping exception capture because of client rate limiting.",{exception:cs}):(is=this._instance.exceptions)==null||is.sendExceptionEvent(es)}},exceptions:class{constructor(es){var $,ts;this.fo=[],this.po=new te([new ve,new xe,new pe,new ce,new ye,new be,new _e,new we],(function(is){for(var cs=arguments.length,Kr=new Array(cs>1?cs-1:0),Xr=1;cs>Xr;Xr++)Kr[Xr-1]=arguments[Xr];return function(Na,Ca){Ca===void 0&&(Ca=0);for(var Aa=[],Ia=Na.split(`
712
- `),Ma=Ca;Ia.length>Ma;Ma++){var Pa=Ia[Ma];if(1024>=Pa.length){var La=de.test(Pa)?Pa.replace(de,"$1"):Pa;if(!La.match(/\S*Error: /)){for(var Fa of Kr){var Ba=Fa(La,is);if(Ba){Aa.push(Ba);break}}if(Aa.length>=50)break}}}return(function(qa){if(!qa.length)return[];var za=Array.from(qa);return za.reverse(),za.slice(0,50).map((Va=>{return f({},Va,{filename:Va.filename||(Ga=za,Ga[Ga.length-1]||{}).filename,function:Va.function||ee});var Ga}))})(Aa)}})("web:javascript",ae,he)),this._instance=es,this.fo=($=(ts=this._instance.persistence)==null?void 0:ts.get_property(Be))!==null&&$!==void 0?$:[],this.mo=ke(this.yo()),this.bo=new Re(this.mo)}onConfigChange(){this.mo=ke(this.yo()),this.bo.setConfig(this.mo)}onRemoteConfig(es){var $,ts,is;if("errorTracking"in es){var cs=($=(ts=es.errorTracking)==null?void 0:ts.suppressionRules)!==null&&$!==void 0?$:[],Kr=(is=es.errorTracking)==null?void 0:is.captureExtensionExceptions;this.fo=cs,this._instance.persistence&&this._instance.persistence.register({[Be]:this.fo,[He]:Kr})}}get _o(){var es,$=!!this._instance.get_property(He),ts=this._instance.config.error_tracking.captureExtensionExceptions;return(es=ts??$)!==null&&es!==void 0&&es}buildProperties(es,$){return this.po.buildFromUnknown(es,{syntheticException:$==null?void 0:$.syntheticException,mechanism:{handled:$==null?void 0:$.handled}})}addExceptionStep(es,$){if(this.mo.enabled)try{if(!F(es)||es.trim().length===0)return void ua.warn("Ignoring exception step because message must be a non-empty string");var ts=this.wo($),{sanitizedProperties:is,droppedKeys:cs}=(function(Kr){if(!Kr)return{sanitizedProperties:{},droppedKeys:[]};var Xr=[];return{sanitizedProperties:Object.keys(Kr).reduce(((Na,Ca)=>$e.has(Ca)?(Xr.push(Ca),Na):(Na[Ca]=Kr[Ca],Na)),{}),droppedKeys:Xr}})(ts);cs.length>0&&ua.warn("Ignoring reserved exception step fields",{droppedKeys:cs}),this.bo.add(f({[Ee]:es,[Se]:new Date().toISOString()},is))}catch(Kr){ua.error("Failed to add exception step. Ignoring breadcrumb.",Kr)}}sendExceptionEvent(es){try{var $=es.$exception_list;if(this.Io($)){if(this.Co($))return this.So("Exception dropped: matched a suppression rule"),void ua.info("Skipping exception capture because a suppression rule matched");if(!this._o&&this.xo($))return this.So("Exception dropped: thrown by a browser extension"),void ua.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ko($))return this.So("Exception dropped: thrown by the PostHog SDK"),void ua.info("Skipping exception capture because it was thrown by the PostHog SDK")}var ts=this.mo.enabled&&D(es.$exception_steps)?this.To(es):es;try{var is=this._instance.capture("$exception",ts,{_noTruncate:!0,_batchKey:"exceptionEvent",en:!0});return is&&this.bo.clear(),is}catch(cs){return ua.error("Failed to capture exception event. Dropping this exception.",cs),void this.bo.clear()}}catch(cs){return void ua.error("Failed to process exception event. Ignoring this exception.",cs)}}To(es){try{var $=this.bo.getAttachable();return $.length===0?es:f({},es,{$exception_steps:$})}catch(ts){return ua.error("Failed to read buffered exception steps. Capturing exception without steps.",ts),es}}So(es){this.mo.enabled&&this.bo.add({[Ee]:es,[Se]:new Date().toISOString()})}wo(es){return O(es)?f({},es):{}}yo(){var es,$;return(es=($=this._instance.config.error_tracking)==null?void 0:$.exception_steps)!==null&&es!==void 0?es:{}}Co(es){if(es.length===0)return!1;var $=es.reduce(((ts,is)=>{var{type:cs,value:Kr}=is;return F(cs)&&cs.length>0&&ts.$exception_types.push(cs),F(Kr)&&Kr.length>0&&ts.$exception_values.push(Kr),ts}),{$exception_types:[],$exception_values:[]});return this.fo.some((ts=>{var is=ts.values.map((cs=>{var Kr,Xr=_n[cs.operator],Na=R(cs.value)?cs.value:[cs.value],Ca=(Kr=$[cs.key])!==null&&Kr!==void 0?Kr:[];return Na.length>0&&Xr(Na,Ca)}));return ts.type==="OR"?is.some(Boolean):is.every(Boolean)}))}xo(es){return es.flatMap(($=>{var ts,is;return(ts=(is=$.stacktrace)==null?void 0:is.frames)!==null&&ts!==void 0?ts:[]})).some(($=>$.filename&&$.filename.startsWith("chrome-extension://")))}ko(es){if(es.length>0){var $,ts,is,cs,Kr=($=(ts=es[0].stacktrace)==null?void 0:ts.frames)!==null&&$!==void 0?$:[],Xr=Kr[Kr.length-1];return(is=Xr==null||(cs=Xr.filename)==null?void 0:cs.includes("posthog.com/static"))!==null&&is!==void 0&&is}return!1}Io(es){return!D(es)&&R(es)}}},ba=f({productTours:class{get ni(){return this._instance.persistence}constructor(es){this.Ao=null,this.Eo=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){"productTours"in es&&(this.ni&&this.ni.register({[We]:!!es.productTours}),this.loadIfEnabled())}loadIfEnabled(){var es,$;this.Ao||(es=this._instance).config.disable_product_tours||($=es.persistence)==null||!$.get_property(We)||this.ur((()=>this.Ro()))}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.generateProductTours?es():(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"product-tours",(is=>{is?Vo.error("Could not load product tours script",is):es()}))}Ro(){var es;!this.Ao&&(es=h.__PosthogExtensions__)!=null&&es.generateProductTours&&(this.Ao=h.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(es,$){if($===void 0&&($=!1),!R(this.Eo)||$){var ts=this.ni;if(ts){var is=ts.props[ci];if(R(is)&&!$)return this.Eo=is,void es(is,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:cs=>{var Kr=cs.statusCode;if(Kr!==200||!cs.json){var Xr="Product Tours API could not be loaded, status: "+Kr;return Vo.error(Xr),void es([],{isLoaded:!1,error:Xr})}var Na=R(cs.json.product_tours)?cs.json.product_tours:[];this.Eo=Na,ts&&ts.register({[ci]:Na}),es(Na,{isLoaded:!0})}})}else es(this.Eo,{isLoaded:!0})}getActiveProductTours(es){D(this.Ao)?es([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ao.getActiveProductTours(es)}showProductTour(es){var $;($=this.Ao)==null||$.showTourById(es)}previewTour(es){this.Ao?this.Ao.previewTour(es):this.ur((()=>{var $;this.Ro(),($=this.Ao)==null||$.previewTour(es)}))}dismissProductTour(){var es;(es=this.Ao)==null||es.dismissTour("user_clicked_skip")}nextStep(){var es;(es=this.Ao)==null||es.nextStep()}previousStep(){var es;(es=this.Ao)==null||es.previousStep()}clearCache(){var es;this.Eo=null,(es=this.ni)==null||es.unregister(ci)}resetTour(es){var $;($=this.Ao)==null||$.resetTour(es)}resetAllTours(){var es;(es=this.Ao)==null||es.resetAllTours()}cancelPendingTour(es){var $;($=this.Ao)==null||$.cancelPendingTour(es)}}},fa),ya={siteApps:class{constructor(es){this._instance=es,this.No=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Mo(es,$){if($){var ts=this.globalsForEvent($);this.No.push(ts),this.No.length>1e3&&(this.No=this.No.slice(10))}}get siteAppLoaders(){var es;return(es=h._POSTHOG_REMOTE_CONFIG)==null||(es=es[this._instance.config.token])==null?void 0:es.siteApps}initialize(){if(this.isEnabled){var es=this._instance._addCaptureHook(this.Mo.bind(this));this.Fo=()=>{es(),this.No=[],this.Fo=void 0}}}globalsForEvent(es){var $,ts,is,cs,Kr,Xr,Na;if(!es)throw new Error("Event payload is required");var Ca={},Aa=this._instance.get_property("$groups")||[],Ia=this._instance.get_property("$stored_group_properties")||{};for(var[Ma,Pa]of Object.entries(Ia))Ca[Ma]={id:Aa[Ma],type:Ma,properties:Pa};var{$set_once:La,$set:Fa}=es;return{event:f({},_(es,Wo),{properties:f({},es.properties,Fa?{$set:f({},($=(ts=es.properties)==null?void 0:ts.$set)!==null&&$!==void 0?$:{},Fa)}:{},La?{$set_once:f({},(is=(cs=es.properties)==null?void 0:cs.$set_once)!==null&&is!==void 0?is:{},La)}:{}),elements_chain:(Kr=(Xr=es.properties)==null?void 0:Xr.$elements_chain)!==null&&Kr!==void 0?Kr:"",distinct_id:(Na=es.properties)==null?void 0:Na.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:Ca}}setupSiteApp(es){var $=this.apps[es.id],ts=()=>{var Xr;!$.errored&&this.No.length&&(Go.info("Processing "+this.No.length+" events for site app with id "+es.id),this.No.forEach((Na=>$.processEvent==null?void 0:$.processEvent(Na))),$.processedBuffer=!0),Object.values(this.apps).every((Na=>Na.processedBuffer||Na.errored))&&((Xr=this.Fo)==null||Xr.call(this))},is=!1,cs=Xr=>{$.errored=!Xr,$.loaded=!0,Go.info("Site app with id "+es.id+" "+(Xr?"loaded":"errored")),is&&ts()};try{var{processEvent:Kr}=es.init({posthog:this._instance,callback(Xr){cs(Xr)}});Kr&&($.processEvent=Kr),is=!0}catch(Xr){Go.error(Yo+es.id,Xr),cs(!1)}if(is&&$.loaded)try{ts()}catch(Xr){Go.error("Error while processing buffered events PostHog app with config id "+es.id,Xr),$.errored=!0}}Oo(){var es=this.siteAppLoaders||[];for(var $ of es)this.apps[$.id]={id:$.id,loaded:!1,errored:!1,processedBuffer:!1};for(var ts of es)this.setupSiteApp(ts)}Po(es){if(Object.keys(this.apps).length!==0){var $=this.globalsForEvent(es);for(var ts of Object.values(this.apps))try{ts.processEvent==null||ts.processEvent($)}catch(is){Go.error("Error while processing event "+es.event+" for site app "+ts.id,is)}}}onRemoteConfig(es){var $,ts,is,cs=this;if(($=this.siteAppLoaders)!=null&&$.length)return this.isEnabled?(this.Oo(),void this._instance.on("eventCaptured",(Ca=>this.Po(Ca)))):void Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((ts=this.Fo)==null||ts.call(this),(is=es.siteApps)!=null&&is.length)if(this.isEnabled){var Kr=function(Ca){var Aa;h["__$$ph_site_app_"+Ca]=cs._instance,(Aa=h.__PosthogExtensions__)==null||Aa.loadSiteApp==null||Aa.loadSiteApp(cs._instance,Na,(Ia=>{if(Ia)return Go.error(Yo+Ca,Ia)}))};for(var{id:Xr,url:Na}of es.siteApps)Kr(Xr)}else Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},wa={tracingHeaders:class{constructor(es){this.Lo=void 0,this.Do=void 0,this.so=()=>{var $,ts,is=this.Bo()||[];C(this.Lo)&&(($=h.__PosthogExtensions__)==null||($=$.tracingHeadersPatchFns)==null||$._patchXHR(is,this._instance.get_distinct_id(),this._instance.sessionManager)),C(this.Do)&&((ts=h.__PosthogExtensions__)==null||(ts=ts.tracingHeadersPatchFns)==null||ts._patchFetch(is,this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=es}initialize(){this.startIfEnabledOrStop()}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.tracingHeadersPatchFns&&es(),(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"tracing-headers",(is=>{if(is)return Ao.error("failed to load script",is);es()}))}Bo(){var es;return(es=this._instance.config.addTracingHeaders)!==null&&es!==void 0?es:this._instance.config.__add_tracing_headers}startIfEnabledOrStop(){var es,$;this.Bo()?this.ur(this.so):((es=this.Lo)==null||es.call(this),($=this.Do)==null||$.call(this),this.Lo=void 0,this.Do=void 0)}}},xa=f({surveys:class{get Bt(){return this._instance.config}constructor(es){this.jo=void 0,this._surveyManager=null,this.$o=!1,this.qo=[],this.Zo=null,this._instance=es,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this.Bt.disable_surveys){var $=es.surveys;if(D($))return En.warn("Flags not loaded yet. Not loading surveys.");var ts=R($);this.jo=ts?$.length>0:$,En.info("flags response received, isSurveysEnabled: "+this.jo),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var es=[],$=0;$<localStorage.length;$++){var ts=localStorage.key($);(ts!=null&&ts.startsWith(Sn)||ts!=null&&ts.startsWith("inProgressSurvey_"))&&es.push(ts)}es.forEach((is=>localStorage.removeItem(is)))}loadIfEnabled(){if(!this._surveyManager)if(this.$o)En.info("Already initializing surveys, skipping...");else if(this.Bt.disable_surveys)En.info(ta);else if(this.Bt.cookieless_mode&&this._instance.consent.isOptedOut())En.info("Not loading surveys in cookieless mode without consent.");else{var es=h==null?void 0:h.__PosthogExtensions__;if(es){if(!C(this.jo)||this.Bt.advanced_enable_surveys){var $=this.jo||this.Bt.advanced_enable_surveys;this.$o=!0;try{var ts=es.generateSurveys;if(ts)return void this.Vo(ts,$);var is=es.loadExternalDependency;if(!is)return void this.Ho(Oi);is(this._instance,"surveys",(cs=>{cs||!es.generateSurveys?this.Ho("Could not load surveys script",cs):this.Vo(es.generateSurveys,$)}))}catch(cs){throw this.Ho("Error initializing surveys",cs),cs}finally{this.$o=!1}}}else En.error("PostHog Extensions not found.")}}Vo(es,$){this._surveyManager=es(this._instance,$),this._surveyEventReceiver=new Qo(this._instance),En.info("Surveys loaded successfully"),this.zo({isLoaded:!0})}Ho(es,$){En.error(es,$),this.zo({isLoaded:!1,error:es})}onSurveysLoaded(es){return this.qo.push(es),this._surveyManager&&this.zo({isLoaded:!0}),()=>{this.qo=this.qo.filter(($=>$!==es))}}getSurveys(es,$){if($===void 0&&($=!1),this.Bt.disable_surveys)return En.info(ta),es([]);var ts,is=this._instance.get_property(di);if(is&&!$)return es(is,{isLoaded:!0});typeof Promise<"u"&&this.Zo?this.Zo.then((cs=>{var{surveys:Kr,context:Xr}=cs;return es(Kr,Xr)})):(typeof Promise<"u"&&(this.Zo=new Promise((cs=>{ts=cs}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Bt.token),method:"GET",timeout:this.Bt.surveys_request_timeout_ms,callback:cs=>{var Kr;this.Zo=null;var Xr=cs.statusCode;if(Xr!==200||!cs.json){var Na="Surveys API could not be loaded, status: "+Xr;En.error(Na);var Ca={isLoaded:!1,error:Na};return es([],Ca),void(ts==null||ts({surveys:[],context:Ca}))}var Aa,Ia=cs.json.surveys||[],Ma=Ia.filter((La=>(function(Fa){return!(!Fa.start_date||Fa.end_date)})(La)&&((function(Fa){var Ba;return!((Ba=Fa.conditions)==null||(Ba=Ba.events)==null||(Ba=Ba.values)==null||!Ba.length)})(La)||(function(Fa){var Ba;return!((Ba=Fa.conditions)==null||(Ba=Ba.actions)==null||(Ba=Ba.values)==null||!Ba.length)})(La))));Ma.length>0&&((Aa=this._surveyEventReceiver)==null||Aa.register(Ma)),(Kr=this._instance.persistence)==null||Kr.register({[di]:Ia});var Pa={isLoaded:!0};es(Ia,Pa),ts==null||ts({surveys:Ia,context:Pa})}}))}zo(es){for(var $ of this.qo)try{if(!es.isLoaded)return $([],es);this.getSurveys($)}catch(ts){En.error("Error in survey callback",ts)}}getActiveMatchingSurveys(es,$){if($===void 0&&($=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(es,$);En.warn("init was not called")}Uo(es){var $=null;return this.getSurveys((ts=>{var is;$=(is=ts.find((cs=>cs.id===es)))!==null&&is!==void 0?is:null})),$}Yo(es){if(D(this._surveyManager))return{eligible:!1,reason:Zo};var $=typeof es=="string"?this.Uo(es):es;return $?this._surveyManager.checkSurveyEligibility($):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(es){if(D(this._surveyManager))return En.warn("init was not called"),{visible:!1,disabledReason:Zo};var $=this.Yo(es);return{visible:$.eligible,disabledReason:$.reason}}canRenderSurveyAsync(es,$){return D(this._surveyManager)?(En.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Zo})):new Promise((ts=>{this.getSurveys((is=>{var cs,Kr=(cs=is.find((Na=>Na.id===es)))!==null&&cs!==void 0?cs:null;if(Kr){var Xr=this.Yo(Kr);ts({visible:Xr.eligible,disabledReason:Xr.reason})}else ts({visible:!1,disabledReason:"Survey not found"})}),$)}))}renderSurvey(es,$,ts){var is;if(D(this._surveyManager))En.warn("init was not called");else{var cs=typeof es=="string"?this.Uo(es):es;if(cs!=null&&cs.id)if($n.includes(cs.type)){var Kr=r==null?void 0:r.querySelector($);if(Kr)return(is=cs.appearance)!=null&&is.surveyPopupDelaySeconds?(En.info("Rendering survey "+cs.id+" with delay of "+cs.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var Xr,Na;En.info("Rendering survey "+cs.id+" with delay of "+((Xr=cs.appearance)==null?void 0:Xr.surveyPopupDelaySeconds)+" seconds"),(Na=this._surveyManager)==null||Na.renderSurvey(cs,Kr,ts),En.info("Survey "+cs.id+" rendered")}),1e3*cs.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(cs,Kr,ts);En.warn("Survey element not found")}else En.warn("Surveys of type "+cs.type+" cannot be rendered in the app");else En.warn("Survey not found")}}displaySurvey(es,$){var ts;if(D(this._surveyManager))En.warn("init was not called");else{var is=this.Uo(es);if(is){var cs=is;if((ts=is.appearance)!=null&&ts.surveyPopupDelaySeconds&&$.ignoreDelay&&(cs=f({},is,{appearance:f({},is.appearance,{surveyPopupDelaySeconds:0})})),$.displayType!==ns.Popover&&$.initialResponses&&En.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),$.ignoreConditions===!1){var Kr=this.canRenderSurvey(is);if(!Kr.visible)return void En.warn("Survey is not eligible to be displayed: ",Kr.disabledReason)}$.displayType!==ns.Inline?this._surveyManager.handlePopoverSurvey(cs,$):this.renderSurvey(cs,$.selector,$.properties)}else En.warn("Survey not found")}}cancelPendingSurvey(es){D(this._surveyManager)?En.warn("init was not called"):this._surveyManager.cancelSurvey(es)}handlePageUnload(){var es;(es=this._surveyManager)==null||es.handlePageUnload()}}},fa),Ea={toolbar:class{constructor(es){this.instance=es}Go(es){h.ph_toolbar_state=es}Wo(){var es;return(es=h.ph_toolbar_state)!==null&&es!==void 0?es:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(es,$,ts){if(es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),Qi(this.instance.config)||!t||!r)return!1;es=es??t.location,ts=ts??t.history;try{if(!$){try{t.localStorage.setItem("test","test"),t.localStorage.removeItem("test")}catch{return!1}$=t==null?void 0:t.localStorage}var is,cs=ea||Ir(es.hash,"__posthog")||Ir(es.hash,"state"),Kr=cs?Wi((()=>JSON.parse(atob(decodeURIComponent(cs)))))||Wi((()=>JSON.parse(decodeURIComponent(cs)))):null;return Kr&&Kr.action==="ph_authorize"?((is=Kr).source="url",is&&Object.keys(is).length>0&&(Kr.desiredHash?es.hash=Kr.desiredHash:ts?ts.replaceState(ts.state,"",es.pathname+es.search):es.hash="")):((is=JSON.parse($.getItem(ia)||"{}")).source="localstorage",delete is.userIntent),!(!is.token||this.instance.config.token!==is.token||(this.loadToolbar(is),0))}catch{return!1}}Xo(es){var $=h.ph_load_toolbar||h.ph_load_editor;!D($)&&P($)?$(es,this.instance):ra.warn("No toolbar load function found")}loadToolbar(es){var $=!(r==null||!r.getElementById($i));if(!t||$)return!1;var ts=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,is=f({token:this.instance.config.token},es,{apiURL:this.instance.requestRouter.endpointFor("ui")},ts?{instrument:!1}:{});if(t.localStorage.setItem(ia,JSON.stringify(f({},is,{source:void 0}))),this.Wo()===2)this.Xo(is);else if(this.Wo()===0){var cs;this.Go(1),(cs=h.__PosthogExtensions__)==null||cs.loadExternalDependency==null||cs.loadExternalDependency(this.instance,"toolbar",(Kr=>{if(Kr)return ra.error("[Toolbar] Failed to load",Kr),void this.Go(0);this.Go(2),this.Xo(is)})),Xi(t,"turbolinks:load",(()=>{this.Go(0),this.loadToolbar(is)}))}return!0}Jo(es){return this.loadToolbar(es)}maybeLoadEditor(es,$,ts){return es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),this.maybeLoadToolbar(es,$,ts)}}},Sa=f({experiments:va},fa),$a={conversations:class{constructor(es){this.Ko=void 0,this._conversationsManager=null,this.Qo=!1,this.ea=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this._instance.config.disable_conversations){var $=es.conversations;D($)||(N($)?this.Ko=$:(this.Ko=$.enabled,this.ea=$),this.loadIfEnabled())}}reset(){var es;(es=this._conversationsManager)==null||es.reset(),this._conversationsManager=null,this.Ko=void 0,this.ea=null}loadIfEnabled(){if(!(this._conversationsManager||this.Qo||this._instance.config.disable_conversations||Qi(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var es=h==null?void 0:h.__PosthogExtensions__;if(es&&!C(this.Ko)&&this.Ko)if(this.ea&&this.ea.token){this.Qo=!0;try{var $=es.initConversations;if($)return this.ta($),void(this.Qo=!1);var ts=es.loadExternalDependency;if(!ts)return void this.ra(Oi);ts(this._instance,"conversations",(is=>{is||!es.initConversations?this.ra("Could not load conversations script",is):this.ta(es.initConversations),this.Qo=!1}))}catch(is){this.ra("Error initializing conversations",is),this.Qo=!1}}else ca.error("Conversations enabled but missing token in remote config.")}}ta(es){if(this.ea)try{this._conversationsManager=es(this.ea,this._instance),ca.info("Conversations loaded successfully")}catch($){this.ra("Error completing conversations initialization",$)}else ca.error("Cannot complete initialization: remote config is null")}ra(es,$){ca.error(es,$),this._conversationsManager=null,this.Qo=!1}show(){this._conversationsManager?this._conversationsManager.show():ca.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ko===!0&&!M(this._conversationsManager)}isVisible(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.isVisible())!==null&&es!==void 0&&es}sendMessage(es,$,ts){var is=this;return p((function*(){return is._conversationsManager?is._conversationsManager.sendMessage(es,$,ts):(ca.warn(pa),null)}))()}getMessages(es,$){var ts=this;return p((function*(){return ts._conversationsManager?ts._conversationsManager.getMessages(es,$):(ca.warn(pa),null)}))()}markAsRead(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.markAsRead(es):(ca.warn(pa),null)}))()}getTickets(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.getTickets(es):(ca.warn(pa),null)}))()}requestRestoreLink(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.requestRestoreLink(es):(ca.warn(pa),null)}))()}restoreFromToken(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.restoreFromToken(es):(ca.warn(pa),null)}))()}restoreFromUrlToken(){var es=this;return p((function*(){return es._conversationsManager?es._conversationsManager.restoreFromUrlToken():(ca.warn(pa),null)}))()}getCurrentTicketId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getCurrentTicketId())!==null&&es!==void 0?es:null}getWidgetSessionId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getWidgetSessionId())!==null&&es!==void 0?es:null}un(){var es;(es=this._conversationsManager)==null||es.setIdentity()}hn(){var es;(es=this._conversationsManager)==null||es.clearIdentity()}}},Ta={logs:class{constructor(es){var $;this.ia=!1,this.na=!1,this.Gt=Ce("[logs]"),this.sa=[],this.oa=0,this.aa=0,this.la=!1,this._instance=es,this._instance&&($=this._instance.config.logs)!=null&&$.captureConsoleLogs&&(this.ia=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(es){var $,ts=($=es.logs)==null?void 0:$.captureConsoleLogs;!D(ts)&&ts&&(this.ia=!0,this.loadIfEnabled())}reset(){this.sa=[],this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.oa=0,this.aa=0,this.la=!1}loadIfEnabled(){if(this.ia&&!this.na){var es=h==null?void 0:h.__PosthogExtensions__;if(es){var $=es.loadExternalDependency;$?$(this._instance,"logs",(ts=>{var is;ts||(is=es.logs)==null||!is.initializeLogs?this.Gt.error("Could not load logs script",ts):(es.logs.initializeLogs(this._instance),this.na=!0)})):this.Gt.error(Oi)}else this.Gt.error("PostHog Extensions not found.")}}captureLog(es){var $,ts,is,cs,Kr,Xr;if(this._instance.is_capturing())if(es&&es.body){var Na=($=(ts=this._instance.config.logs)==null?void 0:ts.flushIntervalMs)!==null&&$!==void 0?$:3e3,Ca=(is=(cs=this._instance.config.logs)==null?void 0:cs.maxLogsPerInterval)!==null&&is!==void 0?is:1e3,Aa=Date.now();if(Na>Aa-this.aa||(this.aa=Aa,this.oa=0,this.la=!1),Ca>this.oa){this.oa++;var Ia=(function(Ma,Pa){var La=Ma.level||"info",{text:Fa,number:Ba}=Jt[La]||Kt,qa=String(Date.now())+"000000",za={};Pa.distinctId&&(za.posthogDistinctId=Pa.distinctId),Pa.sessionId&&(za.sessionId=Pa.sessionId),Pa.currentUrl&&(za["url.full"]=Pa.currentUrl),Pa.screenName&&(za["screen.name"]=Pa.screenName),Pa.appState&&(za["app.state"]=Pa.appState),Pa.activeFeatureFlags&&Pa.activeFeatureFlags.length>0&&(za.feature_flags=Pa.activeFeatureFlags);var Va=f({},za,Ma.attributes||{}),Ga={timeUnixNano:qa,observedTimeUnixNano:qa,severityNumber:Ba,severityText:Fa,body:{stringValue:Ma.body},attributes:Qt(Va)};return Ma.trace_id&&(Ga.traceId=Ma.trace_id),Ma.span_id&&(Ga.spanId=Ma.span_id),C(Ma.trace_flags)||(Ga.flags=Ma.trace_flags),Ga})(es,this.ua());this.sa.push({record:Ia}),((Kr=(Xr=this._instance.config.logs)==null?void 0:Xr.maxBufferSize)!==null&&Kr!==void 0?Kr:100)>this.sa.length?this.ha():this.flushLogs()}else this.la||(this.Gt.warn("captureLog dropping logs: exceeded "+Ca+" logs per "+Na+"ms"),this.la=!0)}else this.Gt.warn("captureLog requires a body")}get logger(){return this.ca||(this.ca={trace:(es,$)=>this.captureLog({body:es,level:"trace",attributes:$}),debug:(es,$)=>this.captureLog({body:es,level:"debug",attributes:$}),info:(es,$)=>this.captureLog({body:es,level:"info",attributes:$}),warn:(es,$)=>this.captureLog({body:es,level:"warn",attributes:$}),error:(es,$)=>this.captureLog({body:es,level:"error",attributes:$}),fatal:(es,$)=>this.captureLog({body:es,level:"fatal",attributes:$})}),this.ca}flushLogs(es){if(this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.sa.length!==0){var $=this.sa;this.sa=[];var ts=this._instance.config.logs,is=f({"service.name":(ts==null?void 0:ts.serviceName)||"unknown_service"},(ts==null?void 0:ts.environment)&&{"deployment.environment":ts.environment},(ts==null?void 0:ts.serviceVersion)&&{"service.version":ts.serviceVersion},ts==null?void 0:ts.resourceAttributes),cs=(function(Xr,Na,Ca,Aa){return{resourceLogs:[{resource:{attributes:Qt(Na)},scopeLogs:[{scope:{name:Ca,version:Aa},logRecords:Xr}]}]}})($.map((Xr=>Xr.record)),is,v.LIB_NAME,v.LIB_VERSION),Kr=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Vi({method:"POST",url:Kr,data:cs,compression:"best-available",batchKey:"logs",transport:es})}}ha(){var es,$;this.jr||(this.jr=setTimeout((()=>{this.jr=void 0,this.flushLogs()}),(es=($=this._instance.config.logs)==null?void 0:$.flushIntervalMs)!==null&&es!==void 0?es:3e3))}ua(){var es,$={};if($.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:ts}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);$.sessionId=ts}if(h!=null&&(es=h.location)!=null&&es.href&&($.currentUrl=h.location.href),this._instance.featureFlags){var is=this._instance.featureFlags.getFlags();is&&is.length>0&&($.activeFeatureFlags=is)}return $}}},ka=f({},fa,_a,ga,ma,ba,ya,xa,wa,Ea,Sa,$a,Ta);qn.__defaultExtensionClasses=f({},ka);var Ra;Ra=In[Un]=new qn,(function(){function es(){es.done||(es.done=!0,Nn=!1,Hi(In,(function($){$._dom_loaded()})))}r!=null&&r.addEventListener?r.readyState==="complete"?es():Xi(r,"DOMContentLoaded",es,{capture:!1}):t&&Ie.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})();function PostHogProvider({children:es}){const{user:$}=useAuth(),ts=useLocation();return reactExports.useRef(null),reactExports.useEffect(()=>{},[]),reactExports.useEffect(()=>{},[$]),reactExports.useEffect(()=>{},[ts.pathname]),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es})}function Separator({className:es,orientation:$="horizontal",decorative:ts=!0,...is}){return jsxRuntimeExports.jsx(Root,{"data-slot":"separator",decorative:ts,orientation:$,className:cn$1("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",es),...is})}function usePendingSuggestionCount(){return useQuery({queryKey:["instruction-suggestions","pending-count"],queryFn:()=>apiGet("/api/instruction-suggestions/pending-count"),staleTime:300*1e3})}function useProjectPaths(){return useQuery({queryKey:["sessions","project-paths"],queryFn:()=>apiGet("/api/sessions/project-paths?limit=20"),select:es=>es.projectPaths})}function useSuggestionsForProjects(es){return useQueries({queries:es.map($=>({queryKey:["instruction-suggestions",$],queryFn:()=>apiGet(`/api/instruction-suggestions?projectPath=${encodeURIComponent($)}&limit=10`).then(ts=>({projectPath:$,suggestions:ts.suggestions}))}))})}function useSuggestionImpacts(es){const $=[...new Set(es)].sort().join(",");return useQuery({queryKey:["insights","suggestion-impact",$],queryFn:()=>apiGet(`/api/insights/suggestion-impact?instructionIds=${encodeURIComponent($)}`),select:ts=>ts.impacts,enabled:$.length>0})}function useLogSuggestionEvent(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instruction-suggestions/${$.suggestionId}/events`,{eventType:$.eventType,projectPath:$.projectPath,tool:$.tool}),onSuccess:()=>{es.invalidateQueries({queryKey:["instruction-suggestions"]})}})}function usePromoteFromPublic(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instructions/${$.sourceInstructionId}/promote-from-public`,{targetScope:$.targetScope,targetScopeRef:$.targetScopeRef,name:$.name}),onSuccess:()=>{es.invalidateQueries({queryKey:["instructions"]}),es.invalidateQueries({queryKey:["catalog"]})}})}const PUBLIC_PAGE_SIZE=50;function usePublicCatalog(es){return useInfiniteQuery({queryKey:["catalog","public",es??""],initialPageParam:0,queryFn:({pageParam:$})=>{const ts=new URLSearchParams({scope:"public",limit:String(PUBLIC_PAGE_SIZE),offset:String($)});return es&&ts.set("search",es),apiGet(`/api/catalog?${ts.toString()}`)},getNextPageParam:($,ts)=>{if(!($.length<PUBLIC_PAGE_SIZE))return ts.length*PUBLIC_PAGE_SIZE}})}function useWorkerStatus(es){const $=useQuery({queryKey:["worker-status"],queryFn:()=>apiGet("/api/workers/status"),refetchInterval:3e4}),ts=$.data??[],is=es?ts.filter(Kr=>Kr.workerType===es):ts,cs=is.filter(Kr=>Kr.status==="active");return{...$,workers:is,activeWorkers:cs,isConnected:cs.length>0,workerCount:cs.length}}function formatRelativeTime$2(es){const $=Date.now()-new Date(es).getTime(),ts=Math.floor($/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}const typeLabels={mcp:"MCP","cli-worker":"CLI Worker",gateway:"Gateway",proxy:"Proxy"};function WorkerStatus(){const{workers:es,activeWorkers:$,isConnected:ts,isLoading:is}=useWorkerStatus();return is||es.length===0?jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full shrink-0 bg-muted-foreground/30"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"No workers connected"})]})}):jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border px-3 py-2 text-xs space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:cn$1("h-2 w-2 rounded-full shrink-0",ts?"bg-teal-500":"bg-amber-500")}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:ts?`${$.length} worker${$.length>1?"s":""} online`:"Workers offline"})]}),es.map(cs=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground pl-4",children:[jsxRuntimeExports.jsx("span",{children:typeLabels[cs.workerType]??cs.workerType}),jsxRuntimeExports.jsx("span",{children:cs.status==="active"?formatRelativeTime$2(cs.lastHeartbeat):"offline"})]},cs.id))]})})}const navItems=[{to:"/dashboard",label:"Dashboard",icon:LayoutDashboard},{to:"/connect",label:"Connect",icon:Plug},{to:"/sessions",label:"Sessions",icon:Activity},{to:"/projects",label:"Projects",icon:Layers},{to:"/eval-targets",label:"Evals",icon:FlaskConical},{to:"/insights",label:"Insights",icon:TrendingUp},{to:"/memories",label:"Memories",icon:Brain},{to:"/usage",label:"Usage",icon:DollarSign},{to:"/skills",label:"Skills",icon:Sparkles},{to:"/catalog/public",label:"Public Catalog",icon:Globe},{to:"/suggestions",label:"Suggestions",icon:Lightbulb},{to:"/docs",label:"Docs",icon:BookOpen}];function Sidebar({className:es}){const $=useLocation(),{profile:ts}=useActiveOrg(),{data:is}=usePendingSuggestionCount();return jsxRuntimeExports.jsxs("aside",{className:cn$1("flex h-full w-60 flex-col border-r border-border bg-background p-4",es),children:[jsxRuntimeExports.jsxs("div",{className:"mb-6 flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("h1",{className:"font-mono text-lg font-semibold tracking-tight",children:"RuleMetric"})]}),jsxRuntimeExports.jsx("nav",{className:"flex flex-col gap-1",children:navItems.map(cs=>{const Kr=$.pathname.startsWith(cs.to);return jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",Kr&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:cs.to,children:[jsxRuntimeExports.jsx(cs.icon,{className:cn$1("mr-2 h-4 w-4",Kr&&"text-primary")}),cs.label,cs.to==="/suggestions"&&((is==null?void 0:is.total)??0)>0&&jsxRuntimeExports.jsx("span",{className:"ml-auto rounded-full bg-primary/15 px-2 py-0.5 font-mono text-xs text-primary",children:is.total>99?"99+":is.total})]})},cs.to)})}),(ts==null?void 0:ts.isSuperadmin)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Separator,{className:"my-4"}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/superadmin")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/superadmin/users",children:[jsxRuntimeExports.jsx(Shield,{className:"mr-2 h-4 w-4"}),"Superadmin"]})}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/admin/announcements")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/admin/announcements",children:[jsxRuntimeExports.jsx(Megaphone,{className:"mr-2 h-4 w-4"}),"Announcements"]})})]}),jsxRuntimeExports.jsx(Separator,{className:"my-4"}),jsxRuntimeExports.jsx("div",{className:"flex flex-col gap-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"justify-start cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/import",children:[jsxRuntimeExports.jsx(Upload,{className:"mr-2 h-4 w-4"}),"Import"]})})}),jsxRuntimeExports.jsx("div",{className:"mt-auto",children:jsxRuntimeExports.jsx(WorkerStatus,{})})]})}function DropdownMenu({...es}){return jsxRuntimeExports.jsx(Root2$2,{"data-slot":"dropdown-menu",...es})}function DropdownMenuTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$3,{"data-slot":"dropdown-menu-trigger",...es})}function DropdownMenuContent({className:es,sideOffset:$=4,...ts}){return jsxRuntimeExports.jsx(Portal2,{children:jsxRuntimeExports.jsx(Content2$2,{"data-slot":"dropdown-menu-content",sideOffset:$,className:cn$1("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",es),...ts})})}function DropdownMenuItem({className:es,inset:$,variant:ts="default",...is}){return jsxRuntimeExports.jsx(Item2,{"data-slot":"dropdown-menu-item","data-inset":$,"data-variant":ts,className:cn$1("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",es),...is})}function DropdownMenuLabel({className:es,inset:$,...ts}){return jsxRuntimeExports.jsx(Label2,{"data-slot":"dropdown-menu-label","data-inset":$,className:cn$1("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",es),...ts})}function DropdownMenuSeparator({className:es,...$}){return jsxRuntimeExports.jsx(Separator2,{"data-slot":"dropdown-menu-separator",className:cn$1("bg-border -mx-1 my-1 h-px",es),...$})}function Avatar({className:es,size:$="default",...ts}){return jsxRuntimeExports.jsx(Root$4,{"data-slot":"avatar","data-size":$,className:cn$1("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",es),...ts})}function AvatarFallback({className:es,...$}){return jsxRuntimeExports.jsx(Fallback,{"data-slot":"avatar-fallback",className:cn$1("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",es),...$})}function Sheet({...es}){return jsxRuntimeExports.jsx(Root$5,{"data-slot":"sheet",...es})}function SheetTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$4,{"data-slot":"sheet-trigger",...es})}function SheetPortal({...es}){return jsxRuntimeExports.jsx(Portal$3,{"data-slot":"sheet-portal",...es})}function SheetOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"sheet-overlay",className:cn$1("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",es),...$})}function SheetContent({className:es,children:$,side:ts="right",showCloseButton:is=!0,...cs}){return jsxRuntimeExports.jsxs(SheetPortal,{children:[jsxRuntimeExports.jsx(SheetOverlay,{}),jsxRuntimeExports.jsxs(Content$2,{"data-slot":"sheet-content",className:cn$1("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",ts==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",ts==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",ts==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",ts==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",es),...cs,children:[$,is&&jsxRuntimeExports.jsxs(Close,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[jsxRuntimeExports.jsx(X$1,{className:"size-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function SheetHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"sheet-header",className:cn$1("flex flex-col gap-1.5 p-4",es),...$})}function SheetTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"sheet-title",className:cn$1("text-foreground font-semibold",es),...$})}function SheetDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"sheet-description",className:cn$1("text-muted-foreground text-sm",es),...$})}const NOTIFICATIONS_QUERY_KEY=["notifications"];function useNotifications(){var Kr,Xr;const es=useQueryClient(),{user:$}=useAuth(),ts=useQuery({queryKey:NOTIFICATIONS_QUERY_KEY,queryFn:()=>apiGet("/api/notifications?limit=20"),enabled:!!$}),is=useMutation({mutationFn:Na=>apiPost(`/api/notifications/${Na}/read`,{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})}),cs=useMutation({mutationFn:()=>apiPost("/api/notifications/read-all",{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})});return{items:((Kr=ts.data)==null?void 0:Kr.items)??[],unreadCount:((Xr=ts.data)==null?void 0:Xr.unreadCount)??0,isLoading:ts.isLoading,markRead:Na=>is.mutate(Na),markAllRead:()=>cs.mutate()}}function NotificationsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;(async()=>{if(!(typeof Notification>"u")&&Notification.permission==="default")try{await Notification.requestPermission()}catch{}})();let is=null;const cs=setTimeout(()=>{is=supabase.channel(`notifications-${es.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications",filter:`user_id=eq.${es.id}`},Kr=>{const Xr=Kr.new,Na={id:Xr.id,userId:Xr.user_id,type:Xr.type,title:Xr.title,body:Xr.body??null,url:Xr.url??null,sourceTable:Xr.source_table??null,sourceId:Xr.source_id??null,metadata:Xr.metadata??{},readAt:Xr.read_at??null,createdAt:Xr.created_at};$.setQueryData(NOTIFICATIONS_QUERY_KEY,Ca=>{const Aa=(Ca==null?void 0:Ca.items)??[];return Aa.some(Ia=>Ia.id===Na.id)?Ca??{items:Aa,unreadCount:0}:{items:[Na,...Aa].slice(0,20),unreadCount:((Ca==null?void 0:Ca.unreadCount)??0)+1}}),fireOsNotification(Na)}).subscribe()},50);return()=>{clearTimeout(cs),is&&supabase.removeChannel(is)}},[es==null?void 0:es.id,$]),null}async function fireOsNotification(es){if(typeof Notification>"u"||Notification.permission!=="granted")return;const $={body:es.body??void 0,icon:"/favicon-192.png",badge:"/favicon-48.png",tag:`notif-${es.id}`,data:{url:es.url??"/",notificationId:es.id}};if("serviceWorker"in navigator)try{await(await navigator.serviceWorker.ready).showNotification(es.title,$);return}catch{}new Notification(es.title,$)}function typeIcon(es){if(es.startsWith("usage_")){const $=es==="usage_imminent"||es==="usage_hit";return jsxRuntimeExports.jsx(TriangleAlert,{className:cn$1("h-3.5 w-3.5",$?"text-red-500":"text-amber-500")})}return es.endsWith("_failed")?jsxRuntimeExports.jsx(CircleAlert,{className:"h-3.5 w-3.5 text-red-500"}):es==="insights_ready"?jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-amber-500"}):es==="labels_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):es==="calibration_ready"?jsxRuntimeExports.jsx(BadgeCheck,{className:"h-3.5 w-3.5 text-teal-500"}):es==="second_engine_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-blue-500"}):es==="second_opinions_flagged"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):jsxRuntimeExports.jsx(BellRing,{className:"h-3.5 w-3.5 text-blue-500"})}function formatRelative(es){const $=Date.now()-new Date(es).getTime(),ts=Math.floor($/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}function NotificationBell(){const es=useNavigate(),{items:$,unreadCount:ts,markRead:is,markAllRead:cs}=useNotifications(),Kr=Xr=>{Xr.readAt||is(Xr.id),Xr.url&&es(Xr.url)};return jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"relative cursor-pointer",children:[jsxRuntimeExports.jsx(Bell,{className:"h-4 w-4"}),ts>0&&jsxRuntimeExports.jsx("span",{className:"absolute top-1 right-1 inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-blue-500 px-1 text-[10px] font-medium text-white",children:ts>9?"9+":ts})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",className:"w-80",children:[jsxRuntimeExports.jsxs(DropdownMenuLabel,{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{children:"Notifications"}),ts>0&&jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(),className:"flex items-center gap-1 text-[10px] font-normal text-muted-foreground hover:text-foreground",children:[jsxRuntimeExports.jsx(CheckCheck,{className:"h-3 w-3"}),"Mark all read"]})]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),$.length===0?jsxRuntimeExports.jsx(DropdownMenuItem,{disabled:!0,children:jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"No notifications yet"})}):$.map(Xr=>jsxRuntimeExports.jsx(DropdownMenuItem,{className:"cursor-pointer",onClick:()=>Kr(Xr),children:jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 w-full",children:[jsxRuntimeExports.jsx("div",{className:"mt-0.5",children:typeIcon(Xr.type)}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium truncate",children:Xr.title}),Xr.body&&jsxRuntimeExports.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:Xr.body}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground",children:formatRelative(Xr.createdAt)})]}),!Xr.readAt&&jsxRuntimeExports.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-blue-500"})]})},Xr.id))]})]})}function OrgSwitcher(){return useActiveOrg(),useSetActiveOrg(),useNavigate(),null}function Header(){var is;const{user:es,signOut:$}=useAuth(),ts=((is=es==null?void 0:es.email)==null?void 0:is.slice(0,2).toUpperCase())??"?";return jsxRuntimeExports.jsxs("header",{className:"flex h-12 items-center border-b border-border px-2 gap-1 sm:px-4 sm:gap-4 bg-background",children:[jsxRuntimeExports.jsxs(Sheet,{children:[jsxRuntimeExports.jsx(SheetTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"md:hidden cursor-pointer",children:jsxRuntimeExports.jsx(Menu$1,{className:"h-5 w-5"})})}),jsxRuntimeExports.jsxs(SheetContent,{side:"left",className:"w-60 p-0",children:[jsxRuntimeExports.jsx(SheetTitle,{className:"sr-only",children:"Navigation"}),jsxRuntimeExports.jsx(Sidebar,{})]})]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx(OrgSwitcher,{}),jsxRuntimeExports.jsx(NotificationBell,{}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"rounded-full cursor-pointer shrink-0",children:jsxRuntimeExports.jsx(Avatar,{className:"h-8 w-8",children:jsxRuntimeExports.jsx(AvatarFallback,{className:"text-xs bg-secondary text-muted-foreground",children:ts})})})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsxs(DropdownMenuItem,{disabled:!0,children:[jsxRuntimeExports.jsx(User,{className:"mr-2 h-4 w-4"}),es==null?void 0:es.email]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),jsxRuntimeExports.jsxs(DropdownMenuItem,{onClick:()=>$(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4"}),"Sign out"]})]})]})]})}function useComputedInsights(es,$,ts){const is=(ts==null?void 0:ts.projectId)??void 0,cs=new URLSearchParams;return es&&cs.set("projectPath",es),is&&cs.set("projectId",is),$&&cs.set("tool",$),ts!=null&&ts.since&&cs.set("since",ts.since),useQuery({queryKey:["insights","computed",es,is??null,$,(ts==null?void 0:ts.since)??null],queryFn:()=>apiGet(`/api/insights/compute?${cs}`),refetchInterval:ts==null?void 0:ts.refetchIntervalMs})}function useInstructionImpact(es){return useQuery({queryKey:["insights","instruction-impact",es],queryFn:()=>apiGet(`/api/insights/instruction-impact?instructionId=${es}`),enabled:!!es})}function useGroomCandidates(){return useQuery({queryKey:["insights","groom-candidates"],queryFn:()=>apiGet("/api/insights/groom-candidates")})}function useArchiveInstruction(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/instructions/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","groom-candidates"]}),es.invalidateQueries({queryKey:["insights"]})}})}function useLinkedInstructions(es){const $=new URLSearchParams;return es&&$.set("projectPath",es),useQuery({queryKey:["insights","linked-instructions",es],queryFn:()=>apiGet(`/api/insights/linked-instructions?${$}`)})}function useInsightsProjects(){return useQuery({queryKey:["insights","projects"],queryFn:()=>apiGet("/api/insights/projects")})}function useInsightsJobs(es,$){const ts=new URLSearchParams;return es&&ts.set("projectPath",es),$&&ts.set("limit",String($)),useQuery({queryKey:["insights-jobs",es,$],queryFn:()=>apiGet(`/api/insights-jobs?${ts}`),refetchInterval:5e3})}const STALE_JOB_MS=600*1e3;function useActiveInsightsJobs(es){const{data:$}=useInsightsJobs(es),ts=Date.now();return($??[]).filter(is=>{if(!["pending","claimed","running"].includes(is.status))return!1;const cs=is.claimedAt?new Date(is.claimedAt).getTime():0;return!cs||ts-cs<=STALE_JOB_MS})}function useCreateInsightsJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs",{projectPath:$}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useRegenerateAllInsights(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs/regenerate-all",$!=null&&$.force?{force:!0}:{}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useAutoAddSuggestion(){return useMutation({mutationFn:es=>apiPost("/api/insights/auto-add",es)})}function useProjectInsights(es,$,ts,is){var Qa;const{data:cs}=useInsightsProjects(),Kr=$?cs==null?void 0:cs.find(Xa=>Xa.projectPath===$):void 0,Xr=ts??(Kr==null?void 0:Kr.projectId)??void 0,{data:Na,isLoading:Ca}=useComputedInsights($,is,{projectId:Xr}),Aa=$?(Kr==null?void 0:Kr.name)??$.split("/").filter(Boolean).slice(-2).join("/"):void 0,Ia=useActiveInsightsJobs($),{data:Ma}=useInsightsJobs($),Pa=useCreateInsightsJob(),La=Na??null,Fa=(Qa=Ia[0])==null?void 0:Qa.progress,Ba=Fa!=null&&Fa.partial&&Object.keys(Fa.partial).length>0?Fa.partial:void 0,qa=(La==null?void 0:La.recommendations)??Ba,za=(Ma??[]).filter(Xa=>Xa.status==="completed"&&Xa.completedAt).sort((Xa,Ja)=>new Date(Ja.completedAt).getTime()-new Date(Xa.completedAt).getTime())[0],Va=(Na==null?void 0:Na.sessions_with_meta)??0,Ga=Aa??"Live Insights",Za=`Computed from ${Va} enriched sessions`;return{data:La,recommendations:qa,isLoading:Ca,fullProjectPath:$,title:Ga,subtitle:Za,lastCompletedJob:za,activeJobs:Ia,createJob:Pa}}function InsightsJobsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;let ts=null;const is=setTimeout(()=>{ts=supabase.channel(`insights-jobs-${es.id}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"insights_jobs",filter:`user_id=eq.${es.id}`},cs=>{const Kr=cs.new,Xr={id:Kr.id,status:Kr.status,projectPath:Kr.project_path??null,progress:Kr.progress??{},error:Kr.error??null,updatedAt:Kr.updated_at,completedAt:Kr.completed_at??null};$.setQueriesData({queryKey:["insights-jobs"]},Na=>{if(!Na)return Na;const Ca=Na.findIndex(Ia=>Ia.id===Xr.id);if(Ca===-1)return Na;const Aa=Na.slice();return Aa[Ca]={...Na[Ca],...Xr},Aa}),Xr.status==="completed"&&$.invalidateQueries({queryKey:["insights","computed"]})}).subscribe()},50);return()=>{clearTimeout(is),ts&&supabase.removeChannel(ts)}},[es==null?void 0:es.id,$]),null}const SEVERITY_LABEL={soft:"soft warning",approaching:"approaching limit",imminent:"imminent limit",hit:"limit reached"};function formatTimeLeft(es,$){if(!es)return"soon";const ts=new Date(es).getTime()-$;if(ts<=0)return"now";const is=Math.round(ts/6e4);if(is<60)return`in ${is} min`;const cs=Math.floor(is/60),Kr=is%60;return Kr>0?`in ${cs}h ${Kr}m`:`in ${cs}h`}function formatAlertMessage(es,$,ts,is,cs=Date.now()){const Kr=formatTimeLeft(is,cs);if(es==="hit")return`Claude ${$} reached 100% — requests will fail. Resets ${Kr}.`;const Xr=ts!=null?`${ts.toFixed(0)}%`:"limit";return`Claude ${$} at ${Xr} — ${SEVERITY_LABEL[es]}. Resets ${Kr}.`}const ACTIVE_WINDOW_MS=600*1e3,POLL_MS=3e4,SEVERITY_STYLES={soft:"bg-yellow-100 border-yellow-300 text-yellow-900",approaching:"bg-amber-200 border-amber-400 text-amber-950",imminent:"bg-orange-300 border-orange-500 text-orange-950",hit:"bg-red-400 border-red-600 text-red-950"};function dismissKey$1(es){return`alert-dismissed:${es}`}function AlertBanner(){var Pa,La,Fa;const{data:es}=useQuery({queryKey:["alerts-recent"],queryFn:()=>apiGet("/api/alerts/recent"),refetchInterval:POLL_MS,refetchOnWindowFocus:!0}),[,$]=reactExports.useState(0);reactExports.useEffect(()=>{const Ba=setInterval(()=>$(qa=>qa+1),6e4);return()=>clearInterval(Ba)},[]);const ts=(es==null?void 0:es.items)??[];reactExports.useEffect(()=>{if(typeof window>"u"||!es)return;const Ba=new Set(ts.map(qa=>qa.id));for(let qa=localStorage.length-1;qa>=0;qa--){const za=localStorage.key(qa);za!=null&&za.startsWith("alert-dismissed:")&&!Ba.has(za.slice(16))&&localStorage.removeItem(za)}},[es,ts]);const is=Date.now(),cs=ts.find(Ba=>!(is-new Date(Ba.lastDispatchedAt).getTime()>ACTIVE_WINDOW_MS||typeof window<"u"&&localStorage.getItem(dismissKey$1(Ba.id)))),[,Kr]=reactExports.useState(0);if(!cs)return null;const Xr=cs.severity,Na=(Pa=cs.lastState)==null?void 0:Pa.usedPercentage,Ca=(La=cs.lastState)==null?void 0:La.resetsAt,[,,Aa]=cs.alertKey.split(":"),Ia=((Fa=cs.lastState)==null?void 0:Fa.message)??formatAlertMessage(Xr,Aa,Na,Ca);function Ma(){typeof window<"u"&&localStorage.setItem(dismissKey$1(cs.id),"1"),Kr(Ba=>Ba+1)}return jsxRuntimeExports.jsxs("div",{role:Xr==="hit"?"alert":"status",className:cn$1("flex items-center gap-3 border-b px-4 py-2 text-sm",SEVERITY_STYLES[Xr]),children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsx("span",{className:"flex-1 font-mono",children:Ia}),jsxRuntimeExports.jsx("button",{type:"button",onClick:Ma,"aria-label":"Dismiss alert",className:"rounded p-1 hover:bg-black/10",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useLatestVersion(){return useQuery({queryKey:["cli-latest-version"],queryFn:()=>apiGet("/api/cli/latest-version"),staleTime:3600*1e3,refetchInterval:3600*1e3,refetchOnWindowFocus:!1})}function compareVersions(es,$){const ts=Xr=>Xr.split(".").map(Na=>Number.parseInt(Na,10)||0),is=ts(es),cs=ts($),Kr=Math.max(is.length,cs.length);for(let Xr=0;Xr<Kr;Xr++){const Na=is[Xr]??0,Ca=cs[Xr]??0;if(Na<Ca)return-1;if(Na>Ca)return 1}return 0}function cliUpdateStatus(es,$){if(!$)return null;const ts=es.filter(cs=>typeof cs=="string"&&cs.length>0);if(ts.length===0)return null;const is=ts.reduce((cs,Kr)=>compareVersions(Kr,cs)>0?Kr:cs,ts[0]);return compareVersions($,is)<=0?null:{current:is,latest:$}}const CLI_WORKER_TYPES=new Set(["cli-worker","gateway","proxy"]);function dismissKey(es){return`cli-update-dismissed:${es}`}function CliUpdateBanner(){const{activeWorkers:es}=useWorkerStatus(),{data:$}=useLatestVersion(),[,ts]=reactExports.useState(0),is=cliUpdateStatus(es.filter(Kr=>CLI_WORKER_TYPES.has(Kr.workerType)).map(Kr=>Kr.clientVersion),$==null?void 0:$.latest);if(!is||typeof window<"u"&&localStorage.getItem(dismissKey(is.latest)))return null;function cs(){typeof window<"u"&&localStorage.setItem(dismissKey(is.latest),"1"),ts(Kr=>Kr+1)}return jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-3 border-b border-primary/20 bg-primary/5 px-4 py-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(CircleArrowUp,{className:"h-4 w-4 flex-shrink-0 text-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex-1",children:["RuleMetric CLI ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:is.current})," →"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold text-primary",children:is.latest})," available. Upgrade:"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"npm i -g @rulemetric/cli@latest"}),", then re-run"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"rulemetric hooks install"})," ","to pick up new capture hooks."]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:cs,"aria-label":"Dismiss CLI update notice",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useWorkerHealth(){return useQuery({queryKey:["worker-health"],queryFn:()=>apiGet("/api/workers/health"),staleTime:6e4,refetchInterval:6e4,refetchOnWindowFocus:!0})}const DISMISS_TTL_MS=1440*60*1e3;function conditionKey(es){return`${es.severity}:${es.headline}`}function dismissStorageKey(es){return`worker-health-dismissed:${es}`}function bannerFor(es){return!es||es.severity==="ok"?null:{severity:es.severity,headline:es.headline,hints:es.hints,key:conditionKey(es)}}function isDismissed(es,$=Date.now(),ts=DISMISS_TTL_MS){if(!es)return!1;const is=Number(es);if(!Number.isFinite(is)||is<=0)return!1;const cs=$-is;return cs<0?!1:cs<ts}function WorkerHealthBanner(){const{data:es}=useWorkerHealth(),[,$]=reactExports.useState(0),ts=bannerFor(es==null?void 0:es.verdict);if(!ts)return null;const is=dismissStorageKey(ts.key),cs=typeof window>"u"?null:localStorage.getItem(is);if(isDismissed(cs))return null;function Kr(){typeof window<"u"&&localStorage.setItem(is,String(Date.now())),$(Ca=>Ca+1)}const Xr=ts.severity==="fail",Na=Xr?CircleX:TriangleAlert;return jsxRuntimeExports.jsxs("div",{role:"alert","data-testid":"worker-health-banner","data-severity":ts.severity,className:"flex items-start gap-3 border-b px-4 py-2 text-sm text-foreground "+(Xr?"border-destructive/30 bg-destructive/10":"border-amber-500/40 bg-amber-500/10"),children:[jsxRuntimeExports.jsx(Na,{className:"mt-0.5 h-4 w-4 flex-shrink-0 "+(Xr?"text-destructive":"text-amber-500")}),jsxRuntimeExports.jsxs("div",{className:"flex-1 space-y-1",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:ts.headline}),ts.hints.map(Ca=>jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ca},Ca))]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:Kr,"aria-label":"Dismiss worker health notice",title:"Hidden for 24 hours — reappears if the problem persists",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}const CORE_ORDER$1=["install","auth","hooks","worker"];function deriveSetupProgress(es){const $=Na=>Na?"detected":es.loading?"loading":"waiting",ts=es.authenticated?"detected":es.loading?"loading":"attention",is=es.cliEverConnected||es.anyCapturedSession||es.workerHeartbeat,cs={install:{id:"install",label:"Install the CLI",optional:!1,state:$(is),command:"npm install -g @rulemetric/cli",waitingFor:"first CLI connection",hint:"Requires Node. No Node? A standalone installer is coming — for now, install Node first."},auth:{id:"auth",label:"Authenticated",optional:!1,state:ts,waitingFor:"an active session"},hooks:{id:"hooks",label:"Hooks installed",optional:!1,state:$(es.anyCapturedSession),command:"rulemetric hooks install",waitingFor:"first captured session",hint:"Hooks capture your Claude Code sessions directly — no CA cert or proxy required. Optional: add the local proxy to also record the exact system prompt each model saw, capture your other AI tools (Copilot, Cursor, Codex), and track live cost & rate limits — which unlocks full cross-tool instruction-effectiveness analysis."},worker:{id:"worker",label:"Worker running",optional:!1,state:$(es.workerHeartbeat),command:"rulemetric service install --worker-only",waitingFor:"a worker heartbeat"},tmux:{id:"tmux",label:"Tmux available",optional:!0,state:$(es.hasActiveTmux),waitingFor:"a Claude Code session running inside tmux"},target:{id:"target",label:"First live target detected",optional:!0,state:$(es.hasAnyTarget),waitingFor:"your first terminal target"},judge:{id:"judge",label:"Judge validation engine",optional:!0,state:$(es.llmEngines!=null&&es.llmEngines.claude&&es.llmEngines.codex),command:"npm install -g @openai/codex",waitingFor:es.llmEngines==null?"a worker heartbeat reporting your installed engines":"a second LLM engine (claude + codex)",hint:"Optional — hand labels + one judge already give you calibrated verdicts. A second engine (e.g. the Codex CLI) unlocks cross-vendor judge validation: two vendors checking each other's blind spots."}},Kr=CORE_ORDER$1.every(Na=>cs[Na].state==="detected"),Xr=Kr?null:CORE_ORDER$1.find(Na=>cs[Na].state!=="detected")??null;return{steps:cs,coreComplete:Kr,currentStepId:Xr}}function useSetupProgress(es=3e4){var Xr,Na,Ca,Aa,Ia;const{session:$}=useAuth(),ts=useQuery({queryKey:["setup-status",es],queryFn:()=>apiGet("/api/setup/status"),refetchInterval:es}),is=useQuery({queryKey:["terminal-targets","all",es],queryFn:()=>apiGet("/api/terminal-targets"),refetchInterval:es}),cs=ts.isLoading||is.isLoading,Kr=((Xr=is.data)==null?void 0:Xr.targets)??[];return deriveSetupProgress({loading:cs,authenticated:!!$,cliEverConnected:((Na=ts.data)==null?void 0:Na.cliEverConnected)??!1,anyCapturedSession:((Ca=ts.data)==null?void 0:Ca.anyCapturedSession)??!1,workerHeartbeat:((Aa=ts.data)==null?void 0:Aa.workerActive)??!1,hasActiveTmux:Kr.some(Ma=>Ma.kind==="tmux"&&Ma.status==="active"),hasAnyTarget:Kr.length>0,llmEngines:((Ia=ts.data)==null?void 0:Ia.llmEngines)??null})}function track(es,$){}const CORE_STEP_IDS=["install","auth","hooks","worker"],DISMISSED_KEY="rm.setupWalkthrough.dismissed";function readDismissed(){try{return sessionStorage.getItem(DISMISSED_KEY)==="1"}catch{return!1}}function writeDismissed(){try{sessionStorage.setItem(DISMISSED_KEY,"1")}catch{}}const SetupWalkthroughContext=reactExports.createContext(null);function SetupWalkthroughProvider({children:es}){const{session:$}=useAuth(),ts=!!$,is=useQueryClient(),{profile:cs,isLoading:Kr}=useActiveOrg(),[Xr,Na]=reactExports.useState(!1),[Ca,Aa]=reactExports.useState("welcome"),[Ia,Ma]=reactExports.useState(readDismissed),Pa=(cs==null?void 0:cs.setupCompletedAt)!=null,La=useSetupProgress(Xr||!Pa?4e3:!1),Fa=reactExports.useRef(!1),Ba=reactExports.useRef(null),qa=reactExports.useRef(null),za=reactExports.useRef({}),Va=reactExports.useRef(new Set),Ga=reactExports.useRef(!1),Za=reactExports.useCallback(()=>{Na(!0)},[]),Qa=reactExports.useCallback(()=>{writeDismissed(),Ma(!0),Na(!1)},[Ca]),Xa=reactExports.useCallback(tl=>{Aa(tl)},[]);reactExports.useEffect(()=>{ts&&(Ia||Kr||La.steps.install.state==="loading"||(cs==null?void 0:cs.setupCompletedAt)==null&&(La.coreComplete||Na(!0)))},[ts,Ia,Kr,cs==null?void 0:cs.setupCompletedAt,La.coreComplete,La.steps.install.state]),reactExports.useEffect(()=>{const tl=Ba.current;if(Ba.current=La.coreComplete,!!ts&&La.coreComplete&&!Fa.current){if((cs==null?void 0:cs.setupCompletedAt)!=null){Fa.current=!0;return}tl===!1&&(Fa.current=!0,Ga.current||(Ga.current=!0),apiPatch("/api/profile",{setupCompletedAt:new Date().toISOString()}).then(()=>{is.invalidateQueries({queryKey:["profile"]})}).catch(()=>{}),Aa("payoff"))}},[ts,La.coreComplete,cs==null?void 0:cs.setupCompletedAt,is]),reactExports.useEffect(()=>{if(!Xr)return;const tl=`${Ca}::${La.currentStepId??""}`;qa.current!==tl&&(qa.current=tl,La.currentStepId,void 0)},[Xr,Ca,La.currentStepId]),reactExports.useEffect(()=>{const tl=Date.now();for(const sl of CORE_STEP_IDS){const ol=La.steps[sl].state;if(ol!=="loading")if(ol==="detected"){if(Va.current.has(sl))continue;Va.current.add(sl),za.current[sl]}else za.current[sl]==null&&(za.current[sl]=tl)}},[La.steps.install.state,La.steps.auth.state,La.steps.hooks.state,La.steps.worker.state]);const Ja={open:Xr,stage:Ca,progress:La,openModal:Za,dismiss:Qa,goTo:Xa,authenticated:ts};return reactExports.createElement(SetupWalkthroughContext.Provider,{value:Ja},es)}function useSetupWalkthrough(){const es=reactExports.useContext(SetupWalkthroughContext);if(!es)throw new Error("useSetupWalkthrough must be used within a SetupWalkthroughProvider");return es}function Dialog({...es}){return jsxRuntimeExports.jsx(Root$5,{"data-slot":"dialog",...es})}function DialogPortal({...es}){return jsxRuntimeExports.jsx(Portal$3,{"data-slot":"dialog-portal",...es})}function DialogOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"dialog-overlay",className:cn$1("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",es),...$})}function DialogContent({className:es,children:$,showCloseButton:ts=!0,...is}){return jsxRuntimeExports.jsxs(DialogPortal,{"data-slot":"dialog-portal",children:[jsxRuntimeExports.jsx(DialogOverlay,{}),jsxRuntimeExports.jsxs(Content$2,{"data-slot":"dialog-content",className:cn$1("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",es),...is,children:[$,ts&&jsxRuntimeExports.jsxs(Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 flex size-8 items-center justify-center rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[jsxRuntimeExports.jsx(X$1,{}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function DialogHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"dialog-header",className:cn$1("flex flex-col gap-2 text-center sm:text-left",es),...$})}function DialogFooter({className:es,showCloseButton:$=!1,children:ts,...is}){return jsxRuntimeExports.jsxs("div",{"data-slot":"dialog-footer",className:cn$1("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",es),...is,children:[ts,$&&jsxRuntimeExports.jsx(Close,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"outline",children:"Close"})})]})}function DialogTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"dialog-title",className:cn$1("text-lg leading-none font-semibold",es),...$})}function DialogDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"dialog-description",className:cn$1("text-muted-foreground text-sm",es),...$})}const badgeVariants=cva("inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"bg-primary text-primary-foreground [a&]:hover:bg-primary/90 [button&]:hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90 [button&]:hover:bg-secondary/90",destructive:"bg-destructive text-white [a&]:hover:bg-destructive/90 [button&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground [button&]:hover:bg-accent [button&]:hover:text-accent-foreground",ghost:"[a&]:hover:bg-accent [a&]:hover:text-accent-foreground [button&]:hover:bg-accent [button&]:hover:text-accent-foreground",link:"text-primary underline-offset-4 [a&]:hover:underline [button&]:hover:underline"}},defaultVariants:{variant:"default"}});function Badge({className:es,variant:$="default",asChild:ts=!1,...is}){const cs=ts?Slot$3:"span";return jsxRuntimeExports.jsx(cs,{"data-slot":"badge","data-variant":$,className:cn$1(badgeVariants({variant:$}),es),...is})}function CopyButton$5({text:es}){const[$,ts]=reactExports.useState(!1);async function is(){const cs=()=>{ts(!0),setTimeout(()=>ts(!1),2e3)};try{await navigator.clipboard.writeText(es),cs()}catch{try{const Kr=document.createElement("textarea");Kr.value=es,Kr.style.position="fixed",Kr.style.opacity="0",document.body.appendChild(Kr),Kr.select(),document.execCommand("copy"),document.body.removeChild(Kr),cs()}catch{}}}return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:is,className:"cursor-pointer",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Check,{className:"mr-1 h-3 w-3"}),"Copied"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Copy,{className:"mr-1 h-3 w-3"}),"Copy"]})})}const CC_SETUP_PROMPT=`Set up RuleMetric on this machine, agentically and transparently.
712
+ `),Ma=Ca;Ia.length>Ma;Ma++){var Pa=Ia[Ma];if(1024>=Pa.length){var La=de.test(Pa)?Pa.replace(de,"$1"):Pa;if(!La.match(/\S*Error: /)){for(var Fa of Kr){var Ba=Fa(La,is);if(Ba){Aa.push(Ba);break}}if(Aa.length>=50)break}}}return(function(qa){if(!qa.length)return[];var za=Array.from(qa);return za.reverse(),za.slice(0,50).map((Va=>{return f({},Va,{filename:Va.filename||(Ga=za,Ga[Ga.length-1]||{}).filename,function:Va.function||ee});var Ga}))})(Aa)}})("web:javascript",ae,he)),this._instance=es,this.fo=($=(ts=this._instance.persistence)==null?void 0:ts.get_property(Be))!==null&&$!==void 0?$:[],this.mo=ke(this.yo()),this.bo=new Re(this.mo)}onConfigChange(){this.mo=ke(this.yo()),this.bo.setConfig(this.mo)}onRemoteConfig(es){var $,ts,is;if("errorTracking"in es){var cs=($=(ts=es.errorTracking)==null?void 0:ts.suppressionRules)!==null&&$!==void 0?$:[],Kr=(is=es.errorTracking)==null?void 0:is.captureExtensionExceptions;this.fo=cs,this._instance.persistence&&this._instance.persistence.register({[Be]:this.fo,[He]:Kr})}}get _o(){var es,$=!!this._instance.get_property(He),ts=this._instance.config.error_tracking.captureExtensionExceptions;return(es=ts??$)!==null&&es!==void 0&&es}buildProperties(es,$){return this.po.buildFromUnknown(es,{syntheticException:$==null?void 0:$.syntheticException,mechanism:{handled:$==null?void 0:$.handled}})}addExceptionStep(es,$){if(this.mo.enabled)try{if(!F(es)||es.trim().length===0)return void ua.warn("Ignoring exception step because message must be a non-empty string");var ts=this.wo($),{sanitizedProperties:is,droppedKeys:cs}=(function(Kr){if(!Kr)return{sanitizedProperties:{},droppedKeys:[]};var Xr=[];return{sanitizedProperties:Object.keys(Kr).reduce(((Na,Ca)=>$e.has(Ca)?(Xr.push(Ca),Na):(Na[Ca]=Kr[Ca],Na)),{}),droppedKeys:Xr}})(ts);cs.length>0&&ua.warn("Ignoring reserved exception step fields",{droppedKeys:cs}),this.bo.add(f({[Ee]:es,[Se]:new Date().toISOString()},is))}catch(Kr){ua.error("Failed to add exception step. Ignoring breadcrumb.",Kr)}}sendExceptionEvent(es){try{var $=es.$exception_list;if(this.Io($)){if(this.Co($))return this.So("Exception dropped: matched a suppression rule"),void ua.info("Skipping exception capture because a suppression rule matched");if(!this._o&&this.xo($))return this.So("Exception dropped: thrown by a browser extension"),void ua.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ko($))return this.So("Exception dropped: thrown by the PostHog SDK"),void ua.info("Skipping exception capture because it was thrown by the PostHog SDK")}var ts=this.mo.enabled&&D(es.$exception_steps)?this.To(es):es;try{var is=this._instance.capture("$exception",ts,{_noTruncate:!0,_batchKey:"exceptionEvent",en:!0});return is&&this.bo.clear(),is}catch(cs){return ua.error("Failed to capture exception event. Dropping this exception.",cs),void this.bo.clear()}}catch(cs){return void ua.error("Failed to process exception event. Ignoring this exception.",cs)}}To(es){try{var $=this.bo.getAttachable();return $.length===0?es:f({},es,{$exception_steps:$})}catch(ts){return ua.error("Failed to read buffered exception steps. Capturing exception without steps.",ts),es}}So(es){this.mo.enabled&&this.bo.add({[Ee]:es,[Se]:new Date().toISOString()})}wo(es){return O(es)?f({},es):{}}yo(){var es,$;return(es=($=this._instance.config.error_tracking)==null?void 0:$.exception_steps)!==null&&es!==void 0?es:{}}Co(es){if(es.length===0)return!1;var $=es.reduce(((ts,is)=>{var{type:cs,value:Kr}=is;return F(cs)&&cs.length>0&&ts.$exception_types.push(cs),F(Kr)&&Kr.length>0&&ts.$exception_values.push(Kr),ts}),{$exception_types:[],$exception_values:[]});return this.fo.some((ts=>{var is=ts.values.map((cs=>{var Kr,Xr=_n[cs.operator],Na=R(cs.value)?cs.value:[cs.value],Ca=(Kr=$[cs.key])!==null&&Kr!==void 0?Kr:[];return Na.length>0&&Xr(Na,Ca)}));return ts.type==="OR"?is.some(Boolean):is.every(Boolean)}))}xo(es){return es.flatMap(($=>{var ts,is;return(ts=(is=$.stacktrace)==null?void 0:is.frames)!==null&&ts!==void 0?ts:[]})).some(($=>$.filename&&$.filename.startsWith("chrome-extension://")))}ko(es){if(es.length>0){var $,ts,is,cs,Kr=($=(ts=es[0].stacktrace)==null?void 0:ts.frames)!==null&&$!==void 0?$:[],Xr=Kr[Kr.length-1];return(is=Xr==null||(cs=Xr.filename)==null?void 0:cs.includes("posthog.com/static"))!==null&&is!==void 0&&is}return!1}Io(es){return!D(es)&&R(es)}}},ba=f({productTours:class{get ni(){return this._instance.persistence}constructor(es){this.Ao=null,this.Eo=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){"productTours"in es&&(this.ni&&this.ni.register({[We]:!!es.productTours}),this.loadIfEnabled())}loadIfEnabled(){var es,$;this.Ao||(es=this._instance).config.disable_product_tours||($=es.persistence)==null||!$.get_property(We)||this.ur((()=>this.Ro()))}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.generateProductTours?es():(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"product-tours",(is=>{is?Vo.error("Could not load product tours script",is):es()}))}Ro(){var es;!this.Ao&&(es=h.__PosthogExtensions__)!=null&&es.generateProductTours&&(this.Ao=h.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(es,$){if($===void 0&&($=!1),!R(this.Eo)||$){var ts=this.ni;if(ts){var is=ts.props[ci];if(R(is)&&!$)return this.Eo=is,void es(is,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:cs=>{var Kr=cs.statusCode;if(Kr!==200||!cs.json){var Xr="Product Tours API could not be loaded, status: "+Kr;return Vo.error(Xr),void es([],{isLoaded:!1,error:Xr})}var Na=R(cs.json.product_tours)?cs.json.product_tours:[];this.Eo=Na,ts&&ts.register({[ci]:Na}),es(Na,{isLoaded:!0})}})}else es(this.Eo,{isLoaded:!0})}getActiveProductTours(es){D(this.Ao)?es([],{isLoaded:!1,error:"Product tours not loaded"}):this.Ao.getActiveProductTours(es)}showProductTour(es){var $;($=this.Ao)==null||$.showTourById(es)}previewTour(es){this.Ao?this.Ao.previewTour(es):this.ur((()=>{var $;this.Ro(),($=this.Ao)==null||$.previewTour(es)}))}dismissProductTour(){var es;(es=this.Ao)==null||es.dismissTour("user_clicked_skip")}nextStep(){var es;(es=this.Ao)==null||es.nextStep()}previousStep(){var es;(es=this.Ao)==null||es.previousStep()}clearCache(){var es;this.Eo=null,(es=this.ni)==null||es.unregister(ci)}resetTour(es){var $;($=this.Ao)==null||$.resetTour(es)}resetAllTours(){var es;(es=this.Ao)==null||es.resetAllTours()}cancelPendingTour(es){var $;($=this.Ao)==null||$.cancelPendingTour(es)}}},fa),ya={siteApps:class{constructor(es){this._instance=es,this.No=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Mo(es,$){if($){var ts=this.globalsForEvent($);this.No.push(ts),this.No.length>1e3&&(this.No=this.No.slice(10))}}get siteAppLoaders(){var es;return(es=h._POSTHOG_REMOTE_CONFIG)==null||(es=es[this._instance.config.token])==null?void 0:es.siteApps}initialize(){if(this.isEnabled){var es=this._instance._addCaptureHook(this.Mo.bind(this));this.Fo=()=>{es(),this.No=[],this.Fo=void 0}}}globalsForEvent(es){var $,ts,is,cs,Kr,Xr,Na;if(!es)throw new Error("Event payload is required");var Ca={},Aa=this._instance.get_property("$groups")||[],Ia=this._instance.get_property("$stored_group_properties")||{};for(var[Ma,Pa]of Object.entries(Ia))Ca[Ma]={id:Aa[Ma],type:Ma,properties:Pa};var{$set_once:La,$set:Fa}=es;return{event:f({},_(es,Wo),{properties:f({},es.properties,Fa?{$set:f({},($=(ts=es.properties)==null?void 0:ts.$set)!==null&&$!==void 0?$:{},Fa)}:{},La?{$set_once:f({},(is=(cs=es.properties)==null?void 0:cs.$set_once)!==null&&is!==void 0?is:{},La)}:{}),elements_chain:(Kr=(Xr=es.properties)==null?void 0:Xr.$elements_chain)!==null&&Kr!==void 0?Kr:"",distinct_id:(Na=es.properties)==null?void 0:Na.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:Ca}}setupSiteApp(es){var $=this.apps[es.id],ts=()=>{var Xr;!$.errored&&this.No.length&&(Go.info("Processing "+this.No.length+" events for site app with id "+es.id),this.No.forEach((Na=>$.processEvent==null?void 0:$.processEvent(Na))),$.processedBuffer=!0),Object.values(this.apps).every((Na=>Na.processedBuffer||Na.errored))&&((Xr=this.Fo)==null||Xr.call(this))},is=!1,cs=Xr=>{$.errored=!Xr,$.loaded=!0,Go.info("Site app with id "+es.id+" "+(Xr?"loaded":"errored")),is&&ts()};try{var{processEvent:Kr}=es.init({posthog:this._instance,callback(Xr){cs(Xr)}});Kr&&($.processEvent=Kr),is=!0}catch(Xr){Go.error(Yo+es.id,Xr),cs(!1)}if(is&&$.loaded)try{ts()}catch(Xr){Go.error("Error while processing buffered events PostHog app with config id "+es.id,Xr),$.errored=!0}}Oo(){var es=this.siteAppLoaders||[];for(var $ of es)this.apps[$.id]={id:$.id,loaded:!1,errored:!1,processedBuffer:!1};for(var ts of es)this.setupSiteApp(ts)}Po(es){if(Object.keys(this.apps).length!==0){var $=this.globalsForEvent(es);for(var ts of Object.values(this.apps))try{ts.processEvent==null||ts.processEvent($)}catch(is){Go.error("Error while processing event "+es.event+" for site app "+ts.id,is)}}}onRemoteConfig(es){var $,ts,is,cs=this;if(($=this.siteAppLoaders)!=null&&$.length)return this.isEnabled?(this.Oo(),void this._instance.on("eventCaptured",(Ca=>this.Po(Ca)))):void Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((ts=this.Fo)==null||ts.call(this),(is=es.siteApps)!=null&&is.length)if(this.isEnabled){var Kr=function(Ca){var Aa;h["__$$ph_site_app_"+Ca]=cs._instance,(Aa=h.__PosthogExtensions__)==null||Aa.loadSiteApp==null||Aa.loadSiteApp(cs._instance,Na,(Ia=>{if(Ia)return Go.error(Yo+Ca,Ia)}))};for(var{id:Xr,url:Na}of es.siteApps)Kr(Xr)}else Go.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}},wa={tracingHeaders:class{constructor(es){this.Lo=void 0,this.Do=void 0,this.so=()=>{var $,ts,is=this.Bo()||[];C(this.Lo)&&(($=h.__PosthogExtensions__)==null||($=$.tracingHeadersPatchFns)==null||$._patchXHR(is,this._instance.get_distinct_id(),this._instance.sessionManager)),C(this.Do)&&((ts=h.__PosthogExtensions__)==null||(ts=ts.tracingHeadersPatchFns)==null||ts._patchFetch(is,this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=es}initialize(){this.startIfEnabledOrStop()}ur(es){var $,ts;($=h.__PosthogExtensions__)!=null&&$.tracingHeadersPatchFns&&es(),(ts=h.__PosthogExtensions__)==null||ts.loadExternalDependency==null||ts.loadExternalDependency(this._instance,"tracing-headers",(is=>{if(is)return Ao.error("failed to load script",is);es()}))}Bo(){var es;return(es=this._instance.config.addTracingHeaders)!==null&&es!==void 0?es:this._instance.config.__add_tracing_headers}startIfEnabledOrStop(){var es,$;this.Bo()?this.ur(this.so):((es=this.Lo)==null||es.call(this),($=this.Do)==null||$.call(this),this.Lo=void 0,this.Do=void 0)}}},xa=f({surveys:class{get Bt(){return this._instance.config}constructor(es){this.jo=void 0,this._surveyManager=null,this.$o=!1,this.qo=[],this.Zo=null,this._instance=es,this._surveyEventReceiver=null}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this.Bt.disable_surveys){var $=es.surveys;if(D($))return En.warn("Flags not loaded yet. Not loading surveys.");var ts=R($);this.jo=ts?$.length>0:$,En.info("flags response received, isSurveysEnabled: "+this.jo),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var es=[],$=0;$<localStorage.length;$++){var ts=localStorage.key($);(ts!=null&&ts.startsWith(Sn)||ts!=null&&ts.startsWith("inProgressSurvey_"))&&es.push(ts)}es.forEach((is=>localStorage.removeItem(is)))}loadIfEnabled(){if(!this._surveyManager)if(this.$o)En.info("Already initializing surveys, skipping...");else if(this.Bt.disable_surveys)En.info(ta);else if(this.Bt.cookieless_mode&&this._instance.consent.isOptedOut())En.info("Not loading surveys in cookieless mode without consent.");else{var es=h==null?void 0:h.__PosthogExtensions__;if(es){if(!C(this.jo)||this.Bt.advanced_enable_surveys){var $=this.jo||this.Bt.advanced_enable_surveys;this.$o=!0;try{var ts=es.generateSurveys;if(ts)return void this.Vo(ts,$);var is=es.loadExternalDependency;if(!is)return void this.Ho(Oi);is(this._instance,"surveys",(cs=>{cs||!es.generateSurveys?this.Ho("Could not load surveys script",cs):this.Vo(es.generateSurveys,$)}))}catch(cs){throw this.Ho("Error initializing surveys",cs),cs}finally{this.$o=!1}}}else En.error("PostHog Extensions not found.")}}Vo(es,$){this._surveyManager=es(this._instance,$),this._surveyEventReceiver=new Qo(this._instance),En.info("Surveys loaded successfully"),this.zo({isLoaded:!0})}Ho(es,$){En.error(es,$),this.zo({isLoaded:!1,error:es})}onSurveysLoaded(es){return this.qo.push(es),this._surveyManager&&this.zo({isLoaded:!0}),()=>{this.qo=this.qo.filter(($=>$!==es))}}getSurveys(es,$){if($===void 0&&($=!1),this.Bt.disable_surveys)return En.info(ta),es([]);var ts,is=this._instance.get_property(di);if(is&&!$)return es(is,{isLoaded:!0});typeof Promise<"u"&&this.Zo?this.Zo.then((cs=>{var{surveys:Kr,context:Xr}=cs;return es(Kr,Xr)})):(typeof Promise<"u"&&(this.Zo=new Promise((cs=>{ts=cs}))),this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this.Bt.token),method:"GET",timeout:this.Bt.surveys_request_timeout_ms,callback:cs=>{var Kr;this.Zo=null;var Xr=cs.statusCode;if(Xr!==200||!cs.json){var Na="Surveys API could not be loaded, status: "+Xr;En.error(Na);var Ca={isLoaded:!1,error:Na};return es([],Ca),void(ts==null||ts({surveys:[],context:Ca}))}var Aa,Ia=cs.json.surveys||[],Ma=Ia.filter((La=>(function(Fa){return!(!Fa.start_date||Fa.end_date)})(La)&&((function(Fa){var Ba;return!((Ba=Fa.conditions)==null||(Ba=Ba.events)==null||(Ba=Ba.values)==null||!Ba.length)})(La)||(function(Fa){var Ba;return!((Ba=Fa.conditions)==null||(Ba=Ba.actions)==null||(Ba=Ba.values)==null||!Ba.length)})(La))));Ma.length>0&&((Aa=this._surveyEventReceiver)==null||Aa.register(Ma)),(Kr=this._instance.persistence)==null||Kr.register({[di]:Ia});var Pa={isLoaded:!0};es(Ia,Pa),ts==null||ts({surveys:Ia,context:Pa})}}))}zo(es){for(var $ of this.qo)try{if(!es.isLoaded)return $([],es);this.getSurveys($)}catch(ts){En.error("Error in survey callback",ts)}}getActiveMatchingSurveys(es,$){if($===void 0&&($=!1),!D(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(es,$);En.warn("init was not called")}Uo(es){var $=null;return this.getSurveys((ts=>{var is;$=(is=ts.find((cs=>cs.id===es)))!==null&&is!==void 0?is:null})),$}Yo(es){if(D(this._surveyManager))return{eligible:!1,reason:Zo};var $=typeof es=="string"?this.Uo(es):es;return $?this._surveyManager.checkSurveyEligibility($):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(es){if(D(this._surveyManager))return En.warn("init was not called"),{visible:!1,disabledReason:Zo};var $=this.Yo(es);return{visible:$.eligible,disabledReason:$.reason}}canRenderSurveyAsync(es,$){return D(this._surveyManager)?(En.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:Zo})):new Promise((ts=>{this.getSurveys((is=>{var cs,Kr=(cs=is.find((Na=>Na.id===es)))!==null&&cs!==void 0?cs:null;if(Kr){var Xr=this.Yo(Kr);ts({visible:Xr.eligible,disabledReason:Xr.reason})}else ts({visible:!1,disabledReason:"Survey not found"})}),$)}))}renderSurvey(es,$,ts){var is;if(D(this._surveyManager))En.warn("init was not called");else{var cs=typeof es=="string"?this.Uo(es):es;if(cs!=null&&cs.id)if($n.includes(cs.type)){var Kr=r==null?void 0:r.querySelector($);if(Kr)return(is=cs.appearance)!=null&&is.surveyPopupDelaySeconds?(En.info("Rendering survey "+cs.id+" with delay of "+cs.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var Xr,Na;En.info("Rendering survey "+cs.id+" with delay of "+((Xr=cs.appearance)==null?void 0:Xr.surveyPopupDelaySeconds)+" seconds"),(Na=this._surveyManager)==null||Na.renderSurvey(cs,Kr,ts),En.info("Survey "+cs.id+" rendered")}),1e3*cs.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(cs,Kr,ts);En.warn("Survey element not found")}else En.warn("Surveys of type "+cs.type+" cannot be rendered in the app");else En.warn("Survey not found")}}displaySurvey(es,$){var ts;if(D(this._surveyManager))En.warn("init was not called");else{var is=this.Uo(es);if(is){var cs=is;if((ts=is.appearance)!=null&&ts.surveyPopupDelaySeconds&&$.ignoreDelay&&(cs=f({},is,{appearance:f({},is.appearance,{surveyPopupDelaySeconds:0})})),$.displayType!==ns.Popover&&$.initialResponses&&En.warn("initialResponses is only supported for popover surveys. prefill will not be applied."),$.ignoreConditions===!1){var Kr=this.canRenderSurvey(is);if(!Kr.visible)return void En.warn("Survey is not eligible to be displayed: ",Kr.disabledReason)}$.displayType!==ns.Inline?this._surveyManager.handlePopoverSurvey(cs,$):this.renderSurvey(cs,$.selector,$.properties)}else En.warn("Survey not found")}}cancelPendingSurvey(es){D(this._surveyManager)?En.warn("init was not called"):this._surveyManager.cancelSurvey(es)}handlePageUnload(){var es;(es=this._surveyManager)==null||es.handlePageUnload()}}},fa),Ea={toolbar:class{constructor(es){this.instance=es}Go(es){h.ph_toolbar_state=es}Wo(){var es;return(es=h.ph_toolbar_state)!==null&&es!==void 0?es:0}initialize(){return this.maybeLoadToolbar()}maybeLoadToolbar(es,$,ts){if(es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),Qi(this.instance.config)||!t||!r)return!1;es=es??t.location,ts=ts??t.history;try{if(!$){try{t.localStorage.setItem("test","test"),t.localStorage.removeItem("test")}catch{return!1}$=t==null?void 0:t.localStorage}var is,cs=ea||Ir(es.hash,"__posthog")||Ir(es.hash,"state"),Kr=cs?Wi((()=>JSON.parse(atob(decodeURIComponent(cs)))))||Wi((()=>JSON.parse(decodeURIComponent(cs)))):null;return Kr&&Kr.action==="ph_authorize"?((is=Kr).source="url",is&&Object.keys(is).length>0&&(Kr.desiredHash?es.hash=Kr.desiredHash:ts?ts.replaceState(ts.state,"",es.pathname+es.search):es.hash="")):((is=JSON.parse($.getItem(ia)||"{}")).source="localstorage",delete is.userIntent),!(!is.token||this.instance.config.token!==is.token||(this.loadToolbar(is),0))}catch{return!1}}Xo(es){var $=h.ph_load_toolbar||h.ph_load_editor;!D($)&&P($)?$(es,this.instance):ra.warn("No toolbar load function found")}loadToolbar(es){var $=!(r==null||!r.getElementById($i));if(!t||$)return!1;var ts=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,is=f({token:this.instance.config.token},es,{apiURL:this.instance.requestRouter.endpointFor("ui")},ts?{instrument:!1}:{});if(t.localStorage.setItem(ia,JSON.stringify(f({},is,{source:void 0}))),this.Wo()===2)this.Xo(is);else if(this.Wo()===0){var cs;this.Go(1),(cs=h.__PosthogExtensions__)==null||cs.loadExternalDependency==null||cs.loadExternalDependency(this.instance,"toolbar",(Kr=>{if(Kr)return ra.error("[Toolbar] Failed to load",Kr),void this.Go(0);this.Go(2),this.Xo(is)})),Xi(t,"turbolinks:load",(()=>{this.Go(0),this.loadToolbar(is)}))}return!0}Jo(es){return this.loadToolbar(es)}maybeLoadEditor(es,$,ts){return es===void 0&&(es=void 0),$===void 0&&($=void 0),ts===void 0&&(ts=void 0),this.maybeLoadToolbar(es,$,ts)}}},Sa=f({experiments:va},fa),$a={conversations:class{constructor(es){this.Ko=void 0,this._conversationsManager=null,this.Qo=!1,this.ea=null,this._instance=es}initialize(){this.loadIfEnabled()}onRemoteConfig(es){if(!this._instance.config.disable_conversations){var $=es.conversations;D($)||(N($)?this.Ko=$:(this.Ko=$.enabled,this.ea=$),this.loadIfEnabled())}}reset(){var es;(es=this._conversationsManager)==null||es.reset(),this._conversationsManager=null,this.Ko=void 0,this.ea=null}loadIfEnabled(){if(!(this._conversationsManager||this.Qo||this._instance.config.disable_conversations||Qi(this._instance.config)||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var es=h==null?void 0:h.__PosthogExtensions__;if(es&&!C(this.Ko)&&this.Ko)if(this.ea&&this.ea.token){this.Qo=!0;try{var $=es.initConversations;if($)return this.ta($),void(this.Qo=!1);var ts=es.loadExternalDependency;if(!ts)return void this.ra(Oi);ts(this._instance,"conversations",(is=>{is||!es.initConversations?this.ra("Could not load conversations script",is):this.ta(es.initConversations),this.Qo=!1}))}catch(is){this.ra("Error initializing conversations",is),this.Qo=!1}}else ca.error("Conversations enabled but missing token in remote config.")}}ta(es){if(this.ea)try{this._conversationsManager=es(this.ea,this._instance),ca.info("Conversations loaded successfully")}catch($){this.ra("Error completing conversations initialization",$)}else ca.error("Cannot complete initialization: remote config is null")}ra(es,$){ca.error(es,$),this._conversationsManager=null,this.Qo=!1}show(){this._conversationsManager?this._conversationsManager.show():ca.warn("Conversations not loaded yet.")}hide(){this._conversationsManager&&this._conversationsManager.hide()}isAvailable(){return this.Ko===!0&&!M(this._conversationsManager)}isVisible(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.isVisible())!==null&&es!==void 0&&es}sendMessage(es,$,ts){var is=this;return p((function*(){return is._conversationsManager?is._conversationsManager.sendMessage(es,$,ts):(ca.warn(pa),null)}))()}getMessages(es,$){var ts=this;return p((function*(){return ts._conversationsManager?ts._conversationsManager.getMessages(es,$):(ca.warn(pa),null)}))()}markAsRead(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.markAsRead(es):(ca.warn(pa),null)}))()}getTickets(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.getTickets(es):(ca.warn(pa),null)}))()}requestRestoreLink(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.requestRestoreLink(es):(ca.warn(pa),null)}))()}restoreFromToken(es){var $=this;return p((function*(){return $._conversationsManager?$._conversationsManager.restoreFromToken(es):(ca.warn(pa),null)}))()}restoreFromUrlToken(){var es=this;return p((function*(){return es._conversationsManager?es._conversationsManager.restoreFromUrlToken():(ca.warn(pa),null)}))()}getCurrentTicketId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getCurrentTicketId())!==null&&es!==void 0?es:null}getWidgetSessionId(){var es,$;return(es=($=this._conversationsManager)==null?void 0:$.getWidgetSessionId())!==null&&es!==void 0?es:null}un(){var es;(es=this._conversationsManager)==null||es.setIdentity()}hn(){var es;(es=this._conversationsManager)==null||es.clearIdentity()}}},Ta={logs:class{constructor(es){var $;this.ia=!1,this.na=!1,this.Gt=Ce("[logs]"),this.sa=[],this.oa=0,this.aa=0,this.la=!1,this._instance=es,this._instance&&($=this._instance.config.logs)!=null&&$.captureConsoleLogs&&(this.ia=!0)}initialize(){this.loadIfEnabled()}onRemoteConfig(es){var $,ts=($=es.logs)==null?void 0:$.captureConsoleLogs;!D(ts)&&ts&&(this.ia=!0,this.loadIfEnabled())}reset(){this.sa=[],this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.oa=0,this.aa=0,this.la=!1}loadIfEnabled(){if(this.ia&&!this.na){var es=h==null?void 0:h.__PosthogExtensions__;if(es){var $=es.loadExternalDependency;$?$(this._instance,"logs",(ts=>{var is;ts||(is=es.logs)==null||!is.initializeLogs?this.Gt.error("Could not load logs script",ts):(es.logs.initializeLogs(this._instance),this.na=!0)})):this.Gt.error(Oi)}else this.Gt.error("PostHog Extensions not found.")}}captureLog(es){var $,ts,is,cs,Kr,Xr;if(this._instance.is_capturing())if(es&&es.body){var Na=($=(ts=this._instance.config.logs)==null?void 0:ts.flushIntervalMs)!==null&&$!==void 0?$:3e3,Ca=(is=(cs=this._instance.config.logs)==null?void 0:cs.maxLogsPerInterval)!==null&&is!==void 0?is:1e3,Aa=Date.now();if(Na>Aa-this.aa||(this.aa=Aa,this.oa=0,this.la=!1),Ca>this.oa){this.oa++;var Ia=(function(Ma,Pa){var La=Ma.level||"info",{text:Fa,number:Ba}=Jt[La]||Kt,qa=String(Date.now())+"000000",za={};Pa.distinctId&&(za.posthogDistinctId=Pa.distinctId),Pa.sessionId&&(za.sessionId=Pa.sessionId),Pa.currentUrl&&(za["url.full"]=Pa.currentUrl),Pa.screenName&&(za["screen.name"]=Pa.screenName),Pa.appState&&(za["app.state"]=Pa.appState),Pa.activeFeatureFlags&&Pa.activeFeatureFlags.length>0&&(za.feature_flags=Pa.activeFeatureFlags);var Va=f({},za,Ma.attributes||{}),Ga={timeUnixNano:qa,observedTimeUnixNano:qa,severityNumber:Ba,severityText:Fa,body:{stringValue:Ma.body},attributes:Qt(Va)};return Ma.trace_id&&(Ga.traceId=Ma.trace_id),Ma.span_id&&(Ga.spanId=Ma.span_id),C(Ma.trace_flags)||(Ga.flags=Ma.trace_flags),Ga})(es,this.ua());this.sa.push({record:Ia}),((Kr=(Xr=this._instance.config.logs)==null?void 0:Xr.maxBufferSize)!==null&&Kr!==void 0?Kr:100)>this.sa.length?this.ha():this.flushLogs()}else this.la||(this.Gt.warn("captureLog dropping logs: exceeded "+Ca+" logs per "+Na+"ms"),this.la=!0)}else this.Gt.warn("captureLog requires a body")}get logger(){return this.ca||(this.ca={trace:(es,$)=>this.captureLog({body:es,level:"trace",attributes:$}),debug:(es,$)=>this.captureLog({body:es,level:"debug",attributes:$}),info:(es,$)=>this.captureLog({body:es,level:"info",attributes:$}),warn:(es,$)=>this.captureLog({body:es,level:"warn",attributes:$}),error:(es,$)=>this.captureLog({body:es,level:"error",attributes:$}),fatal:(es,$)=>this.captureLog({body:es,level:"fatal",attributes:$})}),this.ca}flushLogs(es){if(this.jr&&(clearTimeout(this.jr),this.jr=void 0),this.sa.length!==0){var $=this.sa;this.sa=[];var ts=this._instance.config.logs,is=f({"service.name":(ts==null?void 0:ts.serviceName)||"unknown_service"},(ts==null?void 0:ts.environment)&&{"deployment.environment":ts.environment},(ts==null?void 0:ts.serviceVersion)&&{"service.version":ts.serviceVersion},ts==null?void 0:ts.resourceAttributes),cs=(function(Xr,Na,Ca,Aa){return{resourceLogs:[{resource:{attributes:Qt(Na)},scopeLogs:[{scope:{name:Ca,version:Aa},logRecords:Xr}]}]}})($.map((Xr=>Xr.record)),is,v.LIB_NAME,v.LIB_VERSION),Kr=this._instance.requestRouter.endpointFor("api","/i/v1/logs")+"?token="+encodeURIComponent(this._instance.config.token);this._instance.Vi({method:"POST",url:Kr,data:cs,compression:"best-available",batchKey:"logs",transport:es})}}ha(){var es,$;this.jr||(this.jr=setTimeout((()=>{this.jr=void 0,this.flushLogs()}),(es=($=this._instance.config.logs)==null?void 0:$.flushIntervalMs)!==null&&es!==void 0?es:3e3))}ua(){var es,$={};if($.distinctId=this._instance.get_distinct_id(),this._instance.sessionManager){var{sessionId:ts}=this._instance.sessionManager.checkAndGetSessionAndWindowId(!0);$.sessionId=ts}if(h!=null&&(es=h.location)!=null&&es.href&&($.currentUrl=h.location.href),this._instance.featureFlags){var is=this._instance.featureFlags.getFlags();is&&is.length>0&&($.activeFeatureFlags=is)}return $}}},ka=f({},fa,_a,ga,ma,ba,ya,xa,wa,Ea,Sa,$a,Ta);qn.__defaultExtensionClasses=f({},ka);var Ra;Ra=In[Un]=new qn,(function(){function es(){es.done||(es.done=!0,Nn=!1,Hi(In,(function($){$._dom_loaded()})))}r!=null&&r.addEventListener?r.readyState==="complete"?es():Xi(r,"DOMContentLoaded",es,{capture:!1}):t&&Ie.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})();function PostHogProvider({children:es}){const{user:$}=useAuth(),ts=useLocation();return reactExports.useRef(null),reactExports.useEffect(()=>{},[]),reactExports.useEffect(()=>{},[$]),reactExports.useEffect(()=>{},[ts.pathname]),jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es})}function Separator({className:es,orientation:$="horizontal",decorative:ts=!0,...is}){return jsxRuntimeExports.jsx(Root,{"data-slot":"separator",decorative:ts,orientation:$,className:cn$1("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",es),...is})}function usePendingSuggestionCount(){return useQuery({queryKey:["instruction-suggestions","pending-count"],queryFn:()=>apiGet("/api/instruction-suggestions/pending-count"),staleTime:300*1e3})}function useProjectPaths(){return useQuery({queryKey:["sessions","project-paths"],queryFn:()=>apiGet("/api/sessions/project-paths?limit=20"),select:es=>es.projectPaths})}function useSuggestionsForProjects(es){return useQueries({queries:es.map($=>({queryKey:["instruction-suggestions",$],queryFn:()=>apiGet(`/api/instruction-suggestions?projectPath=${encodeURIComponent($)}&limit=10&groupByKind=true`).then(ts=>({projectPath:$,suggestions:ts.suggestions}))}))})}function useSuggestionImpacts(es){const $=[...new Set(es)].sort().join(",");return useQuery({queryKey:["insights","suggestion-impact",$],queryFn:()=>apiGet(`/api/insights/suggestion-impact?instructionIds=${encodeURIComponent($)}`),select:ts=>ts.impacts,enabled:$.length>0})}function useLogSuggestionEvent(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instruction-suggestions/${$.suggestionId}/events`,{eventType:$.eventType,projectPath:$.projectPath,tool:$.tool}),onSuccess:()=>{es.invalidateQueries({queryKey:["instruction-suggestions"]})}})}function usePromoteFromPublic(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instructions/${$.sourceInstructionId}/promote-from-public`,{targetScope:$.targetScope,targetScopeRef:$.targetScopeRef,name:$.name}),onSuccess:()=>{es.invalidateQueries({queryKey:["instructions"]}),es.invalidateQueries({queryKey:["catalog"]})}})}const PUBLIC_PAGE_SIZE=50;function usePublicCatalog(es){return useInfiniteQuery({queryKey:["catalog","public",es??""],initialPageParam:0,queryFn:({pageParam:$})=>{const ts=new URLSearchParams({scope:"public",limit:String(PUBLIC_PAGE_SIZE),offset:String($)});return es&&ts.set("search",es),apiGet(`/api/catalog?${ts.toString()}`)},getNextPageParam:($,ts)=>{if(!($.length<PUBLIC_PAGE_SIZE))return ts.length*PUBLIC_PAGE_SIZE}})}function useWorkerStatus(es){const $=useQuery({queryKey:["worker-status"],queryFn:()=>apiGet("/api/workers/status"),refetchInterval:3e4}),ts=$.data??[],is=es?ts.filter(Kr=>Kr.workerType===es):ts,cs=is.filter(Kr=>Kr.status==="active");return{...$,workers:is,activeWorkers:cs,isConnected:cs.length>0,workerCount:cs.length}}function formatRelativeTime$2(es){const $=Date.now()-new Date(es).getTime(),ts=Math.floor($/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}const typeLabels={mcp:"MCP","cli-worker":"CLI Worker",gateway:"Gateway",proxy:"Proxy"};function WorkerStatus(){const{workers:es,activeWorkers:$,isConnected:ts,isLoading:is}=useWorkerStatus();return is||es.length===0?jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full shrink-0 bg-muted-foreground/30"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"No workers connected"})]})}):jsxRuntimeExports.jsx("div",{className:"px-2 py-2",children:jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border px-3 py-2 text-xs space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:cn$1("h-2 w-2 rounded-full shrink-0",ts?"bg-teal-500":"bg-amber-500")}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:ts?`${$.length} worker${$.length>1?"s":""} online`:"Workers offline"})]}),es.map(cs=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground pl-4",children:[jsxRuntimeExports.jsx("span",{children:typeLabels[cs.workerType]??cs.workerType}),jsxRuntimeExports.jsx("span",{children:cs.status==="active"?formatRelativeTime$2(cs.lastHeartbeat):"offline"})]},cs.id))]})})}const navItems=[{to:"/dashboard",label:"Dashboard",icon:LayoutDashboard},{to:"/connect",label:"Connect",icon:Plug},{to:"/sessions",label:"Sessions",icon:Activity},{to:"/projects",label:"Projects",icon:Layers},{to:"/eval-targets",label:"Evals",icon:FlaskConical},{to:"/insights",label:"Insights",icon:TrendingUp},{to:"/memories",label:"Memories",icon:Brain},{to:"/usage",label:"Usage",icon:DollarSign},{to:"/skills",label:"Skills",icon:Sparkles},{to:"/catalog/public",label:"Public Catalog",icon:Globe},{to:"/suggestions",label:"Suggestions",icon:Lightbulb},{to:"/docs",label:"Docs",icon:BookOpen}];function Sidebar({className:es}){const $=useLocation(),{profile:ts}=useActiveOrg(),{data:is}=usePendingSuggestionCount();return jsxRuntimeExports.jsxs("aside",{className:cn$1("flex h-full w-60 flex-col border-r border-border bg-background p-4",es),children:[jsxRuntimeExports.jsxs("div",{className:"mb-6 flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("h1",{className:"font-mono text-lg font-semibold tracking-tight",children:"RuleMetric"})]}),jsxRuntimeExports.jsx("nav",{className:"flex flex-col gap-1",children:navItems.map(cs=>{const Kr=$.pathname.startsWith(cs.to);return jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",Kr&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:cs.to,children:[jsxRuntimeExports.jsx(cs.icon,{className:cn$1("mr-2 h-4 w-4",Kr&&"text-primary")}),cs.label,cs.to==="/suggestions"&&((is==null?void 0:is.total)??0)>0&&jsxRuntimeExports.jsx("span",{className:"ml-auto rounded-full bg-primary/15 px-2 py-0.5 font-mono text-xs text-primary",children:is.total>99?"99+":is.total})]})},cs.to)})}),(ts==null?void 0:ts.isSuperadmin)&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Separator,{className:"my-4"}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/superadmin")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/superadmin/users",children:[jsxRuntimeExports.jsx(Shield,{className:"mr-2 h-4 w-4"}),"Superadmin"]})}),jsxRuntimeExports.jsx(Button,{variant:"ghost",className:cn$1("justify-start cursor-pointer transition-colors duration-200",$.pathname.startsWith("/admin/announcements")&&"bg-secondary text-primary"),asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/admin/announcements",children:[jsxRuntimeExports.jsx(Megaphone,{className:"mr-2 h-4 w-4"}),"Announcements"]})})]}),jsxRuntimeExports.jsx(Separator,{className:"my-4"}),jsxRuntimeExports.jsx("div",{className:"flex flex-col gap-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"justify-start cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/import",children:[jsxRuntimeExports.jsx(Upload,{className:"mr-2 h-4 w-4"}),"Import"]})})}),jsxRuntimeExports.jsx("div",{className:"mt-auto",children:jsxRuntimeExports.jsx(WorkerStatus,{})})]})}function DropdownMenu({...es}){return jsxRuntimeExports.jsx(Root2$2,{"data-slot":"dropdown-menu",...es})}function DropdownMenuTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$3,{"data-slot":"dropdown-menu-trigger",...es})}function DropdownMenuContent({className:es,sideOffset:$=4,...ts}){return jsxRuntimeExports.jsx(Portal2,{children:jsxRuntimeExports.jsx(Content2$2,{"data-slot":"dropdown-menu-content",sideOffset:$,className:cn$1("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",es),...ts})})}function DropdownMenuItem({className:es,inset:$,variant:ts="default",...is}){return jsxRuntimeExports.jsx(Item2,{"data-slot":"dropdown-menu-item","data-inset":$,"data-variant":ts,className:cn$1("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",es),...is})}function DropdownMenuLabel({className:es,inset:$,...ts}){return jsxRuntimeExports.jsx(Label2,{"data-slot":"dropdown-menu-label","data-inset":$,className:cn$1("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",es),...ts})}function DropdownMenuSeparator({className:es,...$}){return jsxRuntimeExports.jsx(Separator2,{"data-slot":"dropdown-menu-separator",className:cn$1("bg-border -mx-1 my-1 h-px",es),...$})}function Avatar({className:es,size:$="default",...ts}){return jsxRuntimeExports.jsx(Root$4,{"data-slot":"avatar","data-size":$,className:cn$1("group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",es),...ts})}function AvatarFallback({className:es,...$}){return jsxRuntimeExports.jsx(Fallback,{"data-slot":"avatar-fallback",className:cn$1("bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",es),...$})}function Sheet({...es}){return jsxRuntimeExports.jsx(Root$5,{"data-slot":"sheet",...es})}function SheetTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$4,{"data-slot":"sheet-trigger",...es})}function SheetPortal({...es}){return jsxRuntimeExports.jsx(Portal$3,{"data-slot":"sheet-portal",...es})}function SheetOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"sheet-overlay",className:cn$1("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",es),...$})}function SheetContent({className:es,children:$,side:ts="right",showCloseButton:is=!0,...cs}){return jsxRuntimeExports.jsxs(SheetPortal,{children:[jsxRuntimeExports.jsx(SheetOverlay,{}),jsxRuntimeExports.jsxs(Content$2,{"data-slot":"sheet-content",className:cn$1("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",ts==="right"&&"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",ts==="left"&&"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",ts==="top"&&"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",ts==="bottom"&&"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",es),...cs,children:[$,is&&jsxRuntimeExports.jsxs(Close,{className:"ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none",children:[jsxRuntimeExports.jsx(X$1,{className:"size-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function SheetHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"sheet-header",className:cn$1("flex flex-col gap-1.5 p-4",es),...$})}function SheetTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"sheet-title",className:cn$1("text-foreground font-semibold",es),...$})}function SheetDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"sheet-description",className:cn$1("text-muted-foreground text-sm",es),...$})}const NOTIFICATIONS_QUERY_KEY=["notifications"];function useNotifications(){var Kr,Xr;const es=useQueryClient(),{user:$}=useAuth(),ts=useQuery({queryKey:NOTIFICATIONS_QUERY_KEY,queryFn:()=>apiGet("/api/notifications?limit=20"),enabled:!!$}),is=useMutation({mutationFn:Na=>apiPost(`/api/notifications/${Na}/read`,{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})}),cs=useMutation({mutationFn:()=>apiPost("/api/notifications/read-all",{}),onSuccess:()=>es.invalidateQueries({queryKey:NOTIFICATIONS_QUERY_KEY})});return{items:((Kr=ts.data)==null?void 0:Kr.items)??[],unreadCount:((Xr=ts.data)==null?void 0:Xr.unreadCount)??0,isLoading:ts.isLoading,markRead:Na=>is.mutate(Na),markAllRead:()=>cs.mutate()}}function NotificationsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;(async()=>{if(!(typeof Notification>"u")&&Notification.permission==="default")try{await Notification.requestPermission()}catch{}})();let is=null;const cs=setTimeout(()=>{is=supabase.channel(`notifications-${es.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"notifications",filter:`user_id=eq.${es.id}`},Kr=>{const Xr=Kr.new,Na={id:Xr.id,userId:Xr.user_id,type:Xr.type,title:Xr.title,body:Xr.body??null,url:Xr.url??null,sourceTable:Xr.source_table??null,sourceId:Xr.source_id??null,metadata:Xr.metadata??{},readAt:Xr.read_at??null,createdAt:Xr.created_at};$.setQueryData(NOTIFICATIONS_QUERY_KEY,Ca=>{const Aa=(Ca==null?void 0:Ca.items)??[];return Aa.some(Ia=>Ia.id===Na.id)?Ca??{items:Aa,unreadCount:0}:{items:[Na,...Aa].slice(0,20),unreadCount:((Ca==null?void 0:Ca.unreadCount)??0)+1}}),fireOsNotification(Na)}).subscribe()},50);return()=>{clearTimeout(cs),is&&supabase.removeChannel(is)}},[es==null?void 0:es.id,$]),null}async function fireOsNotification(es){if(typeof Notification>"u"||Notification.permission!=="granted")return;const $={body:es.body??void 0,icon:"/favicon-192.png",badge:"/favicon-48.png",tag:`notif-${es.id}`,data:{url:es.url??"/",notificationId:es.id}};if("serviceWorker"in navigator)try{await(await navigator.serviceWorker.ready).showNotification(es.title,$);return}catch{}new Notification(es.title,$)}function typeIcon(es){if(es.startsWith("usage_")){const $=es==="usage_imminent"||es==="usage_hit";return jsxRuntimeExports.jsx(TriangleAlert,{className:cn$1("h-3.5 w-3.5",$?"text-red-500":"text-amber-500")})}return es.endsWith("_failed")?jsxRuntimeExports.jsx(CircleAlert,{className:"h-3.5 w-3.5 text-red-500"}):es==="insights_ready"?jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-amber-500"}):es==="labels_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):es==="calibration_ready"?jsxRuntimeExports.jsx(BadgeCheck,{className:"h-3.5 w-3.5 text-teal-500"}):es==="second_engine_needed"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-blue-500"}):es==="second_opinions_flagged"?jsxRuntimeExports.jsx(ClipboardList,{className:"h-3.5 w-3.5 text-amber-500"}):jsxRuntimeExports.jsx(BellRing,{className:"h-3.5 w-3.5 text-blue-500"})}function formatRelative(es){const $=Date.now()-new Date(es).getTime(),ts=Math.floor($/6e4);if(ts<1)return"just now";if(ts<60)return`${ts}m ago`;const is=Math.floor(ts/60);return is<24?`${is}h ago`:`${Math.floor(is/24)}d ago`}function NotificationBell(){const es=useNavigate(),{items:$,unreadCount:ts,markRead:is,markAllRead:cs}=useNotifications(),Kr=Xr=>{Xr.readAt||is(Xr.id),Xr.url&&es(Xr.url)};return jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"relative cursor-pointer",children:[jsxRuntimeExports.jsx(Bell,{className:"h-4 w-4"}),ts>0&&jsxRuntimeExports.jsx("span",{className:"absolute top-1 right-1 inline-flex h-4 min-w-[1rem] items-center justify-center rounded-full bg-blue-500 px-1 text-[10px] font-medium text-white",children:ts>9?"9+":ts})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",className:"w-80",children:[jsxRuntimeExports.jsxs(DropdownMenuLabel,{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{children:"Notifications"}),ts>0&&jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(),className:"flex items-center gap-1 text-[10px] font-normal text-muted-foreground hover:text-foreground",children:[jsxRuntimeExports.jsx(CheckCheck,{className:"h-3 w-3"}),"Mark all read"]})]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),$.length===0?jsxRuntimeExports.jsx(DropdownMenuItem,{disabled:!0,children:jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"No notifications yet"})}):$.map(Xr=>jsxRuntimeExports.jsx(DropdownMenuItem,{className:"cursor-pointer",onClick:()=>Kr(Xr),children:jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 w-full",children:[jsxRuntimeExports.jsx("div",{className:"mt-0.5",children:typeIcon(Xr.type)}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium truncate",children:Xr.title}),Xr.body&&jsxRuntimeExports.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:Xr.body}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground",children:formatRelative(Xr.createdAt)})]}),!Xr.readAt&&jsxRuntimeExports.jsx("span",{className:"mt-1.5 h-1.5 w-1.5 shrink-0 rounded-full bg-blue-500"})]})},Xr.id))]})]})}function OrgSwitcher(){return useActiveOrg(),useSetActiveOrg(),useNavigate(),null}function Header(){var is;const{user:es,signOut:$}=useAuth(),ts=((is=es==null?void 0:es.email)==null?void 0:is.slice(0,2).toUpperCase())??"?";return jsxRuntimeExports.jsxs("header",{className:"flex h-12 items-center border-b border-border px-2 gap-1 sm:px-4 sm:gap-4 bg-background",children:[jsxRuntimeExports.jsxs(Sheet,{children:[jsxRuntimeExports.jsx(SheetTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"md:hidden cursor-pointer",children:jsxRuntimeExports.jsx(Menu$1,{className:"h-5 w-5"})})}),jsxRuntimeExports.jsxs(SheetContent,{side:"left",className:"w-60 p-0",children:[jsxRuntimeExports.jsx(SheetTitle,{className:"sr-only",children:"Navigation"}),jsxRuntimeExports.jsx(Sidebar,{})]})]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx(OrgSwitcher,{}),jsxRuntimeExports.jsx(NotificationBell,{}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"rounded-full cursor-pointer shrink-0",children:jsxRuntimeExports.jsx(Avatar,{className:"h-8 w-8",children:jsxRuntimeExports.jsx(AvatarFallback,{className:"text-xs bg-secondary text-muted-foreground",children:ts})})})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsxs(DropdownMenuItem,{disabled:!0,children:[jsxRuntimeExports.jsx(User,{className:"mr-2 h-4 w-4"}),es==null?void 0:es.email]}),jsxRuntimeExports.jsx(DropdownMenuSeparator,{}),jsxRuntimeExports.jsxs(DropdownMenuItem,{onClick:()=>$(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(LogOut,{className:"mr-2 h-4 w-4"}),"Sign out"]})]})]})]})}function useComputedInsights(es,$,ts){const is=(ts==null?void 0:ts.projectId)??void 0,cs=new URLSearchParams;return es&&cs.set("projectPath",es),is&&cs.set("projectId",is),$&&cs.set("tool",$),ts!=null&&ts.since&&cs.set("since",ts.since),useQuery({queryKey:["insights","computed",es,is??null,$,(ts==null?void 0:ts.since)??null],queryFn:()=>apiGet(`/api/insights/compute?${cs}`),refetchInterval:ts==null?void 0:ts.refetchIntervalMs})}function useInstructionImpact(es){return useQuery({queryKey:["insights","instruction-impact",es],queryFn:()=>apiGet(`/api/insights/instruction-impact?instructionId=${es}`),enabled:!!es})}function useGroomCandidates(){return useQuery({queryKey:["insights","groom-candidates"],queryFn:()=>apiGet("/api/insights/groom-candidates")})}function useRestoreInstruction$1(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/instructions/${$}/restore`,{}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","groom-candidates"]}),es.invalidateQueries({queryKey:["insights"]}),es.invalidateQueries({queryKey:["instructions"]}),es.invalidateQueries({queryKey:["instruction-suggestions"]})}})}function useArchiveInstruction$1(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/instructions/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["insights","groom-candidates"]}),es.invalidateQueries({queryKey:["insights"]})}})}function useLinkedInstructions(es){const $=new URLSearchParams;return es&&$.set("projectPath",es),useQuery({queryKey:["insights","linked-instructions",es],queryFn:()=>apiGet(`/api/insights/linked-instructions?${$}`)})}function useInsightsProjects(){return useQuery({queryKey:["insights","projects"],queryFn:()=>apiGet("/api/insights/projects")})}function useInsightsJobs(es,$){const ts=new URLSearchParams;return es&&ts.set("projectPath",es),$&&ts.set("limit",String($)),useQuery({queryKey:["insights-jobs",es,$],queryFn:()=>apiGet(`/api/insights-jobs?${ts}`),refetchInterval:5e3})}const STALE_JOB_MS=600*1e3;function useActiveInsightsJobs(es){const{data:$}=useInsightsJobs(es),ts=Date.now();return($??[]).filter(is=>{if(!["pending","claimed","running"].includes(is.status))return!1;const cs=is.claimedAt?new Date(is.claimedAt).getTime():0;return!cs||ts-cs<=STALE_JOB_MS})}function useCreateInsightsJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs",{projectPath:$}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useRegenerateAllInsights(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/insights-jobs/regenerate-all",$!=null&&$.force?{force:!0}:{}),onSuccess:()=>{es.invalidateQueries({queryKey:["insights-jobs"]})}})}function useAutoAddSuggestion(){return useMutation({mutationFn:es=>apiPost("/api/insights/auto-add",es)})}function useProjectInsights(es,$,ts,is){var Qa;const{data:cs}=useInsightsProjects(),Kr=$?cs==null?void 0:cs.find(Xa=>Xa.projectPath===$):void 0,Xr=ts??(Kr==null?void 0:Kr.projectId)??void 0,{data:Na,isLoading:Ca}=useComputedInsights($,is,{projectId:Xr}),Aa=$?(Kr==null?void 0:Kr.name)??$.split("/").filter(Boolean).slice(-2).join("/"):void 0,Ia=useActiveInsightsJobs($),{data:Ma}=useInsightsJobs($),Pa=useCreateInsightsJob(),La=Na??null,Fa=(Qa=Ia[0])==null?void 0:Qa.progress,Ba=Fa!=null&&Fa.partial&&Object.keys(Fa.partial).length>0?Fa.partial:void 0,qa=(La==null?void 0:La.recommendations)??Ba,za=(Ma??[]).filter(Xa=>Xa.status==="completed"&&Xa.completedAt).sort((Xa,Ja)=>new Date(Ja.completedAt).getTime()-new Date(Xa.completedAt).getTime())[0],Va=(Na==null?void 0:Na.sessions_with_meta)??0,Ga=Aa??"Live Insights",Za=`Computed from ${Va} enriched sessions`;return{data:La,recommendations:qa,isLoading:Ca,fullProjectPath:$,title:Ga,subtitle:Za,lastCompletedJob:za,activeJobs:Ia,createJob:Pa}}function InsightsJobsListener(){const{user:es}=useAuth(),$=useQueryClient();return reactExports.useEffect(()=>{if(!(es!=null&&es.id))return;let ts=null;const is=setTimeout(()=>{ts=supabase.channel(`insights-jobs-${es.id}`).on("postgres_changes",{event:"UPDATE",schema:"public",table:"insights_jobs",filter:`user_id=eq.${es.id}`},cs=>{const Kr=cs.new,Xr={id:Kr.id,status:Kr.status,projectPath:Kr.project_path??null,progress:Kr.progress??{},error:Kr.error??null,updatedAt:Kr.updated_at,completedAt:Kr.completed_at??null};$.setQueriesData({queryKey:["insights-jobs"]},Na=>{if(!Na)return Na;const Ca=Na.findIndex(Ia=>Ia.id===Xr.id);if(Ca===-1)return Na;const Aa=Na.slice();return Aa[Ca]={...Na[Ca],...Xr},Aa}),Xr.status==="completed"&&$.invalidateQueries({queryKey:["insights","computed"]})}).subscribe()},50);return()=>{clearTimeout(is),ts&&supabase.removeChannel(ts)}},[es==null?void 0:es.id,$]),null}const SEVERITY_LABEL={soft:"soft warning",approaching:"approaching limit",imminent:"imminent limit",hit:"limit reached"};function formatTimeLeft(es,$){if(!es)return"soon";const ts=new Date(es).getTime()-$;if(ts<=0)return"now";const is=Math.round(ts/6e4);if(is<60)return`in ${is} min`;const cs=Math.floor(is/60),Kr=is%60;return Kr>0?`in ${cs}h ${Kr}m`:`in ${cs}h`}function formatAlertMessage(es,$,ts,is,cs=Date.now()){const Kr=formatTimeLeft(is,cs);if(es==="hit")return`Claude ${$} reached 100% — requests will fail. Resets ${Kr}.`;const Xr=ts!=null?`${ts.toFixed(0)}%`:"limit";return`Claude ${$} at ${Xr} — ${SEVERITY_LABEL[es]}. Resets ${Kr}.`}const ACTIVE_WINDOW_MS=600*1e3,POLL_MS=3e4,SEVERITY_STYLES={soft:"bg-yellow-100 border-yellow-300 text-yellow-900",approaching:"bg-amber-200 border-amber-400 text-amber-950",imminent:"bg-orange-300 border-orange-500 text-orange-950",hit:"bg-red-400 border-red-600 text-red-950"};function dismissKey$1(es){return`alert-dismissed:${es}`}function AlertBanner(){var Pa,La,Fa;const{data:es}=useQuery({queryKey:["alerts-recent"],queryFn:()=>apiGet("/api/alerts/recent"),refetchInterval:POLL_MS,refetchOnWindowFocus:!0}),[,$]=reactExports.useState(0);reactExports.useEffect(()=>{const Ba=setInterval(()=>$(qa=>qa+1),6e4);return()=>clearInterval(Ba)},[]);const ts=(es==null?void 0:es.items)??[];reactExports.useEffect(()=>{if(typeof window>"u"||!es)return;const Ba=new Set(ts.map(qa=>qa.id));for(let qa=localStorage.length-1;qa>=0;qa--){const za=localStorage.key(qa);za!=null&&za.startsWith("alert-dismissed:")&&!Ba.has(za.slice(16))&&localStorage.removeItem(za)}},[es,ts]);const is=Date.now(),cs=ts.find(Ba=>!(is-new Date(Ba.lastDispatchedAt).getTime()>ACTIVE_WINDOW_MS||typeof window<"u"&&localStorage.getItem(dismissKey$1(Ba.id)))),[,Kr]=reactExports.useState(0);if(!cs)return null;const Xr=cs.severity,Na=(Pa=cs.lastState)==null?void 0:Pa.usedPercentage,Ca=(La=cs.lastState)==null?void 0:La.resetsAt,[,,Aa]=cs.alertKey.split(":"),Ia=((Fa=cs.lastState)==null?void 0:Fa.message)??formatAlertMessage(Xr,Aa,Na,Ca);function Ma(){typeof window<"u"&&localStorage.setItem(dismissKey$1(cs.id),"1"),Kr(Ba=>Ba+1)}return jsxRuntimeExports.jsxs("div",{role:Xr==="hit"?"alert":"status",className:cn$1("flex items-center gap-3 border-b px-4 py-2 text-sm",SEVERITY_STYLES[Xr]),children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsx("span",{className:"flex-1 font-mono",children:Ia}),jsxRuntimeExports.jsx("button",{type:"button",onClick:Ma,"aria-label":"Dismiss alert",className:"rounded p-1 hover:bg-black/10",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useLatestVersion(){return useQuery({queryKey:["cli-latest-version"],queryFn:()=>apiGet("/api/cli/latest-version"),staleTime:3600*1e3,refetchInterval:3600*1e3,refetchOnWindowFocus:!1})}function compareVersions(es,$){const ts=Xr=>Xr.split(".").map(Na=>Number.parseInt(Na,10)||0),is=ts(es),cs=ts($),Kr=Math.max(is.length,cs.length);for(let Xr=0;Xr<Kr;Xr++){const Na=is[Xr]??0,Ca=cs[Xr]??0;if(Na<Ca)return-1;if(Na>Ca)return 1}return 0}function cliUpdateStatus(es,$){if(!$)return null;const ts=es.filter(cs=>typeof cs=="string"&&cs.length>0);if(ts.length===0)return null;const is=ts.reduce((cs,Kr)=>compareVersions(Kr,cs)>0?Kr:cs,ts[0]);return compareVersions($,is)<=0?null:{current:is,latest:$}}const CLI_WORKER_TYPES=new Set(["cli-worker","gateway","proxy"]);function dismissKey(es){return`cli-update-dismissed:${es}`}function CliUpdateBanner(){const{activeWorkers:es}=useWorkerStatus(),{data:$}=useLatestVersion(),[,ts]=reactExports.useState(0),is=cliUpdateStatus(es.filter(Kr=>CLI_WORKER_TYPES.has(Kr.workerType)).map(Kr=>Kr.clientVersion),$==null?void 0:$.latest);if(!is||typeof window<"u"&&localStorage.getItem(dismissKey(is.latest)))return null;function cs(){typeof window<"u"&&localStorage.setItem(dismissKey(is.latest),"1"),ts(Kr=>Kr+1)}return jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-3 border-b border-primary/20 bg-primary/5 px-4 py-2 text-sm text-foreground",children:[jsxRuntimeExports.jsx(CircleArrowUp,{className:"h-4 w-4 flex-shrink-0 text-primary"}),jsxRuntimeExports.jsxs("span",{className:"flex-1",children:["RuleMetric CLI ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:is.current})," →"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold text-primary",children:is.latest})," available. Upgrade:"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"npm i -g @rulemetric/cli@latest"}),", then re-run"," ",jsxRuntimeExports.jsx("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-xs",children:"rulemetric hooks install"})," ","to pick up new capture hooks."]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:cs,"aria-label":"Dismiss CLI update notice",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}function useWorkerHealth(){return useQuery({queryKey:["worker-health"],queryFn:()=>apiGet("/api/workers/health"),staleTime:6e4,refetchInterval:6e4,refetchOnWindowFocus:!0})}const DISMISS_TTL_MS=1440*60*1e3;function conditionKey(es){return`${es.severity}:${es.headline}`}function dismissStorageKey(es){return`worker-health-dismissed:${es}`}function bannerFor(es){return!es||es.severity==="ok"?null:{severity:es.severity,headline:es.headline,hints:es.hints,key:conditionKey(es)}}function isDismissed(es,$=Date.now(),ts=DISMISS_TTL_MS){if(!es)return!1;const is=Number(es);if(!Number.isFinite(is)||is<=0)return!1;const cs=$-is;return cs<0?!1:cs<ts}function WorkerHealthBanner(){const{data:es}=useWorkerHealth(),[,$]=reactExports.useState(0),ts=bannerFor(es==null?void 0:es.verdict);if(!ts)return null;const is=dismissStorageKey(ts.key),cs=typeof window>"u"?null:localStorage.getItem(is);if(isDismissed(cs))return null;function Kr(){typeof window<"u"&&localStorage.setItem(is,String(Date.now())),$(Ca=>Ca+1)}const Xr=ts.severity==="fail",Na=Xr?CircleX:TriangleAlert;return jsxRuntimeExports.jsxs("div",{role:"alert","data-testid":"worker-health-banner","data-severity":ts.severity,className:"flex items-start gap-3 border-b px-4 py-2 text-sm text-foreground "+(Xr?"border-destructive/30 bg-destructive/10":"border-amber-500/40 bg-amber-500/10"),children:[jsxRuntimeExports.jsx(Na,{className:"mt-0.5 h-4 w-4 flex-shrink-0 "+(Xr?"text-destructive":"text-amber-500")}),jsxRuntimeExports.jsxs("div",{className:"flex-1 space-y-1",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:ts.headline}),ts.hints.map(Ca=>jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ca},Ca))]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:Kr,"aria-label":"Dismiss worker health notice",title:"Hidden for 24 hours — reappears if the problem persists",className:"flex h-9 w-9 flex-shrink-0 cursor-pointer items-center justify-center rounded hover:bg-secondary",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})}const CORE_ORDER$1=["install","auth","hooks","worker"];function deriveSetupProgress(es){const $=Na=>Na?"detected":es.loading?"loading":"waiting",ts=es.authenticated?"detected":es.loading?"loading":"attention",is=es.cliEverConnected||es.anyCapturedSession||es.workerHeartbeat,cs={install:{id:"install",label:"Install the CLI",optional:!1,state:$(is),command:"npm install -g @rulemetric/cli",waitingFor:"first CLI connection",hint:"Requires Node. No Node? A standalone installer is coming — for now, install Node first."},auth:{id:"auth",label:"Authenticated",optional:!1,state:ts,waitingFor:"an active session"},hooks:{id:"hooks",label:"Hooks installed",optional:!1,state:$(es.anyCapturedSession),command:"rulemetric hooks install",waitingFor:"first captured session",hint:"Hooks capture your Claude Code sessions directly — no CA cert or proxy required. Optional: add the local proxy to also record the exact system prompt each model saw, capture your other AI tools (Copilot, Cursor, Codex), and track live cost & rate limits — which unlocks full cross-tool instruction-effectiveness analysis."},worker:{id:"worker",label:"Worker running",optional:!1,state:$(es.workerHeartbeat),command:"rulemetric service install --worker-only",waitingFor:"a worker heartbeat"},tmux:{id:"tmux",label:"Tmux available",optional:!0,state:$(es.hasActiveTmux),waitingFor:"a Claude Code session running inside tmux"},target:{id:"target",label:"First live target detected",optional:!0,state:$(es.hasAnyTarget),waitingFor:"your first terminal target"},judge:{id:"judge",label:"Judge validation engine",optional:!0,state:$(es.llmEngines!=null&&es.llmEngines.claude&&es.llmEngines.codex),command:"npm install -g @openai/codex",waitingFor:es.llmEngines==null?"a worker heartbeat reporting your installed engines":"a second LLM engine (claude + codex)",hint:"Optional — hand labels + one judge already give you calibrated verdicts. A second engine (e.g. the Codex CLI) unlocks cross-vendor judge validation: two vendors checking each other's blind spots."}},Kr=CORE_ORDER$1.every(Na=>cs[Na].state==="detected"),Xr=Kr?null:CORE_ORDER$1.find(Na=>cs[Na].state!=="detected")??null;return{steps:cs,coreComplete:Kr,currentStepId:Xr}}function useSetupProgress(es=3e4){var Xr,Na,Ca,Aa,Ia;const{session:$}=useAuth(),ts=useQuery({queryKey:["setup-status",es],queryFn:()=>apiGet("/api/setup/status"),refetchInterval:es}),is=useQuery({queryKey:["terminal-targets","all",es],queryFn:()=>apiGet("/api/terminal-targets"),refetchInterval:es}),cs=ts.isLoading||is.isLoading,Kr=((Xr=is.data)==null?void 0:Xr.targets)??[];return deriveSetupProgress({loading:cs,authenticated:!!$,cliEverConnected:((Na=ts.data)==null?void 0:Na.cliEverConnected)??!1,anyCapturedSession:((Ca=ts.data)==null?void 0:Ca.anyCapturedSession)??!1,workerHeartbeat:((Aa=ts.data)==null?void 0:Aa.workerActive)??!1,hasActiveTmux:Kr.some(Ma=>Ma.kind==="tmux"&&Ma.status==="active"),hasAnyTarget:Kr.length>0,llmEngines:((Ia=ts.data)==null?void 0:Ia.llmEngines)??null})}function track(es,$){}const CORE_STEP_IDS=["install","auth","hooks","worker"],DISMISSED_KEY="rm.setupWalkthrough.dismissed";function readDismissed(){try{return sessionStorage.getItem(DISMISSED_KEY)==="1"}catch{return!1}}function writeDismissed(){try{sessionStorage.setItem(DISMISSED_KEY,"1")}catch{}}const SetupWalkthroughContext=reactExports.createContext(null);function SetupWalkthroughProvider({children:es}){const{session:$}=useAuth(),ts=!!$,is=useQueryClient(),{profile:cs,isLoading:Kr}=useActiveOrg(),[Xr,Na]=reactExports.useState(!1),[Ca,Aa]=reactExports.useState("welcome"),[Ia,Ma]=reactExports.useState(readDismissed),Pa=(cs==null?void 0:cs.setupCompletedAt)!=null,La=useSetupProgress(Xr||!Pa?4e3:!1),Fa=reactExports.useRef(!1),Ba=reactExports.useRef(null),qa=reactExports.useRef(null),za=reactExports.useRef({}),Va=reactExports.useRef(new Set),Ga=reactExports.useRef(!1),Za=reactExports.useCallback(()=>{Na(!0)},[]),Qa=reactExports.useCallback(()=>{writeDismissed(),Ma(!0),Na(!1)},[Ca]),Xa=reactExports.useCallback(tl=>{Aa(tl)},[]);reactExports.useEffect(()=>{ts&&(Ia||Kr||La.steps.install.state==="loading"||(cs==null?void 0:cs.setupCompletedAt)==null&&(La.coreComplete||Na(!0)))},[ts,Ia,Kr,cs==null?void 0:cs.setupCompletedAt,La.coreComplete,La.steps.install.state]),reactExports.useEffect(()=>{const tl=Ba.current;if(Ba.current=La.coreComplete,!!ts&&La.coreComplete&&!Fa.current){if((cs==null?void 0:cs.setupCompletedAt)!=null){Fa.current=!0;return}tl===!1&&(Fa.current=!0,Ga.current||(Ga.current=!0),apiPatch("/api/profile",{setupCompletedAt:new Date().toISOString()}).then(()=>{is.invalidateQueries({queryKey:["profile"]})}).catch(()=>{}),Aa("payoff"))}},[ts,La.coreComplete,cs==null?void 0:cs.setupCompletedAt,is]),reactExports.useEffect(()=>{if(!Xr)return;const tl=`${Ca}::${La.currentStepId??""}`;qa.current!==tl&&(qa.current=tl,La.currentStepId,void 0)},[Xr,Ca,La.currentStepId]),reactExports.useEffect(()=>{const tl=Date.now();for(const sl of CORE_STEP_IDS){const ol=La.steps[sl].state;if(ol!=="loading")if(ol==="detected"){if(Va.current.has(sl))continue;Va.current.add(sl),za.current[sl]}else za.current[sl]==null&&(za.current[sl]=tl)}},[La.steps.install.state,La.steps.auth.state,La.steps.hooks.state,La.steps.worker.state]);const Ja={open:Xr,stage:Ca,progress:La,openModal:Za,dismiss:Qa,goTo:Xa,authenticated:ts};return reactExports.createElement(SetupWalkthroughContext.Provider,{value:Ja},es)}function useSetupWalkthrough(){const es=reactExports.useContext(SetupWalkthroughContext);if(!es)throw new Error("useSetupWalkthrough must be used within a SetupWalkthroughProvider");return es}function Dialog({...es}){return jsxRuntimeExports.jsx(Root$5,{"data-slot":"dialog",...es})}function DialogPortal({...es}){return jsxRuntimeExports.jsx(Portal$3,{"data-slot":"dialog-portal",...es})}function DialogOverlay({className:es,...$}){return jsxRuntimeExports.jsx(Overlay,{"data-slot":"dialog-overlay",className:cn$1("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",es),...$})}function DialogContent({className:es,children:$,showCloseButton:ts=!0,...is}){return jsxRuntimeExports.jsxs(DialogPortal,{"data-slot":"dialog-portal",children:[jsxRuntimeExports.jsx(DialogOverlay,{}),jsxRuntimeExports.jsxs(Content$2,{"data-slot":"dialog-content",className:cn$1("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",es),...is,children:[$,ts&&jsxRuntimeExports.jsxs(Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 flex size-8 items-center justify-center rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[jsxRuntimeExports.jsx(X$1,{}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function DialogHeader({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"dialog-header",className:cn$1("flex flex-col gap-2 text-center sm:text-left",es),...$})}function DialogFooter({className:es,showCloseButton:$=!1,children:ts,...is}){return jsxRuntimeExports.jsxs("div",{"data-slot":"dialog-footer",className:cn$1("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",es),...is,children:[ts,$&&jsxRuntimeExports.jsx(Close,{asChild:!0,children:jsxRuntimeExports.jsx(Button,{variant:"outline",children:"Close"})})]})}function DialogTitle({className:es,...$}){return jsxRuntimeExports.jsx(Title,{"data-slot":"dialog-title",className:cn$1("text-lg leading-none font-semibold",es),...$})}function DialogDescription({className:es,...$}){return jsxRuntimeExports.jsx(Description,{"data-slot":"dialog-description",className:cn$1("text-muted-foreground text-sm",es),...$})}const badgeVariants=cva("inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"bg-primary text-primary-foreground [a&]:hover:bg-primary/90 [button&]:hover:bg-primary/90",secondary:"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90 [button&]:hover:bg-secondary/90",destructive:"bg-destructive text-white [a&]:hover:bg-destructive/90 [button&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground [button&]:hover:bg-accent [button&]:hover:text-accent-foreground",ghost:"[a&]:hover:bg-accent [a&]:hover:text-accent-foreground [button&]:hover:bg-accent [button&]:hover:text-accent-foreground",link:"text-primary underline-offset-4 [a&]:hover:underline [button&]:hover:underline"}},defaultVariants:{variant:"default"}});function Badge({className:es,variant:$="default",asChild:ts=!1,...is}){const cs=ts?Slot$3:"span";return jsxRuntimeExports.jsx(cs,{"data-slot":"badge","data-variant":$,className:cn$1(badgeVariants({variant:$}),es),...is})}function CopyButton$5({text:es}){const[$,ts]=reactExports.useState(!1);async function is(){const cs=()=>{ts(!0),setTimeout(()=>ts(!1),2e3)};try{await navigator.clipboard.writeText(es),cs()}catch{try{const Kr=document.createElement("textarea");Kr.value=es,Kr.style.position="fixed",Kr.style.opacity="0",document.body.appendChild(Kr),Kr.select(),document.execCommand("copy"),document.body.removeChild(Kr),cs()}catch{}}}return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:is,className:"cursor-pointer",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Check,{className:"mr-1 h-3 w-3"}),"Copied"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Copy,{className:"mr-1 h-3 w-3"}),"Copy"]})})}const CC_SETUP_PROMPT=`Set up RuleMetric on this machine, agentically and transparently.
713
713
 
714
714
  STEP 0 — install or UPGRADE the CLI first. The \`setup\` command requires
715
715
  @rulemetric/cli 0.5.0+; older global installs do NOT have it, so always run:
@@ -945,6 +945,6 @@ rulemetric capture scope --tool hooks --off
945
945
 
946
946
  # The worker's Codex transcript sweep
947
947
  rulemetric capture scope --add ~/work/client-a
948
- rulemetric capture scope --off`}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"One honest caveat: the optional mitmproxy network-capture chain is governed by its host allowlist, not by these scopes. Hooks-first capture (the default) is fully governed."})]})})})]})}function DocsPage(){const[es,$]=useTabParam(["getting-started","cli","api","evals","proxy","insights","data"],"getting-started");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Documentation"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Guides, CLI reference, API reference, and system documentation"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"getting-started",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(BookOpen,{className:"mr-2 h-4 w-4"}),"Quick Start"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"cli",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"CLI Reference"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"api",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(CodeXml,{className:"mr-2 h-4 w-4"}),"API Reference"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"evals",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mr-2 h-4 w-4"}),"Eval System"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"proxy",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Radio,{className:"mr-2 h-4 w-4"}),"Proxy & Context"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"insights",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Insights"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"data",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ShieldCheck,{className:"mr-2 h-4 w-4"}),"Data & Retention"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"getting-started",className:"mt-6",children:jsxRuntimeExports.jsx(QuickStartTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"cli",className:"mt-6",children:jsxRuntimeExports.jsx(CLIReferenceTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"api",className:"mt-6",children:jsxRuntimeExports.jsx(APIReferenceTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"evals",className:"mt-6",children:jsxRuntimeExports.jsx(EvalSystemTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"proxy",className:"mt-6",children:jsxRuntimeExports.jsx(ProxyContextTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"insights",className:"mt-6",children:jsxRuntimeExports.jsx(InsightsTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"data",className:"mt-6",children:jsxRuntimeExports.jsx(DataRetentionTab,{})})]})]})}function useHarnessReleases(es,$=50){const ts=new URLSearchParams;return ts.set("harness",es),ts.set("limit",String($)),useQuery({queryKey:["harness-releases",es,$],queryFn:()=>apiGet(`/api/harness-releases?${ts}`)})}function useSyncHarnessReleases(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/harness-releases/sync",{harness:$}),onSuccess:()=>es.invalidateQueries({queryKey:["harness-releases"]})})}function AnalysisFreshnessBanner({freshness:es,totalAnalyzed:$}){if(!es||$===0)return null;const{with_timestamp:ts,pre_instrumentation:is,stale_30d:cs,oldest_analyzed_at:Kr}=es,Xr=$>0?Math.round(is/$*100):0,Na=ts>0?Math.round(cs/ts*100):0;if(is===0&&cs===0)return null;const Ca=Xr>=25||Na>=50?"warn":"info",Aa=Ca==="warn"?"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-border bg-muted/40 text-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-2 rounded-md border px-3 py-2 text-xs ${Aa}`,children:[Ca==="warn"?jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 mt-0.5"}):jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 mt-0.5"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 font-mono space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:Ca==="warn"?"Some inputs to these stats are stale or untimestamped":"Input freshness"}),jsxRuntimeExports.jsxs("p",{children:[is>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is," of ",$," analyzed sessions (",Xr,"%) predate timestamp tracking. Re-analyze them to participate in freshness checks."]}),is>0&&cs>0&&" ",cs>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs," of ",ts," timestamped analyses (",Na,"%) are over 30 days old",Kr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(oldest: ",new Date(Kr).toLocaleDateString(),")"]}),"."]})]})]})]})}function jobStepLabel(es){const $=es.progress;return $!=null&&$.step&&($!=null&&$.current)&&($!=null&&$.total)?`${$.step} (${$.current}/${$.total})`:$!=null&&$.step?$.step:es.status==="claimed"?"starting...":es.status==="pending"?"queued":es.status}function JobStatusIcon({status:es}){switch(es){case"completed":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"});case"running":case"claimed":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3.5 w-3.5 text-blue-500 animate-spin shrink-0"});case"failed":return jsxRuntimeExports.jsx(CircleX,{className:"h-3.5 w-3.5 text-red-500 shrink-0"});case"pending":default:return jsxRuntimeExports.jsx(CircleDashed,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})}}function JobTracker({jobs:es}){if(es.length===0)return null;const $=es.filter(Ma=>Ma.status==="completed").length,ts=es.filter(Ma=>Ma.status==="failed").length,is=es.filter(Ma=>Ma.status==="running"||Ma.status==="claimed").length,cs=es.filter(Ma=>Ma.status==="pending").length,Kr=es.length,Xr=$+ts,Na=Xr===Kr,Ca=$/Kr*100,Aa=ts/Kr*100,Ia=is/Kr*100;return jsxRuntimeExports.jsx(Card,{className:Na?"border-teal-500/30 bg-teal-500/5":"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-4 pb-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[Na?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-blue-500"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Na?Kr===1?"Recommendations ready":`All ${Kr} projects done`:Kr===1?`Generating recommendations — ${jobStepLabel(es[0])}`:`Generating recommendations — ${Xr}/${Kr} complete`})]}),Kr>1&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground font-mono",children:[$>0&&jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[$," done"]}),is>0&&jsxRuntimeExports.jsxs("span",{className:"text-blue-500",children:[is," running"]}),cs>0&&jsxRuntimeExports.jsxs("span",{children:[cs," queued"]}),ts>0&&jsxRuntimeExports.jsxs("span",{className:"text-red-500",children:[ts," failed"]})]})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden flex",children:Kr===1?(()=>{const Ma=es[0],Pa=Ma.progress,La=Pa!=null&&Pa.current&&(Pa!=null&&Pa.total)?Pa.current/Pa.total*100:0;return Ma.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):Ma.status==="failed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500",style:{width:"100%"}}):jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Math.max(La,5)}%`}})})():jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ca>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500 transition-all duration-500",style:{width:`${Ca}%`}}),Aa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500 transition-all duration-500",style:{width:`${Aa}%`}}),Ia>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Ia}%`}})]})}),Kr>1&&jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-1",children:es.map(Ma=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs py-0.5",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:Ma.status}),jsxRuntimeExports.jsx("span",{className:"font-mono truncate",children:Ma.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:Ma.status==="running"||Ma.status==="claimed"?jobStepLabel(Ma):Ma.status==="failed"?"error":Ma.status==="completed"?"done":"queued"})]},Ma.id))})]})})}function ProjectJobBadge({job:es}){return es.status==="completed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"mr-1 h-2.5 w-2.5"})," done"]}):es.status==="failed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleX,{className:"mr-1 h-2.5 w-2.5"})," failed"]}):es.status==="running"||es.status==="claimed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-500 border-blue-500/20 font-mono",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-2.5 w-2.5 animate-spin"})," ",jobStepLabel(es)]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleDashed,{className:"mr-1 h-2.5 w-2.5"})," queued"]})}function WorkerOfflineBanner(){const{workers:es,isLoading:$}=useWorkerStatus("cli-worker");if($)return null;const ts=es.slice().sort((Kr,Xr)=>new Date(Xr.lastHeartbeat).getTime()-new Date(Kr.lastHeartbeat).getTime())[0];if((ts==null?void 0:ts.status)==="active")return null;const cs=ts?`${Math.round((Date.now()-new Date(ts.lastHeartbeat).getTime())/1e3)}s ago`:"never";return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsx("div",{className:"font-medium text-amber-500 mb-1",children:"Worker offline"}),jsxRuntimeExports.jsxs("div",{className:"text-muted-foreground",children:["No cli-worker has heartbeat'd within the last 60s (last seen: ",cs,"). Insights jobs will queue but won't run until the worker is healthy. Restart with"," ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"launchctl kickstart -k gui/$UID/com.rulemetric.worker"}),"."]})]})}function formatCompact(es){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(es)}function parseTimestamp(es){if(!es)return null;const $=es.replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),ts=new Date($);return Number.isNaN(ts.getTime())?null:ts}function formatSessionRange(es,$){const ts=parseTimestamp(es),is=parseTimestamp($),cs={month:"short",day:"numeric",year:"numeric"};if(ts&&is){const Xr=ts.getFullYear()===is.getFullYear();return`${ts.toLocaleDateString(void 0,Xr?{month:"short",day:"numeric"}:cs)} – ${is.toLocaleDateString(void 0,cs)}`}const Kr=ts??is;return Kr?Kr.toLocaleDateString(void 0,cs):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,cs)=>is+cs,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Na;const $=outcomeScore(es.outcomes??{}),ts=es.total_sessions?Math.round(es.sessions_with_analysis/es.total_sessions*100):0,is=Object.entries(es.friction??{}).sort((Ca,Aa)=>Aa[1]-Ca[1])[0],cs=Object.entries(es.tool_counts??{}).sort((Ca,Aa)=>Aa[1]-Ca[1]).slice(0,5),Kr=((Na=cs[0])==null?void 0:Na[1])??1,Xr=[{label:"Successful outcomes",value:$==null?"—":`${$}%`,detail:`${es.sessions_with_analysis} analyzed`,icon:CircleCheck},{label:"Estimated spend",value:`$${(es.estimated_cost_usd??0).toFixed(2)}`,detail:`${formatCompact(es.total_input_tokens+es.total_output_tokens)} tokens`,icon:DollarSign},{label:"Tool errors",value:es.total_tool_errors.toLocaleString(),detail:`${es.total_interruptions} interruptions`,icon:TriangleAlert},{label:"Code changed",value:`+${formatCompact(es.total_lines_added)}`,detail:`${formatCompact(es.total_lines_removed)} removed · ${es.git_commits} commits`,icon:TrendingUp}];return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Xr.map(({label:Ca,value:Aa,detail:Ia,icon:Ma})=>jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",children:Ca}),jsxRuntimeExports.jsx(Ma,{className:"h-4 w-4"})]}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-2xl font-mono font-semibold",children:Aa}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Ia})]})},Ca))}),es.truncated&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{className:"lg:col-span-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"What is slowing work down?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[Object.entries(es.friction??{}).sort((Ca,Aa)=>Aa[1]-Ca[1]).slice(0,5).map(([Ca,Aa])=>{const Ia=Math.max(1,Object.values(es.friction).reduce((Ma,Pa)=>Ma+Pa,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{children:Ca.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Aa})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-amber-500",style:{width:`${Math.max(4,Aa/Ia*100)}%`}})})]},Ca)}),!is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction has been detected in analyzed sessions."})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base flex items-center gap-2",children:[jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"})," Most-used tools"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:cs.map(([Ca,Aa])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:Ca}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${Aa/Kr*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"w-10 text-right font-mono text-xs text-muted-foreground",children:Aa})]},Ca))})]})]}),ts<80&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Analysis coverage is ",ts,"%. Outcome and friction metrics reflect ",es.sessions_with_analysis," of ",es.total_sessions," sessions."]})]})}function ProjectCard({project:es,hasReport:$,activeJob:ts,onClick:is}){const cs=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.name}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[ts?jsxRuntimeExports.jsx(ProjectJobBadge,{job:ts}):$?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs bg-teal-500/10 text-teal-500 border-teal-500/20",children:"Recommendations"}):null,jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:[es.enrichedCount," enriched"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),cs&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:cs})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,cs]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(!is),className:"flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors w-full text-left cursor-pointer",children:[is?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("span",{className:ts,children:es}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",$.length,")"]})]}),is&&jsxRuntimeExports.jsx("ul",{className:"mt-1.5 ml-5 space-y-1",children:$.map((Kr,Xr)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground leading-relaxed",children:Kr},Xr))})]})}function ReleaseCard({release:es}){var Xr,Na,Ca;const $=es.categories??{features:[],fixes:[],security:[]},ts=((Xr=$.features)==null?void 0:Xr.length)??0,is=((Na=$.fixes)==null?void 0:Na.length)??0,cs=((Ca=$.security)==null?void 0:Ca.length)??0,Kr=new Date(es.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.version}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Kr})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[ts>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20",children:[ts," feature",ts!==1?"s":""]}),is>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20",children:[is," fix",is!==1?"es":""]}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[cs," security"]})]})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Features",items:$.features??[],colorClass:"text-teal-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Fixes",items:$.fixes??[],colorClass:"text-amber-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Security",items:$.security??[],colorClass:"text-red-500"}),es.url&&jsxRuntimeExports.jsx("div",{className:"pt-1 flex justify-end",children:jsxRuntimeExports.jsxs("a",{href:es.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["View release ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})})]})]})}function HarnessUpdatesTab(){const{data:es,isLoading:$}=useHarnessReleases("claude_code"),ts=useSyncHarnessReleases();return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Claude Code Releases"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Changelog from the Claude Code GitHub repository"})]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ts.mutate("claude_code"),disabled:ts.isPending,className:"cursor-pointer",children:[ts.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Sync"]})]}),ts.isSuccess&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Synced ",ts.data.synced," new release",ts.data.synced!==1?"s":""," (",ts.data.total," total checked)"]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(4)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},cs))}):!es||es.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(Package,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No releases synced yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Click Sync to fetch the latest releases from GitHub."})]})]})})}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(is=>jsxRuntimeExports.jsx(ReleaseCard,{release:is},is.id))})]})}function InsightsListPage(){const[es,$]=useTabParam(["overview","harness-updates"],"overview"),ts=useNavigate(),{data:is,isLoading:cs}=useComputedInsights(),{data:Kr}=useInsightsProjects(),Xr=useRegenerateAllInsights(),Na=useActiveInsightsJobs(),{data:Ca}=useInsightsJobs(void 0,500),Aa=(Ca??[]).filter(Ba=>Ba.status!=="cancelled"),Ia=(()=>{if(Aa.length<2)return[];const Ba=[...Aa].sort((za,Va)=>new Date(za.createdAt).getTime()-new Date(Va.createdAt).getTime());let qa=[];for(let za=0;za<Ba.length;za++){const Va=new Date(Ba[za].createdAt).getTime(),Ga=Ba.filter(Za=>new Date(Za.createdAt).getTime()-Va<12e4&&new Date(Za.createdAt).getTime()>=Va);Ga.length>qa.length&&(qa=Ga)}return qa.length<2?[]:qa})(),Ma=Ia.length>1,Pa=new Map;for(const Ba of Ia)Ba.projectPath&&!Pa.has(Ba.projectPath)&&Pa.set(Ba.projectPath,Ba);const La=new Set(Aa.filter(Ba=>Ba.status==="completed"&&Ba.projectPath).map(Ba=>Ba.projectPath)),Fa=Ba=>{if(Ba.errors.length>0&&ue$1.error(`${Ba.errors.length} project${Ba.errors.length===1?"":"s"} failed to enqueue`,{description:`${Ba.errors[0].projectPath}: ${Ba.errors[0].error}`}),Ba.created>0){ue$1.success(`Started ${Ba.created} regeneration job${Ba.created===1?"":"s"}`,Ba.noLiveWorker?{description:"No live worker — start `rulemetric evals agent` to run them."}:void 0);return}const qa=Ba.skipped.filter(Va=>Va.reason==="fresh").length,za=Ba.skipped.length-qa;qa>0?ue$1(za>0?`${qa} project${qa===1?"":"s"} fresh (<4h), ${za} skipped`:`All ${qa} project${qa===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>Xr.mutate({force:!0},{onSuccess:Fa,onError:Va=>ue$1.error("Couldn't start the regeneration",{description:Va instanceof Error?Va.message:"Please try again."})})}}):za>0?ue$1(`${za} project${za===1?"":"s"} skipped (no checkout or too few sessions)`):Ba.errors.length===0&&ue$1("No projects eligible for regeneration")};return cs?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Ba,qa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},qa))})]}):!is||is.total_sessions===0?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No sessions captured yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mx-auto mt-2",children:["Run ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric hooks install"})," in a project to start capturing Claude Code sessions. Insights will appear automatically after your next session."]})]})]})})})}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:jsxRuntimeExports.jsx(Button,{onClick:()=>Xr.mutate(void 0,{onSuccess:Fa,onError:Ba=>ue$1.error("Couldn't start the regeneration",{description:Ba instanceof Error?Ba.message:"Please try again."})}),disabled:Xr.isPending||Na.length>0,className:"cursor-pointer",children:Na.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Na.length," remaining)..."]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4"}),"Regenerate All"]})})})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:[Ma&&jsxRuntimeExports.jsx(JobTracker,{jobs:Ia}),(is==null?void 0:is.analysis_freshness)&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:is.analysis_freshness,totalAnalyzed:is.sessions_with_analysis}),jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsx(InsightsOverview,{computed:is}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts("/insights/computed"),className:"text-sm font-medium text-primary hover:underline cursor-pointer",children:"Explore detailed trends and recommendations →"}),Kr&&Kr.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono font-semibold text-muted-foreground pt-2",children:"By Project"}),Kr.filter(Ba=>Ba.sessionCount>=3).map(Ba=>{const qa=La.has(Ba.projectPath),za=Pa.get(Ba.projectPath),Va=Ba.projectId??void 0,Ga=Va?`/insights/computed?projectPath=${encodeURIComponent(Ba.projectPath)}&projectId=${encodeURIComponent(Va)}`:`/insights/computed?projectPath=${encodeURIComponent(Ba.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Ba,hasReport:qa,activeJob:za,onClick:()=>ts(Ga)},Va??Ba.projectPath)})]})]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]})}function formatUsd(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function formatTokens$1(es){return es?es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es):"0"}function Row({label:es,usd:$,detail:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground w-20 text-right",children:ts})]})]})}function CostBreakdownCard({totalUsd:es,breakdown:$,inputTokens:ts=0,outputTokens:is=0,cacheReadTokens:cs=0,cacheWriteTokens:Kr=0,byModel:Xr,byTool:Na}){const Ca=$??{inputUsd:0,outputUsd:0,cacheReadUsd:0,cacheWriteUsd:0},Aa=Xr?Object.entries(Xr).sort(([,Ma],[,Pa])=>Pa.cost_usd-Ma.cost_usd):[],Ia=Na?Object.entries(Na).sort(([,Ma],[,Pa])=>Pa.cost_usd-Ma.cost_usd):[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{children:"Estimated cost"}),jsxRuntimeExports.jsxs("span",{className:"ml-auto font-mono text-base",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground mr-1",children:"≈"}),formatUsd(es)]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Row,{label:"Input",usd:Ca.inputUsd,detail:`${formatTokens$1(ts)} tok`}),jsxRuntimeExports.jsx(Row,{label:"Output",usd:Ca.outputUsd,detail:`${formatTokens$1(is)} tok`}),jsxRuntimeExports.jsx(Row,{label:"Cache read",usd:Ca.cacheReadUsd,detail:cs>0?`${formatTokens$1(cs)} tok`:"no cache"}),jsxRuntimeExports.jsx(Row,{label:"Cache write",usd:Ca.cacheWriteUsd,detail:Kr>0?`${formatTokens$1(Kr)} tok`:"no cache"})]}),Ia.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By tool"}),Ia.map(([Ma,Pa])=>{const La=es>0?Math.round(Pa.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:displayTool(Ma)}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Pa.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[La,"%"]})]})]},Ma)})]})]}),Aa.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By model"}),Aa.map(([Ma,Pa])=>{const La=es>0?Math.round(Pa.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:Ma}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Pa.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[La,"%"]})]})]},Ma)})]})]}),jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground cursor-help",children:[jsxRuntimeExports.jsx("span",{className:"mr-1",children:"≈"}),"estimated · derived from token usage × current published rates"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:"Computed from each model's token usage × its provider's published pricing (Anthropic, OpenAI, Google, and others). May differ from actual billing by ±5% due to per-request rounding; unrecognised models fall back to a Sonnet-equivalent estimate."})})]})})]})]})}function verdictState(es){return es.sufficient?es.significant?"significant":"no-effect":(es.strataDroppedForTimeSeparation??0)>0?"no-comparable-cohort":"insufficient"}function VerdictBadge({verdict:es}){const $=`95% CI ${(es.ci.lower*100).toFixed(0)}–${(es.ci.upper*100).toFixed(0)}%`,ts=`n=${es.nWith}`,is=es.strata!=null?` · within ${es.strata} project${es.strata===1?"":"s"}`:"",cs=es.confounded?` · observational${is}`:"",Kr=verdictState(es);if(Kr==="no-comparable-cohort"){const Aa=es.strataDroppedForTimeSeparation;return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`No comparable cohort. ${Aa} project-month${Aa===1?"":"s"} held both exposed and unexposed sessions, but they're separated in time — this treatment's sessions all ran later than the ones without it, so any difference is a calendar difference, not an effect. More sessions won't resolve it; a randomised holdout would.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-amber-400 border-amber-400/40",children:"no comparable cohort"})})}if(Kr==="insufficient")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Not enough sessions to measure this yet, so no number is shown (rather than a fabricated one).${es.insufficientReason?` ${es.insufficientReason}`:""}`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"insufficient data"})});if(Kr==="no-effect")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`The with-vs-without difference isn't statistically distinguishable from zero, so we report no effect rather than noise. ${$}, ${ts}${cs}.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"no measured effect"})});const Xr=es.delta>0,Na=`${Xr?"+":""}${(es.delta*100).toFixed(0)}%`,Ca=es.pValue!=null?`, p=${es.pValue.toFixed(3)}`:"";return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Sessions with this ${Xr?"did measurably BETTER":"did measurably WORSE"} than sessions without it, and the difference is statistically significant. ${$}, ${ts}${Ca}${cs}. Observational — a correlation from real sessions, not a controlled experiment.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono shrink-0",Xr?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),children:[Na," outcome"]})})}const FRIENDLY_LABELS={debug_investigate:"Debug/Investigate",implement_feature:"Implement Feature",fix_bug:"Fix Bug",write_script_tool:"Write Script/Tool",refactor_code:"Refactor Code",configure_system:"Configure System",create_pr_commit:"Create PR/Commit",understand_codebase:"Understand Codebase",write_tests:"Write Tests",write_docs:"Write Docs",analyze_data:"Analyze Data",deploy_infra:"Deploy/Infra",warmup_minimal:"Cache Warmup",fully_achieved:"Fully Achieved",mostly_achieved:"Mostly Achieved",partially_achieved:"Partially Achieved",not_achieved:"Not Achieved",unclear_from_transcript:"Unclear",frustrated:"Frustrated",dissatisfied:"Dissatisfied",likely_satisfied:"Likely Satisfied",satisfied:"Satisfied",happy:"Happy",unsure:"Unsure",single_task:"Single Task",multi_task:"Multi Task",iterative_refinement:"Iterative Refinement",exploration:"Exploration",quick_question:"Quick Question",unhelpful:"Unhelpful",slightly_helpful:"Slightly Helpful",very_helpful:"Very Helpful",essential:"Essential",moderately_helpful:"Moderately Helpful",misunderstood_request:"Misunderstood Request",wrong_approach:"Wrong Approach",buggy_code:"Buggy Code",user_rejected_action:"User Rejected Action",excessive_changes:"Excessive Changes",wrong_file_or_location:"Wrong File/Location",slow_or_verbose:"Slow/Verbose",tool_failed:"Tool Failed",claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot_cli:"Copilot CLI",antigravity:"Antigravity",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM"};function friendlyLabel(es){return FRIENDLY_LABELS[es]||es.replace(/_/g," ").replace(/\b\w/g,$=>$.toUpperCase())}function CopyButton({text:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:async is=>{is.stopPropagation();try{await navigator.clipboard.writeText(es),ts(!0),setTimeout(()=>ts(!1),2e3)}catch{ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})}},children:$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"})})}function RunCommandButton({prompt:es,label:$="Copy"}){const[ts,is]=reactExports.useState(!1),Kr=/^(claude|rulemetric|pnpm|npm|npx|git)\s/.test(es.trim())?es.trim():`claude -p '${es.replace(/'/g,"'\\''")}'`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-teal-500/30 text-teal-600 hover:bg-teal-500/10 hover:text-teal-600",onClick:async Xr=>{Xr.stopPropagation();try{await navigator.clipboard.writeText(Kr),is(!0),setTimeout(()=>is(!1),2e3)}catch{ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})}},title:`Copy command: ${Kr.slice(0,80)}...`,children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),ts?"Copied!":$]})}function StatCard$2({icon:es,label:$,value:ts,sub:is}){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:jsxRuntimeExports.jsx(es,{className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:ts}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$}),is&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:is})]})]})})})}function HorizontalBar({items:es,maxItems:$=8,onItemClick:ts}){const is=Object.entries(es).sort(([,Kr],[,Xr])=>Xr-Kr).slice(0,$);if(is.length===0)return jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data"});const cs=is[0][1];return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:is.map(([Kr,Xr])=>jsxRuntimeExports.jsxs("div",{className:`space-y-1 ${ts?"cursor-pointer hover:bg-muted/50 rounded px-1 -mx-1 py-0.5":""}`,...ts?activatable(()=>ts(Kr)):{},children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[200px]",children:friendlyLabel(Kr)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:(Xr??0).toLocaleString()})]}),jsxRuntimeExports.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Xr/cs*100}%`}})})]},Kr))})}function HourChart({hours:es}){const $=new Array(24).fill(0);for(const is of es)$[is]++;const ts=Math.max(...$,1);return jsxRuntimeExports.jsx("div",{className:"flex items-end gap-0.5 h-20",children:$.map((is,cs)=>jsxRuntimeExports.jsx("div",{className:"flex-1 bg-primary/60 rounded-t hover:bg-primary transition-colors cursor-default",style:{height:`${is/ts*100}%`,minHeight:is>0?2:0},title:`${cs}:00 — ${is} messages`},cs))})}function formatDurationSec(es){return es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function ResponseTimeChart({histogram:es}){const $=Object.entries(es),ts=Math.max(...$.map(([,is])=>is),1);return jsxRuntimeExports.jsx("div",{className:"space-y-1.5",children:$.map(([is,cs])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-14 text-right shrink-0",children:is}),jsxRuntimeExports.jsx("div",{className:"flex-1 h-4 bg-muted rounded overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary/70 rounded transition-all",style:{width:`${cs/ts*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-8 text-right",children:cs})]},is))})}function OverviewTab({data:es}){const $=es.estimated_cost_usd??0,ts=es.truncated??!1,is=es.response_time,cs=es.parallel_sessions,Kr=es.tools_used,Xr=es.tool_error_categories??{},Na=es.total_interruptions??0,Ca=es.sessions_using_task_agent??0,Aa=es.sessions_using_mcp??0;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:MessageSquare,label:"Messages",value:(es.total_messages??0).toLocaleString(),sub:`${es.messages_per_day??0}/day avg`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Lines Changed",value:`+${(es.total_lines_added??0).toLocaleString()}`,sub:`-${(es.total_lines_removed??0).toLocaleString()} removed`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Files Modified",value:(es.total_files_modified??0).toLocaleString()}),jsxRuntimeExports.jsx(StatCard$2,{icon:ChartColumn,label:"Days Active",value:es.days_active,sub:`${es.total_sessions} sessions`}),jsxRuntimeExports.jsx(StatCard$2,{icon:GitCommitHorizontal,label:"Git Commits",value:es.git_commits,sub:`${es.git_pushes} pushes`})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[$>0&&jsxRuntimeExports.jsxs("div",{className:"md:col-span-2 space-y-2",children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:$,breakdown:es.estimated_cost_breakdown,inputTokens:es.total_input_tokens,outputTokens:es.total_output_tokens,cacheReadTokens:es.total_cache_read_tokens,cacheWriteTokens:es.total_cache_write_tokens,byModel:es.estimated_cost_by_model}),ts&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:Clock,label:"Total Hours",value:Math.round(es.total_duration_hours),sub:Na>0?`${Na} interruptions`:void 0}),Ca>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"Task Agents",value:Ca,sub:"sessions"}),Aa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"MCP Sessions",value:Aa,sub:"sessions"})]})]}),cs&&cs.events>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Parallel Sessions"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-8",children:[jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.events}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"overlap events"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.sessions_involved}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"sessions involved"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsxs("p",{className:"text-2xl font-bold font-mono",children:[es.total_sessions>0?Math.round(cs.sessions_involved/es.total_sessions*100):0,"%"]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"of sessions"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Detected when messages from different sessions overlap within 30-minute windows."})]})]}),Kr&&Object.keys(Kr).length>1&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"AI Tools Used"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Kr})})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[is&&is.total_samples>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"User Response Time Distribution"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Median: ",formatDurationSec(is.median_seconds)," · Avg: ",formatDurationSec(is.avg_seconds)," · ",is.total_samples," samples"]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ResponseTimeChart,{histogram:is.histogram})})]}),es.message_hours.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Messages by Time of Day"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx(HourChart,{hours:es.message_hours}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-1 font-mono",children:[jsxRuntimeExports.jsx("span",{children:"0:00"}),jsxRuntimeExports.jsx("span",{children:"6:00"}),jsxRuntimeExports.jsx("span",{children:"12:00"}),jsxRuntimeExports.jsx("span",{children:"18:00"}),jsxRuntimeExports.jsx("span",{children:"23:00"})]})]})]})]}),Object.keys(Xr).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-red-500"}),"Tool Error Encounters"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Xr})})]})]})}function ToolsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Tool Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.tool_counts,maxItems:12})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Languages"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.languages})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Feature Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[{label:"Task Agents",value:es.sessions_using_task_agent},{label:"MCP Servers",value:es.sessions_using_mcp}].map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-sm",children:$.label}),jsxRuntimeExports.jsxs(Badge,{variant:$.value>0?"default":"outline",children:[$.value," sessions"]})]},$.label))})})]})]})}function QualityTab({data:es}){const $=useNavigate(),ts=[{key:"goal_categories",title:"Goal Categories",items:es.goal_categories??{}},{key:"outcomes",title:"Outcomes",items:es.outcomes??{},onClick:is=>$(`/sessions?outcome=${is}`)},{key:"satisfaction",title:"User Satisfaction",items:es.satisfaction??{}},{key:"session_types",title:"Session Types",items:es.session_types??{}},{key:"friction",title:"Friction Points",items:es.friction??{},icon:TriangleAlert,onClick:is=>$(`/sessions?friction=${is}`)}].filter(is=>Object.keys(is.items).length>0);return ts.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No quality data yet. Session analysis runs automatically on your local worker — make sure ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rulemetric evals agent"})," is running, then use Generate Recommendations to analyze recent sessions."]})})}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:ts.map(is=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:is.title})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:is.items,onItemClick:is.onClick})})]},is.key))})}function SessionsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[Object.keys(es.projects).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Projects (",Object.keys(es.projects).length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.projects})})]}),es.session_summaries.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Sessions with Analysis (",es.session_summaries.length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:es.session_summaries.map($=>{const ts=$.id.length===36&&$.id.includes("-"),is=jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-3 rounded-lg border border-border bg-background p-3 ${ts?"hover:border-primary/50 cursor-pointer":""}`,children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:$.date}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-sm truncate",children:$.summary||$.goal||"No summary"}),$.goal&&$.summary&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:$.goal}),"outcome"in $&&$.outcome&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-1 text-[10px]",children:friendlyLabel($.outcome)})]})]});return ts?jsxRuntimeExports.jsx(Link,{to:`/sessions/${$.id}`,children:is},$.id):jsxRuntimeExports.jsx("div",{children:is},$.id)})})})]})]})}function RecommendationsTab({rec:es,projectPath:$,autoAddAvailable:ts}){var Xr,Na,Ca,Aa,Ia,Ma;const is=useAutoAddSuggestion(),[cs,Kr]=reactExports.useState(new Set);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[es.at_a_glance&&jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30 bg-amber-500/5",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-amber-500"}),"At a Glance"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Object.entries(es.at_a_glance).map(([Pa,La])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1",children:Pa.replace(/_/g," ")}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:La})]},Pa))})]}),((Xr=es.what_works)==null?void 0:Xr.impressive_workflows)&&es.what_works.impressive_workflows.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Impressive Things You Did"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.what_works.impressive_workflows.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.description})]},La))})]}),((Na=es.friction_analysis)==null?void 0:Na.categories)&&es.friction_analysis.categories.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-amber-500"}),"Where Things Go Wrong"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.friction_analysis.categories.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.category}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.description}),Pa.examples.length>0&&jsxRuntimeExports.jsx("ul",{className:"mt-2 space-y-1",children:Pa.examples.map((Fa,Ba)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground pl-3 border-l-2 border-border",children:Fa},Ba))})]},La))})]}),((Ca=es.suggestions)==null?void 0:Ca.features_to_try)&&es.suggestions.features_to_try.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.features_to_try.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.feature}),Pa.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.example_code}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.why_for_you}),Pa.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.example_code})]},La))})]}),((Aa=es.suggestions)==null?void 0:Aa.claude_md_additions)&&es.suggestions.claude_md_additions.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Suggested CLAUDE.md Additions"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.claude_md_additions.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:Pa.addition}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(CopyButton,{text:Pa.addition}),$&&ts&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",disabled:cs.has(La)||is.isPending,onClick:Fa=>{Fa.stopPropagation(),is.mutate({projectPath:$,addition:Pa.addition,why:Pa.why},{onSuccess:Ba=>{(Ba.success||Ba.reason==="already_present")&&Kr(qa=>new Set(qa).add(La))},onError:Ba=>{const qa=Ba instanceof ApiError&&(Ba.code==="not_local_mode"||Ba.statusCode===501);ue$1.error(qa?"Add to CLAUDE.md only works when the API runs on your machine (local mode) — use the copy button instead.":Ba instanceof Error?Ba.message:"Failed to update CLAUDE.md")}})},children:is.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):cs.has(La)?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-teal-500"}):jsxRuntimeExports.jsx(Upload,{className:"h-3 w-3"})})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Pa.why}),cs.has(La)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500 mt-1",children:"Added to CLAUDE.md"})]},La))})]}),((Ia=es.suggestions)==null?void 0:Ia.usage_patterns)&&es.suggestions.usage_patterns.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.usage_patterns.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),Pa.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.suggestion}),Pa.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.copyable_prompt})]},La))})]}),((Ma=es.on_the_horizon)==null?void 0:Ma.opportunities)&&es.on_the_horizon.opportunities.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.on_the_horizon.opportunities.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),Pa.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.whats_possible}),Pa.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.copyable_prompt})]},La))})]}),es.fun_ending&&jsxRuntimeExports.jsx(Card,{className:"border-pink-500/20 bg-pink-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:es.fun_ending.headline}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:es.fun_ending.detail})]})})]})}function ScorePair({label:es,withVal:$,withoutVal:ts,delta:is,unit:cs,inverted:Kr}){const Xr=Aa=>Aa!=null?`${Aa}${cs}`:"—",Na=is!=null&&is!==0?(Kr?is<0:is>0)?"text-teal-500":"text-red-500":"text-muted-foreground",Ca=is!=null&&is>0?"+":"";return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Xr($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"vs"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:Xr(ts)})]}),is!=null&&is!==0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:`text-[10px] mt-1 ${Na} ${(Kr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Ca,is,cs]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Kr=>Kr.verdict.sufficient),cs=ts.length-is.length;return is.length===0&&cs===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:es}),is.map(Kr=>{const Xr=Kr.verdict,Na=Xr.delta>0,Ca=Xr.significant?`${Na?"+":""}${(Xr.delta*100).toFixed(0)}%`:"no effect",Aa=Xr.significant?Na?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40":"text-muted-foreground",Ia=`95% CI ${(Xr.ci.lower*100).toFixed(0)}–${(Xr.ci.upper*100).toFixed(0)}%, n=${Xr.nWith} exposed / ${Xr.nWithout} unexposed (observational)`;return jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono",Aa),title:Ia,children:[Kr.label," ",Ca]},Kr.label)}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`Not enough exposed + unexposed sessions within a project to measure ${cs===1?`this ${$}`:`these ${$}s`} yet.`,children:[cs," ",$,cs===1?"":"s",": insufficient"]})]})}function SegmentBreakdown({impact:es}){const $=(es.segments??[]).map(is=>({label:is.model,verdict:is.verdict})),ts=(es.harnessSegments??[]).map(is=>({label:is.harness,verdict:is.verdict}));return $.length===0&&ts.length===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t",children:[jsxRuntimeExports.jsx(SegmentLine,{title:"By model:",noun:"model",segments:$}),jsxRuntimeExports.jsx(SegmentLine,{title:"By harness:",noun:"harness",segments:ts})]})}function ImpactCard({impact:es,linkedSessions:$}){const ts=es.with,is=es.without,cs=es.comparison;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono truncate",children:es.instructionName}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[es.autoAdded&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40",title:`Auto-added from a recommendation${es.autoAdded.count>1?` ×${es.autoAdded.count}`:""}`+(es.autoAdded.lastAssignedAt?` (last ${new Date(es.autoAdded.lastAssignedAt).toLocaleDateString()})`:"")+" — the verdict beside this is whether it helped.",children:["auto-added",es.autoAdded.count>1?` ×${es.autoAdded.count}`:""]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict}),$!=null&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:[$," sessions"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:"Sessions"}),jsxRuntimeExports.jsxs("p",{className:"font-mono",children:[ts.sessionCount," with / ",is.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[ts.enrichedCount," / ",is.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:ts.avgOutcomeScore,withoutVal:is.avgOutcomeScore,delta:cs.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:ts.avgToolErrors,withoutVal:is.avgToolErrors,delta:cs.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:ts.avgDurationMinutes,withoutVal:is.avgDurationMinutes,delta:cs.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$}){const{data:ts,isLoading:is}=useInstructionImpact(es);return is?jsxRuntimeExports.jsx(Skeleton,{className:"h-24"}):!ts||ts.with.sessionCount===0&&ts.without.sessionCount===0?null:jsxRuntimeExports.jsx(ImpactCard,{impact:ts,linkedSessions:$})}function GroomingCard(){const{data:es,isLoading:$}=useGroomCandidates(),ts=useArchiveInstruction(),[is,cs]=reactExports.useState(new Set);if($||!es)return null;if(!es.captureHealthy)return jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Grooming paused"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.reason})})]});const Kr=es.harmful??[],Xr=es.candidates.length+Kr.length;if(Xr===0)return null;const Na=Aa=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:is.has(Aa)||ts.isPending,onClick:()=>ts.mutate(Aa,{onSuccess:()=>{cs(Ia=>new Set(Ia).add(Aa)),ue$1.success("Archived — reversible from the instruction")},onError:()=>ue$1.error("Archive failed")}),children:is.has(Aa)?"Archived":"Archive"}),Ca=es.safetyGuarded+(es.harmfulSafetyGuarded??0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm",children:["Retirement candidates (",Xr,")"]}),Ca>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Safety / destructive-guardrail rules are never proposed for retirement, however rarely they fire or however they score.",children:[Ca," safety rule",Ca===1?"":"s"," protected"]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Your own instructions worth a second look. Archiving is reversible; safety rules are never listed here."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Kr.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-red-400/90 mb-0.5",children:"Measurably worse outcomes"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Present in sessions that scored significantly lower. Correlational, not proven cause — the rule may just ride along with harder tasks — so review before retiring; the verdict beside each shows the effect."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Kr.map(Aa=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:Aa.name,children:Aa.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:Aa.verdict})]}),Na(Aa.id)]},Aa.id))})]}),es.candidates.length>0&&jsxRuntimeExports.jsxs("div",{children:[Kr.length>0&&jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"No recent use"}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:es.candidates.map(Aa=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:Aa.name,children:Aa.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:Aa.reason})]}),Na(Aa.id)]},Aa.id))})]})]})]})}function InstructionsTab({projectFilter:es}){const{data:$,isLoading:ts}=useLinkedInstructions(es);return ts?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(3)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},cs))}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(GroomingCard,{}),!$||$.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No instructions linked to sessions yet. Instructions are auto-captured from context snapshots — the session-end hook snapshots your on-disk CLAUDE.md files, and the proxy additionally captures runtime-rendered prompts and skills."})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions linked to sessions, ranked by usage. Comparing sessions with vs. without each instruction."}),$.map(is=>jsxRuntimeExports.jsx(InstructionImpactLoader,{instructionId:is.id,linkedSessions:is.linkedSessions},is.id))]})]})}function InsightsDetailPage(){const{id:es}=useParams(),[$]=useSearchParams(),ts=es==="computed",is=ts?$.get("projectPath")??$.get("project")??void 0:void 0,cs=ts?$.get("projectId")??void 0:void 0,[Kr,Xr]=reactExports.useState(""),{data:Na,recommendations:Ca,isLoading:Aa,fullProjectPath:Ia,title:Ma,subtitle:Pa,lastCompletedJob:La,activeJobs:Fa,createJob:Ba}=useProjectInsights(es,is,cs,Kr||void 0),[qa,za]=useTabParam(["overview","tools","quality","sessions","instructions","recommendations"],"overview");if(Aa)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((Qa,Xa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Xa))})]});if(!Na)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Report not found."})]});const Va=ts?Na.tools_used??{}:{},Ga=Object.keys(Va).sort((Qa,Xa)=>(Va[Xa]??0)-(Va[Qa]??0)),Za=Na.autoAddAvailable!==!1;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:Ma}),ts&&(Ga.length>1||Kr)&&jsxRuntimeExports.jsxs("select",{value:Kr,onChange:Qa=>Xr(Qa.target.value),className:"h-8 rounded-md border border-input bg-background px-2 text-xs font-mono cursor-pointer focus:outline-none focus:ring-1 focus:ring-ring",children:[jsxRuntimeExports.jsx("option",{value:"",children:"All Tools"}),Ga.map(Qa=>jsxRuntimeExports.jsxs("option",{value:Qa,children:[displayTool(Qa)," (",Va[Qa],")"]},Qa)),Kr&&!Ga.includes(Kr)&&jsxRuntimeExports.jsx("option",{value:Kr,children:displayTool(Kr)})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Pa}),ts&&Ga.length>0&&!Kr&&jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:Ga.map(Qa=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Xr(Qa),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Qa),": ",Va[Qa]]})},Qa))})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[La&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last generated ",new Date(La.completedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Ba.mutate(Ia??is,{onSuccess:Qa=>{Qa.noLiveWorker?ue$1.warning("Queued, but no worker is listening",{description:"Start one with `rulemetric evals agent` (or `rulemetric service install --worker-only`) and it will pick this up."}):ue$1.success("Generating recommendations…")},onError:Qa=>ue$1.error("Couldn't start the run",{description:Qa instanceof Error?Qa.message:"Please try again."})}),disabled:Ba.isPending||Fa.length>0,variant:"outline",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),Fa.length>0?`Generating — ${jobStepLabel(Fa[0])}`:Ca?"Refresh Recommendations":"Generate Recommendations"]})]})]}),ts&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:Na.analysis_freshness,totalAnalyzed:Na.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),Fa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:Fa}),jsxRuntimeExports.jsxs(Tabs,{value:qa,onValueChange:za,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"mr-2 h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"tools",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Tools"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"quality",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Quality"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"sessions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"mr-2 h-4 w-4"}),"Sessions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"instructions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"mr-2 h-4 w-4"}),"Instructions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"recommendations",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),"Recommendations"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-6",children:jsxRuntimeExports.jsx(OverviewTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"instructions",className:"mt-6",children:jsxRuntimeExports.jsx(InstructionsTab,{projectFilter:is})}),jsxRuntimeExports.jsx(TabsContent,{value:"recommendations",className:"mt-6",children:Ca?jsxRuntimeExports.jsx(RecommendationsTab,{rec:Ca,projectPath:Ia,autoAddAvailable:Za}):jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Fa.length>0?`Generating recommendations — ${jobStepLabel(Fa[0])}`:'No recommendations yet. Use "Generate Recommendations" above to analyze this project’s sessions.'})})})})]})]})}const MEMORY_PAGE_SIZE=50;function useMemories(es="active",$="",ts="all"){return useInfiniteQuery({queryKey:["memories",{status:es,search:$,kind:ts}],initialPageParam:0,queryFn:({pageParam:is})=>{const cs=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&cs.set("search",$),ts&&ts!=="all"&&cs.set("kind",ts),apiGet(`/api/memories?${cs.toString()}`).then(Kr=>Kr.memories)},getNextPageParam:(is,cs)=>is.length<MEMORY_PAGE_SIZE?void 0:cs.length*MEMORY_PAGE_SIZE})}function useMemory(es){return useQuery({queryKey:["memories",es],queryFn:()=>apiGet(`/api/memories/${es}`),enabled:!!es})}function useMemoryImpact(es){return useQuery({queryKey:["insights","memory-impact",es],queryFn:()=>apiGet(`/api/insights/memory-impact?memoryId=${es}`),enabled:!!es})}function useMemoryExperiments(es){return useQuery({queryKey:["memories",es,"experiments"],queryFn:()=>apiGet(`/api/memories/${es}/experiments`),enabled:!!es,select:$=>$.experiments,refetchInterval:$=>{var is;return(((is=$.state.data)==null?void 0:is.experiments)??[]).some(cs=>cs.status==="pending"||cs.status==="running")?5e3:!1}})}function useCreateExperiment(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/memories/${es}/experiments`,ts),onSuccess:()=>$.invalidateQueries({queryKey:["memories",es,"experiments"]})})}function useCreateMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/memories",$),onSuccess:()=>es.invalidateQueries({queryKey:["memories"]})})}function useUpdateMemory(){const es=useQueryClient();return useMutation({mutationFn:({id:$,...ts})=>apiPatch(`/api/memories/${$}`,ts),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts.id]})}})}function useArchiveMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/memories/${$}`),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts]})}})}const KINDS=["fact","decision","correction","convention"];function MemoryFormDialog({open:es,onOpenChange:$,memory:ts}){const is=!!ts,cs=useCreateMemory(),Kr=useUpdateMemory(),[Xr,Na]=reactExports.useState("fact"),[Ca,Aa]=reactExports.useState(""),[Ia,Ma]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Na((ts==null?void 0:ts.kind)??"fact"),Aa((ts==null?void 0:ts.title)??""),Ma((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Pa=cs.isPending||Kr.isPending,La=Ca.trim().length>0&&Ia.trim().length>0&&!Pa,Fa=()=>{if(!La)return;const Ba=za=>()=>{ue$1.success(`Memory ${za}`),$(!1)},qa=za=>ue$1.error(za instanceof Error?za.message:"Something went wrong");is?Kr.mutate({id:ts.id,kind:Xr,title:Ca.trim(),body:Ia.trim()},{onSuccess:Ba("updated"),onError:qa}):cs.mutate({kind:Xr,title:Ca.trim(),body:Ia.trim()},{onSuccess:Ba("created"),onError:qa})};return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:is?"Edit memory":"New memory"}),jsxRuntimeExports.jsx(DialogDescription,{children:"A durable note the session-start hook injects into future sessions as context. Its measured effect is tracked automatically."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Kind"}),jsxRuntimeExports.jsxs(Select,{value:Xr,onValueChange:Ba=>Na(Ba),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsx(SelectContent,{children:KINDS.map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba,className:"capitalize",children:Ba},Ba))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Title"}),jsxRuntimeExports.jsx(Input,{value:Ca,onChange:Ba=>Aa(Ba.target.value),placeholder:"Short, memorable summary",maxLength:300})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:Ba=>Ma(Ba.target.value),placeholder:"The fact / decision / correction / convention to remember.",rows:5})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:Fa,disabled:!La,className:"cursor-pointer",children:Pa?"Saving…":is?"Save changes":"Create"})]})]})})}const kindColors={fact:"bg-blue-500/15 text-blue-400 border-blue-500/30",decision:"bg-primary/15 text-primary border-primary/30",correction:"bg-red-500/15 text-red-400 border-red-500/30",convention:"bg-pink-500/15 text-pink-400 border-pink-500/30"};function useDebouncedValue(es,$){const[ts,is]=reactExports.useState(es);return reactExports.useEffect(()=>{const cs=setTimeout(()=>is(es),$);return()=>clearTimeout(cs)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState("all"),[Xr,Na]=reactExports.useState(!1),Ca=useNavigate(),Aa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:Ma,error:Pa,hasNextPage:La,fetchNextPage:Fa,isFetchingNextPage:Ba}=useMemories(es,Aa,cs),qa=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),za=Aa!==""||cs!=="all";if(Pa)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Pa.message]});const Va=es!=="active";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative min-w-40 flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search memories...",value:ts,onChange:Ga=>is(Ga.target.value),className:"pl-9 bg-background border-border"})]}),jsxRuntimeExports.jsxs(Select,{value:cs,onValueChange:Kr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-36 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All kinds"}),jsxRuntimeExports.jsx(SelectItem,{value:"fact",children:"Fact"}),jsxRuntimeExports.jsx(SelectItem,{value:"decision",children:"Decision"}),jsxRuntimeExports.jsx(SelectItem,{value:"correction",children:"Correction"}),jsxRuntimeExports.jsx(SelectItem,{value:"convention",children:"Convention"})]})]}),jsxRuntimeExports.jsxs(Select,{value:es,onValueChange:Ga=>$(Ga),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-32 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"active",children:"Active"}),jsxRuntimeExports.jsx(SelectItem,{value:"archived",children:"Archived"}),jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All"})]})]}),jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),Ma?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Ga,Za)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Za))}):qa.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12",children:[jsxRuntimeExports.jsx(Brain,{className:"mx-auto h-8 w-8 text-muted-foreground/40 mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-4",children:za?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!za&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create memory"]})]}):jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-transparent",children:[jsxRuntimeExports.jsx(TableHead,{children:"Title"}),jsxRuntimeExports.jsx(TableHead,{children:"Kind"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden md:table-cell",children:"Scope"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden lg:table-cell",children:"Source"}),Va&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:qa.map(Ga=>jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-secondary/50 transition-colors duration-200 cursor-pointer",onClick:()=>Ca(`/memories/${Ga.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium max-w-md truncate",children:Ga.title}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[Ga.kind]}`,children:Ga.kind})}),jsxRuntimeExports.jsx(TableCell,{className:"hidden md:table-cell text-xs text-muted-foreground",children:Ga.projectId?"Project":"Global"}),jsxRuntimeExports.jsx(TableCell,{className:"hidden lg:table-cell text-xs text-muted-foreground",children:Ga.source}),Va&&jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs capitalize text-muted-foreground",children:Ga.status})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-xs text-muted-foreground",children:formatDistanceToNow(Ga.updatedAt)})]},Ga.id))})]})}),La&&jsxRuntimeExports.jsx("div",{className:"flex justify-center",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",disabled:Ba,onClick:()=>Fa(),children:Ba?"Loading…":"Load more"})}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:Xr,onOpenChange:Na})]})}function MemoriesListPage(){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Memories"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Durable project facts your agent recalls — injected at session start, and measured for whether they actually help."})]}),jsxRuntimeExports.jsx(MemoryList,{})]})}function ExperimentRow({exp:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-mono truncate",title:es.taskPrompt,children:es.taskPrompt}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["v",es.memoryVersion," · ",es.trials," trials · ",formatDistanceToNow(es.createdAt)]}),es.status==="failed"&&es.error&&jsxRuntimeExports.jsx("p",{className:"text-[10px] text-red-400 mt-0.5",title:es.error,children:es.error})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&es.result?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["n=",es.result.completedTrials]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.result.verdict})]}):es.status==="failed"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:"failed"}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] text-muted-foreground gap-1",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),es.status==="running"?"running":"queued"]})})]})}function MemoryExperiments({memoryId:es}){const{data:$,isLoading:ts}=useMemoryExperiments(es),is=useCreateExperiment(es),[cs,Kr]=reactExports.useState(!1),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(""),[Ia,Ma]=reactExports.useState(10);function Pa(){const La=Ca.split(`
948
+ rulemetric capture scope --off`}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"One honest caveat: the optional mitmproxy network-capture chain is governed by its host allowlist, not by these scopes. Hooks-first capture (the default) is fully governed."})]})})})]})}function DocsPage(){const[es,$]=useTabParam(["getting-started","cli","api","evals","proxy","insights","data"],"getting-started");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Documentation"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Guides, CLI reference, API reference, and system documentation"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"getting-started",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(BookOpen,{className:"mr-2 h-4 w-4"}),"Quick Start"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"cli",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"CLI Reference"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"api",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(CodeXml,{className:"mr-2 h-4 w-4"}),"API Reference"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"evals",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mr-2 h-4 w-4"}),"Eval System"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"proxy",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Radio,{className:"mr-2 h-4 w-4"}),"Proxy & Context"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"insights",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Insights"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"data",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ShieldCheck,{className:"mr-2 h-4 w-4"}),"Data & Retention"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"getting-started",className:"mt-6",children:jsxRuntimeExports.jsx(QuickStartTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"cli",className:"mt-6",children:jsxRuntimeExports.jsx(CLIReferenceTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"api",className:"mt-6",children:jsxRuntimeExports.jsx(APIReferenceTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"evals",className:"mt-6",children:jsxRuntimeExports.jsx(EvalSystemTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"proxy",className:"mt-6",children:jsxRuntimeExports.jsx(ProxyContextTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"insights",className:"mt-6",children:jsxRuntimeExports.jsx(InsightsTab,{})}),jsxRuntimeExports.jsx(TabsContent,{value:"data",className:"mt-6",children:jsxRuntimeExports.jsx(DataRetentionTab,{})})]})]})}function useHarnessReleases(es,$=50){const ts=new URLSearchParams;return ts.set("harness",es),ts.set("limit",String($)),useQuery({queryKey:["harness-releases",es,$],queryFn:()=>apiGet(`/api/harness-releases?${ts}`)})}function useSyncHarnessReleases(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/harness-releases/sync",{harness:$}),onSuccess:()=>es.invalidateQueries({queryKey:["harness-releases"]})})}function AnalysisFreshnessBanner({freshness:es,totalAnalyzed:$}){if(!es||$===0)return null;const{with_timestamp:ts,pre_instrumentation:is,stale_30d:cs,oldest_analyzed_at:Kr}=es,Xr=$>0?Math.round(is/$*100):0,Na=ts>0?Math.round(cs/ts*100):0;if(is===0&&cs===0)return null;const Ca=Xr>=25||Na>=50?"warn":"info",Aa=Ca==="warn"?"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-border bg-muted/40 text-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-2 rounded-md border px-3 py-2 text-xs ${Aa}`,children:[Ca==="warn"?jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 mt-0.5"}):jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 mt-0.5"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 font-mono space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:Ca==="warn"?"Some inputs to these stats are stale or untimestamped":"Input freshness"}),jsxRuntimeExports.jsxs("p",{children:[is>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is," of ",$," analyzed sessions (",Xr,"%) predate timestamp tracking. Re-analyze them to participate in freshness checks."]}),is>0&&cs>0&&" ",cs>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs," of ",ts," timestamped analyses (",Na,"%) are over 30 days old",Kr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(oldest: ",new Date(Kr).toLocaleDateString(),")"]}),"."]})]})]})]})}function jobStepLabel(es){const $=es.progress;return $!=null&&$.step&&($!=null&&$.current)&&($!=null&&$.total)?`${$.step} (${$.current}/${$.total})`:$!=null&&$.step?$.step:es.status==="claimed"?"starting...":es.status==="pending"?"queued":es.status}function JobStatusIcon({status:es}){switch(es){case"completed":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"});case"running":case"claimed":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3.5 w-3.5 text-blue-500 animate-spin shrink-0"});case"failed":return jsxRuntimeExports.jsx(CircleX,{className:"h-3.5 w-3.5 text-red-500 shrink-0"});case"pending":default:return jsxRuntimeExports.jsx(CircleDashed,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})}}function JobTracker({jobs:es}){if(es.length===0)return null;const $=es.filter(Ma=>Ma.status==="completed").length,ts=es.filter(Ma=>Ma.status==="failed").length,is=es.filter(Ma=>Ma.status==="running"||Ma.status==="claimed").length,cs=es.filter(Ma=>Ma.status==="pending").length,Kr=es.length,Xr=$+ts,Na=Xr===Kr,Ca=$/Kr*100,Aa=ts/Kr*100,Ia=is/Kr*100;return jsxRuntimeExports.jsx(Card,{className:Na?"border-teal-500/30 bg-teal-500/5":"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-4 pb-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[Na?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-blue-500"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Na?Kr===1?"Recommendations ready":`All ${Kr} projects done`:Kr===1?`Generating recommendations — ${jobStepLabel(es[0])}`:`Generating recommendations — ${Xr}/${Kr} complete`})]}),Kr>1&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground font-mono",children:[$>0&&jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[$," done"]}),is>0&&jsxRuntimeExports.jsxs("span",{className:"text-blue-500",children:[is," running"]}),cs>0&&jsxRuntimeExports.jsxs("span",{children:[cs," queued"]}),ts>0&&jsxRuntimeExports.jsxs("span",{className:"text-red-500",children:[ts," failed"]})]})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden flex",children:Kr===1?(()=>{const Ma=es[0],Pa=Ma.progress,La=Pa!=null&&Pa.current&&(Pa!=null&&Pa.total)?Pa.current/Pa.total*100:0;return Ma.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):Ma.status==="failed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500",style:{width:"100%"}}):jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Math.max(La,5)}%`}})})():jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ca>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500 transition-all duration-500",style:{width:`${Ca}%`}}),Aa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500 transition-all duration-500",style:{width:`${Aa}%`}}),Ia>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Ia}%`}})]})}),Kr>1&&jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-1",children:es.map(Ma=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs py-0.5",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:Ma.status}),jsxRuntimeExports.jsx("span",{className:"font-mono truncate",children:Ma.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:Ma.status==="running"||Ma.status==="claimed"?jobStepLabel(Ma):Ma.status==="failed"?"error":Ma.status==="completed"?"done":"queued"})]},Ma.id))})]})})}function ProjectJobBadge({job:es}){return es.status==="completed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"mr-1 h-2.5 w-2.5"})," done"]}):es.status==="failed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleX,{className:"mr-1 h-2.5 w-2.5"})," failed"]}):es.status==="running"||es.status==="claimed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-500 border-blue-500/20 font-mono",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-2.5 w-2.5 animate-spin"})," ",jobStepLabel(es)]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleDashed,{className:"mr-1 h-2.5 w-2.5"})," queued"]})}function WorkerOfflineBanner(){const{workers:es,isLoading:$}=useWorkerStatus("cli-worker");if($)return null;const ts=es.slice().sort((Kr,Xr)=>new Date(Xr.lastHeartbeat).getTime()-new Date(Kr.lastHeartbeat).getTime())[0];if((ts==null?void 0:ts.status)==="active")return null;const cs=ts?`${Math.round((Date.now()-new Date(ts.lastHeartbeat).getTime())/1e3)}s ago`:"never";return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsx("div",{className:"font-medium text-amber-500 mb-1",children:"Worker offline"}),jsxRuntimeExports.jsxs("div",{className:"text-muted-foreground",children:["No cli-worker has heartbeat'd within the last 60s (last seen: ",cs,"). Insights jobs will queue but won't run until the worker is healthy. Restart with"," ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"launchctl kickstart -k gui/$UID/com.rulemetric.worker"}),"."]})]})}function formatCompact(es){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(es)}function parseTimestamp(es){if(!es)return null;const $=es.replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),ts=new Date($);return Number.isNaN(ts.getTime())?null:ts}function formatSessionRange(es,$){const ts=parseTimestamp(es),is=parseTimestamp($),cs={month:"short",day:"numeric",year:"numeric"};if(ts&&is){const Xr=ts.getFullYear()===is.getFullYear();return`${ts.toLocaleDateString(void 0,Xr?{month:"short",day:"numeric"}:cs)} – ${is.toLocaleDateString(void 0,cs)}`}const Kr=ts??is;return Kr?Kr.toLocaleDateString(void 0,cs):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,cs)=>is+cs,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Na;const $=outcomeScore(es.outcomes??{}),ts=es.total_sessions?Math.round(es.sessions_with_analysis/es.total_sessions*100):0,is=Object.entries(es.friction??{}).sort((Ca,Aa)=>Aa[1]-Ca[1])[0],cs=Object.entries(es.tool_counts??{}).sort((Ca,Aa)=>Aa[1]-Ca[1]).slice(0,5),Kr=((Na=cs[0])==null?void 0:Na[1])??1,Xr=[{label:"Successful outcomes",value:$==null?"—":`${$}%`,detail:`${es.sessions_with_analysis} analyzed`,icon:CircleCheck},{label:"Estimated spend",value:`$${(es.estimated_cost_usd??0).toFixed(2)}`,detail:`${formatCompact(es.total_input_tokens+es.total_output_tokens)} tokens`,icon:DollarSign},{label:"Tool errors",value:es.total_tool_errors.toLocaleString(),detail:`${es.total_interruptions} interruptions`,icon:TriangleAlert},{label:"Code changed",value:`+${formatCompact(es.total_lines_added)}`,detail:`${formatCompact(es.total_lines_removed)} removed · ${es.git_commits} commits`,icon:TrendingUp}];return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:Xr.map(({label:Ca,value:Aa,detail:Ia,icon:Ma})=>jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",children:Ca}),jsxRuntimeExports.jsx(Ma,{className:"h-4 w-4"})]}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-2xl font-mono font-semibold",children:Aa}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Ia})]})},Ca))}),es.truncated&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{className:"lg:col-span-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"What is slowing work down?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[Object.entries(es.friction??{}).sort((Ca,Aa)=>Aa[1]-Ca[1]).slice(0,5).map(([Ca,Aa])=>{const Ia=Math.max(1,Object.values(es.friction).reduce((Ma,Pa)=>Ma+Pa,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{children:Ca.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Aa})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-amber-500",style:{width:`${Math.max(4,Aa/Ia*100)}%`}})})]},Ca)}),!is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction has been detected in analyzed sessions."})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base flex items-center gap-2",children:[jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"})," Most-used tools"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:cs.map(([Ca,Aa])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:Ca}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${Aa/Kr*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"w-10 text-right font-mono text-xs text-muted-foreground",children:Aa})]},Ca))})]})]}),ts<80&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Analysis coverage is ",ts,"%. Outcome and friction metrics reflect ",es.sessions_with_analysis," of ",es.total_sessions," sessions."]})]})}function ProjectCard({project:es,hasReport:$,activeJob:ts,onClick:is}){const cs=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.name}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[ts?jsxRuntimeExports.jsx(ProjectJobBadge,{job:ts}):$?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs bg-teal-500/10 text-teal-500 border-teal-500/20",children:"Recommendations"}):null,jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:[es.enrichedCount," enriched"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),cs&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:cs})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,cs]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(!is),className:"flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors w-full text-left cursor-pointer",children:[is?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("span",{className:ts,children:es}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",$.length,")"]})]}),is&&jsxRuntimeExports.jsx("ul",{className:"mt-1.5 ml-5 space-y-1",children:$.map((Kr,Xr)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground leading-relaxed",children:Kr},Xr))})]})}function ReleaseCard({release:es}){var Xr,Na,Ca;const $=es.categories??{features:[],fixes:[],security:[]},ts=((Xr=$.features)==null?void 0:Xr.length)??0,is=((Na=$.fixes)==null?void 0:Na.length)??0,cs=((Ca=$.security)==null?void 0:Ca.length)??0,Kr=new Date(es.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.version}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Kr})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[ts>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20",children:[ts," feature",ts!==1?"s":""]}),is>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20",children:[is," fix",is!==1?"es":""]}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[cs," security"]})]})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Features",items:$.features??[],colorClass:"text-teal-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Fixes",items:$.fixes??[],colorClass:"text-amber-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Security",items:$.security??[],colorClass:"text-red-500"}),es.url&&jsxRuntimeExports.jsx("div",{className:"pt-1 flex justify-end",children:jsxRuntimeExports.jsxs("a",{href:es.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["View release ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})})]})]})}function HarnessUpdatesTab(){const{data:es,isLoading:$}=useHarnessReleases("claude_code"),ts=useSyncHarnessReleases();return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Claude Code Releases"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Changelog from the Claude Code GitHub repository"})]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ts.mutate("claude_code"),disabled:ts.isPending,className:"cursor-pointer",children:[ts.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Sync"]})]}),ts.isSuccess&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Synced ",ts.data.synced," new release",ts.data.synced!==1?"s":""," (",ts.data.total," total checked)"]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(4)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},cs))}):!es||es.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(Package,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No releases synced yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Click Sync to fetch the latest releases from GitHub."})]})]})})}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(is=>jsxRuntimeExports.jsx(ReleaseCard,{release:is},is.id))})]})}function InsightsListPage(){const[es,$]=useTabParam(["overview","harness-updates"],"overview"),ts=useNavigate(),{data:is,isLoading:cs}=useComputedInsights(),{data:Kr}=useInsightsProjects(),Xr=useRegenerateAllInsights(),Na=useActiveInsightsJobs(),{data:Ca}=useInsightsJobs(void 0,500),Aa=(Ca??[]).filter(Ba=>Ba.status!=="cancelled"),Ia=(()=>{if(Aa.length<2)return[];const Ba=[...Aa].sort((za,Va)=>new Date(za.createdAt).getTime()-new Date(Va.createdAt).getTime());let qa=[];for(let za=0;za<Ba.length;za++){const Va=new Date(Ba[za].createdAt).getTime(),Ga=Ba.filter(Za=>new Date(Za.createdAt).getTime()-Va<12e4&&new Date(Za.createdAt).getTime()>=Va);Ga.length>qa.length&&(qa=Ga)}return qa.length<2?[]:qa})(),Ma=Ia.length>1,Pa=new Map;for(const Ba of Ia)Ba.projectPath&&!Pa.has(Ba.projectPath)&&Pa.set(Ba.projectPath,Ba);const La=new Set(Aa.filter(Ba=>Ba.status==="completed"&&Ba.projectPath).map(Ba=>Ba.projectPath)),Fa=Ba=>{if(Ba.errors.length>0&&ue$1.error(`${Ba.errors.length} project${Ba.errors.length===1?"":"s"} failed to enqueue`,{description:`${Ba.errors[0].projectPath}: ${Ba.errors[0].error}`}),Ba.created>0){ue$1.success(`Started ${Ba.created} regeneration job${Ba.created===1?"":"s"}`,Ba.noLiveWorker?{description:"No live worker — start `rulemetric evals agent` to run them."}:void 0);return}const qa=Ba.skipped.filter(Va=>Va.reason==="fresh").length,za=Ba.skipped.length-qa;qa>0?ue$1(za>0?`${qa} project${qa===1?"":"s"} fresh (<4h), ${za} skipped`:`All ${qa} project${qa===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>Xr.mutate({force:!0},{onSuccess:Fa,onError:Va=>ue$1.error("Couldn't start the regeneration",{description:Va instanceof Error?Va.message:"Please try again."})})}}):za>0?ue$1(`${za} project${za===1?"":"s"} skipped (no checkout or too few sessions)`):Ba.errors.length===0&&ue$1("No projects eligible for regeneration")};return cs?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Ba,qa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},qa))})]}):!is||is.total_sessions===0?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No sessions captured yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mx-auto mt-2",children:["Run ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric hooks install"})," in a project to start capturing Claude Code sessions. Insights will appear automatically after your next session."]})]})]})})})}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:jsxRuntimeExports.jsx(Button,{onClick:()=>Xr.mutate(void 0,{onSuccess:Fa,onError:Ba=>ue$1.error("Couldn't start the regeneration",{description:Ba instanceof Error?Ba.message:"Please try again."})}),disabled:Xr.isPending||Na.length>0,className:"cursor-pointer",children:Na.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Na.length," remaining)..."]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4"}),"Regenerate All"]})})})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:[Ma&&jsxRuntimeExports.jsx(JobTracker,{jobs:Ia}),(is==null?void 0:is.analysis_freshness)&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:is.analysis_freshness,totalAnalyzed:is.sessions_with_analysis}),jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsx(InsightsOverview,{computed:is}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts("/insights/computed"),className:"text-sm font-medium text-primary hover:underline cursor-pointer",children:"Explore detailed trends and recommendations →"}),Kr&&Kr.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono font-semibold text-muted-foreground pt-2",children:"By Project"}),Kr.filter(Ba=>Ba.sessionCount>=3).map(Ba=>{const qa=La.has(Ba.projectPath),za=Pa.get(Ba.projectPath),Va=Ba.projectId??void 0,Ga=Va?`/insights/computed?projectPath=${encodeURIComponent(Ba.projectPath)}&projectId=${encodeURIComponent(Va)}`:`/insights/computed?projectPath=${encodeURIComponent(Ba.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Ba,hasReport:qa,activeJob:za,onClick:()=>ts(Ga)},Va??Ba.projectPath)})]})]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]})}function formatUsd(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function formatTokens$1(es){return es?es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es):"0"}function Row({label:es,usd:$,detail:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground w-20 text-right",children:ts})]})]})}function CostBreakdownCard({totalUsd:es,breakdown:$,inputTokens:ts=0,outputTokens:is=0,cacheReadTokens:cs=0,cacheWriteTokens:Kr=0,byModel:Xr,byTool:Na}){const Ca=$??{inputUsd:0,outputUsd:0,cacheReadUsd:0,cacheWriteUsd:0},Aa=Xr?Object.entries(Xr).sort(([,Ma],[,Pa])=>Pa.cost_usd-Ma.cost_usd):[],Ia=Na?Object.entries(Na).sort(([,Ma],[,Pa])=>Pa.cost_usd-Ma.cost_usd):[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{children:"Estimated cost"}),jsxRuntimeExports.jsxs("span",{className:"ml-auto font-mono text-base",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground mr-1",children:"≈"}),formatUsd(es)]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Row,{label:"Input",usd:Ca.inputUsd,detail:`${formatTokens$1(ts)} tok`}),jsxRuntimeExports.jsx(Row,{label:"Output",usd:Ca.outputUsd,detail:`${formatTokens$1(is)} tok`}),jsxRuntimeExports.jsx(Row,{label:"Cache read",usd:Ca.cacheReadUsd,detail:cs>0?`${formatTokens$1(cs)} tok`:"no cache"}),jsxRuntimeExports.jsx(Row,{label:"Cache write",usd:Ca.cacheWriteUsd,detail:Kr>0?`${formatTokens$1(Kr)} tok`:"no cache"})]}),Ia.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By tool"}),Ia.map(([Ma,Pa])=>{const La=es>0?Math.round(Pa.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:displayTool(Ma)}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Pa.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[La,"%"]})]})]},Ma)})]})]}),Aa.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By model"}),Aa.map(([Ma,Pa])=>{const La=es>0?Math.round(Pa.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:Ma}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Pa.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[La,"%"]})]})]},Ma)})]})]}),jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground cursor-help",children:[jsxRuntimeExports.jsx("span",{className:"mr-1",children:"≈"}),"estimated · derived from token usage × current published rates"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:"Computed from each model's token usage × its provider's published pricing (Anthropic, OpenAI, Google, and others). May differ from actual billing by ±5% due to per-request rounding; unrecognised models fall back to a Sonnet-equivalent estimate."})})]})})]})]})}function verdictState(es){return es.sufficient?es.significant?"significant":"no-effect":(es.strataDroppedForTimeSeparation??0)>0?"no-comparable-cohort":"insufficient"}function VerdictBadge({verdict:es}){const $=`95% CI ${(es.ci.lower*100).toFixed(0)}–${(es.ci.upper*100).toFixed(0)}%`,ts=`n=${es.nWith}`,is=es.strata!=null?` · within ${es.strata} project${es.strata===1?"":"s"}`:"",cs=es.confounded?` · observational${is}`:"",Kr=verdictState(es);if(Kr==="no-comparable-cohort"){const Aa=es.strataDroppedForTimeSeparation;return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`No comparable cohort. ${Aa} project-month${Aa===1?"":"s"} held both exposed and unexposed sessions, but they're separated in time — this treatment's sessions all ran later than the ones without it, so any difference is a calendar difference, not an effect. More sessions won't resolve it; a randomised holdout would.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-amber-400 border-amber-400/40",children:"no comparable cohort"})})}if(Kr==="insufficient")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Not enough sessions to measure this yet, so no number is shown (rather than a fabricated one).${es.insufficientReason?` ${es.insufficientReason}`:""}`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"insufficient data"})});if(Kr==="no-effect")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`The with-vs-without difference isn't statistically distinguishable from zero, so we report no effect rather than noise. ${$}, ${ts}${cs}.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"no measured effect"})});const Xr=es.delta>0,Na=`${Xr?"+":""}${(es.delta*100).toFixed(0)}%`,Ca=es.pValue!=null?`, p=${es.pValue.toFixed(3)}`:"";return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Sessions with this ${Xr?"did measurably BETTER":"did measurably WORSE"} than sessions without it, and the difference is statistically significant. ${$}, ${ts}${Ca}${cs}. Observational — a correlation from real sessions, not a controlled experiment.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono shrink-0",Xr?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),children:[Na," outcome"]})})}const FRIENDLY_LABELS={debug_investigate:"Debug/Investigate",implement_feature:"Implement Feature",fix_bug:"Fix Bug",write_script_tool:"Write Script/Tool",refactor_code:"Refactor Code",configure_system:"Configure System",create_pr_commit:"Create PR/Commit",understand_codebase:"Understand Codebase",write_tests:"Write Tests",write_docs:"Write Docs",analyze_data:"Analyze Data",deploy_infra:"Deploy/Infra",warmup_minimal:"Cache Warmup",fully_achieved:"Fully Achieved",mostly_achieved:"Mostly Achieved",partially_achieved:"Partially Achieved",not_achieved:"Not Achieved",unclear_from_transcript:"Unclear",frustrated:"Frustrated",dissatisfied:"Dissatisfied",likely_satisfied:"Likely Satisfied",satisfied:"Satisfied",happy:"Happy",unsure:"Unsure",single_task:"Single Task",multi_task:"Multi Task",iterative_refinement:"Iterative Refinement",exploration:"Exploration",quick_question:"Quick Question",unhelpful:"Unhelpful",slightly_helpful:"Slightly Helpful",very_helpful:"Very Helpful",essential:"Essential",moderately_helpful:"Moderately Helpful",misunderstood_request:"Misunderstood Request",wrong_approach:"Wrong Approach",buggy_code:"Buggy Code",user_rejected_action:"User Rejected Action",excessive_changes:"Excessive Changes",wrong_file_or_location:"Wrong File/Location",slow_or_verbose:"Slow/Verbose",tool_failed:"Tool Failed",claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot_cli:"Copilot CLI",antigravity:"Antigravity",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM"};function friendlyLabel(es){return FRIENDLY_LABELS[es]||es.replace(/_/g," ").replace(/\b\w/g,$=>$.toUpperCase())}function CopyButton({text:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:async is=>{is.stopPropagation();try{await navigator.clipboard.writeText(es),ts(!0),setTimeout(()=>ts(!1),2e3)}catch{ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})}},children:$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"})})}function RunCommandButton({prompt:es,label:$="Copy"}){const[ts,is]=reactExports.useState(!1),Kr=/^(claude|rulemetric|pnpm|npm|npx|git)\s/.test(es.trim())?es.trim():`claude -p '${es.replace(/'/g,"'\\''")}'`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-teal-500/30 text-teal-600 hover:bg-teal-500/10 hover:text-teal-600",onClick:async Xr=>{Xr.stopPropagation();try{await navigator.clipboard.writeText(Kr),is(!0),setTimeout(()=>is(!1),2e3)}catch{ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})}},title:`Copy command: ${Kr.slice(0,80)}...`,children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),ts?"Copied!":$]})}function StatCard$2({icon:es,label:$,value:ts,sub:is}){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:jsxRuntimeExports.jsx(es,{className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:ts}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$}),is&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:is})]})]})})})}function HorizontalBar({items:es,maxItems:$=8,onItemClick:ts}){const is=Object.entries(es).sort(([,Kr],[,Xr])=>Xr-Kr).slice(0,$);if(is.length===0)return jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data"});const cs=is[0][1];return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:is.map(([Kr,Xr])=>jsxRuntimeExports.jsxs("div",{className:`space-y-1 ${ts?"cursor-pointer hover:bg-muted/50 rounded px-1 -mx-1 py-0.5":""}`,...ts?activatable(()=>ts(Kr)):{},children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[200px]",children:friendlyLabel(Kr)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:(Xr??0).toLocaleString()})]}),jsxRuntimeExports.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Xr/cs*100}%`}})})]},Kr))})}function HourChart({hours:es}){const $=new Array(24).fill(0);for(const is of es)$[is]++;const ts=Math.max(...$,1);return jsxRuntimeExports.jsx("div",{className:"flex items-end gap-0.5 h-20",children:$.map((is,cs)=>jsxRuntimeExports.jsx("div",{className:"flex-1 bg-primary/60 rounded-t hover:bg-primary transition-colors cursor-default",style:{height:`${is/ts*100}%`,minHeight:is>0?2:0},title:`${cs}:00 — ${is} messages`},cs))})}function formatDurationSec(es){return es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function ResponseTimeChart({histogram:es}){const $=Object.entries(es),ts=Math.max(...$.map(([,is])=>is),1);return jsxRuntimeExports.jsx("div",{className:"space-y-1.5",children:$.map(([is,cs])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-14 text-right shrink-0",children:is}),jsxRuntimeExports.jsx("div",{className:"flex-1 h-4 bg-muted rounded overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary/70 rounded transition-all",style:{width:`${cs/ts*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-8 text-right",children:cs})]},is))})}function OverviewTab({data:es}){const $=es.estimated_cost_usd??0,ts=es.truncated??!1,is=es.response_time,cs=es.parallel_sessions,Kr=es.tools_used,Xr=es.tool_error_categories??{},Na=es.total_interruptions??0,Ca=es.sessions_using_task_agent??0,Aa=es.sessions_using_mcp??0;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:MessageSquare,label:"Messages",value:(es.total_messages??0).toLocaleString(),sub:`${es.messages_per_day??0}/day avg`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Lines Changed",value:`+${(es.total_lines_added??0).toLocaleString()}`,sub:`-${(es.total_lines_removed??0).toLocaleString()} removed`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Files Modified",value:(es.total_files_modified??0).toLocaleString()}),jsxRuntimeExports.jsx(StatCard$2,{icon:ChartColumn,label:"Days Active",value:es.days_active,sub:`${es.total_sessions} sessions`}),jsxRuntimeExports.jsx(StatCard$2,{icon:GitCommitHorizontal,label:"Git Commits",value:es.git_commits,sub:`${es.git_pushes} pushes`})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[$>0&&jsxRuntimeExports.jsxs("div",{className:"md:col-span-2 space-y-2",children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:$,breakdown:es.estimated_cost_breakdown,inputTokens:es.total_input_tokens,outputTokens:es.total_output_tokens,cacheReadTokens:es.total_cache_read_tokens,cacheWriteTokens:es.total_cache_write_tokens,byModel:es.estimated_cost_by_model}),ts&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:Clock,label:"Total Hours",value:Math.round(es.total_duration_hours),sub:Na>0?`${Na} interruptions`:void 0}),Ca>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"Task Agents",value:Ca,sub:"sessions"}),Aa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"MCP Sessions",value:Aa,sub:"sessions"})]})]}),cs&&cs.events>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Parallel Sessions"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-8",children:[jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.events}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"overlap events"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.sessions_involved}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"sessions involved"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsxs("p",{className:"text-2xl font-bold font-mono",children:[es.total_sessions>0?Math.round(cs.sessions_involved/es.total_sessions*100):0,"%"]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"of sessions"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Detected when messages from different sessions overlap within 30-minute windows."})]})]}),Kr&&Object.keys(Kr).length>1&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"AI Tools Used"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Kr})})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[is&&is.total_samples>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"User Response Time Distribution"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Median: ",formatDurationSec(is.median_seconds)," · Avg: ",formatDurationSec(is.avg_seconds)," · ",is.total_samples," samples"]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ResponseTimeChart,{histogram:is.histogram})})]}),es.message_hours.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Messages by Time of Day"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx(HourChart,{hours:es.message_hours}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-1 font-mono",children:[jsxRuntimeExports.jsx("span",{children:"0:00"}),jsxRuntimeExports.jsx("span",{children:"6:00"}),jsxRuntimeExports.jsx("span",{children:"12:00"}),jsxRuntimeExports.jsx("span",{children:"18:00"}),jsxRuntimeExports.jsx("span",{children:"23:00"})]})]})]})]}),Object.keys(Xr).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-red-500"}),"Tool Error Encounters"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Xr})})]})]})}function ToolsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Tool Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.tool_counts,maxItems:12})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Languages"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.languages})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Feature Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[{label:"Task Agents",value:es.sessions_using_task_agent},{label:"MCP Servers",value:es.sessions_using_mcp}].map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-sm",children:$.label}),jsxRuntimeExports.jsxs(Badge,{variant:$.value>0?"default":"outline",children:[$.value," sessions"]})]},$.label))})})]})]})}function QualityTab({data:es}){const $=useNavigate(),ts=[{key:"goal_categories",title:"Goal Categories",items:es.goal_categories??{}},{key:"outcomes",title:"Outcomes",items:es.outcomes??{},onClick:is=>$(`/sessions?outcome=${is}`)},{key:"satisfaction",title:"User Satisfaction",items:es.satisfaction??{}},{key:"session_types",title:"Session Types",items:es.session_types??{}},{key:"friction",title:"Friction Points",items:es.friction??{},icon:TriangleAlert,onClick:is=>$(`/sessions?friction=${is}`)}].filter(is=>Object.keys(is.items).length>0);return ts.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No quality data yet. Session analysis runs automatically on your local worker — make sure ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rulemetric evals agent"})," is running, then use Generate Recommendations to analyze recent sessions."]})})}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:ts.map(is=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:is.title})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:is.items,onItemClick:is.onClick})})]},is.key))})}function SessionsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[Object.keys(es.projects).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Projects (",Object.keys(es.projects).length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.projects})})]}),es.session_summaries.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Sessions with Analysis (",es.session_summaries.length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:es.session_summaries.map($=>{const ts=$.id.length===36&&$.id.includes("-"),is=jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-3 rounded-lg border border-border bg-background p-3 ${ts?"hover:border-primary/50 cursor-pointer":""}`,children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:$.date}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-sm truncate",children:$.summary||$.goal||"No summary"}),$.goal&&$.summary&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:$.goal}),"outcome"in $&&$.outcome&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-1 text-[10px]",children:friendlyLabel($.outcome)})]})]});return ts?jsxRuntimeExports.jsx(Link,{to:`/sessions/${$.id}`,children:is},$.id):jsxRuntimeExports.jsx("div",{children:is},$.id)})})})]})]})}function RecommendationsTab({rec:es,projectPath:$,autoAddAvailable:ts}){var Xr,Na,Ca,Aa,Ia,Ma;const is=useAutoAddSuggestion(),[cs,Kr]=reactExports.useState(new Set);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[es.at_a_glance&&jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30 bg-amber-500/5",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-amber-500"}),"At a Glance"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Object.entries(es.at_a_glance).map(([Pa,La])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1",children:Pa.replace(/_/g," ")}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:La})]},Pa))})]}),((Xr=es.what_works)==null?void 0:Xr.impressive_workflows)&&es.what_works.impressive_workflows.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Impressive Things You Did"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.what_works.impressive_workflows.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.description})]},La))})]}),((Na=es.friction_analysis)==null?void 0:Na.categories)&&es.friction_analysis.categories.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-amber-500"}),"Where Things Go Wrong"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.friction_analysis.categories.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.category}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.description}),Pa.examples.length>0&&jsxRuntimeExports.jsx("ul",{className:"mt-2 space-y-1",children:Pa.examples.map((Fa,Ba)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground pl-3 border-l-2 border-border",children:Fa},Ba))})]},La))})]}),((Ca=es.suggestions)==null?void 0:Ca.features_to_try)&&es.suggestions.features_to_try.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.features_to_try.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.feature}),Pa.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.example_code}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.why_for_you}),Pa.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.example_code})]},La))})]}),((Aa=es.suggestions)==null?void 0:Aa.claude_md_additions)&&es.suggestions.claude_md_additions.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Suggested CLAUDE.md Additions"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.claude_md_additions.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:Pa.addition}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(CopyButton,{text:Pa.addition}),$&&ts&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",disabled:cs.has(La)||is.isPending,onClick:Fa=>{Fa.stopPropagation(),is.mutate({projectPath:$,addition:Pa.addition,why:Pa.why},{onSuccess:Ba=>{(Ba.success||Ba.reason==="already_present")&&Kr(qa=>new Set(qa).add(La))},onError:Ba=>{const qa=Ba instanceof ApiError&&(Ba.code==="not_local_mode"||Ba.statusCode===501);ue$1.error(qa?"Add to CLAUDE.md only works when the API runs on your machine (local mode) — use the copy button instead.":Ba instanceof Error?Ba.message:"Failed to update CLAUDE.md")}})},children:is.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):cs.has(La)?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-teal-500"}):jsxRuntimeExports.jsx(Upload,{className:"h-3 w-3"})})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Pa.why}),cs.has(La)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500 mt-1",children:"Added to CLAUDE.md"})]},La))})]}),((Ia=es.suggestions)==null?void 0:Ia.usage_patterns)&&es.suggestions.usage_patterns.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.usage_patterns.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),Pa.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.suggestion}),Pa.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.copyable_prompt})]},La))})]}),((Ma=es.on_the_horizon)==null?void 0:Ma.opportunities)&&es.on_the_horizon.opportunities.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.on_the_horizon.opportunities.map((Pa,La)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Pa.title}),Pa.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Pa.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton,{text:Pa.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Pa.whats_possible}),Pa.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Pa.copyable_prompt})]},La))})]}),es.fun_ending&&jsxRuntimeExports.jsx(Card,{className:"border-pink-500/20 bg-pink-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:es.fun_ending.headline}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:es.fun_ending.detail})]})})]})}function ScorePair({label:es,withVal:$,withoutVal:ts,delta:is,unit:cs,inverted:Kr}){const Xr=Aa=>Aa!=null?`${Aa}${cs}`:"—",Na=is!=null&&is!==0?(Kr?is<0:is>0)?"text-teal-500":"text-red-500":"text-muted-foreground",Ca=is!=null&&is>0?"+":"";return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Xr($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"vs"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:Xr(ts)})]}),is!=null&&is!==0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:`text-[10px] mt-1 ${Na} ${(Kr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Ca,is,cs]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Kr=>Kr.verdict.sufficient),cs=ts.length-is.length;return is.length===0&&cs===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:es}),is.map(Kr=>{const Xr=Kr.verdict,Na=Xr.delta>0,Ca=Xr.significant?`${Na?"+":""}${(Xr.delta*100).toFixed(0)}%`:"no effect",Aa=Xr.significant?Na?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40":"text-muted-foreground",Ia=`95% CI ${(Xr.ci.lower*100).toFixed(0)}–${(Xr.ci.upper*100).toFixed(0)}%, n=${Xr.nWith} exposed / ${Xr.nWithout} unexposed (observational)`;return jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono",Aa),title:Ia,children:[Kr.label," ",Ca]},Kr.label)}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`Not enough exposed + unexposed sessions within a project to measure ${cs===1?`this ${$}`:`these ${$}s`} yet.`,children:[cs," ",$,cs===1?"":"s",": insufficient"]})]})}function SegmentBreakdown({impact:es}){const $=(es.segments??[]).map(is=>({label:is.model,verdict:is.verdict})),ts=(es.harnessSegments??[]).map(is=>({label:is.harness,verdict:is.verdict}));return $.length===0&&ts.length===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t",children:[jsxRuntimeExports.jsx(SegmentLine,{title:"By model:",noun:"model",segments:$}),jsxRuntimeExports.jsx(SegmentLine,{title:"By harness:",noun:"harness",segments:ts})]})}function ImpactCard({impact:es,linkedSessions:$}){const ts=es.with,is=es.without,cs=es.comparison;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono truncate",children:es.instructionName}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[es.autoAdded&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40",title:`Auto-added from a recommendation${es.autoAdded.count>1?` ×${es.autoAdded.count}`:""}`+(es.autoAdded.lastAssignedAt?` (last ${new Date(es.autoAdded.lastAssignedAt).toLocaleDateString()})`:"")+" — the verdict beside this is whether it helped.",children:["auto-added",es.autoAdded.count>1?` ×${es.autoAdded.count}`:""]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict}),$!=null&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:[$," sessions"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:"Sessions"}),jsxRuntimeExports.jsxs("p",{className:"font-mono",children:[ts.sessionCount," with / ",is.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[ts.enrichedCount," / ",is.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:ts.avgOutcomeScore,withoutVal:is.avgOutcomeScore,delta:cs.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:ts.avgToolErrors,withoutVal:is.avgToolErrors,delta:cs.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:ts.avgDurationMinutes,withoutVal:is.avgDurationMinutes,delta:cs.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$}){const{data:ts,isLoading:is}=useInstructionImpact(es);return is?jsxRuntimeExports.jsx(Skeleton,{className:"h-24"}):!ts||ts.with.sessionCount===0&&ts.without.sessionCount===0?null:jsxRuntimeExports.jsx(ImpactCard,{impact:ts,linkedSessions:$})}function GroomingCard(){const{data:es,isLoading:$}=useGroomCandidates(),ts=useArchiveInstruction$1(),is=useRestoreInstruction$1(),[cs,Kr]=reactExports.useState(new Set);if($||!es)return null;if(!es.captureHealthy)return jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Grooming paused"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.reason})})]});const Xr=es.harmful??[],Na=es.bloated??[],Ca=es.candidates.length+Xr.length;if(Ca===0&&Na.length===0)return null;const Aa=Ma=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:cs.has(Ma)||ts.isPending,onClick:()=>ts.mutate(Ma,{onSuccess:()=>{Kr(Pa=>new Set(Pa).add(Ma)),ue$1.success("Archived",{description:"Soft delete — this can be restored.",action:{label:"Undo",onClick:()=>is.mutate(Ma,{onSuccess:()=>{Kr(Pa=>{const La=new Set(Pa);return La.delete(Ma),La}),ue$1.success("Restored")},onError:()=>ue$1.error("Restore failed")})}})},onError:()=>ue$1.error("Archive failed")}),children:cs.has(Ma)?"Archived":"Archive"}),Ia=es.safetyGuarded+(es.harmfulSafetyGuarded??0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm",children:["Instructions worth a second look (",Ca+Na.length,")"]}),Ia>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Safety / destructive-guardrail rules are never proposed for retirement, however rarely they fire or however they score.",children:[Ia," safety rule",Ia===1?"":"s"," protected"]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Your own instructions worth a second look. Archiving is reversible; safety rules are never listed here."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-amber-400/90 mb-0.5",children:"Expensive, no measurable effect"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Enough exposure to detect an effect and none was found — so these are candidates to SHORTEN, not to retire. Neutral means undetected, not worthless; the rule may carry something the outcome score cannot see. No archive button here on purpose."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Na.map(Ma=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:Ma.name,children:Ma.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:Ma.verdict}),Ma.containsSafetyLanguage&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400 shrink-0",title:"Contains destructive-command or credential guardrail language. Shown anyway — a trim changes nothing on its own — but preserve those lines when shortening.",children:"has guardrails"})]}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",Ma.estimatedTokens.toLocaleString()," tok/session"]})]},Ma.id))})]}),Xr.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-red-400/90 mb-0.5",children:"Measurably worse outcomes"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Present in sessions that scored significantly lower. Correlational, not proven cause — the rule may just ride along with harder tasks — so review before retiring; the verdict beside each shows the effect."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Xr.map(Ma=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:Ma.name,children:Ma.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:Ma.verdict})]}),Aa(Ma.id)]},Ma.id))})]}),es.candidates.length>0&&jsxRuntimeExports.jsxs("div",{children:[Xr.length>0&&jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"No recent use"}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:es.candidates.map(Ma=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:Ma.name,children:Ma.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:Ma.reason})]}),Aa(Ma.id)]},Ma.id))})]})]})]})}function InstructionsTab({projectFilter:es}){const{data:$,isLoading:ts}=useLinkedInstructions(es);return ts?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(3)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},cs))}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(GroomingCard,{}),!$||$.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No instructions linked to sessions yet. Instructions are auto-captured from context snapshots — the session-end hook snapshots your on-disk CLAUDE.md files, and the proxy additionally captures runtime-rendered prompts and skills."})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions linked to sessions, ranked by usage. Comparing sessions with vs. without each instruction."}),$.map(is=>jsxRuntimeExports.jsx(InstructionImpactLoader,{instructionId:is.id,linkedSessions:is.linkedSessions},is.id))]})]})}function InsightsDetailPage(){const{id:es}=useParams(),[$]=useSearchParams(),ts=es==="computed",is=ts?$.get("projectPath")??$.get("project")??void 0:void 0,cs=ts?$.get("projectId")??void 0:void 0,[Kr,Xr]=reactExports.useState(""),{data:Na,recommendations:Ca,isLoading:Aa,fullProjectPath:Ia,title:Ma,subtitle:Pa,lastCompletedJob:La,activeJobs:Fa,createJob:Ba}=useProjectInsights(es,is,cs,Kr||void 0),[qa,za]=useTabParam(["overview","tools","quality","sessions","instructions","recommendations"],"overview");if(Aa)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((Qa,Xa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Xa))})]});if(!Na)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Report not found."})]});const Va=ts?Na.tools_used??{}:{},Ga=Object.keys(Va).sort((Qa,Xa)=>(Va[Xa]??0)-(Va[Qa]??0)),Za=Na.autoAddAvailable!==!1;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:Ma}),ts&&(Ga.length>1||Kr)&&jsxRuntimeExports.jsxs("select",{value:Kr,onChange:Qa=>Xr(Qa.target.value),className:"h-8 rounded-md border border-input bg-background px-2 text-xs font-mono cursor-pointer focus:outline-none focus:ring-1 focus:ring-ring",children:[jsxRuntimeExports.jsx("option",{value:"",children:"All Tools"}),Ga.map(Qa=>jsxRuntimeExports.jsxs("option",{value:Qa,children:[displayTool(Qa)," (",Va[Qa],")"]},Qa)),Kr&&!Ga.includes(Kr)&&jsxRuntimeExports.jsx("option",{value:Kr,children:displayTool(Kr)})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Pa}),ts&&Ga.length>0&&!Kr&&jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:Ga.map(Qa=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Xr(Qa),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Qa),": ",Va[Qa]]})},Qa))})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[La&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last generated ",new Date(La.completedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Ba.mutate(Ia??is,{onSuccess:Qa=>{Qa.noLiveWorker?ue$1.warning("Queued, but no worker is listening",{description:"Start one with `rulemetric evals agent` (or `rulemetric service install --worker-only`) and it will pick this up."}):ue$1.success("Generating recommendations…")},onError:Qa=>ue$1.error("Couldn't start the run",{description:Qa instanceof Error?Qa.message:"Please try again."})}),disabled:Ba.isPending||Fa.length>0,variant:"outline",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),Fa.length>0?`Generating — ${jobStepLabel(Fa[0])}`:Ca?"Refresh Recommendations":"Generate Recommendations"]})]})]}),ts&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:Na.analysis_freshness,totalAnalyzed:Na.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),Fa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:Fa}),jsxRuntimeExports.jsxs(Tabs,{value:qa,onValueChange:za,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"mr-2 h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"tools",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Tools"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"quality",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Quality"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"sessions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"mr-2 h-4 w-4"}),"Sessions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"instructions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"mr-2 h-4 w-4"}),"Instructions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"recommendations",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),"Recommendations"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-6",children:jsxRuntimeExports.jsx(OverviewTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"instructions",className:"mt-6",children:jsxRuntimeExports.jsx(InstructionsTab,{projectFilter:is})}),jsxRuntimeExports.jsx(TabsContent,{value:"recommendations",className:"mt-6",children:Ca?jsxRuntimeExports.jsx(RecommendationsTab,{rec:Ca,projectPath:Ia,autoAddAvailable:Za}):jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Fa.length>0?`Generating recommendations — ${jobStepLabel(Fa[0])}`:'No recommendations yet. Use "Generate Recommendations" above to analyze this project’s sessions.'})})})})]})]})}const MEMORY_PAGE_SIZE=50;function useMemories(es="active",$="",ts="all"){return useInfiniteQuery({queryKey:["memories",{status:es,search:$,kind:ts}],initialPageParam:0,queryFn:({pageParam:is})=>{const cs=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&cs.set("search",$),ts&&ts!=="all"&&cs.set("kind",ts),apiGet(`/api/memories?${cs.toString()}`).then(Kr=>Kr.memories)},getNextPageParam:(is,cs)=>is.length<MEMORY_PAGE_SIZE?void 0:cs.length*MEMORY_PAGE_SIZE})}function useMemory(es){return useQuery({queryKey:["memories",es],queryFn:()=>apiGet(`/api/memories/${es}`),enabled:!!es})}function useMemoryImpact(es){return useQuery({queryKey:["insights","memory-impact",es],queryFn:()=>apiGet(`/api/insights/memory-impact?memoryId=${es}`),enabled:!!es})}function useMemoryExperiments(es){return useQuery({queryKey:["memories",es,"experiments"],queryFn:()=>apiGet(`/api/memories/${es}/experiments`),enabled:!!es,select:$=>$.experiments,refetchInterval:$=>{var is;return(((is=$.state.data)==null?void 0:is.experiments)??[]).some(cs=>cs.status==="pending"||cs.status==="running")?5e3:!1}})}function useCreateExperiment(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/memories/${es}/experiments`,ts),onSuccess:()=>$.invalidateQueries({queryKey:["memories",es,"experiments"]})})}function useCreateMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/memories",$),onSuccess:()=>es.invalidateQueries({queryKey:["memories"]})})}function useUpdateMemory(){const es=useQueryClient();return useMutation({mutationFn:({id:$,...ts})=>apiPatch(`/api/memories/${$}`,ts),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts.id]})}})}function useArchiveMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/memories/${$}`),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts]})}})}const KINDS=["fact","decision","correction","convention"];function MemoryFormDialog({open:es,onOpenChange:$,memory:ts}){const is=!!ts,cs=useCreateMemory(),Kr=useUpdateMemory(),[Xr,Na]=reactExports.useState("fact"),[Ca,Aa]=reactExports.useState(""),[Ia,Ma]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Na((ts==null?void 0:ts.kind)??"fact"),Aa((ts==null?void 0:ts.title)??""),Ma((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Pa=cs.isPending||Kr.isPending,La=Ca.trim().length>0&&Ia.trim().length>0&&!Pa,Fa=()=>{if(!La)return;const Ba=za=>()=>{ue$1.success(`Memory ${za}`),$(!1)},qa=za=>ue$1.error(za instanceof Error?za.message:"Something went wrong");is?Kr.mutate({id:ts.id,kind:Xr,title:Ca.trim(),body:Ia.trim()},{onSuccess:Ba("updated"),onError:qa}):cs.mutate({kind:Xr,title:Ca.trim(),body:Ia.trim()},{onSuccess:Ba("created"),onError:qa})};return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:is?"Edit memory":"New memory"}),jsxRuntimeExports.jsx(DialogDescription,{children:"A durable note the session-start hook injects into future sessions as context. Its measured effect is tracked automatically."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Kind"}),jsxRuntimeExports.jsxs(Select,{value:Xr,onValueChange:Ba=>Na(Ba),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsx(SelectContent,{children:KINDS.map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba,className:"capitalize",children:Ba},Ba))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Title"}),jsxRuntimeExports.jsx(Input,{value:Ca,onChange:Ba=>Aa(Ba.target.value),placeholder:"Short, memorable summary",maxLength:300})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:Ba=>Ma(Ba.target.value),placeholder:"The fact / decision / correction / convention to remember.",rows:5})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:Fa,disabled:!La,className:"cursor-pointer",children:Pa?"Saving…":is?"Save changes":"Create"})]})]})})}const kindColors={fact:"bg-blue-500/15 text-blue-400 border-blue-500/30",decision:"bg-primary/15 text-primary border-primary/30",correction:"bg-red-500/15 text-red-400 border-red-500/30",convention:"bg-pink-500/15 text-pink-400 border-pink-500/30"};function useDebouncedValue(es,$){const[ts,is]=reactExports.useState(es);return reactExports.useEffect(()=>{const cs=setTimeout(()=>is(es),$);return()=>clearTimeout(cs)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState("all"),[Xr,Na]=reactExports.useState(!1),Ca=useNavigate(),Aa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:Ma,error:Pa,hasNextPage:La,fetchNextPage:Fa,isFetchingNextPage:Ba}=useMemories(es,Aa,cs),qa=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),za=Aa!==""||cs!=="all";if(Pa)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Pa.message]});const Va=es!=="active";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative min-w-40 flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search memories...",value:ts,onChange:Ga=>is(Ga.target.value),className:"pl-9 bg-background border-border"})]}),jsxRuntimeExports.jsxs(Select,{value:cs,onValueChange:Kr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-36 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All kinds"}),jsxRuntimeExports.jsx(SelectItem,{value:"fact",children:"Fact"}),jsxRuntimeExports.jsx(SelectItem,{value:"decision",children:"Decision"}),jsxRuntimeExports.jsx(SelectItem,{value:"correction",children:"Correction"}),jsxRuntimeExports.jsx(SelectItem,{value:"convention",children:"Convention"})]})]}),jsxRuntimeExports.jsxs(Select,{value:es,onValueChange:Ga=>$(Ga),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-32 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"active",children:"Active"}),jsxRuntimeExports.jsx(SelectItem,{value:"archived",children:"Archived"}),jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All"})]})]}),jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),Ma?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Ga,Za)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Za))}):qa.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12",children:[jsxRuntimeExports.jsx(Brain,{className:"mx-auto h-8 w-8 text-muted-foreground/40 mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-4",children:za?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!za&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create memory"]})]}):jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-transparent",children:[jsxRuntimeExports.jsx(TableHead,{children:"Title"}),jsxRuntimeExports.jsx(TableHead,{children:"Kind"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden md:table-cell",children:"Scope"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden lg:table-cell",children:"Source"}),Va&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:qa.map(Ga=>jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-secondary/50 transition-colors duration-200 cursor-pointer",onClick:()=>Ca(`/memories/${Ga.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium max-w-md truncate",children:Ga.title}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[Ga.kind]}`,children:Ga.kind})}),jsxRuntimeExports.jsx(TableCell,{className:"hidden md:table-cell text-xs text-muted-foreground",children:Ga.projectId?"Project":"Global"}),jsxRuntimeExports.jsx(TableCell,{className:"hidden lg:table-cell text-xs text-muted-foreground",children:Ga.source}),Va&&jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs capitalize text-muted-foreground",children:Ga.status})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-xs text-muted-foreground",children:formatDistanceToNow(Ga.updatedAt)})]},Ga.id))})]})}),La&&jsxRuntimeExports.jsx("div",{className:"flex justify-center",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",disabled:Ba,onClick:()=>Fa(),children:Ba?"Loading…":"Load more"})}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:Xr,onOpenChange:Na})]})}function MemoriesListPage(){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Memories"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Durable project facts your agent recalls — injected at session start, and measured for whether they actually help."})]}),jsxRuntimeExports.jsx(MemoryList,{})]})}function ExperimentRow({exp:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-mono truncate",title:es.taskPrompt,children:es.taskPrompt}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["v",es.memoryVersion," · ",es.trials," trials · ",formatDistanceToNow(es.createdAt)]}),es.status==="failed"&&es.error&&jsxRuntimeExports.jsx("p",{className:"text-[10px] text-red-400 mt-0.5",title:es.error,children:es.error})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&es.result?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["n=",es.result.completedTrials]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.result.verdict})]}):es.status==="failed"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:"failed"}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] text-muted-foreground gap-1",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),es.status==="running"?"running":"queued"]})})]})}function MemoryExperiments({memoryId:es}){const{data:$,isLoading:ts}=useMemoryExperiments(es),is=useCreateExperiment(es),[cs,Kr]=reactExports.useState(!1),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(""),[Ia,Ma]=reactExports.useState(10);function Pa(){const La=Ca.split(`
949
949
  `).map(Fa=>Fa.trim()).filter(Boolean);if(!Xr.trim()||La.length===0){ue$1.error("A task prompt and at least one expectation are required.");return}is.mutate({taskPrompt:Xr.trim(),expectations:La,trials:Ia},{onSuccess:Fa=>{ue$1.success(Fa.noLiveWorker?"Queued — start `rulemetric evals agent` on your laptop to run it":"Controlled A/B started — the causal verdict appears when it finishes"),Na(""),Aa(""),Kr(!1)},onError:Fa=>ue$1.error(`Failed: ${Fa.message}`)})}return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-3.5 w-3.5"})," Controlled A/B"]}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:()=>Kr(La=>!La),children:cs?"Cancel":"Run A/B"})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["The gold-standard causal test: the same task run with vs without this memory injected, graded and paired. Unlike the observational effect above, this holds the task constant — so its delta isn't confounded. Each trial runs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"claude"})," on your laptop (needs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"rulemetric evals agent"}),"); ≥10 trials to clear the significance gate."]}),cs&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-md border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-task",className:"text-xs",children:"Task prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-task",value:Xr,onChange:La=>Na(La.target.value),placeholder:"e.g. Add a new dependency to this project.",className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-exp",className:"text-xs",children:"Expectations (one per line)"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-exp",value:Ca,onChange:La=>Aa(La.target.value),placeholder:`Uses pnpm, not npm
950
- Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-end justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-trials",className:"text-xs",children:"Trials"}),jsxRuntimeExports.jsx(Input,{id:"ab-trials",type:"number",min:1,max:50,value:Ia,onChange:La=>Ma(Math.max(1,Math.min(50,Number(La.target.value)||1))),className:"text-xs h-8 w-20"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",className:"cursor-pointer",disabled:is.isPending,onClick:Pa,children:is.isPending?"Starting…":"Run experiment"})]})]}),ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-12"}):!$||$.length===0?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No controlled experiments yet. Run one to get an unconfounded causal delta."}):jsxRuntimeExports.jsx("div",{children:$.map(La=>jsxRuntimeExports.jsx(ExperimentRow,{exp:La},La.id))})]})]})}function formatTokens(es){return es==null?"—":es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es)}function Cohort({label:es,value:$}){return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:$})]})}function MemoryImpactCard({impact:es}){const $=es.with,ts=es.without,is=es.comparison,cs=$.avgOutcomeScore!=null&&ts.avgOutcomeScore!=null?`${$.avgOutcomeScore} vs ${ts.avgOutcomeScore}${is.outcomeScoreDelta!=null?` (${is.outcomeScoreDelta>0?"+":""}${is.outcomeScoreDelta})`:""}`:"—",Kr=$.avgTotalTokens!=null&&ts.avgTotalTokens!=null?`${formatTokens($.avgTotalTokens)} vs ${formatTokens(ts.avgTotalTokens)}`:"—";return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Measured effect"}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs",children:[jsxRuntimeExports.jsx(Cohort,{label:"Sessions",value:`${$.sessionCount} with / ${ts.sessionCount} without`}),jsxRuntimeExports.jsx(Cohort,{label:"Outcome score",value:cs}),jsxRuntimeExports.jsx(Cohort,{label:"Avg tokens/session",value:Kr})]}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mt-3",children:"Observational — sessions exposed to this memory vs not, compared within each project. Not a controlled experiment; cost is estimated."})]})]})}function VersionHistoryCard({versions:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Effect by version"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[es.map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["v",$.version]}),$.isCurrent&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] py-0 text-muted-foreground",children:"current"}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[$.with.sessionCount," session",$.with.sessionCount===1?"":"s"]})]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:$.verdict})]},$.version)),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground pt-1",children:"Each edit bumps the version and re-opens measurement, so a version is scored only on the sessions that actually saw it."})]})]})}function MemoryImpactLoader({memoryId:es}){const{data:$,isLoading:ts}=useMemoryImpact(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-28"}):!$||$.with.sessionCount===0&&$.without.sessionCount===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No measured effect yet. Once this memory is injected into sessions (via the session-start hook) and those sessions are analyzed, its verdict appears here."})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MemoryImpactCard,{impact:$}),$.versions.length>1&&jsxRuntimeExports.jsx(VersionHistoryCard,{versions:$.versions})]})}function MemoryDetail({id:es}){const{data:$,isLoading:ts,error:is}=useMemory(es),cs=useArchiveMemory(),Kr=useUpdateMemory(),[Xr,Na]=reactExports.useState(!1);if(ts)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40"})]});if(is||!$)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Memory not found."})]});const Ca=$.status==="archived";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Pencil,{className:"mr-1.5 h-3.5 w-3.5"})," Edit"]}),Ca?jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",disabled:Kr.isPending,onClick:()=>Kr.mutate({id:$.id,status:"active"},{onSuccess:()=>ue$1.success("Memory restored"),onError:()=>ue$1.error("Restore failed")}),children:[jsxRuntimeExports.jsx(RotateCcw,{className:"mr-1.5 h-3.5 w-3.5"})," Restore"]}):jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer text-red-400 hover:text-red-400",disabled:cs.isPending,onClick:()=>cs.mutate($.id,{onSuccess:()=>ue$1.success("Memory archived (reversible)"),onError:()=>ue$1.error("Archive failed")}),children:[jsxRuntimeExports.jsx(Archive,{className:"mr-1.5 h-3.5 w-3.5"})," Archive"]})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[$.kind]??""}`,children:$.kind}),Ca&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-muted-foreground",children:"archived"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["v",$.version," · ",$.source," · ",$.projectId?"project-scoped":"global"]})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight mt-2",children:$.title})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:$.body})})]}),jsxRuntimeExports.jsx(MemoryImpactLoader,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryExperiments,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:Xr,onOpenChange:Na,memory:$})]})}function MemoryDetailPage(){const{id:es}=useParams();return es?jsxRuntimeExports.jsx(MemoryDetail,{id:es}):null}const CATEGORY_LABELS={workflow:"Workflow",language:"Language",framework:"Framework",tool:"Tool",security:"Security",testing:"Testing",architecture:"Architecture",devops:"DevOps",documentation:"Documentation",performance:"Performance",other:"Other"};function CopyInstallButton({skill:es}){const[$,ts]=reactExports.useState(!1),is=`rulemetric skills install ${es.id}`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:cs=>{cs.stopPropagation(),navigator.clipboard.writeText(is),ts(!0),setTimeout(()=>ts(!1),2e3)},title:is,children:[$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),$?"Copied!":"Install"]})}function SkillCard({skill:es,onSelect:$}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:()=>$(es),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono leading-tight",children:es.name}),jsxRuntimeExports.jsx(CopyInstallButton,{skill:es})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:es.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono",children:CATEGORY_LABELS[es.category]??es.category}),es.tools.slice(0,3).map(ts=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:displayTool(ts)},ts)),es.tools.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:["+",es.tools.length-3]})]}),es.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.tags.slice(0,4).map(ts=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["#",ts]},ts))})]})]})}function SkillDetailDialog({skill:es,open:$,onClose:ts}){var Aa;const[is,cs]=reactExports.useState(!1),{data:Kr,isLoading:Xr}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Na=Kr??es,Ca=`rulemetric skills install ${Na.id}`;return jsxRuntimeExports.jsx(Dialog,{open:$,onOpenChange:Ia=>!Ia&&ts(),children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-[95vw] max-h-[90vh] overflow-y-auto",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{className:"font-mono",children:Na.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Na.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:CATEGORY_LABELS[Na.category]??Na.category}),Na.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Aa=Na.languages)==null?void 0:Aa.length)??0)>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"Languages:"}),Na.languages.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:Ia},Ia))]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium font-mono",children:"Install"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[Na.content&&jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:()=>{const Ia=new Blob([Na.content],{type:"text/markdown"}),Ma=URL.createObjectURL(Ia),Pa=document.createElement("a");Pa.href=Ma,Pa.download=`${Na.id}.md`,Pa.click(),URL.revokeObjectURL(Ma)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:()=>{navigator.clipboard.writeText(Ca),cs(!0),setTimeout(()=>cs(!1),2e3)},children:[is?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),is?"Copied!":"Copy CLI"]})]})]}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-2 overflow-x-auto",children:Ca})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-medium font-mono mb-2",children:"Content"}),Xr&&!Na.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Na.content?jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-3 overflow-x-auto whitespace-pre-wrap max-h-[55vh]",children:Na.content}):jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No content available."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["Source:"," ",jsxRuntimeExports.jsxs("a",{href:Na.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Na.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Na.source.license&&jsxRuntimeExports.jsx("span",{children:Na.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(null),[Ca,Aa]=reactExports.useState(null),[Ia,Ma]=reactExports.useState(PAGE_SIZE$1),Pa=(es==null?void 0:es.skills)??[],La=reactExports.useMemo(()=>[...new Set(Pa.map(Va=>Va.category))].sort(),[Pa]),Fa=reactExports.useMemo(()=>[...new Set(Pa.flatMap(Va=>Va.tools))].sort(),[Pa]),Ba=reactExports.useMemo(()=>{let Va=Pa;if(ts){const Ga=ts.toLowerCase();Va=Va.filter(Za=>Za.name.toLowerCase().includes(Ga)||Za.description.toLowerCase().includes(Ga)||Za.tags.some(Qa=>Qa.toLowerCase().includes(Ga))||Za.id.toLowerCase().includes(Ga))}return cs&&(Va=Va.filter(Ga=>Ga.category===cs)),Xr&&(Va=Va.filter(Ga=>Ga.tools.includes(Xr)||Ga.tools.includes("universal"))),Va.sort((Ga,Za)=>{var Ja,tl;const Qa=((Ja=Ga.popularity)==null?void 0:Ja.stars)??0,Xa=((tl=Za.popularity)==null?void 0:tl.stars)??0;return Qa!==Xa?Xa-Qa:Ga.name.localeCompare(Za.name)}),Va},[Pa,ts,cs,Xr]);reactExports.useEffect(()=>{Ma(PAGE_SIZE$1)},[ts,cs,Xr]);const qa=Ba.slice(0,Ia),za=Ba.length>Ia;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Skills Registry"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Browse and install community-contributed skills for your AI coding tools"})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search skills...",value:ts,onChange:Va=>is(Va.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[cs&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Kr(null),children:[CATEGORY_LABELS[cs]??cs,jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]}),Xr&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Na(null),children:[displayTool(Xr),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!cs&&!Xr&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Category:"}),La.map(Va=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Kr(Va),children:CATEGORY_LABELS[Va]??Va},Va))]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Tool:"}),Fa.map(Va=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Na(Va),children:displayTool(Va)},Va))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Va,Ga)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40"},Ga))}):Ba.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Pa.length===0?"No skills in registry":"No matching skills"}),Pa.length===0&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric skills update"})," ","to fetch the registry"]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono",children:["Showing ",qa.length," of ",Ba.length," skill",Ba.length!==1?"s":"",ts||cs||Xr?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:qa.map(Va=>jsxRuntimeExports.jsx(SkillCard,{skill:Va,onSelect:Aa},Va.id))}),za&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>Ma(Va=>Va+PAGE_SIZE$1),children:["Load ",Math.min(PAGE_SIZE$1,Ba.length-Ia)," more"]})})]}),jsxRuntimeExports.jsx(SkillDetailDialog,{skill:Ca,open:!!Ca,onClose:()=>Aa(null)})]})}function relativeDate(es){if(!es)return"recently";const $=new Date(es).getTime();if(Number.isNaN($))return"recently";const ts=Math.floor((Date.now()-$)/864e5);return ts<1?"today":ts===1?"yesterday":ts<30?`${ts}d ago`:ts<365?`${Math.floor(ts/30)}mo ago`:`${Math.floor(ts/365)}y ago`}function formatStars(es){return es>=1e3?`${(es/1e3).toFixed(1)}k`:String(es)}function PublicCatalogPage(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(es);reactExports.useEffect(()=>{const Ma=setTimeout(()=>is(es),250);return()=>clearTimeout(Ma)},[es]);const{data:cs,isLoading:Kr,isFetchingNextPage:Xr,fetchNextPage:Na,hasNextPage:Ca,error:Aa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(cs==null?void 0:cs.pages.flat())??[],[cs]);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-6 w-6"}),"Public Catalog"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Community-maintained skills and instructions, browsable here for reference."})]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search public catalog...",value:es,onChange:Ma=>$(Ma.target.value),className:"pl-9"})]}),Aa?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load public catalog: ",Aa.message]}):Kr?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Ma,Pa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Pa))}):Ia.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:ts?`No public skills match "${ts}".`:"No public skills available yet. The registry syncs daily."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ia.map(Ma=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${Ma.id}`,className:"block",children:jsxRuntimeExports.jsxs(Card,{className:"flex flex-col h-full hover:border-primary/50 hover:bg-muted/30 transition-colors cursor-pointer",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:Ma.name}),Ma.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:Ma.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[Ma.tags&&Ma.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:Ma.tags.slice(0,5).map(Pa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Pa},Pa))}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{title:Ma.sourceUpdatedAt??Ma.updatedAt,children:["Updated ",relativeDate(Ma.sourceUpdatedAt??Ma.updatedAt)]}),typeof Ma.popularityScore=="number"&&Ma.popularityScore>0&&jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1",title:"GitHub stars on the source repo",children:[jsxRuntimeExports.jsx(Star,{className:"h-3 w-3 fill-current"}),formatStars(Ma.popularityScore)]})]})]})]})},Ma.id))}),Ca&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Na(),disabled:Xr,className:"cursor-pointer",children:Xr?"Loading…":`Load more (showing ${Ia.length})`})}),!Ca&&Ia.length>0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-xs text-muted-foreground pt-2",children:[Ia.length," skill",Ia.length===1?"":"s"," loaded"]})]})]})}function PublicSkillDetailPage(){var cs,Kr;const{id:es}=useParams(),{data:$,isLoading:ts,error:is}=useQuery({queryKey:["instruction",es],queryFn:()=>apiGet(`/api/instructions/${es}`),enabled:!!es});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/catalog/public",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to Public Catalog"]})}),is?jsxRuntimeExports.jsxs("div",{className:"text-destructive",children:["Failed to load: ",is.message]}):ts||!$?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-1/2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.scope}),((cs=$.frontmatter)==null?void 0:cs.category)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.frontmatter.category})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:$.name}),$.description&&jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:$.description})]}),$.tags&&$.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:$.tags.map(Xr=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Xr},Xr))}),((Kr=$.frontmatter)==null?void 0:Kr.source)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source"})}),jsxRuntimeExports.jsxs(CardContent,{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"font-mono text-xs text-muted-foreground",children:[$.frontmatter.source.repo,$.frontmatter.source.path&&` / ${$.frontmatter.source.path}`]}),$.frontmatter.source.url&&jsxRuntimeExports.jsxs("a",{href:$.frontmatter.source.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:["View on GitHub ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]}),$.frontmatter.source.license&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["License: ",$.frontmatter.source.license]})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs font-mono bg-muted/40 rounded p-3 max-h-[60vh] overflow-y-auto",children:$.content})})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Version ",$.version," · updated ",new Date($.updatedAt).toLocaleString()]})]})]})}const scopeColors={public:"bg-teal-500/15 text-teal-400 border-teal-500/30",org:"bg-blue-500/15 text-blue-400 border-blue-500/30",team:"bg-primary/15 text-primary border-primary/30",personal:"bg-muted text-muted-foreground border-border"};function SuggestionRow({suggestion:es,projectPath:$,verdict:ts}){const is=useLogSuggestionEvent(),cs=usePromoteFromPublic(),Kr=is.isPending||cs.isPending;async function Xr(){try{es.instructionScope==="public"&&await cs.mutateAsync({sourceInstructionId:es.instructionId,targetScope:"personal"}),await is.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Accepted: ${es.name}`)}catch(Ca){ue$1.error(`Failed: ${Ca.message}`)}}async function Na(){try{await is.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(Ca){ue$1.error(`Failed: ${Ca.message}`)}}return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0 basis-56 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:scopeColors[es.instructionScope]??scopeColors.personal,children:es.instructionScope}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),es.isStale&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"stale"}),(ts==null?void 0:ts.sufficient)&&jsxRuntimeExports.jsx(VerdictBadge,{verdict:ts})]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generated ",formatDistanceToNow(es.generatedAt)]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 shrink-0",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Xr,disabled:Kr,children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 mr-1"}),"Accept"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:Na,disabled:Kr,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]})]})}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,cs=ts.some(Aa=>Aa.isLoading),Kr=ts.map((Aa,Ia)=>{var Ma;return{projectPath:$[Ia],suggestions:((Ma=Aa.data)==null?void 0:Ma.suggestions)??[],isLoading:Aa.isLoading}}).filter(Aa=>Aa.projectPath),Xr=Kr.reduce((Aa,Ia)=>Aa+Ia.suggestions.length,0),Na=Kr.flatMap(Aa=>Aa.suggestions.map(Ia=>Ia.instructionId)),{data:Ca}=useSuggestionImpacts(Na);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-6 w-6"}),"Suggestions"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Precomputed instruction suggestions for your recent projects. Updated daily at 04:30."})]}),is?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:3}).map((Aa,Ia)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ia))}):Kr.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No recent projects found. Run a session through Claude Code or Cursor to populate this view."}):!cs&&Xr===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No suggestions yet. The cron runs daily at 04:30 and scores your recent projects against your library."}):jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Kr.map(Aa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Aa.projectPath})}),jsxRuntimeExports.jsx(CardContent,{children:Aa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}):Aa.suggestions.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions for this project."}):jsxRuntimeExports.jsx("div",{children:Aa.suggestions.map(Ia=>jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Aa.projectPath,verdict:Ca==null?void 0:Ca[Ia.instructionId]},Ia.id))})})]},Aa.projectPath))})]})}function tierFor(es){return es>=95?"red":es>=80?"orange":es>=60?"yellow":"green"}const TIER_COLOR={green:"stroke-teal-500",yellow:"stroke-yellow-500",orange:"stroke-orange-500",red:"stroke-red-500"},TIER_TEXT={green:"text-teal-600",yellow:"text-yellow-600",orange:"text-orange-600",red:"text-red-600"};function formatCountdown(es,$){const ts=es.getTime()-$.getTime();if(ts<=0)return"resetting now";const is=Math.floor(ts/6e4),cs=Math.floor(is/1440),Kr=Math.floor((is-cs*60*24)/60),Xr=is-cs*60*24-Kr*60;return cs>0?`resets in ${cs}d ${Kr}h`:Kr>0?`resets in ${Kr}h ${Xr}m`:`resets in ${Xr}m`}function formatObservedAt(es,$){const ts=$.getTime()-es.getTime();if(ts<6e4)return{label:"live",fresh:!0};const is=Math.floor(ts/6e4);return is<60?{label:`synced ${is}m ago`,fresh:!1}:{label:`synced ${Math.floor(is/60)}h ago`,fresh:!1}}function Ring({pct:es,tier:$}){const is=2*Math.PI*30,Kr=Math.max(0,Math.min(100,es))/100*is;return jsxRuntimeExports.jsxs("svg",{width:80,height:80,viewBox:"0 0 80 80",className:"-rotate-90",children:[jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",className:"stroke-muted"}),jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",strokeLinecap:"round",strokeDasharray:`${Kr} ${is}`,className:cn$1("transition-all duration-500",TIER_COLOR[$])})]})}function LimitRing(es){const{label:$,usedPercentage:ts,resetsAt:is,observedAt:cs,inferredCap:Kr,unit:Xr,confidenceBandPct:Na,capQualifier:Ca="inferred cap",providerReported:Aa=!1}=es,[Ia,Ma]=reactExports.useState(()=>new Date);reactExports.useEffect(()=>{const Ga=setInterval(()=>Ma(new Date),6e4);return()=>clearInterval(Ga)},[]);const Pa=ts!=null,La=ts??0,Fa=tierFor(La),Ba=La>=100?{icon:Ban,text:"hit",color:"text-red-600"}:La>=95?{icon:TriangleAlert,text:"imminent",color:"text-red-600"}:La>=80?{icon:TriangleAlert,text:"approaching",color:"text-yellow-600"}:null,qa=is?formatCountdown(new Date(is),Ia):"—",za=cs?formatObservedAt(new Date(cs),Ia):null,Va=Pa&&Kr!=null?Math.round(La/100*Kr):null;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx(Ring,{pct:La,tier:Fa}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:$}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-mono",TIER_TEXT[Fa]),children:Pa?`${Math.round(La)}%`:"—"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:qa}),za?jsxRuntimeExports.jsx("span",{className:cn$1("text-xs",za.fresh?"text-teal-600":"text-muted-foreground"),children:za.fresh?"✓ live":za.label}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"? unknown"})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Aa?jsxRuntimeExports.jsx("span",{className:"cursor-help font-mono",children:"Provider-reported quota window percentage"}):jsxRuntimeExports.jsxs("span",{className:"cursor-help font-mono",children:["≈"," ",Va??"?"," ","/ ",Kr??"?"," ",Xr," (",Ca," · ±",Na,"%)"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:Aa?"Reported directly by the provider's rate-limit feed — the percentage is authoritative, not an estimate.":"Estimate based on Anthropic-published ranges. Actuals vary per user."})})]})}),Ba?jsxRuntimeExports.jsxs("span",{className:cn$1("flex items-center gap-1 font-mono",Ba.color),children:[jsxRuntimeExports.jsx(Ba.icon,{className:"h-3 w-3"}),Ba.text]}):null]}),Pa?null:jsxRuntimeExports.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:Aa?"no observation yet — run this tool through the proxy":"~ estimated · no observation yet"})]})]})}const SOURCE_LABEL="Live usage · all tracked tools",COST_POLL_MS=3e4,RATE_LIMIT_RINGS=[{key:"five_hour",label:"5-hour window",unit:"msgs"},{key:"seven_day",label:"7-day (Sonnet tier)",unit:"hrs"},{key:"seven_day_opus",label:"7-day (Opus tier)",unit:"hrs"}],CODEX_RINGS=[{key:"five_hour",label:"Codex 5-hour window"},{key:"seven_day",label:"Codex 7-day window"}],PLAN_LABELS={max_20x:"Max-20x",max_5x:"Max-5x",pro:"Pro"};function planLabel(es){return PLAN_LABELS[es]??es}function startOfMonthIso(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function UsagePage(){var Xa,Ja,tl,sl,ol,ml,rl,ll,dl,_l,il,hl,ul,cl,jl,el,pl,bl,Ol,Pl;const es=useCurrentLimits(),$=useCurrentLimits("codex"),ts=useInferredCaps(),is=startOfMonthIso(),cs=useComputedInsights(void 0,void 0,{since:is,refetchIntervalMs:COST_POLL_MS}),Kr=((Xa=es.data)==null?void 0:Xa.five_hour)??null,Xr=((Ja=es.data)==null?void 0:Ja.seven_day)??null,Na=((tl=es.data)==null?void 0:tl.seven_day_opus)??null,Ca=((sl=$.data)==null?void 0:sl.five_hour)??null,Aa=((ol=$.data)==null?void 0:ol.seven_day)??null,Ia={five_hour:Ca,seven_day:Aa},Ma=!!(Ca||Aa),Pa=((ml=ts.data)==null?void 0:ml.five_hour_percent.inferred_cap)??null,La=((rl=ts.data)==null?void 0:rl.five_hour_percent.confidence_band_pct)??20,Fa=((ll=ts.data)==null?void 0:ll.seven_day_percent.inferred_cap)??null,Ba=((dl=ts.data)==null?void 0:dl.seven_day_percent.confidence_band_pct)??20,qa=((_l=ts.data)==null?void 0:_l.seven_day_opus_percent.inferred_cap)??null,za=((il=ts.data)==null?void 0:il.seven_day_opus_percent.confidence_band_pct)??20,Va=ts.data?`${planLabel(ts.data.plan)}${ts.data.assumed?" est.":""}`:"inferred cap",Ga=es.isLoading||ts.isLoading,Za={five_hour:{obs:Kr,cap:Pa,band:La},seven_day:{obs:Xr,cap:Fa,band:Ba},seven_day_opus:{obs:Na,cap:qa,band:za}},Qa=new Date(is).toLocaleString(void 0,{month:"long",year:"numeric"});return jsxRuntimeExports.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Gauge,{className:"h-6 w-6 text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"font-mono text-xl font-semibold",children:"Usage"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:SOURCE_LABEL})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-4",children:[jsxRuntimeExports.jsx("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),Ga?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]}):es.isError?jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsxs("span",{children:["Couldn't load rate limits",es.error instanceof Error?`: ${es.error.message}`:"",". Retrying…"]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Claude Code"}),RATE_LIMIT_RINGS.map(Fl=>{var Kl,wl,$l;const Nl=Za[Fl.key];return jsxRuntimeExports.jsx(LimitRing,{label:Fl.label,usedPercentage:((Kl=Nl.obs)==null?void 0:Kl.used_percentage)??null,resetsAt:((wl=Nl.obs)==null?void 0:wl.resets_at)??null,observedAt:(($l=Nl.obs)==null?void 0:$l.observed_at)??null,inferredCap:Nl.cap,unit:Fl.unit,confidenceBandPct:Nl.band,capQualifier:Va},Fl.key)})]}),Ma?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Codex"}),CODEX_RINGS.map(Fl=>{const Nl=Ia[Fl.key];return jsxRuntimeExports.jsx(LimitRing,{label:Fl.label,usedPercentage:(Nl==null?void 0:Nl.used_percentage)??null,resetsAt:(Nl==null?void 0:Nl.resets_at)??null,observedAt:(Nl==null?void 0:Nl.observed_at)??null,inferredCap:null,unit:"",confidenceBandPct:0,providerReported:!0},Fl.key)})]}):null]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:["Estimated cost · ",Qa]}),cs.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:((hl=cs.data)==null?void 0:hl.estimated_cost_usd)??0,breakdown:(ul=cs.data)==null?void 0:ul.estimated_cost_breakdown,inputTokens:((cl=cs.data)==null?void 0:cl.total_input_tokens)??0,outputTokens:((jl=cs.data)==null?void 0:jl.total_output_tokens)??0,cacheReadTokens:((el=cs.data)==null?void 0:el.total_cache_read_tokens)??0,cacheWriteTokens:((pl=cs.data)==null?void 0:pl.total_cache_write_tokens)??0,byModel:(bl=cs.data)==null?void 0:bl.estimated_cost_by_model,byTool:(Ol=cs.data)==null?void 0:Ol.estimated_cost_by_tool}),(Pl=cs.data)!=null&&Pl.truncated?jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 flex-shrink-0"}),"Showing your 500 most recent sessions this month — older sessions in the window aren't counted, so this is a lower bound."]}):null]})]})]})}function AdminOverviewPage(){var Ca,Aa,Ia,Ma,Pa,La;const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQuery({queryKey:["org-detail",$],queryFn:()=>getOrg($),enabled:!!$}),is=useQuery({queryKey:["org-activity",$,"7d"],queryFn:()=>getOrgActivity($,"7d"),enabled:!!$}),cs=(Ca=ts.data)==null?void 0:Ca.members.length,Kr=(Aa=ts.data)==null?void 0:Aa.teams.length,Xr=(Ia=is.data)==null?void 0:Ia.sessionCount,Na=((La=(Pa=(Ma=is.data)==null?void 0:Ma.topTools)==null?void 0:Pa[0])==null?void 0:La.tool)??null;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Building2,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Organization admin"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:(es==null?void 0:es.name)??"—"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:es==null?void 0:es.slug}),es&&jsxRuntimeExports.jsxs("span",{className:"ml-2 capitalize",children:["· you are ",es.role]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members",children:"Members"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members/invitations",children:"Pending invites"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/settings",children:"Settings"})})]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Members",value:cs,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Layers,{className:"h-4 w-4"}),label:"Teams",value:Kr,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Sessions (7d)",value:Xr,loading:is.isLoading,error:!!is.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:Na??"—",loading:is.isLoading,error:!!is.error})]})]})}function StatCard$1({icon:es,label:$,value:ts,loading:is,error:cs}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):cs?jsxRuntimeExports.jsx("span",{className:"text-sm text-destructive",children:"failed to load"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}const NO_TEAM="__none";function InviteDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState("member"),[Ca,Aa]=reactExports.useState(NO_TEAM),[Ia,Ma]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(""),Na("member"),Aa(NO_TEAM),Ma(null))},[es]);const Pa=useQuery({queryKey:["org-teams",ts],queryFn:()=>listTeams(ts),enabled:es&&!!ts}),La=useMutation({mutationFn:Ba=>createInvitation(ts,Ba),onSuccess:Ba=>{Ba.emailSent?ue$1.success(`Invitation sent to ${Ba.email}`):ue$1.warning("Invite created, but the email could not be sent",{description:Ba.emailError?`${Ba.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var qa;(qa=navigator.clipboard)==null||qa.writeText(Ba.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy — the link is in the invite row"))}}}),is.invalidateQueries({queryKey:["org-invitations",ts]}),$(!1)},onError:Ba=>{if(Ba instanceof ApiError){if(Ba.code==="INVITE_ALREADY_PENDING"){Ma("There's already a pending invitation for this email. Resend it from the Pending Invites page instead.");return}if(Ba.code==="INVALID_TEAM"){Ma("That team no longer exists in this organization. Refresh and try again.");return}ue$1.error(Ba.message);return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to send invite")}});function Fa(Ba){Ba.preventDefault(),Ma(null);const qa=cs.trim();if(!qa){Ma("Email is required.");return}if(!/^\S+@\S+\.\S+$/.test(qa)){Ma("Enter a valid email address.");return}La.mutate({email:qa,role:Xr,...Ca!==NO_TEAM?{teamId:Ca}:{}})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite a member"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Send an invitation email. The recipient gets a link that's valid for 7 days."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",autoComplete:"off",value:cs,onChange:Ba=>Kr(Ba.target.value),placeholder:"teammate@example.com",required:!0,disabled:La.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-role",children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Xr,onValueChange:Ba=>Na(Ba),disabled:La.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-role",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Admins can invite, remove, and re-role other members. Members have read-only access to admin pages."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-team",children:"Team (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Ca,onValueChange:Aa,disabled:La.isPending||Pa.isLoading,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-team",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"No team"})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:NO_TEAM,children:"No team"}),(Pa.data??[]).map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba.id,children:Ba.name},Ba.id))]})]}),Pa.error&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-destructive",children:["Couldn't load teams: ",Pa.error.message]})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:La.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:La.isPending,className:"cursor-pointer",children:La.isPending?"Sending…":"Send invitation"})]})]})]})})}function AdminMembersPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",$],queryFn:()=>listMembers($),enabled:!!$}),Ca=useMutation({mutationFn:({userId:Ma,role:Pa})=>updateMemberRole($,Ma,Pa),onSuccess:()=>{ue$1.success("Role updated"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]})},onError:Ma=>{Ma instanceof ApiError&&Ma.code==="LAST_OWNER"?ue$1.error("Cannot demote the last owner."):ue$1.error(Ma instanceof Error?Ma.message:"Failed to update role"),ts.invalidateQueries({queryKey:["org-members",$]})}}),Aa=useMutation({mutationFn:Ma=>removeMember($,Ma),onSuccess:()=>{ue$1.success("Member removed"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]}),Xr(null)},onError:Ma=>{Ma instanceof ApiError&&Ma.code==="LAST_OWNER"?ue$1.error("Cannot remove the last owner."):ue$1.error(Ma instanceof Error?Ma.message:"Failed to remove member")}}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Members"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage who has access to"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"}),"."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members/invitations",children:[jsxRuntimeExports.jsx(Mail,{className:"mr-2 h-4 w-4"}),"Pending invites"]})}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Teams"}),jsxRuntimeExports.jsx(TableHead,{children:"Last active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$2,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No members yet."})}):Ia.map(Ma=>{var Pa;return jsxRuntimeExports.jsx(MemberRow,{member:Ma,pending:Ca.isPending&&((Pa=Ca.variables)==null?void 0:Pa.userId)===Ma.userId,onRoleChange:La=>Ca.mutate({userId:Ma.userId,role:La}),onRemove:()=>Xr(Ma)},Ma.userId)})})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(RemoveMemberDialog$1,{member:Kr,onCancel:()=>Xr(null),onConfirm:()=>Kr&&Aa.mutate(Kr.userId),pending:Aa.isPending})]})}function MemberRow({member:es,pending:$,onRoleChange:ts,onRemove:is}){const cs=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:cs})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(Select,{value:es.role,onValueChange:Kr=>ts(Kr),disabled:$,children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32 capitalize",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"Owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"})]})]})}),jsxRuntimeExports.jsx(TableCell,{children:es.teams.length===0?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.teams.map(Kr=>jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-xs",children:Kr.name},Kr.id))})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:es.lastActiveAt?formatDistanceToNow(es.lastActiveAt):"never"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:is,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from organization"})})]})})]})}function SkeletonRows$2(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:4}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-32"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}function RemoveMemberDialog$1({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove member?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will lose access to the organization. They can be re-invited later."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function formatDistanceToFuture(es){const $=new Date(es).getTime(),ts=Date.now(),is=$-ts;if(is<=0)return"expired";const cs=Math.floor(is/6e4),Kr=Math.floor(is/36e5),Xr=Math.floor(is/864e5);return cs<1?"<1m":cs<60?`in ${cs}m`:Kr<24?`in ${Kr}h`:`in ${Xr}d`}function AdminInvitationsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-invitations",$],queryFn:()=>listInvitations($),enabled:!!$}),Ca=useMutation({mutationFn:Ma=>resendInvitation($,Ma),onSuccess:Ma=>{Ma.emailSent?ue$1.success(`Resent invitation to ${Ma.email}`):ue$1.warning("Invite link refreshed, but the email could not be sent",{description:Ma.emailError?`${Ma.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Pa;(Pa=navigator.clipboard)==null||Pa.writeText(Ma.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy the invite link"))}}}),ts.invalidateQueries({queryKey:["org-invitations",$]})},onError:Ma=>ue$1.error(Ma instanceof Error?Ma.message:"Failed to resend invitation")}),Aa=useMutation({mutationFn:Ma=>revokeInvitation($,Ma),onSuccess:()=>{ue$1.success("Invitation revoked"),ts.invalidateQueries({queryKey:["org-invitations",$]}),Xr(null)},onError:Ma=>ue$1.error(Ma instanceof Error?Ma.message:"Failed to revoke invitation")}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",size:"sm",className:"cursor-pointer mb-2 -ml-2 text-muted-foreground",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"}),"Back to members"]})}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Pending invitations"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"Sent but not yet accepted. Invitations expire 7 days after they're issued or last resent."})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load invitations:"," ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Team"}),jsxRuntimeExports.jsx(TableHead,{children:"Invited by"}),jsxRuntimeExports.jsx(TableHead,{children:"Expires"}),jsxRuntimeExports.jsx(TableHead,{className:"w-48 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$1,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No pending invitations. Send one from the Members tab."})}):Ia.map(Ma=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:Ma.email}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize",children:Ma.role})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Ma.teamName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Ma.invitedByName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:formatDistanceToFuture(Ma.expiresAt)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",disabled:Ca.isPending&&Ca.variables===Ma.id,onClick:()=>Ca.mutate(Ma.id),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Resend"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>Xr(Ma),className:"cursor-pointer text-destructive hover:text-destructive",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-1 h-3 w-3"}),"Revoke"]})]})})]},Ma.id))})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(Dialog,{open:!!Kr,onOpenChange:Ma=>{Ma||Xr(null)},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Revoke invitation?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[Kr!=null&&Kr.email?`${Kr.email} will no longer be able to accept this invitation.`:"This invitation will be revoked."," ","You can send a new one from the Members tab."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Xr(null),disabled:Aa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>Kr&&Aa.mutate(Kr.id),disabled:Aa.isPending,className:"cursor-pointer",children:Aa.isPending?"Revoking…":"Revoke"})]})]})})]})}function SkeletonRows$1(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"})]})})]},$))})}const SLUG_REGEX$2=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify$1(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function AdminTeamsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",[ts,is]=reactExports.useState(!1),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(null),Ca=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Aa=Ca.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Teams"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Group members of"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"})," ","to scope activity dashboards."]})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New team"]})]}),Ca.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load teams: ",Ca.error.message]}):Ca.isLoading?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Array.from({length:4}).map((Ia,Ma)=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20 mt-2"})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})})]},Ma))}):Aa.length===0?jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx(Layers,{className:"h-10 w-10 text-muted-foreground mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No teams yet."}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create one to start grouping members."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",variant:"outline",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create team"]})]}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Aa.map(Ia=>jsxRuntimeExports.jsx(TeamCard,{team:Ia,onRename:()=>Kr(Ia),onDelete:()=>Na(Ia)},Ia.id))}),jsxRuntimeExports.jsx(CreateTeamDialog,{open:ts,onOpenChange:is,orgSlug:$}),jsxRuntimeExports.jsx(RenameTeamDialog,{team:cs,orgSlug:$,onClose:()=>Kr(null)}),jsxRuntimeExports.jsx(DeleteTeamDialog,{team:Xr,orgSlug:$,onClose:()=>Na(null)})]})}function TeamCard({team:es,onRename:$,onDelete:ts}){return jsxRuntimeExports.jsxs(Card,{className:"relative",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx(CardTitle,{className:"truncate",children:jsxRuntimeExports.jsx(Link,{to:`/admin/teams/${encodeURIComponent(es.slug)}`,className:"hover:underline",children:es.name})}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:jsxRuntimeExports.jsx("code",{children:es.slug})})]}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer -mr-2 -mt-1",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Team actions"})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"cursor-pointer",children:"Rename"}),jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:ts,className:"text-destructive focus:text-destructive cursor-pointer",children:"Delete"})]})]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),es.memberCount," ",es.memberCount===1?"member":"members"]})})]})}function CreateTeamDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(!1),[Ia,Ma]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(""),Na(""),Aa(!1),Ma(null))},[es]);const Pa=useMutation({mutationFn:Ba=>createTeam(ts,Ba),onSuccess:()=>{ue$1.success("Team created"),is.invalidateQueries({queryKey:["org-teams",ts]}),is.invalidateQueries({queryKey:["org-detail",ts]}),$(!1)},onError:Ba=>{if(Ba instanceof ApiError&&Ba.code==="TEAM_SLUG_TAKEN"){Ma("That slug is already in use by another team.");return}if(Ba instanceof ApiError&&Ba.code==="VALIDATION_ERROR"){Ma("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to create team")}});function La(Ba){Kr(Ba),Ca||Na(slugify$1(Ba))}function Fa(Ba){Ba.preventDefault(),Ma(null);const qa=cs.trim(),za=Xr.trim();if(!qa){Ma("Name is required.");return}if(!SLUG_REGEX$2.test(za)){Ma("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Pa.mutate({name:qa,slug:za})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"New team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Teams group members of an organization for scoped activity views."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"team-name",value:cs,onChange:Ba=>La(Ba.target.value),placeholder:"Platform",required:!0,disabled:Pa.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"team-slug",value:Xr,onChange:Ba=>{Na(Ba.target.value),Aa(!0)},placeholder:"platform",required:!0,disabled:Pa.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs."})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Pa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Pa.isPending,className:"cursor-pointer",children:Pa.isPending?"Creating…":"Create team"})]})]})]})})}function RenameTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(es.name),Na(es.slug),Aa(null))},[es]);const Ia=useMutation({mutationFn:({name:Pa,slug:La})=>updateTeam($,es.id,{name:Pa,slug:La}),onSuccess:()=>{ue$1.success("Team updated"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Pa=>{if(Pa instanceof ApiError&&Pa.code==="TEAM_SLUG_TAKEN"){Aa("That slug is already in use by another team.");return}if(Pa instanceof ApiError&&Pa.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Pa instanceof Error?Pa.message:"Failed to update team")}});function Ma(Pa){Pa.preventDefault(),Aa(null);const La=cs.trim(),Fa=Xr.trim();if(!La){Aa("Name is required.");return}if(!SLUG_REGEX$2.test(Fa)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ia.mutate({name:La,slug:Fa})}return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Pa=>{Pa||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Rename team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Change the team's display name and/or URL slug."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ma,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-name",value:cs,onChange:Pa=>Kr(Pa.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-slug",value:Xr,onChange:Pa=>Na(Pa.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing the slug breaks any bookmarked links to this team."})]}),Ca&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ca}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:Ia.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})]})]})]})})}function DeleteTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),cs=useMutation({mutationFn:()=>deleteTeam($,es.id),onSuccess:()=>{ue$1.success("Team deleted"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Kr=>{ue$1.error(Kr instanceof Error?Kr.message:"Failed to delete team")}});return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Kr=>{Kr||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:es==null?void 0:es.name})," will be permanently deleted. Members will remain in the organization but will no longer be grouped under this team."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:cs.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>cs.mutate(),disabled:cs.isPending,className:"cursor-pointer",children:cs.isPending?"Deleting…":"Delete"})]})]})})}function TeamDetailPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",{teamSlug:ts=""}=useParams(),[is,cs]=useTabParam(["members","activity"],"members"),Kr=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Xr=reactExports.useMemo(()=>{var Na;return((Na=Kr.data)==null?void 0:Na.find(Ca=>Ca.slug===ts))??null},[Kr.data,ts]);return Kr.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]}):Kr.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load team: ",Kr.error.message]}):Xr?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between gap-4",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-3 w-3"}),"All teams"]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:Xr.name}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:Xr.slug}),jsxRuntimeExports.jsxs("span",{className:"ml-2",children:["· ",Xr.memberCount," ",Xr.memberCount===1?"member":"members"]})]})]})}),jsxRuntimeExports.jsxs(Tabs,{value:is,onValueChange:cs,children:[jsxRuntimeExports.jsxs(TabsList,{variant:"line",children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"members",children:"Members"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"activity",children:"Activity"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"members",className:"pt-4",children:jsxRuntimeExports.jsx(MembersTab,{orgSlug:$,teamId:Xr.id})}),jsxRuntimeExports.jsx(TabsContent,{value:"activity",className:"pt-4",children:jsxRuntimeExports.jsx(ActivityTab,{orgSlug:$,teamId:Xr.id})})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Team not found"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["No team with slug ",jsxRuntimeExports.jsx("code",{className:"text-xs",children:ts})," in this organization."]}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to teams"]})})]})}function MembersTab({orgSlug:es,teamId:$}){const ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),Ca=reactExports.useMemo(()=>(Na.data??[]).filter(Ma=>Ma.teams.some(Pa=>Pa.id===$)),[Na.data,$]),Aa=reactExports.useMemo(()=>(Na.data??[]).filter(Ma=>!Ma.teams.some(Pa=>Pa.id===$)),[Na.data,$]),Ia=useMutation({mutationFn:Ma=>removeTeamMember(es,$,Ma),onSuccess:()=>{ue$1.success("Member removed from team"),ts.invalidateQueries({queryKey:["org-members",es]}),ts.invalidateQueries({queryKey:["org-teams",es]}),Xr(null)},onError:Ma=>{ue$1.error(Ma instanceof Error?Ma.message:"Failed to remove member")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Members in this team. Adding a member here doesn't change their organization role — only the team grouping."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Add member"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Org role"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows,{}):Ca.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No members in this team yet."})}):Ca.map(Ma=>jsxRuntimeExports.jsx(TeamMemberRow,{member:Ma,onRemove:()=>Xr(Ma)},Ma.userId))})]})}),jsxRuntimeExports.jsx(AddMemberDialog,{open:is,onOpenChange:cs,orgSlug:es,teamId:$,addable:Aa,loading:Na.isLoading}),jsxRuntimeExports.jsx(RemoveMemberDialog,{member:Kr,onCancel:()=>Xr(null),onConfirm:()=>Kr&&Ia.mutate(Kr.userId),pending:Ia.isPending})]})}function TeamMemberRow({member:es,onRemove:$}){const ts=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:ts})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"capitalize",children:es.role})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from team"})})]})})]})}function SkeletonRows(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}const NO_USER="__none";function AddMemberDialog({open:es,onOpenChange:$,orgSlug:ts,teamId:is,addable:cs,loading:Kr}){const Xr=useQueryClient(),[Na,Ca]=reactExports.useState(NO_USER),[Aa,Ia]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Ca(NO_USER),Ia(null))},[es]);const Ma=useMutation({mutationFn:La=>addTeamMember(ts,is,La),onSuccess:()=>{ue$1.success("Member added to team"),Xr.invalidateQueries({queryKey:["org-members",ts]}),Xr.invalidateQueries({queryKey:["org-teams",ts]}),$(!1)},onError:La=>{ue$1.error(La instanceof Error?La.message:"Failed to add member")}});function Pa(La){if(La.preventDefault(),Na===NO_USER){Ia("Pick a member to add.");return}Ma.mutate(Na)}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Add member to team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Pick an organization member to add. Only members not already on this team are listed."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Pa,className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"space-y-2",children:jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:La=>{Ca(La),Ia(null)},disabled:Ma.isPending||Kr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:Kr?"Loading…":"Select member"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.length===0?jsxRuntimeExports.jsx(SelectItem,{value:NO_USER,disabled:!0,children:Kr?"Loading…":"All org members are on this team."}):cs.map(La=>jsxRuntimeExports.jsx(SelectItem,{value:La.userId,children:La.email??La.displayName??La.userId},La.userId))})]})}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ma.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ma.isPending||cs.length===0||Na===NO_USER,className:"cursor-pointer",children:Ma.isPending?"Adding…":"Add"})]})]})]})})}function RemoveMemberDialog({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove from team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will no longer be grouped under this team. They'll remain in the organization."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function ActivityTab({orgSlug:es,teamId:$}){var Xr,Na;const[ts,is]=reactExports.useState("7d"),cs=useQuery({queryKey:["team-activity",es,$,ts],queryFn:()=>getTeamActivity(es,$,ts),enabled:!!es&&!!$});if(cs.error)return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load activity: ",cs.error.message]});const Kr=cs.data;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end",children:jsxRuntimeExports.jsxs(Select,{value:ts,onValueChange:Ca=>is(Ca),children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"7d",children:"Last 7 days"}),jsxRuntimeExports.jsx(SelectItem,{value:"30d",children:"Last 30 days"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:`Sessions (${ts})`,value:Kr==null?void 0:Kr.sessionCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Active members",value:Kr==null?void 0:Kr.memberCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:((Na=(Xr=Kr==null?void 0:Kr.topTools)==null?void 0:Xr[0])==null?void 0:Na.tool)??"—",loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Avg friction",value:Kr!=null&&Kr.frictionTrend&&Kr.frictionTrend.length>0?(Kr.frictionTrend.reduce((Ca,Aa)=>Ca+Aa.avgFriction,0)/Kr.frictionTrend.length).toFixed(2):"—",loading:cs.isLoading})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsx(TopToolsCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(TopMembersCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(FrictionTrendCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(InstructionEffectivenessCard,{data:Kr,loading:cs.isLoading})]})]})}function StatCard({icon:es,label:$,value:ts,loading:is}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}function TopToolsCard({data:es,loading:$}){var cs;const ts=(es==null?void 0:es.topTools)??[],is=((cs=ts[0])==null?void 0:cs.count)??0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top tools"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(Kr=>jsxRuntimeExports.jsxs("li",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:Kr.tool}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:Kr.count})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?Kr.count/is*100:0}%`}})})]},Kr.tool))})})]})}function TopMembersCard({data:es,loading:$}){const ts=(es==null?void 0:es.topMembers)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top members"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.email??is.displayName??is.userId}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:is.count})]},is.userId))})})]})}function FrictionTrendCard({data:es,loading:$}){const ts=(es==null?void 0:es.frictionTrend)??[],is=ts.reduce((cs,Kr)=>Math.max(cs,Kr.avgFriction),0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Friction trend"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction data in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1.5",children:ts.map(cs=>jsxRuntimeExports.jsxs("li",{className:"space-y-0.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:cs.day}),jsxRuntimeExports.jsx("span",{className:"font-medium tabular-nums",children:cs.avgFriction.toFixed(2)})]}),jsxRuntimeExports.jsx("div",{className:"h-1 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?cs.avgFriction/is*100:0}%`}})})]},cs.day))})})]})}function InstructionEffectivenessCard({data:es,loading:$}){const ts=(es==null?void 0:es.instructionEffectiveness)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Instruction effectiveness"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked instructions in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx(Link,{to:`/instructions/${is.instructionId}`,className:"truncate font-medium hover:underline",children:is.name}),jsxRuntimeExports.jsx("span",{className:is.deltaPct==null?"text-muted-foreground tabular-nums":is.deltaPct>=0?"text-teal-600 dark:text-teal-500 tabular-nums":"text-destructive tabular-nums",children:is.deltaPct==null?"—":`${is.deltaPct>=0?"+":""}${is.deltaPct.toFixed(1)}%`})]},is.instructionId))})})]})}const SLUG_REGEX$1=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function AdminSettingsPage(){const{activeOrg:es}=useActiveOrg();if(!es)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]});const $=es.role==="owner";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:es.name}),"'s name, slug, ownership, and lifecycle."]})]}),jsxRuntimeExports.jsx(GeneralSection,{orgName:es.name,orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(TransferOwnershipSection,{orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(DeleteOrgSection,{orgName:es.name,orgSlug:es.slug})]})}function Section({title:es,description:$,destructive:ts,children:is}){return jsxRuntimeExports.jsx(Card,{className:ts?"border-destructive/30":void 0,children:jsxRuntimeExports.jsx(CardContent,{className:"p-6",children:jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-[200px_1fr]",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h3",{className:ts?"font-mono text-base font-semibold text-destructive":"font-mono text-base font-semibold",children:es}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:is})]})})})}function GeneralSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useNavigate(),[cs,Kr]=reactExports.useState(es),[Xr,Na]=reactExports.useState($),[Ca,Aa]=reactExports.useState(null);reactExports.useEffect(()=>{Kr(es),Na($),Aa(null)},[es,$]);const Ia=useMutation({mutationFn:La=>updateOrg($,La),onSuccess:La=>{ue$1.success("Organization updated"),ts.invalidateQueries({queryKey:["profile"]}),ts.invalidateQueries({queryKey:["orgs"]}),ts.invalidateQueries({queryKey:["org-detail",$]}),La.slug!==$&&is("/admin/settings",{replace:!0})},onError:La=>{if(La instanceof ApiError&&La.code==="ORG_SLUG_TAKEN"){Aa("That slug is already taken by another organization.");return}if(La instanceof ApiError&&La.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(La instanceof Error?La.message:"Failed to update organization")}});function Ma(La){La.preventDefault(),Aa(null);const Fa=cs.trim(),Ba=Xr.trim();if(!Fa){Aa("Name is required.");return}if(!SLUG_REGEX$1.test(Ba)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}const qa={};Fa!==es&&(qa.name=Fa),Ba!==$&&(qa.slug=Ba),!(!qa.name&&!qa.slug)&&Ia.mutate(qa)}const Pa=cs.trim()!==es||Xr.trim()!==$;return jsxRuntimeExports.jsx(Section,{title:"General",description:"The display name and URL slug of this organization.",children:jsxRuntimeExports.jsxs("form",{onSubmit:Ma,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:cs,onChange:La=>Kr(La.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:Xr,onChange:La=>Na(La.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands. Changing the slug breaks any bookmarked links."})]}),Ca&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ca}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending||!Pa,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})})]})})}function TransferOwnershipSection({orgSlug:es}){const $=useQueryClient(),ts=useNavigate(),is=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),cs=reactExports.useMemo(()=>(is.data??[]).filter(Ma=>Ma.role==="admin"),[is.data]),[Kr,Xr]=reactExports.useState(null),[Na,Ca]=reactExports.useState(!1),Aa=useMutation({mutationFn:Ma=>transferOwnership(es,Ma),onSuccess:()=>{ue$1.success("Ownership transferred. You're now an admin."),$.invalidateQueries({queryKey:["org-members",es]}),$.invalidateQueries({queryKey:["orgs"]}),$.invalidateQueries({queryKey:["profile"]}),Ca(!1),ts("/admin/members")},onError:Ma=>{if(Ma instanceof ApiError&&Ma.code==="SAME_USER"){ue$1.error("You can't transfer ownership to yourself.");return}if(Ma instanceof ApiError&&Ma.code==="NOT_A_MEMBER"){ue$1.error("That user is no longer a member of this organization.");return}ue$1.error(Ma instanceof Error?Ma.message:"Failed to transfer ownership")}}),Ia=cs.find(Ma=>Ma.userId===Kr);return jsxRuntimeExports.jsxs(Section,{title:"Transfer ownership",description:"Promote another admin to owner. You will become an admin afterward.",children:[is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"}):cs.length===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No other admins to transfer to. Promote a member to admin first on the"," ",jsxRuntimeExports.jsx("a",{href:"/admin/members",className:"underline",children:"Members"})," ","page."]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"transfer-target",children:"New owner"}),jsxRuntimeExports.jsxs(Select,{value:Kr??"",onValueChange:Ma=>Xr(Ma),disabled:Aa.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"transfer-target",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select an admin…"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.map(Ma=>jsxRuntimeExports.jsx(SelectItem,{value:Ma.userId,children:Ma.email??Ma.displayName??Ma.userId},Ma.userId))})]})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:!Kr||Aa.isPending,onClick:()=>Ca(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ArrowRightLeft,{className:"mr-2 h-4 w-4"}),"Transfer ownership"]})})]}),jsxRuntimeExports.jsx(Dialog,{open:Na,onOpenChange:Ca,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Transfer ownership?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:(Ia==null?void 0:Ia.email)??(Ia==null?void 0:Ia.displayName)??"the selected user"})," ","will become the new owner of this organization. You'll keep admin access but lose the ability to delete the org or transfer ownership again."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Ca(!1),disabled:Aa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",onClick:()=>Kr&&Aa.mutate(Kr),disabled:!Kr||Aa.isPending,className:"cursor-pointer",children:Aa.isPending?"Transferring…":"Transfer"})]})]})})]})}function DeleteOrgSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useSetActiveOrg(),cs=useNavigate(),[Kr,Xr]=reactExports.useState(""),Na=Kr===$,Ca=useMutation({mutationFn:()=>deleteOrg($),onSuccess:async()=>{ue$1.success(`Deleted ${es}`);try{await is.mutateAsync(null)}catch{}ts.clear(),cs("/",{replace:!0})},onError:Aa=>{ue$1.error(Aa instanceof Error?Aa.message:"Failed to delete organization")}});return jsxRuntimeExports.jsxs(Section,{title:"Delete organization",description:"Permanently delete this organization, its teams, invitations, and member roles. Sessions are preserved (org_id is cleared).",destructive:!0,children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-destructive",children:"This action cannot be undone."})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Label,{htmlFor:"delete-confirm",children:["Type ",jsxRuntimeExports.jsx("code",{className:"text-xs font-mono px-1 rounded bg-muted",children:$})," to confirm"]}),jsxRuntimeExports.jsx(Input,{id:"delete-confirm",value:Kr,onChange:Aa=>Xr(Aa.target.value),autoComplete:"off",disabled:Ca.isPending})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"destructive",disabled:!Na||Ca.isPending,onClick:()=>Ca.mutate(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-2 h-4 w-4"}),Ca.isPending?"Deleting…":"Delete organization"]})})]})}function useActiveLimits(){return useQuery({queryKey:["research","active-limits"],queryFn:()=>apiGet("/api/research/active-limits")})}function useObservations(es={}){const $=new URLSearchParams;es.provider&&$.set("provider",es.provider),es.plan&&$.set("plan",es.plan),es.limitType&&$.set("limit_type",es.limitType),es.limit!=null&&$.set("limit",String(es.limit)),es.offset!=null&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["research","observations",es],queryFn:()=>apiGet(`/api/research/observations${ts?`?${ts}`:""}`)})}function useDocChanges(es){return useQuery({queryKey:["research","doc-changes","default"],queryFn:()=>apiGet("/api/research/doc-changes")})}function useDisagreements(es=14){return useQuery({queryKey:["research","disagreements",es],queryFn:()=>apiGet(`/api/research/disagreements?since_days=${es}`)})}function useConfidenceHistory(es,$,ts,is=90){return useQuery({queryKey:["research","confidence-history",es,$,ts,is],queryFn:()=>{const Kr=new URLSearchParams({provider:es,plan:$,limit_type:ts,days:String(is)});return apiGet(`/api/research/confidence-history?${Kr}`)},enabled:!!es&&!!$&&!!ts})}function ConfidenceBar({value:es}){const $=Math.max(0,Math.min(1,es))*100,ts=es>=.9?"high":es>=.6?"mid":"low",is=ts==="high"?"bg-teal-500":ts==="mid"?"bg-amber-500":"bg-rose-500";return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 w-16 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:`h-full ${is}`,style:{width:`${$}%`}})}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[$.toFixed(0),"%"]})]})}function ConfidenceTrendSparkline({provider:es,plan:$,limitType:ts,width:is=80,height:cs=20}){const{data:Kr,isLoading:Xr}=useConfidenceHistory(es,$,ts);if(Xr)return jsxRuntimeExports.jsx("div",{className:"h-5 w-20 animate-pulse rounded bg-muted"});const Na=(Kr==null?void 0:Kr.items)??[];if(Na.length===0)return jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});if(Na.length===1)return jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[(Na[0].confidence*100).toFixed(0),"%"]});const Ca=Na.map((La,Fa)=>Fa/(Na.length-1)*is),Aa=Na.map(La=>cs-La.confidence*cs),Ia=Ca.map((La,Fa)=>`${Fa===0?"M":"L"}${La.toFixed(1)},${Aa[Fa].toFixed(1)}`).join(" "),Ma=Na[Na.length-1].confidence,Pa=Ma>=.9?"stroke-teal-500":Ma>=.6?"stroke-amber-500":"stroke-rose-500";return jsxRuntimeExports.jsx("svg",{width:is,height:cs,viewBox:`0 0 ${is} ${cs}`,className:"overflow-visible",role:"img","aria-label":`Confidence trend (${Na.length} points)`,children:jsxRuntimeExports.jsx("path",{d:Ia,fill:"none",className:Pa,strokeWidth:1.5,strokeLinejoin:"round"})})}function ActiveLimitsTable(){const{data:es,isLoading:$,error:ts}=useActiveLimits();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load active limits."});const is=((es==null?void 0:es.items)??[]).slice().sort((cs,Kr)=>cs.provider!==Kr.provider?cs.provider.localeCompare(Kr.provider):cs.plan!==Kr.plan?cs.plan.localeCompare(Kr.plan):cs.limitType.localeCompare(Kr.limitType));return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No active limits recorded yet."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"}),jsxRuntimeExports.jsx(TableHead,{children:"Trend (90d)"}),jsxRuntimeExports.jsx(TableHead,{children:"Effective from"})]})}),jsxRuntimeExports.jsx(TableBody,{children:is.map(cs=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(cs.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:cs.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(cs.confidence)})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceTrendSparkline,{provider:cs.provider,plan:cs.plan,limitType:cs.limitType})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground",children:new Date(cs.effectiveFrom).toLocaleString()})]},`${cs.provider}-${cs.plan}-${cs.limitType}-${cs.effectiveFrom}`))})]})}function RecentDocChanges(){const{data:es,isLoading:$,error:ts}=useDocChanges(),[is,cs]=reactExports.useState(null);if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load doc snapshots."});const Xr=((es==null?void 0:es.items)??[]).slice().sort((Na,Ca)=>Na.changed!==Ca.changed?Na.changed?-1:1:new Date(Ca.latestFetchedAt).getTime()-new Date(Na.latestFetchedAt).getTime());return Xr.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No doc snapshots in window."}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border rounded-md border border-border",children:Xr.map(Na=>{const Ca=`${Na.provider}::${Na.docUrl}`,Aa=is===Ca;return jsxRuntimeExports.jsxs("li",{className:"px-3 py-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(Aa?null:Ca),className:"flex w-full items-center justify-between gap-3 text-left cursor-pointer",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:Na.provider}),Na.changed?jsxRuntimeExports.jsx(Badge,{variant:"default",className:"text-[10px]",children:"changed"}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px]",children:"stable"}),!Na.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]}),jsxRuntimeExports.jsx("div",{className:"truncate font-mono text-xs text-muted-foreground",children:Na.docUrl})]}),jsxRuntimeExports.jsx("div",{className:"flex-shrink-0 font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Na.latestFetchedAt).toLocaleString()})]}),Aa&&jsxRuntimeExports.jsx(DocSnapshotDetail,{group:Na})]},Ca)})})}function DocSnapshotDetail({group:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-2 border-l-2 border-border pl-3 space-y-1",children:es.snapshots.slice(0,5).map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:new Date($.fetchedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"truncate text-muted-foreground",children:$.contentHash.slice(0,12)}),!$.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]},$.id))})}function SourceBadge({sourceType:es}){const $=LABELS[es]??es,ts=VARIANTS[es]??"outline";return jsxRuntimeExports.jsx(Badge,{variant:ts,className:"font-mono text-[10px] uppercase tracking-wide",children:$})}const LABELS={oauth_usage:"live",self_observed_429:"429",official_docs:"docs",self_observed_lower_bound:"lower",community:"community",llm_research:"llm"},VARIANTS={oauth_usage:"default",self_observed_429:"destructive",official_docs:"secondary",self_observed_lower_bound:"outline",community:"outline",llm_research:"outline"},PAGE_SIZE=50,ANY="__any";function ObservationsList(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(0),Ca=useActiveLimits(),Aa=reactExports.useMemo(()=>{var Va;const Ba=new Set,qa=new Set,za=new Set;for(const Ga of((Va=Ca.data)==null?void 0:Va.items)??[])Ba.add(Ga.provider),qa.add(Ga.plan),za.add(Ga.limitType);return{providers:Array.from(Ba).sort(),plans:Array.from(qa).sort(),limitTypes:Array.from(za).sort()}},[Ca.data]),{data:Ia,isLoading:Ma,error:Pa}=useObservations({provider:es||void 0,plan:ts||void 0,limitType:cs||void 0,limit:PAGE_SIZE,offset:Xr}),La=(Ia==null?void 0:Ia.total)??0,Fa=(Ia==null?void 0:Ia.items)??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(FilterSelect,{label:"Provider",value:es,options:Aa.providers,onChange:Ba=>{$(Ba),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Plan",value:ts,options:Aa.plans,onChange:Ba=>{is(Ba),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Limit type",value:cs,options:Aa.limitTypes,onChange:Ba=>{Kr(Ba),Na(0)}}),jsxRuntimeExports.jsx("div",{className:"ml-auto font-mono text-xs text-muted-foreground tabular-nums",children:La>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Xr+1,"–",Math.min(Xr+PAGE_SIZE,La)," of ",La]})})]}),Ma?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):Pa?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load observations."}):Fa.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No observations match these filters."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Observed at"}),jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Source"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Fa.map(Ba=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Ba.observedAt).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(Ba.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:Ba.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(SourceBadge,{sourceType:Ba.sourceType})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(Ba.confidence)})})]},Ba.id))})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Xr===0,onClick:()=>Na(Math.max(0,Xr-PAGE_SIZE)),children:"Previous"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Xr+PAGE_SIZE>=La,onClick:()=>Na(Xr+PAGE_SIZE),children:"Next"})]})]})}function FilterSelect({label:es,value:$,options:ts,onChange:is}){return jsxRuntimeExports.jsxs(Select,{value:$||ANY,onValueChange:cs=>is(cs===ANY?"":cs),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"h-8 w-[180px] text-xs",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:es})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsxs(SelectItem,{value:ANY,children:["All ",es.toLowerCase(),"s"]}),ts.map(cs=>jsxRuntimeExports.jsx(SelectItem,{value:cs,className:"font-mono text-xs",children:cs},cs))]})]})}function DisagreementView(){const{data:es,isLoading:$,error:ts}=useDisagreements();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load disagreements."});const is=(es==null?void 0:es.items)??[];return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No disagreements (>20% spread) detected in the last 14 days."}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:is.map(cs=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[cs.provider," / ",cs.plan," / ",cs.limitType]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-destructive tabular-nums",children:["Δ ",cs.spreadPct.toFixed(1),"% (",cs.minValue.toLocaleString()," →"," ",cs.maxValue.toLocaleString(),")"]})]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.observations.map(Kr=>jsxRuntimeExports.jsxs("li",{className:"flex items-center gap-3 py-1.5 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"w-40 text-muted-foreground tabular-nums",children:new Date(Kr.observedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-24 text-right tabular-nums",children:Kr.value.toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-16 text-muted-foreground",children:Kr.unit}),jsxRuntimeExports.jsx(SourceBadge,{sourceType:Kr.sourceType}),jsxRuntimeExports.jsx("div",{className:"ml-auto",children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Kr.confidence})})]},Kr.id))})})]},`${cs.provider}-${cs.plan}-${cs.limitType}`))})}function AdminResearchPage(){const[es,$]=useTabParam(["active","docs","observations","disagreements"],"active");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Database,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Usage research"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:"Provider limits intelligence"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Fused view of provider rate-limits sourced from OAuth headers, 429 responses, official docs, and community signals."})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,className:"space-y-4",children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"active",children:"Active limits"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"docs",children:"Doc changes"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"observations",children:"Observations"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"disagreements",children:"Disagreements"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"active",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Active fused limits"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ActiveLimitsTable,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"docs",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Recent doc snapshots (7d)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(RecentDocChanges,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"observations",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Raw observations"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ObservationsList,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"disagreements",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source disagreements (14d, >20% spread)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(DisagreementView,{})})]})})]})]})}function statusBadgeVariant(es){switch(es){case"draft":return{className:"bg-muted text-muted-foreground",label:"draft"};case"queued":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300",label:"queued"};case"sending":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300 animate-pulse",label:"sending"};case"sent":return{className:"bg-teal-500/15 text-teal-700 dark:text-teal-300",label:"sent"};case"failed":return{className:"bg-destructive/15 text-destructive",label:"failed"}}}function StatusBadge({status:es}){const{className:$,label:ts}=statusBadgeVariant(es);return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("font-mono text-xs",$),children:ts})}function AdminAnnouncementsPage(){var Kr;const{profile:es,isLoading:$}=useActiveOrg(),[ts,is]=reactExports.useState(null),cs=useQuery({queryKey:["admin","announcements"],queryFn:()=>apiGet("/api/announcements"),refetchInterval:15e3,enabled:!!(es!=null&&es.isSuperadmin)});return reactExports.useEffect(()=>{var Xr;!ts&&((Xr=cs.data)!=null&&Xr.announcements.length)&&is(cs.data.announcements[0].id)},[cs.data,ts]),$?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"})}):es!=null&&es.isSuperadmin?jsxRuntimeExports.jsxs("div",{className:"flex h-[calc(100vh-4rem)] flex-col",children:[jsxRuntimeExports.jsxs("header",{className:"border-b border-border p-6",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Announcements"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Superadmin · CHANGELOG-driven product announcement emails. Drafts are editable; sent ones are immutable."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden md:flex-row",children:[jsxRuntimeExports.jsx("aside",{className:"max-h-64 w-full shrink-0 overflow-y-auto border-b border-border md:max-h-none md:w-80 md:border-b-0 md:border-r",children:cs.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-2 p-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"})]}):cs.error?jsxRuntimeExports.jsxs("p",{className:"p-4 text-sm text-destructive",children:["Failed to load: ",cs.error.message]}):(((Kr=cs.data)==null?void 0:Kr.announcements.length)??0)===0?jsxRuntimeExports.jsx("div",{className:"p-6 text-center",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No announcements yet. Add an entry to"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"CHANGELOG.md"}),", then run"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric crons run cron_check_changelog"})," ","if this release merits an announcement draft."]})}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.data.announcements.map(Xr=>{const Na=Xr.id===ts;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Xr.id),className:cn$1("flex w-full flex-col gap-1 px-4 py-3 text-left transition-colors","hover:bg-muted/50",Na&&"bg-secondary"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm font-medium",children:["v",Xr.version]}),jsxRuntimeExports.jsx(StatusBadge,{status:Xr.status})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:[Xr.releaseDate,Xr.status==="sent"&&Xr.recipientCount!==null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",Xr.recipientCount," recipients"]})]}),jsxRuntimeExports.jsx("div",{className:"line-clamp-2 text-sm",children:Xr.subject})]})},Xr.id)})})}),jsxRuntimeExports.jsx("main",{className:"flex-1 overflow-y-auto",children:ts?jsxRuntimeExports.jsx(AnnouncementDetailPane,{id:ts}):jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select an announcement to view details."})})]})]}):jsxRuntimeExports.jsx(Navigate,{to:"/admin",replace:!0})}function AnnouncementDetailPane({id:es}){var sl,ol;const $=useQueryClient(),ts=useQuery({queryKey:["admin","announcement",es],queryFn:()=>apiGet(`/api/announcements/${es}`),refetchInterval:ml=>{var ll;const rl=(ll=ml.state.data)==null?void 0:ll.status;return rl==="queued"||rl==="sending"?3e3:!1}}),is=useQuery({queryKey:["admin","announcement",es,"recipient-count"],queryFn:()=>apiGet(`/api/announcements/${es}/recipients/count`)}),[cs,Kr]=reactExports.useState(!1),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(!1),[Ia,Ma]=reactExports.useState(""),[Pa,La]=reactExports.useState("");reactExports.useEffect(()=>{Kr(!1),Aa(!1)},[es]);const Fa=ts.data,Ba=(Fa==null?void 0:Fa.status)==="draft",qa=()=>{$.invalidateQueries({queryKey:["admin","announcements"]}),$.invalidateQueries({queryKey:["admin","announcement",es]})},za=useMutation({mutationFn:ml=>apiPatch(`/api/announcements/${es}`,ml),onSuccess:()=>{ue$1.success("Saved"),Kr(!1),Aa(!1),qa()},onError:ml=>{const rl=ml instanceof ApiError?ml.message:String(ml);ue$1.error(`Save failed: ${rl}`)}}),[Va,Ga]=reactExports.useState(!1),Za=useMutation({mutationFn:()=>apiPost(`/api/announcements/${es}/send`,{}),onSuccess:ml=>{ue$1.success(`Queued — job ${ml.jobId.slice(0,8)}`),ml.noLiveWorker&&ue$1.warning("No worker is currently listening — start `rulemetric evals agent` for the email to actually go out.",{duration:1e4}),Ga(!1),qa()},onError:ml=>{const rl=ml instanceof ApiError?ml.message:String(ml);ue$1.error(`Send failed: ${rl}`)}}),Qa=reactExports.useMemo(()=>!(Fa!=null&&Fa.sections)||typeof Fa.sections!="object"?[]:Object.entries(Fa.sections).map(([rl,ll])=>({key:rl,items:Array.isArray(ll)?ll.map(String):[String(ll)]})),[Fa==null?void 0:Fa.sections]);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-2/3"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(ts.error||!Fa)return jsxRuntimeExports.jsxs("p",{className:"p-6 text-sm text-destructive",children:["Failed to load announcement:"," ",((sl=ts.error)==null?void 0:sl.message)??"not found"]});const Xa=((ol=is.data)==null?void 0:ol.count)??null,Ja=!Ba||Xa===0||Za.isPending,tl=Ba?Xa===0?"No opted-in recipients":"":`Already ${Fa.status} — cannot resend`;return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(StatusBadge,{status:Fa.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["v",Fa.version]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:Fa.releaseDate}),Fa.sentAt&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· Sent ",new Date(Fa.sentAt).toLocaleString()]}),Fa.recipientCount!==null&&Fa.status==="sent"&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· ",Fa.recipientCount," recipients"]})]}),Fa.deliveryCounts&&Object.keys(Fa.deliveryCounts).length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["sent","failed","skipped","pending"].filter(ml=>{var rl;return(((rl=Fa.deliveryCounts)==null?void 0:rl[ml])??0)>0}).map(ml=>{var rl;return jsxRuntimeExports.jsxs(Badge,{variant:ml==="failed"?"destructive":"outline",className:"font-mono text-xs",children:[(rl=Fa.deliveryCounts)==null?void 0:rl[ml]," ",ml]},ml)})}),cs?jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Input,{value:Xr,onChange:ml=>Na(ml.target.value),autoFocus:!0,className:"text-lg"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:!Xr.trim()||za.isPending,onClick:()=>za.mutate({subject:Xr.trim()}),children:za.isPending?"Saving…":"Save"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>Kr(!1),children:"Cancel"})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:Fa.subject}),Ba&&jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",onClick:()=>{Na(Fa.subject),Kr(!0)},"aria-label":"Edit subject",children:jsxRuntimeExports.jsx(Pencil,{className:"h-4 w-4"})})]})]}),Fa.error&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"})," Last error"]}),jsxRuntimeExports.jsx("pre",{className:"mt-2 whitespace-pre-wrap font-mono text-xs",children:Fa.error})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-md border border-border bg-muted/30 p-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Recipients (opted in)"}),jsxRuntimeExports.jsx("div",{className:"font-mono text-3xl font-semibold",children:is.isLoading?"…":Xa??"?"}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Live count from ",jsxRuntimeExports.jsx("code",{children:"notification_preferences"})," — server-side aggregation, not a client filter."]})]}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("span",{tabIndex:Ja?0:-1,children:jsxRuntimeExports.jsxs(Button,{size:"lg",disabled:Ja,onClick:()=>Ga(!0),children:[jsxRuntimeExports.jsx(Send,{className:"mr-2 h-4 w-4"}),"Send announcement"]})})}),tl&&jsxRuntimeExports.jsx(TooltipContent,{children:tl})]})})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"HTML preview"}),Ba&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>{Ca||(Ma(Fa.htmlBody),La(Fa.textBody)),Aa(ml=>!ml)},children:Ca?"Close editor":"Edit body"})]}),jsxRuntimeExports.jsx("iframe",{sandbox:"allow-same-origin",srcDoc:Fa.htmlBody,title:"Announcement HTML preview",className:"h-[480px] w-full rounded-md border border-border bg-white"})]}),Ca&&jsxRuntimeExports.jsxs("section",{className:"space-y-4 rounded-md border border-border p-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"html_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:ml=>Ma(ml.target.value),rows:12,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"text_body"}),jsxRuntimeExports.jsx(Textarea,{value:Pa,onChange:ml=>La(ml.target.value),rows:8,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:()=>Aa(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:za.isPending||Ia===Fa.htmlBody&&Pa===Fa.textBody,onClick:()=>za.mutate({htmlBody:Ia,textBody:Pa}),children:za.isPending?"Saving…":"Save body"})]})]}),jsxRuntimeExports.jsx(CollapsibleSection,{title:"Plain-text body",children:jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 font-mono text-xs",children:Fa.textBody})}),Qa.length>0&&jsxRuntimeExports.jsx(CollapsibleSection,{title:"Parsed sections",children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:Qa.map(({key:ml,items:rl})=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:ml}),jsxRuntimeExports.jsx("ul",{className:"ml-4 list-disc text-sm",children:rl.map((ll,dl)=>jsxRuntimeExports.jsx("li",{children:ll},dl))})]},ml))})}),jsxRuntimeExports.jsx(Dialog,{open:Va,onOpenChange:Ga,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Send announcement?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["Send ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:['"',Fa.subject,'"']})," to"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold",children:Xa??"?"})," ","recipients?"]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"This cannot be undone."]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:"Recipients will receive an email within ~1 minute."})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ga(!1),disabled:Za.isPending,children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:()=>Za.mutate(),disabled:Za.isPending,children:Za.isPending?"Queuing…":"Send now"})]})]})})]})}function CollapsibleSection({title:es,children:$}){const[ts,is]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("section",{className:"rounded-md border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(cs=>!cs),className:"flex w-full items-center justify-between px-4 py-2 text-left text-sm font-medium hover:bg-muted/30",children:[jsxRuntimeExports.jsx("span",{children:es}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:ts?"−":"+"})]}),ts&&jsxRuntimeExports.jsx("div",{className:"border-t border-border p-4",children:$})]})}function listUsers(es={}){const $=new URLSearchParams;es.search&&$.set("search",es.search),es.limit!==void 0&&$.set("limit",String(es.limit)),es.offset!==void 0&&$.set("offset",String(es.offset));const ts=$.toString();return apiGet(`/api/superadmin/users${ts?`?${ts}`:""}`)}function getUserDetail(es){return apiGet(`/api/superadmin/users/${es}`)}function listAllOrgs(){return apiGet("/api/superadmin/orgs")}function assignUserToOrg(es,$){return apiPost(`/api/superadmin/users/${es}/assign`,$)}function removeUserFromOrg(es,$){return apiDelete(`/api/superadmin/users/${es}/orgs/${$}`)}function forceLogoutUser(es){return apiPost(`/api/superadmin/users/${es}/force-logout`,{})}function resetUserPassword(es){return apiPost(`/api/superadmin/users/${es}/reset-password`,{})}function setUserSuspended(es,$){return apiPatch(`/api/superadmin/users/${es}/suspend`,{suspended:$})}function deleteUser(es,$){return api(`/api/superadmin/users/${es}`,{method:"DELETE",body:{confirmEmail:$}})}function inviteUser(es){return apiPost("/api/superadmin/users/invite",es)}function SuperadminUsersPage(){var Ia,Ma,Pa,La;const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(!1),Ca=Fa=>{$(Fa);const Ba=window.setTimeout(()=>is(Fa),300);return()=>window.clearTimeout(Ba)},Aa=useQuery({queryKey:["superadmin","users",ts],queryFn:()=>listUsers({search:ts||void 0,limit:100})});return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsxs("header",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Superadmin · Users"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Platform-level user directory. Click Manage to assign org membership, reset passwords, suspend, or delete."})]}),jsxRuntimeExports.jsx(Button,{onClick:()=>Na(!0),children:"Invite user"})]}),jsxRuntimeExports.jsxs("div",{className:"relative max-w-md",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{value:es,onChange:Fa=>Ca(Fa.target.value),placeholder:"Search by email…",className:"pl-9"})]}),Aa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"}):Aa.error?jsxRuntimeExports.jsxs("p",{className:"text-sm text-destructive",children:["Failed to load: ",Aa.error.message]}):jsxRuntimeExports.jsxs("div",{className:"rounded-md border",children:[jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24 text-right",children:"Orgs"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Sessions"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Orphan org_id"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28",children:"Created"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsxs(TableBody,{children:[(Ia=Aa.data)==null?void 0:Ia.users.map(Fa=>jsxRuntimeExports.jsx(UserRow,{user:Fa,onManage:()=>Kr(Fa.id)},Fa.id)),((Ma=Aa.data)==null?void 0:Ma.users.length)===0&&jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No users."})})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t p-2 text-xs text-muted-foreground text-right",children:["Showing ",(Pa=Aa.data)==null?void 0:Pa.users.length," of ",(La=Aa.data)==null?void 0:La.total," total"]})]}),cs&&jsxRuntimeExports.jsx(ManageUserSheet,{userId:cs,onClose:()=>Kr(null)}),jsxRuntimeExports.jsx(InviteUserDialog,{open:Xr,onOpenChange:Na})]})}function InviteUserDialog({open:es,onOpenChange:$}){var Ma;const ts=useQueryClient(),[is,cs]=reactExports.useState(""),[Kr,Xr]=reactExports.useState(""),[Na,Ca]=reactExports.useState("member"),Aa=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs,enabled:es}),Ia=useMutation({mutationFn:()=>inviteUser({email:is,orgId:Kr||void 0,role:Kr?Na:void 0}),onSuccess:Pa=>{ue$1.success(`Invite sent to ${Pa.email}`+(Pa.assigned?` · pre-assigned as ${Pa.assigned.role}`:"")),ts.invalidateQueries({queryKey:["superadmin","users"]}),cs(""),Xr(""),Ca("member"),$(!1)},onError:Pa=>{const La=Pa instanceof ApiError?Pa.message:String(Pa);ue$1.error(`Invite failed: ${La}`)}});return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite user"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Sends a Supabase invite email. Optionally pre-assign them to an org."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",value:is,onChange:Pa=>cs(Pa.target.value),placeholder:"user@example.com"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Pre-assign to org (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Kr,onValueChange:Xr,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"None — invite only"})}),jsxRuntimeExports.jsx(SelectContent,{children:(((Ma=Aa.data)==null?void 0:Ma.orgs)??[]).map(Pa=>jsxRuntimeExports.jsx(SelectItem,{value:Pa.id,children:Pa.name},Pa.id))})]})]}),Kr&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:Pa=>Ca(Pa),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{disabled:!is||Ia.isPending,onClick:()=>Ia.mutate(),children:Ia.isPending?"Sending…":"Send invite"})]})]})})}function UserRow({user:es,onManage:$}){return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.email??"—"}),es.isSuperadmin&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"superadmin"})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orgCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orphanSessionCount>0?jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"font-mono",children:es.orphanSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"0"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:new Date(es.createdAt).toISOString().slice(0,10)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:$,children:"Manage"})})]})}function ManageUserSheet({userId:es,onClose:$}){var ml;const ts=useQueryClient(),is=useQuery({queryKey:["superadmin","user",es],queryFn:()=>getUserDetail(es)}),cs=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs}),[Kr,Xr]=reactExports.useState(""),[Na,Ca]=reactExports.useState("member"),[Aa,Ia]=reactExports.useState(!0),Ma=()=>{ts.invalidateQueries({queryKey:["superadmin","users"]}),ts.invalidateQueries({queryKey:["superadmin","user",es]})},Pa=useMutation({mutationFn:()=>assignUserToOrg(es,{orgId:Kr,role:Na,claimSessions:Aa}),onSuccess:rl=>{ue$1.success(`Assigned as ${rl.role}`+(rl.claimed_sessions>0?` · claimed ${rl.claimed_sessions} orphan session${rl.claimed_sessions===1?"":"s"}`:"")),Xr(""),Ma()},onError:rl=>{const ll=rl instanceof ApiError?rl.message:String(rl);ue$1.error(`Assign failed: ${ll}`)}}),La=useMutation({mutationFn:rl=>removeUserFromOrg(es,rl),onSuccess:()=>{ue$1.success("Removed from org"),Ma()},onError:rl=>{const ll=rl instanceof ApiError?rl.message:String(rl);ue$1.error(`Remove failed: ${ll}`)}}),Fa=rl=>ll=>{const dl=ll instanceof ApiError?ll.message:String(ll);ue$1.error(`${rl} failed: ${dl}`)},Ba=useMutation({mutationFn:()=>forceLogoutUser(es),onSuccess:()=>ue$1.success("All sessions revoked"),onError:Fa("Force logout")}),qa=useMutation({mutationFn:()=>resetUserPassword(es),onSuccess:rl=>{rl.actionLink?(navigator.clipboard.writeText(rl.actionLink).catch(()=>{}),ue$1.success(`Recovery link copied for ${rl.email}`)):ue$1.success(`Recovery email sent to ${rl.email}`)},onError:Fa("Reset password")}),za=useMutation({mutationFn:rl=>setUserSuspended(es,rl),onSuccess:rl=>{ue$1.success(rl.suspended?"User suspended":"User reinstated"),Ma()},onError:Fa("Suspend")}),[Va,Ga]=reactExports.useState(!1),[Za,Qa]=reactExports.useState(""),Xa=useMutation({mutationFn:()=>deleteUser(es,Za),onSuccess:()=>{ue$1.success("User deleted"),Ga(!1),Qa(""),ts.invalidateQueries({queryKey:["superadmin","users"]}),$()},onError:Fa("Delete")}),Ja=is.data,tl=((ml=cs.data)==null?void 0:ml.orgs)??[],sl=new Set((Ja==null?void 0:Ja.memberships.map(rl=>rl.orgId))??[]),ol=tl.filter(rl=>!sl.has(rl.id));return jsxRuntimeExports.jsxs(Sheet,{open:!0,onOpenChange:rl=>!rl&&$(),children:[jsxRuntimeExports.jsxs(SheetContent,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[jsxRuntimeExports.jsxs(SheetHeader,{children:[jsxRuntimeExports.jsx(SheetTitle,{className:"font-mono text-base",children:(Ja==null?void 0:Ja.user.email)??"Loading…"}),jsxRuntimeExports.jsx(SheetDescription,{children:Ja?`${Ja.sessionCounts.total} sessions, ${Ja.sessionCounts.orphan} without an org`:""})]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 space-y-6 px-1",children:[jsxRuntimeExports.jsxs("section",{children:[jsxRuntimeExports.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Current memberships"}),(Ja==null?void 0:Ja.memberships.length)===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Not a member of any org."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1",children:Ja==null?void 0:Ja.memberships.map(rl=>jsxRuntimeExports.jsxs("li",{className:"flex items-center justify-between rounded-md border px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"font-medium",children:rl.orgName}),jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground",children:rl.orgSlug})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",children:rl.role}),jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",disabled:La.isPending,onClick:()=>La.mutate(rl.orgId),"aria-label":"Remove from org",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})]},rl.orgId))})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2 rounded-md border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Account actions"}),(Ja==null?void 0:Ja.user.banned)&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",children:"Suspended"})]}),(Ja==null?void 0:Ja.user.lastSignInAt)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sign-in: ",new Date(Ja.user.lastSignInAt).toLocaleString()]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:qa.isPending,onClick:()=>qa.mutate(),children:qa.isPending?"Generating…":"Reset password"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ba.isPending,onClick:()=>Ba.mutate(),children:Ba.isPending?"Revoking…":"Force logout"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:za.isPending,onClick:()=>za.mutate(!(Ja!=null&&Ja.user.banned)),children:za.isPending?"Updating…":Ja!=null&&Ja.user.banned?"Reinstate":"Suspend"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>Ga(!0),children:"Delete user"})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3 rounded-md border p-3",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Add to org"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Select,{value:Kr,onValueChange:Xr,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Choose an org…"})}),jsxRuntimeExports.jsx(SelectContent,{children:ol.length===0?jsxRuntimeExports.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No orgs available (already a member of all)."}):ol.map(rl=>jsxRuntimeExports.jsxs(SelectItem,{value:rl.id,children:[rl.name," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["(",rl.memberCount,")"]})]},rl.id))})]}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:rl=>Ca(rl),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Aa,onChange:rl=>Ia(rl.target.checked),className:"h-4 w-4"}),"Claim ",(Ja==null?void 0:Ja.sessionCounts.orphan)??0," orphan session",(Ja==null?void 0:Ja.sessionCounts.orphan)===1?"":"s"," for this org"]}),jsxRuntimeExports.jsx(Button,{disabled:!Kr||Pa.isPending,onClick:()=>Pa.mutate(),className:"w-full",children:Pa.isPending?"Assigning…":"Assign"})]})]})]})]}),jsxRuntimeExports.jsx(Dialog,{open:Va,onOpenChange:Ga,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete user"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["This permanently deletes the auth user and cascades all their sessions and memberships. Type"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:(Ja==null?void 0:Ja.user.email)??"—"})," to confirm."]})]}),jsxRuntimeExports.jsx(Input,{value:Za,onChange:rl=>Qa(rl.target.value),placeholder:(Ja==null?void 0:Ja.user.email)??"",autoComplete:"off"}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ga(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",disabled:!(Ja!=null&&Ja.user.email)||Za.toLowerCase()!==Ja.user.email.toLowerCase()||Xa.isPending,onClick:()=>Xa.mutate(),children:Xa.isPending?"Deleting…":"Delete permanently"})]})]})})]})}function SuperAdminGuard({children:es}){const{profile:$,isLoading:ts}=useActiveOrg();return ts?jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center p-8",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"})]})}):$!=null&&$.isSuperadmin?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es??jsxRuntimeExports.jsx(Outlet,{})}):jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}const SLUG_REGEX=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function NewOrgPage(){const es=useNavigate(),$=useSetActiveOrg(),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(!1),[Ca,Aa]=reactExports.useState(null),[Ia,Ma]=reactExports.useState(null),Pa=useMutation({mutationFn:qa=>createOrg(qa),onSuccess:async qa=>{try{await $.mutateAsync(qa.id)}catch{}ue$1.success(`Created ${qa.name}`),es("/admin",{replace:!0})},onError:qa=>{if(qa instanceof ApiError&&qa.code==="ORG_SLUG_TAKEN"){const za=cs.replace(/-\d+$/,""),Va=(()=>{const Za=cs.match(/-(\d+)$/);return Za?Number(Za[1])+1:2})(),Ga=`${za}-${Va}`.slice(0,40);Ma(Ga),Aa("That slug is already taken.");return}if(qa instanceof ApiError&&qa.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(qa instanceof Error?qa.message:"Failed to create organization")}});function La(qa){is(qa),Xr||Kr(slugify(qa))}function Fa(qa){qa.preventDefault(),Aa(null),Ma(null);const za=ts.trim(),Va=cs.trim();if(!za){Aa("Name is required.");return}if(za.length>100){Aa("Name must be 100 characters or fewer.");return}if(!SLUG_REGEX.test(Va)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Pa.mutate({name:za,slug:Va})}function Ba(){Ia&&(Kr(Ia),Na(!0),Ma(null),Aa(null))}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer -ml-2",children:jsxRuntimeExports.jsxs(Link,{to:"/dashboard",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to dashboard"]})}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"New organization"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Create organization"}),jsxRuntimeExports.jsx(CardDescription,{children:"You'll be the owner. Your existing personal sessions stay where they are — only sessions captured after you switch to this org will be attributed to it."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:ts,onChange:qa=>La(qa.target.value),placeholder:"Acme Inc.",required:!0,maxLength:100,disabled:Pa.isPending,autoFocus:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:cs,onChange:qa=>{Kr(qa.target.value),Na(!0)},placeholder:"acme",required:!0,disabled:Pa.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands."})]}),Ca&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-1",children:[jsxRuntimeExports.jsx("div",{children:Ca}),Ia&&jsxRuntimeExports.jsxs("div",{children:["Try"," ",jsxRuntimeExports.jsx("button",{type:"button",onClick:Ba,className:"font-mono underline cursor-pointer",children:Ia}),"?"]})]}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Pa.isPending,className:"w-full cursor-pointer",children:Pa.isPending?"Creating…":"Create organization"})]})})]})]})})}function AcceptInvitationPage(){const{token:es}=useParams(),{session:$,loading:ts}=useAuth(),is=useNavigate(),cs=useSetActiveOrg(),Kr=useQuery({queryKey:["invitation-preview",es,($==null?void 0:$.user.id)??null],queryFn:()=>previewInvitation(es),enabled:!!es&&!ts,retry:!1}),[Xr,Na]=reactExports.useState(!1),Ca=useMutation({mutationFn:()=>{var Ma;return acceptInvitation({token:es,acknowledgedSessionCount:((Ma=Kr.data)==null?void 0:Ma.sessionCount)??0})},onMutate:()=>{Na(!0)},onSuccess:async Ma=>{var Pa;try{await cs.mutateAsync(Ma.orgId)}catch{}ue$1.success(`Joined ${((Pa=Kr.data)==null?void 0:Pa.orgName)??"the organization"}`),is("/admin",{replace:!0})},onError:async Ma=>{if(Na(!1),Ma instanceof ApiError){if(Ma.code==="ALREADY_MEMBER"){ue$1.success("You're already a member. Taking you there now."),is("/admin",{replace:!0});return}if(Ma.code==="INVITE_EMAIL_MISMATCH"){ue$1.error("This invitation was sent to a different email address. Sign out and sign in with the correct email to accept.");return}if(Ma.code==="SESSION_COUNT_CHANGED"){await Kr.refetch(),ue$1.error("Your session count changed since you reviewed the consent notice. Please re-confirm.");return}if(Ma.code==="INVITE_GONE"||Ma.code==="INVITE_NOT_FOUND"){ue$1.error("This invitation is no longer valid.");return}}ue$1.error(Ma instanceof Error?Ma.message:"Failed to accept invitation")}}),Aa=Kr.error,Ia=Aa instanceof ApiError&&(Aa.code==="INVITE_GONE"||Aa.code==="INVITE_NOT_FOUND"||Aa.statusCode===410||Aa.statusCode===404);return reactExports.useEffect(()=>{Ca.isSuccess&&Na(!1)},[Ca.isSuccess]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?ts||Kr.isLoading?jsxRuntimeExports.jsx(LoadingCard$1,{}):Ia?jsxRuntimeExports.jsx(GoneCard,{message:"This invitation is no longer valid. It may have been revoked, expired, or already accepted."}):Aa?jsxRuntimeExports.jsx(ErrorCard,{message:Aa.message}):Kr.data?jsxRuntimeExports.jsx(InvitationCard,{preview:Kr.data,token:es,isSignedIn:!!$,accepting:Xr||Ca.isPending,onAccept:()=>Ca.mutate()}):jsxRuntimeExports.jsx(LoadingCard$1,{}):jsxRuntimeExports.jsx(GoneCard,{message:"Missing invitation token in URL."})})})}function LoadingCard$1(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48 mt-2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-full mt-2"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]})]})}function GoneCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Invitation unavailable"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"This invitation is no longer valid"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function ErrorCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Couldn't load invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"Something went wrong"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function InvitationCard({preview:es,token:$,isSignedIn:ts,accepting:is,onAccept:cs}){const Kr=`/invite/${encodeURIComponent($)}`;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Organization invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:es.orgName}),jsxRuntimeExports.jsx(CardDescription,{className:"space-y-2",children:jsxRuntimeExports.jsx("span",{className:"block",children:es.inviterName?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("strong",{children:es.inviterName})," invited you to join"," ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["You've been invited to join ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," ","as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]})})})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ConsentNotice,{orgName:es.orgName,sessionCount:es.sessionCount}),jsxRuntimeExports.jsxs(Button,{type:"button",onClick:cs,disabled:is,className:"w-full cursor-pointer",children:[jsxRuntimeExports.jsx(UserCheck,{className:"mr-2 h-4 w-4"}),is?"Joining…":`Accept and join ${es.orgName}`]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/50 px-4 py-3 text-sm",children:"Sign in or sign up with the email this invitation was sent to, and we'll bring you back here to accept."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/login?next=${encodeURIComponent(Kr)}`,children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/signup?next=${encodeURIComponent(Kr)}`,children:"Sign up"})})]})]})})]})}function ConsentNotice({orgName:es,sessionCount:$}){return $===null?jsxRuntimeExports.jsx("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0"}),jsxRuntimeExports.jsx("div",{children:"You're signed in with a different email than this invitation was sent to. Sign out and sign in with the matching email to accept."})]})}):$===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm text-muted-foreground",children:["Accepting will give you ",es," access. You don't have any existing sessions, so nothing will be retroactively shared."]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:["By accepting, all of your existing personal RuleMetric sessions"," (","at least"," ",jsxRuntimeExports.jsx("strong",{className:"font-mono tabular-nums",children:$}),$===1?" session":" sessions"," as of now",") will become visible to ",jsxRuntimeExports.jsx("strong",{children:es})," admins."]})]})})}const API_BASE="";async function fetchUnsubscribePreview(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`);if($.status===404){const ts=new Error("invalid_token");throw ts.statusCode=404,ts}if(!$.ok)throw new Error(`HTTP ${$.status}`);return await $.json()}async function postUnsubscribe(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!$.ok){const ts=new Error(`HTTP ${$.status}`);throw ts.statusCode=$.status,ts}}function UnsubscribePage(){const{token:es}=useParams(),[$,ts]=reactExports.useState(!1),is=useQuery({queryKey:["unsubscribe-preview",es],queryFn:()=>fetchUnsubscribePreview(es),enabled:!!es,retry:!1}),cs=useMutation({mutationFn:()=>postUnsubscribe(es),onSuccess:()=>ts(!0)});return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-12",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?is.isLoading?jsxRuntimeExports.jsx(LoadingCard,{}):is.error?jsxRuntimeExports.jsx(InvalidCard,{}):is.data?$?jsxRuntimeExports.jsx(UnsubscribedCard,{justConfirmed:!0}):is.data.alreadyUnsubscribed?jsxRuntimeExports.jsx(UnsubscribedCard,{}):jsxRuntimeExports.jsx(ConfirmCard,{onConfirm:()=>cs.mutate(),pending:cs.isPending,error:cs.error?"Failed to unsubscribe. Please try again.":null}):jsxRuntimeExports.jsx(LoadingCard,{}):jsxRuntimeExports.jsx(InvalidCard,{})})})}function LoadingCard(){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"}),jsxRuntimeExports.jsx(CardTitle,{className:"text-lg",children:"Loading…"})]})})})}function InvalidCard(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Link invalid"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"This unsubscribe link is invalid or expired"}),jsxRuntimeExports.jsx(CardDescription,{children:"The unsubscribe link you used isn't recognized. It may have been truncated by your email client, or the preference may have been reset."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function ConfirmCard({onConfirm:es,pending:$,error:ts}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Bell,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Product announcements"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"Unsubscribe from RuleMetric product announcements?"}),jsxRuntimeExports.jsx(CardDescription,{children:"You won't receive product update emails from us anymore. You'll still receive transactional emails like sign-in links, invitations, and security alerts."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Button,{onClick:es,disabled:$,className:"w-full",variant:"destructive",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Unsubscribing…"]}):"Confirm unsubscribe"}),ts?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",role:"alert",children:ts}):null,jsxRuntimeExports.jsx(Link,{to:"/",className:"block text-center text-sm text-muted-foreground underline",children:"Cancel"})]})]})}function UnsubscribedCard({justConfirmed:es=!1}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-teal-600",children:"Unsubscribed"})]}),jsxRuntimeExports.jsx(CardTitle,{children:es?"You've been unsubscribed":"You're already unsubscribed"}),jsxRuntimeExports.jsx(CardDescription,{children:es?"You'll still receive transactional emails (sign-in, invitations, security alerts).":"You're already off the product-announcements list. You'll still receive transactional emails (sign-in, invitations, security alerts)."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function NotFoundPage(){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold",children:"404"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/dashboard",children:"Go to Dashboard"})})]})}const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:3e4,retry:1}}});function App(){const es=useRunsEnabled();return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsxs(AuthProvider,{children:[jsxRuntimeExports.jsx(BrowserRouter,{children:jsxRuntimeExports.jsx(PostHogProvider,{children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(LandingPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/login",element:jsxRuntimeExports.jsx(LoginPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/signup",element:jsxRuntimeExports.jsx(SignupPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/confirm",element:jsxRuntimeExports.jsx(ConfirmPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/extension",element:jsxRuntimeExports.jsx(ExtensionAuthPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/forgot-password",element:jsxRuntimeExports.jsx(ForgotPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/reset-password",element:jsxRuntimeExports.jsx(ResetPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/invite/:token",element:jsxRuntimeExports.jsx(AcceptInvitationPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/unsubscribe/:token",element:jsxRuntimeExports.jsx(UnsubscribePage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(AuthGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/orgs/new",element:jsxRuntimeExports.jsx(NewOrgPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(RootLayout,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/dashboard",element:jsxRuntimeExports.jsx(DashboardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions",element:jsxRuntimeExports.jsx(InstructionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/new",element:jsxRuntimeExports.jsx(InstructionCreatePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/:id",element:jsxRuntimeExports.jsx(InstructionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/:id/edit",element:jsxRuntimeExports.jsx(InstructionEditPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/import",element:jsxRuntimeExports.jsx(ImportWizardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/connect",element:jsxRuntimeExports.jsx(ConnectPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions",element:jsxRuntimeExports.jsx(SessionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions/:id",element:jsxRuntimeExports.jsx(SessionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects",element:jsxRuntimeExports.jsx(ProjectsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects/:id",element:jsxRuntimeExports.jsx(ProjectDetailPage,{})}),es,jsxRuntimeExports.jsx(Route,{path:"/eval-targets",element:jsxRuntimeExports.jsx(EvalTargetsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/eval-targets/:id",element:jsxRuntimeExports.jsx(EvalTargetDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights",element:jsxRuntimeExports.jsx(InsightsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights/:id",element:jsxRuntimeExports.jsx(InsightsDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories",element:jsxRuntimeExports.jsx(MemoriesListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories/:id",element:jsxRuntimeExports.jsx(MemoryDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/skills",element:jsxRuntimeExports.jsx(SkillsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public",element:jsxRuntimeExports.jsx(PublicCatalogPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public/:id",element:jsxRuntimeExports.jsx(PublicSkillDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/suggestions",element:jsxRuntimeExports.jsx(SuggestionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/usage",element:jsxRuntimeExports.jsx(UsagePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/docs",element:jsxRuntimeExports.jsx(DocsPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(SuperAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/superadmin",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/superadmin/users",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})})]}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(OrgAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/admin",element:jsxRuntimeExports.jsx(AdminOverviewPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members",element:jsxRuntimeExports.jsx(AdminMembersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members/invitations",element:jsxRuntimeExports.jsx(AdminInvitationsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams",element:jsxRuntimeExports.jsx(AdminTeamsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams/:teamSlug",element:jsxRuntimeExports.jsx(TeamDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/settings",element:jsxRuntimeExports.jsx(AdminSettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/research",element:jsxRuntimeExports.jsx(AdminResearchPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/announcements",element:jsxRuntimeExports.jsx(AdminAnnouncementsPage,{})})]})]})]}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(NotFoundPage,{})})]})})}),jsxRuntimeExports.jsx(Toaster,{})]})})})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").catch(es=>{console.error("Service worker registration failed:",es)})});clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(App,{})}));
950
+ Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-end justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-trials",className:"text-xs",children:"Trials"}),jsxRuntimeExports.jsx(Input,{id:"ab-trials",type:"number",min:1,max:50,value:Ia,onChange:La=>Ma(Math.max(1,Math.min(50,Number(La.target.value)||1))),className:"text-xs h-8 w-20"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",className:"cursor-pointer",disabled:is.isPending,onClick:Pa,children:is.isPending?"Starting…":"Run experiment"})]})]}),ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-12"}):!$||$.length===0?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No controlled experiments yet. Run one to get an unconfounded causal delta."}):jsxRuntimeExports.jsx("div",{children:$.map(La=>jsxRuntimeExports.jsx(ExperimentRow,{exp:La},La.id))})]})]})}function formatTokens(es){return es==null?"—":es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es)}function Cohort({label:es,value:$}){return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:$})]})}function MemoryImpactCard({impact:es}){const $=es.with,ts=es.without,is=es.comparison,cs=$.avgOutcomeScore!=null&&ts.avgOutcomeScore!=null?`${$.avgOutcomeScore} vs ${ts.avgOutcomeScore}${is.outcomeScoreDelta!=null?` (${is.outcomeScoreDelta>0?"+":""}${is.outcomeScoreDelta})`:""}`:"—",Kr=$.avgTotalTokens!=null&&ts.avgTotalTokens!=null?`${formatTokens($.avgTotalTokens)} vs ${formatTokens(ts.avgTotalTokens)}`:"—";return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Measured effect"}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs",children:[jsxRuntimeExports.jsx(Cohort,{label:"Sessions",value:`${$.sessionCount} with / ${ts.sessionCount} without`}),jsxRuntimeExports.jsx(Cohort,{label:"Outcome score",value:cs}),jsxRuntimeExports.jsx(Cohort,{label:"Avg tokens/session",value:Kr})]}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mt-3",children:"Observational — sessions exposed to this memory vs not, compared within each project. Not a controlled experiment; cost is estimated."})]})]})}function VersionHistoryCard({versions:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Effect by version"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[es.map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["v",$.version]}),$.isCurrent&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] py-0 text-muted-foreground",children:"current"}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[$.with.sessionCount," session",$.with.sessionCount===1?"":"s"]})]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:$.verdict})]},$.version)),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground pt-1",children:"Each edit bumps the version and re-opens measurement, so a version is scored only on the sessions that actually saw it."})]})]})}function MemoryImpactLoader({memoryId:es}){const{data:$,isLoading:ts}=useMemoryImpact(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-28"}):!$||$.with.sessionCount===0&&$.without.sessionCount===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No measured effect yet. Once this memory is injected into sessions (via the session-start hook) and those sessions are analyzed, its verdict appears here."})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MemoryImpactCard,{impact:$}),$.versions.length>1&&jsxRuntimeExports.jsx(VersionHistoryCard,{versions:$.versions})]})}function MemoryDetail({id:es}){const{data:$,isLoading:ts,error:is}=useMemory(es),cs=useArchiveMemory(),Kr=useUpdateMemory(),[Xr,Na]=reactExports.useState(!1);if(ts)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40"})]});if(is||!$)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Memory not found."})]});const Ca=$.status==="archived";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Pencil,{className:"mr-1.5 h-3.5 w-3.5"})," Edit"]}),Ca?jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",disabled:Kr.isPending,onClick:()=>Kr.mutate({id:$.id,status:"active"},{onSuccess:()=>ue$1.success("Memory restored"),onError:()=>ue$1.error("Restore failed")}),children:[jsxRuntimeExports.jsx(RotateCcw,{className:"mr-1.5 h-3.5 w-3.5"})," Restore"]}):jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer text-red-400 hover:text-red-400",disabled:cs.isPending,onClick:()=>cs.mutate($.id,{onSuccess:()=>ue$1.success("Memory archived (reversible)"),onError:()=>ue$1.error("Archive failed")}),children:[jsxRuntimeExports.jsx(Archive,{className:"mr-1.5 h-3.5 w-3.5"})," Archive"]})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[$.kind]??""}`,children:$.kind}),Ca&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-muted-foreground",children:"archived"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["v",$.version," · ",$.source," · ",$.projectId?"project-scoped":"global"]})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight mt-2",children:$.title})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:$.body})})]}),jsxRuntimeExports.jsx(MemoryImpactLoader,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryExperiments,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:Xr,onOpenChange:Na,memory:$})]})}function MemoryDetailPage(){const{id:es}=useParams();return es?jsxRuntimeExports.jsx(MemoryDetail,{id:es}):null}const CATEGORY_LABELS={workflow:"Workflow",language:"Language",framework:"Framework",tool:"Tool",security:"Security",testing:"Testing",architecture:"Architecture",devops:"DevOps",documentation:"Documentation",performance:"Performance",other:"Other"};function CopyInstallButton({skill:es}){const[$,ts]=reactExports.useState(!1),is=`rulemetric skills install ${es.id}`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:cs=>{cs.stopPropagation(),navigator.clipboard.writeText(is),ts(!0),setTimeout(()=>ts(!1),2e3)},title:is,children:[$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),$?"Copied!":"Install"]})}function SkillCard({skill:es,onSelect:$}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:()=>$(es),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono leading-tight",children:es.name}),jsxRuntimeExports.jsx(CopyInstallButton,{skill:es})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:es.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono",children:CATEGORY_LABELS[es.category]??es.category}),es.tools.slice(0,3).map(ts=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:displayTool(ts)},ts)),es.tools.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:["+",es.tools.length-3]})]}),es.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.tags.slice(0,4).map(ts=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["#",ts]},ts))})]})]})}function SkillDetailDialog({skill:es,open:$,onClose:ts}){var Aa;const[is,cs]=reactExports.useState(!1),{data:Kr,isLoading:Xr}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Na=Kr??es,Ca=`rulemetric skills install ${Na.id}`;return jsxRuntimeExports.jsx(Dialog,{open:$,onOpenChange:Ia=>!Ia&&ts(),children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-[95vw] max-h-[90vh] overflow-y-auto",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{className:"font-mono",children:Na.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Na.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:CATEGORY_LABELS[Na.category]??Na.category}),Na.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Aa=Na.languages)==null?void 0:Aa.length)??0)>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"Languages:"}),Na.languages.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:Ia},Ia))]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium font-mono",children:"Install"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[Na.content&&jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:()=>{const Ia=new Blob([Na.content],{type:"text/markdown"}),Ma=URL.createObjectURL(Ia),Pa=document.createElement("a");Pa.href=Ma,Pa.download=`${Na.id}.md`,Pa.click(),URL.revokeObjectURL(Ma)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:()=>{navigator.clipboard.writeText(Ca),cs(!0),setTimeout(()=>cs(!1),2e3)},children:[is?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),is?"Copied!":"Copy CLI"]})]})]}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-2 overflow-x-auto",children:Ca})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-medium font-mono mb-2",children:"Content"}),Xr&&!Na.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Na.content?jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-3 overflow-x-auto whitespace-pre-wrap max-h-[55vh]",children:Na.content}):jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No content available."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["Source:"," ",jsxRuntimeExports.jsxs("a",{href:Na.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Na.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Na.source.license&&jsxRuntimeExports.jsx("span",{children:Na.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(null),[Ca,Aa]=reactExports.useState(null),[Ia,Ma]=reactExports.useState(PAGE_SIZE$1),Pa=(es==null?void 0:es.skills)??[],La=reactExports.useMemo(()=>[...new Set(Pa.map(Va=>Va.category))].sort(),[Pa]),Fa=reactExports.useMemo(()=>[...new Set(Pa.flatMap(Va=>Va.tools))].sort(),[Pa]),Ba=reactExports.useMemo(()=>{let Va=Pa;if(ts){const Ga=ts.toLowerCase();Va=Va.filter(Za=>Za.name.toLowerCase().includes(Ga)||Za.description.toLowerCase().includes(Ga)||Za.tags.some(Qa=>Qa.toLowerCase().includes(Ga))||Za.id.toLowerCase().includes(Ga))}return cs&&(Va=Va.filter(Ga=>Ga.category===cs)),Xr&&(Va=Va.filter(Ga=>Ga.tools.includes(Xr)||Ga.tools.includes("universal"))),Va.sort((Ga,Za)=>{var Ja,tl;const Qa=((Ja=Ga.popularity)==null?void 0:Ja.stars)??0,Xa=((tl=Za.popularity)==null?void 0:tl.stars)??0;return Qa!==Xa?Xa-Qa:Ga.name.localeCompare(Za.name)}),Va},[Pa,ts,cs,Xr]);reactExports.useEffect(()=>{Ma(PAGE_SIZE$1)},[ts,cs,Xr]);const qa=Ba.slice(0,Ia),za=Ba.length>Ia;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Skills Registry"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Browse and install community-contributed skills for your AI coding tools"})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search skills...",value:ts,onChange:Va=>is(Va.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[cs&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Kr(null),children:[CATEGORY_LABELS[cs]??cs,jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]}),Xr&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Na(null),children:[displayTool(Xr),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!cs&&!Xr&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Category:"}),La.map(Va=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Kr(Va),children:CATEGORY_LABELS[Va]??Va},Va))]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Tool:"}),Fa.map(Va=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Na(Va),children:displayTool(Va)},Va))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Va,Ga)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40"},Ga))}):Ba.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Pa.length===0?"No skills in registry":"No matching skills"}),Pa.length===0&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric skills update"})," ","to fetch the registry"]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono",children:["Showing ",qa.length," of ",Ba.length," skill",Ba.length!==1?"s":"",ts||cs||Xr?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:qa.map(Va=>jsxRuntimeExports.jsx(SkillCard,{skill:Va,onSelect:Aa},Va.id))}),za&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>Ma(Va=>Va+PAGE_SIZE$1),children:["Load ",Math.min(PAGE_SIZE$1,Ba.length-Ia)," more"]})})]}),jsxRuntimeExports.jsx(SkillDetailDialog,{skill:Ca,open:!!Ca,onClose:()=>Aa(null)})]})}function relativeDate(es){if(!es)return"recently";const $=new Date(es).getTime();if(Number.isNaN($))return"recently";const ts=Math.floor((Date.now()-$)/864e5);return ts<1?"today":ts===1?"yesterday":ts<30?`${ts}d ago`:ts<365?`${Math.floor(ts/30)}mo ago`:`${Math.floor(ts/365)}y ago`}function formatStars(es){return es>=1e3?`${(es/1e3).toFixed(1)}k`:String(es)}function PublicCatalogPage(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(es);reactExports.useEffect(()=>{const Ma=setTimeout(()=>is(es),250);return()=>clearTimeout(Ma)},[es]);const{data:cs,isLoading:Kr,isFetchingNextPage:Xr,fetchNextPage:Na,hasNextPage:Ca,error:Aa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(cs==null?void 0:cs.pages.flat())??[],[cs]);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-6 w-6"}),"Public Catalog"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Community-maintained skills and instructions, browsable here for reference."})]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search public catalog...",value:es,onChange:Ma=>$(Ma.target.value),className:"pl-9"})]}),Aa?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load public catalog: ",Aa.message]}):Kr?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Ma,Pa)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Pa))}):Ia.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:ts?`No public skills match "${ts}".`:"No public skills available yet. The registry syncs daily."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ia.map(Ma=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${Ma.id}`,className:"block",children:jsxRuntimeExports.jsxs(Card,{className:"flex flex-col h-full hover:border-primary/50 hover:bg-muted/30 transition-colors cursor-pointer",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:Ma.name}),Ma.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:Ma.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[Ma.tags&&Ma.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:Ma.tags.slice(0,5).map(Pa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Pa},Pa))}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{title:Ma.sourceUpdatedAt??Ma.updatedAt,children:["Updated ",relativeDate(Ma.sourceUpdatedAt??Ma.updatedAt)]}),typeof Ma.popularityScore=="number"&&Ma.popularityScore>0&&jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1",title:"GitHub stars on the source repo",children:[jsxRuntimeExports.jsx(Star,{className:"h-3 w-3 fill-current"}),formatStars(Ma.popularityScore)]})]})]})]})},Ma.id))}),Ca&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Na(),disabled:Xr,className:"cursor-pointer",children:Xr?"Loading…":`Load more (showing ${Ia.length})`})}),!Ca&&Ia.length>0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-xs text-muted-foreground pt-2",children:[Ia.length," skill",Ia.length===1?"":"s"," loaded"]})]})]})}function PublicSkillDetailPage(){var cs,Kr;const{id:es}=useParams(),{data:$,isLoading:ts,error:is}=useQuery({queryKey:["instruction",es],queryFn:()=>apiGet(`/api/instructions/${es}`),enabled:!!es});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/catalog/public",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to Public Catalog"]})}),is?jsxRuntimeExports.jsxs("div",{className:"text-destructive",children:["Failed to load: ",is.message]}):ts||!$?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-1/2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.scope}),((cs=$.frontmatter)==null?void 0:cs.category)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.frontmatter.category})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:$.name}),$.description&&jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:$.description})]}),$.tags&&$.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:$.tags.map(Xr=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Xr},Xr))}),((Kr=$.frontmatter)==null?void 0:Kr.source)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source"})}),jsxRuntimeExports.jsxs(CardContent,{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"font-mono text-xs text-muted-foreground",children:[$.frontmatter.source.repo,$.frontmatter.source.path&&` / ${$.frontmatter.source.path}`]}),$.frontmatter.source.url&&jsxRuntimeExports.jsxs("a",{href:$.frontmatter.source.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:["View on GitHub ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]}),$.frontmatter.source.license&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["License: ",$.frontmatter.source.license]})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs font-mono bg-muted/40 rounded p-3 max-h-[60vh] overflow-y-auto",children:$.content})})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Version ",$.version," · updated ",new Date($.updatedAt).toLocaleString()]})]})]})}const scopeColors={public:"bg-teal-500/15 text-teal-400 border-teal-500/30",org:"bg-blue-500/15 text-blue-400 border-blue-500/30",team:"bg-primary/15 text-primary border-primary/30",personal:"bg-muted text-muted-foreground border-border"};function SuggestionRow({suggestion:es,projectPath:$,verdict:ts}){const is=useLogSuggestionEvent(),cs=usePromoteFromPublic(),Kr=useArchiveInstruction(),Xr=useRestoreInstruction(),Na=es.kind??"add",Ca=is.isPending||cs.isPending||Kr.isPending;async function Aa(){try{await Kr.mutateAsync(es.instructionId),await is.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Retired: ${es.name}`,{description:"Archived — soft delete, restorable.",action:{label:"Undo",onClick:()=>Xr.mutate(es.instructionId,{onSuccess:()=>ue$1.success("Restored"),onError:()=>ue$1.error("Restore failed")})}})}catch(La){ue$1.error(`Failed: ${La.message}`)}}async function Ia(){try{await is.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Noted: ${es.name}`,{description:"Nothing changed — shorten it yourself and the next cycle re-measures it."})}catch(La){ue$1.error(`Failed: ${La.message}`)}}async function Ma(){try{es.instructionScope==="public"&&await cs.mutateAsync({sourceInstructionId:es.instructionId,targetScope:"personal"}),await is.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Accepted: ${es.name}`)}catch(La){ue$1.error(`Failed: ${La.message}`)}}async function Pa(){try{await is.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(La){ue$1.error(`Failed: ${La.message}`)}}return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0 basis-56 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:scopeColors[es.instructionScope]??scopeColors.personal,children:es.instructionScope}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),Na!=="add"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Na==="remove"?"text-xs border-red-500/40 text-red-400":"text-xs border-amber-500/40 text-amber-400",children:Na==="remove"?"retire":"trim"}),es.estimatedTokens!=null&&Na!=="add"&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"font-mono text-xs text-muted-foreground",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",es.estimatedTokens.toLocaleString()," tok/session"]}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),es.isStale&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"stale"}),(ts==null?void 0:ts.sufficient)&&jsxRuntimeExports.jsx(VerdictBadge,{verdict:ts})]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generated ",formatDistanceToNow(es.generatedAt)]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 shrink-0",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Na==="remove"?Aa:Na==="trim"?Ia:Ma,disabled:Ca,children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 mr-1"}),Na==="remove"?"Retire":Na==="trim"?"Noted":"Accept"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:Pa,disabled:Ca,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]})]})}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,cs=ts.some(Aa=>Aa.isLoading),Kr=ts.map((Aa,Ia)=>{var Ma;return{projectPath:$[Ia],suggestions:((Ma=Aa.data)==null?void 0:Ma.suggestions)??[],isLoading:Aa.isLoading}}).filter(Aa=>Aa.projectPath),Xr=Kr.reduce((Aa,Ia)=>Aa+Ia.suggestions.length,0),Na=Kr.flatMap(Aa=>Aa.suggestions.map(Ia=>Ia.instructionId)),{data:Ca}=useSuggestionImpacts(Na);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-6 w-6"}),"Suggestions"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Precomputed instruction suggestions for your recent projects. Updated daily at 04:30."})]}),is?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:3}).map((Aa,Ia)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ia))}):Kr.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No recent projects found. Run a session through Claude Code or Cursor to populate this view."}):!cs&&Xr===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No suggestions yet. The cron runs daily at 04:30 and scores your recent projects against your library."}):jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Kr.map(Aa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Aa.projectPath})}),jsxRuntimeExports.jsx(CardContent,{children:Aa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}):Aa.suggestions.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions for this project."}):jsxRuntimeExports.jsx("div",{children:Aa.suggestions.map(Ia=>jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Aa.projectPath,verdict:Ca==null?void 0:Ca[Ia.instructionId]},Ia.id))})})]},Aa.projectPath))})]})}function tierFor(es){return es>=95?"red":es>=80?"orange":es>=60?"yellow":"green"}const TIER_COLOR={green:"stroke-teal-500",yellow:"stroke-yellow-500",orange:"stroke-orange-500",red:"stroke-red-500"},TIER_TEXT={green:"text-teal-600",yellow:"text-yellow-600",orange:"text-orange-600",red:"text-red-600"};function formatCountdown(es,$){const ts=es.getTime()-$.getTime();if(ts<=0)return"resetting now";const is=Math.floor(ts/6e4),cs=Math.floor(is/1440),Kr=Math.floor((is-cs*60*24)/60),Xr=is-cs*60*24-Kr*60;return cs>0?`resets in ${cs}d ${Kr}h`:Kr>0?`resets in ${Kr}h ${Xr}m`:`resets in ${Xr}m`}function formatObservedAt(es,$){const ts=$.getTime()-es.getTime();if(ts<6e4)return{label:"live",fresh:!0};const is=Math.floor(ts/6e4);return is<60?{label:`synced ${is}m ago`,fresh:!1}:{label:`synced ${Math.floor(is/60)}h ago`,fresh:!1}}function Ring({pct:es,tier:$}){const is=2*Math.PI*30,Kr=Math.max(0,Math.min(100,es))/100*is;return jsxRuntimeExports.jsxs("svg",{width:80,height:80,viewBox:"0 0 80 80",className:"-rotate-90",children:[jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",className:"stroke-muted"}),jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",strokeLinecap:"round",strokeDasharray:`${Kr} ${is}`,className:cn$1("transition-all duration-500",TIER_COLOR[$])})]})}function LimitRing(es){const{label:$,usedPercentage:ts,resetsAt:is,observedAt:cs,inferredCap:Kr,unit:Xr,confidenceBandPct:Na,capQualifier:Ca="inferred cap",providerReported:Aa=!1}=es,[Ia,Ma]=reactExports.useState(()=>new Date);reactExports.useEffect(()=>{const Ga=setInterval(()=>Ma(new Date),6e4);return()=>clearInterval(Ga)},[]);const Pa=ts!=null,La=ts??0,Fa=tierFor(La),Ba=La>=100?{icon:Ban,text:"hit",color:"text-red-600"}:La>=95?{icon:TriangleAlert,text:"imminent",color:"text-red-600"}:La>=80?{icon:TriangleAlert,text:"approaching",color:"text-yellow-600"}:null,qa=is?formatCountdown(new Date(is),Ia):"—",za=cs?formatObservedAt(new Date(cs),Ia):null,Va=Pa&&Kr!=null?Math.round(La/100*Kr):null;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx(Ring,{pct:La,tier:Fa}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:$}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-mono",TIER_TEXT[Fa]),children:Pa?`${Math.round(La)}%`:"—"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:qa}),za?jsxRuntimeExports.jsx("span",{className:cn$1("text-xs",za.fresh?"text-teal-600":"text-muted-foreground"),children:za.fresh?"✓ live":za.label}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"? unknown"})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Aa?jsxRuntimeExports.jsx("span",{className:"cursor-help font-mono",children:"Provider-reported quota window percentage"}):jsxRuntimeExports.jsxs("span",{className:"cursor-help font-mono",children:["≈"," ",Va??"?"," ","/ ",Kr??"?"," ",Xr," (",Ca," · ±",Na,"%)"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:Aa?"Reported directly by the provider's rate-limit feed — the percentage is authoritative, not an estimate.":"Estimate based on Anthropic-published ranges. Actuals vary per user."})})]})}),Ba?jsxRuntimeExports.jsxs("span",{className:cn$1("flex items-center gap-1 font-mono",Ba.color),children:[jsxRuntimeExports.jsx(Ba.icon,{className:"h-3 w-3"}),Ba.text]}):null]}),Pa?null:jsxRuntimeExports.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:Aa?"no observation yet — run this tool through the proxy":"~ estimated · no observation yet"})]})]})}const SOURCE_LABEL="Live usage · all tracked tools",COST_POLL_MS=3e4,RATE_LIMIT_RINGS=[{key:"five_hour",label:"5-hour window",unit:"msgs"},{key:"seven_day",label:"7-day (Sonnet tier)",unit:"hrs"},{key:"seven_day_opus",label:"7-day (Opus tier)",unit:"hrs"}],CODEX_RINGS=[{key:"five_hour",label:"Codex 5-hour window"},{key:"seven_day",label:"Codex 7-day window"}],PLAN_LABELS={max_20x:"Max-20x",max_5x:"Max-5x",pro:"Pro"};function planLabel(es){return PLAN_LABELS[es]??es}function startOfMonthIso(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function UsagePage(){var Xa,Ja,tl,sl,ol,ml,rl,ll,dl,_l,il,hl,ul,cl,jl,el,pl,bl,Ol,Pl;const es=useCurrentLimits(),$=useCurrentLimits("codex"),ts=useInferredCaps(),is=startOfMonthIso(),cs=useComputedInsights(void 0,void 0,{since:is,refetchIntervalMs:COST_POLL_MS}),Kr=((Xa=es.data)==null?void 0:Xa.five_hour)??null,Xr=((Ja=es.data)==null?void 0:Ja.seven_day)??null,Na=((tl=es.data)==null?void 0:tl.seven_day_opus)??null,Ca=((sl=$.data)==null?void 0:sl.five_hour)??null,Aa=((ol=$.data)==null?void 0:ol.seven_day)??null,Ia={five_hour:Ca,seven_day:Aa},Ma=!!(Ca||Aa),Pa=((ml=ts.data)==null?void 0:ml.five_hour_percent.inferred_cap)??null,La=((rl=ts.data)==null?void 0:rl.five_hour_percent.confidence_band_pct)??20,Fa=((ll=ts.data)==null?void 0:ll.seven_day_percent.inferred_cap)??null,Ba=((dl=ts.data)==null?void 0:dl.seven_day_percent.confidence_band_pct)??20,qa=((_l=ts.data)==null?void 0:_l.seven_day_opus_percent.inferred_cap)??null,za=((il=ts.data)==null?void 0:il.seven_day_opus_percent.confidence_band_pct)??20,Va=ts.data?`${planLabel(ts.data.plan)}${ts.data.assumed?" est.":""}`:"inferred cap",Ga=es.isLoading||ts.isLoading,Za={five_hour:{obs:Kr,cap:Pa,band:La},seven_day:{obs:Xr,cap:Fa,band:Ba},seven_day_opus:{obs:Na,cap:qa,band:za}},Qa=new Date(is).toLocaleString(void 0,{month:"long",year:"numeric"});return jsxRuntimeExports.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Gauge,{className:"h-6 w-6 text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"font-mono text-xl font-semibold",children:"Usage"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:SOURCE_LABEL})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-4",children:[jsxRuntimeExports.jsx("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),Ga?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]}):es.isError?jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsxs("span",{children:["Couldn't load rate limits",es.error instanceof Error?`: ${es.error.message}`:"",". Retrying…"]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Claude Code"}),RATE_LIMIT_RINGS.map(Fl=>{var Kl,wl,$l;const Nl=Za[Fl.key];return jsxRuntimeExports.jsx(LimitRing,{label:Fl.label,usedPercentage:((Kl=Nl.obs)==null?void 0:Kl.used_percentage)??null,resetsAt:((wl=Nl.obs)==null?void 0:wl.resets_at)??null,observedAt:(($l=Nl.obs)==null?void 0:$l.observed_at)??null,inferredCap:Nl.cap,unit:Fl.unit,confidenceBandPct:Nl.band,capQualifier:Va},Fl.key)})]}),Ma?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Codex"}),CODEX_RINGS.map(Fl=>{const Nl=Ia[Fl.key];return jsxRuntimeExports.jsx(LimitRing,{label:Fl.label,usedPercentage:(Nl==null?void 0:Nl.used_percentage)??null,resetsAt:(Nl==null?void 0:Nl.resets_at)??null,observedAt:(Nl==null?void 0:Nl.observed_at)??null,inferredCap:null,unit:"",confidenceBandPct:0,providerReported:!0},Fl.key)})]}):null]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:["Estimated cost · ",Qa]}),cs.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:((hl=cs.data)==null?void 0:hl.estimated_cost_usd)??0,breakdown:(ul=cs.data)==null?void 0:ul.estimated_cost_breakdown,inputTokens:((cl=cs.data)==null?void 0:cl.total_input_tokens)??0,outputTokens:((jl=cs.data)==null?void 0:jl.total_output_tokens)??0,cacheReadTokens:((el=cs.data)==null?void 0:el.total_cache_read_tokens)??0,cacheWriteTokens:((pl=cs.data)==null?void 0:pl.total_cache_write_tokens)??0,byModel:(bl=cs.data)==null?void 0:bl.estimated_cost_by_model,byTool:(Ol=cs.data)==null?void 0:Ol.estimated_cost_by_tool}),(Pl=cs.data)!=null&&Pl.truncated?jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 flex-shrink-0"}),"Showing your 500 most recent sessions this month — older sessions in the window aren't counted, so this is a lower bound."]}):null]})]})]})}function AdminOverviewPage(){var Ca,Aa,Ia,Ma,Pa,La;const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQuery({queryKey:["org-detail",$],queryFn:()=>getOrg($),enabled:!!$}),is=useQuery({queryKey:["org-activity",$,"7d"],queryFn:()=>getOrgActivity($,"7d"),enabled:!!$}),cs=(Ca=ts.data)==null?void 0:Ca.members.length,Kr=(Aa=ts.data)==null?void 0:Aa.teams.length,Xr=(Ia=is.data)==null?void 0:Ia.sessionCount,Na=((La=(Pa=(Ma=is.data)==null?void 0:Ma.topTools)==null?void 0:Pa[0])==null?void 0:La.tool)??null;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Building2,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Organization admin"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:(es==null?void 0:es.name)??"—"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:es==null?void 0:es.slug}),es&&jsxRuntimeExports.jsxs("span",{className:"ml-2 capitalize",children:["· you are ",es.role]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members",children:"Members"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members/invitations",children:"Pending invites"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/settings",children:"Settings"})})]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Members",value:cs,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Layers,{className:"h-4 w-4"}),label:"Teams",value:Kr,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Sessions (7d)",value:Xr,loading:is.isLoading,error:!!is.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:Na??"—",loading:is.isLoading,error:!!is.error})]})]})}function StatCard$1({icon:es,label:$,value:ts,loading:is,error:cs}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):cs?jsxRuntimeExports.jsx("span",{className:"text-sm text-destructive",children:"failed to load"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}const NO_TEAM="__none";function InviteDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState("member"),[Ca,Aa]=reactExports.useState(NO_TEAM),[Ia,Ma]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(""),Na("member"),Aa(NO_TEAM),Ma(null))},[es]);const Pa=useQuery({queryKey:["org-teams",ts],queryFn:()=>listTeams(ts),enabled:es&&!!ts}),La=useMutation({mutationFn:Ba=>createInvitation(ts,Ba),onSuccess:Ba=>{Ba.emailSent?ue$1.success(`Invitation sent to ${Ba.email}`):ue$1.warning("Invite created, but the email could not be sent",{description:Ba.emailError?`${Ba.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var qa;(qa=navigator.clipboard)==null||qa.writeText(Ba.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy — the link is in the invite row"))}}}),is.invalidateQueries({queryKey:["org-invitations",ts]}),$(!1)},onError:Ba=>{if(Ba instanceof ApiError){if(Ba.code==="INVITE_ALREADY_PENDING"){Ma("There's already a pending invitation for this email. Resend it from the Pending Invites page instead.");return}if(Ba.code==="INVALID_TEAM"){Ma("That team no longer exists in this organization. Refresh and try again.");return}ue$1.error(Ba.message);return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to send invite")}});function Fa(Ba){Ba.preventDefault(),Ma(null);const qa=cs.trim();if(!qa){Ma("Email is required.");return}if(!/^\S+@\S+\.\S+$/.test(qa)){Ma("Enter a valid email address.");return}La.mutate({email:qa,role:Xr,...Ca!==NO_TEAM?{teamId:Ca}:{}})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite a member"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Send an invitation email. The recipient gets a link that's valid for 7 days."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",autoComplete:"off",value:cs,onChange:Ba=>Kr(Ba.target.value),placeholder:"teammate@example.com",required:!0,disabled:La.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-role",children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Xr,onValueChange:Ba=>Na(Ba),disabled:La.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-role",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Admins can invite, remove, and re-role other members. Members have read-only access to admin pages."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-team",children:"Team (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Ca,onValueChange:Aa,disabled:La.isPending||Pa.isLoading,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-team",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"No team"})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:NO_TEAM,children:"No team"}),(Pa.data??[]).map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba.id,children:Ba.name},Ba.id))]})]}),Pa.error&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-destructive",children:["Couldn't load teams: ",Pa.error.message]})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:La.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:La.isPending,className:"cursor-pointer",children:La.isPending?"Sending…":"Send invitation"})]})]})]})})}function AdminMembersPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",$],queryFn:()=>listMembers($),enabled:!!$}),Ca=useMutation({mutationFn:({userId:Ma,role:Pa})=>updateMemberRole($,Ma,Pa),onSuccess:()=>{ue$1.success("Role updated"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]})},onError:Ma=>{Ma instanceof ApiError&&Ma.code==="LAST_OWNER"?ue$1.error("Cannot demote the last owner."):ue$1.error(Ma instanceof Error?Ma.message:"Failed to update role"),ts.invalidateQueries({queryKey:["org-members",$]})}}),Aa=useMutation({mutationFn:Ma=>removeMember($,Ma),onSuccess:()=>{ue$1.success("Member removed"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]}),Xr(null)},onError:Ma=>{Ma instanceof ApiError&&Ma.code==="LAST_OWNER"?ue$1.error("Cannot remove the last owner."):ue$1.error(Ma instanceof Error?Ma.message:"Failed to remove member")}}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Members"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage who has access to"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"}),"."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members/invitations",children:[jsxRuntimeExports.jsx(Mail,{className:"mr-2 h-4 w-4"}),"Pending invites"]})}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Teams"}),jsxRuntimeExports.jsx(TableHead,{children:"Last active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$2,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No members yet."})}):Ia.map(Ma=>{var Pa;return jsxRuntimeExports.jsx(MemberRow,{member:Ma,pending:Ca.isPending&&((Pa=Ca.variables)==null?void 0:Pa.userId)===Ma.userId,onRoleChange:La=>Ca.mutate({userId:Ma.userId,role:La}),onRemove:()=>Xr(Ma)},Ma.userId)})})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(RemoveMemberDialog$1,{member:Kr,onCancel:()=>Xr(null),onConfirm:()=>Kr&&Aa.mutate(Kr.userId),pending:Aa.isPending})]})}function MemberRow({member:es,pending:$,onRoleChange:ts,onRemove:is}){const cs=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:cs})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(Select,{value:es.role,onValueChange:Kr=>ts(Kr),disabled:$,children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32 capitalize",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"Owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"})]})]})}),jsxRuntimeExports.jsx(TableCell,{children:es.teams.length===0?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.teams.map(Kr=>jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-xs",children:Kr.name},Kr.id))})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:es.lastActiveAt?formatDistanceToNow(es.lastActiveAt):"never"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:is,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from organization"})})]})})]})}function SkeletonRows$2(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:4}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-32"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}function RemoveMemberDialog$1({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove member?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will lose access to the organization. They can be re-invited later."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function formatDistanceToFuture(es){const $=new Date(es).getTime(),ts=Date.now(),is=$-ts;if(is<=0)return"expired";const cs=Math.floor(is/6e4),Kr=Math.floor(is/36e5),Xr=Math.floor(is/864e5);return cs<1?"<1m":cs<60?`in ${cs}m`:Kr<24?`in ${Kr}h`:`in ${Xr}d`}function AdminInvitationsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-invitations",$],queryFn:()=>listInvitations($),enabled:!!$}),Ca=useMutation({mutationFn:Ma=>resendInvitation($,Ma),onSuccess:Ma=>{Ma.emailSent?ue$1.success(`Resent invitation to ${Ma.email}`):ue$1.warning("Invite link refreshed, but the email could not be sent",{description:Ma.emailError?`${Ma.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Pa;(Pa=navigator.clipboard)==null||Pa.writeText(Ma.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy the invite link"))}}}),ts.invalidateQueries({queryKey:["org-invitations",$]})},onError:Ma=>ue$1.error(Ma instanceof Error?Ma.message:"Failed to resend invitation")}),Aa=useMutation({mutationFn:Ma=>revokeInvitation($,Ma),onSuccess:()=>{ue$1.success("Invitation revoked"),ts.invalidateQueries({queryKey:["org-invitations",$]}),Xr(null)},onError:Ma=>ue$1.error(Ma instanceof Error?Ma.message:"Failed to revoke invitation")}),Ia=Na.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",size:"sm",className:"cursor-pointer mb-2 -ml-2 text-muted-foreground",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"}),"Back to members"]})}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Pending invitations"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"Sent but not yet accepted. Invitations expire 7 days after they're issued or last resent."})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load invitations:"," ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Team"}),jsxRuntimeExports.jsx(TableHead,{children:"Invited by"}),jsxRuntimeExports.jsx(TableHead,{children:"Expires"}),jsxRuntimeExports.jsx(TableHead,{className:"w-48 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows$1,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No pending invitations. Send one from the Members tab."})}):Ia.map(Ma=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:Ma.email}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize",children:Ma.role})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Ma.teamName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Ma.invitedByName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:formatDistanceToFuture(Ma.expiresAt)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",disabled:Ca.isPending&&Ca.variables===Ma.id,onClick:()=>Ca.mutate(Ma.id),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Resend"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>Xr(Ma),className:"cursor-pointer text-destructive hover:text-destructive",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-1 h-3 w-3"}),"Revoke"]})]})})]},Ma.id))})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:cs,orgSlug:$}),jsxRuntimeExports.jsx(Dialog,{open:!!Kr,onOpenChange:Ma=>{Ma||Xr(null)},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Revoke invitation?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[Kr!=null&&Kr.email?`${Kr.email} will no longer be able to accept this invitation.`:"This invitation will be revoked."," ","You can send a new one from the Members tab."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Xr(null),disabled:Aa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>Kr&&Aa.mutate(Kr.id),disabled:Aa.isPending,className:"cursor-pointer",children:Aa.isPending?"Revoking…":"Revoke"})]})]})})]})}function SkeletonRows$1(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"})]})})]},$))})}const SLUG_REGEX$2=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify$1(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function AdminTeamsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",[ts,is]=reactExports.useState(!1),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(null),Ca=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Aa=Ca.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Teams"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Group members of"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"})," ","to scope activity dashboards."]})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New team"]})]}),Ca.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load teams: ",Ca.error.message]}):Ca.isLoading?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Array.from({length:4}).map((Ia,Ma)=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20 mt-2"})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})})]},Ma))}):Aa.length===0?jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx(Layers,{className:"h-10 w-10 text-muted-foreground mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No teams yet."}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create one to start grouping members."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",variant:"outline",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create team"]})]}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Aa.map(Ia=>jsxRuntimeExports.jsx(TeamCard,{team:Ia,onRename:()=>Kr(Ia),onDelete:()=>Na(Ia)},Ia.id))}),jsxRuntimeExports.jsx(CreateTeamDialog,{open:ts,onOpenChange:is,orgSlug:$}),jsxRuntimeExports.jsx(RenameTeamDialog,{team:cs,orgSlug:$,onClose:()=>Kr(null)}),jsxRuntimeExports.jsx(DeleteTeamDialog,{team:Xr,orgSlug:$,onClose:()=>Na(null)})]})}function TeamCard({team:es,onRename:$,onDelete:ts}){return jsxRuntimeExports.jsxs(Card,{className:"relative",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx(CardTitle,{className:"truncate",children:jsxRuntimeExports.jsx(Link,{to:`/admin/teams/${encodeURIComponent(es.slug)}`,className:"hover:underline",children:es.name})}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:jsxRuntimeExports.jsx("code",{children:es.slug})})]}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer -mr-2 -mt-1",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Team actions"})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"cursor-pointer",children:"Rename"}),jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:ts,className:"text-destructive focus:text-destructive cursor-pointer",children:"Delete"})]})]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),es.memberCount," ",es.memberCount===1?"member":"members"]})})]})}function CreateTeamDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(!1),[Ia,Ma]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(""),Na(""),Aa(!1),Ma(null))},[es]);const Pa=useMutation({mutationFn:Ba=>createTeam(ts,Ba),onSuccess:()=>{ue$1.success("Team created"),is.invalidateQueries({queryKey:["org-teams",ts]}),is.invalidateQueries({queryKey:["org-detail",ts]}),$(!1)},onError:Ba=>{if(Ba instanceof ApiError&&Ba.code==="TEAM_SLUG_TAKEN"){Ma("That slug is already in use by another team.");return}if(Ba instanceof ApiError&&Ba.code==="VALIDATION_ERROR"){Ma("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to create team")}});function La(Ba){Kr(Ba),Ca||Na(slugify$1(Ba))}function Fa(Ba){Ba.preventDefault(),Ma(null);const qa=cs.trim(),za=Xr.trim();if(!qa){Ma("Name is required.");return}if(!SLUG_REGEX$2.test(za)){Ma("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Pa.mutate({name:qa,slug:za})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"New team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Teams group members of an organization for scoped activity views."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"team-name",value:cs,onChange:Ba=>La(Ba.target.value),placeholder:"Platform",required:!0,disabled:Pa.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"team-slug",value:Xr,onChange:Ba=>{Na(Ba.target.value),Aa(!0)},placeholder:"platform",required:!0,disabled:Pa.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs."})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Pa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Pa.isPending,className:"cursor-pointer",children:Pa.isPending?"Creating…":"Create team"})]})]})]})})}function RenameTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Kr(es.name),Na(es.slug),Aa(null))},[es]);const Ia=useMutation({mutationFn:({name:Pa,slug:La})=>updateTeam($,es.id,{name:Pa,slug:La}),onSuccess:()=>{ue$1.success("Team updated"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Pa=>{if(Pa instanceof ApiError&&Pa.code==="TEAM_SLUG_TAKEN"){Aa("That slug is already in use by another team.");return}if(Pa instanceof ApiError&&Pa.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Pa instanceof Error?Pa.message:"Failed to update team")}});function Ma(Pa){Pa.preventDefault(),Aa(null);const La=cs.trim(),Fa=Xr.trim();if(!La){Aa("Name is required.");return}if(!SLUG_REGEX$2.test(Fa)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ia.mutate({name:La,slug:Fa})}return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Pa=>{Pa||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Rename team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Change the team's display name and/or URL slug."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ma,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-name",value:cs,onChange:Pa=>Kr(Pa.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-slug",value:Xr,onChange:Pa=>Na(Pa.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing the slug breaks any bookmarked links to this team."})]}),Ca&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ca}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:Ia.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})]})]})]})})}function DeleteTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),cs=useMutation({mutationFn:()=>deleteTeam($,es.id),onSuccess:()=>{ue$1.success("Team deleted"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Kr=>{ue$1.error(Kr instanceof Error?Kr.message:"Failed to delete team")}});return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Kr=>{Kr||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:es==null?void 0:es.name})," will be permanently deleted. Members will remain in the organization but will no longer be grouped under this team."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:cs.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>cs.mutate(),disabled:cs.isPending,className:"cursor-pointer",children:cs.isPending?"Deleting…":"Delete"})]})]})})}function TeamDetailPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",{teamSlug:ts=""}=useParams(),[is,cs]=useTabParam(["members","activity"],"members"),Kr=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Xr=reactExports.useMemo(()=>{var Na;return((Na=Kr.data)==null?void 0:Na.find(Ca=>Ca.slug===ts))??null},[Kr.data,ts]);return Kr.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]}):Kr.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load team: ",Kr.error.message]}):Xr?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between gap-4",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-3 w-3"}),"All teams"]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:Xr.name}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:Xr.slug}),jsxRuntimeExports.jsxs("span",{className:"ml-2",children:["· ",Xr.memberCount," ",Xr.memberCount===1?"member":"members"]})]})]})}),jsxRuntimeExports.jsxs(Tabs,{value:is,onValueChange:cs,children:[jsxRuntimeExports.jsxs(TabsList,{variant:"line",children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"members",children:"Members"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"activity",children:"Activity"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"members",className:"pt-4",children:jsxRuntimeExports.jsx(MembersTab,{orgSlug:$,teamId:Xr.id})}),jsxRuntimeExports.jsx(TabsContent,{value:"activity",className:"pt-4",children:jsxRuntimeExports.jsx(ActivityTab,{orgSlug:$,teamId:Xr.id})})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Team not found"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["No team with slug ",jsxRuntimeExports.jsx("code",{className:"text-xs",children:ts})," in this organization."]}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to teams"]})})]})}function MembersTab({orgSlug:es,teamId:$}){const ts=useQueryClient(),[is,cs]=reactExports.useState(!1),[Kr,Xr]=reactExports.useState(null),Na=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),Ca=reactExports.useMemo(()=>(Na.data??[]).filter(Ma=>Ma.teams.some(Pa=>Pa.id===$)),[Na.data,$]),Aa=reactExports.useMemo(()=>(Na.data??[]).filter(Ma=>!Ma.teams.some(Pa=>Pa.id===$)),[Na.data,$]),Ia=useMutation({mutationFn:Ma=>removeTeamMember(es,$,Ma),onSuccess:()=>{ue$1.success("Member removed from team"),ts.invalidateQueries({queryKey:["org-members",es]}),ts.invalidateQueries({queryKey:["org-teams",es]}),Xr(null)},onError:Ma=>{ue$1.error(Ma instanceof Error?Ma.message:"Failed to remove member")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Members in this team. Adding a member here doesn't change their organization role — only the team grouping."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>cs(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Add member"]})]}),Na.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Na.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Org role"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Na.isLoading?jsxRuntimeExports.jsx(SkeletonRows,{}):Ca.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No members in this team yet."})}):Ca.map(Ma=>jsxRuntimeExports.jsx(TeamMemberRow,{member:Ma,onRemove:()=>Xr(Ma)},Ma.userId))})]})}),jsxRuntimeExports.jsx(AddMemberDialog,{open:is,onOpenChange:cs,orgSlug:es,teamId:$,addable:Aa,loading:Na.isLoading}),jsxRuntimeExports.jsx(RemoveMemberDialog,{member:Kr,onCancel:()=>Xr(null),onConfirm:()=>Kr&&Ia.mutate(Kr.userId),pending:Ia.isPending})]})}function TeamMemberRow({member:es,onRemove:$}){const ts=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:ts})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"capitalize",children:es.role})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from team"})})]})})]})}function SkeletonRows(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}const NO_USER="__none";function AddMemberDialog({open:es,onOpenChange:$,orgSlug:ts,teamId:is,addable:cs,loading:Kr}){const Xr=useQueryClient(),[Na,Ca]=reactExports.useState(NO_USER),[Aa,Ia]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Ca(NO_USER),Ia(null))},[es]);const Ma=useMutation({mutationFn:La=>addTeamMember(ts,is,La),onSuccess:()=>{ue$1.success("Member added to team"),Xr.invalidateQueries({queryKey:["org-members",ts]}),Xr.invalidateQueries({queryKey:["org-teams",ts]}),$(!1)},onError:La=>{ue$1.error(La instanceof Error?La.message:"Failed to add member")}});function Pa(La){if(La.preventDefault(),Na===NO_USER){Ia("Pick a member to add.");return}Ma.mutate(Na)}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Add member to team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Pick an organization member to add. Only members not already on this team are listed."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Pa,className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"space-y-2",children:jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:La=>{Ca(La),Ia(null)},disabled:Ma.isPending||Kr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:Kr?"Loading…":"Select member"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.length===0?jsxRuntimeExports.jsx(SelectItem,{value:NO_USER,disabled:!0,children:Kr?"Loading…":"All org members are on this team."}):cs.map(La=>jsxRuntimeExports.jsx(SelectItem,{value:La.userId,children:La.email??La.displayName??La.userId},La.userId))})]})}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ma.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ma.isPending||cs.length===0||Na===NO_USER,className:"cursor-pointer",children:Ma.isPending?"Adding…":"Add"})]})]})]})})}function RemoveMemberDialog({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:cs=>{cs||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove from team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will no longer be grouped under this team. They'll remain in the organization."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function ActivityTab({orgSlug:es,teamId:$}){var Xr,Na;const[ts,is]=reactExports.useState("7d"),cs=useQuery({queryKey:["team-activity",es,$,ts],queryFn:()=>getTeamActivity(es,$,ts),enabled:!!es&&!!$});if(cs.error)return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load activity: ",cs.error.message]});const Kr=cs.data;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end",children:jsxRuntimeExports.jsxs(Select,{value:ts,onValueChange:Ca=>is(Ca),children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"7d",children:"Last 7 days"}),jsxRuntimeExports.jsx(SelectItem,{value:"30d",children:"Last 30 days"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:`Sessions (${ts})`,value:Kr==null?void 0:Kr.sessionCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Active members",value:Kr==null?void 0:Kr.memberCount,loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:((Na=(Xr=Kr==null?void 0:Kr.topTools)==null?void 0:Xr[0])==null?void 0:Na.tool)??"—",loading:cs.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Avg friction",value:Kr!=null&&Kr.frictionTrend&&Kr.frictionTrend.length>0?(Kr.frictionTrend.reduce((Ca,Aa)=>Ca+Aa.avgFriction,0)/Kr.frictionTrend.length).toFixed(2):"—",loading:cs.isLoading})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsx(TopToolsCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(TopMembersCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(FrictionTrendCard,{data:Kr,loading:cs.isLoading}),jsxRuntimeExports.jsx(InstructionEffectivenessCard,{data:Kr,loading:cs.isLoading})]})]})}function StatCard({icon:es,label:$,value:ts,loading:is}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}function TopToolsCard({data:es,loading:$}){var cs;const ts=(es==null?void 0:es.topTools)??[],is=((cs=ts[0])==null?void 0:cs.count)??0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top tools"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(Kr=>jsxRuntimeExports.jsxs("li",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:Kr.tool}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:Kr.count})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?Kr.count/is*100:0}%`}})})]},Kr.tool))})})]})}function TopMembersCard({data:es,loading:$}){const ts=(es==null?void 0:es.topMembers)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top members"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.email??is.displayName??is.userId}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:is.count})]},is.userId))})})]})}function FrictionTrendCard({data:es,loading:$}){const ts=(es==null?void 0:es.frictionTrend)??[],is=ts.reduce((cs,Kr)=>Math.max(cs,Kr.avgFriction),0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Friction trend"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction data in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1.5",children:ts.map(cs=>jsxRuntimeExports.jsxs("li",{className:"space-y-0.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:cs.day}),jsxRuntimeExports.jsx("span",{className:"font-medium tabular-nums",children:cs.avgFriction.toFixed(2)})]}),jsxRuntimeExports.jsx("div",{className:"h-1 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?cs.avgFriction/is*100:0}%`}})})]},cs.day))})})]})}function InstructionEffectivenessCard({data:es,loading:$}){const ts=(es==null?void 0:es.instructionEffectiveness)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Instruction effectiveness"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked instructions in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx(Link,{to:`/instructions/${is.instructionId}`,className:"truncate font-medium hover:underline",children:is.name}),jsxRuntimeExports.jsx("span",{className:is.deltaPct==null?"text-muted-foreground tabular-nums":is.deltaPct>=0?"text-teal-600 dark:text-teal-500 tabular-nums":"text-destructive tabular-nums",children:is.deltaPct==null?"—":`${is.deltaPct>=0?"+":""}${is.deltaPct.toFixed(1)}%`})]},is.instructionId))})})]})}const SLUG_REGEX$1=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function AdminSettingsPage(){const{activeOrg:es}=useActiveOrg();if(!es)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]});const $=es.role==="owner";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:es.name}),"'s name, slug, ownership, and lifecycle."]})]}),jsxRuntimeExports.jsx(GeneralSection,{orgName:es.name,orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(TransferOwnershipSection,{orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(DeleteOrgSection,{orgName:es.name,orgSlug:es.slug})]})}function Section({title:es,description:$,destructive:ts,children:is}){return jsxRuntimeExports.jsx(Card,{className:ts?"border-destructive/30":void 0,children:jsxRuntimeExports.jsx(CardContent,{className:"p-6",children:jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-[200px_1fr]",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h3",{className:ts?"font-mono text-base font-semibold text-destructive":"font-mono text-base font-semibold",children:es}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:is})]})})})}function GeneralSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useNavigate(),[cs,Kr]=reactExports.useState(es),[Xr,Na]=reactExports.useState($),[Ca,Aa]=reactExports.useState(null);reactExports.useEffect(()=>{Kr(es),Na($),Aa(null)},[es,$]);const Ia=useMutation({mutationFn:La=>updateOrg($,La),onSuccess:La=>{ue$1.success("Organization updated"),ts.invalidateQueries({queryKey:["profile"]}),ts.invalidateQueries({queryKey:["orgs"]}),ts.invalidateQueries({queryKey:["org-detail",$]}),La.slug!==$&&is("/admin/settings",{replace:!0})},onError:La=>{if(La instanceof ApiError&&La.code==="ORG_SLUG_TAKEN"){Aa("That slug is already taken by another organization.");return}if(La instanceof ApiError&&La.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(La instanceof Error?La.message:"Failed to update organization")}});function Ma(La){La.preventDefault(),Aa(null);const Fa=cs.trim(),Ba=Xr.trim();if(!Fa){Aa("Name is required.");return}if(!SLUG_REGEX$1.test(Ba)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}const qa={};Fa!==es&&(qa.name=Fa),Ba!==$&&(qa.slug=Ba),!(!qa.name&&!qa.slug)&&Ia.mutate(qa)}const Pa=cs.trim()!==es||Xr.trim()!==$;return jsxRuntimeExports.jsx(Section,{title:"General",description:"The display name and URL slug of this organization.",children:jsxRuntimeExports.jsxs("form",{onSubmit:Ma,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:cs,onChange:La=>Kr(La.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:Xr,onChange:La=>Na(La.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands. Changing the slug breaks any bookmarked links."})]}),Ca&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ca}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending||!Pa,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})})]})})}function TransferOwnershipSection({orgSlug:es}){const $=useQueryClient(),ts=useNavigate(),is=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),cs=reactExports.useMemo(()=>(is.data??[]).filter(Ma=>Ma.role==="admin"),[is.data]),[Kr,Xr]=reactExports.useState(null),[Na,Ca]=reactExports.useState(!1),Aa=useMutation({mutationFn:Ma=>transferOwnership(es,Ma),onSuccess:()=>{ue$1.success("Ownership transferred. You're now an admin."),$.invalidateQueries({queryKey:["org-members",es]}),$.invalidateQueries({queryKey:["orgs"]}),$.invalidateQueries({queryKey:["profile"]}),Ca(!1),ts("/admin/members")},onError:Ma=>{if(Ma instanceof ApiError&&Ma.code==="SAME_USER"){ue$1.error("You can't transfer ownership to yourself.");return}if(Ma instanceof ApiError&&Ma.code==="NOT_A_MEMBER"){ue$1.error("That user is no longer a member of this organization.");return}ue$1.error(Ma instanceof Error?Ma.message:"Failed to transfer ownership")}}),Ia=cs.find(Ma=>Ma.userId===Kr);return jsxRuntimeExports.jsxs(Section,{title:"Transfer ownership",description:"Promote another admin to owner. You will become an admin afterward.",children:[is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"}):cs.length===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No other admins to transfer to. Promote a member to admin first on the"," ",jsxRuntimeExports.jsx("a",{href:"/admin/members",className:"underline",children:"Members"})," ","page."]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"transfer-target",children:"New owner"}),jsxRuntimeExports.jsxs(Select,{value:Kr??"",onValueChange:Ma=>Xr(Ma),disabled:Aa.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"transfer-target",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select an admin…"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs.map(Ma=>jsxRuntimeExports.jsx(SelectItem,{value:Ma.userId,children:Ma.email??Ma.displayName??Ma.userId},Ma.userId))})]})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:!Kr||Aa.isPending,onClick:()=>Ca(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ArrowRightLeft,{className:"mr-2 h-4 w-4"}),"Transfer ownership"]})})]}),jsxRuntimeExports.jsx(Dialog,{open:Na,onOpenChange:Ca,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Transfer ownership?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:(Ia==null?void 0:Ia.email)??(Ia==null?void 0:Ia.displayName)??"the selected user"})," ","will become the new owner of this organization. You'll keep admin access but lose the ability to delete the org or transfer ownership again."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Ca(!1),disabled:Aa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",onClick:()=>Kr&&Aa.mutate(Kr),disabled:!Kr||Aa.isPending,className:"cursor-pointer",children:Aa.isPending?"Transferring…":"Transfer"})]})]})})]})}function DeleteOrgSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useSetActiveOrg(),cs=useNavigate(),[Kr,Xr]=reactExports.useState(""),Na=Kr===$,Ca=useMutation({mutationFn:()=>deleteOrg($),onSuccess:async()=>{ue$1.success(`Deleted ${es}`);try{await is.mutateAsync(null)}catch{}ts.clear(),cs("/",{replace:!0})},onError:Aa=>{ue$1.error(Aa instanceof Error?Aa.message:"Failed to delete organization")}});return jsxRuntimeExports.jsxs(Section,{title:"Delete organization",description:"Permanently delete this organization, its teams, invitations, and member roles. Sessions are preserved (org_id is cleared).",destructive:!0,children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-destructive",children:"This action cannot be undone."})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Label,{htmlFor:"delete-confirm",children:["Type ",jsxRuntimeExports.jsx("code",{className:"text-xs font-mono px-1 rounded bg-muted",children:$})," to confirm"]}),jsxRuntimeExports.jsx(Input,{id:"delete-confirm",value:Kr,onChange:Aa=>Xr(Aa.target.value),autoComplete:"off",disabled:Ca.isPending})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"destructive",disabled:!Na||Ca.isPending,onClick:()=>Ca.mutate(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-2 h-4 w-4"}),Ca.isPending?"Deleting…":"Delete organization"]})})]})}function useActiveLimits(){return useQuery({queryKey:["research","active-limits"],queryFn:()=>apiGet("/api/research/active-limits")})}function useObservations(es={}){const $=new URLSearchParams;es.provider&&$.set("provider",es.provider),es.plan&&$.set("plan",es.plan),es.limitType&&$.set("limit_type",es.limitType),es.limit!=null&&$.set("limit",String(es.limit)),es.offset!=null&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["research","observations",es],queryFn:()=>apiGet(`/api/research/observations${ts?`?${ts}`:""}`)})}function useDocChanges(es){return useQuery({queryKey:["research","doc-changes","default"],queryFn:()=>apiGet("/api/research/doc-changes")})}function useDisagreements(es=14){return useQuery({queryKey:["research","disagreements",es],queryFn:()=>apiGet(`/api/research/disagreements?since_days=${es}`)})}function useConfidenceHistory(es,$,ts,is=90){return useQuery({queryKey:["research","confidence-history",es,$,ts,is],queryFn:()=>{const Kr=new URLSearchParams({provider:es,plan:$,limit_type:ts,days:String(is)});return apiGet(`/api/research/confidence-history?${Kr}`)},enabled:!!es&&!!$&&!!ts})}function ConfidenceBar({value:es}){const $=Math.max(0,Math.min(1,es))*100,ts=es>=.9?"high":es>=.6?"mid":"low",is=ts==="high"?"bg-teal-500":ts==="mid"?"bg-amber-500":"bg-rose-500";return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 w-16 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:`h-full ${is}`,style:{width:`${$}%`}})}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[$.toFixed(0),"%"]})]})}function ConfidenceTrendSparkline({provider:es,plan:$,limitType:ts,width:is=80,height:cs=20}){const{data:Kr,isLoading:Xr}=useConfidenceHistory(es,$,ts);if(Xr)return jsxRuntimeExports.jsx("div",{className:"h-5 w-20 animate-pulse rounded bg-muted"});const Na=(Kr==null?void 0:Kr.items)??[];if(Na.length===0)return jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});if(Na.length===1)return jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[(Na[0].confidence*100).toFixed(0),"%"]});const Ca=Na.map((La,Fa)=>Fa/(Na.length-1)*is),Aa=Na.map(La=>cs-La.confidence*cs),Ia=Ca.map((La,Fa)=>`${Fa===0?"M":"L"}${La.toFixed(1)},${Aa[Fa].toFixed(1)}`).join(" "),Ma=Na[Na.length-1].confidence,Pa=Ma>=.9?"stroke-teal-500":Ma>=.6?"stroke-amber-500":"stroke-rose-500";return jsxRuntimeExports.jsx("svg",{width:is,height:cs,viewBox:`0 0 ${is} ${cs}`,className:"overflow-visible",role:"img","aria-label":`Confidence trend (${Na.length} points)`,children:jsxRuntimeExports.jsx("path",{d:Ia,fill:"none",className:Pa,strokeWidth:1.5,strokeLinejoin:"round"})})}function ActiveLimitsTable(){const{data:es,isLoading:$,error:ts}=useActiveLimits();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load active limits."});const is=((es==null?void 0:es.items)??[]).slice().sort((cs,Kr)=>cs.provider!==Kr.provider?cs.provider.localeCompare(Kr.provider):cs.plan!==Kr.plan?cs.plan.localeCompare(Kr.plan):cs.limitType.localeCompare(Kr.limitType));return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No active limits recorded yet."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"}),jsxRuntimeExports.jsx(TableHead,{children:"Trend (90d)"}),jsxRuntimeExports.jsx(TableHead,{children:"Effective from"})]})}),jsxRuntimeExports.jsx(TableBody,{children:is.map(cs=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:cs.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(cs.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:cs.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(cs.confidence)})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceTrendSparkline,{provider:cs.provider,plan:cs.plan,limitType:cs.limitType})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground",children:new Date(cs.effectiveFrom).toLocaleString()})]},`${cs.provider}-${cs.plan}-${cs.limitType}-${cs.effectiveFrom}`))})]})}function RecentDocChanges(){const{data:es,isLoading:$,error:ts}=useDocChanges(),[is,cs]=reactExports.useState(null);if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load doc snapshots."});const Xr=((es==null?void 0:es.items)??[]).slice().sort((Na,Ca)=>Na.changed!==Ca.changed?Na.changed?-1:1:new Date(Ca.latestFetchedAt).getTime()-new Date(Na.latestFetchedAt).getTime());return Xr.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No doc snapshots in window."}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border rounded-md border border-border",children:Xr.map(Na=>{const Ca=`${Na.provider}::${Na.docUrl}`,Aa=is===Ca;return jsxRuntimeExports.jsxs("li",{className:"px-3 py-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(Aa?null:Ca),className:"flex w-full items-center justify-between gap-3 text-left cursor-pointer",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:Na.provider}),Na.changed?jsxRuntimeExports.jsx(Badge,{variant:"default",className:"text-[10px]",children:"changed"}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px]",children:"stable"}),!Na.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]}),jsxRuntimeExports.jsx("div",{className:"truncate font-mono text-xs text-muted-foreground",children:Na.docUrl})]}),jsxRuntimeExports.jsx("div",{className:"flex-shrink-0 font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Na.latestFetchedAt).toLocaleString()})]}),Aa&&jsxRuntimeExports.jsx(DocSnapshotDetail,{group:Na})]},Ca)})})}function DocSnapshotDetail({group:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-2 border-l-2 border-border pl-3 space-y-1",children:es.snapshots.slice(0,5).map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:new Date($.fetchedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"truncate text-muted-foreground",children:$.contentHash.slice(0,12)}),!$.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]},$.id))})}function SourceBadge({sourceType:es}){const $=LABELS[es]??es,ts=VARIANTS[es]??"outline";return jsxRuntimeExports.jsx(Badge,{variant:ts,className:"font-mono text-[10px] uppercase tracking-wide",children:$})}const LABELS={oauth_usage:"live",self_observed_429:"429",official_docs:"docs",self_observed_lower_bound:"lower",community:"community",llm_research:"llm"},VARIANTS={oauth_usage:"default",self_observed_429:"destructive",official_docs:"secondary",self_observed_lower_bound:"outline",community:"outline",llm_research:"outline"},PAGE_SIZE=50,ANY="__any";function ObservationsList(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(0),Ca=useActiveLimits(),Aa=reactExports.useMemo(()=>{var Va;const Ba=new Set,qa=new Set,za=new Set;for(const Ga of((Va=Ca.data)==null?void 0:Va.items)??[])Ba.add(Ga.provider),qa.add(Ga.plan),za.add(Ga.limitType);return{providers:Array.from(Ba).sort(),plans:Array.from(qa).sort(),limitTypes:Array.from(za).sort()}},[Ca.data]),{data:Ia,isLoading:Ma,error:Pa}=useObservations({provider:es||void 0,plan:ts||void 0,limitType:cs||void 0,limit:PAGE_SIZE,offset:Xr}),La=(Ia==null?void 0:Ia.total)??0,Fa=(Ia==null?void 0:Ia.items)??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(FilterSelect,{label:"Provider",value:es,options:Aa.providers,onChange:Ba=>{$(Ba),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Plan",value:ts,options:Aa.plans,onChange:Ba=>{is(Ba),Na(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Limit type",value:cs,options:Aa.limitTypes,onChange:Ba=>{Kr(Ba),Na(0)}}),jsxRuntimeExports.jsx("div",{className:"ml-auto font-mono text-xs text-muted-foreground tabular-nums",children:La>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Xr+1,"–",Math.min(Xr+PAGE_SIZE,La)," of ",La]})})]}),Ma?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):Pa?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load observations."}):Fa.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No observations match these filters."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Observed at"}),jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Source"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Fa.map(Ba=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Ba.observedAt).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Ba.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(Ba.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:Ba.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(SourceBadge,{sourceType:Ba.sourceType})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(Ba.confidence)})})]},Ba.id))})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Xr===0,onClick:()=>Na(Math.max(0,Xr-PAGE_SIZE)),children:"Previous"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Xr+PAGE_SIZE>=La,onClick:()=>Na(Xr+PAGE_SIZE),children:"Next"})]})]})}function FilterSelect({label:es,value:$,options:ts,onChange:is}){return jsxRuntimeExports.jsxs(Select,{value:$||ANY,onValueChange:cs=>is(cs===ANY?"":cs),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"h-8 w-[180px] text-xs",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:es})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsxs(SelectItem,{value:ANY,children:["All ",es.toLowerCase(),"s"]}),ts.map(cs=>jsxRuntimeExports.jsx(SelectItem,{value:cs,className:"font-mono text-xs",children:cs},cs))]})]})}function DisagreementView(){const{data:es,isLoading:$,error:ts}=useDisagreements();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load disagreements."});const is=(es==null?void 0:es.items)??[];return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No disagreements (>20% spread) detected in the last 14 days."}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:is.map(cs=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[cs.provider," / ",cs.plan," / ",cs.limitType]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-destructive tabular-nums",children:["Δ ",cs.spreadPct.toFixed(1),"% (",cs.minValue.toLocaleString()," →"," ",cs.maxValue.toLocaleString(),")"]})]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.observations.map(Kr=>jsxRuntimeExports.jsxs("li",{className:"flex items-center gap-3 py-1.5 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"w-40 text-muted-foreground tabular-nums",children:new Date(Kr.observedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-24 text-right tabular-nums",children:Kr.value.toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-16 text-muted-foreground",children:Kr.unit}),jsxRuntimeExports.jsx(SourceBadge,{sourceType:Kr.sourceType}),jsxRuntimeExports.jsx("div",{className:"ml-auto",children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Kr.confidence})})]},Kr.id))})})]},`${cs.provider}-${cs.plan}-${cs.limitType}`))})}function AdminResearchPage(){const[es,$]=useTabParam(["active","docs","observations","disagreements"],"active");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Database,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Usage research"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:"Provider limits intelligence"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Fused view of provider rate-limits sourced from OAuth headers, 429 responses, official docs, and community signals."})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,className:"space-y-4",children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"active",children:"Active limits"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"docs",children:"Doc changes"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"observations",children:"Observations"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"disagreements",children:"Disagreements"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"active",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Active fused limits"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ActiveLimitsTable,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"docs",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Recent doc snapshots (7d)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(RecentDocChanges,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"observations",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Raw observations"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ObservationsList,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"disagreements",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source disagreements (14d, >20% spread)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(DisagreementView,{})})]})})]})]})}function statusBadgeVariant(es){switch(es){case"draft":return{className:"bg-muted text-muted-foreground",label:"draft"};case"queued":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300",label:"queued"};case"sending":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300 animate-pulse",label:"sending"};case"sent":return{className:"bg-teal-500/15 text-teal-700 dark:text-teal-300",label:"sent"};case"failed":return{className:"bg-destructive/15 text-destructive",label:"failed"}}}function StatusBadge({status:es}){const{className:$,label:ts}=statusBadgeVariant(es);return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("font-mono text-xs",$),children:ts})}function AdminAnnouncementsPage(){var Kr;const{profile:es,isLoading:$}=useActiveOrg(),[ts,is]=reactExports.useState(null),cs=useQuery({queryKey:["admin","announcements"],queryFn:()=>apiGet("/api/announcements"),refetchInterval:15e3,enabled:!!(es!=null&&es.isSuperadmin)});return reactExports.useEffect(()=>{var Xr;!ts&&((Xr=cs.data)!=null&&Xr.announcements.length)&&is(cs.data.announcements[0].id)},[cs.data,ts]),$?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"})}):es!=null&&es.isSuperadmin?jsxRuntimeExports.jsxs("div",{className:"flex h-[calc(100vh-4rem)] flex-col",children:[jsxRuntimeExports.jsxs("header",{className:"border-b border-border p-6",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Announcements"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Superadmin · CHANGELOG-driven product announcement emails. Drafts are editable; sent ones are immutable."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden md:flex-row",children:[jsxRuntimeExports.jsx("aside",{className:"max-h-64 w-full shrink-0 overflow-y-auto border-b border-border md:max-h-none md:w-80 md:border-b-0 md:border-r",children:cs.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-2 p-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"})]}):cs.error?jsxRuntimeExports.jsxs("p",{className:"p-4 text-sm text-destructive",children:["Failed to load: ",cs.error.message]}):(((Kr=cs.data)==null?void 0:Kr.announcements.length)??0)===0?jsxRuntimeExports.jsx("div",{className:"p-6 text-center",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No announcements yet. Add an entry to"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"CHANGELOG.md"}),", then run"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric crons run cron_check_changelog"})," ","if this release merits an announcement draft."]})}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:cs.data.announcements.map(Xr=>{const Na=Xr.id===ts;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Xr.id),className:cn$1("flex w-full flex-col gap-1 px-4 py-3 text-left transition-colors","hover:bg-muted/50",Na&&"bg-secondary"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm font-medium",children:["v",Xr.version]}),jsxRuntimeExports.jsx(StatusBadge,{status:Xr.status})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:[Xr.releaseDate,Xr.status==="sent"&&Xr.recipientCount!==null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",Xr.recipientCount," recipients"]})]}),jsxRuntimeExports.jsx("div",{className:"line-clamp-2 text-sm",children:Xr.subject})]})},Xr.id)})})}),jsxRuntimeExports.jsx("main",{className:"flex-1 overflow-y-auto",children:ts?jsxRuntimeExports.jsx(AnnouncementDetailPane,{id:ts}):jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select an announcement to view details."})})]})]}):jsxRuntimeExports.jsx(Navigate,{to:"/admin",replace:!0})}function AnnouncementDetailPane({id:es}){var sl,ol;const $=useQueryClient(),ts=useQuery({queryKey:["admin","announcement",es],queryFn:()=>apiGet(`/api/announcements/${es}`),refetchInterval:ml=>{var ll;const rl=(ll=ml.state.data)==null?void 0:ll.status;return rl==="queued"||rl==="sending"?3e3:!1}}),is=useQuery({queryKey:["admin","announcement",es,"recipient-count"],queryFn:()=>apiGet(`/api/announcements/${es}/recipients/count`)}),[cs,Kr]=reactExports.useState(!1),[Xr,Na]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(!1),[Ia,Ma]=reactExports.useState(""),[Pa,La]=reactExports.useState("");reactExports.useEffect(()=>{Kr(!1),Aa(!1)},[es]);const Fa=ts.data,Ba=(Fa==null?void 0:Fa.status)==="draft",qa=()=>{$.invalidateQueries({queryKey:["admin","announcements"]}),$.invalidateQueries({queryKey:["admin","announcement",es]})},za=useMutation({mutationFn:ml=>apiPatch(`/api/announcements/${es}`,ml),onSuccess:()=>{ue$1.success("Saved"),Kr(!1),Aa(!1),qa()},onError:ml=>{const rl=ml instanceof ApiError?ml.message:String(ml);ue$1.error(`Save failed: ${rl}`)}}),[Va,Ga]=reactExports.useState(!1),Za=useMutation({mutationFn:()=>apiPost(`/api/announcements/${es}/send`,{}),onSuccess:ml=>{ue$1.success(`Queued — job ${ml.jobId.slice(0,8)}`),ml.noLiveWorker&&ue$1.warning("No worker is currently listening — start `rulemetric evals agent` for the email to actually go out.",{duration:1e4}),Ga(!1),qa()},onError:ml=>{const rl=ml instanceof ApiError?ml.message:String(ml);ue$1.error(`Send failed: ${rl}`)}}),Qa=reactExports.useMemo(()=>!(Fa!=null&&Fa.sections)||typeof Fa.sections!="object"?[]:Object.entries(Fa.sections).map(([rl,ll])=>({key:rl,items:Array.isArray(ll)?ll.map(String):[String(ll)]})),[Fa==null?void 0:Fa.sections]);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-2/3"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(ts.error||!Fa)return jsxRuntimeExports.jsxs("p",{className:"p-6 text-sm text-destructive",children:["Failed to load announcement:"," ",((sl=ts.error)==null?void 0:sl.message)??"not found"]});const Xa=((ol=is.data)==null?void 0:ol.count)??null,Ja=!Ba||Xa===0||Za.isPending,tl=Ba?Xa===0?"No opted-in recipients":"":`Already ${Fa.status} — cannot resend`;return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(StatusBadge,{status:Fa.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["v",Fa.version]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:Fa.releaseDate}),Fa.sentAt&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· Sent ",new Date(Fa.sentAt).toLocaleString()]}),Fa.recipientCount!==null&&Fa.status==="sent"&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· ",Fa.recipientCount," recipients"]})]}),Fa.deliveryCounts&&Object.keys(Fa.deliveryCounts).length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["sent","failed","skipped","pending"].filter(ml=>{var rl;return(((rl=Fa.deliveryCounts)==null?void 0:rl[ml])??0)>0}).map(ml=>{var rl;return jsxRuntimeExports.jsxs(Badge,{variant:ml==="failed"?"destructive":"outline",className:"font-mono text-xs",children:[(rl=Fa.deliveryCounts)==null?void 0:rl[ml]," ",ml]},ml)})}),cs?jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Input,{value:Xr,onChange:ml=>Na(ml.target.value),autoFocus:!0,className:"text-lg"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:!Xr.trim()||za.isPending,onClick:()=>za.mutate({subject:Xr.trim()}),children:za.isPending?"Saving…":"Save"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>Kr(!1),children:"Cancel"})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:Fa.subject}),Ba&&jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",onClick:()=>{Na(Fa.subject),Kr(!0)},"aria-label":"Edit subject",children:jsxRuntimeExports.jsx(Pencil,{className:"h-4 w-4"})})]})]}),Fa.error&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"})," Last error"]}),jsxRuntimeExports.jsx("pre",{className:"mt-2 whitespace-pre-wrap font-mono text-xs",children:Fa.error})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-md border border-border bg-muted/30 p-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Recipients (opted in)"}),jsxRuntimeExports.jsx("div",{className:"font-mono text-3xl font-semibold",children:is.isLoading?"…":Xa??"?"}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Live count from ",jsxRuntimeExports.jsx("code",{children:"notification_preferences"})," — server-side aggregation, not a client filter."]})]}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("span",{tabIndex:Ja?0:-1,children:jsxRuntimeExports.jsxs(Button,{size:"lg",disabled:Ja,onClick:()=>Ga(!0),children:[jsxRuntimeExports.jsx(Send,{className:"mr-2 h-4 w-4"}),"Send announcement"]})})}),tl&&jsxRuntimeExports.jsx(TooltipContent,{children:tl})]})})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"HTML preview"}),Ba&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>{Ca||(Ma(Fa.htmlBody),La(Fa.textBody)),Aa(ml=>!ml)},children:Ca?"Close editor":"Edit body"})]}),jsxRuntimeExports.jsx("iframe",{sandbox:"allow-same-origin",srcDoc:Fa.htmlBody,title:"Announcement HTML preview",className:"h-[480px] w-full rounded-md border border-border bg-white"})]}),Ca&&jsxRuntimeExports.jsxs("section",{className:"space-y-4 rounded-md border border-border p-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"html_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:ml=>Ma(ml.target.value),rows:12,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"text_body"}),jsxRuntimeExports.jsx(Textarea,{value:Pa,onChange:ml=>La(ml.target.value),rows:8,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:()=>Aa(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:za.isPending||Ia===Fa.htmlBody&&Pa===Fa.textBody,onClick:()=>za.mutate({htmlBody:Ia,textBody:Pa}),children:za.isPending?"Saving…":"Save body"})]})]}),jsxRuntimeExports.jsx(CollapsibleSection,{title:"Plain-text body",children:jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 font-mono text-xs",children:Fa.textBody})}),Qa.length>0&&jsxRuntimeExports.jsx(CollapsibleSection,{title:"Parsed sections",children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:Qa.map(({key:ml,items:rl})=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:ml}),jsxRuntimeExports.jsx("ul",{className:"ml-4 list-disc text-sm",children:rl.map((ll,dl)=>jsxRuntimeExports.jsx("li",{children:ll},dl))})]},ml))})}),jsxRuntimeExports.jsx(Dialog,{open:Va,onOpenChange:Ga,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Send announcement?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["Send ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:['"',Fa.subject,'"']})," to"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold",children:Xa??"?"})," ","recipients?"]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"This cannot be undone."]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:"Recipients will receive an email within ~1 minute."})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ga(!1),disabled:Za.isPending,children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:()=>Za.mutate(),disabled:Za.isPending,children:Za.isPending?"Queuing…":"Send now"})]})]})})]})}function CollapsibleSection({title:es,children:$}){const[ts,is]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("section",{className:"rounded-md border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(cs=>!cs),className:"flex w-full items-center justify-between px-4 py-2 text-left text-sm font-medium hover:bg-muted/30",children:[jsxRuntimeExports.jsx("span",{children:es}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:ts?"−":"+"})]}),ts&&jsxRuntimeExports.jsx("div",{className:"border-t border-border p-4",children:$})]})}function listUsers(es={}){const $=new URLSearchParams;es.search&&$.set("search",es.search),es.limit!==void 0&&$.set("limit",String(es.limit)),es.offset!==void 0&&$.set("offset",String(es.offset));const ts=$.toString();return apiGet(`/api/superadmin/users${ts?`?${ts}`:""}`)}function getUserDetail(es){return apiGet(`/api/superadmin/users/${es}`)}function listAllOrgs(){return apiGet("/api/superadmin/orgs")}function assignUserToOrg(es,$){return apiPost(`/api/superadmin/users/${es}/assign`,$)}function removeUserFromOrg(es,$){return apiDelete(`/api/superadmin/users/${es}/orgs/${$}`)}function forceLogoutUser(es){return apiPost(`/api/superadmin/users/${es}/force-logout`,{})}function resetUserPassword(es){return apiPost(`/api/superadmin/users/${es}/reset-password`,{})}function setUserSuspended(es,$){return apiPatch(`/api/superadmin/users/${es}/suspend`,{suspended:$})}function deleteUser(es,$){return api(`/api/superadmin/users/${es}`,{method:"DELETE",body:{confirmEmail:$}})}function inviteUser(es){return apiPost("/api/superadmin/users/invite",es)}function SuperadminUsersPage(){var Ia,Ma,Pa,La;const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(null),[Xr,Na]=reactExports.useState(!1),Ca=Fa=>{$(Fa);const Ba=window.setTimeout(()=>is(Fa),300);return()=>window.clearTimeout(Ba)},Aa=useQuery({queryKey:["superadmin","users",ts],queryFn:()=>listUsers({search:ts||void 0,limit:100})});return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsxs("header",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Superadmin · Users"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Platform-level user directory. Click Manage to assign org membership, reset passwords, suspend, or delete."})]}),jsxRuntimeExports.jsx(Button,{onClick:()=>Na(!0),children:"Invite user"})]}),jsxRuntimeExports.jsxs("div",{className:"relative max-w-md",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{value:es,onChange:Fa=>Ca(Fa.target.value),placeholder:"Search by email…",className:"pl-9"})]}),Aa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"}):Aa.error?jsxRuntimeExports.jsxs("p",{className:"text-sm text-destructive",children:["Failed to load: ",Aa.error.message]}):jsxRuntimeExports.jsxs("div",{className:"rounded-md border",children:[jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24 text-right",children:"Orgs"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Sessions"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Orphan org_id"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28",children:"Created"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsxs(TableBody,{children:[(Ia=Aa.data)==null?void 0:Ia.users.map(Fa=>jsxRuntimeExports.jsx(UserRow,{user:Fa,onManage:()=>Kr(Fa.id)},Fa.id)),((Ma=Aa.data)==null?void 0:Ma.users.length)===0&&jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No users."})})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t p-2 text-xs text-muted-foreground text-right",children:["Showing ",(Pa=Aa.data)==null?void 0:Pa.users.length," of ",(La=Aa.data)==null?void 0:La.total," total"]})]}),cs&&jsxRuntimeExports.jsx(ManageUserSheet,{userId:cs,onClose:()=>Kr(null)}),jsxRuntimeExports.jsx(InviteUserDialog,{open:Xr,onOpenChange:Na})]})}function InviteUserDialog({open:es,onOpenChange:$}){var Ma;const ts=useQueryClient(),[is,cs]=reactExports.useState(""),[Kr,Xr]=reactExports.useState(""),[Na,Ca]=reactExports.useState("member"),Aa=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs,enabled:es}),Ia=useMutation({mutationFn:()=>inviteUser({email:is,orgId:Kr||void 0,role:Kr?Na:void 0}),onSuccess:Pa=>{ue$1.success(`Invite sent to ${Pa.email}`+(Pa.assigned?` · pre-assigned as ${Pa.assigned.role}`:"")),ts.invalidateQueries({queryKey:["superadmin","users"]}),cs(""),Xr(""),Ca("member"),$(!1)},onError:Pa=>{const La=Pa instanceof ApiError?Pa.message:String(Pa);ue$1.error(`Invite failed: ${La}`)}});return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite user"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Sends a Supabase invite email. Optionally pre-assign them to an org."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",value:is,onChange:Pa=>cs(Pa.target.value),placeholder:"user@example.com"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Pre-assign to org (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Kr,onValueChange:Xr,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"None — invite only"})}),jsxRuntimeExports.jsx(SelectContent,{children:(((Ma=Aa.data)==null?void 0:Ma.orgs)??[]).map(Pa=>jsxRuntimeExports.jsx(SelectItem,{value:Pa.id,children:Pa.name},Pa.id))})]})]}),Kr&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:Pa=>Ca(Pa),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{disabled:!is||Ia.isPending,onClick:()=>Ia.mutate(),children:Ia.isPending?"Sending…":"Send invite"})]})]})})}function UserRow({user:es,onManage:$}){return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.email??"—"}),es.isSuperadmin&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"superadmin"})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orgCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orphanSessionCount>0?jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"font-mono",children:es.orphanSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"0"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:new Date(es.createdAt).toISOString().slice(0,10)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:$,children:"Manage"})})]})}function ManageUserSheet({userId:es,onClose:$}){var ml;const ts=useQueryClient(),is=useQuery({queryKey:["superadmin","user",es],queryFn:()=>getUserDetail(es)}),cs=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs}),[Kr,Xr]=reactExports.useState(""),[Na,Ca]=reactExports.useState("member"),[Aa,Ia]=reactExports.useState(!0),Ma=()=>{ts.invalidateQueries({queryKey:["superadmin","users"]}),ts.invalidateQueries({queryKey:["superadmin","user",es]})},Pa=useMutation({mutationFn:()=>assignUserToOrg(es,{orgId:Kr,role:Na,claimSessions:Aa}),onSuccess:rl=>{ue$1.success(`Assigned as ${rl.role}`+(rl.claimed_sessions>0?` · claimed ${rl.claimed_sessions} orphan session${rl.claimed_sessions===1?"":"s"}`:"")),Xr(""),Ma()},onError:rl=>{const ll=rl instanceof ApiError?rl.message:String(rl);ue$1.error(`Assign failed: ${ll}`)}}),La=useMutation({mutationFn:rl=>removeUserFromOrg(es,rl),onSuccess:()=>{ue$1.success("Removed from org"),Ma()},onError:rl=>{const ll=rl instanceof ApiError?rl.message:String(rl);ue$1.error(`Remove failed: ${ll}`)}}),Fa=rl=>ll=>{const dl=ll instanceof ApiError?ll.message:String(ll);ue$1.error(`${rl} failed: ${dl}`)},Ba=useMutation({mutationFn:()=>forceLogoutUser(es),onSuccess:()=>ue$1.success("All sessions revoked"),onError:Fa("Force logout")}),qa=useMutation({mutationFn:()=>resetUserPassword(es),onSuccess:rl=>{rl.actionLink?(navigator.clipboard.writeText(rl.actionLink).catch(()=>{}),ue$1.success(`Recovery link copied for ${rl.email}`)):ue$1.success(`Recovery email sent to ${rl.email}`)},onError:Fa("Reset password")}),za=useMutation({mutationFn:rl=>setUserSuspended(es,rl),onSuccess:rl=>{ue$1.success(rl.suspended?"User suspended":"User reinstated"),Ma()},onError:Fa("Suspend")}),[Va,Ga]=reactExports.useState(!1),[Za,Qa]=reactExports.useState(""),Xa=useMutation({mutationFn:()=>deleteUser(es,Za),onSuccess:()=>{ue$1.success("User deleted"),Ga(!1),Qa(""),ts.invalidateQueries({queryKey:["superadmin","users"]}),$()},onError:Fa("Delete")}),Ja=is.data,tl=((ml=cs.data)==null?void 0:ml.orgs)??[],sl=new Set((Ja==null?void 0:Ja.memberships.map(rl=>rl.orgId))??[]),ol=tl.filter(rl=>!sl.has(rl.id));return jsxRuntimeExports.jsxs(Sheet,{open:!0,onOpenChange:rl=>!rl&&$(),children:[jsxRuntimeExports.jsxs(SheetContent,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[jsxRuntimeExports.jsxs(SheetHeader,{children:[jsxRuntimeExports.jsx(SheetTitle,{className:"font-mono text-base",children:(Ja==null?void 0:Ja.user.email)??"Loading…"}),jsxRuntimeExports.jsx(SheetDescription,{children:Ja?`${Ja.sessionCounts.total} sessions, ${Ja.sessionCounts.orphan} without an org`:""})]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 space-y-6 px-1",children:[jsxRuntimeExports.jsxs("section",{children:[jsxRuntimeExports.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Current memberships"}),(Ja==null?void 0:Ja.memberships.length)===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Not a member of any org."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1",children:Ja==null?void 0:Ja.memberships.map(rl=>jsxRuntimeExports.jsxs("li",{className:"flex items-center justify-between rounded-md border px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"font-medium",children:rl.orgName}),jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground",children:rl.orgSlug})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",children:rl.role}),jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",disabled:La.isPending,onClick:()=>La.mutate(rl.orgId),"aria-label":"Remove from org",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})]},rl.orgId))})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2 rounded-md border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Account actions"}),(Ja==null?void 0:Ja.user.banned)&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",children:"Suspended"})]}),(Ja==null?void 0:Ja.user.lastSignInAt)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sign-in: ",new Date(Ja.user.lastSignInAt).toLocaleString()]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:qa.isPending,onClick:()=>qa.mutate(),children:qa.isPending?"Generating…":"Reset password"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ba.isPending,onClick:()=>Ba.mutate(),children:Ba.isPending?"Revoking…":"Force logout"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:za.isPending,onClick:()=>za.mutate(!(Ja!=null&&Ja.user.banned)),children:za.isPending?"Updating…":Ja!=null&&Ja.user.banned?"Reinstate":"Suspend"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>Ga(!0),children:"Delete user"})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3 rounded-md border p-3",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Add to org"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Select,{value:Kr,onValueChange:Xr,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Choose an org…"})}),jsxRuntimeExports.jsx(SelectContent,{children:ol.length===0?jsxRuntimeExports.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No orgs available (already a member of all)."}):ol.map(rl=>jsxRuntimeExports.jsxs(SelectItem,{value:rl.id,children:[rl.name," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["(",rl.memberCount,")"]})]},rl.id))})]}),jsxRuntimeExports.jsxs(Select,{value:Na,onValueChange:rl=>Ca(rl),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Aa,onChange:rl=>Ia(rl.target.checked),className:"h-4 w-4"}),"Claim ",(Ja==null?void 0:Ja.sessionCounts.orphan)??0," orphan session",(Ja==null?void 0:Ja.sessionCounts.orphan)===1?"":"s"," for this org"]}),jsxRuntimeExports.jsx(Button,{disabled:!Kr||Pa.isPending,onClick:()=>Pa.mutate(),className:"w-full",children:Pa.isPending?"Assigning…":"Assign"})]})]})]})]}),jsxRuntimeExports.jsx(Dialog,{open:Va,onOpenChange:Ga,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete user"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["This permanently deletes the auth user and cascades all their sessions and memberships. Type"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:(Ja==null?void 0:Ja.user.email)??"—"})," to confirm."]})]}),jsxRuntimeExports.jsx(Input,{value:Za,onChange:rl=>Qa(rl.target.value),placeholder:(Ja==null?void 0:Ja.user.email)??"",autoComplete:"off"}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ga(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",disabled:!(Ja!=null&&Ja.user.email)||Za.toLowerCase()!==Ja.user.email.toLowerCase()||Xa.isPending,onClick:()=>Xa.mutate(),children:Xa.isPending?"Deleting…":"Delete permanently"})]})]})})]})}function SuperAdminGuard({children:es}){const{profile:$,isLoading:ts}=useActiveOrg();return ts?jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center p-8",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"})]})}):$!=null&&$.isSuperadmin?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es??jsxRuntimeExports.jsx(Outlet,{})}):jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}const SLUG_REGEX=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function NewOrgPage(){const es=useNavigate(),$=useSetActiveOrg(),[ts,is]=reactExports.useState(""),[cs,Kr]=reactExports.useState(""),[Xr,Na]=reactExports.useState(!1),[Ca,Aa]=reactExports.useState(null),[Ia,Ma]=reactExports.useState(null),Pa=useMutation({mutationFn:qa=>createOrg(qa),onSuccess:async qa=>{try{await $.mutateAsync(qa.id)}catch{}ue$1.success(`Created ${qa.name}`),es("/admin",{replace:!0})},onError:qa=>{if(qa instanceof ApiError&&qa.code==="ORG_SLUG_TAKEN"){const za=cs.replace(/-\d+$/,""),Va=(()=>{const Za=cs.match(/-(\d+)$/);return Za?Number(Za[1])+1:2})(),Ga=`${za}-${Va}`.slice(0,40);Ma(Ga),Aa("That slug is already taken.");return}if(qa instanceof ApiError&&qa.code==="VALIDATION_ERROR"){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(qa instanceof Error?qa.message:"Failed to create organization")}});function La(qa){is(qa),Xr||Kr(slugify(qa))}function Fa(qa){qa.preventDefault(),Aa(null),Ma(null);const za=ts.trim(),Va=cs.trim();if(!za){Aa("Name is required.");return}if(za.length>100){Aa("Name must be 100 characters or fewer.");return}if(!SLUG_REGEX.test(Va)){Aa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Pa.mutate({name:za,slug:Va})}function Ba(){Ia&&(Kr(Ia),Na(!0),Ma(null),Aa(null))}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer -ml-2",children:jsxRuntimeExports.jsxs(Link,{to:"/dashboard",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to dashboard"]})}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"New organization"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Create organization"}),jsxRuntimeExports.jsx(CardDescription,{children:"You'll be the owner. Your existing personal sessions stay where they are — only sessions captured after you switch to this org will be attributed to it."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("form",{onSubmit:Fa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:ts,onChange:qa=>La(qa.target.value),placeholder:"Acme Inc.",required:!0,maxLength:100,disabled:Pa.isPending,autoFocus:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:cs,onChange:qa=>{Kr(qa.target.value),Na(!0)},placeholder:"acme",required:!0,disabled:Pa.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands."})]}),Ca&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-1",children:[jsxRuntimeExports.jsx("div",{children:Ca}),Ia&&jsxRuntimeExports.jsxs("div",{children:["Try"," ",jsxRuntimeExports.jsx("button",{type:"button",onClick:Ba,className:"font-mono underline cursor-pointer",children:Ia}),"?"]})]}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Pa.isPending,className:"w-full cursor-pointer",children:Pa.isPending?"Creating…":"Create organization"})]})})]})]})})}function AcceptInvitationPage(){const{token:es}=useParams(),{session:$,loading:ts}=useAuth(),is=useNavigate(),cs=useSetActiveOrg(),Kr=useQuery({queryKey:["invitation-preview",es,($==null?void 0:$.user.id)??null],queryFn:()=>previewInvitation(es),enabled:!!es&&!ts,retry:!1}),[Xr,Na]=reactExports.useState(!1),Ca=useMutation({mutationFn:()=>{var Ma;return acceptInvitation({token:es,acknowledgedSessionCount:((Ma=Kr.data)==null?void 0:Ma.sessionCount)??0})},onMutate:()=>{Na(!0)},onSuccess:async Ma=>{var Pa;try{await cs.mutateAsync(Ma.orgId)}catch{}ue$1.success(`Joined ${((Pa=Kr.data)==null?void 0:Pa.orgName)??"the organization"}`),is("/admin",{replace:!0})},onError:async Ma=>{if(Na(!1),Ma instanceof ApiError){if(Ma.code==="ALREADY_MEMBER"){ue$1.success("You're already a member. Taking you there now."),is("/admin",{replace:!0});return}if(Ma.code==="INVITE_EMAIL_MISMATCH"){ue$1.error("This invitation was sent to a different email address. Sign out and sign in with the correct email to accept.");return}if(Ma.code==="SESSION_COUNT_CHANGED"){await Kr.refetch(),ue$1.error("Your session count changed since you reviewed the consent notice. Please re-confirm.");return}if(Ma.code==="INVITE_GONE"||Ma.code==="INVITE_NOT_FOUND"){ue$1.error("This invitation is no longer valid.");return}}ue$1.error(Ma instanceof Error?Ma.message:"Failed to accept invitation")}}),Aa=Kr.error,Ia=Aa instanceof ApiError&&(Aa.code==="INVITE_GONE"||Aa.code==="INVITE_NOT_FOUND"||Aa.statusCode===410||Aa.statusCode===404);return reactExports.useEffect(()=>{Ca.isSuccess&&Na(!1)},[Ca.isSuccess]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?ts||Kr.isLoading?jsxRuntimeExports.jsx(LoadingCard$1,{}):Ia?jsxRuntimeExports.jsx(GoneCard,{message:"This invitation is no longer valid. It may have been revoked, expired, or already accepted."}):Aa?jsxRuntimeExports.jsx(ErrorCard,{message:Aa.message}):Kr.data?jsxRuntimeExports.jsx(InvitationCard,{preview:Kr.data,token:es,isSignedIn:!!$,accepting:Xr||Ca.isPending,onAccept:()=>Ca.mutate()}):jsxRuntimeExports.jsx(LoadingCard$1,{}):jsxRuntimeExports.jsx(GoneCard,{message:"Missing invitation token in URL."})})})}function LoadingCard$1(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48 mt-2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-full mt-2"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]})]})}function GoneCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Invitation unavailable"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"This invitation is no longer valid"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function ErrorCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Couldn't load invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"Something went wrong"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function InvitationCard({preview:es,token:$,isSignedIn:ts,accepting:is,onAccept:cs}){const Kr=`/invite/${encodeURIComponent($)}`;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Organization invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:es.orgName}),jsxRuntimeExports.jsx(CardDescription,{className:"space-y-2",children:jsxRuntimeExports.jsx("span",{className:"block",children:es.inviterName?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("strong",{children:es.inviterName})," invited you to join"," ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["You've been invited to join ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," ","as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]})})})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ConsentNotice,{orgName:es.orgName,sessionCount:es.sessionCount}),jsxRuntimeExports.jsxs(Button,{type:"button",onClick:cs,disabled:is,className:"w-full cursor-pointer",children:[jsxRuntimeExports.jsx(UserCheck,{className:"mr-2 h-4 w-4"}),is?"Joining…":`Accept and join ${es.orgName}`]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/50 px-4 py-3 text-sm",children:"Sign in or sign up with the email this invitation was sent to, and we'll bring you back here to accept."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/login?next=${encodeURIComponent(Kr)}`,children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/signup?next=${encodeURIComponent(Kr)}`,children:"Sign up"})})]})]})})]})}function ConsentNotice({orgName:es,sessionCount:$}){return $===null?jsxRuntimeExports.jsx("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0"}),jsxRuntimeExports.jsx("div",{children:"You're signed in with a different email than this invitation was sent to. Sign out and sign in with the matching email to accept."})]})}):$===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm text-muted-foreground",children:["Accepting will give you ",es," access. You don't have any existing sessions, so nothing will be retroactively shared."]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:["By accepting, all of your existing personal RuleMetric sessions"," (","at least"," ",jsxRuntimeExports.jsx("strong",{className:"font-mono tabular-nums",children:$}),$===1?" session":" sessions"," as of now",") will become visible to ",jsxRuntimeExports.jsx("strong",{children:es})," admins."]})]})})}const API_BASE="";async function fetchUnsubscribePreview(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`);if($.status===404){const ts=new Error("invalid_token");throw ts.statusCode=404,ts}if(!$.ok)throw new Error(`HTTP ${$.status}`);return await $.json()}async function postUnsubscribe(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!$.ok){const ts=new Error(`HTTP ${$.status}`);throw ts.statusCode=$.status,ts}}function UnsubscribePage(){const{token:es}=useParams(),[$,ts]=reactExports.useState(!1),is=useQuery({queryKey:["unsubscribe-preview",es],queryFn:()=>fetchUnsubscribePreview(es),enabled:!!es,retry:!1}),cs=useMutation({mutationFn:()=>postUnsubscribe(es),onSuccess:()=>ts(!0)});return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-12",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?is.isLoading?jsxRuntimeExports.jsx(LoadingCard,{}):is.error?jsxRuntimeExports.jsx(InvalidCard,{}):is.data?$?jsxRuntimeExports.jsx(UnsubscribedCard,{justConfirmed:!0}):is.data.alreadyUnsubscribed?jsxRuntimeExports.jsx(UnsubscribedCard,{}):jsxRuntimeExports.jsx(ConfirmCard,{onConfirm:()=>cs.mutate(),pending:cs.isPending,error:cs.error?"Failed to unsubscribe. Please try again.":null}):jsxRuntimeExports.jsx(LoadingCard,{}):jsxRuntimeExports.jsx(InvalidCard,{})})})}function LoadingCard(){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"}),jsxRuntimeExports.jsx(CardTitle,{className:"text-lg",children:"Loading…"})]})})})}function InvalidCard(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Link invalid"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"This unsubscribe link is invalid or expired"}),jsxRuntimeExports.jsx(CardDescription,{children:"The unsubscribe link you used isn't recognized. It may have been truncated by your email client, or the preference may have been reset."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function ConfirmCard({onConfirm:es,pending:$,error:ts}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Bell,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Product announcements"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"Unsubscribe from RuleMetric product announcements?"}),jsxRuntimeExports.jsx(CardDescription,{children:"You won't receive product update emails from us anymore. You'll still receive transactional emails like sign-in links, invitations, and security alerts."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Button,{onClick:es,disabled:$,className:"w-full",variant:"destructive",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Unsubscribing…"]}):"Confirm unsubscribe"}),ts?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",role:"alert",children:ts}):null,jsxRuntimeExports.jsx(Link,{to:"/",className:"block text-center text-sm text-muted-foreground underline",children:"Cancel"})]})]})}function UnsubscribedCard({justConfirmed:es=!1}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-teal-600",children:"Unsubscribed"})]}),jsxRuntimeExports.jsx(CardTitle,{children:es?"You've been unsubscribed":"You're already unsubscribed"}),jsxRuntimeExports.jsx(CardDescription,{children:es?"You'll still receive transactional emails (sign-in, invitations, security alerts).":"You're already off the product-announcements list. You'll still receive transactional emails (sign-in, invitations, security alerts)."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function NotFoundPage(){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold",children:"404"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/dashboard",children:"Go to Dashboard"})})]})}const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:3e4,retry:1}}});function App(){const es=useRunsEnabled();return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsxs(AuthProvider,{children:[jsxRuntimeExports.jsx(BrowserRouter,{children:jsxRuntimeExports.jsx(PostHogProvider,{children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(LandingPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/login",element:jsxRuntimeExports.jsx(LoginPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/signup",element:jsxRuntimeExports.jsx(SignupPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/confirm",element:jsxRuntimeExports.jsx(ConfirmPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/extension",element:jsxRuntimeExports.jsx(ExtensionAuthPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/forgot-password",element:jsxRuntimeExports.jsx(ForgotPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/reset-password",element:jsxRuntimeExports.jsx(ResetPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/invite/:token",element:jsxRuntimeExports.jsx(AcceptInvitationPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/unsubscribe/:token",element:jsxRuntimeExports.jsx(UnsubscribePage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(AuthGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/orgs/new",element:jsxRuntimeExports.jsx(NewOrgPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(RootLayout,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/dashboard",element:jsxRuntimeExports.jsx(DashboardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions",element:jsxRuntimeExports.jsx(InstructionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/new",element:jsxRuntimeExports.jsx(InstructionCreatePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/:id",element:jsxRuntimeExports.jsx(InstructionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/instructions/:id/edit",element:jsxRuntimeExports.jsx(InstructionEditPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/import",element:jsxRuntimeExports.jsx(ImportWizardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/connect",element:jsxRuntimeExports.jsx(ConnectPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions",element:jsxRuntimeExports.jsx(SessionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions/:id",element:jsxRuntimeExports.jsx(SessionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects",element:jsxRuntimeExports.jsx(ProjectsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects/:id",element:jsxRuntimeExports.jsx(ProjectDetailPage,{})}),es,jsxRuntimeExports.jsx(Route,{path:"/eval-targets",element:jsxRuntimeExports.jsx(EvalTargetsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/eval-targets/:id",element:jsxRuntimeExports.jsx(EvalTargetDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights",element:jsxRuntimeExports.jsx(InsightsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights/:id",element:jsxRuntimeExports.jsx(InsightsDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories",element:jsxRuntimeExports.jsx(MemoriesListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories/:id",element:jsxRuntimeExports.jsx(MemoryDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/skills",element:jsxRuntimeExports.jsx(SkillsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public",element:jsxRuntimeExports.jsx(PublicCatalogPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public/:id",element:jsxRuntimeExports.jsx(PublicSkillDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/suggestions",element:jsxRuntimeExports.jsx(SuggestionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/usage",element:jsxRuntimeExports.jsx(UsagePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/docs",element:jsxRuntimeExports.jsx(DocsPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(SuperAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/superadmin",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/superadmin/users",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})})]}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(OrgAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/admin",element:jsxRuntimeExports.jsx(AdminOverviewPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members",element:jsxRuntimeExports.jsx(AdminMembersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members/invitations",element:jsxRuntimeExports.jsx(AdminInvitationsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams",element:jsxRuntimeExports.jsx(AdminTeamsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams/:teamSlug",element:jsxRuntimeExports.jsx(TeamDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/settings",element:jsxRuntimeExports.jsx(AdminSettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/research",element:jsxRuntimeExports.jsx(AdminResearchPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/announcements",element:jsxRuntimeExports.jsx(AdminAnnouncementsPage,{})})]})]})]}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(NotFoundPage,{})})]})})}),jsxRuntimeExports.jsx(Toaster,{})]})})})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").catch(es=>{console.error("Service worker registration failed:",es)})});clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(App,{})}));