@agentlang/lstudio 0.0.5 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/{index-fMnzpK9a.js → index-Cn4B33_-.js} +1 -1
- package/assets/{index-I5fcLGMl.js → index-DlZFTbUB.js} +1 -1
- package/assets/{index-D8JajO05.js → index-Doo87e5X.js} +5 -5
- package/assets/{index-FFWbIO7-.js → index-fkBiak1w.js} +1 -1
- package/assets/{index.browser-BMODMYhe.js → index.browser-BO5G3NbX.js} +3 -3
- package/assets/{loadCognitoIdentity-DuwaH8PQ.js → loadCognitoIdentity-7ZPodCIQ.js} +1 -1
- package/assets/{loadSts-SG-u3IDA.js → loadSts-CsI2lH7u.js} +1 -1
- package/assets/{replService-4Oc5i5Yn.js → replService-CStUCo8F.js} +1 -1
- package/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CNLtnwcG-CT9Tl0QI.js","assets/_commonjsHelpers-38a7CZ6X-W3E8ocG7.js","assets/winston-BvKfy0iJ-CwnGwJ9X.js","assets/__vite-browser-external-CoxO8HJt-D7Ct-6yo.js","assets/winston-Bb5ONwX_-B86ttl8E.js","assets/index-BfpeqTCw.js","assets/_commonjsHelpers-D6-XlEtG.js","assets/winston-DaXMbKRs.js","assets/util-qaS8mbUT.js","assets/inherits_browser-5Fj3Mjxs.js","assets/index-DIt05veo.js","assets/index-D1jV2j2Y.js","assets/__vite-browser-external-DJy8wZt7.js","assets/_commonjs-dynamic-modules-TDtrdbi3.js","assets/winston-D8lBg2T-.js","assets/util-ByC4ZISM-BeKX2g97.js","assets/util-Di1GNq-L-D-kgTTr0.js","assets/index-xuotMAFm-B-PTrwYx.js","assets/index-69shuAsh-DF18H7zf.js","assets/_commonjsHelpers-B4e78b8K-W3E8ocG7.js","assets/inherits_browser-BPb0V7-q-C7Z2MfVc.js","assets/index-CZyH7rAI-yNipxqK_.js","assets/winston-CtcDki1r-tmxR7nDg.js","assets/index-DsIu-45t-Bejjlpz4.js","assets/index-DSosZ5sh-Ceejs_jv.js","assets/index-6mKfgpcs-DsgiI2lM.js","assets/_commonjs-dynamic-modules-BpilXLfW-DfYEAvWy.js","assets/winston-CLh__iui-Dz2dJhwh.js","assets/index-Dy4QD7s1-DSfoLCzX.js","assets/preload-helper-BlTxHScW.js","assets/index-CUtIwvTY-Dla_hTy0.js","assets/index-D5v913EJ-CsbEilVn.js","assets/index-DGQM-tVy-4NRC-u1U.js","assets/index-CNLtnwcG-HJoxiQBn-DSWPwCKS.js","assets/_commonjsHelpers-38a7CZ6X-BfEUBFWa-BEFu9Otg.js","assets/winston-BvKfy0iJ-DkFo4NVo-UY_jirKN.js","assets/__vite-browser-external-CoxO8HJt-YbutIfMq-D7Ct-6yo.js","assets/winston-Bb5ONwX_-ziOUC-cl-v-kyB29h.js","assets/index.browser-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CNLtnwcG-CT9Tl0QI.js","assets/_commonjsHelpers-38a7CZ6X-W3E8ocG7.js","assets/winston-BvKfy0iJ-CwnGwJ9X.js","assets/__vite-browser-external-CoxO8HJt-D7Ct-6yo.js","assets/winston-Bb5ONwX_-B86ttl8E.js","assets/index-BfpeqTCw.js","assets/_commonjsHelpers-D6-XlEtG.js","assets/winston-DaXMbKRs.js","assets/util-qaS8mbUT.js","assets/inherits_browser-5Fj3Mjxs.js","assets/index-DIt05veo.js","assets/index-D1jV2j2Y.js","assets/__vite-browser-external-DJy8wZt7.js","assets/_commonjs-dynamic-modules-TDtrdbi3.js","assets/winston-D8lBg2T-.js","assets/util-ByC4ZISM-BeKX2g97.js","assets/util-Di1GNq-L-D-kgTTr0.js","assets/index-xuotMAFm-B-PTrwYx.js","assets/index-69shuAsh-DF18H7zf.js","assets/_commonjsHelpers-B4e78b8K-W3E8ocG7.js","assets/inherits_browser-BPb0V7-q-C7Z2MfVc.js","assets/index-CZyH7rAI-yNipxqK_.js","assets/winston-CtcDki1r-tmxR7nDg.js","assets/index-DsIu-45t-Bejjlpz4.js","assets/index-DSosZ5sh-Ceejs_jv.js","assets/index-6mKfgpcs-DsgiI2lM.js","assets/_commonjs-dynamic-modules-BpilXLfW-DfYEAvWy.js","assets/winston-CLh__iui-Dz2dJhwh.js","assets/index-Dy4QD7s1-DSfoLCzX.js","assets/preload-helper-BlTxHScW.js","assets/index-CUtIwvTY-Dla_hTy0.js","assets/index-D5v913EJ-CsbEilVn.js","assets/index-DGQM-tVy-4NRC-u1U.js","assets/index-CNLtnwcG-HJoxiQBn-DSWPwCKS.js","assets/_commonjsHelpers-38a7CZ6X-BfEUBFWa-BEFu9Otg.js","assets/winston-BvKfy0iJ-DkFo4NVo-UY_jirKN.js","assets/__vite-browser-external-CoxO8HJt-YbutIfMq-D7Ct-6yo.js","assets/winston-Bb5ONwX_-ziOUC-cl-v-kyB29h.js","assets/index.browser-BO5G3NbX.js","assets/normalizeProvider-BrOPyH3l.js","assets/index-Cn4B33_-.js","assets/index-fkBiak1w.js","assets/index-VamKv2HZ--hbiLl7B.js","assets/index-ChvoNxcO.js","assets/index-BJBOx-Z---hbiLl7B.js","assets/index-VamKv2HZ-CaraMydH-D75zmpPt.js","assets/index-BOLaQ9_Z.js","assets/index-Ynim4IDh.js","assets/replService-CStUCo8F.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{g as getDefaultExportFromCjs,c as commonjsGlobal,a as getAugmentedNamespace}from"./_commonjsHelpers-D6-XlEtG.js";import{_ as __vitePreload}from"./preload-helper-BlTxHScW.js";import{f as f$j,l as l$b,u as u$j}from"./_commonjsHelpers-38a7CZ6X-W3E8ocG7.js";import G$9 from"./index-VamKv2HZ--hbiLl7B.js";import chalk from"./index-ChvoNxcO.js";import{c as crypto$1}from"./__vite-browser-external-DJy8wZt7.js";import{b as b$b}from"./index-xuotMAFm-B-PTrwYx.js";import{f as f$k,u as u$k,l as l$d}from"./_commonjsHelpers-B4e78b8K-W3E8ocG7.js";import{Y as Yr$3}from"./index-6mKfgpcs-DsgiI2lM.js";import{s as s$g}from"./inherits_browser-BPb0V7-q-C7Z2MfVc.js";import{S as Sr$3,L as Lr$3,D as Dr$3}from"./index-DsIu-45t-Bejjlpz4.js";import{F as Ft$6,G as Gt$4,J as J$9}from"./index-69shuAsh-DF18H7zf.js";import G$a from"./index-BJBOx-Z---hbiLl7B.js";import{l as l$c}from"./index-D5v913EJ-CsbEilVn.js";import{r as r$f}from"./_commonjs-dynamic-modules-BpilXLfW-DfYEAvWy.js";import{I as I$c}from"./index-DSosZ5sh-Ceejs_jv.js";import{p as p$f,a as a$l,l as l$e}from"./_commonjsHelpers-38a7CZ6X-BfEUBFWa-BEFu9Otg.js";import{G as N$9}from"./index-VamKv2HZ-CaraMydH-D75zmpPt.js";import{r as require$$0$2,b as requireBase64Js}from"./index-D1jV2j2Y.js";import{c as commonjsRequire}from"./_commonjs-dynamic-modules-TDtrdbi3.js";import{a as requireBuffer,b as requireSafeBuffer,r as requireMs}from"./index-DIt05veo.js";import{a as requireCallBound,f as requireIsTypedArray$1,d as requireType,h as requireInherits_browser}from"./inherits_browser-5Fj3Mjxs.js";function _mergeNamespaces(ta,Ln){for(var Ta=0;Ta<Ln.length;Ta++){const ja=Ln[Ta];if(typeof ja!="string"&&!Array.isArray(ja)){for(const La in ja)if(La!=="default"&&!(La in ta)){const Fa=Object.getOwnPropertyDescriptor(ja,La);Fa&&Object.defineProperty(ta,La,Fa.get?Fa:{enumerable:!0,get:()=>ja[La]})}}}return Object.freeze(Object.defineProperty(ta,Symbol.toStringTag,{value:"Module"}))}(function(){const Ln=document.createElement("link").relList;if(Ln&&Ln.supports&&Ln.supports("modulepreload"))return;for(const La of document.querySelectorAll('link[rel="modulepreload"]'))ja(La);new MutationObserver(La=>{for(const Fa of La)if(Fa.type==="childList")for(const wl of Fa.addedNodes)wl.tagName==="LINK"&&wl.rel==="modulepreload"&&ja(wl)}).observe(document,{childList:!0,subtree:!0});function Ta(La){const Fa={};return La.integrity&&(Fa.integrity=La.integrity),La.referrerPolicy&&(Fa.referrerPolicy=La.referrerPolicy),La.crossOrigin==="use-credentials"?Fa.credentials="include":La.crossOrigin==="anonymous"?Fa.credentials="omit":Fa.credentials="same-origin",Fa}function ja(La){if(La.ep)return;La.ep=!0;const Fa=Ta(La);fetch(La.href,Fa)}})();var jsxRuntime$1={exports:{}},reactJsxRuntime_production$1={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.js
|
|
@@ -30420,7 +30420,7 @@ ${Em}`),Pl=`${Pl}
|
|
|
30420
30420
|
${wl} --> ${Em}
|
|
30421
30421
|
`,kf?wl=await preprocessStep(Em.trim(),ja):(ja.setFlowContext(Pl),await agentInvoke(Ln,`${Fa}
|
|
30422
30422
|
${Pl}`,ja),wl=await preprocessStep(ja.getLastResult().trim(),ja))}}finally{ja.decrementMonitor().revokeLastResult().setMonitorFlowResult()}console.debug(`No more flow steps, completed iteration ${mc} on flow:
|
|
30423
|
-
${ta}`)}async function preprocessStep(ta,Ln){if(ta.startsWith("{")){const ja=(await parseStatement$1(ta)).pattern.crudMap;if(ja){Ln.resetTemplateMappings();const La=ja.name;return ja.body&&ja.body.attributes.forEach(Fa=>{var wl;const Pl=(wl=Fa.value.$cstNode)===null||wl===void 0?void 0:wl.text;Pl&&Ln.setTemplateMapping(Fa.name,Pl)}),La}else throw new Error(`Invalid step - ${ta}`)}else return ta}async function handleOpenApiEvent(ta,Ln){const Ta=await invokeOpenApiEvent(ta.moduleName,ta.name,ta.attributesAsObject());Ln.setLastResult(Ta)}async function evaluateUpsert(ta,Ln){Ln.setInUpsertMode(!0);try{await evaluateCrudMap(ta,Ln)}finally{Ln.setInUpsertMode(!1)}}async function evaluateForEach(ta,Ln){const Ta=ta.var;await evaluatePattern(ta.src,Ln);const ja=Ln.getLastResult();if(ja instanceof Array&&ja.length>0){const La=Environment.from(Ln),Fa=new Array;for(let wl=0;wl<ja.length;++wl)La.bind(Ta,ja[wl]),await evaluateStatements(ta.statements,La),Fa.push(La.getLastResult());Ln.setLastResult(Fa)}else Ln.setLastResult(EmptyResult)}async function evaluateIf(ta,Ln){await evaluateExpression(ta.cond,Ln),Ln.getLastResult()?await evaluateStatements(ta.statements,Ln):ta.else!==void 0&&await evaluateStatements(ta.else.statements,Ln)}async function evaluateDeleteHelper(ta,Ln,Ta){const ja=Environment.from(Ta).setInDeleteMode(!0);await evaluatePattern(ta,ja),await maybeDeleteQueriedInstances(ja,Ta,Ln)}async function maybeDeleteQueriedInstances(ta,Ln,Ta=!1){const ja=ta.getLastResult();let La=Resolver.Default;if(ja instanceof Array)if(ja.length>0){La=await getResolverForPath(ja[0].name,ja[0].moduleName,ta);const Fa=new Array;for(let wl=0;wl<ja.length;++wl){await runPreDeleteEvents(ja[wl],Ln);const Pl=await La.deleteInstance(ja[wl],Ta);await runPostDeleteEvents(ja[wl],Ln),Fa.push(Pl)}ta.setLastResult(Fa)}else ta.setLastResult(ja);else{La=await getResolverForPath(ja.name,ja.moduleName,ta),await runPreDeleteEvents(ja,Ln);const Fa=await La.deleteInstance(ja,Ta);await runPostDeleteEvents(ja,Ln),ta.setLastResult(Fa)}Ln.setLastResult(ta.getLastResult())}async function evaluateDelete(ta,Ln){await evaluateDeleteHelper(ta.pattern,!1,Ln)}async function evaluatePurge(ta,Ln){await evaluateDeleteHelper(ta.pattern,!0,Ln)}async function evaluateExpression(ta,Ln){let Ta=EmptyResult;if(isBinExpr$1(ta)){await evaluateExpression(ta.e1,Ln);const ja=Ln.getLastResult();if(ta.op=="or"){if(ja)return;await evaluateExpression(ta.e2,Ln);return}else if(ta.op=="and"){if(!ja)return;await evaluateExpression(ta.e2,Ln);return}if(ja==null){Ln.setLastResult(void 0);return}await evaluateExpression(ta.e2,Ln);const La=Ln.getLastResult();if(La==null){Ln.setLastResult(void 0);return}switch(ta.op){case"+":Ta=ja+La;break;case"-":Ta=ja-La;break;case"*":Ta=ja*La;break;case"/":Ta=ja/La;break;case"==":Ta=ja==La;break;case"<":Ta=ja<La;break;case">":Ta=ja>La;break;case"<=":Ta=ja<=La;break;case">=":Ta=ja>=La;break;case"<>":case"!=":Ta=ja!=La;break;case"like":Ta=ja.startsWith(La);break;case"in":Ta=La.find(Fa=>{});break;default:throw new Error(`Unrecognized binary operator: ${ta.op}`)}}else if(isNegExpr$1(ta))await evaluateExpression(ta.ne,Ln),Ta=-1*Ln.getLastResult();else if(isGroup$2(ta))await evaluateExpression(ta.ge,Ln),Ta=Ln.getLastResult();else if(isLiteral$1(ta)){await evaluateLiteral(ta,Ln);return}else isNotExpr$1(ta)&&(await evaluateExpression(ta.ne,Ln),Ta=!Ln.getLastResult());Ln.setLastResult(Ta)}async function getRef(ta,Ln,Ta){return Instance$1.IsInstance(Ln)?Ln.lookup(ta):Ln instanceof Map?Ln.get(ta):Ln instanceof Object?Ln[ta]:isPath$1(Ln)?await getRef(ta,await dereferencePath(Ln,Ta),Ta):void 0}async function followReference(ta,Ln){const Ta=splitRefs$1(Ln);let ja=EmptyResult,La=ta;for(let Fa=0;Fa<Ta.length;++Fa){const wl=Ta[Fa],Pl=await getRef(wl,La,ta);if(Pl===void 0)return EmptyResult;ja=Pl,La=ja}return ja}async function dereferencePath(ta,Ln){const Ta=fqNameFromPath$1(ta);if(Ta===void 0)throw new Error(`Failed to deduce entry-name from path - ${ta}`);const ja=new Environment("path-deref",Ln);await parseAndEvaluateStatement(`{${Ta} {${PathAttributeNameQuery$1} "${ta}"}}`,Ln.getAuthContextUserId(),ja);const La=ja.getLastResult();if(La&&La instanceof Array&&La.length>0)return La[0]}async function applyFn(ta,Ln,Ta){const ja=ta.name;if(ja!==void 0){let La=null;if(ta.args!==void 0){La=new Array;for(let wl=0;wl<ta.args.length;++wl){const Pl=ta.args[wl];isLiteral$1(Pl)?await evaluateLiteral(Pl,Ln):await evaluateExpression(Pl,Ln),La.push(Ln.getLastResult())}La.push(Ln)}const Fa=await invokeModuleFn(ja,La,Ta);Ln.setLastResult(Fa)}}async function realizeArray(ta,Ln){const Ta=new Array;for(let ja=0;ja<ta.vals.length;++ja)await evaluateStatement(ta.vals[ja],Ln),Ta.push(Ln.getLastResult());Ln.setLastResult(Ta)}async function realizeMap(ta,Ln){const Ta=new Map;for(let ja=0;ja<ta.entries.length;++ja){const La=ta.entries[ja],Fa=getMapKey(La.key);await evaluateExpression(La.value,Ln),Ta.set(Fa,Ln.getLastResult())}Ln.setLastResult(Object.fromEntries(Ta.entries()))}async function callPostEventOnSubscription(ta,Ln,Ta){const ja=new Environment("onSubs.env");return await runPrePostEvents(ta,!1,Ln,ja),ja.getLastResult()}async function runPrePostEvents(ta,Ln,Ta,ja){const La=Ln?Ta.record.getPreTriggerInfo(ta):Ta.record.getPostTriggerInfo(ta);if(La){const Fa=nameToPath$1(La.eventName),wl=Fa.hasModule()?Fa.getModuleName():Ta.record.moduleName,Pl=makeInstance$1(wl,Fa.getEntryName(),newInstanceAttributes$1().set(Ta.record.name,Ta)),pc=ja.getActiveAuthContext();pc&&Pl.setAuthContext(pc);const mc=`${Ln?"Pre":"Post"}-${CrudType$1[ta]} ${Ta.record.getFqName()}`,gc=Wd=>{logger$3.debug(`${mc}: ${Wd}`)},Vd=Wd=>{throw ja.hasHandlers()?Wd:new Error(`${mc}: ${Wd}`)};La.async?evaluate$1(Pl,gc,bindAliasesForPrePost(ja,Ta,mc)).catch(Vd):await evaluate$1(Pl,gc,bindAliasesForPrePost(ja,Ta,mc)).catch(Vd)}}function bindAliasesForPrePost(ta,Ln,Ta){const ja=new Environment(`${Ta}.env`,ta),La=Ln.getFqName();return ja.bind("this",Ln),ja.bind(La,Ln),ja.bind(Ln.name,Ln),ja}async function runPreCreateEvents(ta,Ln){await runPrePostEvents(CrudType$1.CREATE,!0,ta,Ln)}async function runPostCreateEvents(ta,Ln){ta.requireAudit()&&await addCreateAudit(ta.getPath(),Ln),await runPrePostEvents(CrudType$1.CREATE,!1,ta,Ln)}async function runPreUpdateEvents(ta,Ln){await runPrePostEvents(CrudType$1.UPDATE,!0,ta,Ln)}async function runPostUpdateEvents(ta,Ln,Ta){ta.requireAudit()&&await addUpdateAudit(ta.getPath(),Ln,Ta),await runPrePostEvents(CrudType$1.UPDATE,!1,ta,Ta)}async function runPreDeleteEvents(ta,Ln){await runPrePostEvents(CrudType$1.DELETE,!0,ta,Ln)}async function runPostDeleteEvents(ta,Ln){ta.requireAudit()&&await addDeleteAudit(ta.getPath(),ta,Ln),await runPrePostEvents(CrudType$1.DELETE,!1,ta,Ln)}const interpreter=Object.freeze(Object.defineProperty({__proto__:null,DocEventName,Environment,GlobalEnvironment,PatternHandler,callPostEventOnSubscription,evaluate:evaluate$1,evaluateAsEvent,evaluateExpression,evaluatePattern,evaluateStatement,evaluateStatements,handleAgentInvocation,handleOpenApiEvent,makeEventEvaluator,maybeBindStatementResultToAlias,maybeDeleteQueriedInstances,parseAndEvaluateStatement,restartFlow,runPostCreateEvents,runPostDeleteEvents,runPostUpdateEvents},Symbol.toStringTag,{value:"Module"}));class JwtBaseError extends Error{}class FailedAssertionError extends JwtBaseError{constructor(Ln,Ta,ja){super(Ln),this.failedAssertion={actual:Ta,expected:ja}}}class JwtParseError extends JwtBaseError{constructor(Ln,Ta){const ja=Ta!=null?`${Ln}: ${Ta}`:Ln;super(ja)}}class ParameterValidationError extends JwtBaseError{}class JwtInvalidSignatureError extends JwtBaseError{}class JwtInvalidSignatureAlgorithmError extends FailedAssertionError{}class JwtInvalidClaimError extends FailedAssertionError{withRawJwt({header:Ln,payload:Ta}){return this.rawJwt={header:Ln,payload:Ta},this}}class JwtInvalidIssuerError extends JwtInvalidClaimError{}class JwtInvalidAudienceError extends JwtInvalidClaimError{}class JwtInvalidScopeError extends JwtInvalidClaimError{}class JwtExpiredError extends JwtInvalidClaimError{}class JwtNotBeforeError extends JwtInvalidClaimError{}class CognitoJwtInvalidGroupError extends JwtInvalidClaimError{}class CognitoJwtInvalidTokenUseError extends JwtInvalidClaimError{}class CognitoJwtInvalidClientIdError extends JwtInvalidClaimError{}class JwksValidationError extends JwtBaseError{}class JwkValidationError extends JwtBaseError{}class JwtWithoutValidKidError extends JwtBaseError{}class KidNotFoundInJwksError extends JwtBaseError{}class WaitPeriodNotYetEndedJwkError extends JwtBaseError{}class JwksNotAvailableInCacheError extends JwtBaseError{}class JwkInvalidUseError extends FailedAssertionError{}class JwkInvalidKtyError extends FailedAssertionError{}class FetchError extends JwtBaseError{constructor(Ln,Ta){super(`Failed to fetch ${Ln}: ${Ta}`)}}class NonRetryableFetchError extends FetchError{}class NotSupportedError extends JwtBaseError{}var NamedCurvesWebCrypto;(function(ta){ta.ES256="P-256",ta.ES384="P-384",ta.ES512="P-521"})(NamedCurvesWebCrypto||(NamedCurvesWebCrypto={}));const nodeWebCompat={fetch:async(ta,Ln,Ta)=>{const ja=Number(Ln?.responseTimeout);if(ja){const Fa=new AbortController;setTimeout(()=>Fa.abort(new FetchError(ta,`Response time-out (after ${ja} ms.)`)),ja),Ln={signal:Fa.signal,...Ln}}const La=await fetch(ta,{...Ln,body:Ta}).catch(Fa=>{throw new FetchError(ta,Fa.message)});if(La.status!==200)throw new NonRetryableFetchError(ta,`Status code is ${La.status}, expected 200`);return La.arrayBuffer()},defaultFetchTimeouts:{response:3e3},transformJwkToKeyObjectSync:()=>{throw new NotSupportedError("Synchronously transforming a JWK into a key object is not supported in the browser")},transformJwkToKeyObjectAsync:(ta,Ln)=>{const Ta=ta.alg??Ln;if(!Ta)throw new JwtInvalidSignatureAlgorithmError("Missing alg on both JWK and JWT header",Ta);const ja=Ta.startsWith("RS")?{name:"RSASSA-PKCS1-v1_5",hash:`SHA-${Ta.slice(2)}`}:Ta.startsWith("ES")?{name:"ECDSA",namedCurve:NamedCurvesWebCrypto[Ta]}:ta.crv;return crypto.subtle.importKey("jwk",ta,ja,!1,["verify"]).then(La=>({key:La,jwk:ta}))},verifySignatureSync:()=>{throw new NotSupportedError("Synchronously verifying a JWT signature is not supported in the browser")},verifySignatureAsync:({jwsSigningInput:ta,keyObject:Ln,signature:Ta,alg:ja})=>crypto.subtle.verify(ja.startsWith("RS")?{name:"RSASSA-PKCS1-v1_5"}:ja.startsWith("ES")?{name:"ECDSA",hash:`SHA-${ja.slice(2)}`}:{name:Ln.jwk.crv},Ln.key,bufferFromBase64url(Ta),new TextEncoder().encode(ta)),parseB64UrlString:ta=>new TextDecoder().decode(bufferFromBase64url(ta)),setTimeoutUnref:setTimeout.bind(void 0),transformPemToJwk:async(ta,Ln)=>{let Ta;switch(Ln){case"RS256":case"RS384":case"RS512":Ta={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${Ln.slice(2)}`};break;case"ES256":case"ES384":case"ES512":Ta={name:"ECDSA",namedCurve:NamedCurvesWebCrypto[Ln]};break;default:throw new JwtInvalidSignatureAlgorithmError("Unsupported signature algorithm",Ln)}const ja=await crypto.subtle.importKey("spki",bufferFromBase64(new TextDecoder().decode(ta).replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,"")),Ta,!0,["verify"]);return crypto.subtle.exportKey("jwk",ja)}};function _bufferFromBase64(ta){const Ln=ta.split("").reduce((Ta,ja,La)=>Object.assign(Ta,{[ja.charCodeAt(0)]:La}),{});return function(Ta){Ta=Ta.replace(/={1,2}$/,"");let ja,La,Fa,wl;return Ta.match(/.{1,4}/g).reduce((Pl,pc,mc)=>(ja=Ln[pc.charCodeAt(0)],La=Ln[pc.charCodeAt(1)],Fa=Ln[pc.charCodeAt(2)],wl=Ln[pc.charCodeAt(3)],Pl[3*mc]=ja<<2|La>>4,Pl[3*mc+1]=(La&15)<<4|Fa>>2,Pl[3*mc+2]=(Fa&3)<<6|wl,Pl),new Uint8Array(Ta.length*3/4))}}const bufferFromBase64url=_bufferFromBase64("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),bufferFromBase64=_bufferFromBase64("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),fetch$1=nodeWebCompat.fetch.bind(void 0);class SimpleFetcher{constructor(Ln){this.defaultRequestOptions={timeout:nodeWebCompat.defaultFetchTimeouts.socketIdle,responseTimeout:nodeWebCompat.defaultFetchTimeouts.response,...Ln?.defaultRequestOptions}}async fetch(Ln,Ta,ja){Ta={...this.defaultRequestOptions,...Ta};try{return await fetch$1(Ln,Ta,ja)}catch(La){if(La instanceof NonRetryableFetchError)throw La;return fetch$1(Ln,Ta,ja)}}}function isJsonObject(ta){return typeof ta=="object"&&!Array.isArray(ta)&&ta!==null}function safeJsonParse(ta){return JSON.parse(ta,(Ln,Ta)=>(typeof Ta=="object"&&!Array.isArray(Ta)&&Ta!==null&&(delete Ta.__proto__,delete Ta.constructor),Ta))}function assertStringEquals(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. Expected: ${Ta}`,Ln,Ta);if(typeof Ln!="string")throw new ja(`${ta} is not of type string`,Ln,Ta);if(Ta!==Ln)throw new ja(`${ta} not allowed: ${Ln}. Expected: ${Ta}`,Ln,Ta)}function assertStringArrayContainsString(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. ${expectationMessage(Ta)}`,Ln,Ta);if(typeof Ln!="string")throw new ja(`${ta} is not of type string`,Ln,Ta);return assertStringArraysOverlap(ta,Ln,Ta,ja)}function assertStringArraysOverlap(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. ${expectationMessage(Ta)}`,Ln,Ta);const La=new Set(Array.isArray(Ta)?Ta:[Ta]);if(typeof Ln=="string"&&(Ln=[Ln]),!Array.isArray(Ln))throw new ja(`${ta} is not an array`,Ln,Ta);if(!Ln.some(wl=>{if(typeof wl!="string")throw new ja(`${ta} includes elements that are not of type string`,Ln,Ta);return La.has(wl)}))throw new ja(`${ta} not allowed: ${Ln.join(", ")}. ${expectationMessage(Ta)}`,Ln,Ta)}function expectationMessage(ta){return Array.isArray(ta)?ta.length>1?`Expected one of: ${ta.join(", ")}`:`Expected: ${ta[0]}`:`Expected: ${ta}`}function assertIsNotPromise(ta,Ln){if(ta&&typeof ta.then=="function")throw Ln()}const optionalJwkFieldNames=["use","alg","kid","n","e","x","y","crv"],mandatoryJwkFieldNames=["kty"];function findJwkInJwks(ta,Ln){return ta.keys.find(Ta=>Ta.kid!=null&&Ta.kid===Ln)}const parseJwks=function(ta){let Ln;try{const Ta=new TextDecoder("utf8",{fatal:!0,ignoreBOM:!0}).decode(ta);Ln=safeJsonParse(Ta)}catch(Ta){throw new JwksValidationError(`JWKS could not be parsed as JSON: ${Ta}`)}return assertIsJwks(Ln),Ln};function assertIsJwks(ta){if(!ta)throw new JwksValidationError("JWKS empty");if(!isJsonObject(ta))throw new JwksValidationError("JWKS should be an object");if(!Object.keys(ta).includes("keys"))throw new JwksValidationError("JWKS does not include keys");if(!Array.isArray(ta.keys))throw new JwksValidationError("JWKS keys should be an array");for(const Ln of ta.keys)assertIsJwk(Ln)}function assertIsSignatureJwk(ta){assertStringArrayContainsString("JWK kty",ta.kty,["EC","RSA","OKP"],JwkInvalidKtyError),ta.kty==="EC"?assertIsEsSignatureJwk(ta):ta.kty==="RSA"?assertIsRsaSignatureJwk(ta):ta.kty==="OKP"&&assertIsEdDSASignatureJwk(ta)}function assertIsEdDSASignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"OKP",JwkInvalidKtyError),!ta.crv)throw new JwkValidationError("Missing Curve (crv)");if(!ta.x)throw new JwkValidationError("Missing X Coordinate (x)")}function assertIsEsSignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"EC",JwkInvalidKtyError),!ta.crv)throw new JwkValidationError("Missing Curve (crv)");if(!ta.x)throw new JwkValidationError("Missing X Coordinate (x)");if(!ta.y)throw new JwkValidationError("Missing Y Coordinate (y)")}function assertIsRsaSignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"RSA",JwkInvalidKtyError),!ta.n)throw new JwkValidationError("Missing modulus (n)");if(!ta.e)throw new JwkValidationError("Missing exponent (e)")}function assertIsJwk(ta){if(!ta)throw new JwkValidationError("JWK empty");if(!isJsonObject(ta))throw new JwkValidationError("JWK should be an object");for(const Ln of mandatoryJwkFieldNames)if(typeof ta[Ln]!="string")throw new JwkValidationError(`JWK ${Ln} should be a string`);for(const Ln of optionalJwkFieldNames)if(Ln in ta&&typeof ta[Ln]!="string")throw new JwkValidationError(`JWK ${Ln} should be a string`)}function isJwks(ta){try{return assertIsJwks(ta),!0}catch{return!1}}function isJwk(ta){try{return assertIsJwk(ta),!0}catch{return!1}}class SimplePenaltyBox{constructor(Ln){this.waitingUris=new Map,this.waitSeconds=Ln?.waitSeconds??10}async wait(Ln){if(this.waitingUris.has(Ln))throw new WaitPeriodNotYetEndedJwkError("Not allowed to fetch JWKS yet, still waiting for back off period to end")}release(Ln){const Ta=this.waitingUris.get(Ln);Ta&&(clearTimeout(Ta),this.waitingUris.delete(Ln))}registerFailedAttempt(Ln){const Ta=nodeWebCompat.setTimeoutUnref(()=>{this.waitingUris.delete(Ln)},this.waitSeconds*1e3);this.waitingUris.set(Ln,Ta)}registerSuccessfulAttempt(Ln){this.release(Ln)}}class SimpleJwksCache{constructor(Ln){this.jwksCache=new Map,this.fetchingJwks=new Map,this.penaltyBox=Ln?.penaltyBox??new SimplePenaltyBox,this.fetcher=Ln?.fetcher??new SimpleFetcher,this.jwksParser=Ln?.jwksParser??parseJwks}addJwks(Ln,Ta){this.jwksCache.set(Ln,Ta)}async getJwks(Ln){const Ta=this.fetchingJwks.get(Ln);if(Ta)return Ta;const ja=this.fetcher.fetch(Ln).then(this.jwksParser);this.fetchingJwks.set(Ln,ja);let La;try{La=await ja}finally{this.fetchingJwks.delete(Ln)}return this.jwksCache.set(Ln,La),La}getCachedJwk(Ln,Ta){if(typeof Ta.header.kid!="string")throw new JwtWithoutValidKidError("JWT header does not have valid kid claim");if(!this.jwksCache.has(Ln))throw new JwksNotAvailableInCacheError(`JWKS for uri ${Ln} not yet available in cache`);const ja=findJwkInJwks(this.jwksCache.get(Ln),Ta.header.kid);if(!ja)throw new KidNotFoundInJwksError(`JWK for kid ${Ta.header.kid} not found in the JWKS`);return ja}async getJwk(Ln,Ta){if(typeof Ta.header.kid!="string")throw new JwtWithoutValidKidError("JWT header does not have valid kid claim");const ja=this.jwksCache.get(Ln);if(ja){const wl=findJwkInJwks(ja,Ta.header.kid);if(wl)return wl}await this.penaltyBox.wait(Ln,Ta.header.kid);const La=await this.getJwks(Ln),Fa=findJwkInJwks(La,Ta.header.kid);if(Fa)this.penaltyBox.registerSuccessfulAttempt(Ln,Ta.header.kid);else throw this.penaltyBox.registerFailedAttempt(Ln,Ta.header.kid),new KidNotFoundInJwksError(`JWK for kid "${Ta.header.kid}" not found in the JWKS`);return Fa}}function assertJwtHeader(ta){if(!isJsonObject(ta))throw new JwtParseError("JWT header is not an object");if(ta.alg!==void 0&&typeof ta.alg!="string")throw new JwtParseError("JWT header alg claim is not a string");if(ta.kid!==void 0&&typeof ta.kid!="string")throw new JwtParseError("JWT header kid claim is not a string")}function assertJwtPayload(ta){if(!isJsonObject(ta))throw new JwtParseError("JWT payload is not an object");if(ta.exp!==void 0&&!Number.isFinite(ta.exp))throw new JwtParseError("JWT payload exp claim is not a number");if(ta.iss!==void 0&&typeof ta.iss!="string")throw new JwtParseError("JWT payload iss claim is not a string");if(ta.sub!==void 0&&typeof ta.sub!="string")throw new JwtParseError("JWT payload sub claim is not a string");if(ta.aud!==void 0&&typeof ta.aud!="string"&&(!Array.isArray(ta.aud)||ta.aud.some(Ln=>typeof Ln!="string")))throw new JwtParseError("JWT payload aud claim is not a string or array of strings");if(ta.nbf!==void 0&&!Number.isFinite(ta.nbf))throw new JwtParseError("JWT payload nbf claim is not a number");if(ta.iat!==void 0&&!Number.isFinite(ta.iat))throw new JwtParseError("JWT payload iat claim is not a number");if(ta.scope!==void 0&&typeof ta.scope!="string")throw new JwtParseError("JWT payload scope claim is not a string");if(ta.jti!==void 0&&typeof ta.jti!="string")throw new JwtParseError("JWT payload jti claim is not a string")}const JWT_REGEX=/^[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/;function decomposeUnverifiedJwt(ta){if(!ta)throw new JwtParseError("Empty JWT");if(typeof ta!="string")throw new JwtParseError("JWT is not a string");if(!JWT_REGEX.test(ta))throw new JwtParseError("JWT string does not consist of exactly 3 parts (header, payload, signature)");const[Ln,Ta,ja]=ta.split("."),[La,Fa]=[Ln,Ta].map(nodeWebCompat.parseB64UrlString);let wl;try{wl=safeJsonParse(La)}catch(pc){throw new JwtParseError("Invalid JWT. Header is not a valid JSON object",pc)}assertJwtHeader(wl);let Pl;try{Pl=safeJsonParse(Fa)}catch(pc){throw new JwtParseError("Invalid JWT. Payload is not a valid JSON object",pc)}return assertJwtPayload(Pl),{header:wl,headerB64:Ln,payload:Pl,payloadB64:Ta,signatureB64:ja}}function validateJwtFields(ta,Ln){if(ta.exp!==void 0&&ta.exp+(Ln.graceSeconds??0)<Date.now()/1e3)throw new JwtExpiredError(`Token expired at ${new Date(ta.exp*1e3).toISOString()}`,ta.exp);if(ta.nbf!==void 0&&ta.nbf-(Ln.graceSeconds??0)>Date.now()/1e3)throw new JwtNotBeforeError(`Token can't be used before ${new Date(ta.nbf*1e3).toISOString()}`,ta.nbf);if(Ln.issuer!==null){if(Ln.issuer===void 0)throw new ParameterValidationError("issuer must be provided or set to null explicitly");assertStringArrayContainsString("Issuer",ta.iss,Ln.issuer,JwtInvalidIssuerError)}if(Ln.audience!==null){if(Ln.audience===void 0)throw new ParameterValidationError("audience must be provided or set to null explicitly");assertStringArraysOverlap("Audience",ta.aud,Ln.audience,JwtInvalidAudienceError)}Ln.scope!=null&&assertStringArraysOverlap("Scope",ta.scope?.split(" "),Ln.scope,JwtInvalidScopeError)}const supportedSignatureAlgorithms=["RS256","RS384","RS512","ES256","ES384","ES512","EdDSA"];function validateJwtHeaderAndJwk(ta,Ln){assertIsSignatureJwk(Ln),Ln.alg&&assertStringEquals("JWT signature algorithm",ta.alg,Ln.alg,JwtInvalidSignatureAlgorithmError),assertStringArrayContainsString("JWT signature algorithm",ta.alg,supportedSignatureAlgorithms,JwtInvalidSignatureAlgorithmError)}async function verifyDecomposedJwt(ta,Ln,Ta,ja,La){const{header:Fa,headerB64:wl,payload:Pl,payloadB64:pc,signatureB64:mc}=ta,gc=await ja(Ln,ta);validateJwtHeaderAndJwk(ta.header,gc);const Vd=await La(gc,Fa.alg,Pl.iss);if(!await nodeWebCompat.verifySignatureAsync({jwsSigningInput:`${wl}.${pc}`,signature:mc,alg:Fa.alg,keyObject:Vd}))throw new JwtInvalidSignatureError("Invalid signature");try{validateJwtFields(Pl,Ta),Ta.customJwtCheck&&await Ta.customJwtCheck({header:Fa,payload:Pl,jwk:gc})}catch(kf){throw Ta.includeRawJwtInErrors&&kf instanceof JwtInvalidClaimError?kf.withRawJwt(ta):kf}return Pl}function verifyDecomposedJwtSync(ta,Ln,Ta,ja){const{header:La,headerB64:Fa,payload:wl,payloadB64:Pl,signatureB64:pc}=ta;let mc;if(isJwk(Ln))mc=Ln;else if(isJwks(Ln)){const Wd=La.kid?findJwkInJwks(Ln,La.kid):void 0;if(!Wd)throw new KidNotFoundInJwksError(`JWK for kid ${La.kid} not found in the JWKS`);mc=Wd}else throw new ParameterValidationError([`Expected a valid JWK or JWKS (parsed as JavaScript object), but received: ${Ln}.`,"If you're passing a JWKS URI, use the async verify() method instead, it will download and parse the JWKS for you"].join());validateJwtHeaderAndJwk(ta.header,mc);const gc=ja(mc,La.alg,wl.iss);if(!nodeWebCompat.verifySignatureSync({jwsSigningInput:`${Fa}.${Pl}`,signature:pc,alg:La.alg,keyObject:gc}))throw new JwtInvalidSignatureError("Invalid signature");try{if(validateJwtFields(wl,Ta),Ta.customJwtCheck){const Wd=Ta.customJwtCheck({header:La,payload:wl,jwk:mc});assertIsNotPromise(Wd,()=>new ParameterValidationError("Custom JWT checks must be synchronous but a promise was returned"))}}catch(Wd){throw Ta.includeRawJwtInErrors&&Wd instanceof JwtInvalidClaimError?Wd.withRawJwt(ta):Wd}return wl}class JwtVerifierBase{constructor(Ln,Ta=new SimpleJwksCache){if(this.jwksCache=Ta,this.issuersConfig=new Map,this.publicKeyCache=new KeyObjectCache,Array.isArray(Ln)){if(!Ln.length)throw new ParameterValidationError("Provide at least one issuer configuration");Ln.forEach((ja,La)=>{if(this.issuersConfig.has(ja.issuer))throw new ParameterValidationError(`issuer ${ja.issuer} supplied multiple times`);if(ja.issuer===null&&Ln.length>=2)throw new ParameterValidationError(`issuer cannot be null when multiple issuers are supplied (at issuer: ${La})`);this.issuersConfig.set(ja.issuer,this.withJwksUri(ja))})}else this.issuersConfig.set(Ln.issuer,this.withJwksUri(Ln))}getIssuerConfig(Ln){if(this.issuersConfig.size===1&&(Ln=this.issuersConfig.keys().next().value),Ln===void 0)throw new ParameterValidationError("issuer must be provided");const Ta=this.issuersConfig.get(Ln);if(!Ta)throw new ParameterValidationError(`issuer not configured: ${Ln}`);return Ta}cacheJwks(...[Ln,Ta]){const ja=this.getIssuerConfig(Ta);this.jwksCache.addJwks(ja.jwksUri,Ln),this.publicKeyCache.clearCache(ja.issuer)}async hydrate(){const Ln=Array.from(this.issuersConfig.values()).map(({jwksUri:Ta})=>this.jwksCache.getJwks(Ta));await Promise.all(Ln)}verifySync(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);return this.verifyDecomposedJwtSync(ja,La,Fa)}verifyDecomposedJwtSync(Ln,Ta,ja){const La=this.jwksCache.getCachedJwk(Ta,Ln);return verifyDecomposedJwtSync(Ln,La,ja,this.publicKeyCache.transformJwkToKeyObjectSync.bind(this.publicKeyCache))}async verify(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);return this.verifyDecomposedJwt(ja,La,Fa)}verifyDecomposedJwt(Ln,Ta,ja){return verifyDecomposedJwt(Ln,Ta,ja,this.jwksCache.getJwk.bind(this.jwksCache),this.publicKeyCache.transformJwkToKeyObjectAsync.bind(this.publicKeyCache))}getVerifyParameters(Ln,Ta){const ja=decomposeUnverifiedJwt(Ln),La=this.getIssuerConfig(ja.payload.iss);return{decomposedJwt:ja,jwksUri:La.jwksUri,verifyProperties:{...La,...Ta}}}withJwksUri(Ln){if(Ln.jwksUri)return Ln;const Ta=Ln.issuer;if(!Ta)throw new ParameterValidationError("jwksUri must be provided for issuer null");const ja=new URL(Ta).pathname.replace(/\/$/,"");return{jwksUri:new URL(`${ja}/.well-known/jwks.json`,Ta).href,...Ln}}}class KeyObjectCache{constructor(Ln=nodeWebCompat.transformJwkToKeyObjectSync,Ta=nodeWebCompat.transformJwkToKeyObjectAsync){this.transformJwkToKeyObjectSyncFn=Ln,this.transformJwkToKeyObjectAsyncFn=Ta,this.publicKeys=new Map}transformJwkToKeyObjectSync(Ln,Ta,ja){const La=Ln.alg??Ta;if(!ja||!Ln.kid||!La)return this.transformJwkToKeyObjectSyncFn(Ln,La,ja);const Fa=this.publicKeys.get(ja)?.get(Ln.kid)?.get(La);if(Fa)return Fa;const wl=this.transformJwkToKeyObjectSyncFn(Ln,La,ja);return this.putKeyObjectInCache(ja,Ln.kid,La,wl),wl}async transformJwkToKeyObjectAsync(Ln,Ta,ja){const La=Ln.alg??Ta;if(!ja||!Ln.kid||!La)return this.transformJwkToKeyObjectAsyncFn(Ln,La,ja);const Fa=this.publicKeys.get(ja)?.get(Ln.kid)?.get(La);if(Fa)return Fa;const wl=await this.transformJwkToKeyObjectAsyncFn(Ln,La,ja);return this.putKeyObjectInCache(ja,Ln.kid,La,wl),wl}putKeyObjectInCache(Ln,Ta,ja,La){const Fa=this.publicKeys.get(Ln),wl=Fa?.get(Ta);wl?wl.set(ja,La):Fa?Fa.set(Ta,new Map([[ja,La]])):this.publicKeys.set(Ln,new Map([[Ta,new Map([[ja,La]])]]))}clearCache(Ln){this.publicKeys.delete(Ln)}}function validateCognitoJwtFields(ta,Ln){if(Ln.groups!=null&&assertStringArraysOverlap("Cognito group",ta["cognito:groups"],Ln.groups,CognitoJwtInvalidGroupError),assertStringArrayContainsString("Token use",ta.token_use,["id","access"],CognitoJwtInvalidTokenUseError),Ln.tokenUse!==null){if(Ln.tokenUse===void 0)throw new ParameterValidationError("tokenUse must be provided or set to null explicitly");assertStringEquals("Token use",ta.token_use,Ln.tokenUse,CognitoJwtInvalidTokenUseError)}if(Ln.clientId!==null){if(Ln.clientId===void 0)throw new ParameterValidationError("clientId must be provided or set to null explicitly");ta.token_use==="id"?assertStringArrayContainsString('Client ID ("audience")',ta.aud,Ln.clientId,CognitoJwtInvalidClientIdError):assertStringArrayContainsString("Client ID",ta.client_id,Ln.clientId,CognitoJwtInvalidClientIdError)}}class CognitoJwtVerifier extends JwtVerifierBase{constructor(Ln,Ta){const ja=Array.isArray(Ln)?Ln.map(La=>({...La,...CognitoJwtVerifier.parseUserPoolId(La.userPoolId),audience:null})):{...Ln,...CognitoJwtVerifier.parseUserPoolId(Ln.userPoolId),audience:null};super(ja,Ta)}static parseUserPoolId(Ln){const Ta=Ln.match(this.USER_POOL_ID_REGEX);if(!Ta)throw new ParameterValidationError(`Invalid Cognito User Pool ID: ${Ln}`);const La=`https://cognito-idp.${Ta.groups.region}.amazonaws.com/${Ln}`;return{issuer:La,jwksUri:`${La}/.well-known/jwks.json`}}static create(Ln,Ta){return new this(Ln,Ta?.jwksCache)}verifySync(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);this.verifyDecomposedJwtSync(ja,La,Fa);try{validateCognitoJwtFields(ja.payload,Fa)}catch(wl){throw Fa.includeRawJwtInErrors&&wl instanceof JwtInvalidClaimError?wl.withRawJwt(ja):wl}return ja.payload}async verify(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);await this.verifyDecomposedJwt(ja,La,Fa);try{validateCognitoJwtFields(ja.payload,Fa)}catch(wl){throw Fa.includeRawJwtInErrors&&wl instanceof JwtInvalidClaimError?wl.withRawJwt(ja):wl}return ja.payload}cacheJwks(...[Ln,Ta]){let ja;if(Ta!==void 0)ja=CognitoJwtVerifier.parseUserPoolId(Ta).issuer;else if(Array.from(this.issuersConfig).length>1)throw new ParameterValidationError("userPoolId must be provided");const La=this.getIssuerConfig(ja);super.cacheJwks(Ln,La.issuer)}}CognitoJwtVerifier.USER_POOL_ID_REGEX=/^(?<region>[a-z]{2}-(gov-)?[a-z]+-\d)_[a-zA-Z0-9]+$/;var __assign=function(){return __assign=Object.assign||function(Ln){for(var Ta,ja=1,La=arguments.length;ja<La;ja++){Ta=arguments[ja];for(var Fa in Ta)Object.prototype.hasOwnProperty.call(Ta,Fa)&&(Ln[Fa]=Ta[Fa])}return Ln},__assign.apply(this,arguments)};function __rest(ta,Ln){var Ta={};for(var ja in ta)Object.prototype.hasOwnProperty.call(ta,ja)&&Ln.indexOf(ja)<0&&(Ta[ja]=ta[ja]);if(ta!=null&&typeof Object.getOwnPropertySymbols=="function")for(var La=0,ja=Object.getOwnPropertySymbols(ta);La<ja.length;La++)Ln.indexOf(ja[La])<0&&Object.prototype.propertyIsEnumerable.call(ta,ja[La])&&(Ta[ja[La]]=ta[ja[La]]);return Ta}function __awaiter(ta,Ln,Ta,ja){function La(Fa){return Fa instanceof Ta?Fa:new Ta(function(wl){wl(Fa)})}return new(Ta||(Ta=Promise))(function(Fa,wl){function Pl(gc){try{mc(ja.next(gc))}catch(Vd){wl(Vd)}}function pc(gc){try{mc(ja.throw(gc))}catch(Vd){wl(Vd)}}function mc(gc){gc.done?Fa(gc.value):La(gc.value).then(Pl,pc)}mc((ja=ja.apply(ta,Ln||[])).next())})}function __generator(ta,Ln){var Ta={label:0,sent:function(){if(Fa[0]&1)throw Fa[1];return Fa[1]},trys:[],ops:[]},ja,La,Fa,wl=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return wl.next=Pl(0),wl.throw=Pl(1),wl.return=Pl(2),typeof Symbol=="function"&&(wl[Symbol.iterator]=function(){return this}),wl;function Pl(mc){return function(gc){return pc([mc,gc])}}function pc(mc){if(ja)throw new TypeError("Generator is already executing.");for(;wl&&(wl=0,mc[0]&&(Ta=0)),Ta;)try{if(ja=1,La&&(Fa=mc[0]&2?La.return:mc[0]?La.throw||((Fa=La.return)&&Fa.call(La),0):La.next)&&!(Fa=Fa.call(La,mc[1])).done)return Fa;switch(La=0,Fa&&(mc=[mc[0]&2,Fa.value]),mc[0]){case 0:case 1:Fa=mc;break;case 4:return Ta.label++,{value:mc[1],done:!1};case 5:Ta.label++,La=mc[1],mc=[0];continue;case 7:mc=Ta.ops.pop(),Ta.trys.pop();continue;default:if(Fa=Ta.trys,!(Fa=Fa.length>0&&Fa[Fa.length-1])&&(mc[0]===6||mc[0]===2)){Ta=0;continue}if(mc[0]===3&&(!Fa||mc[1]>Fa[0]&&mc[1]<Fa[3])){Ta.label=mc[1];break}if(mc[0]===6&&Ta.label<Fa[1]){Ta.label=Fa[1],Fa=mc;break}if(Fa&&Ta.label<Fa[2]){Ta.label=Fa[2],Ta.ops.push(mc);break}Fa[2]&&Ta.ops.pop(),Ta.trys.pop();continue}mc=Ln.call(ta,Ta)}catch(gc){mc=[6,gc],La=0}finally{ja=Fa=0}if(mc[0]&5)throw mc[1];return{value:mc[0]?mc[1]:void 0,done:!0}}}function __spreadArray(ta,Ln,Ta){if(Ta||arguments.length===2)for(var ja=0,La=Ln.length,Fa;ja<La;ja++)(Fa||!(ja in Ln))&&(Fa||(Fa=Array.prototype.slice.call(Ln,0,ja)),Fa[ja]=Ln[ja]);return ta.concat(Fa||Array.prototype.slice.call(Ln))}typeof SuppressedError=="function"&&SuppressedError;var define_process_env_default$2={};let fromEnv,CognitoIdentityProviderClient,SignUpCommand,ConfirmSignUp,ResendConfirmationCodeCommand,ForgotPasswordCommand,ConfirmForgotPasswordCommand,AdminGetUserCommand,InitiateAuthCommand,AdminCreateUserCommand,AdminDisableUserCommand,AdminEnableUserCommand,AdminDeleteUserCommand,RespondToAuthChallengeCommand,AuthenticationDetails,CognitoUser,CognitoUserPool,CognitoUserSession,CognitoIdToken,CognitoAccessToken,CognitoRefreshToken;if(isNodeEnv$1){fromEnv=(await __vitePreload(()=>import("./index.browser-BMODMYhe.js"),__vite__mapDeps([38,29,39]))).fromEnv;const Ln=await __vitePreload(()=>import("./index-fMnzpK9a.js"),__vite__mapDeps([40,41,39,29,6,1,42,43,12,17,19,25,20,23,24,18,44,31,26,34,45,11,13,10,9]));CognitoIdentityProviderClient=Ln.CognitoIdentityProviderClient,SignUpCommand=Ln.SignUpCommand,ConfirmSignUp=Ln.ConfirmSignUpCommand,ResendConfirmationCodeCommand=Ln.ResendConfirmationCodeCommand,ForgotPasswordCommand=Ln.ForgotPasswordCommand,ConfirmForgotPasswordCommand=Ln.ConfirmForgotPasswordCommand,AdminGetUserCommand=Ln.AdminGetUserCommand,InitiateAuthCommand=Ln.InitiateAuthCommand,AdminCreateUserCommand=Ln.AdminCreateUserCommand,AdminDisableUserCommand=Ln.AdminDisableUserCommand,AdminEnableUserCommand=Ln.AdminEnableUserCommand,AdminDeleteUserCommand=Ln.AdminDeleteUserCommand,RespondToAuthChallengeCommand=Ln.RespondToAuthChallengeCommand;const Ta=await __vitePreload(()=>import("./index-BOLaQ9_Z.js"),__vite__mapDeps([46,6,11,12,13]));AuthenticationDetails=Ta.AuthenticationDetails,CognitoUser=Ta.CognitoUser,CognitoUserPool=Ta.CognitoUserPool,CognitoUserSession=Ta.CognitoUserSession,CognitoIdToken=Ta.CognitoIdToken,CognitoAccessToken=Ta.CognitoAccessToken,CognitoRefreshToken=Ta.CognitoRefreshToken}const defaultConfig$1=isNodeEnv$1?new Map().set("UserPoolId",define_process_env_default$2.COGNITO_USER_POOL_ID).set("ClientId",define_process_env_default$2.COGNITO_CLIENT_ID):new Map;function handleCognitoError(ta,Ln){var Ta;const ja=sanitizeErrorMessage(ta.message||"");switch(logger$3.error(`Cognito error in ${Ln}: ${ta.name} - ${ja}`,{errorName:ta.name,errorCode:ta.code,context:Ln,statusCode:(Ta=ta.$metadata)===null||Ta===void 0?void 0:Ta.httpStatusCode}),ta.name){case"UserNotFoundException":throw logger$3.debug(`User not found in context: ${Ln}`),new UserNotFoundError$1("User account not found. Please check your email or sign up.");case"NotAuthorizedException":throw ta.message&&ta.message.includes("password")?(logger$3.debug(`Invalid password attempt in context: ${Ln}`),new UnauthorisedError$1("Invalid password. Please try again.")):ta.message&&ta.message.includes("not confirmed")?(logger$3.debug(`User not confirmed in context: ${Ln}`),new UserNotConfirmedError$1):(logger$3.debug(`Authentication failed in context: ${Ln}`),new UnauthorisedError$1("Authentication failed. Please check your credentials."));case"UserNotConfirmedException":throw logger$3.debug(`User not confirmed in context: ${Ln}`),new UserNotConfirmedError$1;case"PasswordResetRequiredException":throw logger$3.debug(`Password reset required in context: ${Ln}`),new PasswordResetRequiredError$1;case"TooManyRequestsException":throw logger$3.warn(`Rate limit exceeded in context: ${Ln}`),new TooManyRequestsError$1;case"TooManyFailedAttemptsException":throw logger$3.warn(`Too many failed attempts in context: ${Ln}`),new TooManyRequestsError$1("Too many failed login attempts. Please try again later.");case"InvalidParameterException":throw logger$3.debug(`Invalid parameters in context: ${Ln}`),new InvalidParameterError$1(sanitizeErrorMessage(ta.message)||"Invalid parameters provided");case"ExpiredCodeException":throw logger$3.debug(`Expired code in context: ${Ln}`),new ExpiredCodeError$1;case"CodeMismatchException":throw logger$3.debug(`Code mismatch in context: ${Ln}`),new CodeMismatchError$1;case"UsernameExistsException":throw logger$3.debug(`Username exists in context: ${Ln}`),new BadRequestError$4("An account with this email already exists.");case"InvalidPasswordException":throw logger$3.debug(`Invalid password format in context: ${Ln}`),new BadRequestError$4("Password does not meet requirements. It must be at least 8 characters long and contain uppercase, lowercase, numbers, and special characters.");case"LimitExceededException":throw logger$3.warn(`Service limit exceeded in context: ${Ln}`),new TooManyRequestsError$1("Service limit exceeded. Please try again later.");case"InternalErrorException":throw logger$3.error(`Internal Cognito error in context: ${Ln}`),new Error("Authentication service is temporarily unavailable. Please try again later.");case"ResourceNotFoundException":throw logger$3.error(`Resource not found in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");case"AliasExistsException":throw logger$3.debug(`Alias exists in context: ${Ln}`),new BadRequestError$4("An account with this email already exists.");case"InvalidEmailRoleAccessPolicyException":throw logger$3.error(`Invalid email role access policy in context: ${Ln}`),new Error("Email service configuration error. Please contact support.");case"UserLambdaValidationException":throw logger$3.error(`User lambda validation error in context: ${Ln}`),new BadRequestError$4("User validation failed. Please check your input and try again.");case"UnsupportedUserStateException":throw logger$3.debug(`Unsupported user state in context: ${Ln}`),new UserNotConfirmedError$1("User account is in an unsupported state. Please contact support.");case"MFAMethodNotFoundException":throw logger$3.debug(`MFA method not found in context: ${Ln}`),new BadRequestError$4("MFA method not found. Please set up MFA and try again.");case"CodeDeliveryFailureException":throw logger$3.error(`Code delivery failure in context: ${Ln}`),new Error("Unable to deliver verification code. Please try again later.");case"DuplicateProviderException":throw logger$3.error(`Duplicate provider in context: ${Ln}`),new BadRequestError$4("Authentication provider already exists.");case"EnableSoftwareTokenMFAException":throw logger$3.debug(`Software token MFA required in context: ${Ln}`),new BadRequestError$4("Software token MFA setup required.");case"ForbiddenException":throw logger$3.warn(`Forbidden access in context: ${Ln}`),new UnauthorisedError$1("Access forbidden. Please check your permissions.");case"GroupExistsException":throw logger$3.debug(`Group exists in context: ${Ln}`),new BadRequestError$4("Group already exists.");case"InvalidLambdaResponseException":throw logger$3.error(`Invalid lambda response in context: ${Ln}`),new Error("Authentication service error. Please try again later.");case"InvalidOAuthFlowException":throw logger$3.error(`Invalid OAuth flow in context: ${Ln}`),new BadRequestError$4("Invalid OAuth flow. Please try again.");case"InvalidSmsRoleAccessPolicyException":throw logger$3.error(`Invalid SMS role access policy in context: ${Ln}`),new Error("SMS service configuration error. Please contact support.");case"InvalidSmsRoleTrustRelationshipException":throw logger$3.error(`Invalid SMS role trust relationship in context: ${Ln}`),new Error("SMS service configuration error. Please contact support.");case"InvalidUserPoolConfigurationException":throw logger$3.error(`Invalid user pool configuration in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");case"PreconditionNotMetException":throw logger$3.debug(`Precondition not met in context: ${Ln}`),new BadRequestError$4("Precondition not met. Please check your request and try again.");case"ScopeDoesNotExistException":throw logger$3.error(`Scope does not exist in context: ${Ln}`),new BadRequestError$4("Invalid scope. Please check your request.");case"UnexpectedLambdaException":throw logger$3.error(`Unexpected lambda exception in context: ${Ln}`),new Error("Authentication service error. Please try again later.");case"UserImportInProgressException":throw logger$3.warn(`User import in progress in context: ${Ln}`),new TooManyRequestsError$1("User import in progress. Please try again later.");case"UserPoolTaggingException":throw logger$3.error(`User pool tagging exception in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");default:throw logger$3.error(`Unhandled Cognito error: ${ta.name}`,{errorName:ta.name,errorCode:ta.code,context:Ln}),new Error(`Authentication error: ${sanitizeErrorMessage(ta.message)||"An unexpected error occurred"}`)}}function sanitizeErrorMessage(ta){return ta?ta.replace(/password/gi,"[REDACTED]").replace(/token/gi,"[REDACTED]").replace(/secret/gi,"[REDACTED]").replace(/key/gi,"[REDACTED]").replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,"[EMAIL_REDACTED]").replace(/\b[A-Fa-f0-9]{32,}\b/g,"[TOKEN_REDACTED]").replace(/\b\d{4,}\b/g,"[NUMBER_REDACTED]"):""}class CognitoAuth{constructor(Ln){this.config=Ln||defaultConfig$1;const Ta=this.config.get("UserPoolId");Ta&&(this.userPool=new CognitoUserPool({UserPoolId:Ta,ClientId:this.fetchClientId()}))}fetchUserPoolId(){return this.fetchConfig("UserPoolId")}fetchClientId(){return this.fetchConfig("ClientId")}fetchConfig(Ln){const Ta=this.config.get(Ln);if(Ta)return Ta;throw new Error(`${Ln} is not set`)}async signUp(Ln,Ta,ja,La,Fa,wl,Pl){const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),mc=[{Name:"email",Value:ja},{Name:"name",Value:ja},{Name:"given_name",Value:Ln},{Name:"family_name",Value:Ta}];Fa&&Fa.forEach((Wd,kf)=>{mc.push({Name:kf,Value:Wd})});const gc={ClientId:this.config.get("ClientId"),Username:ja,Password:La,UserAttributes:mc,ValidationData:mc},Vd=new SignUpCommand(gc);try{logger$3.debug(`Attempting signup for user: ${ja}`);const Wd=await pc.send(Vd);if(Wd.$metadata.httpStatusCode==200){logger$3.info(`Signup successful for user: ${ja}`);const kf=await ensureUser(ja,Ln,Ta,wl,"Active"),Pf={username:ja,firstName:Ln,lastName:Ta,id:kf.id,systemUserInfo:Wd.UserSub};Pl(Pf)}else throw logger$3.error(`Signup failed with HTTP status ${Wd.$metadata.httpStatusCode}`,{username:ja,statusCode:Wd.$metadata.httpStatusCode}),new BadRequestError$4(`Signup failed with status ${Wd.$metadata.httpStatusCode}`)}catch(Wd){if(Wd instanceof BadRequestError$4)throw Wd;logger$3.error(`Signup error for user ${ja}:`,{errorName:Wd.name,errorMessage:sanitizeErrorMessage(Wd.message)}),handleCognitoError(Wd,"signUp")}}async confirmSignup(Ln,Ta,ja){try{const La=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),Fa=new ConfirmSignUp({ClientId:this.config.get("ClientId"),Username:Ln,ConfirmationCode:Ta});await La.send(Fa)}catch(La){logger$3.error(`Failed to confirm signup: ${La.message}`),handleCognitoError(La,"confirmSignup")}}async resendConfirmationCode(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new ResendConfirmationCodeCommand({ClientId:this.config.get("ClientId"),Username:Ln});await ja.send(La)}catch(ja){logger$3.error(`Failed to resend confirmation code: ${ja.message}`),handleCognitoError(ja,"resendConfirmationCode")}}async forgotPassword(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new ForgotPasswordCommand({ClientId:this.fetchClientId(),Username:Ln});await ja.send(La)}catch(ja){logger$3.error(`Forgot password failed for ${Ln}: ${sanitizeErrorMessage(ja.message)}`),handleCognitoError(ja,"forgotPassword")}}async confirmForgotPassword(Ln,Ta,ja,La){try{const Fa=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),wl=new ConfirmForgotPasswordCommand({ClientId:this.fetchClientId(),Username:Ln,ConfirmationCode:Ta,Password:ja});await Fa.send(wl)}catch(Fa){logger$3.error(`Confirm forgot password failed for ${Ln}: ${sanitizeErrorMessage(Fa.message)}`),handleCognitoError(Fa,"confirmForgotPassword")}}async login(Ln,Ta,ja,La){if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID){const wl=new CognitoUser({Username:Ln,Pool:this.fetchUserPool()}),Pl=new AuthenticationDetails({Username:Ln,Password:Ta});let pc,mc;for(wl.authenticateUser(Pl,{onSuccess:gc=>{pc=gc},onFailure:gc=>{logger$3.debug(`Cognito authentication failed for user ${Ln}:`,{errorName:gc.name,errorMessage:sanitizeErrorMessage(gc.message)}),mc=gc},mfaRequired:(gc,Vd)=>{logger$3.info(`MFA required for user ${Ln}: ${gc}`),mc=new Error("MFA authentication required")},newPasswordRequired:(gc,Vd)=>{logger$3.info(`New password required for user ${Ln}`),mc=new PasswordResetRequiredError$1("New password required. Please reset your password.")}});pc===void 0&&mc===void 0;)await sleepMilliseconds$1(100);if(mc){if(mc instanceof PasswordResetRequiredError$1)throw mc;logger$3.error(`Login failed for user ${Ln}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),handleCognitoError(mc,"login")}if(pc){const gc=pc.getIdToken(),Vd=gc.getJwtToken(),Wd=gc.decodePayload(),kf=Wd.given_name||Wd.name||"",Pf=Wd.family_name||"",Nf=Wd["cognito:groups"];let Eh=await findUserByEmail(Ln,ja);Eh||(Eh=await ensureUser(Ln,kf,Pf,ja));const Em=Eh.lookup("id");Nf&&await ensureUserRoles(Em,Nf,ja);const qg=pc.getAccessToken().getJwtToken(),Ug=pc.getRefreshToken().getToken(),U_={sessionId:(await ensureUserSession(Em,Vd,qg,Ug,ja)).lookup("id"),userId:Em,authToken:Vd,idToken:Vd,accessToken:qg,refreshToken:Ug,systemSesionInfo:pc};La(U_)}else throw logger$3.error(`Login failed for ${Ln} - no result received`),new UnauthorisedError$1("Login failed. Please try again.")}else{let wl=await findUserByEmail(Ln,ja);wl||(logger$3.warn(`User ${Ln} not found in local store`),wl=await ensureUser(Ln,"","",ja));const Pl=new CognitoUser({Username:Ln,Pool:this.fetchUserPool()}),pc=new AuthenticationDetails({Username:Ln,Password:Ta});let mc,gc;for(Pl.authenticateUser(pc,{onSuccess:Vd=>{mc=Vd},onFailure:Vd=>{logger$3.debug(`Cognito authentication failed for user ${Ln}:`,{errorName:Vd.name,errorMessage:sanitizeErrorMessage(Vd.message)}),gc=Vd},mfaRequired:(Vd,Wd)=>{logger$3.info(`MFA required for user ${Ln}: ${Vd}`),gc=new Error("MFA authentication required")},newPasswordRequired:(Vd,Wd)=>{logger$3.info(`New password required for user ${Ln}`),gc=new PasswordResetRequiredError$1("New password required. Please reset your password.")}});mc===void 0&&gc===void 0;)await sleepMilliseconds$1(100);if(gc){if(gc instanceof PasswordResetRequiredError$1)throw gc;logger$3.error(`Login failed for user ${Ln}:`,{errorName:gc.name,errorMessage:sanitizeErrorMessage(gc.message)}),handleCognitoError(gc,"login")}if(mc){const Vd=wl.lookup("id"),Wd=mc.getIdToken().getJwtToken(),kf=mc.getAccessToken().getJwtToken(),Pf=mc.getRefreshToken().getToken(),Eh={sessionId:(await ensureUserSession(Vd,Wd,kf,Pf,ja)).lookup("id"),userId:Vd,authToken:Wd,idToken:Wd,accessToken:kf,refreshToken:Pf,systemSesionInfo:mc};La(Eh)}else throw logger$3.error(`Login failed for ${Ln} - no result received`),new UnauthorisedError$1("Login failed. Please try again.")}}async logout(Ln,Ta,ja){try{const La=await findUser(Ln.userId,Ta);if(!La){logger$3.warn(`User ${Ln.userId} not found during logout`),ja&&ja(!0);return}const Fa=new CognitoUser({Username:La.lookup("email"),Pool:this.fetchUserPool()});let wl=!1,Pl;const pc=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:Ln.idToken}),AccessToken:new CognitoAccessToken({AccessToken:Ln.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:Ln.refreshToken})});for(Fa.setSignInUserSession(pc),Fa.globalSignOut({onSuccess:function(){wl=!0},onFailure:function(mc){wl=!0,logger$3.error(`Cognito signOut error for user ${Ln.userId}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),Pl=mc}});!wl;)await sleepMilliseconds$1(100);Pl&&logger$3.error(`Error during Cognito logout for user ${Ln.userId}: ${Pl.message}`),logger$3.debug(`Successfully logged out user ${Ln.userId}`),ja&&ja(!0)}catch(La){throw logger$3.error(`Logout failed for user ${Ln.userId}: ${La.message}`),ja&&ja(!1),La}}async changePassword(Ln,Ta,ja,La){const Fa=await findUser(Ln.userId,La);if(!Fa)return logger$3.warn(`User ${Ln.userId} not found for password-change`),!1;const wl=Fa.lookup("email"),Pl=new CognitoUser({Username:wl,Pool:this.fetchUserPool()}),pc=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:Ln.idToken}),AccessToken:new CognitoAccessToken({AccessToken:Ln.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:Ln.refreshToken})});Pl.setSignInUserSession(pc);let mc=!1,gc;for(Pl.changePassword(ja,Ta,(Vd,Wd)=>{Vd?(mc=!0,gc=Vd):mc=!0});!mc;)await sleepMilliseconds$1(100);return gc?(logger$3.warn(`Failed to change the password for ${wl} - ${gc.message}`),!1):!0}fetchUserPool(){if(this.userPool)return this.userPool;throw new Error("UserPool not initialized")}async verifyToken(Ln){try{const ja=await CognitoJwtVerifier.create({userPoolId:this.fetchUserPoolId(),tokenUse:"id",clientId:this.fetchClientId()}).verify(Ln);logger$3.debug(`Decoded JWT for ${ja.email}`)}catch(Ta){throw logger$3.error("Token verification failed:",{errorName:Ta.name,errorMessage:sanitizeErrorMessage(Ta.message)}),Ta.message&&Ta.message.includes("expired")?new UnauthorisedError$1("Token has expired. Please login again."):Ta.message&&Ta.message.includes("invalid")?new UnauthorisedError$1("Invalid token format."):Ta.message&&Ta.message.includes("not before")?new UnauthorisedError$1("Token is not yet valid."):Ta.message&&Ta.message.includes("audience")?new UnauthorisedError$1("Token audience mismatch."):new UnauthorisedError$1(`Token verification failed: ${sanitizeErrorMessage(Ta.message)||"Invalid token"}`)}}async getUser(Ln,Ta){const ja=await findUser(Ln,Ta);if(!ja)throw new UserNotFoundError$1(`User ${Ln} not found in local database`);const La=ja.lookup("email"),Fa=ja.lookup("firstName"),wl=ja.lookup("lastName");if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID&&La)try{const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),mc=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:La}),gc=await pc.send(mc);return{id:Ln,username:La,firstName:Fa,lastName:wl,systemUserInfo:{localUser:ja,cognitoData:{userAttributes:gc.UserAttributes,userCreateDate:gc.UserCreateDate,userLastModifiedDate:gc.UserLastModifiedDate,userStatus:gc.UserStatus,enabled:gc.Enabled,preferredMfaSetting:gc.PreferredMfaSetting,userMFASettingList:gc.UserMFASettingList}}}}catch(pc){return logger$3.warn(`Failed to get Cognito user info for ${La}, using local data only:`,{errorName:pc.name,errorMessage:sanitizeErrorMessage(pc.message)}),{id:Ln,username:La,firstName:Fa,lastName:wl,systemUserInfo:ja}}else return{id:Ln,username:La||Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}async getUserByEmail(Ln,Ta){const ja=await findUserByEmail(Ln,Ta);if(!ja)throw new UserNotFoundError$1(`User with email ${Ln} not found in local database`);const La=ja.lookup("id"),Fa=ja.lookup("firstName"),wl=ja.lookup("lastName");if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID)try{const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),mc=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),ClientId:this.fetchClientId(),Username:Ln}),gc=await pc.send(mc);return{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:{localUser:ja,cognitoData:{userAttributes:gc.UserAttributes,userCreateDate:gc.UserCreateDate,userLastModifiedDate:gc.UserLastModifiedDate,userStatus:gc.UserStatus,enabled:gc.Enabled,preferredMfaSetting:gc.PreferredMfaSetting,userMFASettingList:gc.UserMFASettingList}}}}catch(pc){return console.log(`Failed to get Cognito user info for email ${Ln}, using local data only:`,{errorName:pc.name,errorMessage:sanitizeErrorMessage(pc.message)}),{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}else return{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}async refreshToken(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.fetchClientId(),AuthParameters:{REFRESH_TOKEN:Ln}}),Fa=await ja.send(La);if(!Fa.AuthenticationResult)throw new UnauthorisedError$1("Token refresh failed");const wl=Fa.AuthenticationResult.IdToken,Pl=Fa.AuthenticationResult.AccessToken,pc=Fa.AuthenticationResult.RefreshToken||Ln,gc=JSON.parse(atob(wl.split(".")[1])).email;let Vd=await findUserByEmail(gc,Ta);Vd||(Vd=await ensureUser(gc,"","",Ta));const Wd=Vd.lookup("id");return{sessionId:(await ensureUserSession(Wd,wl,Pl,pc,Ta)).lookup("id"),userId:Wd,authToken:wl,idToken:wl,accessToken:Pl,refreshToken:pc,systemSesionInfo:Fa.AuthenticationResult}}catch(ja){throw logger$3.error(`Refresh token operation failed: ${ja.message}`),ja.name==="NotAuthorizedException"?new UnauthorisedError$1("Invalid or expired refresh token"):(handleCognitoError(ja,"refreshToken"),ja)}}async inviteUser(Ln,Ta,ja,La,Fa,wl,Pl){var pc;try{const mc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),gc=[{Name:"email",Value:Ln},{Name:"email_verified",Value:"true"},{Name:"given_name",Value:Ta},{Name:"family_name",Value:ja}];La&&La.forEach((Pf,Nf)=>{gc.push({Name:Nf,Value:String(Pf)})});let Vd=!1;try{const Pf=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});await mc.send(Pf),Vd=!0,logger$3.debug(`User ${Ln} already exists, will resend invitation`)}catch(Pf){if(Pf.name!=="UserNotFoundException")throw Pf;logger$3.debug(`User ${Ln} does not exist, will create new user`)}const Wd=new AdminCreateUserCommand(Object.assign({UserPoolId:this.fetchUserPoolId(),Username:Ln,UserAttributes:gc,DesiredDeliveryMediums:["EMAIL"],TemporaryPassword:generateUrlSafePassword$1()},Vd?{MessageAction:"RESEND"}:{}));logger$3.debug(`Attempting to invite user: ${Ln}`);const kf=await mc.send(Wd);if(kf.$metadata.httpStatusCode===200){logger$3.info(`User invitation successful for: ${Ln}`);const Nf=(await ensureUser(Ln,Ta,ja,wl,"Invited")).lookup("id");await ensureUserRoles(Nf,[Fa||"user"],wl);const Eh={email:Ln,firstName:Ta,lastName:ja,invitationId:(pc=kf.User)===null||pc===void 0?void 0:pc.Username,systemInvitationInfo:kf};Pl(Eh)}else throw logger$3.error(`User invitation failed with HTTP status ${kf.$metadata.httpStatusCode}`,{email:Ln,statusCode:kf.$metadata.httpStatusCode}),new BadRequestError$4(`User invitation failed with status ${kf.$metadata.httpStatusCode}`)}catch(mc){if(mc instanceof BadRequestError$4)throw mc;logger$3.error(`User invitation error for ${Ln}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),handleCognitoError(mc,"inviteUser")}}async resendInvitation(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"});try{const wl=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});await ja.send(wl)}catch(wl){throw wl.name==="UserNotFoundException"?new UserNotFoundError$1(`User ${Ln} not found. Cannot resend invitation.`):wl}const La=new AdminCreateUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln,DesiredDeliveryMediums:["EMAIL"],MessageAction:"RESEND"});logger$3.debug(`Attempting to resend invitation for user: ${Ln}`);const Fa=await ja.send(La);if(Fa.$metadata.httpStatusCode===200)logger$3.info(`Invitation resent successfully for: ${Ln}`);else throw logger$3.error(`Failed to resend invitation with HTTP status ${Fa.$metadata.httpStatusCode}`,{email:Ln,statusCode:Fa.$metadata.httpStatusCode}),new BadRequestError$4(`Failed to resend invitation with status ${Fa.$metadata.httpStatusCode}`)}catch(ja){if(ja instanceof BadRequestError$4||ja instanceof UserNotFoundError$1)throw ja;logger$3.error(`Resend invitation error for ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"resendInvitation")}}async acceptInvitation(Ln,Ta,ja,La){try{const Fa=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),wl=new InitiateAuthCommand({AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.fetchClientId(),AuthParameters:{USERNAME:Ln,PASSWORD:Ta}}),Pl=await Fa.send(wl);if(Pl.ChallengeName==="NEW_PASSWORD_REQUIRED"){const pc=new RespondToAuthChallengeCommand({ClientId:this.fetchClientId(),ChallengeName:"NEW_PASSWORD_REQUIRED",Session:Pl.Session,ChallengeResponses:{USERNAME:Ln,NEW_PASSWORD:ja}});await Fa.send(pc),logger$3.info(`User invitation accepted successfully for: ${Ln}`)}else throw new Error(`Unexpected challenge: ${Pl.ChallengeName}`)}catch(Fa){logger$3.error(`Accept invitation failed for ${Ln}: ${sanitizeErrorMessage(Fa.message)}`),handleCognitoError(Fa,"acceptInvitation")}}async callback(Ln,Ta,ja){try{if(!isNodeEnv$1)throw new Error("Callback authentication is only supported in Node.js environment");const La=this.fetchConfig("ClientId"),Fa=define_process_env_default$2.AWS_REGION||"us-east-1",wl=define_process_env_default$2.COGNITO_REDIRECT_URI||"http://localhost:3000/auth/callback",pc=`https://${define_process_env_default$2.COGNITO_HOSTED_DOMAIN}.auth.${Fa}.amazoncognito.com/oauth2/token`,mc=new URLSearchParams({grant_type:"authorization_code",client_id:La,code:Ln,redirect_uri:wl});logger$3.debug("Exchanging authorization code for tokens via OAuth2 endpoint"),console.log("te",pc,mc.toString());const gc=await fetch(pc,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:mc.toString()});if(!gc.ok){const tj=await gc.text();throw new Error(`Token exchange failed: ${gc.status} ${tj}`)}const Vd=await gc.json();if(!Vd.access_token||!Vd.id_token||!Vd.refresh_token)throw new Error("Missing required tokens in response");const{access_token:Wd,id_token:kf,refresh_token:Pf}=Vd,Nf=this.decodeJwtPayload(kf),Eh=Nf.email,Em=Nf.given_name||Nf.name||"",qg=Nf.family_name||"",Ug=Nf["cognito:groups"];if(!Eh)throw new Error("Email not found in ID attributes");let Bg=await findUserByEmail(Eh,Ta);Bg||(Bg=await ensureUser(Eh,Em,qg,Ta));const U_=Bg.lookup("id");Ug&&await ensureUserRoles(U_,Ug,Ta);const VC={sessionId:(await ensureUserSession(U_,kf,Wd,Pf,Ta)).lookup("id"),userId:U_,authToken:kf,idToken:kf,accessToken:Wd,refreshToken:Pf,systemSesionInfo:Vd};logger$3.info(`Auth callback successful for user ${Eh}`),ja(VC)}catch(La){console.log(La),logger$3.error(`Auth callback failed: ${sanitizeErrorMessage(La.message)}`),handleCognitoError(La,"callback")}}decodeJwtPayload(Ln){try{const ja=Ln.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),La=decodeURIComponent(atob(ja).split("").map(Fa=>"%"+("00"+Fa.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(La)}catch(Ta){throw logger$3.error(`Failed to decode JWT payload: ${Ta}`),new Error("Invalid JWT token")}}async deleteUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminDeleteUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to delete user: ${Ln}`),await ja.send(La),logger$3.info(`User deleted successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to delete user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"deleteUser")}}async disableUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminDisableUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to disable user: ${Ln}`),await ja.send(La),logger$3.info(`User disabled successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to disable user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"disableUser")}}async enableUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminEnableUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to enable user: ${Ln}`),await ja.send(La),logger$3.info(`User enabled successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to enable user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"enableUser")}}}const CoreAuthModuleName=makeCoreModuleName$1("auth"),auth=`module ${CoreAuthModuleName}
|
|
30423
|
+
${ta}`)}async function preprocessStep(ta,Ln){if(ta.startsWith("{")){const ja=(await parseStatement$1(ta)).pattern.crudMap;if(ja){Ln.resetTemplateMappings();const La=ja.name;return ja.body&&ja.body.attributes.forEach(Fa=>{var wl;const Pl=(wl=Fa.value.$cstNode)===null||wl===void 0?void 0:wl.text;Pl&&Ln.setTemplateMapping(Fa.name,Pl)}),La}else throw new Error(`Invalid step - ${ta}`)}else return ta}async function handleOpenApiEvent(ta,Ln){const Ta=await invokeOpenApiEvent(ta.moduleName,ta.name,ta.attributesAsObject());Ln.setLastResult(Ta)}async function evaluateUpsert(ta,Ln){Ln.setInUpsertMode(!0);try{await evaluateCrudMap(ta,Ln)}finally{Ln.setInUpsertMode(!1)}}async function evaluateForEach(ta,Ln){const Ta=ta.var;await evaluatePattern(ta.src,Ln);const ja=Ln.getLastResult();if(ja instanceof Array&&ja.length>0){const La=Environment.from(Ln),Fa=new Array;for(let wl=0;wl<ja.length;++wl)La.bind(Ta,ja[wl]),await evaluateStatements(ta.statements,La),Fa.push(La.getLastResult());Ln.setLastResult(Fa)}else Ln.setLastResult(EmptyResult)}async function evaluateIf(ta,Ln){await evaluateExpression(ta.cond,Ln),Ln.getLastResult()?await evaluateStatements(ta.statements,Ln):ta.else!==void 0&&await evaluateStatements(ta.else.statements,Ln)}async function evaluateDeleteHelper(ta,Ln,Ta){const ja=Environment.from(Ta).setInDeleteMode(!0);await evaluatePattern(ta,ja),await maybeDeleteQueriedInstances(ja,Ta,Ln)}async function maybeDeleteQueriedInstances(ta,Ln,Ta=!1){const ja=ta.getLastResult();let La=Resolver.Default;if(ja instanceof Array)if(ja.length>0){La=await getResolverForPath(ja[0].name,ja[0].moduleName,ta);const Fa=new Array;for(let wl=0;wl<ja.length;++wl){await runPreDeleteEvents(ja[wl],Ln);const Pl=await La.deleteInstance(ja[wl],Ta);await runPostDeleteEvents(ja[wl],Ln),Fa.push(Pl)}ta.setLastResult(Fa)}else ta.setLastResult(ja);else{La=await getResolverForPath(ja.name,ja.moduleName,ta),await runPreDeleteEvents(ja,Ln);const Fa=await La.deleteInstance(ja,Ta);await runPostDeleteEvents(ja,Ln),ta.setLastResult(Fa)}Ln.setLastResult(ta.getLastResult())}async function evaluateDelete(ta,Ln){await evaluateDeleteHelper(ta.pattern,!1,Ln)}async function evaluatePurge(ta,Ln){await evaluateDeleteHelper(ta.pattern,!0,Ln)}async function evaluateExpression(ta,Ln){let Ta=EmptyResult;if(isBinExpr$1(ta)){await evaluateExpression(ta.e1,Ln);const ja=Ln.getLastResult();if(ta.op=="or"){if(ja)return;await evaluateExpression(ta.e2,Ln);return}else if(ta.op=="and"){if(!ja)return;await evaluateExpression(ta.e2,Ln);return}if(ja==null){Ln.setLastResult(void 0);return}await evaluateExpression(ta.e2,Ln);const La=Ln.getLastResult();if(La==null){Ln.setLastResult(void 0);return}switch(ta.op){case"+":Ta=ja+La;break;case"-":Ta=ja-La;break;case"*":Ta=ja*La;break;case"/":Ta=ja/La;break;case"==":Ta=ja==La;break;case"<":Ta=ja<La;break;case">":Ta=ja>La;break;case"<=":Ta=ja<=La;break;case">=":Ta=ja>=La;break;case"<>":case"!=":Ta=ja!=La;break;case"like":Ta=ja.startsWith(La);break;case"in":Ta=La.find(Fa=>{});break;default:throw new Error(`Unrecognized binary operator: ${ta.op}`)}}else if(isNegExpr$1(ta))await evaluateExpression(ta.ne,Ln),Ta=-1*Ln.getLastResult();else if(isGroup$2(ta))await evaluateExpression(ta.ge,Ln),Ta=Ln.getLastResult();else if(isLiteral$1(ta)){await evaluateLiteral(ta,Ln);return}else isNotExpr$1(ta)&&(await evaluateExpression(ta.ne,Ln),Ta=!Ln.getLastResult());Ln.setLastResult(Ta)}async function getRef(ta,Ln,Ta){return Instance$1.IsInstance(Ln)?Ln.lookup(ta):Ln instanceof Map?Ln.get(ta):Ln instanceof Object?Ln[ta]:isPath$1(Ln)?await getRef(ta,await dereferencePath(Ln,Ta),Ta):void 0}async function followReference(ta,Ln){const Ta=splitRefs$1(Ln);let ja=EmptyResult,La=ta;for(let Fa=0;Fa<Ta.length;++Fa){const wl=Ta[Fa],Pl=await getRef(wl,La,ta);if(Pl===void 0)return EmptyResult;ja=Pl,La=ja}return ja}async function dereferencePath(ta,Ln){const Ta=fqNameFromPath$1(ta);if(Ta===void 0)throw new Error(`Failed to deduce entry-name from path - ${ta}`);const ja=new Environment("path-deref",Ln);await parseAndEvaluateStatement(`{${Ta} {${PathAttributeNameQuery$1} "${ta}"}}`,Ln.getAuthContextUserId(),ja);const La=ja.getLastResult();if(La&&La instanceof Array&&La.length>0)return La[0]}async function applyFn(ta,Ln,Ta){const ja=ta.name;if(ja!==void 0){let La=null;if(ta.args!==void 0){La=new Array;for(let wl=0;wl<ta.args.length;++wl){const Pl=ta.args[wl];isLiteral$1(Pl)?await evaluateLiteral(Pl,Ln):await evaluateExpression(Pl,Ln),La.push(Ln.getLastResult())}La.push(Ln)}const Fa=await invokeModuleFn(ja,La,Ta);Ln.setLastResult(Fa)}}async function realizeArray(ta,Ln){const Ta=new Array;for(let ja=0;ja<ta.vals.length;++ja)await evaluateStatement(ta.vals[ja],Ln),Ta.push(Ln.getLastResult());Ln.setLastResult(Ta)}async function realizeMap(ta,Ln){const Ta=new Map;for(let ja=0;ja<ta.entries.length;++ja){const La=ta.entries[ja],Fa=getMapKey(La.key);await evaluateExpression(La.value,Ln),Ta.set(Fa,Ln.getLastResult())}Ln.setLastResult(Object.fromEntries(Ta.entries()))}async function callPostEventOnSubscription(ta,Ln,Ta){const ja=new Environment("onSubs.env");return await runPrePostEvents(ta,!1,Ln,ja),ja.getLastResult()}async function runPrePostEvents(ta,Ln,Ta,ja){const La=Ln?Ta.record.getPreTriggerInfo(ta):Ta.record.getPostTriggerInfo(ta);if(La){const Fa=nameToPath$1(La.eventName),wl=Fa.hasModule()?Fa.getModuleName():Ta.record.moduleName,Pl=makeInstance$1(wl,Fa.getEntryName(),newInstanceAttributes$1().set(Ta.record.name,Ta)),pc=ja.getActiveAuthContext();pc&&Pl.setAuthContext(pc);const mc=`${Ln?"Pre":"Post"}-${CrudType$1[ta]} ${Ta.record.getFqName()}`,gc=Wd=>{logger$3.debug(`${mc}: ${Wd}`)},Vd=Wd=>{throw ja.hasHandlers()?Wd:new Error(`${mc}: ${Wd}`)};La.async?evaluate$1(Pl,gc,bindAliasesForPrePost(ja,Ta,mc)).catch(Vd):await evaluate$1(Pl,gc,bindAliasesForPrePost(ja,Ta,mc)).catch(Vd)}}function bindAliasesForPrePost(ta,Ln,Ta){const ja=new Environment(`${Ta}.env`,ta),La=Ln.getFqName();return ja.bind("this",Ln),ja.bind(La,Ln),ja.bind(Ln.name,Ln),ja}async function runPreCreateEvents(ta,Ln){await runPrePostEvents(CrudType$1.CREATE,!0,ta,Ln)}async function runPostCreateEvents(ta,Ln){ta.requireAudit()&&await addCreateAudit(ta.getPath(),Ln),await runPrePostEvents(CrudType$1.CREATE,!1,ta,Ln)}async function runPreUpdateEvents(ta,Ln){await runPrePostEvents(CrudType$1.UPDATE,!0,ta,Ln)}async function runPostUpdateEvents(ta,Ln,Ta){ta.requireAudit()&&await addUpdateAudit(ta.getPath(),Ln,Ta),await runPrePostEvents(CrudType$1.UPDATE,!1,ta,Ta)}async function runPreDeleteEvents(ta,Ln){await runPrePostEvents(CrudType$1.DELETE,!0,ta,Ln)}async function runPostDeleteEvents(ta,Ln){ta.requireAudit()&&await addDeleteAudit(ta.getPath(),ta,Ln),await runPrePostEvents(CrudType$1.DELETE,!1,ta,Ln)}const interpreter=Object.freeze(Object.defineProperty({__proto__:null,DocEventName,Environment,GlobalEnvironment,PatternHandler,callPostEventOnSubscription,evaluate:evaluate$1,evaluateAsEvent,evaluateExpression,evaluatePattern,evaluateStatement,evaluateStatements,handleAgentInvocation,handleOpenApiEvent,makeEventEvaluator,maybeBindStatementResultToAlias,maybeDeleteQueriedInstances,parseAndEvaluateStatement,restartFlow,runPostCreateEvents,runPostDeleteEvents,runPostUpdateEvents},Symbol.toStringTag,{value:"Module"}));class JwtBaseError extends Error{}class FailedAssertionError extends JwtBaseError{constructor(Ln,Ta,ja){super(Ln),this.failedAssertion={actual:Ta,expected:ja}}}class JwtParseError extends JwtBaseError{constructor(Ln,Ta){const ja=Ta!=null?`${Ln}: ${Ta}`:Ln;super(ja)}}class ParameterValidationError extends JwtBaseError{}class JwtInvalidSignatureError extends JwtBaseError{}class JwtInvalidSignatureAlgorithmError extends FailedAssertionError{}class JwtInvalidClaimError extends FailedAssertionError{withRawJwt({header:Ln,payload:Ta}){return this.rawJwt={header:Ln,payload:Ta},this}}class JwtInvalidIssuerError extends JwtInvalidClaimError{}class JwtInvalidAudienceError extends JwtInvalidClaimError{}class JwtInvalidScopeError extends JwtInvalidClaimError{}class JwtExpiredError extends JwtInvalidClaimError{}class JwtNotBeforeError extends JwtInvalidClaimError{}class CognitoJwtInvalidGroupError extends JwtInvalidClaimError{}class CognitoJwtInvalidTokenUseError extends JwtInvalidClaimError{}class CognitoJwtInvalidClientIdError extends JwtInvalidClaimError{}class JwksValidationError extends JwtBaseError{}class JwkValidationError extends JwtBaseError{}class JwtWithoutValidKidError extends JwtBaseError{}class KidNotFoundInJwksError extends JwtBaseError{}class WaitPeriodNotYetEndedJwkError extends JwtBaseError{}class JwksNotAvailableInCacheError extends JwtBaseError{}class JwkInvalidUseError extends FailedAssertionError{}class JwkInvalidKtyError extends FailedAssertionError{}class FetchError extends JwtBaseError{constructor(Ln,Ta){super(`Failed to fetch ${Ln}: ${Ta}`)}}class NonRetryableFetchError extends FetchError{}class NotSupportedError extends JwtBaseError{}var NamedCurvesWebCrypto;(function(ta){ta.ES256="P-256",ta.ES384="P-384",ta.ES512="P-521"})(NamedCurvesWebCrypto||(NamedCurvesWebCrypto={}));const nodeWebCompat={fetch:async(ta,Ln,Ta)=>{const ja=Number(Ln?.responseTimeout);if(ja){const Fa=new AbortController;setTimeout(()=>Fa.abort(new FetchError(ta,`Response time-out (after ${ja} ms.)`)),ja),Ln={signal:Fa.signal,...Ln}}const La=await fetch(ta,{...Ln,body:Ta}).catch(Fa=>{throw new FetchError(ta,Fa.message)});if(La.status!==200)throw new NonRetryableFetchError(ta,`Status code is ${La.status}, expected 200`);return La.arrayBuffer()},defaultFetchTimeouts:{response:3e3},transformJwkToKeyObjectSync:()=>{throw new NotSupportedError("Synchronously transforming a JWK into a key object is not supported in the browser")},transformJwkToKeyObjectAsync:(ta,Ln)=>{const Ta=ta.alg??Ln;if(!Ta)throw new JwtInvalidSignatureAlgorithmError("Missing alg on both JWK and JWT header",Ta);const ja=Ta.startsWith("RS")?{name:"RSASSA-PKCS1-v1_5",hash:`SHA-${Ta.slice(2)}`}:Ta.startsWith("ES")?{name:"ECDSA",namedCurve:NamedCurvesWebCrypto[Ta]}:ta.crv;return crypto.subtle.importKey("jwk",ta,ja,!1,["verify"]).then(La=>({key:La,jwk:ta}))},verifySignatureSync:()=>{throw new NotSupportedError("Synchronously verifying a JWT signature is not supported in the browser")},verifySignatureAsync:({jwsSigningInput:ta,keyObject:Ln,signature:Ta,alg:ja})=>crypto.subtle.verify(ja.startsWith("RS")?{name:"RSASSA-PKCS1-v1_5"}:ja.startsWith("ES")?{name:"ECDSA",hash:`SHA-${ja.slice(2)}`}:{name:Ln.jwk.crv},Ln.key,bufferFromBase64url(Ta),new TextEncoder().encode(ta)),parseB64UrlString:ta=>new TextDecoder().decode(bufferFromBase64url(ta)),setTimeoutUnref:setTimeout.bind(void 0),transformPemToJwk:async(ta,Ln)=>{let Ta;switch(Ln){case"RS256":case"RS384":case"RS512":Ta={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${Ln.slice(2)}`};break;case"ES256":case"ES384":case"ES512":Ta={name:"ECDSA",namedCurve:NamedCurvesWebCrypto[Ln]};break;default:throw new JwtInvalidSignatureAlgorithmError("Unsupported signature algorithm",Ln)}const ja=await crypto.subtle.importKey("spki",bufferFromBase64(new TextDecoder().decode(ta).replace(/-----BEGIN PUBLIC KEY-----/,"").replace(/-----END PUBLIC KEY-----/,"").replace(/\s/g,"")),Ta,!0,["verify"]);return crypto.subtle.exportKey("jwk",ja)}};function _bufferFromBase64(ta){const Ln=ta.split("").reduce((Ta,ja,La)=>Object.assign(Ta,{[ja.charCodeAt(0)]:La}),{});return function(Ta){Ta=Ta.replace(/={1,2}$/,"");let ja,La,Fa,wl;return Ta.match(/.{1,4}/g).reduce((Pl,pc,mc)=>(ja=Ln[pc.charCodeAt(0)],La=Ln[pc.charCodeAt(1)],Fa=Ln[pc.charCodeAt(2)],wl=Ln[pc.charCodeAt(3)],Pl[3*mc]=ja<<2|La>>4,Pl[3*mc+1]=(La&15)<<4|Fa>>2,Pl[3*mc+2]=(Fa&3)<<6|wl,Pl),new Uint8Array(Ta.length*3/4))}}const bufferFromBase64url=_bufferFromBase64("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),bufferFromBase64=_bufferFromBase64("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),fetch$1=nodeWebCompat.fetch.bind(void 0);class SimpleFetcher{constructor(Ln){this.defaultRequestOptions={timeout:nodeWebCompat.defaultFetchTimeouts.socketIdle,responseTimeout:nodeWebCompat.defaultFetchTimeouts.response,...Ln?.defaultRequestOptions}}async fetch(Ln,Ta,ja){Ta={...this.defaultRequestOptions,...Ta};try{return await fetch$1(Ln,Ta,ja)}catch(La){if(La instanceof NonRetryableFetchError)throw La;return fetch$1(Ln,Ta,ja)}}}function isJsonObject(ta){return typeof ta=="object"&&!Array.isArray(ta)&&ta!==null}function safeJsonParse(ta){return JSON.parse(ta,(Ln,Ta)=>(typeof Ta=="object"&&!Array.isArray(Ta)&&Ta!==null&&(delete Ta.__proto__,delete Ta.constructor),Ta))}function assertStringEquals(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. Expected: ${Ta}`,Ln,Ta);if(typeof Ln!="string")throw new ja(`${ta} is not of type string`,Ln,Ta);if(Ta!==Ln)throw new ja(`${ta} not allowed: ${Ln}. Expected: ${Ta}`,Ln,Ta)}function assertStringArrayContainsString(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. ${expectationMessage(Ta)}`,Ln,Ta);if(typeof Ln!="string")throw new ja(`${ta} is not of type string`,Ln,Ta);return assertStringArraysOverlap(ta,Ln,Ta,ja)}function assertStringArraysOverlap(ta,Ln,Ta,ja=FailedAssertionError){if(!Ln)throw new ja(`Missing ${ta}. ${expectationMessage(Ta)}`,Ln,Ta);const La=new Set(Array.isArray(Ta)?Ta:[Ta]);if(typeof Ln=="string"&&(Ln=[Ln]),!Array.isArray(Ln))throw new ja(`${ta} is not an array`,Ln,Ta);if(!Ln.some(wl=>{if(typeof wl!="string")throw new ja(`${ta} includes elements that are not of type string`,Ln,Ta);return La.has(wl)}))throw new ja(`${ta} not allowed: ${Ln.join(", ")}. ${expectationMessage(Ta)}`,Ln,Ta)}function expectationMessage(ta){return Array.isArray(ta)?ta.length>1?`Expected one of: ${ta.join(", ")}`:`Expected: ${ta[0]}`:`Expected: ${ta}`}function assertIsNotPromise(ta,Ln){if(ta&&typeof ta.then=="function")throw Ln()}const optionalJwkFieldNames=["use","alg","kid","n","e","x","y","crv"],mandatoryJwkFieldNames=["kty"];function findJwkInJwks(ta,Ln){return ta.keys.find(Ta=>Ta.kid!=null&&Ta.kid===Ln)}const parseJwks=function(ta){let Ln;try{const Ta=new TextDecoder("utf8",{fatal:!0,ignoreBOM:!0}).decode(ta);Ln=safeJsonParse(Ta)}catch(Ta){throw new JwksValidationError(`JWKS could not be parsed as JSON: ${Ta}`)}return assertIsJwks(Ln),Ln};function assertIsJwks(ta){if(!ta)throw new JwksValidationError("JWKS empty");if(!isJsonObject(ta))throw new JwksValidationError("JWKS should be an object");if(!Object.keys(ta).includes("keys"))throw new JwksValidationError("JWKS does not include keys");if(!Array.isArray(ta.keys))throw new JwksValidationError("JWKS keys should be an array");for(const Ln of ta.keys)assertIsJwk(Ln)}function assertIsSignatureJwk(ta){assertStringArrayContainsString("JWK kty",ta.kty,["EC","RSA","OKP"],JwkInvalidKtyError),ta.kty==="EC"?assertIsEsSignatureJwk(ta):ta.kty==="RSA"?assertIsRsaSignatureJwk(ta):ta.kty==="OKP"&&assertIsEdDSASignatureJwk(ta)}function assertIsEdDSASignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"OKP",JwkInvalidKtyError),!ta.crv)throw new JwkValidationError("Missing Curve (crv)");if(!ta.x)throw new JwkValidationError("Missing X Coordinate (x)")}function assertIsEsSignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"EC",JwkInvalidKtyError),!ta.crv)throw new JwkValidationError("Missing Curve (crv)");if(!ta.x)throw new JwkValidationError("Missing X Coordinate (x)");if(!ta.y)throw new JwkValidationError("Missing Y Coordinate (y)")}function assertIsRsaSignatureJwk(ta){if(ta.use&&assertStringEquals("JWK use",ta.use,"sig",JwkInvalidUseError),assertStringEquals("JWK kty",ta.kty,"RSA",JwkInvalidKtyError),!ta.n)throw new JwkValidationError("Missing modulus (n)");if(!ta.e)throw new JwkValidationError("Missing exponent (e)")}function assertIsJwk(ta){if(!ta)throw new JwkValidationError("JWK empty");if(!isJsonObject(ta))throw new JwkValidationError("JWK should be an object");for(const Ln of mandatoryJwkFieldNames)if(typeof ta[Ln]!="string")throw new JwkValidationError(`JWK ${Ln} should be a string`);for(const Ln of optionalJwkFieldNames)if(Ln in ta&&typeof ta[Ln]!="string")throw new JwkValidationError(`JWK ${Ln} should be a string`)}function isJwks(ta){try{return assertIsJwks(ta),!0}catch{return!1}}function isJwk(ta){try{return assertIsJwk(ta),!0}catch{return!1}}class SimplePenaltyBox{constructor(Ln){this.waitingUris=new Map,this.waitSeconds=Ln?.waitSeconds??10}async wait(Ln){if(this.waitingUris.has(Ln))throw new WaitPeriodNotYetEndedJwkError("Not allowed to fetch JWKS yet, still waiting for back off period to end")}release(Ln){const Ta=this.waitingUris.get(Ln);Ta&&(clearTimeout(Ta),this.waitingUris.delete(Ln))}registerFailedAttempt(Ln){const Ta=nodeWebCompat.setTimeoutUnref(()=>{this.waitingUris.delete(Ln)},this.waitSeconds*1e3);this.waitingUris.set(Ln,Ta)}registerSuccessfulAttempt(Ln){this.release(Ln)}}class SimpleJwksCache{constructor(Ln){this.jwksCache=new Map,this.fetchingJwks=new Map,this.penaltyBox=Ln?.penaltyBox??new SimplePenaltyBox,this.fetcher=Ln?.fetcher??new SimpleFetcher,this.jwksParser=Ln?.jwksParser??parseJwks}addJwks(Ln,Ta){this.jwksCache.set(Ln,Ta)}async getJwks(Ln){const Ta=this.fetchingJwks.get(Ln);if(Ta)return Ta;const ja=this.fetcher.fetch(Ln).then(this.jwksParser);this.fetchingJwks.set(Ln,ja);let La;try{La=await ja}finally{this.fetchingJwks.delete(Ln)}return this.jwksCache.set(Ln,La),La}getCachedJwk(Ln,Ta){if(typeof Ta.header.kid!="string")throw new JwtWithoutValidKidError("JWT header does not have valid kid claim");if(!this.jwksCache.has(Ln))throw new JwksNotAvailableInCacheError(`JWKS for uri ${Ln} not yet available in cache`);const ja=findJwkInJwks(this.jwksCache.get(Ln),Ta.header.kid);if(!ja)throw new KidNotFoundInJwksError(`JWK for kid ${Ta.header.kid} not found in the JWKS`);return ja}async getJwk(Ln,Ta){if(typeof Ta.header.kid!="string")throw new JwtWithoutValidKidError("JWT header does not have valid kid claim");const ja=this.jwksCache.get(Ln);if(ja){const wl=findJwkInJwks(ja,Ta.header.kid);if(wl)return wl}await this.penaltyBox.wait(Ln,Ta.header.kid);const La=await this.getJwks(Ln),Fa=findJwkInJwks(La,Ta.header.kid);if(Fa)this.penaltyBox.registerSuccessfulAttempt(Ln,Ta.header.kid);else throw this.penaltyBox.registerFailedAttempt(Ln,Ta.header.kid),new KidNotFoundInJwksError(`JWK for kid "${Ta.header.kid}" not found in the JWKS`);return Fa}}function assertJwtHeader(ta){if(!isJsonObject(ta))throw new JwtParseError("JWT header is not an object");if(ta.alg!==void 0&&typeof ta.alg!="string")throw new JwtParseError("JWT header alg claim is not a string");if(ta.kid!==void 0&&typeof ta.kid!="string")throw new JwtParseError("JWT header kid claim is not a string")}function assertJwtPayload(ta){if(!isJsonObject(ta))throw new JwtParseError("JWT payload is not an object");if(ta.exp!==void 0&&!Number.isFinite(ta.exp))throw new JwtParseError("JWT payload exp claim is not a number");if(ta.iss!==void 0&&typeof ta.iss!="string")throw new JwtParseError("JWT payload iss claim is not a string");if(ta.sub!==void 0&&typeof ta.sub!="string")throw new JwtParseError("JWT payload sub claim is not a string");if(ta.aud!==void 0&&typeof ta.aud!="string"&&(!Array.isArray(ta.aud)||ta.aud.some(Ln=>typeof Ln!="string")))throw new JwtParseError("JWT payload aud claim is not a string or array of strings");if(ta.nbf!==void 0&&!Number.isFinite(ta.nbf))throw new JwtParseError("JWT payload nbf claim is not a number");if(ta.iat!==void 0&&!Number.isFinite(ta.iat))throw new JwtParseError("JWT payload iat claim is not a number");if(ta.scope!==void 0&&typeof ta.scope!="string")throw new JwtParseError("JWT payload scope claim is not a string");if(ta.jti!==void 0&&typeof ta.jti!="string")throw new JwtParseError("JWT payload jti claim is not a string")}const JWT_REGEX=/^[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}\.[A-Za-z0-9_-]+={0,2}$/;function decomposeUnverifiedJwt(ta){if(!ta)throw new JwtParseError("Empty JWT");if(typeof ta!="string")throw new JwtParseError("JWT is not a string");if(!JWT_REGEX.test(ta))throw new JwtParseError("JWT string does not consist of exactly 3 parts (header, payload, signature)");const[Ln,Ta,ja]=ta.split("."),[La,Fa]=[Ln,Ta].map(nodeWebCompat.parseB64UrlString);let wl;try{wl=safeJsonParse(La)}catch(pc){throw new JwtParseError("Invalid JWT. Header is not a valid JSON object",pc)}assertJwtHeader(wl);let Pl;try{Pl=safeJsonParse(Fa)}catch(pc){throw new JwtParseError("Invalid JWT. Payload is not a valid JSON object",pc)}return assertJwtPayload(Pl),{header:wl,headerB64:Ln,payload:Pl,payloadB64:Ta,signatureB64:ja}}function validateJwtFields(ta,Ln){if(ta.exp!==void 0&&ta.exp+(Ln.graceSeconds??0)<Date.now()/1e3)throw new JwtExpiredError(`Token expired at ${new Date(ta.exp*1e3).toISOString()}`,ta.exp);if(ta.nbf!==void 0&&ta.nbf-(Ln.graceSeconds??0)>Date.now()/1e3)throw new JwtNotBeforeError(`Token can't be used before ${new Date(ta.nbf*1e3).toISOString()}`,ta.nbf);if(Ln.issuer!==null){if(Ln.issuer===void 0)throw new ParameterValidationError("issuer must be provided or set to null explicitly");assertStringArrayContainsString("Issuer",ta.iss,Ln.issuer,JwtInvalidIssuerError)}if(Ln.audience!==null){if(Ln.audience===void 0)throw new ParameterValidationError("audience must be provided or set to null explicitly");assertStringArraysOverlap("Audience",ta.aud,Ln.audience,JwtInvalidAudienceError)}Ln.scope!=null&&assertStringArraysOverlap("Scope",ta.scope?.split(" "),Ln.scope,JwtInvalidScopeError)}const supportedSignatureAlgorithms=["RS256","RS384","RS512","ES256","ES384","ES512","EdDSA"];function validateJwtHeaderAndJwk(ta,Ln){assertIsSignatureJwk(Ln),Ln.alg&&assertStringEquals("JWT signature algorithm",ta.alg,Ln.alg,JwtInvalidSignatureAlgorithmError),assertStringArrayContainsString("JWT signature algorithm",ta.alg,supportedSignatureAlgorithms,JwtInvalidSignatureAlgorithmError)}async function verifyDecomposedJwt(ta,Ln,Ta,ja,La){const{header:Fa,headerB64:wl,payload:Pl,payloadB64:pc,signatureB64:mc}=ta,gc=await ja(Ln,ta);validateJwtHeaderAndJwk(ta.header,gc);const Vd=await La(gc,Fa.alg,Pl.iss);if(!await nodeWebCompat.verifySignatureAsync({jwsSigningInput:`${wl}.${pc}`,signature:mc,alg:Fa.alg,keyObject:Vd}))throw new JwtInvalidSignatureError("Invalid signature");try{validateJwtFields(Pl,Ta),Ta.customJwtCheck&&await Ta.customJwtCheck({header:Fa,payload:Pl,jwk:gc})}catch(kf){throw Ta.includeRawJwtInErrors&&kf instanceof JwtInvalidClaimError?kf.withRawJwt(ta):kf}return Pl}function verifyDecomposedJwtSync(ta,Ln,Ta,ja){const{header:La,headerB64:Fa,payload:wl,payloadB64:Pl,signatureB64:pc}=ta;let mc;if(isJwk(Ln))mc=Ln;else if(isJwks(Ln)){const Wd=La.kid?findJwkInJwks(Ln,La.kid):void 0;if(!Wd)throw new KidNotFoundInJwksError(`JWK for kid ${La.kid} not found in the JWKS`);mc=Wd}else throw new ParameterValidationError([`Expected a valid JWK or JWKS (parsed as JavaScript object), but received: ${Ln}.`,"If you're passing a JWKS URI, use the async verify() method instead, it will download and parse the JWKS for you"].join());validateJwtHeaderAndJwk(ta.header,mc);const gc=ja(mc,La.alg,wl.iss);if(!nodeWebCompat.verifySignatureSync({jwsSigningInput:`${Fa}.${Pl}`,signature:pc,alg:La.alg,keyObject:gc}))throw new JwtInvalidSignatureError("Invalid signature");try{if(validateJwtFields(wl,Ta),Ta.customJwtCheck){const Wd=Ta.customJwtCheck({header:La,payload:wl,jwk:mc});assertIsNotPromise(Wd,()=>new ParameterValidationError("Custom JWT checks must be synchronous but a promise was returned"))}}catch(Wd){throw Ta.includeRawJwtInErrors&&Wd instanceof JwtInvalidClaimError?Wd.withRawJwt(ta):Wd}return wl}class JwtVerifierBase{constructor(Ln,Ta=new SimpleJwksCache){if(this.jwksCache=Ta,this.issuersConfig=new Map,this.publicKeyCache=new KeyObjectCache,Array.isArray(Ln)){if(!Ln.length)throw new ParameterValidationError("Provide at least one issuer configuration");Ln.forEach((ja,La)=>{if(this.issuersConfig.has(ja.issuer))throw new ParameterValidationError(`issuer ${ja.issuer} supplied multiple times`);if(ja.issuer===null&&Ln.length>=2)throw new ParameterValidationError(`issuer cannot be null when multiple issuers are supplied (at issuer: ${La})`);this.issuersConfig.set(ja.issuer,this.withJwksUri(ja))})}else this.issuersConfig.set(Ln.issuer,this.withJwksUri(Ln))}getIssuerConfig(Ln){if(this.issuersConfig.size===1&&(Ln=this.issuersConfig.keys().next().value),Ln===void 0)throw new ParameterValidationError("issuer must be provided");const Ta=this.issuersConfig.get(Ln);if(!Ta)throw new ParameterValidationError(`issuer not configured: ${Ln}`);return Ta}cacheJwks(...[Ln,Ta]){const ja=this.getIssuerConfig(Ta);this.jwksCache.addJwks(ja.jwksUri,Ln),this.publicKeyCache.clearCache(ja.issuer)}async hydrate(){const Ln=Array.from(this.issuersConfig.values()).map(({jwksUri:Ta})=>this.jwksCache.getJwks(Ta));await Promise.all(Ln)}verifySync(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);return this.verifyDecomposedJwtSync(ja,La,Fa)}verifyDecomposedJwtSync(Ln,Ta,ja){const La=this.jwksCache.getCachedJwk(Ta,Ln);return verifyDecomposedJwtSync(Ln,La,ja,this.publicKeyCache.transformJwkToKeyObjectSync.bind(this.publicKeyCache))}async verify(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);return this.verifyDecomposedJwt(ja,La,Fa)}verifyDecomposedJwt(Ln,Ta,ja){return verifyDecomposedJwt(Ln,Ta,ja,this.jwksCache.getJwk.bind(this.jwksCache),this.publicKeyCache.transformJwkToKeyObjectAsync.bind(this.publicKeyCache))}getVerifyParameters(Ln,Ta){const ja=decomposeUnverifiedJwt(Ln),La=this.getIssuerConfig(ja.payload.iss);return{decomposedJwt:ja,jwksUri:La.jwksUri,verifyProperties:{...La,...Ta}}}withJwksUri(Ln){if(Ln.jwksUri)return Ln;const Ta=Ln.issuer;if(!Ta)throw new ParameterValidationError("jwksUri must be provided for issuer null");const ja=new URL(Ta).pathname.replace(/\/$/,"");return{jwksUri:new URL(`${ja}/.well-known/jwks.json`,Ta).href,...Ln}}}class KeyObjectCache{constructor(Ln=nodeWebCompat.transformJwkToKeyObjectSync,Ta=nodeWebCompat.transformJwkToKeyObjectAsync){this.transformJwkToKeyObjectSyncFn=Ln,this.transformJwkToKeyObjectAsyncFn=Ta,this.publicKeys=new Map}transformJwkToKeyObjectSync(Ln,Ta,ja){const La=Ln.alg??Ta;if(!ja||!Ln.kid||!La)return this.transformJwkToKeyObjectSyncFn(Ln,La,ja);const Fa=this.publicKeys.get(ja)?.get(Ln.kid)?.get(La);if(Fa)return Fa;const wl=this.transformJwkToKeyObjectSyncFn(Ln,La,ja);return this.putKeyObjectInCache(ja,Ln.kid,La,wl),wl}async transformJwkToKeyObjectAsync(Ln,Ta,ja){const La=Ln.alg??Ta;if(!ja||!Ln.kid||!La)return this.transformJwkToKeyObjectAsyncFn(Ln,La,ja);const Fa=this.publicKeys.get(ja)?.get(Ln.kid)?.get(La);if(Fa)return Fa;const wl=await this.transformJwkToKeyObjectAsyncFn(Ln,La,ja);return this.putKeyObjectInCache(ja,Ln.kid,La,wl),wl}putKeyObjectInCache(Ln,Ta,ja,La){const Fa=this.publicKeys.get(Ln),wl=Fa?.get(Ta);wl?wl.set(ja,La):Fa?Fa.set(Ta,new Map([[ja,La]])):this.publicKeys.set(Ln,new Map([[Ta,new Map([[ja,La]])]]))}clearCache(Ln){this.publicKeys.delete(Ln)}}function validateCognitoJwtFields(ta,Ln){if(Ln.groups!=null&&assertStringArraysOverlap("Cognito group",ta["cognito:groups"],Ln.groups,CognitoJwtInvalidGroupError),assertStringArrayContainsString("Token use",ta.token_use,["id","access"],CognitoJwtInvalidTokenUseError),Ln.tokenUse!==null){if(Ln.tokenUse===void 0)throw new ParameterValidationError("tokenUse must be provided or set to null explicitly");assertStringEquals("Token use",ta.token_use,Ln.tokenUse,CognitoJwtInvalidTokenUseError)}if(Ln.clientId!==null){if(Ln.clientId===void 0)throw new ParameterValidationError("clientId must be provided or set to null explicitly");ta.token_use==="id"?assertStringArrayContainsString('Client ID ("audience")',ta.aud,Ln.clientId,CognitoJwtInvalidClientIdError):assertStringArrayContainsString("Client ID",ta.client_id,Ln.clientId,CognitoJwtInvalidClientIdError)}}class CognitoJwtVerifier extends JwtVerifierBase{constructor(Ln,Ta){const ja=Array.isArray(Ln)?Ln.map(La=>({...La,...CognitoJwtVerifier.parseUserPoolId(La.userPoolId),audience:null})):{...Ln,...CognitoJwtVerifier.parseUserPoolId(Ln.userPoolId),audience:null};super(ja,Ta)}static parseUserPoolId(Ln){const Ta=Ln.match(this.USER_POOL_ID_REGEX);if(!Ta)throw new ParameterValidationError(`Invalid Cognito User Pool ID: ${Ln}`);const La=`https://cognito-idp.${Ta.groups.region}.amazonaws.com/${Ln}`;return{issuer:La,jwksUri:`${La}/.well-known/jwks.json`}}static create(Ln,Ta){return new this(Ln,Ta?.jwksCache)}verifySync(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);this.verifyDecomposedJwtSync(ja,La,Fa);try{validateCognitoJwtFields(ja.payload,Fa)}catch(wl){throw Fa.includeRawJwtInErrors&&wl instanceof JwtInvalidClaimError?wl.withRawJwt(ja):wl}return ja.payload}async verify(...[Ln,Ta]){const{decomposedJwt:ja,jwksUri:La,verifyProperties:Fa}=this.getVerifyParameters(Ln,Ta);await this.verifyDecomposedJwt(ja,La,Fa);try{validateCognitoJwtFields(ja.payload,Fa)}catch(wl){throw Fa.includeRawJwtInErrors&&wl instanceof JwtInvalidClaimError?wl.withRawJwt(ja):wl}return ja.payload}cacheJwks(...[Ln,Ta]){let ja;if(Ta!==void 0)ja=CognitoJwtVerifier.parseUserPoolId(Ta).issuer;else if(Array.from(this.issuersConfig).length>1)throw new ParameterValidationError("userPoolId must be provided");const La=this.getIssuerConfig(ja);super.cacheJwks(Ln,La.issuer)}}CognitoJwtVerifier.USER_POOL_ID_REGEX=/^(?<region>[a-z]{2}-(gov-)?[a-z]+-\d)_[a-zA-Z0-9]+$/;var __assign=function(){return __assign=Object.assign||function(Ln){for(var Ta,ja=1,La=arguments.length;ja<La;ja++){Ta=arguments[ja];for(var Fa in Ta)Object.prototype.hasOwnProperty.call(Ta,Fa)&&(Ln[Fa]=Ta[Fa])}return Ln},__assign.apply(this,arguments)};function __rest(ta,Ln){var Ta={};for(var ja in ta)Object.prototype.hasOwnProperty.call(ta,ja)&&Ln.indexOf(ja)<0&&(Ta[ja]=ta[ja]);if(ta!=null&&typeof Object.getOwnPropertySymbols=="function")for(var La=0,ja=Object.getOwnPropertySymbols(ta);La<ja.length;La++)Ln.indexOf(ja[La])<0&&Object.prototype.propertyIsEnumerable.call(ta,ja[La])&&(Ta[ja[La]]=ta[ja[La]]);return Ta}function __awaiter(ta,Ln,Ta,ja){function La(Fa){return Fa instanceof Ta?Fa:new Ta(function(wl){wl(Fa)})}return new(Ta||(Ta=Promise))(function(Fa,wl){function Pl(gc){try{mc(ja.next(gc))}catch(Vd){wl(Vd)}}function pc(gc){try{mc(ja.throw(gc))}catch(Vd){wl(Vd)}}function mc(gc){gc.done?Fa(gc.value):La(gc.value).then(Pl,pc)}mc((ja=ja.apply(ta,Ln||[])).next())})}function __generator(ta,Ln){var Ta={label:0,sent:function(){if(Fa[0]&1)throw Fa[1];return Fa[1]},trys:[],ops:[]},ja,La,Fa,wl=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return wl.next=Pl(0),wl.throw=Pl(1),wl.return=Pl(2),typeof Symbol=="function"&&(wl[Symbol.iterator]=function(){return this}),wl;function Pl(mc){return function(gc){return pc([mc,gc])}}function pc(mc){if(ja)throw new TypeError("Generator is already executing.");for(;wl&&(wl=0,mc[0]&&(Ta=0)),Ta;)try{if(ja=1,La&&(Fa=mc[0]&2?La.return:mc[0]?La.throw||((Fa=La.return)&&Fa.call(La),0):La.next)&&!(Fa=Fa.call(La,mc[1])).done)return Fa;switch(La=0,Fa&&(mc=[mc[0]&2,Fa.value]),mc[0]){case 0:case 1:Fa=mc;break;case 4:return Ta.label++,{value:mc[1],done:!1};case 5:Ta.label++,La=mc[1],mc=[0];continue;case 7:mc=Ta.ops.pop(),Ta.trys.pop();continue;default:if(Fa=Ta.trys,!(Fa=Fa.length>0&&Fa[Fa.length-1])&&(mc[0]===6||mc[0]===2)){Ta=0;continue}if(mc[0]===3&&(!Fa||mc[1]>Fa[0]&&mc[1]<Fa[3])){Ta.label=mc[1];break}if(mc[0]===6&&Ta.label<Fa[1]){Ta.label=Fa[1],Fa=mc;break}if(Fa&&Ta.label<Fa[2]){Ta.label=Fa[2],Ta.ops.push(mc);break}Fa[2]&&Ta.ops.pop(),Ta.trys.pop();continue}mc=Ln.call(ta,Ta)}catch(gc){mc=[6,gc],La=0}finally{ja=Fa=0}if(mc[0]&5)throw mc[1];return{value:mc[0]?mc[1]:void 0,done:!0}}}function __spreadArray(ta,Ln,Ta){if(Ta||arguments.length===2)for(var ja=0,La=Ln.length,Fa;ja<La;ja++)(Fa||!(ja in Ln))&&(Fa||(Fa=Array.prototype.slice.call(Ln,0,ja)),Fa[ja]=Ln[ja]);return ta.concat(Fa||Array.prototype.slice.call(Ln))}typeof SuppressedError=="function"&&SuppressedError;var define_process_env_default$2={};let fromEnv,CognitoIdentityProviderClient,SignUpCommand,ConfirmSignUp,ResendConfirmationCodeCommand,ForgotPasswordCommand,ConfirmForgotPasswordCommand,AdminGetUserCommand,InitiateAuthCommand,AdminCreateUserCommand,AdminDisableUserCommand,AdminEnableUserCommand,AdminDeleteUserCommand,RespondToAuthChallengeCommand,AuthenticationDetails,CognitoUser,CognitoUserPool,CognitoUserSession,CognitoIdToken,CognitoAccessToken,CognitoRefreshToken;if(isNodeEnv$1){fromEnv=(await __vitePreload(()=>import("./index.browser-BO5G3NbX.js"),__vite__mapDeps([38,29,39]))).fromEnv;const Ln=await __vitePreload(()=>import("./index-Cn4B33_-.js"),__vite__mapDeps([40,41,39,29,6,1,42,43,12,17,19,25,20,23,24,18,44,31,26,34,45,11,13,10,9]));CognitoIdentityProviderClient=Ln.CognitoIdentityProviderClient,SignUpCommand=Ln.SignUpCommand,ConfirmSignUp=Ln.ConfirmSignUpCommand,ResendConfirmationCodeCommand=Ln.ResendConfirmationCodeCommand,ForgotPasswordCommand=Ln.ForgotPasswordCommand,ConfirmForgotPasswordCommand=Ln.ConfirmForgotPasswordCommand,AdminGetUserCommand=Ln.AdminGetUserCommand,InitiateAuthCommand=Ln.InitiateAuthCommand,AdminCreateUserCommand=Ln.AdminCreateUserCommand,AdminDisableUserCommand=Ln.AdminDisableUserCommand,AdminEnableUserCommand=Ln.AdminEnableUserCommand,AdminDeleteUserCommand=Ln.AdminDeleteUserCommand,RespondToAuthChallengeCommand=Ln.RespondToAuthChallengeCommand;const Ta=await __vitePreload(()=>import("./index-BOLaQ9_Z.js"),__vite__mapDeps([46,6,11,12,13]));AuthenticationDetails=Ta.AuthenticationDetails,CognitoUser=Ta.CognitoUser,CognitoUserPool=Ta.CognitoUserPool,CognitoUserSession=Ta.CognitoUserSession,CognitoIdToken=Ta.CognitoIdToken,CognitoAccessToken=Ta.CognitoAccessToken,CognitoRefreshToken=Ta.CognitoRefreshToken}const defaultConfig$1=isNodeEnv$1?new Map().set("UserPoolId",define_process_env_default$2.COGNITO_USER_POOL_ID).set("ClientId",define_process_env_default$2.COGNITO_CLIENT_ID):new Map;function handleCognitoError(ta,Ln){var Ta;const ja=sanitizeErrorMessage(ta.message||"");switch(logger$3.error(`Cognito error in ${Ln}: ${ta.name} - ${ja}`,{errorName:ta.name,errorCode:ta.code,context:Ln,statusCode:(Ta=ta.$metadata)===null||Ta===void 0?void 0:Ta.httpStatusCode}),ta.name){case"UserNotFoundException":throw logger$3.debug(`User not found in context: ${Ln}`),new UserNotFoundError$1("User account not found. Please check your email or sign up.");case"NotAuthorizedException":throw ta.message&&ta.message.includes("password")?(logger$3.debug(`Invalid password attempt in context: ${Ln}`),new UnauthorisedError$1("Invalid password. Please try again.")):ta.message&&ta.message.includes("not confirmed")?(logger$3.debug(`User not confirmed in context: ${Ln}`),new UserNotConfirmedError$1):(logger$3.debug(`Authentication failed in context: ${Ln}`),new UnauthorisedError$1("Authentication failed. Please check your credentials."));case"UserNotConfirmedException":throw logger$3.debug(`User not confirmed in context: ${Ln}`),new UserNotConfirmedError$1;case"PasswordResetRequiredException":throw logger$3.debug(`Password reset required in context: ${Ln}`),new PasswordResetRequiredError$1;case"TooManyRequestsException":throw logger$3.warn(`Rate limit exceeded in context: ${Ln}`),new TooManyRequestsError$1;case"TooManyFailedAttemptsException":throw logger$3.warn(`Too many failed attempts in context: ${Ln}`),new TooManyRequestsError$1("Too many failed login attempts. Please try again later.");case"InvalidParameterException":throw logger$3.debug(`Invalid parameters in context: ${Ln}`),new InvalidParameterError$1(sanitizeErrorMessage(ta.message)||"Invalid parameters provided");case"ExpiredCodeException":throw logger$3.debug(`Expired code in context: ${Ln}`),new ExpiredCodeError$1;case"CodeMismatchException":throw logger$3.debug(`Code mismatch in context: ${Ln}`),new CodeMismatchError$1;case"UsernameExistsException":throw logger$3.debug(`Username exists in context: ${Ln}`),new BadRequestError$4("An account with this email already exists.");case"InvalidPasswordException":throw logger$3.debug(`Invalid password format in context: ${Ln}`),new BadRequestError$4("Password does not meet requirements. It must be at least 8 characters long and contain uppercase, lowercase, numbers, and special characters.");case"LimitExceededException":throw logger$3.warn(`Service limit exceeded in context: ${Ln}`),new TooManyRequestsError$1("Service limit exceeded. Please try again later.");case"InternalErrorException":throw logger$3.error(`Internal Cognito error in context: ${Ln}`),new Error("Authentication service is temporarily unavailable. Please try again later.");case"ResourceNotFoundException":throw logger$3.error(`Resource not found in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");case"AliasExistsException":throw logger$3.debug(`Alias exists in context: ${Ln}`),new BadRequestError$4("An account with this email already exists.");case"InvalidEmailRoleAccessPolicyException":throw logger$3.error(`Invalid email role access policy in context: ${Ln}`),new Error("Email service configuration error. Please contact support.");case"UserLambdaValidationException":throw logger$3.error(`User lambda validation error in context: ${Ln}`),new BadRequestError$4("User validation failed. Please check your input and try again.");case"UnsupportedUserStateException":throw logger$3.debug(`Unsupported user state in context: ${Ln}`),new UserNotConfirmedError$1("User account is in an unsupported state. Please contact support.");case"MFAMethodNotFoundException":throw logger$3.debug(`MFA method not found in context: ${Ln}`),new BadRequestError$4("MFA method not found. Please set up MFA and try again.");case"CodeDeliveryFailureException":throw logger$3.error(`Code delivery failure in context: ${Ln}`),new Error("Unable to deliver verification code. Please try again later.");case"DuplicateProviderException":throw logger$3.error(`Duplicate provider in context: ${Ln}`),new BadRequestError$4("Authentication provider already exists.");case"EnableSoftwareTokenMFAException":throw logger$3.debug(`Software token MFA required in context: ${Ln}`),new BadRequestError$4("Software token MFA setup required.");case"ForbiddenException":throw logger$3.warn(`Forbidden access in context: ${Ln}`),new UnauthorisedError$1("Access forbidden. Please check your permissions.");case"GroupExistsException":throw logger$3.debug(`Group exists in context: ${Ln}`),new BadRequestError$4("Group already exists.");case"InvalidLambdaResponseException":throw logger$3.error(`Invalid lambda response in context: ${Ln}`),new Error("Authentication service error. Please try again later.");case"InvalidOAuthFlowException":throw logger$3.error(`Invalid OAuth flow in context: ${Ln}`),new BadRequestError$4("Invalid OAuth flow. Please try again.");case"InvalidSmsRoleAccessPolicyException":throw logger$3.error(`Invalid SMS role access policy in context: ${Ln}`),new Error("SMS service configuration error. Please contact support.");case"InvalidSmsRoleTrustRelationshipException":throw logger$3.error(`Invalid SMS role trust relationship in context: ${Ln}`),new Error("SMS service configuration error. Please contact support.");case"InvalidUserPoolConfigurationException":throw logger$3.error(`Invalid user pool configuration in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");case"PreconditionNotMetException":throw logger$3.debug(`Precondition not met in context: ${Ln}`),new BadRequestError$4("Precondition not met. Please check your request and try again.");case"ScopeDoesNotExistException":throw logger$3.error(`Scope does not exist in context: ${Ln}`),new BadRequestError$4("Invalid scope. Please check your request.");case"UnexpectedLambdaException":throw logger$3.error(`Unexpected lambda exception in context: ${Ln}`),new Error("Authentication service error. Please try again later.");case"UserImportInProgressException":throw logger$3.warn(`User import in progress in context: ${Ln}`),new TooManyRequestsError$1("User import in progress. Please try again later.");case"UserPoolTaggingException":throw logger$3.error(`User pool tagging exception in context: ${Ln}`),new Error("Authentication service configuration error. Please contact support.");default:throw logger$3.error(`Unhandled Cognito error: ${ta.name}`,{errorName:ta.name,errorCode:ta.code,context:Ln}),new Error(`Authentication error: ${sanitizeErrorMessage(ta.message)||"An unexpected error occurred"}`)}}function sanitizeErrorMessage(ta){return ta?ta.replace(/password/gi,"[REDACTED]").replace(/token/gi,"[REDACTED]").replace(/secret/gi,"[REDACTED]").replace(/key/gi,"[REDACTED]").replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g,"[EMAIL_REDACTED]").replace(/\b[A-Fa-f0-9]{32,}\b/g,"[TOKEN_REDACTED]").replace(/\b\d{4,}\b/g,"[NUMBER_REDACTED]"):""}class CognitoAuth{constructor(Ln){this.config=Ln||defaultConfig$1;const Ta=this.config.get("UserPoolId");Ta&&(this.userPool=new CognitoUserPool({UserPoolId:Ta,ClientId:this.fetchClientId()}))}fetchUserPoolId(){return this.fetchConfig("UserPoolId")}fetchClientId(){return this.fetchConfig("ClientId")}fetchConfig(Ln){const Ta=this.config.get(Ln);if(Ta)return Ta;throw new Error(`${Ln} is not set`)}async signUp(Ln,Ta,ja,La,Fa,wl,Pl){const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),mc=[{Name:"email",Value:ja},{Name:"name",Value:ja},{Name:"given_name",Value:Ln},{Name:"family_name",Value:Ta}];Fa&&Fa.forEach((Wd,kf)=>{mc.push({Name:kf,Value:Wd})});const gc={ClientId:this.config.get("ClientId"),Username:ja,Password:La,UserAttributes:mc,ValidationData:mc},Vd=new SignUpCommand(gc);try{logger$3.debug(`Attempting signup for user: ${ja}`);const Wd=await pc.send(Vd);if(Wd.$metadata.httpStatusCode==200){logger$3.info(`Signup successful for user: ${ja}`);const kf=await ensureUser(ja,Ln,Ta,wl,"Active"),Pf={username:ja,firstName:Ln,lastName:Ta,id:kf.id,systemUserInfo:Wd.UserSub};Pl(Pf)}else throw logger$3.error(`Signup failed with HTTP status ${Wd.$metadata.httpStatusCode}`,{username:ja,statusCode:Wd.$metadata.httpStatusCode}),new BadRequestError$4(`Signup failed with status ${Wd.$metadata.httpStatusCode}`)}catch(Wd){if(Wd instanceof BadRequestError$4)throw Wd;logger$3.error(`Signup error for user ${ja}:`,{errorName:Wd.name,errorMessage:sanitizeErrorMessage(Wd.message)}),handleCognitoError(Wd,"signUp")}}async confirmSignup(Ln,Ta,ja){try{const La=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),Fa=new ConfirmSignUp({ClientId:this.config.get("ClientId"),Username:Ln,ConfirmationCode:Ta});await La.send(Fa)}catch(La){logger$3.error(`Failed to confirm signup: ${La.message}`),handleCognitoError(La,"confirmSignup")}}async resendConfirmationCode(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new ResendConfirmationCodeCommand({ClientId:this.config.get("ClientId"),Username:Ln});await ja.send(La)}catch(ja){logger$3.error(`Failed to resend confirmation code: ${ja.message}`),handleCognitoError(ja,"resendConfirmationCode")}}async forgotPassword(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new ForgotPasswordCommand({ClientId:this.fetchClientId(),Username:Ln});await ja.send(La)}catch(ja){logger$3.error(`Forgot password failed for ${Ln}: ${sanitizeErrorMessage(ja.message)}`),handleCognitoError(ja,"forgotPassword")}}async confirmForgotPassword(Ln,Ta,ja,La){try{const Fa=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),wl=new ConfirmForgotPasswordCommand({ClientId:this.fetchClientId(),Username:Ln,ConfirmationCode:Ta,Password:ja});await Fa.send(wl)}catch(Fa){logger$3.error(`Confirm forgot password failed for ${Ln}: ${sanitizeErrorMessage(Fa.message)}`),handleCognitoError(Fa,"confirmForgotPassword")}}async login(Ln,Ta,ja,La){if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID){const wl=new CognitoUser({Username:Ln,Pool:this.fetchUserPool()}),Pl=new AuthenticationDetails({Username:Ln,Password:Ta});let pc,mc;for(wl.authenticateUser(Pl,{onSuccess:gc=>{pc=gc},onFailure:gc=>{logger$3.debug(`Cognito authentication failed for user ${Ln}:`,{errorName:gc.name,errorMessage:sanitizeErrorMessage(gc.message)}),mc=gc},mfaRequired:(gc,Vd)=>{logger$3.info(`MFA required for user ${Ln}: ${gc}`),mc=new Error("MFA authentication required")},newPasswordRequired:(gc,Vd)=>{logger$3.info(`New password required for user ${Ln}`),mc=new PasswordResetRequiredError$1("New password required. Please reset your password.")}});pc===void 0&&mc===void 0;)await sleepMilliseconds$1(100);if(mc){if(mc instanceof PasswordResetRequiredError$1)throw mc;logger$3.error(`Login failed for user ${Ln}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),handleCognitoError(mc,"login")}if(pc){const gc=pc.getIdToken(),Vd=gc.getJwtToken(),Wd=gc.decodePayload(),kf=Wd.given_name||Wd.name||"",Pf=Wd.family_name||"",Nf=Wd["cognito:groups"];let Eh=await findUserByEmail(Ln,ja);Eh||(Eh=await ensureUser(Ln,kf,Pf,ja));const Em=Eh.lookup("id");Nf&&await ensureUserRoles(Em,Nf,ja);const qg=pc.getAccessToken().getJwtToken(),Ug=pc.getRefreshToken().getToken(),U_={sessionId:(await ensureUserSession(Em,Vd,qg,Ug,ja)).lookup("id"),userId:Em,authToken:Vd,idToken:Vd,accessToken:qg,refreshToken:Ug,systemSesionInfo:pc};La(U_)}else throw logger$3.error(`Login failed for ${Ln} - no result received`),new UnauthorisedError$1("Login failed. Please try again.")}else{let wl=await findUserByEmail(Ln,ja);wl||(logger$3.warn(`User ${Ln} not found in local store`),wl=await ensureUser(Ln,"","",ja));const Pl=new CognitoUser({Username:Ln,Pool:this.fetchUserPool()}),pc=new AuthenticationDetails({Username:Ln,Password:Ta});let mc,gc;for(Pl.authenticateUser(pc,{onSuccess:Vd=>{mc=Vd},onFailure:Vd=>{logger$3.debug(`Cognito authentication failed for user ${Ln}:`,{errorName:Vd.name,errorMessage:sanitizeErrorMessage(Vd.message)}),gc=Vd},mfaRequired:(Vd,Wd)=>{logger$3.info(`MFA required for user ${Ln}: ${Vd}`),gc=new Error("MFA authentication required")},newPasswordRequired:(Vd,Wd)=>{logger$3.info(`New password required for user ${Ln}`),gc=new PasswordResetRequiredError$1("New password required. Please reset your password.")}});mc===void 0&&gc===void 0;)await sleepMilliseconds$1(100);if(gc){if(gc instanceof PasswordResetRequiredError$1)throw gc;logger$3.error(`Login failed for user ${Ln}:`,{errorName:gc.name,errorMessage:sanitizeErrorMessage(gc.message)}),handleCognitoError(gc,"login")}if(mc){const Vd=wl.lookup("id"),Wd=mc.getIdToken().getJwtToken(),kf=mc.getAccessToken().getJwtToken(),Pf=mc.getRefreshToken().getToken(),Eh={sessionId:(await ensureUserSession(Vd,Wd,kf,Pf,ja)).lookup("id"),userId:Vd,authToken:Wd,idToken:Wd,accessToken:kf,refreshToken:Pf,systemSesionInfo:mc};La(Eh)}else throw logger$3.error(`Login failed for ${Ln} - no result received`),new UnauthorisedError$1("Login failed. Please try again.")}}async logout(Ln,Ta,ja){try{const La=await findUser(Ln.userId,Ta);if(!La){logger$3.warn(`User ${Ln.userId} not found during logout`),ja&&ja(!0);return}const Fa=new CognitoUser({Username:La.lookup("email"),Pool:this.fetchUserPool()});let wl=!1,Pl;const pc=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:Ln.idToken}),AccessToken:new CognitoAccessToken({AccessToken:Ln.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:Ln.refreshToken})});for(Fa.setSignInUserSession(pc),Fa.globalSignOut({onSuccess:function(){wl=!0},onFailure:function(mc){wl=!0,logger$3.error(`Cognito signOut error for user ${Ln.userId}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),Pl=mc}});!wl;)await sleepMilliseconds$1(100);Pl&&logger$3.error(`Error during Cognito logout for user ${Ln.userId}: ${Pl.message}`),logger$3.debug(`Successfully logged out user ${Ln.userId}`),ja&&ja(!0)}catch(La){throw logger$3.error(`Logout failed for user ${Ln.userId}: ${La.message}`),ja&&ja(!1),La}}async changePassword(Ln,Ta,ja,La){const Fa=await findUser(Ln.userId,La);if(!Fa)return logger$3.warn(`User ${Ln.userId} not found for password-change`),!1;const wl=Fa.lookup("email"),Pl=new CognitoUser({Username:wl,Pool:this.fetchUserPool()}),pc=new CognitoUserSession({IdToken:new CognitoIdToken({IdToken:Ln.idToken}),AccessToken:new CognitoAccessToken({AccessToken:Ln.accessToken}),RefreshToken:new CognitoRefreshToken({RefreshToken:Ln.refreshToken})});Pl.setSignInUserSession(pc);let mc=!1,gc;for(Pl.changePassword(ja,Ta,(Vd,Wd)=>{Vd?(mc=!0,gc=Vd):mc=!0});!mc;)await sleepMilliseconds$1(100);return gc?(logger$3.warn(`Failed to change the password for ${wl} - ${gc.message}`),!1):!0}fetchUserPool(){if(this.userPool)return this.userPool;throw new Error("UserPool not initialized")}async verifyToken(Ln){try{const ja=await CognitoJwtVerifier.create({userPoolId:this.fetchUserPoolId(),tokenUse:"id",clientId:this.fetchClientId()}).verify(Ln);logger$3.debug(`Decoded JWT for ${ja.email}`)}catch(Ta){throw logger$3.error("Token verification failed:",{errorName:Ta.name,errorMessage:sanitizeErrorMessage(Ta.message)}),Ta.message&&Ta.message.includes("expired")?new UnauthorisedError$1("Token has expired. Please login again."):Ta.message&&Ta.message.includes("invalid")?new UnauthorisedError$1("Invalid token format."):Ta.message&&Ta.message.includes("not before")?new UnauthorisedError$1("Token is not yet valid."):Ta.message&&Ta.message.includes("audience")?new UnauthorisedError$1("Token audience mismatch."):new UnauthorisedError$1(`Token verification failed: ${sanitizeErrorMessage(Ta.message)||"Invalid token"}`)}}async getUser(Ln,Ta){const ja=await findUser(Ln,Ta);if(!ja)throw new UserNotFoundError$1(`User ${Ln} not found in local database`);const La=ja.lookup("email"),Fa=ja.lookup("firstName"),wl=ja.lookup("lastName");if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID&&La)try{const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),mc=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:La}),gc=await pc.send(mc);return{id:Ln,username:La,firstName:Fa,lastName:wl,systemUserInfo:{localUser:ja,cognitoData:{userAttributes:gc.UserAttributes,userCreateDate:gc.UserCreateDate,userLastModifiedDate:gc.UserLastModifiedDate,userStatus:gc.UserStatus,enabled:gc.Enabled,preferredMfaSetting:gc.PreferredMfaSetting,userMFASettingList:gc.UserMFASettingList}}}}catch(pc){return logger$3.warn(`Failed to get Cognito user info for ${La}, using local data only:`,{errorName:pc.name,errorMessage:sanitizeErrorMessage(pc.message)}),{id:Ln,username:La,firstName:Fa,lastName:wl,systemUserInfo:ja}}else return{id:Ln,username:La||Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}async getUserByEmail(Ln,Ta){const ja=await findUserByEmail(Ln,Ta);if(!ja)throw new UserNotFoundError$1(`User with email ${Ln} not found in local database`);const La=ja.lookup("id"),Fa=ja.lookup("firstName"),wl=ja.lookup("lastName");if(define_process_env_default$2.COGNITO_USER_POOL_ID&&define_process_env_default$2.COGNITO_CLIENT_ID)try{const pc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),mc=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),ClientId:this.fetchClientId(),Username:Ln}),gc=await pc.send(mc);return{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:{localUser:ja,cognitoData:{userAttributes:gc.UserAttributes,userCreateDate:gc.UserCreateDate,userLastModifiedDate:gc.UserLastModifiedDate,userStatus:gc.UserStatus,enabled:gc.Enabled,preferredMfaSetting:gc.PreferredMfaSetting,userMFASettingList:gc.UserMFASettingList}}}}catch(pc){return console.log(`Failed to get Cognito user info for email ${Ln}, using local data only:`,{errorName:pc.name,errorMessage:sanitizeErrorMessage(pc.message)}),{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}else return{id:La,username:Ln,firstName:Fa,lastName:wl,systemUserInfo:ja}}async refreshToken(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),La=new InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.fetchClientId(),AuthParameters:{REFRESH_TOKEN:Ln}}),Fa=await ja.send(La);if(!Fa.AuthenticationResult)throw new UnauthorisedError$1("Token refresh failed");const wl=Fa.AuthenticationResult.IdToken,Pl=Fa.AuthenticationResult.AccessToken,pc=Fa.AuthenticationResult.RefreshToken||Ln,gc=JSON.parse(atob(wl.split(".")[1])).email;let Vd=await findUserByEmail(gc,Ta);Vd||(Vd=await ensureUser(gc,"","",Ta));const Wd=Vd.lookup("id");return{sessionId:(await ensureUserSession(Wd,wl,Pl,pc,Ta)).lookup("id"),userId:Wd,authToken:wl,idToken:wl,accessToken:Pl,refreshToken:pc,systemSesionInfo:Fa.AuthenticationResult}}catch(ja){throw logger$3.error(`Refresh token operation failed: ${ja.message}`),ja.name==="NotAuthorizedException"?new UnauthorisedError$1("Invalid or expired refresh token"):(handleCognitoError(ja,"refreshToken"),ja)}}async inviteUser(Ln,Ta,ja,La,Fa,wl,Pl){var pc;try{const mc=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),gc=[{Name:"email",Value:Ln},{Name:"email_verified",Value:"true"},{Name:"given_name",Value:Ta},{Name:"family_name",Value:ja}];La&&La.forEach((Pf,Nf)=>{gc.push({Name:Nf,Value:String(Pf)})});let Vd=!1;try{const Pf=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});await mc.send(Pf),Vd=!0,logger$3.debug(`User ${Ln} already exists, will resend invitation`)}catch(Pf){if(Pf.name!=="UserNotFoundException")throw Pf;logger$3.debug(`User ${Ln} does not exist, will create new user`)}const Wd=new AdminCreateUserCommand(Object.assign({UserPoolId:this.fetchUserPoolId(),Username:Ln,UserAttributes:gc,DesiredDeliveryMediums:["EMAIL"],TemporaryPassword:generateUrlSafePassword$1()},Vd?{MessageAction:"RESEND"}:{}));logger$3.debug(`Attempting to invite user: ${Ln}`);const kf=await mc.send(Wd);if(kf.$metadata.httpStatusCode===200){logger$3.info(`User invitation successful for: ${Ln}`);const Nf=(await ensureUser(Ln,Ta,ja,wl,"Invited")).lookup("id");await ensureUserRoles(Nf,[Fa||"user"],wl);const Eh={email:Ln,firstName:Ta,lastName:ja,invitationId:(pc=kf.User)===null||pc===void 0?void 0:pc.Username,systemInvitationInfo:kf};Pl(Eh)}else throw logger$3.error(`User invitation failed with HTTP status ${kf.$metadata.httpStatusCode}`,{email:Ln,statusCode:kf.$metadata.httpStatusCode}),new BadRequestError$4(`User invitation failed with status ${kf.$metadata.httpStatusCode}`)}catch(mc){if(mc instanceof BadRequestError$4)throw mc;logger$3.error(`User invitation error for ${Ln}:`,{errorName:mc.name,errorMessage:sanitizeErrorMessage(mc.message)}),handleCognitoError(mc,"inviteUser")}}async resendInvitation(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"});try{const wl=new AdminGetUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});await ja.send(wl)}catch(wl){throw wl.name==="UserNotFoundException"?new UserNotFoundError$1(`User ${Ln} not found. Cannot resend invitation.`):wl}const La=new AdminCreateUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln,DesiredDeliveryMediums:["EMAIL"],MessageAction:"RESEND"});logger$3.debug(`Attempting to resend invitation for user: ${Ln}`);const Fa=await ja.send(La);if(Fa.$metadata.httpStatusCode===200)logger$3.info(`Invitation resent successfully for: ${Ln}`);else throw logger$3.error(`Failed to resend invitation with HTTP status ${Fa.$metadata.httpStatusCode}`,{email:Ln,statusCode:Fa.$metadata.httpStatusCode}),new BadRequestError$4(`Failed to resend invitation with status ${Fa.$metadata.httpStatusCode}`)}catch(ja){if(ja instanceof BadRequestError$4||ja instanceof UserNotFoundError$1)throw ja;logger$3.error(`Resend invitation error for ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"resendInvitation")}}async acceptInvitation(Ln,Ta,ja,La){try{const Fa=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2",credentials:fromEnv()}),wl=new InitiateAuthCommand({AuthFlow:"USER_PASSWORD_AUTH",ClientId:this.fetchClientId(),AuthParameters:{USERNAME:Ln,PASSWORD:Ta}}),Pl=await Fa.send(wl);if(Pl.ChallengeName==="NEW_PASSWORD_REQUIRED"){const pc=new RespondToAuthChallengeCommand({ClientId:this.fetchClientId(),ChallengeName:"NEW_PASSWORD_REQUIRED",Session:Pl.Session,ChallengeResponses:{USERNAME:Ln,NEW_PASSWORD:ja}});await Fa.send(pc),logger$3.info(`User invitation accepted successfully for: ${Ln}`)}else throw new Error(`Unexpected challenge: ${Pl.ChallengeName}`)}catch(Fa){logger$3.error(`Accept invitation failed for ${Ln}: ${sanitizeErrorMessage(Fa.message)}`),handleCognitoError(Fa,"acceptInvitation")}}async callback(Ln,Ta,ja){try{if(!isNodeEnv$1)throw new Error("Callback authentication is only supported in Node.js environment");const La=this.fetchConfig("ClientId"),Fa=define_process_env_default$2.AWS_REGION||"us-east-1",wl=define_process_env_default$2.COGNITO_REDIRECT_URI||"http://localhost:3000/auth/callback",pc=`https://${define_process_env_default$2.COGNITO_HOSTED_DOMAIN}.auth.${Fa}.amazoncognito.com/oauth2/token`,mc=new URLSearchParams({grant_type:"authorization_code",client_id:La,code:Ln,redirect_uri:wl});logger$3.debug("Exchanging authorization code for tokens via OAuth2 endpoint"),console.log("te",pc,mc.toString());const gc=await fetch(pc,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:mc.toString()});if(!gc.ok){const tj=await gc.text();throw new Error(`Token exchange failed: ${gc.status} ${tj}`)}const Vd=await gc.json();if(!Vd.access_token||!Vd.id_token||!Vd.refresh_token)throw new Error("Missing required tokens in response");const{access_token:Wd,id_token:kf,refresh_token:Pf}=Vd,Nf=this.decodeJwtPayload(kf),Eh=Nf.email,Em=Nf.given_name||Nf.name||"",qg=Nf.family_name||"",Ug=Nf["cognito:groups"];if(!Eh)throw new Error("Email not found in ID attributes");let Bg=await findUserByEmail(Eh,Ta);Bg||(Bg=await ensureUser(Eh,Em,qg,Ta));const U_=Bg.lookup("id");Ug&&await ensureUserRoles(U_,Ug,Ta);const VC={sessionId:(await ensureUserSession(U_,kf,Wd,Pf,Ta)).lookup("id"),userId:U_,authToken:kf,idToken:kf,accessToken:Wd,refreshToken:Pf,systemSesionInfo:Vd};logger$3.info(`Auth callback successful for user ${Eh}`),ja(VC)}catch(La){console.log(La),logger$3.error(`Auth callback failed: ${sanitizeErrorMessage(La.message)}`),handleCognitoError(La,"callback")}}decodeJwtPayload(Ln){try{const ja=Ln.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),La=decodeURIComponent(atob(ja).split("").map(Fa=>"%"+("00"+Fa.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(La)}catch(Ta){throw logger$3.error(`Failed to decode JWT payload: ${Ta}`),new Error("Invalid JWT token")}}async deleteUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminDeleteUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to delete user: ${Ln}`),await ja.send(La),logger$3.info(`User deleted successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to delete user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"deleteUser")}}async disableUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminDisableUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to disable user: ${Ln}`),await ja.send(La),logger$3.info(`User disabled successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to disable user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"disableUser")}}async enableUser(Ln,Ta){try{const ja=new CognitoIdentityProviderClient({region:define_process_env_default$2.AWS_REGION||"us-west-2"}),La=new AdminEnableUserCommand({UserPoolId:this.fetchUserPoolId(),Username:Ln});logger$3.debug(`Attempting to enable user: ${Ln}`),await ja.send(La),logger$3.info(`User enabled successfully: ${Ln}`)}catch(ja){logger$3.error(`Failed to enable user ${Ln}:`,{errorName:ja.name,errorMessage:sanitizeErrorMessage(ja.message)}),handleCognitoError(ja,"enableUser")}}}const CoreAuthModuleName=makeCoreModuleName$1("auth"),auth=`module ${CoreAuthModuleName}
|
|
30424
30424
|
|
|
30425
30425
|
import "./modules/auth.js" @as Auth
|
|
30426
30426
|
|
|
@@ -34773,10 +34773,10 @@ workflow generateAgentlangResolver {
|
|
|
34773
34773
|
+`).split(`
|
|
34774
34774
|
`)),gc=mc.reduce((Vd,Wd)=>Vd.concat(...Wd),[]);return[mc,gc]}return[[],[]]},[ta]);return reactExports$1.useEffect(()=>{const pc=Ln?.target??defaultDoc,mc=Ln?.actInsideInputWithModifier??!0;if(ta!==null){const gc=kf=>{if(La.current=kf.ctrlKey||kf.metaKey||kf.shiftKey||kf.altKey,(!La.current||La.current&&!mc)&&isInputDOMNode(kf))return!1;const Nf=useKeyOrCode(kf.code,Pl);if(Fa.current.add(kf[Nf]),isMatchingKey(wl,Fa.current,!1)){const Eh=kf.composedPath?.()?.[0]||kf.target,Em=Eh?.nodeName==="BUTTON"||Eh?.nodeName==="A";Ln.preventDefault!==!1&&(La.current||!Em)&&kf.preventDefault(),ja(!0)}},Vd=kf=>{const Pf=useKeyOrCode(kf.code,Pl);isMatchingKey(wl,Fa.current,!0)?(ja(!1),Fa.current.clear()):Fa.current.delete(kf[Pf]),kf.key==="Meta"&&Fa.current.clear(),La.current=!1},Wd=()=>{Fa.current.clear(),ja(!1)};return pc?.addEventListener("keydown",gc),pc?.addEventListener("keyup",Vd),window.addEventListener("blur",Wd),window.addEventListener("contextmenu",Wd),()=>{pc?.removeEventListener("keydown",gc),pc?.removeEventListener("keyup",Vd),window.removeEventListener("blur",Wd),window.removeEventListener("contextmenu",Wd)}}},[ta,ja]),Ta}function isMatchingKey(ta,Ln,Ta){return ta.filter(ja=>Ta||ja.length===Ln.size).some(ja=>ja.every(La=>Ln.has(La)))}function useKeyOrCode(ta,Ln){return Ln.includes(ta)?"code":"key"}const useViewportHelper=()=>{const ta=useStoreApi();return reactExports$1.useMemo(()=>({zoomIn:Ln=>{const{panZoom:Ta}=ta.getState();return Ta?Ta.scaleBy(1.2,{duration:Ln?.duration}):Promise.resolve(!1)},zoomOut:Ln=>{const{panZoom:Ta}=ta.getState();return Ta?Ta.scaleBy(1/1.2,{duration:Ln?.duration}):Promise.resolve(!1)},zoomTo:(Ln,Ta)=>{const{panZoom:ja}=ta.getState();return ja?ja.scaleTo(Ln,{duration:Ta?.duration}):Promise.resolve(!1)},getZoom:()=>ta.getState().transform[2],setViewport:async(Ln,Ta)=>{const{transform:[ja,La,Fa],panZoom:wl}=ta.getState();return wl?(await wl.setViewport({x:Ln.x??ja,y:Ln.y??La,zoom:Ln.zoom??Fa},Ta),Promise.resolve(!0)):Promise.resolve(!1)},getViewport:()=>{const[Ln,Ta,ja]=ta.getState().transform;return{x:Ln,y:Ta,zoom:ja}},setCenter:async(Ln,Ta,ja)=>ta.getState().setCenter(Ln,Ta,ja),fitBounds:async(Ln,Ta)=>{const{width:ja,height:La,minZoom:Fa,maxZoom:wl,panZoom:Pl}=ta.getState(),pc=getViewportForBounds(Ln,ja,La,Fa,wl,Ta?.padding??.1);return Pl?(await Pl.setViewport(pc,{duration:Ta?.duration,ease:Ta?.ease,interpolate:Ta?.interpolate}),Promise.resolve(!0)):Promise.resolve(!1)},screenToFlowPosition:(Ln,Ta={})=>{const{transform:ja,snapGrid:La,snapToGrid:Fa,domNode:wl}=ta.getState();if(!wl)return Ln;const{x:Pl,y:pc}=wl.getBoundingClientRect(),mc={x:Ln.x-Pl,y:Ln.y-pc},gc=Ta.snapGrid??La,Vd=Ta.snapToGrid??Fa;return pointToRendererPoint(mc,ja,Vd,gc)},flowToScreenPosition:Ln=>{const{transform:Ta,domNode:ja}=ta.getState();if(!ja)return Ln;const{x:La,y:Fa}=ja.getBoundingClientRect(),wl=rendererPointToPoint(Ln,Ta);return{x:wl.x+La,y:wl.y+Fa}}}),[])};function applyChanges(ta,Ln){const Ta=[],ja=new Map,La=[];for(const Fa of ta)if(Fa.type==="add"){La.push(Fa);continue}else if(Fa.type==="remove"||Fa.type==="replace")ja.set(Fa.id,[Fa]);else{const wl=ja.get(Fa.id);wl?wl.push(Fa):ja.set(Fa.id,[Fa])}for(const Fa of Ln){const wl=ja.get(Fa.id);if(!wl){Ta.push(Fa);continue}if(wl[0].type==="remove")continue;if(wl[0].type==="replace"){Ta.push({...wl[0].item});continue}const Pl={...Fa};for(const pc of wl)applyChange(pc,Pl);Ta.push(Pl)}return La.length&&La.forEach(Fa=>{Fa.index!==void 0?Ta.splice(Fa.index,0,{...Fa.item}):Ta.push({...Fa.item})}),Ta}function applyChange(ta,Ln){switch(ta.type){case"select":{Ln.selected=ta.selected;break}case"position":{typeof ta.position<"u"&&(Ln.position=ta.position),typeof ta.dragging<"u"&&(Ln.dragging=ta.dragging);break}case"dimensions":{typeof ta.dimensions<"u"&&(Ln.measured??={},Ln.measured.width=ta.dimensions.width,Ln.measured.height=ta.dimensions.height,ta.setAttributes&&((ta.setAttributes===!0||ta.setAttributes==="width")&&(Ln.width=ta.dimensions.width),(ta.setAttributes===!0||ta.setAttributes==="height")&&(Ln.height=ta.dimensions.height))),typeof ta.resizing=="boolean"&&(Ln.resizing=ta.resizing);break}}}function applyNodeChanges(ta,Ln){return applyChanges(ta,Ln)}function applyEdgeChanges(ta,Ln){return applyChanges(ta,Ln)}function createSelectionChange(ta,Ln){return{id:ta,type:"select",selected:Ln}}function getSelectionChanges(ta,Ln=new Set,Ta=!1){const ja=[];for(const[La,Fa]of ta){const wl=Ln.has(La);!(Fa.selected===void 0&&!wl)&&Fa.selected!==wl&&(Ta&&(Fa.selected=wl),ja.push(createSelectionChange(Fa.id,wl)))}return ja}function getElementsDiffChanges({items:ta=[],lookup:Ln}){const Ta=[],ja=new Map(ta.map(La=>[La.id,La]));for(const[La,Fa]of ta.entries()){const wl=Ln.get(Fa.id),Pl=wl?.internals?.userNode??wl;Pl!==void 0&&Pl!==Fa&&Ta.push({id:Fa.id,item:Fa,type:"replace"}),Pl===void 0&&Ta.push({item:Fa,type:"add",index:La})}for(const[La]of Ln)ja.get(La)===void 0&&Ta.push({id:La,type:"remove"});return Ta}function elementToRemoveChange(ta){return{id:ta.id,type:"remove"}}const isNode$2=ta=>isNodeBase(ta),isEdge=ta=>isEdgeBase(ta);function fixedForwardRef(ta){return reactExports$1.forwardRef(ta)}const useIsomorphicLayoutEffect$3=typeof window<"u"?reactExports$1.useLayoutEffect:reactExports$1.useEffect;function useQueue(ta){const[Ln,Ta]=reactExports$1.useState(BigInt(0)),[ja]=reactExports$1.useState(()=>createQueue(()=>Ta(La=>La+BigInt(1))));return useIsomorphicLayoutEffect$3(()=>{const La=ja.get();La.length&&(ta(La),ja.reset())},[Ln]),ja}function createQueue(ta){let Ln=[];return{get:()=>Ln,reset:()=>{Ln=[]},push:Ta=>{Ln.push(Ta),ta()}}}const BatchContext=reactExports$1.createContext(null);function BatchProvider({children:ta}){const Ln=useStoreApi(),Ta=reactExports$1.useCallback(Pl=>{const{nodes:pc=[],setNodes:mc,hasDefaultNodes:gc,onNodesChange:Vd,nodeLookup:Wd,fitViewQueued:kf}=Ln.getState();let Pf=pc;for(const Eh of Pl)Pf=typeof Eh=="function"?Eh(Pf):Eh;const Nf=getElementsDiffChanges({items:Pf,lookup:Wd});gc&&mc(Pf),Nf.length>0?Vd?.(Nf):kf&&window.requestAnimationFrame(()=>{const{fitViewQueued:Eh,nodes:Em,setNodes:qg}=Ln.getState();Eh&&qg(Em)})},[]),ja=useQueue(Ta),La=reactExports$1.useCallback(Pl=>{const{edges:pc=[],setEdges:mc,hasDefaultEdges:gc,onEdgesChange:Vd,edgeLookup:Wd}=Ln.getState();let kf=pc;for(const Pf of Pl)kf=typeof Pf=="function"?Pf(kf):Pf;gc?mc(kf):Vd&&Vd(getElementsDiffChanges({items:kf,lookup:Wd}))},[]),Fa=useQueue(La),wl=reactExports$1.useMemo(()=>({nodeQueue:ja,edgeQueue:Fa}),[]);return jsxRuntimeExports$1.jsx(BatchContext.Provider,{value:wl,children:ta})}function useBatchContext(){const ta=reactExports$1.useContext(BatchContext);if(!ta)throw new Error("useBatchContext must be used within a BatchProvider");return ta}const selector$k=ta=>!!ta.panZoom;function useReactFlow(){const ta=useViewportHelper(),Ln=useStoreApi(),Ta=useBatchContext(),ja=useStore$1(selector$k),La=reactExports$1.useMemo(()=>{const Fa=Vd=>Ln.getState().nodeLookup.get(Vd),wl=Vd=>{Ta.nodeQueue.push(Vd)},Pl=Vd=>{Ta.edgeQueue.push(Vd)},pc=Vd=>{const{nodeLookup:Wd,nodeOrigin:kf}=Ln.getState(),Pf=isNode$2(Vd)?Vd:Wd.get(Vd.id),Nf=Pf.parentId?evaluateAbsolutePosition(Pf.position,Pf.measured,Pf.parentId,Wd,kf):Pf.position,Eh={...Pf,position:Nf,width:Pf.measured?.width??Pf.width,height:Pf.measured?.height??Pf.height};return nodeToRect(Eh)},mc=(Vd,Wd,kf={replace:!1})=>{wl(Pf=>Pf.map(Nf=>{if(Nf.id===Vd){const Eh=typeof Wd=="function"?Wd(Nf):Wd;return kf.replace&&isNode$2(Eh)?Eh:{...Nf,...Eh}}return Nf}))},gc=(Vd,Wd,kf={replace:!1})=>{Pl(Pf=>Pf.map(Nf=>{if(Nf.id===Vd){const Eh=typeof Wd=="function"?Wd(Nf):Wd;return kf.replace&&isEdge(Eh)?Eh:{...Nf,...Eh}}return Nf}))};return{getNodes:()=>Ln.getState().nodes.map(Vd=>({...Vd})),getNode:Vd=>Fa(Vd)?.internals.userNode,getInternalNode:Fa,getEdges:()=>{const{edges:Vd=[]}=Ln.getState();return Vd.map(Wd=>({...Wd}))},getEdge:Vd=>Ln.getState().edgeLookup.get(Vd),setNodes:wl,setEdges:Pl,addNodes:Vd=>{const Wd=Array.isArray(Vd)?Vd:[Vd];Ta.nodeQueue.push(kf=>[...kf,...Wd])},addEdges:Vd=>{const Wd=Array.isArray(Vd)?Vd:[Vd];Ta.edgeQueue.push(kf=>[...kf,...Wd])},toObject:()=>{const{nodes:Vd=[],edges:Wd=[],transform:kf}=Ln.getState(),[Pf,Nf,Eh]=kf;return{nodes:Vd.map(Em=>({...Em})),edges:Wd.map(Em=>({...Em})),viewport:{x:Pf,y:Nf,zoom:Eh}}},deleteElements:async({nodes:Vd=[],edges:Wd=[]})=>{const{nodes:kf,edges:Pf,onNodesDelete:Nf,onEdgesDelete:Eh,triggerNodeChanges:Em,triggerEdgeChanges:qg,onDelete:Ug,onBeforeDelete:Bg}=Ln.getState(),{nodes:U_,edges:B_}=await getElementsToRemove({nodesToRemove:Vd,edgesToRemove:Wd,nodes:kf,edges:Pf,onBeforeDelete:Bg}),VC=B_.length>0,tj=U_.length>0;if(VC){const aB=B_.map(elementToRemoveChange);Eh?.(B_),qg(aB)}if(tj){const aB=U_.map(elementToRemoveChange);Nf?.(U_),Em(aB)}return(tj||VC)&&Ug?.({nodes:U_,edges:B_}),{deletedNodes:U_,deletedEdges:B_}},getIntersectingNodes:(Vd,Wd=!0,kf)=>{const Pf=isRectObject(Vd),Nf=Pf?Vd:pc(Vd),Eh=kf!==void 0;return Nf?(kf||Ln.getState().nodes).filter(Em=>{const qg=Ln.getState().nodeLookup.get(Em.id);if(qg&&!Pf&&(Em.id===Vd.id||!qg.internals.positionAbsolute))return!1;const Ug=nodeToRect(Eh?Em:qg),Bg=getOverlappingArea(Ug,Nf);return Wd&&Bg>0||Bg>=Ug.width*Ug.height||Bg>=Nf.width*Nf.height}):[]},isNodeIntersecting:(Vd,Wd,kf=!0)=>{const Nf=isRectObject(Vd)?Vd:pc(Vd);if(!Nf)return!1;const Eh=getOverlappingArea(Nf,Wd);return kf&&Eh>0||Eh>=Wd.width*Wd.height||Eh>=Nf.width*Nf.height},updateNode:mc,updateNodeData:(Vd,Wd,kf={replace:!1})=>{mc(Vd,Pf=>{const Nf=typeof Wd=="function"?Wd(Pf):Wd;return kf.replace?{...Pf,data:Nf}:{...Pf,data:{...Pf.data,...Nf}}},kf)},updateEdge:gc,updateEdgeData:(Vd,Wd,kf={replace:!1})=>{gc(Vd,Pf=>{const Nf=typeof Wd=="function"?Wd(Pf):Wd;return kf.replace?{...Pf,data:Nf}:{...Pf,data:{...Pf.data,...Nf}}},kf)},getNodesBounds:Vd=>{const{nodeLookup:Wd,nodeOrigin:kf}=Ln.getState();return getNodesBounds(Vd,{nodeLookup:Wd,nodeOrigin:kf})},getHandleConnections:({type:Vd,id:Wd,nodeId:kf})=>Array.from(Ln.getState().connectionLookup.get(`${kf}-${Vd}${Wd?`-${Wd}`:""}`)?.values()??[]),getNodeConnections:({type:Vd,handleId:Wd,nodeId:kf})=>Array.from(Ln.getState().connectionLookup.get(`${kf}${Vd?Wd?`-${Vd}-${Wd}`:`-${Vd}`:""}`)?.values()??[]),fitView:async Vd=>{const Wd=Ln.getState().fitViewResolver??withResolvers();return Ln.setState({fitViewQueued:!0,fitViewOptions:Vd,fitViewResolver:Wd}),Ta.nodeQueue.push(kf=>[...kf]),Wd.promise}}},[]);return reactExports$1.useMemo(()=>({...La,...ta,viewportInitialized:ja}),[ja])}const selected=ta=>ta.selected,win$1=typeof window<"u"?window:void 0;function useGlobalKeyHandler({deleteKeyCode:ta,multiSelectionKeyCode:Ln}){const Ta=useStoreApi(),{deleteElements:ja}=useReactFlow(),La=useKeyPress(ta,{actInsideInputWithModifier:!1}),Fa=useKeyPress(Ln,{target:win$1});reactExports$1.useEffect(()=>{if(La){const{edges:wl,nodes:Pl}=Ta.getState();ja({nodes:Pl.filter(selected),edges:wl.filter(selected)}),Ta.setState({nodesSelectionActive:!1})}},[La]),reactExports$1.useEffect(()=>{Ta.setState({multiSelectionActive:Fa})},[Fa])}function useResizeHandler(ta){const Ln=useStoreApi();reactExports$1.useEffect(()=>{const Ta=()=>{if(!ta.current||!(ta.current.checkVisibility?.()??!0))return!1;const ja=getDimensions$1(ta.current);(ja.height===0||ja.width===0)&&Ln.getState().onError?.("004",errorMessages$3.error004()),Ln.setState({width:ja.width||500,height:ja.height||500})};if(ta.current){Ta(),window.addEventListener("resize",Ta);const ja=new ResizeObserver(()=>Ta());return ja.observe(ta.current),()=>{window.removeEventListener("resize",Ta),ja&&ta.current&&ja.unobserve(ta.current)}}},[])}const containerStyle={position:"absolute",width:"100%",height:"100%",top:0,left:0},selector$j=ta=>({userSelectionActive:ta.userSelectionActive,lib:ta.lib,connectionInProgress:ta.connection.inProgress});function ZoomPane({onPaneContextMenu:ta,zoomOnScroll:Ln=!0,zoomOnPinch:Ta=!0,panOnScroll:ja=!1,panOnScrollSpeed:La=.5,panOnScrollMode:Fa=PanOnScrollMode.Free,zoomOnDoubleClick:wl=!0,panOnDrag:Pl=!0,defaultViewport:pc,translateExtent:mc,minZoom:gc,maxZoom:Vd,zoomActivationKeyCode:Wd,preventScrolling:kf=!0,children:Pf,noWheelClassName:Nf,noPanClassName:Eh,onViewportChange:Em,isControlledViewport:qg,paneClickDistance:Ug,selectionOnDrag:Bg}){const U_=useStoreApi(),B_=reactExports$1.useRef(null),{userSelectionActive:VC,lib:tj,connectionInProgress:aB}=useStore$1(selector$j,shallow$1),r6=useKeyPress(Wd),J2=reactExports$1.useRef();useResizeHandler(B_);const V_=reactExports$1.useCallback(sP=>{Em?.({x:sP[0],y:sP[1],zoom:sP[2]}),qg||U_.setState({transform:sP})},[Em,qg]);return reactExports$1.useEffect(()=>{if(B_.current){J2.current=XYPanZoom({domNode:B_.current,minZoom:gc,maxZoom:Vd,translateExtent:mc,viewport:pc,onDraggingChange:nj=>U_.setState({paneDragging:nj}),onPanZoomStart:(nj,n6)=>{const{onViewportChangeStart:l6,onMoveStart:i6}=U_.getState();i6?.(nj,n6),l6?.(n6)},onPanZoom:(nj,n6)=>{const{onViewportChange:l6,onMove:i6}=U_.getState();i6?.(nj,n6),l6?.(n6)},onPanZoomEnd:(nj,n6)=>{const{onViewportChangeEnd:l6,onMoveEnd:i6}=U_.getState();i6?.(nj,n6),l6?.(n6)}});const{x:sP,y:Q2,zoom:q5}=J2.current.getViewport();return U_.setState({panZoom:J2.current,transform:[sP,Q2,q5],domNode:B_.current.closest(".react-flow")}),()=>{J2.current?.destroy()}}},[]),reactExports$1.useEffect(()=>{J2.current?.update({onPaneContextMenu:ta,zoomOnScroll:Ln,zoomOnPinch:Ta,panOnScroll:ja,panOnScrollSpeed:La,panOnScrollMode:Fa,zoomOnDoubleClick:wl,panOnDrag:Pl,zoomActivationKeyPressed:r6,preventScrolling:kf,noPanClassName:Eh,userSelectionActive:VC,noWheelClassName:Nf,lib:tj,onTransformChange:V_,connectionInProgress:aB,selectionOnDrag:Bg,paneClickDistance:Ug})},[ta,Ln,Ta,ja,La,Fa,wl,Pl,r6,kf,Eh,VC,Nf,tj,V_,aB,Bg,Ug]),jsxRuntimeExports$1.jsx("div",{className:"react-flow__renderer",ref:B_,style:containerStyle,children:Pf})}const selector$i=ta=>({userSelectionActive:ta.userSelectionActive,userSelectionRect:ta.userSelectionRect});function UserSelection(){const{userSelectionActive:ta,userSelectionRect:Ln}=useStore$1(selector$i,shallow$1);return ta&&Ln?jsxRuntimeExports$1.jsx("div",{className:"react-flow__selection react-flow__container",style:{width:Ln.width,height:Ln.height,transform:`translate(${Ln.x}px, ${Ln.y}px)`}}):null}const wrapHandler=(ta,Ln)=>Ta=>{Ta.target===Ln.current&&ta?.(Ta)},selector$h=ta=>({userSelectionActive:ta.userSelectionActive,elementsSelectable:ta.elementsSelectable,connectionInProgress:ta.connection.inProgress,dragging:ta.paneDragging});function Pane({isSelecting:ta,selectionKeyPressed:Ln,selectionMode:Ta=SelectionMode.Full,panOnDrag:ja,paneClickDistance:La,selectionOnDrag:Fa,onSelectionStart:wl,onSelectionEnd:Pl,onPaneClick:pc,onPaneContextMenu:mc,onPaneScroll:gc,onPaneMouseEnter:Vd,onPaneMouseMove:Wd,onPaneMouseLeave:kf,children:Pf}){const Nf=useStoreApi(),{userSelectionActive:Eh,elementsSelectable:Em,dragging:qg,connectionInProgress:Ug}=useStore$1(selector$h,shallow$1),Bg=Em&&(ta||Eh),U_=reactExports$1.useRef(null),B_=reactExports$1.useRef(),VC=reactExports$1.useRef(new Set),tj=reactExports$1.useRef(new Set),aB=reactExports$1.useRef(!1),r6=l6=>{if(aB.current||Ug){aB.current=!1;return}pc?.(l6),Nf.getState().resetSelectedElements(),Nf.setState({nodesSelectionActive:!1})},J2=l6=>{if(Array.isArray(ja)&&ja?.includes(2)){l6.preventDefault();return}mc?.(l6)},V_=gc?l6=>gc(l6):void 0,sP=l6=>{aB.current&&(l6.stopPropagation(),aB.current=!1)},Q2=l6=>{const{domNode:i6}=Nf.getState();if(B_.current=i6?.getBoundingClientRect(),!B_.current)return;const s6=l6.target===U_.current;if(!s6&&!!l6.target.closest(".nokey")||!ta||!(Fa&&s6||Ln)||l6.button!==0||!l6.isPrimary)return;l6.target?.setPointerCapture?.(l6.pointerId),aB.current=!1;const{x:Rpe,y:Xae}=getEventPosition(l6.nativeEvent,B_.current);Nf.setState({userSelectionRect:{width:0,height:0,startX:Rpe,startY:Xae,x:Rpe,y:Xae}}),s6||(l6.stopPropagation(),l6.preventDefault())},q5=l6=>{const{userSelectionRect:i6,transform:s6,nodeLookup:u6,edgeLookup:f6,connectionLookup:Rpe,triggerNodeChanges:Xae,triggerEdgeChanges:g$e,defaultEdgeOptions:n$e,resetSelectedElements:v$e}=Nf.getState();if(!B_.current||!i6)return;const{x:S$e,y:M$e}=getEventPosition(l6.nativeEvent,B_.current),{startX:T$e,startY:nae}=i6;if(!aB.current){const l1e=Ln?0:La;if(Math.hypot(S$e-T$e,M$e-nae)<=l1e)return;v$e(),wl?.(l6)}aB.current=!0;const h$e={startX:T$e,startY:nae,x:S$e<T$e?S$e:T$e,y:M$e<nae?M$e:nae,width:Math.abs(S$e-T$e),height:Math.abs(M$e-nae)},w$e=VC.current,m$e=tj.current;VC.current=new Set(getNodesInside(u6,h$e,s6,Ta===SelectionMode.Partial,!0).map(l1e=>l1e.id)),tj.current=new Set;const K$e=n$e?.selectable??!0;for(const l1e of VC.current){const U$e=Rpe.get(l1e);if(U$e)for(const{edgeId:$1e}of U$e.values()){const C1e=f6.get($1e);C1e&&(C1e.selectable??K$e)&&tj.current.add($1e)}}if(!areSetsEqual(w$e,VC.current)){const l1e=getSelectionChanges(u6,VC.current,!0);Xae(l1e)}if(!areSetsEqual(m$e,tj.current)){const l1e=getSelectionChanges(f6,tj.current);g$e(l1e)}Nf.setState({userSelectionRect:h$e,userSelectionActive:!0,nodesSelectionActive:!1})},nj=l6=>{l6.button===0&&(l6.target?.releasePointerCapture?.(l6.pointerId),!Eh&&l6.target===U_.current&&Nf.getState().userSelectionRect&&r6?.(l6),Nf.setState({userSelectionActive:!1,userSelectionRect:null}),aB.current&&(Pl?.(l6),Nf.setState({nodesSelectionActive:VC.current.size>0})))},n6=ja===!0||Array.isArray(ja)&&ja.includes(0);return jsxRuntimeExports$1.jsxs("div",{className:cc(["react-flow__pane",{draggable:n6,dragging:qg,selection:ta}]),onClick:Bg?void 0:wrapHandler(r6,U_),onContextMenu:wrapHandler(J2,U_),onWheel:wrapHandler(V_,U_),onPointerEnter:Bg?void 0:Vd,onPointerMove:Bg?q5:Wd,onPointerUp:Bg?nj:void 0,onPointerDownCapture:Bg?Q2:void 0,onClickCapture:Bg?sP:void 0,onPointerLeave:kf,ref:U_,style:containerStyle,children:[Pf,jsxRuntimeExports$1.jsx(UserSelection,{})]})}function handleNodeClick({id:ta,store:Ln,unselect:Ta=!1,nodeRef:ja}){const{addSelectedNodes:La,unselectNodesAndEdges:Fa,multiSelectionActive:wl,nodeLookup:Pl,onError:pc}=Ln.getState(),mc=Pl.get(ta);if(!mc){pc?.("012",errorMessages$3.error012(ta));return}Ln.setState({nodesSelectionActive:!1}),mc.selected?(Ta||mc.selected&&wl)&&(Fa({nodes:[mc],edges:[]}),requestAnimationFrame(()=>ja?.current?.blur())):La([ta])}function useDrag({nodeRef:ta,disabled:Ln=!1,noDragClassName:Ta,handleSelector:ja,nodeId:La,isSelectable:Fa,nodeClickDistance:wl}){const Pl=useStoreApi(),[pc,mc]=reactExports$1.useState(!1),gc=reactExports$1.useRef();return reactExports$1.useEffect(()=>{gc.current=XYDrag({getStoreItems:()=>Pl.getState(),onNodeMouseDown:Vd=>{handleNodeClick({id:Vd,store:Pl,nodeRef:ta})},onDragStart:()=>{mc(!0)},onDragStop:()=>{mc(!1)}})},[]),reactExports$1.useEffect(()=>{if(Ln)gc.current?.destroy();else if(ta.current)return gc.current?.update({noDragClassName:Ta,handleSelector:ja,domNode:ta.current,isSelectable:Fa,nodeId:La,nodeClickDistance:wl}),()=>{gc.current?.destroy()}},[Ta,ja,Ln,Fa,ta,La]),pc}const selectedAndDraggable=ta=>Ln=>Ln.selected&&(Ln.draggable||ta&&typeof Ln.draggable>"u");function useMoveSelectedNodes(){const ta=useStoreApi();return reactExports$1.useCallback(Ta=>{const{nodeExtent:ja,snapToGrid:La,snapGrid:Fa,nodesDraggable:wl,onError:Pl,updateNodePositions:pc,nodeLookup:mc,nodeOrigin:gc}=ta.getState(),Vd=new Map,Wd=selectedAndDraggable(wl),kf=La?Fa[0]:5,Pf=La?Fa[1]:5,Nf=Ta.direction.x*kf*Ta.factor,Eh=Ta.direction.y*Pf*Ta.factor;for(const[,Em]of mc){if(!Wd(Em))continue;let qg={x:Em.internals.positionAbsolute.x+Nf,y:Em.internals.positionAbsolute.y+Eh};La&&(qg=snapPosition(qg,Fa));const{position:Ug,positionAbsolute:Bg}=calculateNodePosition({nodeId:Em.id,nextPosition:qg,nodeLookup:mc,nodeExtent:ja,nodeOrigin:gc,onError:Pl});Em.position=Ug,Em.internals.positionAbsolute=Bg,Vd.set(Em.id,Em)}pc(Vd)},[])}const NodeIdContext=reactExports$1.createContext(null),Provider$2=NodeIdContext.Provider;NodeIdContext.Consumer;const useNodeId=()=>reactExports$1.useContext(NodeIdContext),selector$g=ta=>({connectOnClick:ta.connectOnClick,noPanClassName:ta.noPanClassName,rfId:ta.rfId}),connectingSelector=(ta,Ln,Ta)=>ja=>{const{connectionClickStartHandle:La,connectionMode:Fa,connection:wl}=ja,{fromHandle:Pl,toHandle:pc,isValid:mc}=wl,gc=pc?.nodeId===ta&&pc?.id===Ln&&pc?.type===Ta;return{connectingFrom:Pl?.nodeId===ta&&Pl?.id===Ln&&Pl?.type===Ta,connectingTo:gc,clickConnecting:La?.nodeId===ta&&La?.id===Ln&&La?.type===Ta,isPossibleEndHandle:Fa===ConnectionMode.Strict?Pl?.type!==Ta:ta!==Pl?.nodeId||Ln!==Pl?.id,connectionInProcess:!!Pl,clickConnectionInProcess:!!La,valid:gc&&mc}};function HandleComponent({type:ta="source",position:Ln=Position.Top,isValidConnection:Ta,isConnectable:ja=!0,isConnectableStart:La=!0,isConnectableEnd:Fa=!0,id:wl,onConnect:Pl,children:pc,className:mc,onMouseDown:gc,onTouchStart:Vd,...Wd},kf){const Pf=wl||null,Nf=ta==="target",Eh=useStoreApi(),Em=useNodeId(),{connectOnClick:qg,noPanClassName:Ug,rfId:Bg}=useStore$1(selector$g,shallow$1),{connectingFrom:U_,connectingTo:B_,clickConnecting:VC,isPossibleEndHandle:tj,connectionInProcess:aB,clickConnectionInProcess:r6,valid:J2}=useStore$1(connectingSelector(Em,Pf,ta),shallow$1);Em||Eh.getState().onError?.("010",errorMessages$3.error010());const V_=q5=>{const{defaultEdgeOptions:nj,onConnect:n6,hasDefaultEdges:l6}=Eh.getState(),i6={...nj,...q5};if(l6){const{edges:s6,setEdges:u6}=Eh.getState();u6(addEdge(i6,s6))}n6?.(i6),Pl?.(i6)},sP=q5=>{if(!Em)return;const nj=isMouseEvent(q5.nativeEvent);if(La&&(nj&&q5.button===0||!nj)){const n6=Eh.getState();XYHandle.onPointerDown(q5.nativeEvent,{handleDomNode:q5.currentTarget,autoPanOnConnect:n6.autoPanOnConnect,connectionMode:n6.connectionMode,connectionRadius:n6.connectionRadius,domNode:n6.domNode,nodeLookup:n6.nodeLookup,lib:n6.lib,isTarget:Nf,handleId:Pf,nodeId:Em,flowId:n6.rfId,panBy:n6.panBy,cancelConnection:n6.cancelConnection,onConnectStart:n6.onConnectStart,onConnectEnd:n6.onConnectEnd,updateConnection:n6.updateConnection,onConnect:V_,isValidConnection:Ta||n6.isValidConnection,getTransform:()=>Eh.getState().transform,getFromHandle:()=>Eh.getState().connection.fromHandle,autoPanSpeed:n6.autoPanSpeed,dragThreshold:n6.connectionDragThreshold})}nj?gc?.(q5):Vd?.(q5)},Q2=q5=>{const{onClickConnectStart:nj,onClickConnectEnd:n6,connectionClickStartHandle:l6,connectionMode:i6,isValidConnection:s6,lib:u6,rfId:f6,nodeLookup:Rpe,connection:Xae}=Eh.getState();if(!Em||!l6&&!La)return;if(!l6){nj?.(q5.nativeEvent,{nodeId:Em,handleId:Pf,handleType:ta}),Eh.setState({connectionClickStartHandle:{nodeId:Em,type:ta,id:Pf}});return}const g$e=getHostForElement(q5.target),n$e=Ta||s6,{connection:v$e,isValid:S$e}=XYHandle.isValid(q5.nativeEvent,{handle:{nodeId:Em,id:Pf,type:ta},connectionMode:i6,fromNodeId:l6.nodeId,fromHandleId:l6.id||null,fromType:l6.type,isValidConnection:n$e,flowId:f6,doc:g$e,lib:u6,nodeLookup:Rpe});S$e&&v$e&&V_(v$e);const M$e=structuredClone(Xae);delete M$e.inProgress,M$e.toPosition=M$e.toHandle?M$e.toHandle.position:null,n6?.(q5,M$e),Eh.setState({connectionClickStartHandle:null})};return jsxRuntimeExports$1.jsx("div",{"data-handleid":Pf,"data-nodeid":Em,"data-handlepos":Ln,"data-id":`${Bg}-${Em}-${Pf}-${ta}`,className:cc(["react-flow__handle",`react-flow__handle-${Ln}`,"nodrag",Ug,mc,{source:!Nf,target:Nf,connectable:ja,connectablestart:La,connectableend:Fa,clickconnecting:VC,connectingfrom:U_,connectingto:B_,valid:J2,connectionindicator:ja&&(!aB||tj)&&(aB||r6?Fa:La)}]),onMouseDown:sP,onTouchStart:sP,onClick:qg?Q2:void 0,ref:kf,...Wd,children:pc})}const Handle=reactExports$1.memo(fixedForwardRef(HandleComponent));function InputNode({data:ta,isConnectable:Ln,sourcePosition:Ta=Position.Bottom}){return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[ta?.label,jsxRuntimeExports$1.jsx(Handle,{type:"source",position:Ta,isConnectable:Ln})]})}function DefaultNode({data:ta,isConnectable:Ln,targetPosition:Ta=Position.Top,sourcePosition:ja=Position.Bottom}){return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(Handle,{type:"target",position:Ta,isConnectable:Ln}),ta?.label,jsxRuntimeExports$1.jsx(Handle,{type:"source",position:ja,isConnectable:Ln})]})}function GroupNode(){return null}function OutputNode({data:ta,isConnectable:Ln,targetPosition:Ta=Position.Top}){return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(Handle,{type:"target",position:Ta,isConnectable:Ln}),ta?.label]})}const arrowKeyDiffs={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},builtinNodeTypes={input:InputNode,default:DefaultNode,output:OutputNode,group:GroupNode};function getNodeInlineStyleDimensions(ta){return ta.internals.handleBounds===void 0?{width:ta.width??ta.initialWidth??ta.style?.width,height:ta.height??ta.initialHeight??ta.style?.height}:{width:ta.width??ta.style?.width,height:ta.height??ta.style?.height}}const selector$f=ta=>{const{width:Ln,height:Ta,x:ja,y:La}=getInternalNodesBounds(ta.nodeLookup,{filter:Fa=>!!Fa.selected});return{width:isNumeric(Ln)?Ln:null,height:isNumeric(Ta)?Ta:null,userSelectionActive:ta.userSelectionActive,transformString:`translate(${ta.transform[0]}px,${ta.transform[1]}px) scale(${ta.transform[2]}) translate(${ja}px,${La}px)`}};function NodesSelection({onSelectionContextMenu:ta,noPanClassName:Ln,disableKeyboardA11y:Ta}){const ja=useStoreApi(),{width:La,height:Fa,transformString:wl,userSelectionActive:Pl}=useStore$1(selector$f,shallow$1),pc=useMoveSelectedNodes(),mc=reactExports$1.useRef(null);if(reactExports$1.useEffect(()=>{Ta||mc.current?.focus({preventScroll:!0})},[Ta]),useDrag({nodeRef:mc}),Pl||!La||!Fa)return null;const gc=ta?Wd=>{const kf=ja.getState().nodes.filter(Pf=>Pf.selected);ta(Wd,kf)}:void 0,Vd=Wd=>{Object.prototype.hasOwnProperty.call(arrowKeyDiffs,Wd.key)&&(Wd.preventDefault(),pc({direction:arrowKeyDiffs[Wd.key],factor:Wd.shiftKey?4:1}))};return jsxRuntimeExports$1.jsx("div",{className:cc(["react-flow__nodesselection","react-flow__container",Ln]),style:{transform:wl},children:jsxRuntimeExports$1.jsx("div",{ref:mc,className:"react-flow__nodesselection-rect",onContextMenu:gc,tabIndex:Ta?void 0:-1,onKeyDown:Ta?void 0:Vd,style:{width:La,height:Fa}})})}const win=typeof window<"u"?window:void 0,selector$e=ta=>({nodesSelectionActive:ta.nodesSelectionActive,userSelectionActive:ta.userSelectionActive});function FlowRendererComponent({children:ta,onPaneClick:Ln,onPaneMouseEnter:Ta,onPaneMouseMove:ja,onPaneMouseLeave:La,onPaneContextMenu:Fa,onPaneScroll:wl,paneClickDistance:Pl,deleteKeyCode:pc,selectionKeyCode:mc,selectionOnDrag:gc,selectionMode:Vd,onSelectionStart:Wd,onSelectionEnd:kf,multiSelectionKeyCode:Pf,panActivationKeyCode:Nf,zoomActivationKeyCode:Eh,elementsSelectable:Em,zoomOnScroll:qg,zoomOnPinch:Ug,panOnScroll:Bg,panOnScrollSpeed:U_,panOnScrollMode:B_,zoomOnDoubleClick:VC,panOnDrag:tj,defaultViewport:aB,translateExtent:r6,minZoom:J2,maxZoom:V_,preventScrolling:sP,onSelectionContextMenu:Q2,noWheelClassName:q5,noPanClassName:nj,disableKeyboardA11y:n6,onViewportChange:l6,isControlledViewport:i6}){const{nodesSelectionActive:s6,userSelectionActive:u6}=useStore$1(selector$e),f6=useKeyPress(mc,{target:win}),Rpe=useKeyPress(Nf,{target:win}),Xae=Rpe||tj,g$e=Rpe||Bg,n$e=gc&&Xae!==!0,v$e=f6||u6||n$e;return useGlobalKeyHandler({deleteKeyCode:pc,multiSelectionKeyCode:Pf}),jsxRuntimeExports$1.jsx(ZoomPane,{onPaneContextMenu:Fa,elementsSelectable:Em,zoomOnScroll:qg,zoomOnPinch:Ug,panOnScroll:g$e,panOnScrollSpeed:U_,panOnScrollMode:B_,zoomOnDoubleClick:VC,panOnDrag:!f6&&Xae,defaultViewport:aB,translateExtent:r6,minZoom:J2,maxZoom:V_,zoomActivationKeyCode:Eh,preventScrolling:sP,noWheelClassName:q5,noPanClassName:nj,onViewportChange:l6,isControlledViewport:i6,paneClickDistance:Pl,selectionOnDrag:n$e,children:jsxRuntimeExports$1.jsxs(Pane,{onSelectionStart:Wd,onSelectionEnd:kf,onPaneClick:Ln,onPaneMouseEnter:Ta,onPaneMouseMove:ja,onPaneMouseLeave:La,onPaneContextMenu:Fa,onPaneScroll:wl,panOnDrag:Xae,isSelecting:!!v$e,selectionMode:Vd,selectionKeyPressed:f6,paneClickDistance:Pl,selectionOnDrag:n$e,children:[ta,s6&&jsxRuntimeExports$1.jsx(NodesSelection,{onSelectionContextMenu:Q2,noPanClassName:nj,disableKeyboardA11y:n6})]})})}FlowRendererComponent.displayName="FlowRenderer";const FlowRenderer=reactExports$1.memo(FlowRendererComponent),selector$d=ta=>Ln=>ta?getNodesInside(Ln.nodeLookup,{x:0,y:0,width:Ln.width,height:Ln.height},Ln.transform,!0).map(Ta=>Ta.id):Array.from(Ln.nodeLookup.keys());function useVisibleNodeIds(ta){return useStore$1(reactExports$1.useCallback(selector$d(ta),[ta]),shallow$1)}const selector$c=ta=>ta.updateNodeInternals;function useResizeObserver$1(){const ta=useStore$1(selector$c),[Ln]=reactExports$1.useState(()=>typeof ResizeObserver>"u"?null:new ResizeObserver(Ta=>{const ja=new Map;Ta.forEach(La=>{const Fa=La.target.getAttribute("data-id");ja.set(Fa,{id:Fa,nodeElement:La.target,force:!0})}),ta(ja)}));return reactExports$1.useEffect(()=>()=>{Ln?.disconnect()},[Ln]),Ln}function useNodeObserver({node:ta,nodeType:Ln,hasDimensions:Ta,resizeObserver:ja}){const La=useStoreApi(),Fa=reactExports$1.useRef(null),wl=reactExports$1.useRef(null),Pl=reactExports$1.useRef(ta.sourcePosition),pc=reactExports$1.useRef(ta.targetPosition),mc=reactExports$1.useRef(Ln),gc=Ta&&!!ta.internals.handleBounds;return reactExports$1.useEffect(()=>{Fa.current&&!ta.hidden&&(!gc||wl.current!==Fa.current)&&(wl.current&&ja?.unobserve(wl.current),ja?.observe(Fa.current),wl.current=Fa.current)},[gc,ta.hidden]),reactExports$1.useEffect(()=>()=>{wl.current&&(ja?.unobserve(wl.current),wl.current=null)},[]),reactExports$1.useEffect(()=>{if(Fa.current){const Vd=mc.current!==Ln,Wd=Pl.current!==ta.sourcePosition,kf=pc.current!==ta.targetPosition;(Vd||Wd||kf)&&(mc.current=Ln,Pl.current=ta.sourcePosition,pc.current=ta.targetPosition,La.getState().updateNodeInternals(new Map([[ta.id,{id:ta.id,nodeElement:Fa.current,force:!0}]])))}},[ta.id,Ln,ta.sourcePosition,ta.targetPosition]),Fa}function NodeWrapper({id:ta,onClick:Ln,onMouseEnter:Ta,onMouseMove:ja,onMouseLeave:La,onContextMenu:Fa,onDoubleClick:wl,nodesDraggable:Pl,elementsSelectable:pc,nodesConnectable:mc,nodesFocusable:gc,resizeObserver:Vd,noDragClassName:Wd,noPanClassName:kf,disableKeyboardA11y:Pf,rfId:Nf,nodeTypes:Eh,nodeClickDistance:Em,onError:qg}){const{node:Ug,internals:Bg,isParent:U_}=useStore$1(S$e=>{const M$e=S$e.nodeLookup.get(ta),T$e=S$e.parentLookup.has(ta);return{node:M$e,internals:M$e.internals,isParent:T$e}},shallow$1);let B_=Ug.type||"default",VC=Eh?.[B_]||builtinNodeTypes[B_];VC===void 0&&(qg?.("003",errorMessages$3.error003(B_)),B_="default",VC=Eh?.default||builtinNodeTypes.default);const tj=!!(Ug.draggable||Pl&&typeof Ug.draggable>"u"),aB=!!(Ug.selectable||pc&&typeof Ug.selectable>"u"),r6=!!(Ug.connectable||mc&&typeof Ug.connectable>"u"),J2=!!(Ug.focusable||gc&&typeof Ug.focusable>"u"),V_=useStoreApi(),sP=nodeHasDimensions(Ug),Q2=useNodeObserver({node:Ug,nodeType:B_,hasDimensions:sP,resizeObserver:Vd}),q5=useDrag({nodeRef:Q2,disabled:Ug.hidden||!tj,noDragClassName:Wd,handleSelector:Ug.dragHandle,nodeId:ta,isSelectable:aB,nodeClickDistance:Em}),nj=useMoveSelectedNodes();if(Ug.hidden)return null;const n6=getNodeDimensions(Ug),l6=getNodeInlineStyleDimensions(Ug),i6=aB||tj||Ln||Ta||ja||La,s6=Ta?S$e=>Ta(S$e,{...Bg.userNode}):void 0,u6=ja?S$e=>ja(S$e,{...Bg.userNode}):void 0,f6=La?S$e=>La(S$e,{...Bg.userNode}):void 0,Rpe=Fa?S$e=>Fa(S$e,{...Bg.userNode}):void 0,Xae=wl?S$e=>wl(S$e,{...Bg.userNode}):void 0,g$e=S$e=>{const{selectNodesOnDrag:M$e,nodeDragThreshold:T$e}=V_.getState();aB&&(!M$e||!tj||T$e>0)&&handleNodeClick({id:ta,store:V_,nodeRef:Q2}),Ln&&Ln(S$e,{...Bg.userNode})},n$e=S$e=>{if(!(isInputDOMNode(S$e.nativeEvent)||Pf)){if(elementSelectionKeys.includes(S$e.key)&&aB){const M$e=S$e.key==="Escape";handleNodeClick({id:ta,store:V_,unselect:M$e,nodeRef:Q2})}else if(tj&&Ug.selected&&Object.prototype.hasOwnProperty.call(arrowKeyDiffs,S$e.key)){S$e.preventDefault();const{ariaLabelConfig:M$e}=V_.getState();V_.setState({ariaLiveMessage:M$e["node.a11yDescription.ariaLiveMessage"]({direction:S$e.key.replace("Arrow","").toLowerCase(),x:~~Bg.positionAbsolute.x,y:~~Bg.positionAbsolute.y})}),nj({direction:arrowKeyDiffs[S$e.key],factor:S$e.shiftKey?4:1})}}},v$e=()=>{if(Pf||!Q2.current?.matches(":focus-visible"))return;const{transform:S$e,width:M$e,height:T$e,autoPanOnNodeFocus:nae,setCenter:h$e}=V_.getState();if(!nae)return;getNodesInside(new Map([[ta,Ug]]),{x:0,y:0,width:M$e,height:T$e},S$e,!0).length>0||h$e(Ug.position.x+n6.width/2,Ug.position.y+n6.height/2,{zoom:S$e[2]})};return jsxRuntimeExports$1.jsx("div",{className:cc(["react-flow__node",`react-flow__node-${B_}`,{[kf]:tj},Ug.className,{selected:Ug.selected,selectable:aB,parent:U_,draggable:tj,dragging:q5}]),ref:Q2,style:{zIndex:Bg.z,transform:`translate(${Bg.positionAbsolute.x}px,${Bg.positionAbsolute.y}px)`,pointerEvents:i6?"all":"none",visibility:sP?"visible":"hidden",...Ug.style,...l6},"data-id":ta,"data-testid":`rf__node-${ta}`,onMouseEnter:s6,onMouseMove:u6,onMouseLeave:f6,onContextMenu:Rpe,onClick:g$e,onDoubleClick:Xae,onKeyDown:J2?n$e:void 0,tabIndex:J2?0:void 0,onFocus:J2?v$e:void 0,role:Ug.ariaRole??(J2?"group":void 0),"aria-roledescription":"node","aria-describedby":Pf?void 0:`${ARIA_NODE_DESC_KEY}-${Nf}`,"aria-label":Ug.ariaLabel,...Ug.domAttributes,children:jsxRuntimeExports$1.jsx(Provider$2,{value:ta,children:jsxRuntimeExports$1.jsx(VC,{id:ta,data:Ug.data,type:B_,positionAbsoluteX:Bg.positionAbsolute.x,positionAbsoluteY:Bg.positionAbsolute.y,selected:Ug.selected??!1,selectable:aB,draggable:tj,deletable:Ug.deletable??!0,isConnectable:r6,sourcePosition:Ug.sourcePosition,targetPosition:Ug.targetPosition,dragging:q5,dragHandle:Ug.dragHandle,zIndex:Bg.z,parentId:Ug.parentId,...n6})})})}var NodeWrapper$1=reactExports$1.memo(NodeWrapper);const selector$b=ta=>({nodesDraggable:ta.nodesDraggable,nodesConnectable:ta.nodesConnectable,nodesFocusable:ta.nodesFocusable,elementsSelectable:ta.elementsSelectable,onError:ta.onError});function NodeRendererComponent(ta){const{nodesDraggable:Ln,nodesConnectable:Ta,nodesFocusable:ja,elementsSelectable:La,onError:Fa}=useStore$1(selector$b,shallow$1),wl=useVisibleNodeIds(ta.onlyRenderVisibleElements),Pl=useResizeObserver$1();return jsxRuntimeExports$1.jsx("div",{className:"react-flow__nodes",style:containerStyle,children:wl.map(pc=>jsxRuntimeExports$1.jsx(NodeWrapper$1,{id:pc,nodeTypes:ta.nodeTypes,nodeExtent:ta.nodeExtent,onClick:ta.onNodeClick,onMouseEnter:ta.onNodeMouseEnter,onMouseMove:ta.onNodeMouseMove,onMouseLeave:ta.onNodeMouseLeave,onContextMenu:ta.onNodeContextMenu,onDoubleClick:ta.onNodeDoubleClick,noDragClassName:ta.noDragClassName,noPanClassName:ta.noPanClassName,rfId:ta.rfId,disableKeyboardA11y:ta.disableKeyboardA11y,resizeObserver:Pl,nodesDraggable:Ln,nodesConnectable:Ta,nodesFocusable:ja,elementsSelectable:La,nodeClickDistance:ta.nodeClickDistance,onError:Fa},pc))})}NodeRendererComponent.displayName="NodeRenderer";const NodeRenderer=reactExports$1.memo(NodeRendererComponent);function useVisibleEdgeIds(ta){return useStore$1(reactExports$1.useCallback(Ta=>{if(!ta)return Ta.edges.map(La=>La.id);const ja=[];if(Ta.width&&Ta.height)for(const La of Ta.edges){const Fa=Ta.nodeLookup.get(La.source),wl=Ta.nodeLookup.get(La.target);Fa&&wl&&isEdgeVisible({sourceNode:Fa,targetNode:wl,width:Ta.width,height:Ta.height,transform:Ta.transform})&&ja.push(La.id)}return ja},[ta]),shallow$1)}const ArrowSymbol=({color:ta="none",strokeWidth:Ln=1})=>{const Ta={strokeWidth:Ln,...ta&&{stroke:ta}};return jsxRuntimeExports$1.jsx("polyline",{className:"arrow",style:Ta,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},ArrowClosedSymbol=({color:ta="none",strokeWidth:Ln=1})=>{const Ta={strokeWidth:Ln,...ta&&{stroke:ta,fill:ta}};return jsxRuntimeExports$1.jsx("polyline",{className:"arrowclosed",style:Ta,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})},MarkerSymbols={[MarkerType.Arrow]:ArrowSymbol,[MarkerType.ArrowClosed]:ArrowClosedSymbol};function useMarkerSymbol(ta){const Ln=useStoreApi();return reactExports$1.useMemo(()=>Object.prototype.hasOwnProperty.call(MarkerSymbols,ta)?MarkerSymbols[ta]:(Ln.getState().onError?.("009",errorMessages$3.error009(ta)),null),[ta])}const Marker=({id:ta,type:Ln,color:Ta,width:ja=12.5,height:La=12.5,markerUnits:Fa="strokeWidth",strokeWidth:wl,orient:Pl="auto-start-reverse"})=>{const pc=useMarkerSymbol(Ln);return pc?jsxRuntimeExports$1.jsx("marker",{className:"react-flow__arrowhead",id:ta,markerWidth:`${ja}`,markerHeight:`${La}`,viewBox:"-10 -10 20 20",markerUnits:Fa,orient:Pl,refX:"0",refY:"0",children:jsxRuntimeExports$1.jsx(pc,{color:Ta,strokeWidth:wl})}):null},MarkerDefinitions=({defaultColor:ta,rfId:Ln})=>{const Ta=useStore$1(Fa=>Fa.edges),ja=useStore$1(Fa=>Fa.defaultEdgeOptions),La=reactExports$1.useMemo(()=>createMarkerIds(Ta,{id:Ln,defaultColor:ta,defaultMarkerStart:ja?.markerStart,defaultMarkerEnd:ja?.markerEnd}),[Ta,ja,Ln,ta]);return La.length?jsxRuntimeExports$1.jsx("svg",{className:"react-flow__marker","aria-hidden":"true",children:jsxRuntimeExports$1.jsx("defs",{children:La.map(Fa=>jsxRuntimeExports$1.jsx(Marker,{id:Fa.id,type:Fa.type,color:Fa.color,width:Fa.width,height:Fa.height,markerUnits:Fa.markerUnits,strokeWidth:Fa.strokeWidth,orient:Fa.orient},Fa.id))})}):null};MarkerDefinitions.displayName="MarkerDefinitions";var MarkerDefinitions$1=reactExports$1.memo(MarkerDefinitions);function EdgeTextComponent({x:ta,y:Ln,label:Ta,labelStyle:ja,labelShowBg:La=!0,labelBgStyle:Fa,labelBgPadding:wl=[2,4],labelBgBorderRadius:Pl=2,children:pc,className:mc,...gc}){const[Vd,Wd]=reactExports$1.useState({x:1,y:0,width:0,height:0}),kf=cc(["react-flow__edge-textwrapper",mc]),Pf=reactExports$1.useRef(null);return reactExports$1.useEffect(()=>{if(Pf.current){const Nf=Pf.current.getBBox();Wd({x:Nf.x,y:Nf.y,width:Nf.width,height:Nf.height})}},[Ta]),Ta?jsxRuntimeExports$1.jsxs("g",{transform:`translate(${ta-Vd.width/2} ${Ln-Vd.height/2})`,className:kf,visibility:Vd.width?"visible":"hidden",...gc,children:[La&&jsxRuntimeExports$1.jsx("rect",{width:Vd.width+2*wl[0],x:-wl[0],y:-wl[1],height:Vd.height+2*wl[1],className:"react-flow__edge-textbg",style:Fa,rx:Pl,ry:Pl}),jsxRuntimeExports$1.jsx("text",{className:"react-flow__edge-text",y:Vd.height/2,dy:"0.3em",ref:Pf,style:ja,children:Ta}),pc]}):null}EdgeTextComponent.displayName="EdgeText";const EdgeText=reactExports$1.memo(EdgeTextComponent);function BaseEdge({path:ta,labelX:Ln,labelY:Ta,label:ja,labelStyle:La,labelShowBg:Fa,labelBgStyle:wl,labelBgPadding:Pl,labelBgBorderRadius:pc,interactionWidth:mc=20,...gc}){return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("path",{...gc,d:ta,fill:"none",className:cc(["react-flow__edge-path",gc.className])}),mc?jsxRuntimeExports$1.jsx("path",{d:ta,fill:"none",strokeOpacity:0,strokeWidth:mc,className:"react-flow__edge-interaction"}):null,ja&&isNumeric(Ln)&&isNumeric(Ta)?jsxRuntimeExports$1.jsx(EdgeText,{x:Ln,y:Ta,label:ja,labelStyle:La,labelShowBg:Fa,labelBgStyle:wl,labelBgPadding:Pl,labelBgBorderRadius:pc}):null]})}function getControl({pos:ta,x1:Ln,y1:Ta,x2:ja,y2:La}){return ta===Position.Left||ta===Position.Right?[.5*(Ln+ja),Ta]:[Ln,.5*(Ta+La)]}function getSimpleBezierPath({sourceX:ta,sourceY:Ln,sourcePosition:Ta=Position.Bottom,targetX:ja,targetY:La,targetPosition:Fa=Position.Top}){const[wl,Pl]=getControl({pos:Ta,x1:ta,y1:Ln,x2:ja,y2:La}),[pc,mc]=getControl({pos:Fa,x1:ja,y1:La,x2:ta,y2:Ln}),[gc,Vd,Wd,kf]=getBezierEdgeCenter({sourceX:ta,sourceY:Ln,targetX:ja,targetY:La,sourceControlX:wl,sourceControlY:Pl,targetControlX:pc,targetControlY:mc});return[`M${ta},${Ln} C${wl},${Pl} ${pc},${mc} ${ja},${La}`,gc,Vd,Wd,kf]}function createSimpleBezierEdge(ta){return reactExports$1.memo(({id:Ln,sourceX:Ta,sourceY:ja,targetX:La,targetY:Fa,sourcePosition:wl,targetPosition:Pl,label:pc,labelStyle:mc,labelShowBg:gc,labelBgStyle:Vd,labelBgPadding:Wd,labelBgBorderRadius:kf,style:Pf,markerEnd:Nf,markerStart:Eh,interactionWidth:Em})=>{const[qg,Ug,Bg]=getSimpleBezierPath({sourceX:Ta,sourceY:ja,sourcePosition:wl,targetX:La,targetY:Fa,targetPosition:Pl}),U_=ta.isInternal?void 0:Ln;return jsxRuntimeExports$1.jsx(BaseEdge,{id:U_,path:qg,labelX:Ug,labelY:Bg,label:pc,labelStyle:mc,labelShowBg:gc,labelBgStyle:Vd,labelBgPadding:Wd,labelBgBorderRadius:kf,style:Pf,markerEnd:Nf,markerStart:Eh,interactionWidth:Em})})}const SimpleBezierEdge=createSimpleBezierEdge({isInternal:!1}),SimpleBezierEdgeInternal=createSimpleBezierEdge({isInternal:!0});SimpleBezierEdge.displayName="SimpleBezierEdge";SimpleBezierEdgeInternal.displayName="SimpleBezierEdgeInternal";function createSmoothStepEdge(ta){return reactExports$1.memo(({id:Ln,sourceX:Ta,sourceY:ja,targetX:La,targetY:Fa,label:wl,labelStyle:Pl,labelShowBg:pc,labelBgStyle:mc,labelBgPadding:gc,labelBgBorderRadius:Vd,style:Wd,sourcePosition:kf=Position.Bottom,targetPosition:Pf=Position.Top,markerEnd:Nf,markerStart:Eh,pathOptions:Em,interactionWidth:qg})=>{const[Ug,Bg,U_]=getSmoothStepPath({sourceX:Ta,sourceY:ja,sourcePosition:kf,targetX:La,targetY:Fa,targetPosition:Pf,borderRadius:Em?.borderRadius,offset:Em?.offset,stepPosition:Em?.stepPosition}),B_=ta.isInternal?void 0:Ln;return jsxRuntimeExports$1.jsx(BaseEdge,{id:B_,path:Ug,labelX:Bg,labelY:U_,label:wl,labelStyle:Pl,labelShowBg:pc,labelBgStyle:mc,labelBgPadding:gc,labelBgBorderRadius:Vd,style:Wd,markerEnd:Nf,markerStart:Eh,interactionWidth:qg})})}const SmoothStepEdge=createSmoothStepEdge({isInternal:!1}),SmoothStepEdgeInternal=createSmoothStepEdge({isInternal:!0});SmoothStepEdge.displayName="SmoothStepEdge";SmoothStepEdgeInternal.displayName="SmoothStepEdgeInternal";function createStepEdge(ta){return reactExports$1.memo(({id:Ln,...Ta})=>{const ja=ta.isInternal?void 0:Ln;return jsxRuntimeExports$1.jsx(SmoothStepEdge,{...Ta,id:ja,pathOptions:reactExports$1.useMemo(()=>({borderRadius:0,offset:Ta.pathOptions?.offset}),[Ta.pathOptions?.offset])})})}const StepEdge=createStepEdge({isInternal:!1}),StepEdgeInternal=createStepEdge({isInternal:!0});StepEdge.displayName="StepEdge";StepEdgeInternal.displayName="StepEdgeInternal";function createStraightEdge(ta){return reactExports$1.memo(({id:Ln,sourceX:Ta,sourceY:ja,targetX:La,targetY:Fa,label:wl,labelStyle:Pl,labelShowBg:pc,labelBgStyle:mc,labelBgPadding:gc,labelBgBorderRadius:Vd,style:Wd,markerEnd:kf,markerStart:Pf,interactionWidth:Nf})=>{const[Eh,Em,qg]=getStraightPath({sourceX:Ta,sourceY:ja,targetX:La,targetY:Fa}),Ug=ta.isInternal?void 0:Ln;return jsxRuntimeExports$1.jsx(BaseEdge,{id:Ug,path:Eh,labelX:Em,labelY:qg,label:wl,labelStyle:Pl,labelShowBg:pc,labelBgStyle:mc,labelBgPadding:gc,labelBgBorderRadius:Vd,style:Wd,markerEnd:kf,markerStart:Pf,interactionWidth:Nf})})}const StraightEdge=createStraightEdge({isInternal:!1}),StraightEdgeInternal=createStraightEdge({isInternal:!0});StraightEdge.displayName="StraightEdge";StraightEdgeInternal.displayName="StraightEdgeInternal";function createBezierEdge(ta){return reactExports$1.memo(({id:Ln,sourceX:Ta,sourceY:ja,targetX:La,targetY:Fa,sourcePosition:wl=Position.Bottom,targetPosition:Pl=Position.Top,label:pc,labelStyle:mc,labelShowBg:gc,labelBgStyle:Vd,labelBgPadding:Wd,labelBgBorderRadius:kf,style:Pf,markerEnd:Nf,markerStart:Eh,pathOptions:Em,interactionWidth:qg})=>{const[Ug,Bg,U_]=getBezierPath({sourceX:Ta,sourceY:ja,sourcePosition:wl,targetX:La,targetY:Fa,targetPosition:Pl,curvature:Em?.curvature}),B_=ta.isInternal?void 0:Ln;return jsxRuntimeExports$1.jsx(BaseEdge,{id:B_,path:Ug,labelX:Bg,labelY:U_,label:pc,labelStyle:mc,labelShowBg:gc,labelBgStyle:Vd,labelBgPadding:Wd,labelBgBorderRadius:kf,style:Pf,markerEnd:Nf,markerStart:Eh,interactionWidth:qg})})}const BezierEdge=createBezierEdge({isInternal:!1}),BezierEdgeInternal=createBezierEdge({isInternal:!0});BezierEdge.displayName="BezierEdge";BezierEdgeInternal.displayName="BezierEdgeInternal";const builtinEdgeTypes={default:BezierEdgeInternal,straight:StraightEdgeInternal,step:StepEdgeInternal,smoothstep:SmoothStepEdgeInternal,simplebezier:SimpleBezierEdgeInternal},nullPosition={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},shiftX=(ta,Ln,Ta)=>Ta===Position.Left?ta-Ln:Ta===Position.Right?ta+Ln:ta,shiftY=(ta,Ln,Ta)=>Ta===Position.Top?ta-Ln:Ta===Position.Bottom?ta+Ln:ta,EdgeUpdaterClassName="react-flow__edgeupdater";function EdgeAnchor({position:ta,centerX:Ln,centerY:Ta,radius:ja=10,onMouseDown:La,onMouseEnter:Fa,onMouseOut:wl,type:Pl}){return jsxRuntimeExports$1.jsx("circle",{onMouseDown:La,onMouseEnter:Fa,onMouseOut:wl,className:cc([EdgeUpdaterClassName,`${EdgeUpdaterClassName}-${Pl}`]),cx:shiftX(Ln,ja,ta),cy:shiftY(Ta,ja,ta),r:ja,stroke:"transparent",fill:"transparent"})}function EdgeUpdateAnchors({isReconnectable:ta,reconnectRadius:Ln,edge:Ta,sourceX:ja,sourceY:La,targetX:Fa,targetY:wl,sourcePosition:Pl,targetPosition:pc,onReconnect:mc,onReconnectStart:gc,onReconnectEnd:Vd,setReconnecting:Wd,setUpdateHover:kf}){const Pf=useStoreApi(),Nf=(Bg,U_)=>{if(Bg.button!==0)return;const{autoPanOnConnect:B_,domNode:VC,isValidConnection:tj,connectionMode:aB,connectionRadius:r6,lib:J2,onConnectStart:V_,onConnectEnd:sP,cancelConnection:Q2,nodeLookup:q5,rfId:nj,panBy:n6,updateConnection:l6}=Pf.getState(),i6=U_.type==="target",s6=(Rpe,Xae)=>{Wd(!1),Vd?.(Rpe,Ta,U_.type,Xae)},u6=Rpe=>mc?.(Ta,Rpe),f6=(Rpe,Xae)=>{Wd(!0),gc?.(Bg,Ta,U_.type),V_?.(Rpe,Xae)};XYHandle.onPointerDown(Bg.nativeEvent,{autoPanOnConnect:B_,connectionMode:aB,connectionRadius:r6,domNode:VC,handleId:U_.id,nodeId:U_.nodeId,nodeLookup:q5,isTarget:i6,edgeUpdaterType:U_.type,lib:J2,flowId:nj,cancelConnection:Q2,panBy:n6,isValidConnection:tj,onConnect:u6,onConnectStart:f6,onConnectEnd:sP,onReconnectEnd:s6,updateConnection:l6,getTransform:()=>Pf.getState().transform,getFromHandle:()=>Pf.getState().connection.fromHandle,dragThreshold:Pf.getState().connectionDragThreshold,handleDomNode:Bg.currentTarget})},Eh=Bg=>Nf(Bg,{nodeId:Ta.target,id:Ta.targetHandle??null,type:"target"}),Em=Bg=>Nf(Bg,{nodeId:Ta.source,id:Ta.sourceHandle??null,type:"source"}),qg=()=>kf(!0),Ug=()=>kf(!1);return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[(ta===!0||ta==="source")&&jsxRuntimeExports$1.jsx(EdgeAnchor,{position:Pl,centerX:ja,centerY:La,radius:Ln,onMouseDown:Eh,onMouseEnter:qg,onMouseOut:Ug,type:"source"}),(ta===!0||ta==="target")&&jsxRuntimeExports$1.jsx(EdgeAnchor,{position:pc,centerX:Fa,centerY:wl,radius:Ln,onMouseDown:Em,onMouseEnter:qg,onMouseOut:Ug,type:"target"})]})}function EdgeWrapper({id:ta,edgesFocusable:Ln,edgesReconnectable:Ta,elementsSelectable:ja,onClick:La,onDoubleClick:Fa,onContextMenu:wl,onMouseEnter:Pl,onMouseMove:pc,onMouseLeave:mc,reconnectRadius:gc,onReconnect:Vd,onReconnectStart:Wd,onReconnectEnd:kf,rfId:Pf,edgeTypes:Nf,noPanClassName:Eh,onError:Em,disableKeyboardA11y:qg}){let Ug=useStore$1(h$e=>h$e.edgeLookup.get(ta));const Bg=useStore$1(h$e=>h$e.defaultEdgeOptions);Ug=Bg?{...Bg,...Ug}:Ug;let U_=Ug.type||"default",B_=Nf?.[U_]||builtinEdgeTypes[U_];B_===void 0&&(Em?.("011",errorMessages$3.error011(U_)),U_="default",B_=Nf?.default||builtinEdgeTypes.default);const VC=!!(Ug.focusable||Ln&&typeof Ug.focusable>"u"),tj=typeof Vd<"u"&&(Ug.reconnectable||Ta&&typeof Ug.reconnectable>"u"),aB=!!(Ug.selectable||ja&&typeof Ug.selectable>"u"),r6=reactExports$1.useRef(null),[J2,V_]=reactExports$1.useState(!1),[sP,Q2]=reactExports$1.useState(!1),q5=useStoreApi(),{zIndex:nj,sourceX:n6,sourceY:l6,targetX:i6,targetY:s6,sourcePosition:u6,targetPosition:f6}=useStore$1(reactExports$1.useCallback(h$e=>{const w$e=h$e.nodeLookup.get(Ug.source),m$e=h$e.nodeLookup.get(Ug.target);if(!w$e||!m$e)return{zIndex:Ug.zIndex,...nullPosition};const K$e=getEdgePosition({id:ta,sourceNode:w$e,targetNode:m$e,sourceHandle:Ug.sourceHandle||null,targetHandle:Ug.targetHandle||null,connectionMode:h$e.connectionMode,onError:Em});return{zIndex:getElevatedEdgeZIndex({selected:Ug.selected,zIndex:Ug.zIndex,sourceNode:w$e,targetNode:m$e,elevateOnSelect:h$e.elevateEdgesOnSelect}),...K$e||nullPosition}},[Ug.source,Ug.target,Ug.sourceHandle,Ug.targetHandle,Ug.selected,Ug.zIndex]),shallow$1),Rpe=reactExports$1.useMemo(()=>Ug.markerStart?`url('#${getMarkerId(Ug.markerStart,Pf)}')`:void 0,[Ug.markerStart,Pf]),Xae=reactExports$1.useMemo(()=>Ug.markerEnd?`url('#${getMarkerId(Ug.markerEnd,Pf)}')`:void 0,[Ug.markerEnd,Pf]);if(Ug.hidden||n6===null||l6===null||i6===null||s6===null)return null;const g$e=h$e=>{const{addSelectedEdges:w$e,unselectNodesAndEdges:m$e,multiSelectionActive:K$e}=q5.getState();aB&&(q5.setState({nodesSelectionActive:!1}),Ug.selected&&K$e?(m$e({nodes:[],edges:[Ug]}),r6.current?.blur()):w$e([ta])),La&&La(h$e,Ug)},n$e=Fa?h$e=>{Fa(h$e,{...Ug})}:void 0,v$e=wl?h$e=>{wl(h$e,{...Ug})}:void 0,S$e=Pl?h$e=>{Pl(h$e,{...Ug})}:void 0,M$e=pc?h$e=>{pc(h$e,{...Ug})}:void 0,T$e=mc?h$e=>{mc(h$e,{...Ug})}:void 0,nae=h$e=>{if(!qg&&elementSelectionKeys.includes(h$e.key)&&aB){const{unselectNodesAndEdges:w$e,addSelectedEdges:m$e}=q5.getState();h$e.key==="Escape"?(r6.current?.blur(),w$e({edges:[Ug]})):m$e([ta])}};return jsxRuntimeExports$1.jsx("svg",{style:{zIndex:nj},children:jsxRuntimeExports$1.jsxs("g",{className:cc(["react-flow__edge",`react-flow__edge-${U_}`,Ug.className,Eh,{selected:Ug.selected,animated:Ug.animated,inactive:!aB&&!La,updating:J2,selectable:aB}]),onClick:g$e,onDoubleClick:n$e,onContextMenu:v$e,onMouseEnter:S$e,onMouseMove:M$e,onMouseLeave:T$e,onKeyDown:VC?nae:void 0,tabIndex:VC?0:void 0,role:Ug.ariaRole??(VC?"group":"img"),"aria-roledescription":"edge","data-id":ta,"data-testid":`rf__edge-${ta}`,"aria-label":Ug.ariaLabel===null?void 0:Ug.ariaLabel||`Edge from ${Ug.source} to ${Ug.target}`,"aria-describedby":VC?`${ARIA_EDGE_DESC_KEY}-${Pf}`:void 0,ref:r6,...Ug.domAttributes,children:[!sP&&jsxRuntimeExports$1.jsx(B_,{id:ta,source:Ug.source,target:Ug.target,type:Ug.type,selected:Ug.selected,animated:Ug.animated,selectable:aB,deletable:Ug.deletable??!0,label:Ug.label,labelStyle:Ug.labelStyle,labelShowBg:Ug.labelShowBg,labelBgStyle:Ug.labelBgStyle,labelBgPadding:Ug.labelBgPadding,labelBgBorderRadius:Ug.labelBgBorderRadius,sourceX:n6,sourceY:l6,targetX:i6,targetY:s6,sourcePosition:u6,targetPosition:f6,data:Ug.data,style:Ug.style,sourceHandleId:Ug.sourceHandle,targetHandleId:Ug.targetHandle,markerStart:Rpe,markerEnd:Xae,pathOptions:"pathOptions"in Ug?Ug.pathOptions:void 0,interactionWidth:Ug.interactionWidth}),tj&&jsxRuntimeExports$1.jsx(EdgeUpdateAnchors,{edge:Ug,isReconnectable:tj,reconnectRadius:gc,onReconnect:Vd,onReconnectStart:Wd,onReconnectEnd:kf,sourceX:n6,sourceY:l6,targetX:i6,targetY:s6,sourcePosition:u6,targetPosition:f6,setUpdateHover:V_,setReconnecting:Q2})]})})}var EdgeWrapper$1=reactExports$1.memo(EdgeWrapper);const selector$a=ta=>({edgesFocusable:ta.edgesFocusable,edgesReconnectable:ta.edgesReconnectable,elementsSelectable:ta.elementsSelectable,connectionMode:ta.connectionMode,onError:ta.onError});function EdgeRendererComponent({defaultMarkerColor:ta,onlyRenderVisibleElements:Ln,rfId:Ta,edgeTypes:ja,noPanClassName:La,onReconnect:Fa,onEdgeContextMenu:wl,onEdgeMouseEnter:Pl,onEdgeMouseMove:pc,onEdgeMouseLeave:mc,onEdgeClick:gc,reconnectRadius:Vd,onEdgeDoubleClick:Wd,onReconnectStart:kf,onReconnectEnd:Pf,disableKeyboardA11y:Nf}){const{edgesFocusable:Eh,edgesReconnectable:Em,elementsSelectable:qg,onError:Ug}=useStore$1(selector$a,shallow$1),Bg=useVisibleEdgeIds(Ln);return jsxRuntimeExports$1.jsxs("div",{className:"react-flow__edges",children:[jsxRuntimeExports$1.jsx(MarkerDefinitions$1,{defaultColor:ta,rfId:Ta}),Bg.map(U_=>jsxRuntimeExports$1.jsx(EdgeWrapper$1,{id:U_,edgesFocusable:Eh,edgesReconnectable:Em,elementsSelectable:qg,noPanClassName:La,onReconnect:Fa,onContextMenu:wl,onMouseEnter:Pl,onMouseMove:pc,onMouseLeave:mc,onClick:gc,reconnectRadius:Vd,onDoubleClick:Wd,onReconnectStart:kf,onReconnectEnd:Pf,rfId:Ta,onError:Ug,edgeTypes:ja,disableKeyboardA11y:Nf},U_))]})}EdgeRendererComponent.displayName="EdgeRenderer";const EdgeRenderer=reactExports$1.memo(EdgeRendererComponent),selector$9=ta=>`translate(${ta.transform[0]}px,${ta.transform[1]}px) scale(${ta.transform[2]})`;function Viewport({children:ta}){const Ln=useStore$1(selector$9);return jsxRuntimeExports$1.jsx("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:Ln},children:ta})}function useOnInitHandler(ta){const Ln=useReactFlow(),Ta=reactExports$1.useRef(!1);reactExports$1.useEffect(()=>{!Ta.current&&Ln.viewportInitialized&&ta&&(setTimeout(()=>ta(Ln),1),Ta.current=!0)},[ta,Ln.viewportInitialized])}const selector$8=ta=>ta.panZoom?.syncViewport;function useViewportSync(ta){const Ln=useStore$1(selector$8),Ta=useStoreApi();return reactExports$1.useEffect(()=>{ta&&(Ln?.(ta),Ta.setState({transform:[ta.x,ta.y,ta.zoom]}))},[ta,Ln]),null}function storeSelector$1(ta){return ta.connection.inProgress?{...ta.connection,to:pointToRendererPoint(ta.connection.to,ta.transform)}:{...ta.connection}}function getSelector(ta){return storeSelector$1}function useConnection(ta){const Ln=getSelector();return useStore$1(Ln,shallow$1)}const selector$7=ta=>({nodesConnectable:ta.nodesConnectable,isValid:ta.connection.isValid,inProgress:ta.connection.inProgress,width:ta.width,height:ta.height});function ConnectionLineWrapper({containerStyle:ta,style:Ln,type:Ta,component:ja}){const{nodesConnectable:La,width:Fa,height:wl,isValid:Pl,inProgress:pc}=useStore$1(selector$7,shallow$1);return!(Fa&&La&&pc)?null:jsxRuntimeExports$1.jsx("svg",{style:ta,width:Fa,height:wl,className:"react-flow__connectionline react-flow__container",children:jsxRuntimeExports$1.jsx("g",{className:cc(["react-flow__connection",getConnectionStatus(Pl)]),children:jsxRuntimeExports$1.jsx(ConnectionLine,{style:Ln,type:Ta,CustomComponent:ja,isValid:Pl})})})}const ConnectionLine=({style:ta,type:Ln=ConnectionLineType.Bezier,CustomComponent:Ta,isValid:ja})=>{const{inProgress:La,from:Fa,fromNode:wl,fromHandle:Pl,fromPosition:pc,to:mc,toNode:gc,toHandle:Vd,toPosition:Wd,pointer:kf}=useConnection();if(!La)return;if(Ta)return jsxRuntimeExports$1.jsx(Ta,{connectionLineType:Ln,connectionLineStyle:ta,fromNode:wl,fromHandle:Pl,fromX:Fa.x,fromY:Fa.y,toX:mc.x,toY:mc.y,fromPosition:pc,toPosition:Wd,connectionStatus:getConnectionStatus(ja),toNode:gc,toHandle:Vd,pointer:kf});let Pf="";const Nf={sourceX:Fa.x,sourceY:Fa.y,sourcePosition:pc,targetX:mc.x,targetY:mc.y,targetPosition:Wd};switch(Ln){case ConnectionLineType.Bezier:[Pf]=getBezierPath(Nf);break;case ConnectionLineType.SimpleBezier:[Pf]=getSimpleBezierPath(Nf);break;case ConnectionLineType.Step:[Pf]=getSmoothStepPath({...Nf,borderRadius:0});break;case ConnectionLineType.SmoothStep:[Pf]=getSmoothStepPath(Nf);break;default:[Pf]=getStraightPath(Nf)}return jsxRuntimeExports$1.jsx("path",{d:Pf,fill:"none",className:"react-flow__connection-path",style:ta})};ConnectionLine.displayName="ConnectionLine";const emptyTypes={};function useNodeOrEdgeTypesWarning(ta=emptyTypes){reactExports$1.useRef(ta),useStoreApi(),reactExports$1.useEffect(()=>{},[ta])}function useStylesLoadedWarning(){useStoreApi(),reactExports$1.useRef(!1),reactExports$1.useEffect(()=>{},[])}function GraphViewComponent({nodeTypes:ta,edgeTypes:Ln,onInit:Ta,onNodeClick:ja,onEdgeClick:La,onNodeDoubleClick:Fa,onEdgeDoubleClick:wl,onNodeMouseEnter:Pl,onNodeMouseMove:pc,onNodeMouseLeave:mc,onNodeContextMenu:gc,onSelectionContextMenu:Vd,onSelectionStart:Wd,onSelectionEnd:kf,connectionLineType:Pf,connectionLineStyle:Nf,connectionLineComponent:Eh,connectionLineContainerStyle:Em,selectionKeyCode:qg,selectionOnDrag:Ug,selectionMode:Bg,multiSelectionKeyCode:U_,panActivationKeyCode:B_,zoomActivationKeyCode:VC,deleteKeyCode:tj,onlyRenderVisibleElements:aB,elementsSelectable:r6,defaultViewport:J2,translateExtent:V_,minZoom:sP,maxZoom:Q2,preventScrolling:q5,defaultMarkerColor:nj,zoomOnScroll:n6,zoomOnPinch:l6,panOnScroll:i6,panOnScrollSpeed:s6,panOnScrollMode:u6,zoomOnDoubleClick:f6,panOnDrag:Rpe,onPaneClick:Xae,onPaneMouseEnter:g$e,onPaneMouseMove:n$e,onPaneMouseLeave:v$e,onPaneScroll:S$e,onPaneContextMenu:M$e,paneClickDistance:T$e,nodeClickDistance:nae,onEdgeContextMenu:h$e,onEdgeMouseEnter:w$e,onEdgeMouseMove:m$e,onEdgeMouseLeave:K$e,reconnectRadius:l1e,onReconnect:U$e,onReconnectStart:$1e,onReconnectEnd:C1e,noDragClassName:R1e,noWheelClassName:y1e,noPanClassName:t1e,disableKeyboardA11y:h1e,nodeExtent:S1e,rfId:A1e,viewport:L1e,onViewportChange:b1e}){return useNodeOrEdgeTypesWarning(ta),useNodeOrEdgeTypesWarning(Ln),useStylesLoadedWarning(),useOnInitHandler(Ta),useViewportSync(L1e),jsxRuntimeExports$1.jsx(FlowRenderer,{onPaneClick:Xae,onPaneMouseEnter:g$e,onPaneMouseMove:n$e,onPaneMouseLeave:v$e,onPaneContextMenu:M$e,onPaneScroll:S$e,paneClickDistance:T$e,deleteKeyCode:tj,selectionKeyCode:qg,selectionOnDrag:Ug,selectionMode:Bg,onSelectionStart:Wd,onSelectionEnd:kf,multiSelectionKeyCode:U_,panActivationKeyCode:B_,zoomActivationKeyCode:VC,elementsSelectable:r6,zoomOnScroll:n6,zoomOnPinch:l6,zoomOnDoubleClick:f6,panOnScroll:i6,panOnScrollSpeed:s6,panOnScrollMode:u6,panOnDrag:Rpe,defaultViewport:J2,translateExtent:V_,minZoom:sP,maxZoom:Q2,onSelectionContextMenu:Vd,preventScrolling:q5,noDragClassName:R1e,noWheelClassName:y1e,noPanClassName:t1e,disableKeyboardA11y:h1e,onViewportChange:b1e,isControlledViewport:!!L1e,children:jsxRuntimeExports$1.jsxs(Viewport,{children:[jsxRuntimeExports$1.jsx(EdgeRenderer,{edgeTypes:Ln,onEdgeClick:La,onEdgeDoubleClick:wl,onReconnect:U$e,onReconnectStart:$1e,onReconnectEnd:C1e,onlyRenderVisibleElements:aB,onEdgeContextMenu:h$e,onEdgeMouseEnter:w$e,onEdgeMouseMove:m$e,onEdgeMouseLeave:K$e,reconnectRadius:l1e,defaultMarkerColor:nj,noPanClassName:t1e,disableKeyboardA11y:h1e,rfId:A1e}),jsxRuntimeExports$1.jsx(ConnectionLineWrapper,{style:Nf,type:Pf,component:Eh,containerStyle:Em}),jsxRuntimeExports$1.jsx("div",{className:"react-flow__edgelabel-renderer"}),jsxRuntimeExports$1.jsx(NodeRenderer,{nodeTypes:ta,onNodeClick:ja,onNodeDoubleClick:Fa,onNodeMouseEnter:Pl,onNodeMouseMove:pc,onNodeMouseLeave:mc,onNodeContextMenu:gc,nodeClickDistance:nae,onlyRenderVisibleElements:aB,noPanClassName:t1e,noDragClassName:R1e,disableKeyboardA11y:h1e,nodeExtent:S1e,rfId:A1e}),jsxRuntimeExports$1.jsx("div",{className:"react-flow__viewport-portal"})]})})}GraphViewComponent.displayName="GraphView";const GraphView=reactExports$1.memo(GraphViewComponent),getInitialState$1=({nodes:ta,edges:Ln,defaultNodes:Ta,defaultEdges:ja,width:La,height:Fa,fitView:wl,fitViewOptions:Pl,minZoom:pc=.5,maxZoom:mc=2,nodeOrigin:gc,nodeExtent:Vd}={})=>{const Wd=new Map,kf=new Map,Pf=new Map,Nf=new Map,Eh=ja??Ln??[],Em=Ta??ta??[],qg=gc??[0,0],Ug=Vd??infiniteExtent;updateConnectionLookup(Pf,Nf,Eh);const Bg=adoptUserNodes(Em,Wd,kf,{nodeOrigin:qg,nodeExtent:Ug,elevateNodesOnSelect:!1});let U_=[0,0,1];if(wl&&La&&Fa){const B_=getInternalNodesBounds(Wd,{filter:r6=>!!((r6.width||r6.initialWidth)&&(r6.height||r6.initialHeight))}),{x:VC,y:tj,zoom:aB}=getViewportForBounds(B_,La,Fa,pc,mc,Pl?.padding??.1);U_=[VC,tj,aB]}return{rfId:"1",width:La??0,height:Fa??0,transform:U_,nodes:Em,nodesInitialized:Bg,nodeLookup:Wd,parentLookup:kf,edges:Eh,edgeLookup:Nf,connectionLookup:Pf,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:Ta!==void 0,hasDefaultEdges:ja!==void 0,panZoom:null,minZoom:pc,maxZoom:mc,translateExtent:infiniteExtent,nodeExtent:Ug,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:ConnectionMode.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:qg,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!1,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:wl??!1,fitViewOptions:Pl,fitViewResolver:null,connection:{...initialConnection},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:devWarn,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:defaultAriaLabelConfig}},createStore=({nodes:ta,edges:Ln,defaultNodes:Ta,defaultEdges:ja,width:La,height:Fa,fitView:wl,fitViewOptions:Pl,minZoom:pc,maxZoom:mc,nodeOrigin:gc,nodeExtent:Vd})=>createWithEqualityFn((Wd,kf)=>{async function Pf(){const{nodeLookup:Nf,panZoom:Eh,fitViewOptions:Em,fitViewResolver:qg,width:Ug,height:Bg,minZoom:U_,maxZoom:B_}=kf();Eh&&(await fitViewport({nodes:Nf,width:Ug,height:Bg,panZoom:Eh,minZoom:U_,maxZoom:B_},Em),qg?.resolve(!0),Wd({fitViewResolver:null}))}return{...getInitialState$1({nodes:ta,edges:Ln,width:La,height:Fa,fitView:wl,fitViewOptions:Pl,minZoom:pc,maxZoom:mc,nodeOrigin:gc,nodeExtent:Vd,defaultNodes:Ta,defaultEdges:ja}),setNodes:Nf=>{const{nodeLookup:Eh,parentLookup:Em,nodeOrigin:qg,elevateNodesOnSelect:Ug,fitViewQueued:Bg}=kf(),U_=adoptUserNodes(Nf,Eh,Em,{nodeOrigin:qg,nodeExtent:Vd,elevateNodesOnSelect:Ug,checkEquality:!0});Bg&&U_?(Pf(),Wd({nodes:Nf,nodesInitialized:U_,fitViewQueued:!1,fitViewOptions:void 0})):Wd({nodes:Nf,nodesInitialized:U_})},setEdges:Nf=>{const{connectionLookup:Eh,edgeLookup:Em}=kf();updateConnectionLookup(Eh,Em,Nf),Wd({edges:Nf})},setDefaultNodesAndEdges:(Nf,Eh)=>{if(Nf){const{setNodes:Em}=kf();Em(Nf),Wd({hasDefaultNodes:!0})}if(Eh){const{setEdges:Em}=kf();Em(Eh),Wd({hasDefaultEdges:!0})}},updateNodeInternals:Nf=>{const{triggerNodeChanges:Eh,nodeLookup:Em,parentLookup:qg,domNode:Ug,nodeOrigin:Bg,nodeExtent:U_,debug:B_,fitViewQueued:VC}=kf(),{changes:tj,updatedInternals:aB}=updateNodeInternals(Nf,Em,qg,Ug,Bg,U_);aB&&(updateAbsolutePositions(Em,qg,{nodeOrigin:Bg,nodeExtent:U_}),VC?(Pf(),Wd({fitViewQueued:!1,fitViewOptions:void 0})):Wd({}),tj?.length>0&&(B_&&console.log("React Flow: trigger node changes",tj),Eh?.(tj)))},updateNodePositions:(Nf,Eh=!1)=>{const Em=[],qg=[],{nodeLookup:Ug,triggerNodeChanges:Bg}=kf();for(const[U_,B_]of Nf){const VC=Ug.get(U_),tj=!!(VC?.expandParent&&VC?.parentId&&B_?.position),aB={id:U_,type:"position",position:tj?{x:Math.max(0,B_.position.x),y:Math.max(0,B_.position.y)}:B_.position,dragging:Eh};tj&&VC.parentId&&Em.push({id:U_,parentId:VC.parentId,rect:{...B_.internals.positionAbsolute,width:B_.measured.width??0,height:B_.measured.height??0}}),qg.push(aB)}if(Em.length>0){const{parentLookup:U_,nodeOrigin:B_}=kf(),VC=handleExpandParent(Em,Ug,U_,B_);qg.push(...VC)}Bg(qg)},triggerNodeChanges:Nf=>{const{onNodesChange:Eh,setNodes:Em,nodes:qg,hasDefaultNodes:Ug,debug:Bg}=kf();if(Nf?.length){if(Ug){const U_=applyNodeChanges(Nf,qg);Em(U_)}Bg&&console.log("React Flow: trigger node changes",Nf),Eh?.(Nf)}},triggerEdgeChanges:Nf=>{const{onEdgesChange:Eh,setEdges:Em,edges:qg,hasDefaultEdges:Ug,debug:Bg}=kf();if(Nf?.length){if(Ug){const U_=applyEdgeChanges(Nf,qg);Em(U_)}Bg&&console.log("React Flow: trigger edge changes",Nf),Eh?.(Nf)}},addSelectedNodes:Nf=>{const{multiSelectionActive:Eh,edgeLookup:Em,nodeLookup:qg,triggerNodeChanges:Ug,triggerEdgeChanges:Bg}=kf();if(Eh){const U_=Nf.map(B_=>createSelectionChange(B_,!0));Ug(U_);return}Ug(getSelectionChanges(qg,new Set([...Nf]),!0)),Bg(getSelectionChanges(Em))},addSelectedEdges:Nf=>{const{multiSelectionActive:Eh,edgeLookup:Em,nodeLookup:qg,triggerNodeChanges:Ug,triggerEdgeChanges:Bg}=kf();if(Eh){const U_=Nf.map(B_=>createSelectionChange(B_,!0));Bg(U_);return}Bg(getSelectionChanges(Em,new Set([...Nf]))),Ug(getSelectionChanges(qg,new Set,!0))},unselectNodesAndEdges:({nodes:Nf,edges:Eh}={})=>{const{edges:Em,nodes:qg,nodeLookup:Ug,triggerNodeChanges:Bg,triggerEdgeChanges:U_}=kf(),B_=Nf||qg,VC=Eh||Em,tj=B_.map(r6=>{const J2=Ug.get(r6.id);return J2&&(J2.selected=!1),createSelectionChange(r6.id,!1)}),aB=VC.map(r6=>createSelectionChange(r6.id,!1));Bg(tj),U_(aB)},setMinZoom:Nf=>{const{panZoom:Eh,maxZoom:Em}=kf();Eh?.setScaleExtent([Nf,Em]),Wd({minZoom:Nf})},setMaxZoom:Nf=>{const{panZoom:Eh,minZoom:Em}=kf();Eh?.setScaleExtent([Em,Nf]),Wd({maxZoom:Nf})},setTranslateExtent:Nf=>{kf().panZoom?.setTranslateExtent(Nf),Wd({translateExtent:Nf})},resetSelectedElements:()=>{const{edges:Nf,nodes:Eh,triggerNodeChanges:Em,triggerEdgeChanges:qg,elementsSelectable:Ug}=kf();if(!Ug)return;const Bg=Eh.reduce((B_,VC)=>VC.selected?[...B_,createSelectionChange(VC.id,!1)]:B_,[]),U_=Nf.reduce((B_,VC)=>VC.selected?[...B_,createSelectionChange(VC.id,!1)]:B_,[]);Em(Bg),qg(U_)},setNodeExtent:Nf=>{const{nodes:Eh,nodeLookup:Em,parentLookup:qg,nodeOrigin:Ug,elevateNodesOnSelect:Bg,nodeExtent:U_}=kf();Nf[0][0]===U_[0][0]&&Nf[0][1]===U_[0][1]&&Nf[1][0]===U_[1][0]&&Nf[1][1]===U_[1][1]||(adoptUserNodes(Eh,Em,qg,{nodeOrigin:Ug,nodeExtent:Nf,elevateNodesOnSelect:Bg,checkEquality:!1}),Wd({nodeExtent:Nf}))},panBy:Nf=>{const{transform:Eh,width:Em,height:qg,panZoom:Ug,translateExtent:Bg}=kf();return panBy({delta:Nf,panZoom:Ug,transform:Eh,translateExtent:Bg,width:Em,height:qg})},setCenter:async(Nf,Eh,Em)=>{const{width:qg,height:Ug,maxZoom:Bg,panZoom:U_}=kf();if(!U_)return Promise.resolve(!1);const B_=typeof Em?.zoom<"u"?Em.zoom:Bg;return await U_.setViewport({x:qg/2-Nf*B_,y:Ug/2-Eh*B_,zoom:B_},{duration:Em?.duration,ease:Em?.ease,interpolate:Em?.interpolate}),Promise.resolve(!0)},cancelConnection:()=>{Wd({connection:{...initialConnection}})},updateConnection:Nf=>{Wd({connection:Nf})},reset:()=>Wd({...getInitialState$1()})}},Object.is);function ReactFlowProvider({initialNodes:ta,initialEdges:Ln,defaultNodes:Ta,defaultEdges:ja,initialWidth:La,initialHeight:Fa,initialMinZoom:wl,initialMaxZoom:Pl,initialFitViewOptions:pc,fitView:mc,nodeOrigin:gc,nodeExtent:Vd,children:Wd}){const[kf]=reactExports$1.useState(()=>createStore({nodes:ta,edges:Ln,defaultNodes:Ta,defaultEdges:ja,width:La,height:Fa,fitView:mc,minZoom:wl,maxZoom:Pl,fitViewOptions:pc,nodeOrigin:gc,nodeExtent:Vd}));return jsxRuntimeExports$1.jsx(Provider$1,{value:kf,children:jsxRuntimeExports$1.jsx(BatchProvider,{children:Wd})})}function Wrapper({children:ta,nodes:Ln,edges:Ta,defaultNodes:ja,defaultEdges:La,width:Fa,height:wl,fitView:Pl,fitViewOptions:pc,minZoom:mc,maxZoom:gc,nodeOrigin:Vd,nodeExtent:Wd}){return reactExports$1.useContext(StoreContext)?jsxRuntimeExports$1.jsx(jsxRuntimeExports$1.Fragment,{children:ta}):jsxRuntimeExports$1.jsx(ReactFlowProvider,{initialNodes:Ln,initialEdges:Ta,defaultNodes:ja,defaultEdges:La,initialWidth:Fa,initialHeight:wl,fitView:Pl,initialFitViewOptions:pc,initialMinZoom:mc,initialMaxZoom:gc,nodeOrigin:Vd,nodeExtent:Wd,children:ta})}const wrapperStyle={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};function ReactFlow({nodes:ta,edges:Ln,defaultNodes:Ta,defaultEdges:ja,className:La,nodeTypes:Fa,edgeTypes:wl,onNodeClick:Pl,onEdgeClick:pc,onInit:mc,onMove:gc,onMoveStart:Vd,onMoveEnd:Wd,onConnect:kf,onConnectStart:Pf,onConnectEnd:Nf,onClickConnectStart:Eh,onClickConnectEnd:Em,onNodeMouseEnter:qg,onNodeMouseMove:Ug,onNodeMouseLeave:Bg,onNodeContextMenu:U_,onNodeDoubleClick:B_,onNodeDragStart:VC,onNodeDrag:tj,onNodeDragStop:aB,onNodesDelete:r6,onEdgesDelete:J2,onDelete:V_,onSelectionChange:sP,onSelectionDragStart:Q2,onSelectionDrag:q5,onSelectionDragStop:nj,onSelectionContextMenu:n6,onSelectionStart:l6,onSelectionEnd:i6,onBeforeDelete:s6,connectionMode:u6,connectionLineType:f6=ConnectionLineType.Bezier,connectionLineStyle:Rpe,connectionLineComponent:Xae,connectionLineContainerStyle:g$e,deleteKeyCode:n$e="Backspace",selectionKeyCode:v$e="Shift",selectionOnDrag:S$e=!1,selectionMode:M$e=SelectionMode.Full,panActivationKeyCode:T$e="Space",multiSelectionKeyCode:nae=isMacOs()?"Meta":"Control",zoomActivationKeyCode:h$e=isMacOs()?"Meta":"Control",snapToGrid:w$e,snapGrid:m$e,onlyRenderVisibleElements:K$e=!1,selectNodesOnDrag:l1e,nodesDraggable:U$e,autoPanOnNodeFocus:$1e,nodesConnectable:C1e,nodesFocusable:R1e,nodeOrigin:y1e=defaultNodeOrigin,edgesFocusable:t1e,edgesReconnectable:h1e,elementsSelectable:S1e=!0,defaultViewport:A1e=defaultViewport,minZoom:L1e=.5,maxZoom:b1e=2,translateExtent:E$e=infiniteExtent,preventScrolling:R$e=!0,nodeExtent:Z$e,defaultMarkerColor:L$e="#b1b1b7",zoomOnScroll:k$e=!0,zoomOnPinch:x$e=!0,panOnScroll:O$e=!1,panOnScrollSpeed:I$e=.5,panOnScrollMode:W$e=PanOnScrollMode.Free,zoomOnDoubleClick:t$e=!0,panOnDrag:B$e=!0,onPaneClick:r1e,onPaneMouseEnter:lae,onPaneMouseMove:_$e,onPaneMouseLeave:q$e,onPaneScroll:b$e,onPaneContextMenu:N$e,paneClickDistance:G$e=1,nodeClickDistance:c1e=0,children:a1e,onReconnect:v1e,onReconnectStart:H1e,onReconnectEnd:tRe,onEdgeContextMenu:e1e,onEdgeDoubleClick:n1e,onEdgeMouseEnter:d1e,onEdgeMouseMove:c6,onEdgeMouseLeave:m1e,reconnectRadius:T1e=10,onNodesChange:i1e,onEdgesChange:h6,noDragClassName:A$e="nodrag",noWheelClassName:H$e="nowheel",noPanClassName:J$e="nopan",fitView:x1e,fitViewOptions:O1e,connectOnClick:F1e,attributionPosition:z1e,proOptions:P1e,defaultEdgeOptions:G1e,elevateNodesOnSelect:k1e,elevateEdgesOnSelect:V1e,disableKeyboardA11y:$Ce=!1,autoPanOnConnect:BCe,autoPanOnNodeDrag:MAe,autoPanSpeed:rke,connectionRadius:LCe,isValidConnection:pAe,onError:BAe,style:IAe,id:cAe,nodeDragThreshold:CAe,connectionDragThreshold:JAe,viewport:XAe,onViewportChange:kAe,width:bAe,height:yAe,colorMode:uke="light",debug:dke,onScroll:wke,ariaLabelConfig:fke,...Dke},eke){const _ke=cAe||"1",xke=useColorModeClass(uke),sPe=reactExports$1.useCallback(jke=>{jke.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),wke?.(jke)},[wke]);return jsxRuntimeExports$1.jsx("div",{"data-testid":"rf__wrapper",...Dke,onScroll:sPe,style:{...IAe,...wrapperStyle},ref:eke,className:cc(["react-flow",La,xke]),id:cAe,role:"application",children:jsxRuntimeExports$1.jsxs(Wrapper,{nodes:ta,edges:Ln,width:bAe,height:yAe,fitView:x1e,fitViewOptions:O1e,minZoom:L1e,maxZoom:b1e,nodeOrigin:y1e,nodeExtent:Z$e,children:[jsxRuntimeExports$1.jsx(GraphView,{onInit:mc,onNodeClick:Pl,onEdgeClick:pc,onNodeMouseEnter:qg,onNodeMouseMove:Ug,onNodeMouseLeave:Bg,onNodeContextMenu:U_,onNodeDoubleClick:B_,nodeTypes:Fa,edgeTypes:wl,connectionLineType:f6,connectionLineStyle:Rpe,connectionLineComponent:Xae,connectionLineContainerStyle:g$e,selectionKeyCode:v$e,selectionOnDrag:S$e,selectionMode:M$e,deleteKeyCode:n$e,multiSelectionKeyCode:nae,panActivationKeyCode:T$e,zoomActivationKeyCode:h$e,onlyRenderVisibleElements:K$e,defaultViewport:A1e,translateExtent:E$e,minZoom:L1e,maxZoom:b1e,preventScrolling:R$e,zoomOnScroll:k$e,zoomOnPinch:x$e,zoomOnDoubleClick:t$e,panOnScroll:O$e,panOnScrollSpeed:I$e,panOnScrollMode:W$e,panOnDrag:B$e,onPaneClick:r1e,onPaneMouseEnter:lae,onPaneMouseMove:_$e,onPaneMouseLeave:q$e,onPaneScroll:b$e,onPaneContextMenu:N$e,paneClickDistance:G$e,nodeClickDistance:c1e,onSelectionContextMenu:n6,onSelectionStart:l6,onSelectionEnd:i6,onReconnect:v1e,onReconnectStart:H1e,onReconnectEnd:tRe,onEdgeContextMenu:e1e,onEdgeDoubleClick:n1e,onEdgeMouseEnter:d1e,onEdgeMouseMove:c6,onEdgeMouseLeave:m1e,reconnectRadius:T1e,defaultMarkerColor:L$e,noDragClassName:A$e,noWheelClassName:H$e,noPanClassName:J$e,rfId:_ke,disableKeyboardA11y:$Ce,nodeExtent:Z$e,viewport:XAe,onViewportChange:kAe}),jsxRuntimeExports$1.jsx(StoreUpdater,{nodes:ta,edges:Ln,defaultNodes:Ta,defaultEdges:ja,onConnect:kf,onConnectStart:Pf,onConnectEnd:Nf,onClickConnectStart:Eh,onClickConnectEnd:Em,nodesDraggable:U$e,autoPanOnNodeFocus:$1e,nodesConnectable:C1e,nodesFocusable:R1e,edgesFocusable:t1e,edgesReconnectable:h1e,elementsSelectable:S1e,elevateNodesOnSelect:k1e,elevateEdgesOnSelect:V1e,minZoom:L1e,maxZoom:b1e,nodeExtent:Z$e,onNodesChange:i1e,onEdgesChange:h6,snapToGrid:w$e,snapGrid:m$e,connectionMode:u6,translateExtent:E$e,connectOnClick:F1e,defaultEdgeOptions:G1e,fitView:x1e,fitViewOptions:O1e,onNodesDelete:r6,onEdgesDelete:J2,onDelete:V_,onNodeDragStart:VC,onNodeDrag:tj,onNodeDragStop:aB,onSelectionDrag:q5,onSelectionDragStart:Q2,onSelectionDragStop:nj,onMove:gc,onMoveStart:Vd,onMoveEnd:Wd,noPanClassName:J$e,nodeOrigin:y1e,rfId:_ke,autoPanOnConnect:BCe,autoPanOnNodeDrag:MAe,autoPanSpeed:rke,onError:BAe,connectionRadius:LCe,isValidConnection:pAe,selectNodesOnDrag:l1e,nodeDragThreshold:CAe,connectionDragThreshold:JAe,onBeforeDelete:s6,debug:dke,ariaLabelConfig:fke}),jsxRuntimeExports$1.jsx(SelectionListener,{onSelectionChange:sP}),a1e,jsxRuntimeExports$1.jsx(Attribution,{proOptions:P1e,position:z1e}),jsxRuntimeExports$1.jsx(A11yDescriptions,{rfId:_ke,disableKeyboardA11y:$Ce})]})})}var index$3=fixedForwardRef(ReactFlow);function useNodesState(ta){const[Ln,Ta]=reactExports$1.useState(ta),ja=reactExports$1.useCallback(La=>Ta(Fa=>applyNodeChanges(La,Fa)),[]);return[Ln,Ta,ja]}function useEdgesState(ta){const[Ln,Ta]=reactExports$1.useState(ta),ja=reactExports$1.useCallback(La=>Ta(Fa=>applyEdgeChanges(La,Fa)),[]);return[Ln,Ta,ja]}function LinePattern({dimensions:ta,lineWidth:Ln,variant:Ta,className:ja}){return jsxRuntimeExports$1.jsx("path",{strokeWidth:Ln,d:`M${ta[0]/2} 0 V${ta[1]} M0 ${ta[1]/2} H${ta[0]}`,className:cc(["react-flow__background-pattern",Ta,ja])})}function DotPattern({radius:ta,className:Ln}){return jsxRuntimeExports$1.jsx("circle",{cx:ta,cy:ta,r:ta,className:cc(["react-flow__background-pattern","dots",Ln])})}var BackgroundVariant;(function(ta){ta.Lines="lines",ta.Dots="dots",ta.Cross="cross"})(BackgroundVariant||(BackgroundVariant={}));const defaultSize={[BackgroundVariant.Dots]:1,[BackgroundVariant.Lines]:1,[BackgroundVariant.Cross]:6},selector$3=ta=>({transform:ta.transform,patternId:`pattern-${ta.rfId}`});function BackgroundComponent({id:ta,variant:Ln=BackgroundVariant.Dots,gap:Ta=20,size:ja,lineWidth:La=1,offset:Fa=0,color:wl,bgColor:Pl,style:pc,className:mc,patternClassName:gc}){const Vd=reactExports$1.useRef(null),{transform:Wd,patternId:kf}=useStore$1(selector$3,shallow$1),Pf=ja||defaultSize[Ln],Nf=Ln===BackgroundVariant.Dots,Eh=Ln===BackgroundVariant.Cross,Em=Array.isArray(Ta)?Ta:[Ta,Ta],qg=[Em[0]*Wd[2]||1,Em[1]*Wd[2]||1],Ug=Pf*Wd[2],Bg=Array.isArray(Fa)?Fa:[Fa,Fa],U_=Eh?[Ug,Ug]:qg,B_=[Bg[0]*Wd[2]||1+U_[0]/2,Bg[1]*Wd[2]||1+U_[1]/2],VC=`${kf}${ta||""}`;return jsxRuntimeExports$1.jsxs("svg",{className:cc(["react-flow__background",mc]),style:{...pc,...containerStyle,"--xy-background-color-props":Pl,"--xy-background-pattern-color-props":wl},ref:Vd,"data-testid":"rf__background",children:[jsxRuntimeExports$1.jsx("pattern",{id:VC,x:Wd[0]%qg[0],y:Wd[1]%qg[1],width:qg[0],height:qg[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${B_[0]},-${B_[1]})`,children:Nf?jsxRuntimeExports$1.jsx(DotPattern,{radius:Ug/2,className:gc}):jsxRuntimeExports$1.jsx(LinePattern,{dimensions:U_,lineWidth:La,variant:Ln,className:gc})}),jsxRuntimeExports$1.jsx("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${VC})`})]})}BackgroundComponent.displayName="Background";const Background=reactExports$1.memo(BackgroundComponent);function PlusIcon(){return jsxRuntimeExports$1.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:jsxRuntimeExports$1.jsx("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function MinusIcon(){return jsxRuntimeExports$1.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:jsxRuntimeExports$1.jsx("path",{d:"M0 0h32v4.2H0z"})})}function FitViewIcon(){return jsxRuntimeExports$1.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:jsxRuntimeExports$1.jsx("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function LockIcon(){return jsxRuntimeExports$1.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:jsxRuntimeExports$1.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function UnlockIcon(){return jsxRuntimeExports$1.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:jsxRuntimeExports$1.jsx("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function ControlButton({children:ta,className:Ln,...Ta}){return jsxRuntimeExports$1.jsx("button",{type:"button",className:cc(["react-flow__controls-button",Ln]),...Ta,children:ta})}const selector$2=ta=>({isInteractive:ta.nodesDraggable||ta.nodesConnectable||ta.elementsSelectable,minZoomReached:ta.transform[2]<=ta.minZoom,maxZoomReached:ta.transform[2]>=ta.maxZoom,ariaLabelConfig:ta.ariaLabelConfig});function ControlsComponent({style:ta,showZoom:Ln=!0,showFitView:Ta=!0,showInteractive:ja=!0,fitViewOptions:La,onZoomIn:Fa,onZoomOut:wl,onFitView:Pl,onInteractiveChange:pc,className:mc,children:gc,position:Vd="bottom-left",orientation:Wd="vertical","aria-label":kf}){const Pf=useStoreApi(),{isInteractive:Nf,minZoomReached:Eh,maxZoomReached:Em,ariaLabelConfig:qg}=useStore$1(selector$2,shallow$1),{zoomIn:Ug,zoomOut:Bg,fitView:U_}=useReactFlow(),B_=()=>{Ug(),Fa?.()},VC=()=>{Bg(),wl?.()},tj=()=>{U_(La),Pl?.()},aB=()=>{Pf.setState({nodesDraggable:!Nf,nodesConnectable:!Nf,elementsSelectable:!Nf}),pc?.(!Nf)},r6=Wd==="horizontal"?"horizontal":"vertical";return jsxRuntimeExports$1.jsxs(Panel,{className:cc(["react-flow__controls",r6,mc]),position:Vd,style:ta,"data-testid":"rf__controls","aria-label":kf??qg["controls.ariaLabel"],children:[Ln&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(ControlButton,{onClick:B_,className:"react-flow__controls-zoomin",title:qg["controls.zoomIn.ariaLabel"],"aria-label":qg["controls.zoomIn.ariaLabel"],disabled:Em,children:jsxRuntimeExports$1.jsx(PlusIcon,{})}),jsxRuntimeExports$1.jsx(ControlButton,{onClick:VC,className:"react-flow__controls-zoomout",title:qg["controls.zoomOut.ariaLabel"],"aria-label":qg["controls.zoomOut.ariaLabel"],disabled:Eh,children:jsxRuntimeExports$1.jsx(MinusIcon,{})})]}),Ta&&jsxRuntimeExports$1.jsx(ControlButton,{className:"react-flow__controls-fitview",onClick:tj,title:qg["controls.fitView.ariaLabel"],"aria-label":qg["controls.fitView.ariaLabel"],children:jsxRuntimeExports$1.jsx(FitViewIcon,{})}),ja&&jsxRuntimeExports$1.jsx(ControlButton,{className:"react-flow__controls-interactive",onClick:aB,title:qg["controls.interactive.ariaLabel"],"aria-label":qg["controls.interactive.ariaLabel"],children:Nf?jsxRuntimeExports$1.jsx(UnlockIcon,{}):jsxRuntimeExports$1.jsx(LockIcon,{})}),gc]})}ControlsComponent.displayName="Controls";reactExports$1.memo(ControlsComponent);function MiniMapNodeComponent({id:ta,x:Ln,y:Ta,width:ja,height:La,style:Fa,color:wl,strokeColor:Pl,strokeWidth:pc,className:mc,borderRadius:gc,shapeRendering:Vd,selected:Wd,onClick:kf}){const{background:Pf,backgroundColor:Nf}=Fa||{},Eh=wl||Pf||Nf;return jsxRuntimeExports$1.jsx("rect",{className:cc(["react-flow__minimap-node",{selected:Wd},mc]),x:Ln,y:Ta,rx:gc,ry:gc,width:ja,height:La,style:{fill:Eh,stroke:Pl,strokeWidth:pc},shapeRendering:Vd,onClick:kf?Em=>kf(Em,ta):void 0})}const MiniMapNode=reactExports$1.memo(MiniMapNodeComponent),selectorNodeIds=ta=>ta.nodes.map(Ln=>Ln.id),getAttrFunction=ta=>ta instanceof Function?ta:()=>ta;function MiniMapNodes({nodeStrokeColor:ta,nodeColor:Ln,nodeClassName:Ta="",nodeBorderRadius:ja=5,nodeStrokeWidth:La,nodeComponent:Fa=MiniMapNode,onClick:wl}){const Pl=useStore$1(selectorNodeIds,shallow$1),pc=getAttrFunction(Ln),mc=getAttrFunction(ta),gc=getAttrFunction(Ta),Vd=typeof window>"u"||window.chrome?"crispEdges":"geometricPrecision";return jsxRuntimeExports$1.jsx(jsxRuntimeExports$1.Fragment,{children:Pl.map(Wd=>jsxRuntimeExports$1.jsx(NodeComponentWrapper,{id:Wd,nodeColorFunc:pc,nodeStrokeColorFunc:mc,nodeClassNameFunc:gc,nodeBorderRadius:ja,nodeStrokeWidth:La,NodeComponent:Fa,onClick:wl,shapeRendering:Vd},Wd))})}function NodeComponentWrapperInner({id:ta,nodeColorFunc:Ln,nodeStrokeColorFunc:Ta,nodeClassNameFunc:ja,nodeBorderRadius:La,nodeStrokeWidth:Fa,shapeRendering:wl,NodeComponent:Pl,onClick:pc}){const{node:mc,x:gc,y:Vd,width:Wd,height:kf}=useStore$1(Pf=>{const{internals:Nf}=Pf.nodeLookup.get(ta),Eh=Nf.userNode,{x:Em,y:qg}=Nf.positionAbsolute,{width:Ug,height:Bg}=getNodeDimensions(Eh);return{node:Eh,x:Em,y:qg,width:Ug,height:Bg}},shallow$1);return!mc||mc.hidden||!nodeHasDimensions(mc)?null:jsxRuntimeExports$1.jsx(Pl,{x:gc,y:Vd,width:Wd,height:kf,style:mc.style,selected:!!mc.selected,className:ja(mc),color:Ln(mc),borderRadius:La,strokeColor:Ta(mc),strokeWidth:Fa,shapeRendering:wl,onClick:pc,id:mc.id})}const NodeComponentWrapper=reactExports$1.memo(NodeComponentWrapperInner);var MiniMapNodes$1=reactExports$1.memo(MiniMapNodes);const defaultWidth=200,defaultHeight=150,filterHidden=ta=>!ta.hidden,selector$1=ta=>{const Ln={x:-ta.transform[0]/ta.transform[2],y:-ta.transform[1]/ta.transform[2],width:ta.width/ta.transform[2],height:ta.height/ta.transform[2]};return{viewBB:Ln,boundingRect:ta.nodeLookup.size>0?getBoundsOfRects(getInternalNodesBounds(ta.nodeLookup,{filter:filterHidden}),Ln):Ln,rfId:ta.rfId,panZoom:ta.panZoom,translateExtent:ta.translateExtent,flowWidth:ta.width,flowHeight:ta.height,ariaLabelConfig:ta.ariaLabelConfig}},ARIA_LABEL_KEY="react-flow__minimap-desc";function MiniMapComponent({style:ta,className:Ln,nodeStrokeColor:Ta,nodeColor:ja,nodeClassName:La="",nodeBorderRadius:Fa=5,nodeStrokeWidth:wl,nodeComponent:Pl,bgColor:pc,maskColor:mc,maskStrokeColor:gc,maskStrokeWidth:Vd,position:Wd="bottom-right",onClick:kf,onNodeClick:Pf,pannable:Nf=!1,zoomable:Eh=!1,ariaLabel:Em,inversePan:qg,zoomStep:Ug=1,offsetScale:Bg=5}){const U_=useStoreApi(),B_=reactExports$1.useRef(null),{boundingRect:VC,viewBB:tj,rfId:aB,panZoom:r6,translateExtent:J2,flowWidth:V_,flowHeight:sP,ariaLabelConfig:Q2}=useStore$1(selector$1,shallow$1),q5=ta?.width??defaultWidth,nj=ta?.height??defaultHeight,n6=VC.width/q5,l6=VC.height/nj,i6=Math.max(n6,l6),s6=i6*q5,u6=i6*nj,f6=Bg*i6,Rpe=VC.x-(s6-VC.width)/2-f6,Xae=VC.y-(u6-VC.height)/2-f6,g$e=s6+f6*2,n$e=u6+f6*2,v$e=`${ARIA_LABEL_KEY}-${aB}`,S$e=reactExports$1.useRef(0),M$e=reactExports$1.useRef();S$e.current=i6,reactExports$1.useEffect(()=>{if(B_.current&&r6)return M$e.current=XYMinimap({domNode:B_.current,panZoom:r6,getTransform:()=>U_.getState().transform,getViewScale:()=>S$e.current}),()=>{M$e.current?.destroy()}},[r6]),reactExports$1.useEffect(()=>{M$e.current?.update({translateExtent:J2,width:V_,height:sP,inversePan:qg,pannable:Nf,zoomStep:Ug,zoomable:Eh})},[Nf,Eh,qg,Ug,J2,V_,sP]);const T$e=kf?w$e=>{const[m$e,K$e]=M$e.current?.pointer(w$e)||[0,0];kf(w$e,{x:m$e,y:K$e})}:void 0,nae=Pf?reactExports$1.useCallback((w$e,m$e)=>{const K$e=U_.getState().nodeLookup.get(m$e).internals.userNode;Pf(w$e,K$e)},[]):void 0,h$e=Em??Q2["minimap.ariaLabel"];return jsxRuntimeExports$1.jsx(Panel,{position:Wd,style:{...ta,"--xy-minimap-background-color-props":typeof pc=="string"?pc:void 0,"--xy-minimap-mask-background-color-props":typeof mc=="string"?mc:void 0,"--xy-minimap-mask-stroke-color-props":typeof gc=="string"?gc:void 0,"--xy-minimap-mask-stroke-width-props":typeof Vd=="number"?Vd*i6:void 0,"--xy-minimap-node-background-color-props":typeof ja=="string"?ja:void 0,"--xy-minimap-node-stroke-color-props":typeof Ta=="string"?Ta:void 0,"--xy-minimap-node-stroke-width-props":typeof wl=="number"?wl:void 0},className:cc(["react-flow__minimap",Ln]),"data-testid":"rf__minimap",children:jsxRuntimeExports$1.jsxs("svg",{width:q5,height:nj,viewBox:`${Rpe} ${Xae} ${g$e} ${n$e}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":v$e,ref:B_,onClick:T$e,children:[h$e&&jsxRuntimeExports$1.jsx("title",{id:v$e,children:h$e}),jsxRuntimeExports$1.jsx(MiniMapNodes$1,{onClick:nae,nodeColor:ja,nodeStrokeColor:Ta,nodeBorderRadius:Fa,nodeClassName:La,nodeStrokeWidth:wl,nodeComponent:Pl}),jsxRuntimeExports$1.jsx("path",{className:"react-flow__minimap-mask",d:`M${Rpe-f6},${Xae-f6}h${g$e+f6*2}v${n$e+f6*2}h${-g$e-f6*2}z
|
|
34775
34775
|
M${tj.x},${tj.y}h${tj.width}v${tj.height}h${-tj.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}MiniMapComponent.displayName="MiniMap";reactExports$1.memo(MiniMapComponent);const scaleSelector=ta=>Ln=>ta?`${Math.max(1/Ln.transform[2],1)}`:void 0,defaultPositions={[ResizeControlVariant.Line]:"right",[ResizeControlVariant.Handle]:"bottom-right"};function ResizeControl({nodeId:ta,position:Ln,variant:Ta=ResizeControlVariant.Handle,className:ja,style:La=void 0,children:Fa,color:wl,minWidth:Pl=10,minHeight:pc=10,maxWidth:mc=Number.MAX_VALUE,maxHeight:gc=Number.MAX_VALUE,keepAspectRatio:Vd=!1,resizeDirection:Wd,autoScale:kf=!0,shouldResize:Pf,onResizeStart:Nf,onResize:Eh,onResizeEnd:Em}){const qg=useNodeId(),Ug=typeof ta=="string"?ta:qg,Bg=useStoreApi(),U_=reactExports$1.useRef(null),B_=Ta===ResizeControlVariant.Handle,VC=useStore$1(reactExports$1.useCallback(scaleSelector(B_&&kf),[B_,kf]),shallow$1),tj=reactExports$1.useRef(null),aB=Ln??defaultPositions[Ta];reactExports$1.useEffect(()=>{if(!(!U_.current||!Ug))return tj.current||(tj.current=XYResizer({domNode:U_.current,nodeId:Ug,getStoreItems:()=>{const{nodeLookup:J2,transform:V_,snapGrid:sP,snapToGrid:Q2,nodeOrigin:q5,domNode:nj}=Bg.getState();return{nodeLookup:J2,transform:V_,snapGrid:sP,snapToGrid:Q2,nodeOrigin:q5,paneDomNode:nj}},onChange:(J2,V_)=>{const{triggerNodeChanges:sP,nodeLookup:Q2,parentLookup:q5,nodeOrigin:nj}=Bg.getState(),n6=[],l6={x:J2.x,y:J2.y},i6=Q2.get(Ug);if(i6&&i6.expandParent&&i6.parentId){const s6=i6.origin??nj,u6=J2.width??i6.measured.width??0,f6=J2.height??i6.measured.height??0,Rpe={id:i6.id,parentId:i6.parentId,rect:{width:u6,height:f6,...evaluateAbsolutePosition({x:J2.x??i6.position.x,y:J2.y??i6.position.y},{width:u6,height:f6},i6.parentId,Q2,s6)}},Xae=handleExpandParent([Rpe],Q2,q5,nj);n6.push(...Xae),l6.x=J2.x?Math.max(s6[0]*u6,J2.x):void 0,l6.y=J2.y?Math.max(s6[1]*f6,J2.y):void 0}if(l6.x!==void 0&&l6.y!==void 0){const s6={id:Ug,type:"position",position:{...l6}};n6.push(s6)}if(J2.width!==void 0&&J2.height!==void 0){const u6={id:Ug,type:"dimensions",resizing:!0,setAttributes:Wd?Wd==="horizontal"?"width":"height":!0,dimensions:{width:J2.width,height:J2.height}};n6.push(u6)}for(const s6 of V_){const u6={...s6,type:"position"};n6.push(u6)}sP(n6)},onEnd:({width:J2,height:V_})=>{const sP={id:Ug,type:"dimensions",resizing:!1,dimensions:{width:J2,height:V_}};Bg.getState().triggerNodeChanges([sP])}})),tj.current.update({controlPosition:aB,boundaries:{minWidth:Pl,minHeight:pc,maxWidth:mc,maxHeight:gc},keepAspectRatio:Vd,resizeDirection:Wd,onResizeStart:Nf,onResize:Eh,onResizeEnd:Em,shouldResize:Pf}),()=>{tj.current?.destroy()}},[aB,Pl,pc,mc,gc,Vd,Nf,Eh,Em,Pf]);const r6=aB.split("-");return jsxRuntimeExports$1.jsx("div",{className:cc(["react-flow__resize-control","nodrag",...r6,Ta,ja]),ref:U_,style:{...La,scale:VC,...wl&&{[B_?"backgroundColor":"borderColor"]:wl}},children:Fa})}reactExports$1.memo(ResizeControl);const INITIAL_VIEWPORT_NODE_ID="__INITIAL_VIEWPORT__",useZoomHandler=()=>{const{getNode:ta,setCenter:Ln,fitView:Ta,getNodes:ja,setViewport:La}=useReactFlow(),{moduleName:Fa}=useParams(),wl=useAppStore(Eh=>Eh.setPreviouslyFocusedNode),Pl=useAppStore(Eh=>Eh.currentFocusedNode),pc=useAppStore(Eh=>Eh.setCurrentFocusedNode),mc=useAppStore(Eh=>Eh.setSelectedAgentId),gc=useAppStore(Eh=>Eh.setSelectedDecisionId),Vd=useAppStore(Eh=>Eh.setLastFocusedAgentId),Wd=useAppStore(Eh=>Eh.pushFocusedNode),kf=useAppStore(Eh=>Eh.clearFocusedForward);return{zoomHandler:(Eh,Em,qg)=>{const Ug=Em?.mode||"normal";Pl&&Pl!==Eh&&(Ug==="normal"?(Wd(Pl),wl(Pl),kf()):Ug==="back"?useAppStore.getState().pushFocusedForward(Pl):Ug==="forward"&&Wd(Pl)),pc(Eh);const Bg=ta(Eh);if(Bg){if(Bg.type==="event")try{const B_=fetchModule$2(Fa||"").getWorkflowForEvent(Eh);if(!B_)return;const VC=B_.name,tj=ta(VC);if(tj){const aB=Bg.width||0,r6=Bg.height||0,J2=Bg.position.x+aB/2,V_=Bg.position.y+r6/2,sP=tj.width||0,Q2=tj.height||0,q5=tj.position.x+sP/2,nj=tj.position.y+Q2/2,n6=(J2+q5)/2,l6=(V_+nj)/2,i6=Math.abs(J2-q5)+(aB+sP)/2,s6=Math.abs(V_-nj)+(r6+Q2),u6=Math.max(i6,s6);let f6=.9;u6>1200?f6=.5:u6>800?f6=.65:u6>500?f6=.8:u6>300&&(f6=.85),requestAnimationFrame(()=>{Ln(n6,l6,{zoom:f6,duration:1200})})}else{const aB=Bg.width||0,r6=Bg.height||0,J2=Bg.position.x+aB/2,V_=Bg.position.y+r6/2;requestAnimationFrame(()=>{Ln(J2,V_,{zoom:1.15,duration:700})})}}catch(U_){console.error("Error getting workflow for event:",U_);const B_=Bg.width||0,VC=Bg.height||0,tj=Bg.position.x+B_/2,aB=Bg.position.y+VC/2;requestAnimationFrame(()=>{Ln(tj,aB,{zoom:1.15,duration:700})})}else if(Bg.type==="agent")try{if(fetchModule$2(Fa||"").getAgent(Eh)){const tj=ja().filter(aB=>aB.type==="swimlane"&&aB.data.name.includes(Eh)).map(aB=>({id:aB.id}));if(tj.length>0)requestAnimationFrame(()=>{Ta({nodes:[{id:Eh},...tj],duration:700,padding:.1})});else{const aB=Bg.width||0,r6=Bg.height||0,J2=Bg.position.x+aB/2,V_=Bg.position.y+r6/2;requestAnimationFrame(()=>{Ln(J2,V_,{zoom:1.15,duration:700})})}}else{const VC=Bg.width||0,tj=Bg.height||0,aB=Bg.position.x+VC/2,r6=Bg.position.y+tj/2;requestAnimationFrame(()=>{Ln(aB,r6,{zoom:1.15,duration:700})})}Vd(Eh),Em?.openForm&&mc(Eh)}catch(U_){console.error("Error getting flows for agent:",U_);const B_=Bg.width||0,VC=Bg.height||0,tj=Bg.position.x+B_/2,aB=Bg.position.y+VC/2;requestAnimationFrame(()=>{Ln(tj,aB,{zoom:1.15,duration:700})})}else if(Bg.type==="decision"){const U_=Bg.width||0,B_=Bg.height||0,VC=Bg.position.x+U_/2,tj=Bg.position.y+B_/2;requestAnimationFrame(()=>{Ln(VC,tj,{zoom:1.15,duration:700})}),Em?.openForm&&(gc(Eh),mc(null))}else if(Bg.type==="decisionNode"){const U_=Bg.width||0,B_=Bg.height||0,VC=Bg.position.x+U_/2,tj=Bg.position.y+B_/2;if(requestAnimationFrame(()=>{Ln(VC,tj,{zoom:1.15,duration:700})}),Em?.openForm){const aB=Eh.replace("decision-node-","");gc(aB),mc(null)}}else{const U_=Bg.width||0,B_=Bg.height||0,VC=Bg.position.x+U_/2,tj=Bg.position.y+B_/2;requestAnimationFrame(()=>{Ln(VC,tj,{zoom:1.15,duration:700})})}qg&&qg()}},restoreInitialViewport:Eh=>{const Em=Eh||{x:100,y:50,zoom:.6};requestAnimationFrame(()=>{typeof La=="function"?La(Em,{duration:700}):Ln(Em.x,Em.y,{zoom:Em.zoom,duration:700})}),pc(null)}}},useSaveUISpec=()=>{const ta=UCe(),{teamName:Ln}=useParams(),Ta=useAppStore(wl=>wl.user),ja=Ta.GitHub.Token,La=Ta.GitHub.Username;return{saveUISpec:(wl,Pl)=>{if(!Ln)throw new Error("Team name is required to save UI spec");ta(wl),saveUISpecToGit(Ln,JSON.stringify(wl,null,2),Pl,La,ja)}}},useAgent=()=>{const{fitView:ta}=useReactFlow(),{incrementModuleDbChangeCount:Ln,setSelectedAgentId:Ta}=useAppStore(),{zoomHandler:ja}=useZoomHandler(),{teamName:La,moduleName:Fa}=useParams(),wl=useAppStore(Xae=>Xae.user),Pl=wl.GitHub.Token,pc=wl.GitHub.Username,mc=Qn$1(),{saveUISpec:gc}=useSaveUISpec(),Vd=()=>{if(!La)throw new Error("teamName is undefined");if(!Fa)throw new Error("moduleName is undefined");return{teamName:La,moduleName:Fa,githubToken:Pl,githubUsername:pc}},Wd=Xae=>{const g$e=Vd(),n$e=fetchModule$2(g$e.moduleName),v$e=n$e.getAgent(Xae);if(!v$e)throw new Error(`Agent ${Xae} not found`);return{module:n$e,agent:v$e,moduleName:g$e.moduleName}},kf=async Xae=>{const{teamName:g$e,moduleName:n$e,githubToken:v$e,githubUsername:S$e}=Vd(),M$e=fetchModule$2(n$e).toString();Ln(),await saveModuleToGit(g$e,n$e,M$e,Xae,S$e,v$e)},Pf=()=>{requestAnimationFrame(()=>{ta()})};return{addAgent:async Xae=>{const g$e=Vd(),n$e=fetchModule$2(g$e.moduleName),v$e=new Agent$2(Xae,n$e.name);if(n$e.addAgent(v$e),n$e.getAgent(Xae)?.setLLM("llm01"),kf(`Add Agent ${Xae}`),mc&&gc)try{const M$e=`${Fa}/${Xae}`,T$e=repopulateUISchemaForNewAgent(mc,M$e);gc(T$e,`Update UI schema for new agent ${Xae}`)}catch(M$e){console.error("Failed to repopulate UI schema for new agent:",M$e)}setTimeout(()=>{Ta(Xae),ja(Xae,{openForm:!0})},200),Pf()},removeAgent:async Xae=>{const g$e=Vd();fetchModule$2(g$e.moduleName).removeAgent(Xae),kf(`Remove Agent ${Xae}`),Pf()},getAgents:()=>{const Xae=Vd();try{const g$e=fetchModule$2(Xae.moduleName);return g$e?g$e.getAgentNames():[]}catch(g$e){return console.error("Failed to get agents:",g$e),[]}},setAgentInstruction:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);if(g$e.length>0){const v$e=escapeAgentlangString(g$e);n$e.setInstruction(v$e)}else n$e.removeInstruction();await kf(`Set Instruction for Agent ${Xae}`)},setAgentLLM:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);g$e.length>0?n$e.setLLM(g$e):n$e.removeLLM(),await kf(`Set LLM for Agent ${Xae}`)},setAgentTools:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);g$e.length>0?n$e.setTools(g$e):n$e.removeTools(),await kf(`Set Tools for Agent ${Xae}`)},setAgentIntegration:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);g$e.length>0?n$e.attributes.set("integration",g$e):n$e.attributes.delete("integration"),await kf(`Set Integration for Agent ${Xae}`)},getAgent:Xae=>{const g$e=Vd(),n$e=fetchModule$2(g$e.moduleName);if(!n$e)throw new Error("Module not found");return n$e.getAgent(Xae)},getAgentDirectives:Xae=>{const{module:g$e}=Wd(Xae);return g$e.getAllDirectives().filter(n$e=>n$e.name.startsWith(`${Xae}.`))},getAgentScenarios:Xae=>{const{module:g$e}=Wd(Xae);return g$e.getAllScenarios().filter(n$e=>n$e.name.startsWith(`${Xae}.`))},getAgentGlossary:Xae=>{const{module:g$e}=Wd(Xae);return g$e.getAllGlossaryEntries().filter(n$e=>n$e.name.startsWith(`${Xae}.`))},getAgentFlows:Xae=>{const{module:g$e}=Wd(Xae);return g$e.getAllFlows().filter(n$e=>n$e.name.startsWith(`${Xae}.`))},setAgentRole:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);if(g$e.length>0){const v$e=escapeAgentlangString(g$e);n$e.attributes.set("role",v$e)}else n$e.removeAttribute("role");await kf(`Set Role for Agent ${Xae}`)},setAgentResponseSchema:async(Xae,g$e)=>{Vd();const{agent:n$e}=Wd(Xae);g$e.length>0?n$e.setResponseSchema(g$e):(console.log("removeAgentResponseSchema",n$e.getAgentFqName()),removeAgentResponseSchema$1(n$e.getAgentFqName())),await kf(`Set Response Schema for Agent ${Xae}`)},removeAgentDirective:async Xae=>{Vd();const{module:g$e}=Wd(Xae.split(".")[0]);g$e.removeDirective(Xae),await kf(`Remove directive ${Xae}`)},addAgentDirective:async Xae=>{Vd();const{module:g$e}=Wd(Xae.split(".")[0]);g$e.addDirective(Xae,newAgentDirectiveFromIf(new IfPattern$1)),await kf(`Add directive ${Xae}`)},updateAgentDirective:async(Xae,g$e,n$e)=>{Vd();const{module:v$e}=Wd(Xae.split(".")[0]);v$e.removeDirective(Xae);const S$e=escapeAgentlangString(g$e),M$e=escapeAgentlangString(n$e),T$e=new IfPattern$1(LiteralPattern$1.String(S$e)).addPattern(LiteralPattern$1.String(M$e));v$e.addDirective(Xae,newAgentDirectiveFromIf(T$e)),await kf(`Update directive ${Xae}`)},removeAgentScenario:async Xae=>{Vd();const{module:g$e}=Wd(Xae.split(".")[0]);g$e.removeScenario(Xae),await kf(`Remove scenario ${Xae}`)},removeAgentGlossary:async Xae=>{Vd();const{module:g$e}=Wd(Xae.split(".")[0]);g$e.removeGlossaryEntry(Xae),await kf(`Remove glossary ${Xae}`)},addAgentScenario:async Xae=>{Vd();const{module:g$e}=Wd(Xae.split(".")[0]);g$e.addScenario(Xae,newAgentScenarioFromIf(new IfPattern$1)),await kf(`Add scenario ${Xae}`)},updateAgentScenario:async(Xae,g$e,n$e)=>{Vd();const{module:v$e}=Wd(Xae.split(".")[0]);v$e.removeScenario(Xae);const S$e=escapeAgentlangString(g$e),M$e=new IfPattern$1(LiteralPattern$1.String(S$e)).addPattern(LiteralPattern$1.Id(n$e));v$e.addScenario(Xae,newAgentScenarioFromIf(M$e)),await kf(`Update scenario ${Xae}`)},addAgentGlossaryEntry:async(Xae,g$e,n$e)=>{Vd();const{module:v$e}=Wd(Xae.split(".")[0]),S$e=escapeAgentlangString(g$e),M$e=n$e?escapeAgentlangString(n$e):"";v$e.addGlossaryEntry(Xae,{name:M$e,meaning:S$e,synonyms:[],internal:!1}),await kf(`Add glossary ${Xae}`)},updateAgentGlossaryEntry:async(Xae,g$e,n$e,v$e)=>{Vd();const{module:S$e}=Wd(Xae.split(".")[0]);S$e.removeGlossaryEntry(Xae);const M$e=escapeAgentlangString(g$e),T$e=v$e?escapeAgentlangString(v$e):"",nae=Array.isArray(n$e)?n$e.map(h$e=>escapeAgentlangString(h$e)).join(", "):escapeAgentlangString(n$e);S$e.addGlossaryEntry(Xae,{name:T$e,meaning:M$e,synonyms:nae,internal:!1}),await kf(`Update glossary ${Xae}`)},setAgentPublic:async(Xae,g$e)=>{Vd();const{agent:n$e,moduleName:v$e}=Wd(Xae);if(n$e.setPublic(g$e),await kf(`Set Public status for Agent ${Xae}`),mc&&gc)try{const S$e=`${v$e}/${Xae}`,M$e=repopulateUISchemaForNewAgent(mc,S$e);gc(M$e,`Update UI schema - agent ${Xae} ${g$e?"made public":"made private"}`)}catch(S$e){console.error("Failed to repopulate UI schema after agent public status change:",S$e)}},getAgentPublic:Xae=>{const{agent:g$e}=Wd(Xae);return g$e.isPublic()}}};function r$e(ta){var Ln,Ta,ja="";if(typeof ta=="string"||typeof ta=="number")ja+=ta;else if(typeof ta=="object")if(Array.isArray(ta)){var La=ta.length;for(Ln=0;Ln<La;Ln++)ta[Ln]&&(Ta=r$e(ta[Ln]))&&(ja&&(ja+=" "),ja+=Ta)}else for(Ta in ta)ta[Ta]&&(ja&&(ja+=" "),ja+=Ta);return ja}function clsx(){for(var ta,Ln,Ta=0,ja="",La=arguments.length;Ta<La;Ta++)(ta=arguments[Ta])&&(Ln=r$e(ta))&&(ja&&(ja+=" "),ja+=Ln);return ja}function Mt$3(ta){if(typeof document>"u")return;let Ln=document.head||document.getElementsByTagName("head")[0],Ta=document.createElement("style");Ta.type="text/css",Ln.firstChild?Ln.insertBefore(Ta,Ln.firstChild):Ln.appendChild(Ta),Ta.styleSheet?Ta.styleSheet.cssText=ta:Ta.appendChild(document.createTextNode(ta))}Mt$3(`:root{--toastify-color-light: #fff;--toastify-color-dark: #121212;--toastify-color-info: #3498db;--toastify-color-success: #07bc0c;--toastify-color-warning: #f1c40f;--toastify-color-error: hsl(6, 78%, 57%);--toastify-color-transparent: rgba(255, 255, 255, .7);--toastify-icon-color-info: var(--toastify-color-info);--toastify-icon-color-success: var(--toastify-color-success);--toastify-icon-color-warning: var(--toastify-color-warning);--toastify-icon-color-error: var(--toastify-color-error);--toastify-container-width: fit-content;--toastify-toast-width: 320px;--toastify-toast-offset: 16px;--toastify-toast-top: max(var(--toastify-toast-offset), env(safe-area-inset-top));--toastify-toast-right: max(var(--toastify-toast-offset), env(safe-area-inset-right));--toastify-toast-left: max(var(--toastify-toast-offset), env(safe-area-inset-left));--toastify-toast-bottom: max(var(--toastify-toast-offset), env(safe-area-inset-bottom));--toastify-toast-background: #fff;--toastify-toast-padding: 14px;--toastify-toast-min-height: 64px;--toastify-toast-max-height: 800px;--toastify-toast-bd-radius: 6px;--toastify-toast-shadow: 0px 4px 12px rgba(0, 0, 0, .1);--toastify-font-family: sans-serif;--toastify-z-index: 9999;--toastify-text-color-light: #757575;--toastify-text-color-dark: #fff;--toastify-text-color-info: #fff;--toastify-text-color-success: #fff;--toastify-text-color-warning: #fff;--toastify-text-color-error: #fff;--toastify-spinner-color: #616161;--toastify-spinner-color-empty-area: #e0e0e0;--toastify-color-progress-light: linear-gradient(to right, #4cd964, #5ac8fa, #007aff, #34aadc, #5856d6, #ff2d55);--toastify-color-progress-dark: #bb86fc;--toastify-color-progress-info: var(--toastify-color-info);--toastify-color-progress-success: var(--toastify-color-success);--toastify-color-progress-warning: var(--toastify-color-warning);--toastify-color-progress-error: var(--toastify-color-error);--toastify-color-progress-bgo: .2}.Toastify__toast-container{z-index:var(--toastify-z-index);-webkit-transform:translate3d(0,0,var(--toastify-z-index));position:fixed;width:var(--toastify-container-width);box-sizing:border-box;color:#fff;display:flex;flex-direction:column}.Toastify__toast-container--top-left{top:var(--toastify-toast-top);left:var(--toastify-toast-left)}.Toastify__toast-container--top-center{top:var(--toastify-toast-top);left:50%;transform:translate(-50%);align-items:center}.Toastify__toast-container--top-right{top:var(--toastify-toast-top);right:var(--toastify-toast-right);align-items:end}.Toastify__toast-container--bottom-left{bottom:var(--toastify-toast-bottom);left:var(--toastify-toast-left)}.Toastify__toast-container--bottom-center{bottom:var(--toastify-toast-bottom);left:50%;transform:translate(-50%);align-items:center}.Toastify__toast-container--bottom-right{bottom:var(--toastify-toast-bottom);right:var(--toastify-toast-right);align-items:end}.Toastify__toast{--y: 0;position:relative;touch-action:none;width:var(--toastify-toast-width);min-height:var(--toastify-toast-min-height);box-sizing:border-box;margin-bottom:1rem;padding:var(--toastify-toast-padding);border-radius:var(--toastify-toast-bd-radius);box-shadow:var(--toastify-toast-shadow);max-height:var(--toastify-toast-max-height);font-family:var(--toastify-font-family);z-index:0;display:flex;flex:1 auto;align-items:center;word-break:break-word}@media only screen and (max-width: 480px){.Toastify__toast-container{width:100vw;left:env(safe-area-inset-left);margin:0}.Toastify__toast-container--top-left,.Toastify__toast-container--top-center,.Toastify__toast-container--top-right{top:env(safe-area-inset-top);transform:translate(0)}.Toastify__toast-container--bottom-left,.Toastify__toast-container--bottom-center,.Toastify__toast-container--bottom-right{bottom:env(safe-area-inset-bottom);transform:translate(0)}.Toastify__toast-container--rtl{right:env(safe-area-inset-right);left:initial}.Toastify__toast{--toastify-toast-width: 100%;margin-bottom:0;border-radius:0}}.Toastify__toast-container[data-stacked=true]{width:var(--toastify-toast-width)}.Toastify__toast--stacked{position:absolute;width:100%;transform:translate3d(0,var(--y),0) scale(var(--s));transition:transform .3s}.Toastify__toast--stacked[data-collapsed] .Toastify__toast-body,.Toastify__toast--stacked[data-collapsed] .Toastify__close-button{transition:opacity .1s}.Toastify__toast--stacked[data-collapsed=false]{overflow:visible}.Toastify__toast--stacked[data-collapsed=true]:not(:last-child)>*{opacity:0}.Toastify__toast--stacked:after{content:"";position:absolute;left:0;right:0;height:calc(var(--g) * 1px);bottom:100%}.Toastify__toast--stacked[data-pos=top]{top:0}.Toastify__toast--stacked[data-pos=bot]{bottom:0}.Toastify__toast--stacked[data-pos=bot].Toastify__toast--stacked:before{transform-origin:top}.Toastify__toast--stacked[data-pos=top].Toastify__toast--stacked:before{transform-origin:bottom}.Toastify__toast--stacked:before{content:"";position:absolute;left:0;right:0;bottom:0;height:100%;transform:scaleY(3);z-index:-1}.Toastify__toast--rtl{direction:rtl}.Toastify__toast--close-on-click{cursor:pointer}.Toastify__toast-icon{margin-inline-end:10px;width:22px;flex-shrink:0;display:flex}.Toastify--animate{animation-fill-mode:both;animation-duration:.5s}.Toastify--animate-icon{animation-fill-mode:both;animation-duration:.3s}.Toastify__toast-theme--dark{background:var(--toastify-color-dark);color:var(--toastify-text-color-dark)}.Toastify__toast-theme--light,.Toastify__toast-theme--colored.Toastify__toast--default{background:var(--toastify-color-light);color:var(--toastify-text-color-light)}.Toastify__toast-theme--colored.Toastify__toast--info{color:var(--toastify-text-color-info);background:var(--toastify-color-info)}.Toastify__toast-theme--colored.Toastify__toast--success{color:var(--toastify-text-color-success);background:var(--toastify-color-success)}.Toastify__toast-theme--colored.Toastify__toast--warning{color:var(--toastify-text-color-warning);background:var(--toastify-color-warning)}.Toastify__toast-theme--colored.Toastify__toast--error{color:var(--toastify-text-color-error);background:var(--toastify-color-error)}.Toastify__progress-bar-theme--light{background:var(--toastify-color-progress-light)}.Toastify__progress-bar-theme--dark{background:var(--toastify-color-progress-dark)}.Toastify__progress-bar--info{background:var(--toastify-color-progress-info)}.Toastify__progress-bar--success{background:var(--toastify-color-progress-success)}.Toastify__progress-bar--warning{background:var(--toastify-color-progress-warning)}.Toastify__progress-bar--error{background:var(--toastify-color-progress-error)}.Toastify__progress-bar-theme--colored.Toastify__progress-bar--info,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--success,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--warning,.Toastify__progress-bar-theme--colored.Toastify__progress-bar--error{background:var(--toastify-color-transparent)}.Toastify__close-button{color:#fff;position:absolute;top:6px;right:6px;background:transparent;outline:none;border:none;padding:0;cursor:pointer;opacity:.7;transition:.3s ease;z-index:1}.Toastify__toast--rtl .Toastify__close-button{left:6px;right:unset}.Toastify__close-button--light{color:#000;opacity:.3}.Toastify__close-button>svg{fill:currentColor;height:16px;width:14px}.Toastify__close-button:hover,.Toastify__close-button:focus{opacity:1}@keyframes Toastify__trackProgress{0%{transform:scaleX(1)}to{transform:scaleX(0)}}.Toastify__progress-bar{position:absolute;bottom:0;left:0;width:100%;height:100%;z-index:1;opacity:.7;transform-origin:left}.Toastify__progress-bar--animated{animation:Toastify__trackProgress linear 1 forwards}.Toastify__progress-bar--controlled{transition:transform .2s}.Toastify__progress-bar--rtl{right:0;left:initial;transform-origin:right;border-bottom-left-radius:initial}.Toastify__progress-bar--wrp{position:absolute;overflow:hidden;bottom:0;left:0;width:100%;height:5px;border-bottom-left-radius:var(--toastify-toast-bd-radius);border-bottom-right-radius:var(--toastify-toast-bd-radius)}.Toastify__progress-bar--wrp[data-hidden=true]{opacity:0}.Toastify__progress-bar--bg{opacity:var(--toastify-color-progress-bgo);width:100%;height:100%}.Toastify__spinner{width:20px;height:20px;box-sizing:border-box;border:2px solid;border-radius:100%;border-color:var(--toastify-spinner-color-empty-area);border-right-color:var(--toastify-spinner-color);animation:Toastify__spin .65s linear infinite}@keyframes Toastify__bounceInRight{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(3000px,0,0)}60%{opacity:1;transform:translate3d(-25px,0,0)}75%{transform:translate3d(10px,0,0)}90%{transform:translate3d(-5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutRight{20%{opacity:1;transform:translate3d(-20px,var(--y),0)}to{opacity:0;transform:translate3d(2000px,var(--y),0)}}@keyframes Toastify__bounceInLeft{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(-3000px,0,0)}60%{opacity:1;transform:translate3d(25px,0,0)}75%{transform:translate3d(-10px,0,0)}90%{transform:translate3d(5px,0,0)}to{transform:none}}@keyframes Toastify__bounceOutLeft{20%{opacity:1;transform:translate3d(20px,var(--y),0)}to{opacity:0;transform:translate3d(-2000px,var(--y),0)}}@keyframes Toastify__bounceInUp{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,3000px,0)}60%{opacity:1;transform:translate3d(0,-20px,0)}75%{transform:translate3d(0,10px,0)}90%{transform:translate3d(0,-5px,0)}to{transform:translateZ(0)}}@keyframes Toastify__bounceOutUp{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,-2000px,0)}}@keyframes Toastify__bounceInDown{0%,60%,75%,90%,to{animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;transform:translate3d(0,-3000px,0)}60%{opacity:1;transform:translate3d(0,25px,0)}75%{transform:translate3d(0,-10px,0)}90%{transform:translate3d(0,5px,0)}to{transform:none}}@keyframes Toastify__bounceOutDown{20%{transform:translate3d(0,calc(var(--y) - 10px),0)}40%,45%{opacity:1;transform:translate3d(0,calc(var(--y) + 20px),0)}to{opacity:0;transform:translate3d(0,2000px,0)}}.Toastify__bounce-enter--top-left,.Toastify__bounce-enter--bottom-left{animation-name:Toastify__bounceInLeft}.Toastify__bounce-enter--top-right,.Toastify__bounce-enter--bottom-right{animation-name:Toastify__bounceInRight}.Toastify__bounce-enter--top-center{animation-name:Toastify__bounceInDown}.Toastify__bounce-enter--bottom-center{animation-name:Toastify__bounceInUp}.Toastify__bounce-exit--top-left,.Toastify__bounce-exit--bottom-left{animation-name:Toastify__bounceOutLeft}.Toastify__bounce-exit--top-right,.Toastify__bounce-exit--bottom-right{animation-name:Toastify__bounceOutRight}.Toastify__bounce-exit--top-center{animation-name:Toastify__bounceOutUp}.Toastify__bounce-exit--bottom-center{animation-name:Toastify__bounceOutDown}@keyframes Toastify__zoomIn{0%{opacity:0;transform:scale3d(.3,.3,.3)}50%{opacity:1}}@keyframes Toastify__zoomOut{0%{opacity:1}50%{opacity:0;transform:translate3d(0,var(--y),0) scale3d(.3,.3,.3)}to{opacity:0}}.Toastify__zoom-enter{animation-name:Toastify__zoomIn}.Toastify__zoom-exit{animation-name:Toastify__zoomOut}@keyframes Toastify__flipIn{0%{transform:perspective(400px) rotateX(90deg);animation-timing-function:ease-in;opacity:0}40%{transform:perspective(400px) rotateX(-20deg);animation-timing-function:ease-in}60%{transform:perspective(400px) rotateX(10deg);opacity:1}80%{transform:perspective(400px) rotateX(-5deg)}to{transform:perspective(400px)}}@keyframes Toastify__flipOut{0%{transform:translate3d(0,var(--y),0) perspective(400px)}30%{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(-20deg);opacity:1}to{transform:translate3d(0,var(--y),0) perspective(400px) rotateX(90deg);opacity:0}}.Toastify__flip-enter{animation-name:Toastify__flipIn}.Toastify__flip-exit{animation-name:Toastify__flipOut}@keyframes Toastify__slideInRight{0%{transform:translate3d(110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInLeft{0%{transform:translate3d(-110%,0,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInUp{0%{transform:translate3d(0,110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideInDown{0%{transform:translate3d(0,-110%,0);visibility:visible}to{transform:translate3d(0,var(--y),0)}}@keyframes Toastify__slideOutRight{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(110%,var(--y),0)}}@keyframes Toastify__slideOutLeft{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(-110%,var(--y),0)}}@keyframes Toastify__slideOutDown{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,500px,0)}}@keyframes Toastify__slideOutUp{0%{transform:translate3d(0,var(--y),0)}to{visibility:hidden;transform:translate3d(0,-500px,0)}}.Toastify__slide-enter--top-left,.Toastify__slide-enter--bottom-left{animation-name:Toastify__slideInLeft}.Toastify__slide-enter--top-right,.Toastify__slide-enter--bottom-right{animation-name:Toastify__slideInRight}.Toastify__slide-enter--top-center{animation-name:Toastify__slideInDown}.Toastify__slide-enter--bottom-center{animation-name:Toastify__slideInUp}.Toastify__slide-exit--top-left,.Toastify__slide-exit--bottom-left{animation-name:Toastify__slideOutLeft;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-right,.Toastify__slide-exit--bottom-right{animation-name:Toastify__slideOutRight;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--top-center{animation-name:Toastify__slideOutUp;animation-timing-function:ease-in;animation-duration:.3s}.Toastify__slide-exit--bottom-center{animation-name:Toastify__slideOutDown;animation-timing-function:ease-in;animation-duration:.3s}@keyframes Toastify__spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}
|
|
34776
|
-
`);var L$7=ta=>typeof ta=="number"&&!isNaN(ta),N$7=ta=>typeof ta=="string",P$b=ta=>typeof ta=="function",mt$2=ta=>N$7(ta)||L$7(ta),B$7=ta=>N$7(ta)||P$b(ta)?ta:null,pt$2=(ta,Ln)=>ta===!1||L$7(ta)&&ta>0?ta:Ln,z$7=ta=>reactExports$1.isValidElement(ta)||N$7(ta)||P$b(ta)||L$7(ta);function Z$5(ta,Ln,Ta=300){let{scrollHeight:ja,style:La}=ta;requestAnimationFrame(()=>{La.minHeight="initial",La.height=ja+"px",La.transition=`all ${Ta}ms`,requestAnimationFrame(()=>{La.height="0",La.padding="0",La.margin="0",setTimeout(Ln,Ta)})})}function $$7({enter:ta,exit:Ln,appendPosition:Ta=!1,collapse:ja=!0,collapseDuration:La=300}){return function({children:Fa,position:wl,preventExitTransition:Pl,done:pc,nodeRef:mc,isIn:gc,playToast:Vd}){let Wd=Ta?`${ta}--${wl}`:ta,kf=Ta?`${Ln}--${wl}`:Ln,Pf=reactExports$1.useRef(0);return reactExports$1.useLayoutEffect(()=>{let Nf=mc.current,Eh=Wd.split(" "),Em=qg=>{qg.target===mc.current&&(Vd(),Nf.removeEventListener("animationend",Em),Nf.removeEventListener("animationcancel",Em),Pf.current===0&&qg.type!=="animationcancel"&&Nf.classList.remove(...Eh))};Nf.classList.add(...Eh),Nf.addEventListener("animationend",Em),Nf.addEventListener("animationcancel",Em)},[]),reactExports$1.useEffect(()=>{let Nf=mc.current,Eh=()=>{Nf.removeEventListener("animationend",Eh),ja?Z$5(Nf,pc,La):pc()};gc||(Pl?Eh():(Pf.current=1,Nf.className+=` ${kf}`,Nf.addEventListener("animationend",Eh)))},[gc]),React.createElement(React.Fragment,null,Fa)}}function J$6(ta,Ln){return{content:tt$2(ta.content,ta.props),containerId:ta.props.containerId,id:ta.props.toastId,theme:ta.props.theme,type:ta.props.type,data:ta.props.data||{},isLoading:ta.props.isLoading,icon:ta.props.icon,reason:ta.removalReason,status:Ln}}function tt$2(ta,Ln,Ta=!1){return reactExports$1.isValidElement(ta)&&!N$7(ta.type)?reactExports$1.cloneElement(ta,{closeToast:Ln.closeToast,toastProps:Ln,data:Ln.data,isPaused:Ta}):P$b(ta)?ta({closeToast:Ln.closeToast,toastProps:Ln,data:Ln.data,isPaused:Ta}):ta}function yt$2({closeToast:ta,theme:Ln,ariaLabel:Ta="close"}){return React.createElement("button",{className:`Toastify__close-button Toastify__close-button--${Ln}`,type:"button",onClick:ja=>{ja.stopPropagation(),ta(!0)},"aria-label":Ta},React.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},React.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}function gt$3({delay:ta,isRunning:Ln,closeToast:Ta,type:ja="default",hide:La,className:Fa,controlledProgress:wl,progress:Pl,rtl:pc,isIn:mc,theme:gc}){let Vd=La||wl&&Pl===0,Wd={animationDuration:`${ta}ms`,animationPlayState:Ln?"running":"paused"};wl&&(Wd.transform=`scaleX(${Pl})`);let kf=clsx("Toastify__progress-bar",wl?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${gc}`,`Toastify__progress-bar--${ja}`,{"Toastify__progress-bar--rtl":pc}),Pf=P$b(Fa)?Fa({rtl:pc,type:ja,defaultClassName:kf}):clsx(kf,Fa),Nf={[wl&&Pl>=1?"onTransitionEnd":"onAnimationEnd"]:wl&&Pl<1?null:()=>{mc&&Ta()}};return React.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":Vd},React.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${gc} Toastify__progress-bar--${ja}`}),React.createElement("div",{role:"progressbar","aria-hidden":Vd?"true":"false","aria-label":"notification timer",className:Pf,style:Wd,...Nf}))}var Xt$1=1,at$2=()=>`${Xt$1++}`;function _t$2(ta,Ln,Ta){let ja=1,La=0,Fa=[],wl=[],Pl=Ln,pc=new Map,mc=new Set,gc=qg=>(mc.add(qg),()=>mc.delete(qg)),Vd=()=>{wl=Array.from(pc.values()),mc.forEach(qg=>qg())},Wd=({containerId:qg,toastId:Ug,updateId:Bg})=>{let U_=qg?qg!==ta:ta!==1,B_=pc.has(Ug)&&Bg==null;return U_||B_},kf=(qg,Ug)=>{pc.forEach(Bg=>{var U_;(Ug==null||Ug===Bg.props.toastId)&&((U_=Bg.toggle)==null||U_.call(Bg,qg))})},Pf=qg=>{var Ug,Bg;(Bg=(Ug=qg.props)==null?void 0:Ug.onClose)==null||Bg.call(Ug,qg.removalReason),qg.isActive=!1},Nf=qg=>{if(qg==null)pc.forEach(Pf);else{let Ug=pc.get(qg);Ug&&Pf(Ug)}Vd()},Eh=()=>{La-=Fa.length,Fa=[]},Em=qg=>{var Ug,Bg;let{toastId:U_,updateId:B_}=qg.props,VC=B_==null;qg.staleId&&pc.delete(qg.staleId),qg.isActive=!0,pc.set(U_,qg),Vd(),Ta(J$6(qg,VC?"added":"updated")),VC&&((Bg=(Ug=qg.props).onOpen)==null||Bg.call(Ug))};return{id:ta,props:Pl,observe:gc,toggle:kf,removeToast:Nf,toasts:pc,clearQueue:Eh,buildToast:(qg,Ug)=>{if(Wd(Ug))return;let{toastId:Bg,updateId:U_,data:B_,staleId:VC,delay:tj}=Ug,aB=U_==null;aB&&La++;let r6={...Pl,style:Pl.toastStyle,key:ja++,...Object.fromEntries(Object.entries(Ug).filter(([V_,sP])=>sP!=null)),toastId:Bg,updateId:U_,data:B_,isIn:!1,className:B$7(Ug.className||Pl.toastClassName),progressClassName:B$7(Ug.progressClassName||Pl.progressClassName),autoClose:Ug.isLoading?!1:pt$2(Ug.autoClose,Pl.autoClose),closeToast(V_){pc.get(Bg).removalReason=V_,Nf(Bg)},deleteToast(){let V_=pc.get(Bg);if(V_!=null){if(Ta(J$6(V_,"removed")),pc.delete(Bg),La--,La<0&&(La=0),Fa.length>0){Em(Fa.shift());return}Vd()}}};r6.closeButton=Pl.closeButton,Ug.closeButton===!1||z$7(Ug.closeButton)?r6.closeButton=Ug.closeButton:Ug.closeButton===!0&&(r6.closeButton=z$7(Pl.closeButton)?Pl.closeButton:!0);let J2={content:qg,props:r6,staleId:VC};Pl.limit&&Pl.limit>0&&La>Pl.limit&&aB?Fa.push(J2):L$7(tj)?setTimeout(()=>{Em(J2)},tj):Em(J2)},setProps(qg){Pl=qg},setToggle:(qg,Ug)=>{let Bg=pc.get(qg);Bg&&(Bg.toggle=Ug)},isToastActive:qg=>{var Ug;return(Ug=pc.get(qg))==null?void 0:Ug.isActive},getSnapshot:()=>wl}}var I$a=new Map,F$9=[],st$2=new Set,Vt$1=ta=>st$2.forEach(Ln=>Ln(ta)),bt$1=()=>I$a.size>0;function Qt$1(){F$9.forEach(ta=>nt$2(ta.content,ta.options)),F$9=[]}var vt$2=(ta,{containerId:Ln})=>{var Ta;return(Ta=I$a.get(Ln||1))==null?void 0:Ta.toasts.get(ta)};function X$5(ta,Ln){var Ta;if(Ln)return!!((Ta=I$a.get(Ln))!=null&&Ta.isToastActive(ta));let ja=!1;return I$a.forEach(La=>{La.isToastActive(ta)&&(ja=!0)}),ja}function ht$2(ta){if(!bt$1()){F$9=F$9.filter(Ln=>ta!=null&&Ln.options.toastId!==ta);return}if(ta==null||mt$2(ta))I$a.forEach(Ln=>{Ln.removeToast(ta)});else if(ta&&("containerId"in ta||"id"in ta)){let Ln=I$a.get(ta.containerId);Ln?Ln.removeToast(ta.id):I$a.forEach(Ta=>{Ta.removeToast(ta.id)})}}var Ct$2=(ta={})=>{I$a.forEach(Ln=>{Ln.props.limit&&(!ta.containerId||Ln.id===ta.containerId)&&Ln.clearQueue()})};function nt$2(ta,Ln){z$7(ta)&&(bt$1()||F$9.push({content:ta,options:Ln}),I$a.forEach(Ta=>{Ta.buildToast(ta,Ln)}))}function xt$1(ta){var Ln;(Ln=I$a.get(ta.containerId||1))==null||Ln.setToggle(ta.id,ta.fn)}function rt$2(ta,Ln){I$a.forEach(Ta=>{(Ln==null||!(Ln!=null&&Ln.containerId)||Ln?.containerId===Ta.id)&&Ta.toggle(ta,Ln?.id)})}function Et$3(ta){let Ln=ta.containerId||1;return{subscribe(Ta){let ja=_t$2(Ln,ta,Vt$1);I$a.set(Ln,ja);let La=ja.observe(Ta);return Qt$1(),()=>{La(),I$a.delete(Ln)}},setProps(Ta){var ja;(ja=I$a.get(Ln))==null||ja.setProps(Ta)},getSnapshot(){var Ta;return(Ta=I$a.get(Ln))==null?void 0:Ta.getSnapshot()}}}function Pt$3(ta){return st$2.add(ta),()=>{st$2.delete(ta)}}function Wt$1(ta){return ta&&(N$7(ta.toastId)||L$7(ta.toastId))?ta.toastId:at$2()}function U$5(ta,Ln){return nt$2(ta,Ln),Ln.toastId}function V$8(ta,Ln){return{...Ln,type:Ln&&Ln.type||ta,toastId:Wt$1(Ln)}}function Q$6(ta){return(Ln,Ta)=>U$5(Ln,V$8(ta,Ta))}function y$b(ta,Ln){return U$5(ta,V$8("default",Ln))}y$b.loading=(ta,Ln)=>U$5(ta,V$8("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...Ln}));function Gt$1(ta,{pending:Ln,error:Ta,success:ja},La){let Fa;Ln&&(Fa=N$7(Ln)?y$b.loading(Ln,La):y$b.loading(Ln.render,{...La,...Ln}));let wl={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},Pl=(mc,gc,Vd)=>{if(gc==null){y$b.dismiss(Fa);return}let Wd={type:mc,...wl,...La,data:Vd},kf=N$7(gc)?{render:gc}:gc;return Fa?y$b.update(Fa,{...Wd,...kf}):y$b(kf.render,{...Wd,...kf}),Vd},pc=P$b(ta)?ta():ta;return pc.then(mc=>Pl("success",ja,mc)).catch(mc=>Pl("error",Ta,mc)),pc}y$b.promise=Gt$1;y$b.success=Q$6("success");y$b.info=Q$6("info");y$b.error=Q$6("error");y$b.warning=Q$6("warning");y$b.warn=y$b.warning;y$b.dark=(ta,Ln)=>U$5(ta,V$8("default",{theme:"dark",...Ln}));function qt$1(ta){ht$2(ta)}y$b.dismiss=qt$1;y$b.clearWaitingQueue=Ct$2;y$b.isActive=X$5;y$b.update=(ta,Ln={})=>{let Ta=vt$2(ta,Ln);if(Ta){let{props:ja,content:La}=Ta,Fa={delay:100,...ja,...Ln,toastId:Ln.toastId||ta,updateId:at$2()};Fa.toastId!==ta&&(Fa.staleId=ta);let wl=Fa.render||La;delete Fa.render,U$5(wl,Fa)}};y$b.done=ta=>{y$b.update(ta,{progress:1})};y$b.onChange=Pt$3;y$b.play=ta=>rt$2(!0,ta);y$b.pause=ta=>rt$2(!1,ta);function It$2(ta){var Ln;let{subscribe:Ta,getSnapshot:ja,setProps:La}=reactExports$1.useRef(Et$3(ta)).current;La(ta);let Fa=(Ln=reactExports$1.useSyncExternalStore(Ta,ja,ja))==null?void 0:Ln.slice();function wl(Pl){if(!Fa)return[];let pc=new Map;return ta.newestOnTop&&Fa.reverse(),Fa.forEach(mc=>{let{position:gc}=mc.props;pc.has(gc)||pc.set(gc,[]),pc.get(gc).push(mc)}),Array.from(pc,mc=>Pl(mc[0],mc[1]))}return{getToastToRender:wl,isToastActive:X$5,count:Fa?.length}}function At$2(ta){let[Ln,Ta]=reactExports$1.useState(!1),[ja,La]=reactExports$1.useState(!1),Fa=reactExports$1.useRef(null),wl=reactExports$1.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:Pl,pauseOnHover:pc,closeToast:mc,onClick:gc,closeOnClick:Vd}=ta;xt$1({id:ta.toastId,containerId:ta.containerId,fn:Ta}),reactExports$1.useEffect(()=>{if(ta.pauseOnFocusLoss)return Wd(),()=>{kf()}},[ta.pauseOnFocusLoss]);function Wd(){document.hasFocus()||Em(),window.addEventListener("focus",Eh),window.addEventListener("blur",Em)}function kf(){window.removeEventListener("focus",Eh),window.removeEventListener("blur",Em)}function Pf(VC){if(ta.draggable===!0||ta.draggable===VC.pointerType){qg();let tj=Fa.current;wl.canCloseOnClick=!0,wl.canDrag=!0,tj.style.transition="none",ta.draggableDirection==="x"?(wl.start=VC.clientX,wl.removalDistance=tj.offsetWidth*(ta.draggablePercent/100)):(wl.start=VC.clientY,wl.removalDistance=tj.offsetHeight*(ta.draggablePercent===80?ta.draggablePercent*1.5:ta.draggablePercent)/100)}}function Nf(VC){let{top:tj,bottom:aB,left:r6,right:J2}=Fa.current.getBoundingClientRect();VC.nativeEvent.type!=="touchend"&&ta.pauseOnHover&&VC.clientX>=r6&&VC.clientX<=J2&&VC.clientY>=tj&&VC.clientY<=aB?Em():Eh()}function Eh(){Ta(!0)}function Em(){Ta(!1)}function qg(){wl.didMove=!1,document.addEventListener("pointermove",Bg),document.addEventListener("pointerup",U_)}function Ug(){document.removeEventListener("pointermove",Bg),document.removeEventListener("pointerup",U_)}function Bg(VC){let tj=Fa.current;if(wl.canDrag&&tj){wl.didMove=!0,Ln&&Em(),ta.draggableDirection==="x"?wl.delta=VC.clientX-wl.start:wl.delta=VC.clientY-wl.start,wl.start!==VC.clientX&&(wl.canCloseOnClick=!1);let aB=ta.draggableDirection==="x"?`${wl.delta}px, var(--y)`:`0, calc(${wl.delta}px + var(--y))`;tj.style.transform=`translate3d(${aB},0)`,tj.style.opacity=`${1-Math.abs(wl.delta/wl.removalDistance)}`}}function U_(){Ug();let VC=Fa.current;if(wl.canDrag&&wl.didMove&&VC){if(wl.canDrag=!1,Math.abs(wl.delta)>wl.removalDistance){La(!0),ta.closeToast(!0),ta.collapseAll();return}VC.style.transition="transform 0.2s, opacity 0.2s",VC.style.removeProperty("transform"),VC.style.removeProperty("opacity")}}let B_={onPointerDown:Pf,onPointerUp:Nf};return Pl&&pc&&(B_.onMouseEnter=Em,ta.stacked||(B_.onMouseLeave=Eh)),Vd&&(B_.onClick=VC=>{gc&&gc(VC),wl.canCloseOnClick&&mc(!0)}),{playToast:Eh,pauseToast:Em,isRunning:Ln,preventExitTransition:ja,toastRef:Fa,eventHandlers:B_}}var Ot$1=typeof window<"u"?reactExports$1.useLayoutEffect:reactExports$1.useEffect,G$6=({theme:ta,type:Ln,isLoading:Ta,...ja})=>React.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:ta==="colored"?"currentColor":`var(--toastify-icon-color-${Ln})`,...ja});function ao$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))}function so$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))}function no$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))}function ro$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))}function io$1(){return React.createElement("div",{className:"Toastify__spinner"})}var W$5={info:so$1,warning:ao$1,success:no$1,error:ro$1,spinner:io$1},lo$2=ta=>ta in W$5;function Nt$1({theme:ta,type:Ln,isLoading:Ta,icon:ja}){let La=null,Fa={theme:ta,type:Ln};return ja===!1||(P$b(ja)?La=ja({...Fa,isLoading:Ta}):reactExports$1.isValidElement(ja)?La=reactExports$1.cloneElement(ja,Fa):Ta?La=W$5.spinner():lo$2(Ln)&&(La=W$5[Ln](Fa))),La}var wt$2=ta=>{let{isRunning:Ln,preventExitTransition:Ta,toastRef:ja,eventHandlers:La,playToast:Fa}=At$2(ta),{closeButton:wl,children:Pl,autoClose:pc,onClick:mc,type:gc,hideProgressBar:Vd,closeToast:Wd,transition:kf,position:Pf,className:Nf,style:Eh,progressClassName:Em,updateId:qg,role:Ug,progress:Bg,rtl:U_,toastId:B_,deleteToast:VC,isIn:tj,isLoading:aB,closeOnClick:r6,theme:J2,ariaLabel:V_}=ta,sP=clsx("Toastify__toast",`Toastify__toast-theme--${J2}`,`Toastify__toast--${gc}`,{"Toastify__toast--rtl":U_},{"Toastify__toast--close-on-click":r6}),Q2=P$b(Nf)?Nf({rtl:U_,position:Pf,type:gc,defaultClassName:sP}):clsx(sP,Nf),q5=Nt$1(ta),nj=!!Bg||!pc,n6={closeToast:Wd,type:gc,theme:J2},l6=null;return wl===!1||(P$b(wl)?l6=wl(n6):reactExports$1.isValidElement(wl)?l6=reactExports$1.cloneElement(wl,n6):l6=yt$2(n6)),React.createElement(kf,{isIn:tj,done:VC,position:Pf,preventExitTransition:Ta,nodeRef:ja,playToast:Fa},React.createElement("div",{id:B_,tabIndex:0,onClick:mc,"data-in":tj,className:Q2,...La,style:Eh,ref:ja,...tj&&{role:Ug,"aria-label":V_}},q5!=null&&React.createElement("div",{className:clsx("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!aB})},q5),tt$2(Pl,ta,!Ln),l6,!ta.customProgressBar&&React.createElement(gt$3,{...qg&&!nj?{key:`p-${qg}`}:{},rtl:U_,theme:J2,delay:pc,isRunning:Ln,isIn:tj,closeToast:Wd,hide:Vd,type:gc,className:Em,controlledProgress:nj,progress:Bg||0})))},K$7=(ta,Ln=!1)=>({enter:`Toastify--animate Toastify__${ta}-enter`,exit:`Toastify--animate Toastify__${ta}-exit`,appendPosition:Ln}),lt$2=$$7(K$7("bounce",!0)),_o$1={position:"top-right",transition:lt$2,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light","aria-label":"Notifications Alt+T",hotKeys:ta=>ta.altKey&&ta.code==="KeyT"};function Lt$1(ta){let Ln={..._o$1,...ta},Ta=ta.stacked,[ja,La]=reactExports$1.useState(!0),Fa=reactExports$1.useRef(null),{getToastToRender:wl,isToastActive:Pl,count:pc}=It$2(Ln),{className:mc,style:gc,rtl:Vd,containerId:Wd,hotKeys:kf}=Ln;function Pf(Eh){let Em=clsx("Toastify__toast-container",`Toastify__toast-container--${Eh}`,{"Toastify__toast-container--rtl":Vd});return P$b(mc)?mc({position:Eh,rtl:Vd,defaultClassName:Em}):clsx(Em,B$7(mc))}function Nf(){Ta&&(La(!0),y$b.play())}return Ot$1(()=>{var Eh;if(Ta){let Em=Fa.current.querySelectorAll('[data-in="true"]'),qg=12,Ug=(Eh=Ln.position)==null?void 0:Eh.includes("top"),Bg=0,U_=0;Array.from(Em).reverse().forEach((B_,VC)=>{let tj=B_;tj.classList.add("Toastify__toast--stacked"),VC>0&&(tj.dataset.collapsed=`${ja}`),tj.dataset.pos||(tj.dataset.pos=Ug?"top":"bot");let aB=Bg*(ja?.2:1)+(ja?0:qg*VC);tj.style.setProperty("--y",`${Ug?aB:aB*-1}px`),tj.style.setProperty("--g",`${qg}`),tj.style.setProperty("--s",`${1-(ja?U_:0)}`),Bg+=tj.offsetHeight,U_+=.025})}},[ja,pc,Ta]),reactExports$1.useEffect(()=>{function Eh(Em){var qg;let Ug=Fa.current;kf(Em)&&((qg=Ug.querySelector('[tabIndex="0"]'))==null||qg.focus(),La(!1),y$b.pause()),Em.key==="Escape"&&(document.activeElement===Ug||Ug!=null&&Ug.contains(document.activeElement))&&(La(!0),y$b.play())}return document.addEventListener("keydown",Eh),()=>{document.removeEventListener("keydown",Eh)}},[kf]),React.createElement("section",{ref:Fa,className:"Toastify",id:Wd,onMouseEnter:()=>{Ta&&(La(!1),y$b.pause())},onMouseLeave:Nf,"aria-live":"polite","aria-atomic":"false","aria-relevant":"additions text","aria-label":Ln["aria-label"]},wl((Eh,Em)=>{let qg=Em.length?{...gc}:{...gc,pointerEvents:"none"};return React.createElement("div",{tabIndex:-1,className:Pf(Eh),"data-stacked":Ta,style:qg,key:`c-${Eh}`},Em.map(({content:Ug,props:Bg})=>React.createElement(wt$2,{...Bg,stacked:Ta,collapseAll:Nf,isIn:Pl(Bg.toastId,Bg.containerId),key:`t-${Bg.key}`},Ug)))}))}const RECENTLY_VISITED_TEAMS_KEY="recently-visited-teams",MAX_RECENTLY_VISITED=10;function transformSimpleTeamToTeam(ta){return{Branch:ta.branch||"",Config:ta.config||{},CreatedAt:ta.createdAt||"",Dependencies:ta.dependencies||{FractlModels:[],ClojureLibraries:[]},Description:ta.description||"",EntityType:ta.entityType||"",GitHubOrg:ta.gitHubOrg||"",GitHubRepo:ta.gitHubRepo||"",GithubUrl:ta.githubUrl||"",Id:ta.id||"",__Id__:ta.__Id__||ta.id||"",LastUpdatedAt:ta.lastUpdatedAt||"",Name:ta.name||"",Owner:ta.owner||"",Tags:ta.tags||null,Type:ta.type||"",Version:ta.version||"",isEditable:ta.isEditable||!1,isPin:ta.isPin==="true"||ta.isPin===!0}}function getRecentlyVisitedTeams(){try{const ta=localStorage.getItem(RECENTLY_VISITED_TEAMS_KEY);return ta?JSON.parse(ta):[]}catch{return[]}}function addRecentlyVisitedTeam(ta){try{const Ta=getRecentlyVisitedTeams().filter(La=>La!==ta),ja=[ta,...Ta].slice(0,MAX_RECENTLY_VISITED);localStorage.setItem(RECENTLY_VISITED_TEAMS_KEY,JSON.stringify(ja))}catch(Ln){console.warn("Failed to save recently visited team:",Ln)}}function filterAndSortTeams(ta,Ln){return Object.values(ta).filter(ja=>ja.Name!==void 0).filter(ja=>(ja.Name??"").toLowerCase().includes(Ln.toLowerCase())).sort((ja,La)=>{const Fa=Number(La.isPin??!1)-Number(ja.isPin??!1);if(Fa!==0)return Fa;const wl=(ja.Name??"").toLowerCase(),Pl=(La.Name??"").toLowerCase();return wl.localeCompare(Pl)})}function getIconsTree(ta,Ln){const Ta=ta.icons,ja=ta.aliases||Object.create(null),La=Object.create(null);function Fa(wl){if(Ta[wl])return La[wl]=[];if(!(wl in La)){La[wl]=null;const Pl=ja[wl]&&ja[wl].parent,pc=Pl&&Fa(Pl);pc&&(La[wl]=[Pl].concat(pc))}return La[wl]}return Object.keys(Ta).concat(Object.keys(ja)).forEach(Fa),La}const defaultIconDimensions=Object.freeze({left:0,top:0,width:16,height:16}),defaultIconTransformations=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),defaultIconProps=Object.freeze({...defaultIconDimensions,...defaultIconTransformations}),defaultExtendedIconProps=Object.freeze({...defaultIconProps,body:"",hidden:!1});function mergeIconTransformations(ta,Ln){const Ta={};!ta.hFlip!=!Ln.hFlip&&(Ta.hFlip=!0),!ta.vFlip!=!Ln.vFlip&&(Ta.vFlip=!0);const ja=((ta.rotate||0)+(Ln.rotate||0))%4;return ja&&(Ta.rotate=ja),Ta}function mergeIconData(ta,Ln){const Ta=mergeIconTransformations(ta,Ln);for(const ja in defaultExtendedIconProps)ja in defaultIconTransformations?ja in ta&&!(ja in Ta)&&(Ta[ja]=defaultIconTransformations[ja]):ja in Ln?Ta[ja]=Ln[ja]:ja in ta&&(Ta[ja]=ta[ja]);return Ta}function internalGetIconData(ta,Ln,Ta){const ja=ta.icons,La=ta.aliases||Object.create(null);let Fa={};function wl(Pl){Fa=mergeIconData(ja[Pl]||La[Pl],Fa)}return wl(Ln),Ta.forEach(wl),mergeIconData(ta,Fa)}function parseIconSet(ta,Ln){const Ta=[];if(typeof ta!="object"||typeof ta.icons!="object")return Ta;ta.not_found instanceof Array&&ta.not_found.forEach(La=>{Ln(La,null),Ta.push(La)});const ja=getIconsTree(ta);for(const La in ja){const Fa=ja[La];Fa&&(Ln(La,internalGetIconData(ta,La,Fa)),Ta.push(La))}return Ta}const optionalPropertyDefaults={provider:"",aliases:{},not_found:{},...defaultIconDimensions};function checkOptionalProps(ta,Ln){for(const Ta in Ln)if(Ta in ta&&typeof ta[Ta]!=typeof Ln[Ta])return!1;return!0}function quicklyValidateIconSet(ta){if(typeof ta!="object"||ta===null)return null;const Ln=ta;if(typeof Ln.prefix!="string"||!ta.icons||typeof ta.icons!="object"||!checkOptionalProps(ta,optionalPropertyDefaults))return null;const Ta=Ln.icons;for(const La in Ta){const Fa=Ta[La];if(!La||typeof Fa.body!="string"||!checkOptionalProps(Fa,defaultExtendedIconProps))return null}const ja=Ln.aliases||Object.create(null);for(const La in ja){const Fa=ja[La],wl=Fa.parent;if(!La||typeof wl!="string"||!Ta[wl]&&!ja[wl]||!checkOptionalProps(Fa,defaultExtendedIconProps))return null}return Ln}const dataStorage=Object.create(null);function newStorage(ta,Ln){return{provider:ta,prefix:Ln,icons:Object.create(null),missing:new Set}}function getStorage(ta,Ln){const Ta=dataStorage[ta]||(dataStorage[ta]=Object.create(null));return Ta[Ln]||(Ta[Ln]=newStorage(ta,Ln))}function addIconSet(ta,Ln){return quicklyValidateIconSet(Ln)?parseIconSet(Ln,(Ta,ja)=>{ja?ta.icons[Ta]=ja:ta.missing.add(Ta)}):[]}function addIconToStorage(ta,Ln,Ta){try{if(typeof Ta.body=="string")return ta.icons[Ln]={...Ta},!0}catch{}return!1}const matchIconName=/^[a-z0-9]+(-[a-z0-9]+)*$/,stringToIcon=(ta,Ln,Ta,ja="")=>{const La=ta.split(":");if(ta.slice(0,1)==="@"){if(La.length<2||La.length>3)return null;ja=La.shift().slice(1)}if(La.length>3||!La.length)return null;if(La.length>1){const Pl=La.pop(),pc=La.pop(),mc={provider:La.length>0?La[0]:ja,prefix:pc,name:Pl};return Ln&&!validateIconName(mc)?null:mc}const Fa=La[0],wl=Fa.split("-");if(wl.length>1){const Pl={provider:ja,prefix:wl.shift(),name:wl.join("-")};return Ln&&!validateIconName(Pl)?null:Pl}if(Ta&&ja===""){const Pl={provider:ja,prefix:"",name:Fa};return Ln&&!validateIconName(Pl,Ta)?null:Pl}return null},validateIconName=(ta,Ln)=>ta?!!((Ln&&ta.prefix===""||ta.prefix)&&ta.name):!1;let simpleNames=!1;function allowSimpleNames(ta){return typeof ta=="boolean"&&(simpleNames=ta),simpleNames}function getIconData(ta){const Ln=typeof ta=="string"?stringToIcon(ta,!0,simpleNames):ta;if(Ln){const Ta=getStorage(Ln.provider,Ln.prefix),ja=Ln.name;return Ta.icons[ja]||(Ta.missing.has(ja)?null:void 0)}}function addIcon(ta,Ln){const Ta=stringToIcon(ta,!0,simpleNames);if(!Ta)return!1;const ja=getStorage(Ta.provider,Ta.prefix);return Ln?addIconToStorage(ja,Ta.name,Ln):(ja.missing.add(Ta.name),!0)}function addCollection(ta,Ln){if(typeof ta!="object")return!1;if(typeof Ln!="string"&&(Ln=ta.provider||""),simpleNames&&!Ln&&!ta.prefix){let La=!1;return quicklyValidateIconSet(ta)&&(ta.prefix="",parseIconSet(ta,(Fa,wl)=>{addIcon(Fa,wl)&&(La=!0)})),La}const Ta=ta.prefix;if(!validateIconName({prefix:Ta,name:"a"}))return!1;const ja=getStorage(Ln,Ta);return!!addIconSet(ja,ta)}const defaultIconSizeCustomisations=Object.freeze({width:null,height:null}),defaultIconCustomisations=Object.freeze({...defaultIconSizeCustomisations,...defaultIconTransformations}),unitsSplit=/(-?[0-9.]*[0-9]+[0-9.]*)/g,unitsTest=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function calculateSize(ta,Ln,Ta){if(Ln===1)return ta;if(Ta=Ta||100,typeof ta=="number")return Math.ceil(ta*Ln*Ta)/Ta;if(typeof ta!="string")return ta;const ja=ta.split(unitsSplit);if(ja===null||!ja.length)return ta;const La=[];let Fa=ja.shift(),wl=unitsTest.test(Fa);for(;;){if(wl){const Pl=parseFloat(Fa);isNaN(Pl)?La.push(Fa):La.push(Math.ceil(Pl*Ln*Ta)/Ta)}else La.push(Fa);if(Fa=ja.shift(),Fa===void 0)return La.join("");wl=!wl}}function splitSVGDefs(ta,Ln="defs"){let Ta="";const ja=ta.indexOf("<"+Ln);for(;ja>=0;){const La=ta.indexOf(">",ja),Fa=ta.indexOf("</"+Ln);if(La===-1||Fa===-1)break;const wl=ta.indexOf(">",Fa);if(wl===-1)break;Ta+=ta.slice(La+1,Fa).trim(),ta=ta.slice(0,ja).trim()+ta.slice(wl+1)}return{defs:Ta,content:ta}}function mergeDefsAndContent(ta,Ln){return ta?"<defs>"+ta+"</defs>"+Ln:Ln}function wrapSVGContent(ta,Ln,Ta){const ja=splitSVGDefs(ta);return mergeDefsAndContent(ja.defs,Ln+ja.content+Ta)}const isUnsetKeyword=ta=>ta==="unset"||ta==="undefined"||ta==="none";function iconToSVG(ta,Ln){const Ta={...defaultIconProps,...ta},ja={...defaultIconCustomisations,...Ln},La={left:Ta.left,top:Ta.top,width:Ta.width,height:Ta.height};let Fa=Ta.body;[Ta,ja].forEach(Nf=>{const Eh=[],Em=Nf.hFlip,qg=Nf.vFlip;let Ug=Nf.rotate;Em?qg?Ug+=2:(Eh.push("translate("+(La.width+La.left).toString()+" "+(0-La.top).toString()+")"),Eh.push("scale(-1 1)"),La.top=La.left=0):qg&&(Eh.push("translate("+(0-La.left).toString()+" "+(La.height+La.top).toString()+")"),Eh.push("scale(1 -1)"),La.top=La.left=0);let Bg;switch(Ug<0&&(Ug-=Math.floor(Ug/4)*4),Ug=Ug%4,Ug){case 1:Bg=La.height/2+La.top,Eh.unshift("rotate(90 "+Bg.toString()+" "+Bg.toString()+")");break;case 2:Eh.unshift("rotate(180 "+(La.width/2+La.left).toString()+" "+(La.height/2+La.top).toString()+")");break;case 3:Bg=La.width/2+La.left,Eh.unshift("rotate(-90 "+Bg.toString()+" "+Bg.toString()+")");break}Ug%2===1&&(La.left!==La.top&&(Bg=La.left,La.left=La.top,La.top=Bg),La.width!==La.height&&(Bg=La.width,La.width=La.height,La.height=Bg)),Eh.length&&(Fa=wrapSVGContent(Fa,'<g transform="'+Eh.join(" ")+'">',"</g>"))});const wl=ja.width,Pl=ja.height,pc=La.width,mc=La.height;let gc,Vd;wl===null?(Vd=Pl===null?"1em":Pl==="auto"?mc:Pl,gc=calculateSize(Vd,pc/mc)):(gc=wl==="auto"?pc:wl,Vd=Pl===null?calculateSize(gc,mc/pc):Pl==="auto"?mc:Pl);const Wd={},kf=(Nf,Eh)=>{isUnsetKeyword(Eh)||(Wd[Nf]=Eh.toString())};kf("width",gc),kf("height",Vd);const Pf=[La.left,La.top,pc,mc];return Wd.viewBox=Pf.join(" "),{attributes:Wd,viewBox:Pf,body:Fa}}const regex=/\sid="(\S+)"/g,randomPrefix="IconifyId"+Date.now().toString(16)+(Math.random()*16777216|0).toString(16);let counter=0;function replaceIDs(ta,Ln=randomPrefix){const Ta=[];let ja;for(;ja=regex.exec(ta);)Ta.push(ja[1]);if(!Ta.length)return ta;const La="suffix"+(Math.random()*16777216|Date.now()).toString(16);return Ta.forEach(Fa=>{const wl=typeof Ln=="function"?Ln(Fa):Ln+(counter++).toString(),Pl=Fa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");ta=ta.replace(new RegExp('([#;"])('+Pl+')([")]|\\.[a-z])',"g"),"$1"+wl+La+"$3")}),ta=ta.replace(new RegExp(La,"g"),""),ta}const storage=Object.create(null);function setAPIModule(ta,Ln){storage[ta]=Ln}function getAPIModule(ta){return storage[ta]||storage[""]}function createAPIConfig(ta){let Ln;if(typeof ta.resources=="string")Ln=[ta.resources];else if(Ln=ta.resources,!(Ln instanceof Array)||!Ln.length)return null;return{resources:Ln,path:ta.path||"/",maxURL:ta.maxURL||500,rotate:ta.rotate||750,timeout:ta.timeout||5e3,random:ta.random===!0,index:ta.index||0,dataAfterTimeout:ta.dataAfterTimeout!==!1}}const configStorage=Object.create(null),fallBackAPISources=["https://api.simplesvg.com","https://api.unisvg.com"],fallBackAPI=[];for(;fallBackAPISources.length>0;)fallBackAPISources.length===1||Math.random()>.5?fallBackAPI.push(fallBackAPISources.shift()):fallBackAPI.push(fallBackAPISources.pop());configStorage[""]=createAPIConfig({resources:["https://api.iconify.design"].concat(fallBackAPI)});function addAPIProvider(ta,Ln){const Ta=createAPIConfig(Ln);return Ta===null?!1:(configStorage[ta]=Ta,!0)}function getAPIConfig(ta){return configStorage[ta]}const detectFetch=()=>{let ta;try{if(ta=fetch,typeof ta=="function")return ta}catch{}};let fetchModule=detectFetch();function calculateMaxLength(ta,Ln){const Ta=getAPIConfig(ta);if(!Ta)return 0;let ja;if(!Ta.maxURL)ja=0;else{let La=0;Ta.resources.forEach(wl=>{La=Math.max(La,wl.length)});const Fa=Ln+".json?icons=";ja=Ta.maxURL-La-Ta.path.length-Fa.length}return ja}function shouldAbort(ta){return ta===404}const prepare=(ta,Ln,Ta)=>{const ja=[],La=calculateMaxLength(ta,Ln),Fa="icons";let wl={type:Fa,provider:ta,prefix:Ln,icons:[]},Pl=0;return Ta.forEach((pc,mc)=>{Pl+=pc.length+1,Pl>=La&&mc>0&&(ja.push(wl),wl={type:Fa,provider:ta,prefix:Ln,icons:[]},Pl=pc.length),wl.icons.push(pc)}),ja.push(wl),ja};function getPath$2(ta){if(typeof ta=="string"){const Ln=getAPIConfig(ta);if(Ln)return Ln.path}return"/"}const send=(ta,Ln,Ta)=>{if(!fetchModule){Ta("abort",424);return}let ja=getPath$2(Ln.provider);switch(Ln.type){case"icons":{const Fa=Ln.prefix,Pl=Ln.icons.join(","),pc=new URLSearchParams({icons:Pl});ja+=Fa+".json?"+pc.toString();break}case"custom":{const Fa=Ln.uri;ja+=Fa.slice(0,1)==="/"?Fa.slice(1):Fa;break}default:Ta("abort",400);return}let La=503;fetchModule(ta+ja).then(Fa=>{const wl=Fa.status;if(wl!==200){setTimeout(()=>{Ta(shouldAbort(wl)?"abort":"next",wl)});return}return La=501,Fa.json()}).then(Fa=>{if(typeof Fa!="object"||Fa===null){setTimeout(()=>{Fa===404?Ta("abort",Fa):Ta("next",La)});return}setTimeout(()=>{Ta("success",Fa)})}).catch(()=>{Ta("next",La)})},fetchAPIModule={prepare,send};function removeCallback(ta,Ln){ta.forEach(Ta=>{const ja=Ta.loaderCallbacks;ja&&(Ta.loaderCallbacks=ja.filter(La=>La.id!==Ln))})}function updateCallbacks(ta){ta.pendingCallbacksFlag||(ta.pendingCallbacksFlag=!0,setTimeout(()=>{ta.pendingCallbacksFlag=!1;const Ln=ta.loaderCallbacks?ta.loaderCallbacks.slice(0):[];if(!Ln.length)return;let Ta=!1;const ja=ta.provider,La=ta.prefix;Ln.forEach(Fa=>{const wl=Fa.icons,Pl=wl.pending.length;wl.pending=wl.pending.filter(pc=>{if(pc.prefix!==La)return!0;const mc=pc.name;if(ta.icons[mc])wl.loaded.push({provider:ja,prefix:La,name:mc});else if(ta.missing.has(mc))wl.missing.push({provider:ja,prefix:La,name:mc});else return Ta=!0,!0;return!1}),wl.pending.length!==Pl&&(Ta||removeCallback([ta],Fa.id),Fa.callback(wl.loaded.slice(0),wl.missing.slice(0),wl.pending.slice(0),Fa.abort))})}))}let idCounter$1=0;function storeCallback(ta,Ln,Ta){const ja=idCounter$1++,La=removeCallback.bind(null,Ta,ja);if(!Ln.pending.length)return La;const Fa={id:ja,icons:Ln,callback:ta,abort:La};return Ta.forEach(wl=>{(wl.loaderCallbacks||(wl.loaderCallbacks=[])).push(Fa)}),La}function sortIcons(ta){const Ln={loaded:[],missing:[],pending:[]},Ta=Object.create(null);ta.sort((La,Fa)=>La.provider!==Fa.provider?La.provider.localeCompare(Fa.provider):La.prefix!==Fa.prefix?La.prefix.localeCompare(Fa.prefix):La.name.localeCompare(Fa.name));let ja={provider:"",prefix:"",name:""};return ta.forEach(La=>{if(ja.name===La.name&&ja.prefix===La.prefix&&ja.provider===La.provider)return;ja=La;const Fa=La.provider,wl=La.prefix,Pl=La.name,pc=Ta[Fa]||(Ta[Fa]=Object.create(null)),mc=pc[wl]||(pc[wl]=getStorage(Fa,wl));let gc;Pl in mc.icons?gc=Ln.loaded:wl===""||mc.missing.has(Pl)?gc=Ln.missing:gc=Ln.pending;const Vd={provider:Fa,prefix:wl,name:Pl};gc.push(Vd)}),Ln}function listToIcons(ta,Ln=!0,Ta=!1){const ja=[];return ta.forEach(La=>{const Fa=typeof La=="string"?stringToIcon(La,Ln,Ta):La;Fa&&ja.push(Fa)}),ja}const defaultConfig={resources:[],index:0,timeout:2e3,rotate:750,random:!1,dataAfterTimeout:!1};function sendQuery(ta,Ln,Ta,ja){const La=ta.resources.length,Fa=ta.random?Math.floor(Math.random()*La):ta.index;let wl;if(ta.random){let B_=ta.resources.slice(0);for(wl=[];B_.length>1;){const VC=Math.floor(Math.random()*B_.length);wl.push(B_[VC]),B_=B_.slice(0,VC).concat(B_.slice(VC+1))}wl=wl.concat(B_)}else wl=ta.resources.slice(Fa).concat(ta.resources.slice(0,Fa));const Pl=Date.now();let pc="pending",mc=0,gc,Vd=null,Wd=[],kf=[];typeof ja=="function"&&kf.push(ja);function Pf(){Vd&&(clearTimeout(Vd),Vd=null)}function Nf(){pc==="pending"&&(pc="aborted"),Pf(),Wd.forEach(B_=>{B_.status==="pending"&&(B_.status="aborted")}),Wd=[]}function Eh(B_,VC){VC&&(kf=[]),typeof B_=="function"&&kf.push(B_)}function Em(){return{startTime:Pl,payload:Ln,status:pc,queriesSent:mc,queriesPending:Wd.length,subscribe:Eh,abort:Nf}}function qg(){pc="failed",kf.forEach(B_=>{B_(void 0,gc)})}function Ug(){Wd.forEach(B_=>{B_.status==="pending"&&(B_.status="aborted")}),Wd=[]}function Bg(B_,VC,tj){const aB=VC!=="success";switch(Wd=Wd.filter(r6=>r6!==B_),pc){case"pending":break;case"failed":if(aB||!ta.dataAfterTimeout)return;break;default:return}if(VC==="abort"){gc=tj,qg();return}if(aB){gc=tj,Wd.length||(wl.length?U_():qg());return}if(Pf(),Ug(),!ta.random){const r6=ta.resources.indexOf(B_.resource);r6!==-1&&r6!==ta.index&&(ta.index=r6)}pc="completed",kf.forEach(r6=>{r6(tj)})}function U_(){if(pc!=="pending")return;Pf();const B_=wl.shift();if(B_===void 0){if(Wd.length){Vd=setTimeout(()=>{Pf(),pc==="pending"&&(Ug(),qg())},ta.timeout);return}qg();return}const VC={status:"pending",resource:B_,callback:(tj,aB)=>{Bg(VC,tj,aB)}};Wd.push(VC),mc++,Vd=setTimeout(U_,ta.rotate),Ta(B_,Ln,VC.callback)}return setTimeout(U_),Em}function initRedundancy(ta){const Ln={...defaultConfig,...ta};let Ta=[];function ja(){Ta=Ta.filter(Pl=>Pl().status==="pending")}function La(Pl,pc,mc){const gc=sendQuery(Ln,Pl,pc,(Vd,Wd)=>{ja(),mc&&mc(Vd,Wd)});return Ta.push(gc),gc}function Fa(Pl){return Ta.find(pc=>Pl(pc))||null}return{query:La,find:Fa,setIndex:Pl=>{Ln.index=Pl},getIndex:()=>Ln.index,cleanup:ja}}function emptyCallback$1(){}const redundancyCache=Object.create(null);function getRedundancyCache(ta){if(!redundancyCache[ta]){const Ln=getAPIConfig(ta);if(!Ln)return;const Ta=initRedundancy(Ln),ja={config:Ln,redundancy:Ta};redundancyCache[ta]=ja}return redundancyCache[ta]}function sendAPIQuery(ta,Ln,Ta){let ja,La;if(typeof ta=="string"){const Fa=getAPIModule(ta);if(!Fa)return Ta(void 0,424),emptyCallback$1;La=Fa.send;const wl=getRedundancyCache(ta);wl&&(ja=wl.redundancy)}else{const Fa=createAPIConfig(ta);if(Fa){ja=initRedundancy(Fa);const wl=ta.resources?ta.resources[0]:"",Pl=getAPIModule(wl);Pl&&(La=Pl.send)}}return!ja||!La?(Ta(void 0,424),emptyCallback$1):ja.query(Ln,La,Ta)().abort}function emptyCallback(){}function loadedNewIcons(ta){ta.iconsLoaderFlag||(ta.iconsLoaderFlag=!0,setTimeout(()=>{ta.iconsLoaderFlag=!1,updateCallbacks(ta)}))}function checkIconNamesForAPI(ta){const Ln=[],Ta=[];return ta.forEach(ja=>{(ja.match(matchIconName)?Ln:Ta).push(ja)}),{valid:Ln,invalid:Ta}}function parseLoaderResponse(ta,Ln,Ta){function ja(){const La=ta.pendingIcons;Ln.forEach(Fa=>{La&&La.delete(Fa),ta.icons[Fa]||ta.missing.add(Fa)})}if(Ta&&typeof Ta=="object")try{if(!addIconSet(ta,Ta).length){ja();return}}catch(La){console.error(La)}ja(),loadedNewIcons(ta)}function parsePossiblyAsyncResponse(ta,Ln){ta instanceof Promise?ta.then(Ta=>{Ln(Ta)}).catch(()=>{Ln(null)}):Ln(ta)}function loadNewIcons(ta,Ln){ta.iconsToLoad?ta.iconsToLoad=ta.iconsToLoad.concat(Ln).sort():ta.iconsToLoad=Ln,ta.iconsQueueFlag||(ta.iconsQueueFlag=!0,setTimeout(()=>{ta.iconsQueueFlag=!1;const{provider:Ta,prefix:ja}=ta,La=ta.iconsToLoad;if(delete ta.iconsToLoad,!La||!La.length)return;const Fa=ta.loadIcon;if(ta.loadIcons&&(La.length>1||!Fa)){parsePossiblyAsyncResponse(ta.loadIcons(La,ja,Ta),gc=>{parseLoaderResponse(ta,La,gc)});return}if(Fa){La.forEach(gc=>{const Vd=Fa(gc,ja,Ta);parsePossiblyAsyncResponse(Vd,Wd=>{const kf=Wd?{prefix:ja,icons:{[gc]:Wd}}:null;parseLoaderResponse(ta,[gc],kf)})});return}const{valid:wl,invalid:Pl}=checkIconNamesForAPI(La);if(Pl.length&&parseLoaderResponse(ta,Pl,null),!wl.length)return;const pc=ja.match(matchIconName)?getAPIModule(Ta):null;if(!pc){parseLoaderResponse(ta,wl,null);return}pc.prepare(Ta,ja,wl).forEach(gc=>{sendAPIQuery(Ta,gc,Vd=>{parseLoaderResponse(ta,gc.icons,Vd)})})}))}const loadIcons=(ta,Ln)=>{const Ta=listToIcons(ta,!0,allowSimpleNames()),ja=sortIcons(Ta);if(!ja.pending.length){let pc=!0;return Ln&&setTimeout(()=>{pc&&Ln(ja.loaded,ja.missing,ja.pending,emptyCallback)}),()=>{pc=!1}}const La=Object.create(null),Fa=[];let wl,Pl;return ja.pending.forEach(pc=>{const{provider:mc,prefix:gc}=pc;if(gc===Pl&&mc===wl)return;wl=mc,Pl=gc,Fa.push(getStorage(mc,gc));const Vd=La[mc]||(La[mc]=Object.create(null));Vd[gc]||(Vd[gc]=[])}),ja.pending.forEach(pc=>{const{provider:mc,prefix:gc,name:Vd}=pc,Wd=getStorage(mc,gc),kf=Wd.pendingIcons||(Wd.pendingIcons=new Set);kf.has(Vd)||(kf.add(Vd),La[mc][gc].push(Vd))}),Fa.forEach(pc=>{const mc=La[pc.provider][pc.prefix];mc.length&&loadNewIcons(pc,mc)}),Ln?storeCallback(Ln,ja,Fa):emptyCallback};function mergeCustomisations(ta,Ln){const Ta={...ta};for(const ja in Ln){const La=Ln[ja],Fa=typeof La;ja in defaultIconSizeCustomisations?(La===null||La&&(Fa==="string"||Fa==="number"))&&(Ta[ja]=La):Fa===typeof Ta[ja]&&(Ta[ja]=ja==="rotate"?La%4:La)}return Ta}const separator$1=/[\s,]+/;function flipFromString(ta,Ln){Ln.split(separator$1).forEach(Ta=>{switch(Ta.trim()){case"horizontal":ta.hFlip=!0;break;case"vertical":ta.vFlip=!0;break}})}function rotateFromString(ta,Ln=0){const Ta=ta.replace(/^-?[0-9.]*/,"");function ja(La){for(;La<0;)La+=4;return La%4}if(Ta===""){const La=parseInt(ta);return isNaN(La)?0:ja(La)}else if(Ta!==ta){let La=0;switch(Ta){case"%":La=25;break;case"deg":La=90}if(La){let Fa=parseFloat(ta.slice(0,ta.length-Ta.length));return isNaN(Fa)?0:(Fa=Fa/La,Fa%1===0?ja(Fa):0)}}return Ln}function iconToHTML(ta,Ln){let Ta=ta.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(const ja in Ln)Ta+=" "+ja+'="'+Ln[ja]+'"';return'<svg xmlns="http://www.w3.org/2000/svg"'+Ta+">"+ta+"</svg>"}function encodeSVGforURL(ta){return ta.replace(/"/g,"'").replace(/%/g,"%25").replace(/#/g,"%23").replace(/</g,"%3C").replace(/>/g,"%3E").replace(/\s+/g," ")}function svgToData(ta){return"data:image/svg+xml,"+encodeSVGforURL(ta)}function svgToURL(ta){return'url("'+svgToData(ta)+'")'}let policy;function createPolicy(){try{policy=window.trustedTypes.createPolicy("iconify",{createHTML:ta=>ta})}catch{policy=null}}function cleanUpInnerHTML(ta){return policy===void 0&&createPolicy(),policy?policy.createHTML(ta):ta}const defaultExtendedIconCustomisations={...defaultIconCustomisations,inline:!1},svgDefaults={xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink","aria-hidden":!0,role:"img"},commonProps={display:"inline-block"},monotoneProps={backgroundColor:"currentColor"},coloredProps={backgroundColor:"transparent"},propsToAdd={Image:"var(--svg)",Repeat:"no-repeat",Size:"100% 100%"},propsToAddTo={WebkitMask:monotoneProps,mask:monotoneProps,background:coloredProps};for(const ta in propsToAddTo){const Ln=propsToAddTo[ta];for(const Ta in propsToAdd)Ln[ta+Ta]=propsToAdd[Ta]}const inlineDefaults={...defaultExtendedIconCustomisations,inline:!0};function fixSize(ta){return ta+(ta.match(/^[-0-9.]+$/)?"px":"")}const render=(ta,Ln,Ta)=>{const ja=Ln.inline?inlineDefaults:defaultExtendedIconCustomisations,La=mergeCustomisations(ja,Ln),Fa=Ln.mode||"svg",wl={},Pl=Ln.style||{},pc={...Fa==="svg"?svgDefaults:{}};if(Ta){const Eh=stringToIcon(Ta,!1,!0);if(Eh){const Em=["iconify"],qg=["provider","prefix"];for(const Ug of qg)Eh[Ug]&&Em.push("iconify--"+Eh[Ug]);pc.className=Em.join(" ")}}for(let Eh in Ln){const Em=Ln[Eh];if(Em!==void 0)switch(Eh){case"icon":case"style":case"children":case"onLoad":case"mode":case"ssr":case"fallback":break;case"_ref":pc.ref=Em;break;case"className":pc[Eh]=(pc[Eh]?pc[Eh]+" ":"")+Em;break;case"inline":case"hFlip":case"vFlip":La[Eh]=Em===!0||Em==="true"||Em===1;break;case"flip":typeof Em=="string"&&flipFromString(La,Em);break;case"color":wl.color=Em;break;case"rotate":typeof Em=="string"?La[Eh]=rotateFromString(Em):typeof Em=="number"&&(La[Eh]=Em);break;case"ariaHidden":case"aria-hidden":Em!==!0&&Em!=="true"&&delete pc["aria-hidden"];break;default:ja[Eh]===void 0&&(pc[Eh]=Em)}}const mc=iconToSVG(ta,La),gc=mc.attributes;if(La.inline&&(wl.verticalAlign="-0.125em"),Fa==="svg"){pc.style={...wl,...Pl},Object.assign(pc,gc);let Eh=0,Em=Ln.id;return typeof Em=="string"&&(Em=Em.replace(/-/g,"_")),pc.dangerouslySetInnerHTML={__html:cleanUpInnerHTML(replaceIDs(mc.body,Em?()=>Em+"ID"+Eh++:"iconifyReact"))},reactExports$1.createElement("svg",pc)}const{body:Vd,width:Wd,height:kf}=ta,Pf=Fa==="mask"||(Fa==="bg"?!1:Vd.indexOf("currentColor")!==-1),Nf=iconToHTML(Vd,{...gc,width:Wd+"",height:kf+""});return pc.style={...wl,"--svg":svgToURL(Nf),width:fixSize(gc.width),height:fixSize(gc.height),...commonProps,...Pf?monotoneProps:coloredProps,...Pl},reactExports$1.createElement("span",pc)};allowSimpleNames(!0);setAPIModule("",fetchAPIModule);if(typeof document<"u"&&typeof window<"u"){const ta=window;if(ta.IconifyPreload!==void 0){const Ln=ta.IconifyPreload,Ta="Invalid IconifyPreload syntax.";typeof Ln=="object"&&Ln!==null&&(Ln instanceof Array?Ln:[Ln]).forEach(ja=>{try{(typeof ja!="object"||ja===null||ja instanceof Array||typeof ja.icons!="object"||typeof ja.prefix!="string"||!addCollection(ja))&&console.error(Ta)}catch{console.error(Ta)}})}if(ta.IconifyProviders!==void 0){const Ln=ta.IconifyProviders;if(typeof Ln=="object"&&Ln!==null)for(let Ta in Ln){const ja="IconifyProviders["+Ta+"] is invalid.";try{const La=Ln[Ta];if(typeof La!="object"||!La||La.resources===void 0)continue;addAPIProvider(Ta,La)||console.error(ja)}catch{console.error(ja)}}}}function IconComponent(ta){const[Ln,Ta]=reactExports$1.useState(!!ta.ssr),[ja,La]=reactExports$1.useState({});function Fa(kf){if(kf){const Pf=ta.icon;if(typeof Pf=="object")return{name:"",data:Pf};const Nf=getIconData(Pf);if(Nf)return{name:Pf,data:Nf}}return{name:""}}const[wl,Pl]=reactExports$1.useState(Fa(!!ta.ssr));function pc(){const kf=ja.callback;kf&&(kf(),La({}))}function mc(kf){if(JSON.stringify(wl)!==JSON.stringify(kf))return pc(),Pl(kf),!0}function gc(){var kf;const Pf=ta.icon;if(typeof Pf=="object"){mc({name:"",data:Pf});return}const Nf=getIconData(Pf);if(mc({name:Pf,data:Nf}))if(Nf===void 0){const Eh=loadIcons([Pf],gc);La({callback:Eh})}else Nf&&((kf=ta.onLoad)===null||kf===void 0||kf.call(ta,Pf))}reactExports$1.useEffect(()=>(Ta(!0),pc),[]),reactExports$1.useEffect(()=>{Ln&&gc()},[ta.icon,Ln]);const{name:Vd,data:Wd}=wl;return Wd?render({...defaultIconProps,...Wd},ta,Vd):ta.children?ta.children:ta.fallback?ta.fallback:reactExports$1.createElement("span",{})}const Icon=reactExports$1.forwardRef((ta,Ln)=>IconComponent({...ta,_ref:Ln}));reactExports$1.forwardRef((ta,Ln)=>IconComponent({inline:!0,...ta,_ref:Ln}));const getDate=ta=>{const Ln=new Date(ta),Ta=Ln.getMonth()+1,ja=Ln.getDate(),La=Ln.getFullYear(),Fa=Ln.toLocaleString("en-US",{hour:"numeric",minute:"numeric",hour12:!0});return`${Ta}/${ja}/${La} ${Fa}`},registerBase64Icon=(ta,Ln)=>{try{const Ta=Ln.replace(/^data:image\/svg\+xml;base64,/,""),ja=atob(Ta),La=ja.match(/width="([^"]+)"/),Fa=ja.match(/height="([^"]+)"/),wl=La?La[1]:"1536",Pl=Fa?Fa[1]:"1280",pc=ja.replace(/^.*?<svg[^>]*>(.*)<\/svg>.*$/,"$1");addIcon(ta,{body:pc,width:parseInt(wl,10),height:parseInt(Pl,10)})}catch(Ta){console.error(`Failed to register icon: ${ta}`,Ta)}};function extractRepoNameFromUrl(ta){const Ln=ta.split("/");return Ln[Ln.length-1]}function scrollIntoView(ta,Ln=!0){const Ta=document.getElementById(ta);Ta&&Ta.scrollIntoView({behavior:Ln?"smooth":"auto",block:"start",inline:"center"})}function roundTo3Decimals(ta){return ta.toFixed(3)}function convertBytes(ta){return ta<1024?`${ta} bytes`:ta<1024*1024?`${roundTo3Decimals(ta/1024)} KB`:ta<1024*1024*1024?`${roundTo3Decimals(ta/(1024*1024))} MB`:`${roundTo3Decimals(ta/(1024*1024*1024))} GB`}function generateGitHubUrl(ta,Ln,Ta,ja){if(!ta||!Ln)throw new Error("GitHub organization and repository name are required");if(Ta&&ja){const La=Ta.trim(),Fa=ja.trim();return!La||!Fa?(console.warn("GitHub credentials contain only whitespace - falling back to public URL"),`https://github.com/${ta}/${Ln}.git`):`https://${La}:${Fa}@github.com/${ta}/${Ln}.git`}return console.warn(`No GitHub credentials provided for ${ta}/${Ln} - using public URL (may fail for private repositories)`),`https://github.com/${ta}/${Ln}.git`}const useWorkspace=()=>{const ta=axiosInstance("meta"),Ln=useAppStore(gc=>gc.user),Ta=useAppStore(gc=>gc.authData.userProfileId),ja=useAppStore(gc=>gc.authData.username),La=useAppStore(gc=>gc.setUser),Fa=useAppStore(gc=>gc.setWorkspace),wl=async()=>{let gc=Ln?.user_profile_id;if(gc||(gc=Ta||void 0),!gc){const Vd=localStorage.getItem("user_profile_id");Vd&&(gc=Vd)}if(!gc){y$b.error("User Profile ID not found. Please re-login.");return}return gc},Pl=async()=>{try{if(!await wl())throw new Error("User Profile ID not found. Please re-login.");const Wd=await ta.get("/AgentMeta/Workspace");if(console.log("fetchWorkspace response:",Wd.data),!Wd.data||Array.isArray(Wd.data)&&Wd.data.length===0)return console.log("GetWorkspace returned empty or null response - workspace does not exist"),null;let kf;if(Wd.data.id||Wd.data.Id)kf=Wd.data;else if(Array.isArray(Wd.data)&&Wd.data.length>0){const Pf=Wd.data[0];Pf?.Workspace?kf=Pf.Workspace:Pf?.result&&Array.isArray(Pf.result)&&Pf.result.length>0?kf=Pf.result[0]:Pf&&(Pf.id||Pf.Id)&&(kf=Pf)}return kf||(console.log("No workspace found in response"),null)}catch(gc){return console.error("fetchWorkspace error:",gc),null}};return{fetchWorkspace:Pl,createWorkspace:async(gc,Vd)=>{try{if(!await wl())throw new Error("User Profile ID not found. Please re-login.");const Pf=await ta.post("/AgentMeta/Workspace",{name:gc,createdBy:Vd});let Nf;if(Pf.data.UserWorkspace?.Workspace)Nf=Pf.data.UserWorkspace.Workspace;else if(Pf.data.id)Nf=Pf.data;else if(Array.isArray(Pf.data)&&Pf.data.length>0){const Eh=Pf.data[0];Eh?.result&&Array.isArray(Eh.result)&&Eh.result.length>0?Nf=Eh.result[0]:Eh?.Workspace?Nf=Eh.Workspace:Nf=Eh}else if(Pf.data.Workspace)Nf=Pf.data.Workspace;else{const Eh=Object.keys(Pf.data);Eh.length>0&&(Nf=Pf.data[Eh[0]])}return Nf||(console.error("Failed to parse workspace from create response"),null)}catch(Wd){throw console.error("createWorkspace error:",Wd),y$b.error(Wd?.response?.data?.reason||"Failed to create workspace"),Wd}},fetchOrCreateWorkspace:async gc=>{if(!(ja||Ln?.Email))throw new Error("No username found in store");let Wd=await Pl();if(Wd){const kf=Wd.id||Wd.Id;if(kf&&!localStorage.getItem("workspace_id")){localStorage.setItem("workspace_id",kf);try{Ln?La({...Ln,CurrentWorkspace:{Id:kf}}):Fa(kf)}catch{}}}else{console.error(`Workspace '${gc}' not found - workspace creation disabled`);try{if(await wl()){const Nf=await ta.get("/AgentMeta/Workspace");if(Nf.data&&Array.isArray(Nf.data)&&Nf.data.length>0){const Eh=Nf.data[Nf.data.length-1];if(Wd=Eh.Workspace||Eh,Wd){const Em=Wd.id||Wd.Id;if(Em){localStorage.setItem("workspace_id",Em);try{Ln?La({...Ln,CurrentWorkspace:{Id:Em}}):Fa(Em)}catch{}console.log("Using existing workspace instead:",Em)}}}}}catch(kf){console.error("Failed to fetch all workspaces:",kf)}if(!Wd)throw new Error(`Workspace '${gc}' not found and creation is disabled`)}return Wd}}},deletePlaygroundTeam=ta=>[],STORAGE_KEY="playground-workspace-apps",ID_COUNTER_KEY="playground-workspace-id-counter";class PlaygroundWorkspaceStorage{apps=new Map;idCounter=0;constructor(){this.loadFromLocalStorage()}loadFromLocalStorage(){try{const Ln=localStorage.getItem(STORAGE_KEY);if(Ln){const ja=JSON.parse(Ln);ja.forEach(La=>{this.apps.set(La.Id,La)}),console.log(`[PLAYGROUND] Loaded ${ja.length} workspace apps from localStorage`)}const Ta=localStorage.getItem(ID_COUNTER_KEY);Ta&&(this.idCounter=parseInt(Ta,10))}catch(Ln){console.error("[PLAYGROUND] Error loading workspace apps from localStorage:",Ln)}}saveToLocalStorage(){try{const Ln=Array.from(this.apps.values());localStorage.setItem(STORAGE_KEY,JSON.stringify(Ln)),localStorage.setItem(ID_COUNTER_KEY,this.idCounter.toString()),console.log(`[PLAYGROUND] Saved ${Ln.length} workspace apps to localStorage`)}catch(Ln){console.error("[PLAYGROUND] Error saving workspace apps to localStorage:",Ln)}}getApps(){return Array.from(this.apps.values())}addApp(Ln){const Ta=Ln.Id||`playground-app-${++this.idCounter}`,ja={...Ln,Id:Ta};return this.apps.set(Ta,ja),this.saveToLocalStorage(),ja}updateApp(Ln,Ta){const ja=this.apps.get(Ln);if(!ja)return null;const La={...ja,...Ta};return this.apps.set(Ln,La),this.saveToLocalStorage(),La}deleteApp(Ln){const Ta=this.apps.delete(Ln);return Ta&&this.saveToLocalStorage(),Ta}getApp(Ln){return this.apps.get(Ln)||null}clearApps(){this.apps.clear(),this.idCounter=0,this.saveToLocalStorage()}hasApp(Ln){return this.apps.has(Ln)}}const playgroundWorkspaceStorage=new PlaygroundWorkspaceStorage,IS_PLAYGROUND$8=!1,IS_LOCAL_MODE$2=!0,metaAxiosInstance$2=axiosInstance("meta");async function fetchPackageInfo$1(ta){const Ln="http://localhost:4000",Ta=ta?`${Ln}/info?app=${encodeURIComponent(ta)}`:`${Ln}/info`,ja=await fetch(Ta);if(!ja.ok)return{};const La=await ja.json();return console.log(La),La}async function fetchBranchInfo(ta){const Ln="http://localhost:4000";try{const Ta=ta?`${Ln}/branch?app=${encodeURIComponent(ta)}`:`${Ln}/branch`,ja=await fetch(Ta);return ja.ok&&(await ja.json()).branch||null}catch(Ta){return console.warn("Failed to fetch branch info:",Ta),null}}const useTeams=()=>{const{teamName:ta,modelName:Ln}=useParams(),{pathname:Ta}=useLocation(),ja=useQueryClient(),La=Ta.includes("/design/marketplace/"),Fa=useAppStore(V_=>V_.authData.username),wl=useAppStore(V_=>V_.authData.userProfileId),Pl=useAppStore(V_=>V_.user.CurrentWorkspace?.Id),pc=useAppStore(V_=>V_.user.GitHub.Token)||"",mc=useAppStore(V_=>V_.user.GitHub.Username)||"",{fetchOrCreateWorkspace:gc}=useWorkspace();useAppStore(V_=>V_.authReady),useAppStore(V_=>V_.isAuthenticated);const{data:Vd}=useQuery({queryKey:["localPackageInfo",ta],queryFn:()=>fetchPackageInfo$1(ta),enabled:IS_LOCAL_MODE$2,staleTime:0,refetchOnMount:"always",gcTime:0}),{data:Wd}=useQuery({queryKey:["localBranch",ta],queryFn:()=>fetchBranchInfo(ta),enabled:IS_LOCAL_MODE$2,staleTime:0,refetchOnMount:"always",gcTime:0}),{data:kf,isLoading:Pf,error:Nf,refetch:Eh}=useQuery({queryKey:["workspace",Pl,"apps",wl],queryFn:async()=>[],enabled:IS_LOCAL_MODE$2,staleTime:120*1e3,gcTime:300*1e3,refetchOnMount:"always",retry:(V_,sP)=>sP?.response?.status===401||sP?.response?.status===403?!1:V_<2}),{mutate:Em}=useMutation({mutationFn:async({appId:V_,isEditable:sP})=>{const Q2=await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`,{isEditable:sP});return transformSimpleTeamToTeam(Q2.data)},onMutate:async V_=>{const{appId:sP,isEditable:Q2}=V_;await ja.cancelQueries({queryKey:["workspace",Pl,"apps",wl]});const q5=ja.getQueryData(["workspace",Pl,"apps",wl]);if(q5){const nj=q5.map(n6=>n6.Id===sP?{...n6,isEditable:Q2}:n6);ja.setQueryData(["workspace",Pl,"apps",wl],nj)}return{previousApps:q5}},onError:(V_,sP,Q2)=>{Q2?.previousApps&&ja.setQueryData(["workspace",Pl,"apps",wl],Q2.previousApps),y$b.error("Failed to update status. Please try again.")},onSettled:()=>{ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]})}}),qg=reactExports$1.useMemo(()=>{{let V_="";if(Vd&&Vd.name)if(V_=Vd.name,V_.startsWith("@")){const sP=V_.substring(1).split("/");sP.length===2&&(V_=sP[1])}else V_=Vd.name;return{Name:V_,isEditable:!0,Type:"Local",GitHubRepo:V_,Branch:Wd||"main"}}},[La,Ln,kf,ta,Vd,Wd]);if(Nf){console.error("fetchWorkspaceApps: Query failed",Nf);let V_="Failed to fetch workspace apps";const sP=Nf;sP?.response?.status===401?V_="Authentication expired. Please sign in again.":sP?.response?.status===403?V_="Access denied. Please check your workspace permissions.":sP?.response?.status===404?V_="Workspace not found. Please verify your workspace access.":sP?.response?.data?.reason?V_=sP.response.data.reason:sP?.message&&(V_=`Network error: ${sP.message}`),y$b.error(V_)}const Ug=async(V_,sP)=>{try{const q5=(await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${sP}`,V_)).data,nj=transformSimpleTeamToTeam(q5);return ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh(),{...nj}}catch(Q2){throw console.error("Error editing workspace app:",Q2),Q2}},Bg=async(V_,sP)=>{try{const q5=(await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`,{branch:sP})).data,nj=transformSimpleTeamToTeam(q5);return ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh(),{...nj,Branch:sP}}catch(Q2){throw console.error("Error switching workspace app branch:",Q2),Q2}},U_=async V_=>{try{let sP=Pl;if(!sP){const Q2=await gc("Default");if(Q2)sP=Q2.id||Q2.Id;else throw new Error("Failed to create or fetch Default workspace")}if(!sP)throw new Error("No workspace ID available after all attempts");await metaAxiosInstance$2.post(`/AgentMeta/Workspace/${sP}/WorkspaceApp/App`,V_),ja.invalidateQueries({queryKey:["workspace",sP,"apps",wl]}),ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh()}catch(sP){console.error("Error occurred:",sP),y$b.error(sP?.response?.data?.["status-text"]||sP?.response?.data?.reason||sP?.message||"Operation failed")}},B_=async V_=>{try{await metaAxiosInstance$2.delete(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`),ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh()}catch(sP){console.error("Error occurred:",sP),y$b.error(sP?.response?.data?.["status-text"]||sP?.response?.data?.reason||sP?.message||"Operation failed")}},VC=async(V_,sP,Q2)=>{try{const q5=`/${V_.githubRepo}`,nj=V_.branchSelected&&V_.githubBranch?V_.githubBranch:"main",n6=mc&&mc.trim().length>0,l6=pc&&pc.trim().length>0,i6=generateGitHubUrl(V_.githubOrg,V_.githubRepo,mc,pc);if((!n6||!l6)&&sP("⚠️ GitHub credentials missing. Clone may fail for private repositories. Please set your GitHub username and token in Settings.",!1,!1),await pathExists(q5)){Q2("checking"),sP("Repository exists, checking for updates...",!1,!1);try{const u6=await updateExistingRepository(q5,pc,{branch:nj,checkOnly:!0});if(!u6.success)sP(`Warning: Could not check for updates - ${u6.message}. Using existing repository.`,!1,!1);else if(u6.hasUpdates){Q2("updating"),sP("Fetching latest changes...",!1,!1);const f6=await updateExistingRepository(q5,pc,{branch:nj,force:!0});f6.success?sP("Repository updated successfully!",!0,!1):sP(`Warning: Could not update repository - ${f6.message}. Using existing version.`,!1,!1)}else sP("No updates available",!0,!1)}catch(u6){console.error("Failed to update repository:",u6),sP(`Warning: Could not check for updates - ${u6.message}. Using existing repository.`,!1,!1)}}else{Q2("cloning"),sP("Cloning repository...",!1,!1);try{await cloneRepository(i6,q5,nj,pc),sP("Repository cloned successfully!",!0,!1)}catch(u6){console.error("Failed to clone repository:",u6),sP(`Failed to clone repository: ${u6.message}`,!1,!0);try{await pathExists(q5)&&(console.log(`Cleaning up failed clone: removing ${q5} from IndexedDB`),await removeDirectory(q5))}catch(f6){console.error("Error cleaning up failed clone:",f6)}return Q2("error"),{path:null,fileContent:null}}}try{Q2("processing"),sP("Searching for .al files...",!1,!1);const u6=await findFilesWithExtension(q5,"al");if(u6.length===0)return sP("No .al files found in the repository.",!1,!0),Q2("error"),{path:null,fileContent:null};sP(`Found ${u6.length} .al file(s).`,!0,!1);const f6=u6[0];sP(`Reading file: ${f6}...`,!1,!1);const Rpe=await readRepoFile(q5,f6);try{await readRepoFile(q5,"package.json")}catch{sP("Warning: package.json not found in repository",!1,!1)}try{return Q2("creating"),await flushAllAndLoad(q5,{name:"studio"}),sP(`${f6} loaded successfully!`,!0,!1),Q2("complete"),{path:q5,fileContent:Rpe}}catch(Xae){return console.error(`Failed to load ${f6}:`,Xae),sP(`Failed to load ${f6}: ${Xae.message}`,!1,!0),Q2("error"),{path:null,fileContent:null}}}catch(u6){return console.error("Failed to process .al files:",u6),sP(`Note: .al files not found or could not be read: ${u6.message}`,!1,!0),Q2("error"),{path:q5,fileContent:null}}}catch(q5){return console.error("Failed to execute Git operation:",q5),sP(`Failed to execute Git operation: ${q5.message}`,!1,!0),Q2("error"),{path:null,fileContent:null}}},tj=async(V_,sP,Q2)=>{try{Q2("Saving changes...",!1,!1);const q5=await openRepository(V_);return await writeRepoFile(V_,"README.md",sP),await commitChanges(q5,"README.md","Update README.md",{name:"Fractl Studio User",email:Fa||"user@fractl.studio"}),Q2("Changes saved successfully!",!0,!1),!0}catch(q5){return console.error("Failed to save README:",q5),Q2(`Failed to save: ${q5.message}`,!1,!0),!1}},aB=async(V_,sP)=>{try{sP("Pushing changes to repository...",!1,!1);const Q2=await openRepository(V_);return await pushChanges(Q2,"origin","main",pc),sP("Changes pushed successfully!",!0,!1),!0}catch(Q2){return console.error("Failed to push changes:",Q2),sP(`Failed to push: ${Q2.message}`,!1,!0),!1}},r6=reactExports$1.useCallback(async(V_,sP,Q2=!1)=>{Q2&&await Eh()},[Eh]),J2=qg?.isEditable??!0;return{currentTeam:qg,workspaceApps:kf,isLoadingApps:Pf,appsError:Nf,fetchWorkspaceApps:r6,editWorkspaceApp:Ug,switchWorkspaceAppBranch:Bg,updateWorkspaceAppEditable:Em,addWorkspaceApp:U_,cloneGitRepository:VC,saveReadmeChanges:tj,pushChanges:aB,deleteWorkspaceApp:B_,isEditable:J2}},integrationAxiosInstance$1=axiosInstance("connection-manager"),useLLM=()=>{const ta=useQueryClient(),Ln=useAppStore(kf=>kf.authReady),Ta=useAppStore(kf=>kf.isAuthenticated),ja=kf=>{const{__parent__:Pf,__path__:Nf,...Eh}=kf;return Eh},{data:La,isLoading:Fa,isError:wl,error:Pl,refetch:pc}=useQuery({queryKey:["llms"],queryFn:async()=>{const kf=await integrationAxiosInstance$1.get("/integmanager.core/llm"),{data:Pf,status:Nf}=kf;if(Nf!==200)throw new Error("Failed to fetch llms");return Pf.map(Em=>({...Em.llm,config:JSON.parse(Em.llm.config)}))},enabled:Ln&&Ta&&!0});wl&&Pl&&y$b.error(Pl?.response?.data?.reason||Pl.message);const mc=reactExports$1.useCallback(async kf=>{await pc()},[pc]),gc=reactExports$1.useCallback(async kf=>{try{const Pf=ja(kf),Nf=await integrationAxiosInstance$1.post("/integmanager.core/llm",Pf);if(Nf.status===200||Nf.status===201)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM created successfully");else{const Eh=Nf.data?.reason||Nf.data?.message||`Failed to create LLM (Status: ${Nf.status})`;throw y$b.error(Eh),new Error(Eh)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to create LLM";throw y$b.error(Nf),Pf}},[ta]),Vd=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance$1.delete(`/integmanager.core/llm/${kf}`);if(Pf.status===200||Pf.status===204)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM deleted successfully");else{const Nf=Pf.data?.reason||Pf.data?.message||`Failed to delete LLM (Status: ${Pf.status})`;throw y$b.error(Nf),new Error(Nf)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to delete LLM";throw y$b.error(Nf),Pf}},[ta]),Wd=reactExports$1.useCallback(async(kf,Pf)=>{try{const Nf=ja(Pf),Eh=await integrationAxiosInstance$1.put(`/integmanager.core/llm/${kf}`,Nf);if(Eh.status===200||Eh.status===201||Eh.status===204)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM updated successfully");else{const Em=Eh.data?.reason||Eh.data?.message||`Failed to update LLM (Status: ${Eh.status})`;throw y$b.error(Em),new Error(Em)}}catch(Nf){const Eh=Nf?.response?.data?.reason||Nf?.response?.data?.message||Nf?.message||"Failed to update LLM";throw y$b.error(Eh),Nf}},[ta]);return{llmData:La,isLoadingLLMs:Fa,isErrorLLMs:wl,llmError:Pl,fetchLLMs:mc,createLLM:gc,deleteLLM:Vd,updateLLM:Wd}},integrationAxiosInstance=axiosInstance("connection-manager"),useIntegration=()=>{const ta=useQueryClient(),Ln=useAppStore(kf=>kf.authReady),Ta=useAppStore(kf=>kf.isAuthenticated),ja=async kf=>{try{const Pf=await integrationAxiosInstance.get(`/api/IntegrationManager.Core/Integration/${kf}/ConnectionConfigGroup/ConnectionConfig`),{result:Nf,status:Eh,message:Em}=Pf.data;if(Eh==="ok")return Nf;Eh==="error"&&y$b.error(Em||`Failed to load configs for ${kf}`)}catch(Pf){console.error(`Error fetching configs for ${kf}:`,Pf),y$b.error(`Error fetching configs for ${kf}`)}},{data:La,isLoading:Fa,isError:wl,error:Pl,refetch:pc}=useQuery({queryKey:["integrations"],queryFn:async()=>{const kf=await integrationAxiosInstance.get("/integmanager.core/integration"),{data:Pf,status:Nf}=kf;if(Nf!==200)throw new Error("Failed to fetch integrations");return Pf.map(Em=>({...Em.integration,userData:JSON.parse(Em.integration.userData)}))},enabled:Ln&&Ta&&!0});wl&&Pl&&y$b.error(Pl?.response?.data?.reason||Pl.message);const mc=reactExports$1.useCallback(async()=>{await pc()},[pc]),gc=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance.post("/integmanager.core/integration",kf);(Pf.status===200||Pf.status===201)&&(ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration created successfully"))}catch(Pf){y$b.error(Pf?.response?.data?.reason||"Failed to create integration")}},[ta]),Vd=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance.delete(`/integmanager.core/integration/${kf}`);if(console.log(Pf.data),Pf.status===200||Pf.status===204)ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration deleted successfully");else{const Nf=Pf.data?.reason||Pf.data?.message||`Failed to delete integration (Status: ${Pf.status})`;throw y$b.error(Nf),new Error(Nf)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to delete integration";throw y$b.error(Nf),Pf}},[ta]),Wd=reactExports$1.useCallback(async(kf,Pf)=>{try{const Nf=await integrationAxiosInstance.put(`/integmanager.core/integration/${kf}`,Pf);if(console.log(Nf.data),Nf.status===200)ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration updated successfully");else{const Eh=Nf.data?.reason||Nf.data?.message||`Failed to update integration (Status: ${Nf.status})`;throw y$b.error(Eh),new Error(Eh)}}catch(Nf){const Eh=Nf?.response?.data?.reason||Nf?.response?.data?.message||Nf?.message||"Failed to update integration";throw y$b.error(Eh),Nf}},[ta]);return{integrationData:La,isLoadingIntegrations:Fa,isErrorIntegrations:wl,integrationsError:Pl,fetchIntegrations:mc,fetchIntegrationConnectionConfigs:ja,createIntegration:gc,deleteIntegration:Vd,updateIntegration:Wd}},IS_PLAYGROUND$7=!1,IS_LOCAL_MODE$1=!0,useDeployments=()=>{const ta=useQueryClient(),Ln=useAppStore(Vd=>Vd.authReady),Ta=useAppStore(Vd=>Vd.isAuthenticated),{data:ja,isLoading:La,isError:Fa,error:wl,refetch:Pl}=useQuery({queryKey:["deployments"],queryFn:async()=>(console.log("[SERVE_MODE] Skipping deployments fetch - returning empty object"),{}),enabled:Ln&&Ta&&!IS_PLAYGROUND$7&&!IS_LOCAL_MODE$1});Fa&&wl&&y$b.error(wl?.response?.data?.reason||wl.message);const pc=reactExports$1.useCallback(async()=>{{console.log("[SERVE_MODE] Skipping deployments fetch");return}},[Pl]),mc=reactExports$1.useCallback(async Vd=>{try{if(IS_PLAYGROUND$7||IS_LOCAL_MODE$1)return console.log(`[${IS_PLAYGROUND$7?"PLAYGROUND":"SERVE_MODE"}] Skipping app deployment`),y$b.success(`App deployed successfully! (${IS_PLAYGROUND$7?"playground":"serve"} mode)`),{success:!0};const Wd=await axiosInstance("deployment").post("/Deployment/DeployApp",Vd);return y$b.success("App deployed successfully!"),ta.invalidateQueries({queryKey:["deployments"]}),Wd.data}catch(Wd){throw y$b.error(Wd?.response?.data?.reason||"Failed to deploy app"),Wd}},[ta]),gc=reactExports$1.useCallback(async Vd=>{try{if(IS_PLAYGROUND$7||IS_LOCAL_MODE$1)return console.log(`[${IS_PLAYGROUND$7?"PLAYGROUND":"SERVE_MODE"}] Skipping app undeployment`),y$b.success(`App undeployed successfully! (${IS_PLAYGROUND$7?"playground":"serve"} mode)`),{success:!0};const Wd=await axiosInstance("deployment").post("/Deployment/UndeployApp",Vd);return y$b.success("App undeployed successfully!"),ta.invalidateQueries({queryKey:["deployments"]}),Wd.data}catch(Wd){throw y$b.error(Wd?.response?.data?.reason||"Failed to undeploy app"),Wd}},[ta]);return{deploymentsData:ja,isLoadingDeployments:La,isErrorDeployments:Fa,deploymentsError:wl,fetchDeployments:pc,deployApp:mc,undeployApp:gc}};let globalInitializationState={isInitializing:!1,isInitialized:!1,error:null,retryCount:0,progress:{userLoaded:!1,workspaceLoaded:!1,dataLoaded:!1}};const listeners=new Set,updateGlobalState=ta=>{globalInitializationState={...globalInitializationState,...ta},listeners.forEach(Ln=>Ln(globalInitializationState))},useAppInitialization=()=>{const[ta,Ln]=reactExports$1.useState(globalInitializationState),Ta=reactExports$1.useRef(!1),{setUser:ja,user:La,lastDataFetch:Fa,setLastDataFetch:wl}=useAppStore(),Pl=axiosInstance("meta"),{fetchWorkspaceApps:pc}=useTeams(),{fetchIntegrations:mc}=useIntegration(),{fetchDeployments:gc}=useDeployments(),{fetchLLMs:Vd}=useLLM();reactExports$1.useEffect(()=>{const U_=B_=>{Ln(B_)};return listeners.add(U_),()=>{listeners.delete(U_)}},[]);const Wd=reactExports$1.useCallback(U_=>{const B_={...globalInitializationState,progress:{...globalInitializationState.progress,...U_}};updateGlobalState(B_)},[]),kf=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("agentlang-studio-store");if(!U_)return!1;try{const B_=JSON.parse(U_),VC=B_.state&&B_.state.user&&B_.state.user.Email,tj=B_.state&&B_.state.workspace&&B_.state.workspace.Id,aB=B_.state&&B_.state.lastDataFetch&&B_.state.lastDataFetch>0;return VC&&tj&&aB}catch(B_){return console.warn("Failed to parse cached store:",B_),!1}},[]),Pf=reactExports$1.useCallback(()=>{if(Fa===0)return!0;const U_=Date.now()-600*1e3;if(Fa>U_)return!1;const B_=Date.now()-300*1e3;return Fa<B_},[Fa]),Nf=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("agentlang-studio-store");if(!U_)return!1;try{const B_=JSON.parse(U_);if(B_.state&&B_.state.user&&B_.state.user.Email)return Wd({userLoaded:!0}),!0}catch(B_){console.warn("Failed to parse cached store:",B_)}return!1},[Wd]),Eh=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("workspace_id"),B_=localStorage.getItem("username");return U_&&B_?(Wd({workspaceLoaded:!0}),!0):!1},[Wd]),Em=reactExports$1.useCallback(async(U_,B_,VC=!1)=>{{console.log("[DEV MODE] Skipping app data initialization - no API calls needed"),Wd({dataLoaded:!0});return}},[pc,mc,gc,Vd,Wd,wl]),qg=reactExports$1.useCallback(async(U_=0)=>{if(!Ta.current){console.log("[DEV MODE] Skipping app initialization - no API calls needed"),wl(Date.now()),updateGlobalState({isInitializing:!1,isInitialized:!0,retryCount:0,progress:{userLoaded:!0,workspaceLoaded:!0,dataLoaded:!0}}),y$b.success("App initialized in dev mode");return}},[Pl,ja,La,Em,Wd,kf,Nf,Eh,Pf,wl]),Ug=reactExports$1.useCallback(()=>{updateGlobalState({retryCount:0}),Ta.current=!1,qg()},[qg]),Bg=reactExports$1.useCallback(()=>{updateGlobalState({isInitializing:!1,isInitialized:!1,error:null,retryCount:0,progress:{userLoaded:!1,workspaceLoaded:!1,dataLoaded:!1}}),Ta.current=!1},[]);return reactExports$1.useEffect(()=>()=>{Ta.current=!1},[]),{...ta,initializeApp:qg,retryInitialization:Ug,resetInitialization:Bg}};var t$9=typeof window<"u"?window:void 0,i$a=typeof globalThis<"u"?globalThis:t$9,e$a=Array.prototype,r$d=e$a.forEach,s$f=e$a.indexOf,n$9=i$a?.navigator,o$d=i$a?.document,a$i=i$a?.location,l$9=i$a?.fetch,u$h=i$a!=null&&i$a.XMLHttpRequest&&"withCredentials"in new i$a.XMLHttpRequest?i$a.XMLHttpRequest:void 0,h$c=i$a?.AbortController,d$6=n$9?.userAgent,v$7=t$9??{},c$e={DEBUG:!1,LIB_VERSION:"1.298.0"};function f$g(ta,Ln,Ta,ja,La,Fa,wl){try{var Pl=ta[Fa](wl),pc=Pl.value}catch(mc){return void Ta(mc)}Pl.done?Ln(pc):Promise.resolve(pc).then(ja,La)}function p$d(ta){return function(){var Ln=this,Ta=arguments;return new Promise((function(ja,La){var Fa=ta.apply(Ln,Ta);function wl(pc){f$g(Fa,ja,La,wl,Pl,"next",pc)}function Pl(pc){f$g(Fa,ja,La,wl,Pl,"throw",pc)}wl(void 0)}))}}function g$8(){return g$8=Object.assign?Object.assign.bind():function(ta){for(var Ln=1;Ln<arguments.length;Ln++){var Ta=arguments[Ln];for(var ja in Ta)({}).hasOwnProperty.call(Ta,ja)&&(ta[ja]=Ta[ja])}return ta},g$8.apply(null,arguments)}function _$8(ta,Ln){if(ta==null)return{};var Ta={};for(var ja in ta)if({}.hasOwnProperty.call(ta,ja)){if(Ln.indexOf(ja)!==-1)continue;Ta[ja]=ta[ja]}return Ta}var m$8=["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"],y$a=function(ta,Ln){if(Ln===void 0&&(Ln=[]),!ta)return!1;var Ta=ta.toLowerCase();return m$8.concat(Ln).some((ja=>{var La=ja.toLowerCase();return Ta.indexOf(La)!==-1}))},b$9=["$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$a(ta,Ln){return ta.indexOf(Ln)!==-1}var x$7=function(ta){return ta.trim()},E$8=function(ta){return ta.replace(/^\$/,"")},S$b=Array.isArray,k$b=Object.prototype,P$a=k$b.hasOwnProperty,T$b=k$b.toString,I$9=S$b||function(ta){return T$b.call(ta)==="[object Array]"},R$3=ta=>typeof ta=="function",F$8=ta=>ta===Object(ta)&&!I$9(ta),C$c=ta=>{if(F$8(ta)){for(var Ln in ta)if(P$a.call(ta,Ln))return!1;return!0}return!1},O$6=ta=>ta===void 0,M$7=ta=>T$b.call(ta)=="[object String]",A$8=ta=>M$7(ta)&&ta.trim().length===0,D$b=ta=>ta===null,j$b=ta=>O$6(ta)||D$b(ta),L$6=ta=>T$b.call(ta)=="[object Number]",N$6=ta=>T$b.call(ta)==="[object Boolean]",U$4=ta=>ta instanceof FormData,z$6=ta=>w$a(b$9,ta);function H$9(ta){return ta===null||typeof ta!="object"}function B$6(ta,Ln){return Object.prototype.toString.call(ta)==="[object "+Ln+"]"}function q$6(ta){return!O$6(Event)&&(function(Ln,Ta){try{return Ln instanceof Ta}catch{return!1}})(ta,Event)}var W$4=[!0,"true",1,"1","yes"],G$5=ta=>w$a(W$4,ta),V$7=[!1,"false",0,"0","no"];function J$5(ta,Ln,Ta,ja,La){return Ln>Ta&&(ja.warn("min cannot be greater than max."),Ln=Ta),L$6(ta)?ta>Ta?(ja.warn(" cannot be greater than max: "+Ta+". Using max value instead."),Ta):ta<Ln?(ja.warn(" cannot be less than min: "+Ln+". Using min value instead."),Ln):ta:(ja.warn(" must be a number. using max or fallback. max: "+Ta+", fallback: "+La),J$5(La||Ta,Ln,Ta,ja))}let K$6=class{constructor(Ln){this.t={},this.i=Ln.i,this.o=J$5(Ln.bucketSize,0,100,Ln.h),this.m=J$5(Ln.refillRate,0,this.o,Ln.h),this.$=J$5(Ln.refillInterval,0,864e5,Ln.h)}S(Ln,Ta){var ja=Ta-Ln.lastAccess,La=Math.floor(ja/this.$);if(La>0){var Fa=La*this.m;Ln.tokens=Math.min(Ln.tokens+Fa,this.o),Ln.lastAccess=Ln.lastAccess+La*this.$}}consumeRateLimit(Ln){var Ta,ja=Date.now(),La=String(Ln),Fa=this.t[La];return Fa?this.S(Fa,ja):(Fa={tokens:this.o,lastAccess:ja},this.t[La]=Fa),Fa.tokens===0||(Fa.tokens--,Fa.tokens===0&&((Ta=this.i)==null||Ta.call(this,Ln)),Fa.tokens===0)}stop(){this.t={}}};var Y$3,X$4,Q$5,Z$4=ta=>ta instanceof Error;function tt$1(ta){var Ln=globalThis._posthogChunkIds;if(Ln){var Ta=Object.keys(Ln);return Q$5&&Ta.length===X$4||(X$4=Ta.length,Q$5=Ta.reduce(((ja,La)=>{Y$3||(Y$3={});var Fa=Y$3[La];if(Fa)ja[Fa[0]]=Fa[1];else for(var wl=ta(La),Pl=wl.length-1;Pl>=0;Pl--){var pc=wl[Pl],mc=pc?.filename,gc=Ln[La];if(mc&&gc){ja[mc]=gc,Y$3[La]=[mc,gc];break}}return ja}),{})),Q$5}}let it$1=class{constructor(Ln,Ta,ja){ja===void 0&&(ja=[]),this.coercers=Ln,this.stackParser=Ta,this.modifiers=ja}buildFromUnknown(Ln,Ta){Ta===void 0&&(Ta={});var ja=Ta&&Ta.mechanism||{handled:!0,type:"generic"},La=this.buildCoercingContext(ja,Ta,0).apply(Ln),Fa=this.buildParsingContext(),wl=this.parseStacktrace(La,Fa);return{$exception_list:this.convertToExceptionList(wl,ja),$exception_level:"error"}}modifyFrames(Ln){var Ta=this;return p$d((function*(){for(var ja of Ln)ja.stacktrace&&ja.stacktrace.frames&&I$9(ja.stacktrace.frames)&&(ja.stacktrace.frames=yield Ta.applyModifiers(ja.stacktrace.frames));return Ln}))()}coerceFallback(Ln){var Ta;return{type:"Error",value:"Unknown error",stack:(Ta=Ln.syntheticException)==null?void 0:Ta.stack,synthetic:!0}}parseStacktrace(Ln,Ta){var ja,La;return Ln.cause!=null&&(ja=this.parseStacktrace(Ln.cause,Ta)),Ln.stack!=""&&Ln.stack!=null&&(La=this.applyChunkIds(this.stackParser(Ln.stack,Ln.synthetic?1:0),Ta.chunkIdMap)),g$8({},Ln,{cause:ja,stack:La})}applyChunkIds(Ln,Ta){return Ln.map((ja=>(ja.filename&&Ta&&(ja.chunk_id=Ta[ja.filename]),ja)))}applyCoercers(Ln,Ta){for(var ja of this.coercers)if(ja.match(Ln))return ja.coerce(Ln,Ta);return this.coerceFallback(Ta)}applyModifiers(Ln){var Ta=this;return p$d((function*(){var ja=Ln;for(var La of Ta.modifiers)ja=yield La(ja);return ja}))()}convertToExceptionList(Ln,Ta){var ja,La,Fa,wl={type:Ln.type,value:Ln.value,mechanism:{type:(ja=Ta.type)!==null&&ja!==void 0?ja:"generic",handled:(La=Ta.handled)===null||La===void 0||La,synthetic:(Fa=Ln.synthetic)!==null&&Fa!==void 0&&Fa}};Ln.stack&&(wl.stacktrace={type:"raw",frames:Ln.stack});var Pl=[wl];return Ln.cause!=null&&Pl.push(...this.convertToExceptionList(Ln.cause,g$8({},Ta,{handled:!0}))),Pl}buildParsingContext(){return{chunkIdMap:tt$1(this.stackParser)}}buildCoercingContext(Ln,Ta,ja){ja===void 0&&(ja=0);var La=(Fa,wl)=>{if(wl<=4){var Pl=this.buildCoercingContext(Ln,Ta,wl);return this.applyCoercers(Fa,Pl)}};return g$8({},Ta,{syntheticException:ja==0?Ta.syntheticException:void 0,mechanism:Ln,apply:Fa=>La(Fa,ja),next:Fa=>La(Fa,ja+1)})}};var et$1="?";function rt$1(ta,Ln,Ta,ja,La){var Fa={platform:ta,filename:Ln,function:Ta==="<anonymous>"?et$1:Ta,in_app:!0};return O$6(ja)||(Fa.lineno=ja),O$6(La)||(Fa.colno=La),Fa}var st$1=(ta,Ln)=>{var Ta=ta.indexOf("safari-extension")!==-1,ja=ta.indexOf("safari-web-extension")!==-1;return Ta||ja?[ta.indexOf("@")!==-1?ta.split("@")[0]:et$1,Ta?"safari-extension:"+Ln:"safari-web-extension:"+Ln]:[ta,Ln]},nt$1=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ot$1=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,at$1=/\((\S*)(?::(\d+))(?::(\d+))\)/,lt$1=(ta,Ln)=>{var Ta=nt$1.exec(ta);if(Ta){var[,ja,La,Fa]=Ta;return rt$1(Ln,ja,et$1,+La,+Fa)}var wl=ot$1.exec(ta);if(wl){if(wl[2]&&wl[2].indexOf("eval")===0){var Pl=at$1.exec(wl[2]);Pl&&(wl[2]=Pl[1],wl[3]=Pl[2],wl[4]=Pl[3])}var[pc,mc]=st$1(wl[1]||et$1,wl[2]);return rt$1(Ln,mc,pc,wl[3]?+wl[3]:void 0,wl[4]?+wl[4]:void 0)}},ut$1=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ht$1=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dt$2=(ta,Ln)=>{var Ta=ut$1.exec(ta);if(Ta){if(Ta[3]&&Ta[3].indexOf(" > eval")>-1){var ja=ht$1.exec(Ta[3]);ja&&(Ta[1]=Ta[1]||"eval",Ta[3]=ja[1],Ta[4]=ja[2],Ta[5]="")}var La=Ta[3],Fa=Ta[1]||et$1;return[Fa,La]=st$1(Fa,La),rt$1(Ln,La,Fa,Ta[4]?+Ta[4]:void 0,Ta[5]?+Ta[5]:void 0)}},vt$1=/\(error: (.*)\)/,ct$1=50;function ft$1(ta){for(var Ln=arguments.length,Ta=new Array(Ln>1?Ln-1:0),ja=1;ja<Ln;ja++)Ta[ja-1]=arguments[ja];return function(La,Fa){Fa===void 0&&(Fa=0);for(var wl=[],Pl=La.split(`
|
|
34776
|
+
`);var L$7=ta=>typeof ta=="number"&&!isNaN(ta),N$7=ta=>typeof ta=="string",P$b=ta=>typeof ta=="function",mt$2=ta=>N$7(ta)||L$7(ta),B$7=ta=>N$7(ta)||P$b(ta)?ta:null,pt$2=(ta,Ln)=>ta===!1||L$7(ta)&&ta>0?ta:Ln,z$7=ta=>reactExports$1.isValidElement(ta)||N$7(ta)||P$b(ta)||L$7(ta);function Z$5(ta,Ln,Ta=300){let{scrollHeight:ja,style:La}=ta;requestAnimationFrame(()=>{La.minHeight="initial",La.height=ja+"px",La.transition=`all ${Ta}ms`,requestAnimationFrame(()=>{La.height="0",La.padding="0",La.margin="0",setTimeout(Ln,Ta)})})}function $$7({enter:ta,exit:Ln,appendPosition:Ta=!1,collapse:ja=!0,collapseDuration:La=300}){return function({children:Fa,position:wl,preventExitTransition:Pl,done:pc,nodeRef:mc,isIn:gc,playToast:Vd}){let Wd=Ta?`${ta}--${wl}`:ta,kf=Ta?`${Ln}--${wl}`:Ln,Pf=reactExports$1.useRef(0);return reactExports$1.useLayoutEffect(()=>{let Nf=mc.current,Eh=Wd.split(" "),Em=qg=>{qg.target===mc.current&&(Vd(),Nf.removeEventListener("animationend",Em),Nf.removeEventListener("animationcancel",Em),Pf.current===0&&qg.type!=="animationcancel"&&Nf.classList.remove(...Eh))};Nf.classList.add(...Eh),Nf.addEventListener("animationend",Em),Nf.addEventListener("animationcancel",Em)},[]),reactExports$1.useEffect(()=>{let Nf=mc.current,Eh=()=>{Nf.removeEventListener("animationend",Eh),ja?Z$5(Nf,pc,La):pc()};gc||(Pl?Eh():(Pf.current=1,Nf.className+=` ${kf}`,Nf.addEventListener("animationend",Eh)))},[gc]),React.createElement(React.Fragment,null,Fa)}}function J$6(ta,Ln){return{content:tt$2(ta.content,ta.props),containerId:ta.props.containerId,id:ta.props.toastId,theme:ta.props.theme,type:ta.props.type,data:ta.props.data||{},isLoading:ta.props.isLoading,icon:ta.props.icon,reason:ta.removalReason,status:Ln}}function tt$2(ta,Ln,Ta=!1){return reactExports$1.isValidElement(ta)&&!N$7(ta.type)?reactExports$1.cloneElement(ta,{closeToast:Ln.closeToast,toastProps:Ln,data:Ln.data,isPaused:Ta}):P$b(ta)?ta({closeToast:Ln.closeToast,toastProps:Ln,data:Ln.data,isPaused:Ta}):ta}function yt$2({closeToast:ta,theme:Ln,ariaLabel:Ta="close"}){return React.createElement("button",{className:`Toastify__close-button Toastify__close-button--${Ln}`,type:"button",onClick:ja=>{ja.stopPropagation(),ta(!0)},"aria-label":Ta},React.createElement("svg",{"aria-hidden":"true",viewBox:"0 0 14 16"},React.createElement("path",{fillRule:"evenodd",d:"M7.71 8.23l3.75 3.75-1.48 1.48-3.75-3.75-3.75 3.75L1 11.98l3.75-3.75L1 4.48 2.48 3l3.75 3.75L9.98 3l1.48 1.48-3.75 3.75z"})))}function gt$3({delay:ta,isRunning:Ln,closeToast:Ta,type:ja="default",hide:La,className:Fa,controlledProgress:wl,progress:Pl,rtl:pc,isIn:mc,theme:gc}){let Vd=La||wl&&Pl===0,Wd={animationDuration:`${ta}ms`,animationPlayState:Ln?"running":"paused"};wl&&(Wd.transform=`scaleX(${Pl})`);let kf=clsx("Toastify__progress-bar",wl?"Toastify__progress-bar--controlled":"Toastify__progress-bar--animated",`Toastify__progress-bar-theme--${gc}`,`Toastify__progress-bar--${ja}`,{"Toastify__progress-bar--rtl":pc}),Pf=P$b(Fa)?Fa({rtl:pc,type:ja,defaultClassName:kf}):clsx(kf,Fa),Nf={[wl&&Pl>=1?"onTransitionEnd":"onAnimationEnd"]:wl&&Pl<1?null:()=>{mc&&Ta()}};return React.createElement("div",{className:"Toastify__progress-bar--wrp","data-hidden":Vd},React.createElement("div",{className:`Toastify__progress-bar--bg Toastify__progress-bar-theme--${gc} Toastify__progress-bar--${ja}`}),React.createElement("div",{role:"progressbar","aria-hidden":Vd?"true":"false","aria-label":"notification timer",className:Pf,style:Wd,...Nf}))}var Xt$1=1,at$2=()=>`${Xt$1++}`;function _t$2(ta,Ln,Ta){let ja=1,La=0,Fa=[],wl=[],Pl=Ln,pc=new Map,mc=new Set,gc=qg=>(mc.add(qg),()=>mc.delete(qg)),Vd=()=>{wl=Array.from(pc.values()),mc.forEach(qg=>qg())},Wd=({containerId:qg,toastId:Ug,updateId:Bg})=>{let U_=qg?qg!==ta:ta!==1,B_=pc.has(Ug)&&Bg==null;return U_||B_},kf=(qg,Ug)=>{pc.forEach(Bg=>{var U_;(Ug==null||Ug===Bg.props.toastId)&&((U_=Bg.toggle)==null||U_.call(Bg,qg))})},Pf=qg=>{var Ug,Bg;(Bg=(Ug=qg.props)==null?void 0:Ug.onClose)==null||Bg.call(Ug,qg.removalReason),qg.isActive=!1},Nf=qg=>{if(qg==null)pc.forEach(Pf);else{let Ug=pc.get(qg);Ug&&Pf(Ug)}Vd()},Eh=()=>{La-=Fa.length,Fa=[]},Em=qg=>{var Ug,Bg;let{toastId:U_,updateId:B_}=qg.props,VC=B_==null;qg.staleId&&pc.delete(qg.staleId),qg.isActive=!0,pc.set(U_,qg),Vd(),Ta(J$6(qg,VC?"added":"updated")),VC&&((Bg=(Ug=qg.props).onOpen)==null||Bg.call(Ug))};return{id:ta,props:Pl,observe:gc,toggle:kf,removeToast:Nf,toasts:pc,clearQueue:Eh,buildToast:(qg,Ug)=>{if(Wd(Ug))return;let{toastId:Bg,updateId:U_,data:B_,staleId:VC,delay:tj}=Ug,aB=U_==null;aB&&La++;let r6={...Pl,style:Pl.toastStyle,key:ja++,...Object.fromEntries(Object.entries(Ug).filter(([V_,sP])=>sP!=null)),toastId:Bg,updateId:U_,data:B_,isIn:!1,className:B$7(Ug.className||Pl.toastClassName),progressClassName:B$7(Ug.progressClassName||Pl.progressClassName),autoClose:Ug.isLoading?!1:pt$2(Ug.autoClose,Pl.autoClose),closeToast(V_){pc.get(Bg).removalReason=V_,Nf(Bg)},deleteToast(){let V_=pc.get(Bg);if(V_!=null){if(Ta(J$6(V_,"removed")),pc.delete(Bg),La--,La<0&&(La=0),Fa.length>0){Em(Fa.shift());return}Vd()}}};r6.closeButton=Pl.closeButton,Ug.closeButton===!1||z$7(Ug.closeButton)?r6.closeButton=Ug.closeButton:Ug.closeButton===!0&&(r6.closeButton=z$7(Pl.closeButton)?Pl.closeButton:!0);let J2={content:qg,props:r6,staleId:VC};Pl.limit&&Pl.limit>0&&La>Pl.limit&&aB?Fa.push(J2):L$7(tj)?setTimeout(()=>{Em(J2)},tj):Em(J2)},setProps(qg){Pl=qg},setToggle:(qg,Ug)=>{let Bg=pc.get(qg);Bg&&(Bg.toggle=Ug)},isToastActive:qg=>{var Ug;return(Ug=pc.get(qg))==null?void 0:Ug.isActive},getSnapshot:()=>wl}}var I$a=new Map,F$9=[],st$2=new Set,Vt$1=ta=>st$2.forEach(Ln=>Ln(ta)),bt$1=()=>I$a.size>0;function Qt$1(){F$9.forEach(ta=>nt$2(ta.content,ta.options)),F$9=[]}var vt$2=(ta,{containerId:Ln})=>{var Ta;return(Ta=I$a.get(Ln||1))==null?void 0:Ta.toasts.get(ta)};function X$5(ta,Ln){var Ta;if(Ln)return!!((Ta=I$a.get(Ln))!=null&&Ta.isToastActive(ta));let ja=!1;return I$a.forEach(La=>{La.isToastActive(ta)&&(ja=!0)}),ja}function ht$2(ta){if(!bt$1()){F$9=F$9.filter(Ln=>ta!=null&&Ln.options.toastId!==ta);return}if(ta==null||mt$2(ta))I$a.forEach(Ln=>{Ln.removeToast(ta)});else if(ta&&("containerId"in ta||"id"in ta)){let Ln=I$a.get(ta.containerId);Ln?Ln.removeToast(ta.id):I$a.forEach(Ta=>{Ta.removeToast(ta.id)})}}var Ct$2=(ta={})=>{I$a.forEach(Ln=>{Ln.props.limit&&(!ta.containerId||Ln.id===ta.containerId)&&Ln.clearQueue()})};function nt$2(ta,Ln){z$7(ta)&&(bt$1()||F$9.push({content:ta,options:Ln}),I$a.forEach(Ta=>{Ta.buildToast(ta,Ln)}))}function xt$1(ta){var Ln;(Ln=I$a.get(ta.containerId||1))==null||Ln.setToggle(ta.id,ta.fn)}function rt$2(ta,Ln){I$a.forEach(Ta=>{(Ln==null||!(Ln!=null&&Ln.containerId)||Ln?.containerId===Ta.id)&&Ta.toggle(ta,Ln?.id)})}function Et$3(ta){let Ln=ta.containerId||1;return{subscribe(Ta){let ja=_t$2(Ln,ta,Vt$1);I$a.set(Ln,ja);let La=ja.observe(Ta);return Qt$1(),()=>{La(),I$a.delete(Ln)}},setProps(Ta){var ja;(ja=I$a.get(Ln))==null||ja.setProps(Ta)},getSnapshot(){var Ta;return(Ta=I$a.get(Ln))==null?void 0:Ta.getSnapshot()}}}function Pt$3(ta){return st$2.add(ta),()=>{st$2.delete(ta)}}function Wt$1(ta){return ta&&(N$7(ta.toastId)||L$7(ta.toastId))?ta.toastId:at$2()}function U$5(ta,Ln){return nt$2(ta,Ln),Ln.toastId}function V$8(ta,Ln){return{...Ln,type:Ln&&Ln.type||ta,toastId:Wt$1(Ln)}}function Q$6(ta){return(Ln,Ta)=>U$5(Ln,V$8(ta,Ta))}function y$b(ta,Ln){return U$5(ta,V$8("default",Ln))}y$b.loading=(ta,Ln)=>U$5(ta,V$8("default",{isLoading:!0,autoClose:!1,closeOnClick:!1,closeButton:!1,draggable:!1,...Ln}));function Gt$1(ta,{pending:Ln,error:Ta,success:ja},La){let Fa;Ln&&(Fa=N$7(Ln)?y$b.loading(Ln,La):y$b.loading(Ln.render,{...La,...Ln}));let wl={isLoading:null,autoClose:null,closeOnClick:null,closeButton:null,draggable:null},Pl=(mc,gc,Vd)=>{if(gc==null){y$b.dismiss(Fa);return}let Wd={type:mc,...wl,...La,data:Vd},kf=N$7(gc)?{render:gc}:gc;return Fa?y$b.update(Fa,{...Wd,...kf}):y$b(kf.render,{...Wd,...kf}),Vd},pc=P$b(ta)?ta():ta;return pc.then(mc=>Pl("success",ja,mc)).catch(mc=>Pl("error",Ta,mc)),pc}y$b.promise=Gt$1;y$b.success=Q$6("success");y$b.info=Q$6("info");y$b.error=Q$6("error");y$b.warning=Q$6("warning");y$b.warn=y$b.warning;y$b.dark=(ta,Ln)=>U$5(ta,V$8("default",{theme:"dark",...Ln}));function qt$1(ta){ht$2(ta)}y$b.dismiss=qt$1;y$b.clearWaitingQueue=Ct$2;y$b.isActive=X$5;y$b.update=(ta,Ln={})=>{let Ta=vt$2(ta,Ln);if(Ta){let{props:ja,content:La}=Ta,Fa={delay:100,...ja,...Ln,toastId:Ln.toastId||ta,updateId:at$2()};Fa.toastId!==ta&&(Fa.staleId=ta);let wl=Fa.render||La;delete Fa.render,U$5(wl,Fa)}};y$b.done=ta=>{y$b.update(ta,{progress:1})};y$b.onChange=Pt$3;y$b.play=ta=>rt$2(!0,ta);y$b.pause=ta=>rt$2(!1,ta);function It$2(ta){var Ln;let{subscribe:Ta,getSnapshot:ja,setProps:La}=reactExports$1.useRef(Et$3(ta)).current;La(ta);let Fa=(Ln=reactExports$1.useSyncExternalStore(Ta,ja,ja))==null?void 0:Ln.slice();function wl(Pl){if(!Fa)return[];let pc=new Map;return ta.newestOnTop&&Fa.reverse(),Fa.forEach(mc=>{let{position:gc}=mc.props;pc.has(gc)||pc.set(gc,[]),pc.get(gc).push(mc)}),Array.from(pc,mc=>Pl(mc[0],mc[1]))}return{getToastToRender:wl,isToastActive:X$5,count:Fa?.length}}function At$2(ta){let[Ln,Ta]=reactExports$1.useState(!1),[ja,La]=reactExports$1.useState(!1),Fa=reactExports$1.useRef(null),wl=reactExports$1.useRef({start:0,delta:0,removalDistance:0,canCloseOnClick:!0,canDrag:!1,didMove:!1}).current,{autoClose:Pl,pauseOnHover:pc,closeToast:mc,onClick:gc,closeOnClick:Vd}=ta;xt$1({id:ta.toastId,containerId:ta.containerId,fn:Ta}),reactExports$1.useEffect(()=>{if(ta.pauseOnFocusLoss)return Wd(),()=>{kf()}},[ta.pauseOnFocusLoss]);function Wd(){document.hasFocus()||Em(),window.addEventListener("focus",Eh),window.addEventListener("blur",Em)}function kf(){window.removeEventListener("focus",Eh),window.removeEventListener("blur",Em)}function Pf(VC){if(ta.draggable===!0||ta.draggable===VC.pointerType){qg();let tj=Fa.current;wl.canCloseOnClick=!0,wl.canDrag=!0,tj.style.transition="none",ta.draggableDirection==="x"?(wl.start=VC.clientX,wl.removalDistance=tj.offsetWidth*(ta.draggablePercent/100)):(wl.start=VC.clientY,wl.removalDistance=tj.offsetHeight*(ta.draggablePercent===80?ta.draggablePercent*1.5:ta.draggablePercent)/100)}}function Nf(VC){let{top:tj,bottom:aB,left:r6,right:J2}=Fa.current.getBoundingClientRect();VC.nativeEvent.type!=="touchend"&&ta.pauseOnHover&&VC.clientX>=r6&&VC.clientX<=J2&&VC.clientY>=tj&&VC.clientY<=aB?Em():Eh()}function Eh(){Ta(!0)}function Em(){Ta(!1)}function qg(){wl.didMove=!1,document.addEventListener("pointermove",Bg),document.addEventListener("pointerup",U_)}function Ug(){document.removeEventListener("pointermove",Bg),document.removeEventListener("pointerup",U_)}function Bg(VC){let tj=Fa.current;if(wl.canDrag&&tj){wl.didMove=!0,Ln&&Em(),ta.draggableDirection==="x"?wl.delta=VC.clientX-wl.start:wl.delta=VC.clientY-wl.start,wl.start!==VC.clientX&&(wl.canCloseOnClick=!1);let aB=ta.draggableDirection==="x"?`${wl.delta}px, var(--y)`:`0, calc(${wl.delta}px + var(--y))`;tj.style.transform=`translate3d(${aB},0)`,tj.style.opacity=`${1-Math.abs(wl.delta/wl.removalDistance)}`}}function U_(){Ug();let VC=Fa.current;if(wl.canDrag&&wl.didMove&&VC){if(wl.canDrag=!1,Math.abs(wl.delta)>wl.removalDistance){La(!0),ta.closeToast(!0),ta.collapseAll();return}VC.style.transition="transform 0.2s, opacity 0.2s",VC.style.removeProperty("transform"),VC.style.removeProperty("opacity")}}let B_={onPointerDown:Pf,onPointerUp:Nf};return Pl&&pc&&(B_.onMouseEnter=Em,ta.stacked||(B_.onMouseLeave=Eh)),Vd&&(B_.onClick=VC=>{gc&&gc(VC),wl.canCloseOnClick&&mc(!0)}),{playToast:Eh,pauseToast:Em,isRunning:Ln,preventExitTransition:ja,toastRef:Fa,eventHandlers:B_}}var Ot$1=typeof window<"u"?reactExports$1.useLayoutEffect:reactExports$1.useEffect,G$6=({theme:ta,type:Ln,isLoading:Ta,...ja})=>React.createElement("svg",{viewBox:"0 0 24 24",width:"100%",height:"100%",fill:ta==="colored"?"currentColor":`var(--toastify-icon-color-${Ln})`,...ja});function ao$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M23.32 17.191L15.438 2.184C14.728.833 13.416 0 11.996 0c-1.42 0-2.733.833-3.443 2.184L.533 17.448a4.744 4.744 0 000 4.368C1.243 23.167 2.555 24 3.975 24h16.05C22.22 24 24 22.044 24 19.632c0-.904-.251-1.746-.68-2.44zm-9.622 1.46c0 1.033-.724 1.823-1.698 1.823s-1.698-.79-1.698-1.822v-.043c0-1.028.724-1.822 1.698-1.822s1.698.79 1.698 1.822v.043zm.039-12.285l-.84 8.06c-.057.581-.408.943-.897.943-.49 0-.84-.367-.896-.942l-.84-8.065c-.057-.624.25-1.095.779-1.095h1.91c.528.005.84.476.784 1.1z"}))}function so$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M12 0a12 12 0 1012 12A12.013 12.013 0 0012 0zm.25 5a1.5 1.5 0 11-1.5 1.5 1.5 1.5 0 011.5-1.5zm2.25 13.5h-4a1 1 0 010-2h.75a.25.25 0 00.25-.25v-4.5a.25.25 0 00-.25-.25h-.75a1 1 0 010-2h1a2 2 0 012 2v4.75a.25.25 0 00.25.25h.75a1 1 0 110 2z"}))}function no$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M12 0a12 12 0 1012 12A12.014 12.014 0 0012 0zm6.927 8.2l-6.845 9.289a1.011 1.011 0 01-1.43.188l-4.888-3.908a1 1 0 111.25-1.562l4.076 3.261 6.227-8.451a1 1 0 111.61 1.183z"}))}function ro$1(ta){return React.createElement(G$6,{...ta},React.createElement("path",{d:"M11.983 0a12.206 12.206 0 00-8.51 3.653A11.8 11.8 0 000 12.207 11.779 11.779 0 0011.8 24h.214A12.111 12.111 0 0024 11.791 11.766 11.766 0 0011.983 0zM10.5 16.542a1.476 1.476 0 011.449-1.53h.027a1.527 1.527 0 011.523 1.47 1.475 1.475 0 01-1.449 1.53h-.027a1.529 1.529 0 01-1.523-1.47zM11 12.5v-6a1 1 0 012 0v6a1 1 0 11-2 0z"}))}function io$1(){return React.createElement("div",{className:"Toastify__spinner"})}var W$5={info:so$1,warning:ao$1,success:no$1,error:ro$1,spinner:io$1},lo$2=ta=>ta in W$5;function Nt$1({theme:ta,type:Ln,isLoading:Ta,icon:ja}){let La=null,Fa={theme:ta,type:Ln};return ja===!1||(P$b(ja)?La=ja({...Fa,isLoading:Ta}):reactExports$1.isValidElement(ja)?La=reactExports$1.cloneElement(ja,Fa):Ta?La=W$5.spinner():lo$2(Ln)&&(La=W$5[Ln](Fa))),La}var wt$2=ta=>{let{isRunning:Ln,preventExitTransition:Ta,toastRef:ja,eventHandlers:La,playToast:Fa}=At$2(ta),{closeButton:wl,children:Pl,autoClose:pc,onClick:mc,type:gc,hideProgressBar:Vd,closeToast:Wd,transition:kf,position:Pf,className:Nf,style:Eh,progressClassName:Em,updateId:qg,role:Ug,progress:Bg,rtl:U_,toastId:B_,deleteToast:VC,isIn:tj,isLoading:aB,closeOnClick:r6,theme:J2,ariaLabel:V_}=ta,sP=clsx("Toastify__toast",`Toastify__toast-theme--${J2}`,`Toastify__toast--${gc}`,{"Toastify__toast--rtl":U_},{"Toastify__toast--close-on-click":r6}),Q2=P$b(Nf)?Nf({rtl:U_,position:Pf,type:gc,defaultClassName:sP}):clsx(sP,Nf),q5=Nt$1(ta),nj=!!Bg||!pc,n6={closeToast:Wd,type:gc,theme:J2},l6=null;return wl===!1||(P$b(wl)?l6=wl(n6):reactExports$1.isValidElement(wl)?l6=reactExports$1.cloneElement(wl,n6):l6=yt$2(n6)),React.createElement(kf,{isIn:tj,done:VC,position:Pf,preventExitTransition:Ta,nodeRef:ja,playToast:Fa},React.createElement("div",{id:B_,tabIndex:0,onClick:mc,"data-in":tj,className:Q2,...La,style:Eh,ref:ja,...tj&&{role:Ug,"aria-label":V_}},q5!=null&&React.createElement("div",{className:clsx("Toastify__toast-icon",{"Toastify--animate-icon Toastify__zoom-enter":!aB})},q5),tt$2(Pl,ta,!Ln),l6,!ta.customProgressBar&&React.createElement(gt$3,{...qg&&!nj?{key:`p-${qg}`}:{},rtl:U_,theme:J2,delay:pc,isRunning:Ln,isIn:tj,closeToast:Wd,hide:Vd,type:gc,className:Em,controlledProgress:nj,progress:Bg||0})))},K$7=(ta,Ln=!1)=>({enter:`Toastify--animate Toastify__${ta}-enter`,exit:`Toastify--animate Toastify__${ta}-exit`,appendPosition:Ln}),lt$2=$$7(K$7("bounce",!0)),_o$1={position:"top-right",transition:lt$2,autoClose:5e3,closeButton:!0,pauseOnHover:!0,pauseOnFocusLoss:!0,draggable:"touch",draggablePercent:80,draggableDirection:"x",role:"alert",theme:"light","aria-label":"Notifications Alt+T",hotKeys:ta=>ta.altKey&&ta.code==="KeyT"};function Lt$1(ta){let Ln={..._o$1,...ta},Ta=ta.stacked,[ja,La]=reactExports$1.useState(!0),Fa=reactExports$1.useRef(null),{getToastToRender:wl,isToastActive:Pl,count:pc}=It$2(Ln),{className:mc,style:gc,rtl:Vd,containerId:Wd,hotKeys:kf}=Ln;function Pf(Eh){let Em=clsx("Toastify__toast-container",`Toastify__toast-container--${Eh}`,{"Toastify__toast-container--rtl":Vd});return P$b(mc)?mc({position:Eh,rtl:Vd,defaultClassName:Em}):clsx(Em,B$7(mc))}function Nf(){Ta&&(La(!0),y$b.play())}return Ot$1(()=>{var Eh;if(Ta){let Em=Fa.current.querySelectorAll('[data-in="true"]'),qg=12,Ug=(Eh=Ln.position)==null?void 0:Eh.includes("top"),Bg=0,U_=0;Array.from(Em).reverse().forEach((B_,VC)=>{let tj=B_;tj.classList.add("Toastify__toast--stacked"),VC>0&&(tj.dataset.collapsed=`${ja}`),tj.dataset.pos||(tj.dataset.pos=Ug?"top":"bot");let aB=Bg*(ja?.2:1)+(ja?0:qg*VC);tj.style.setProperty("--y",`${Ug?aB:aB*-1}px`),tj.style.setProperty("--g",`${qg}`),tj.style.setProperty("--s",`${1-(ja?U_:0)}`),Bg+=tj.offsetHeight,U_+=.025})}},[ja,pc,Ta]),reactExports$1.useEffect(()=>{function Eh(Em){var qg;let Ug=Fa.current;kf(Em)&&((qg=Ug.querySelector('[tabIndex="0"]'))==null||qg.focus(),La(!1),y$b.pause()),Em.key==="Escape"&&(document.activeElement===Ug||Ug!=null&&Ug.contains(document.activeElement))&&(La(!0),y$b.play())}return document.addEventListener("keydown",Eh),()=>{document.removeEventListener("keydown",Eh)}},[kf]),React.createElement("section",{ref:Fa,className:"Toastify",id:Wd,onMouseEnter:()=>{Ta&&(La(!1),y$b.pause())},onMouseLeave:Nf,"aria-live":"polite","aria-atomic":"false","aria-relevant":"additions text","aria-label":Ln["aria-label"]},wl((Eh,Em)=>{let qg=Em.length?{...gc}:{...gc,pointerEvents:"none"};return React.createElement("div",{tabIndex:-1,className:Pf(Eh),"data-stacked":Ta,style:qg,key:`c-${Eh}`},Em.map(({content:Ug,props:Bg})=>React.createElement(wt$2,{...Bg,stacked:Ta,collapseAll:Nf,isIn:Pl(Bg.toastId,Bg.containerId),key:`t-${Bg.key}`},Ug)))}))}const RECENTLY_VISITED_TEAMS_KEY="recently-visited-teams",MAX_RECENTLY_VISITED=10;function transformSimpleTeamToTeam(ta){return{Branch:ta.branch||"",Config:ta.config||{},CreatedAt:ta.createdAt||"",Dependencies:ta.dependencies||{FractlModels:[],ClojureLibraries:[]},Description:ta.description||"",EntityType:ta.entityType||"",GitHubOrg:ta.gitHubOrg||"",GitHubRepo:ta.gitHubRepo||"",GithubUrl:ta.githubUrl||"",Id:ta.id||"",__Id__:ta.__Id__||ta.id||"",LastUpdatedAt:ta.lastUpdatedAt||"",Name:ta.name||"",Owner:ta.owner||"",Tags:ta.tags||null,Type:ta.type||"",Version:ta.version||"",isEditable:ta.isEditable||!1,isPin:ta.isPin==="true"||ta.isPin===!0}}function getRecentlyVisitedTeams(){try{const ta=localStorage.getItem(RECENTLY_VISITED_TEAMS_KEY);return ta?JSON.parse(ta):[]}catch{return[]}}function addRecentlyVisitedTeam(ta){try{const Ta=getRecentlyVisitedTeams().filter(La=>La!==ta),ja=[ta,...Ta].slice(0,MAX_RECENTLY_VISITED);localStorage.setItem(RECENTLY_VISITED_TEAMS_KEY,JSON.stringify(ja))}catch(Ln){console.warn("Failed to save recently visited team:",Ln)}}function filterAndSortTeams(ta,Ln){return Object.values(ta).filter(ja=>ja.Name!==void 0).filter(ja=>(ja.Name??"").toLowerCase().includes(Ln.toLowerCase())).sort((ja,La)=>{const Fa=Number(La.isPin??!1)-Number(ja.isPin??!1);if(Fa!==0)return Fa;const wl=(ja.Name??"").toLowerCase(),Pl=(La.Name??"").toLowerCase();return wl.localeCompare(Pl)})}function getIconsTree(ta,Ln){const Ta=ta.icons,ja=ta.aliases||Object.create(null),La=Object.create(null);function Fa(wl){if(Ta[wl])return La[wl]=[];if(!(wl in La)){La[wl]=null;const Pl=ja[wl]&&ja[wl].parent,pc=Pl&&Fa(Pl);pc&&(La[wl]=[Pl].concat(pc))}return La[wl]}return Object.keys(Ta).concat(Object.keys(ja)).forEach(Fa),La}const defaultIconDimensions=Object.freeze({left:0,top:0,width:16,height:16}),defaultIconTransformations=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),defaultIconProps=Object.freeze({...defaultIconDimensions,...defaultIconTransformations}),defaultExtendedIconProps=Object.freeze({...defaultIconProps,body:"",hidden:!1});function mergeIconTransformations(ta,Ln){const Ta={};!ta.hFlip!=!Ln.hFlip&&(Ta.hFlip=!0),!ta.vFlip!=!Ln.vFlip&&(Ta.vFlip=!0);const ja=((ta.rotate||0)+(Ln.rotate||0))%4;return ja&&(Ta.rotate=ja),Ta}function mergeIconData(ta,Ln){const Ta=mergeIconTransformations(ta,Ln);for(const ja in defaultExtendedIconProps)ja in defaultIconTransformations?ja in ta&&!(ja in Ta)&&(Ta[ja]=defaultIconTransformations[ja]):ja in Ln?Ta[ja]=Ln[ja]:ja in ta&&(Ta[ja]=ta[ja]);return Ta}function internalGetIconData(ta,Ln,Ta){const ja=ta.icons,La=ta.aliases||Object.create(null);let Fa={};function wl(Pl){Fa=mergeIconData(ja[Pl]||La[Pl],Fa)}return wl(Ln),Ta.forEach(wl),mergeIconData(ta,Fa)}function parseIconSet(ta,Ln){const Ta=[];if(typeof ta!="object"||typeof ta.icons!="object")return Ta;ta.not_found instanceof Array&&ta.not_found.forEach(La=>{Ln(La,null),Ta.push(La)});const ja=getIconsTree(ta);for(const La in ja){const Fa=ja[La];Fa&&(Ln(La,internalGetIconData(ta,La,Fa)),Ta.push(La))}return Ta}const optionalPropertyDefaults={provider:"",aliases:{},not_found:{},...defaultIconDimensions};function checkOptionalProps(ta,Ln){for(const Ta in Ln)if(Ta in ta&&typeof ta[Ta]!=typeof Ln[Ta])return!1;return!0}function quicklyValidateIconSet(ta){if(typeof ta!="object"||ta===null)return null;const Ln=ta;if(typeof Ln.prefix!="string"||!ta.icons||typeof ta.icons!="object"||!checkOptionalProps(ta,optionalPropertyDefaults))return null;const Ta=Ln.icons;for(const La in Ta){const Fa=Ta[La];if(!La||typeof Fa.body!="string"||!checkOptionalProps(Fa,defaultExtendedIconProps))return null}const ja=Ln.aliases||Object.create(null);for(const La in ja){const Fa=ja[La],wl=Fa.parent;if(!La||typeof wl!="string"||!Ta[wl]&&!ja[wl]||!checkOptionalProps(Fa,defaultExtendedIconProps))return null}return Ln}const dataStorage=Object.create(null);function newStorage(ta,Ln){return{provider:ta,prefix:Ln,icons:Object.create(null),missing:new Set}}function getStorage(ta,Ln){const Ta=dataStorage[ta]||(dataStorage[ta]=Object.create(null));return Ta[Ln]||(Ta[Ln]=newStorage(ta,Ln))}function addIconSet(ta,Ln){return quicklyValidateIconSet(Ln)?parseIconSet(Ln,(Ta,ja)=>{ja?ta.icons[Ta]=ja:ta.missing.add(Ta)}):[]}function addIconToStorage(ta,Ln,Ta){try{if(typeof Ta.body=="string")return ta.icons[Ln]={...Ta},!0}catch{}return!1}const matchIconName=/^[a-z0-9]+(-[a-z0-9]+)*$/,stringToIcon=(ta,Ln,Ta,ja="")=>{const La=ta.split(":");if(ta.slice(0,1)==="@"){if(La.length<2||La.length>3)return null;ja=La.shift().slice(1)}if(La.length>3||!La.length)return null;if(La.length>1){const Pl=La.pop(),pc=La.pop(),mc={provider:La.length>0?La[0]:ja,prefix:pc,name:Pl};return Ln&&!validateIconName(mc)?null:mc}const Fa=La[0],wl=Fa.split("-");if(wl.length>1){const Pl={provider:ja,prefix:wl.shift(),name:wl.join("-")};return Ln&&!validateIconName(Pl)?null:Pl}if(Ta&&ja===""){const Pl={provider:ja,prefix:"",name:Fa};return Ln&&!validateIconName(Pl,Ta)?null:Pl}return null},validateIconName=(ta,Ln)=>ta?!!((Ln&&ta.prefix===""||ta.prefix)&&ta.name):!1;let simpleNames=!1;function allowSimpleNames(ta){return typeof ta=="boolean"&&(simpleNames=ta),simpleNames}function getIconData(ta){const Ln=typeof ta=="string"?stringToIcon(ta,!0,simpleNames):ta;if(Ln){const Ta=getStorage(Ln.provider,Ln.prefix),ja=Ln.name;return Ta.icons[ja]||(Ta.missing.has(ja)?null:void 0)}}function addIcon(ta,Ln){const Ta=stringToIcon(ta,!0,simpleNames);if(!Ta)return!1;const ja=getStorage(Ta.provider,Ta.prefix);return Ln?addIconToStorage(ja,Ta.name,Ln):(ja.missing.add(Ta.name),!0)}function addCollection(ta,Ln){if(typeof ta!="object")return!1;if(typeof Ln!="string"&&(Ln=ta.provider||""),simpleNames&&!Ln&&!ta.prefix){let La=!1;return quicklyValidateIconSet(ta)&&(ta.prefix="",parseIconSet(ta,(Fa,wl)=>{addIcon(Fa,wl)&&(La=!0)})),La}const Ta=ta.prefix;if(!validateIconName({prefix:Ta,name:"a"}))return!1;const ja=getStorage(Ln,Ta);return!!addIconSet(ja,ta)}const defaultIconSizeCustomisations=Object.freeze({width:null,height:null}),defaultIconCustomisations=Object.freeze({...defaultIconSizeCustomisations,...defaultIconTransformations}),unitsSplit=/(-?[0-9.]*[0-9]+[0-9.]*)/g,unitsTest=/^-?[0-9.]*[0-9]+[0-9.]*$/g;function calculateSize(ta,Ln,Ta){if(Ln===1)return ta;if(Ta=Ta||100,typeof ta=="number")return Math.ceil(ta*Ln*Ta)/Ta;if(typeof ta!="string")return ta;const ja=ta.split(unitsSplit);if(ja===null||!ja.length)return ta;const La=[];let Fa=ja.shift(),wl=unitsTest.test(Fa);for(;;){if(wl){const Pl=parseFloat(Fa);isNaN(Pl)?La.push(Fa):La.push(Math.ceil(Pl*Ln*Ta)/Ta)}else La.push(Fa);if(Fa=ja.shift(),Fa===void 0)return La.join("");wl=!wl}}function splitSVGDefs(ta,Ln="defs"){let Ta="";const ja=ta.indexOf("<"+Ln);for(;ja>=0;){const La=ta.indexOf(">",ja),Fa=ta.indexOf("</"+Ln);if(La===-1||Fa===-1)break;const wl=ta.indexOf(">",Fa);if(wl===-1)break;Ta+=ta.slice(La+1,Fa).trim(),ta=ta.slice(0,ja).trim()+ta.slice(wl+1)}return{defs:Ta,content:ta}}function mergeDefsAndContent(ta,Ln){return ta?"<defs>"+ta+"</defs>"+Ln:Ln}function wrapSVGContent(ta,Ln,Ta){const ja=splitSVGDefs(ta);return mergeDefsAndContent(ja.defs,Ln+ja.content+Ta)}const isUnsetKeyword=ta=>ta==="unset"||ta==="undefined"||ta==="none";function iconToSVG(ta,Ln){const Ta={...defaultIconProps,...ta},ja={...defaultIconCustomisations,...Ln},La={left:Ta.left,top:Ta.top,width:Ta.width,height:Ta.height};let Fa=Ta.body;[Ta,ja].forEach(Nf=>{const Eh=[],Em=Nf.hFlip,qg=Nf.vFlip;let Ug=Nf.rotate;Em?qg?Ug+=2:(Eh.push("translate("+(La.width+La.left).toString()+" "+(0-La.top).toString()+")"),Eh.push("scale(-1 1)"),La.top=La.left=0):qg&&(Eh.push("translate("+(0-La.left).toString()+" "+(La.height+La.top).toString()+")"),Eh.push("scale(1 -1)"),La.top=La.left=0);let Bg;switch(Ug<0&&(Ug-=Math.floor(Ug/4)*4),Ug=Ug%4,Ug){case 1:Bg=La.height/2+La.top,Eh.unshift("rotate(90 "+Bg.toString()+" "+Bg.toString()+")");break;case 2:Eh.unshift("rotate(180 "+(La.width/2+La.left).toString()+" "+(La.height/2+La.top).toString()+")");break;case 3:Bg=La.width/2+La.left,Eh.unshift("rotate(-90 "+Bg.toString()+" "+Bg.toString()+")");break}Ug%2===1&&(La.left!==La.top&&(Bg=La.left,La.left=La.top,La.top=Bg),La.width!==La.height&&(Bg=La.width,La.width=La.height,La.height=Bg)),Eh.length&&(Fa=wrapSVGContent(Fa,'<g transform="'+Eh.join(" ")+'">',"</g>"))});const wl=ja.width,Pl=ja.height,pc=La.width,mc=La.height;let gc,Vd;wl===null?(Vd=Pl===null?"1em":Pl==="auto"?mc:Pl,gc=calculateSize(Vd,pc/mc)):(gc=wl==="auto"?pc:wl,Vd=Pl===null?calculateSize(gc,mc/pc):Pl==="auto"?mc:Pl);const Wd={},kf=(Nf,Eh)=>{isUnsetKeyword(Eh)||(Wd[Nf]=Eh.toString())};kf("width",gc),kf("height",Vd);const Pf=[La.left,La.top,pc,mc];return Wd.viewBox=Pf.join(" "),{attributes:Wd,viewBox:Pf,body:Fa}}const regex=/\sid="(\S+)"/g,randomPrefix="IconifyId"+Date.now().toString(16)+(Math.random()*16777216|0).toString(16);let counter=0;function replaceIDs(ta,Ln=randomPrefix){const Ta=[];let ja;for(;ja=regex.exec(ta);)Ta.push(ja[1]);if(!Ta.length)return ta;const La="suffix"+(Math.random()*16777216|Date.now()).toString(16);return Ta.forEach(Fa=>{const wl=typeof Ln=="function"?Ln(Fa):Ln+(counter++).toString(),Pl=Fa.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");ta=ta.replace(new RegExp('([#;"])('+Pl+')([")]|\\.[a-z])',"g"),"$1"+wl+La+"$3")}),ta=ta.replace(new RegExp(La,"g"),""),ta}const storage=Object.create(null);function setAPIModule(ta,Ln){storage[ta]=Ln}function getAPIModule(ta){return storage[ta]||storage[""]}function createAPIConfig(ta){let Ln;if(typeof ta.resources=="string")Ln=[ta.resources];else if(Ln=ta.resources,!(Ln instanceof Array)||!Ln.length)return null;return{resources:Ln,path:ta.path||"/",maxURL:ta.maxURL||500,rotate:ta.rotate||750,timeout:ta.timeout||5e3,random:ta.random===!0,index:ta.index||0,dataAfterTimeout:ta.dataAfterTimeout!==!1}}const configStorage=Object.create(null),fallBackAPISources=["https://api.simplesvg.com","https://api.unisvg.com"],fallBackAPI=[];for(;fallBackAPISources.length>0;)fallBackAPISources.length===1||Math.random()>.5?fallBackAPI.push(fallBackAPISources.shift()):fallBackAPI.push(fallBackAPISources.pop());configStorage[""]=createAPIConfig({resources:["https://api.iconify.design"].concat(fallBackAPI)});function addAPIProvider(ta,Ln){const Ta=createAPIConfig(Ln);return Ta===null?!1:(configStorage[ta]=Ta,!0)}function getAPIConfig(ta){return configStorage[ta]}const detectFetch=()=>{let ta;try{if(ta=fetch,typeof ta=="function")return ta}catch{}};let fetchModule=detectFetch();function calculateMaxLength(ta,Ln){const Ta=getAPIConfig(ta);if(!Ta)return 0;let ja;if(!Ta.maxURL)ja=0;else{let La=0;Ta.resources.forEach(wl=>{La=Math.max(La,wl.length)});const Fa=Ln+".json?icons=";ja=Ta.maxURL-La-Ta.path.length-Fa.length}return ja}function shouldAbort(ta){return ta===404}const prepare=(ta,Ln,Ta)=>{const ja=[],La=calculateMaxLength(ta,Ln),Fa="icons";let wl={type:Fa,provider:ta,prefix:Ln,icons:[]},Pl=0;return Ta.forEach((pc,mc)=>{Pl+=pc.length+1,Pl>=La&&mc>0&&(ja.push(wl),wl={type:Fa,provider:ta,prefix:Ln,icons:[]},Pl=pc.length),wl.icons.push(pc)}),ja.push(wl),ja};function getPath$2(ta){if(typeof ta=="string"){const Ln=getAPIConfig(ta);if(Ln)return Ln.path}return"/"}const send=(ta,Ln,Ta)=>{if(!fetchModule){Ta("abort",424);return}let ja=getPath$2(Ln.provider);switch(Ln.type){case"icons":{const Fa=Ln.prefix,Pl=Ln.icons.join(","),pc=new URLSearchParams({icons:Pl});ja+=Fa+".json?"+pc.toString();break}case"custom":{const Fa=Ln.uri;ja+=Fa.slice(0,1)==="/"?Fa.slice(1):Fa;break}default:Ta("abort",400);return}let La=503;fetchModule(ta+ja).then(Fa=>{const wl=Fa.status;if(wl!==200){setTimeout(()=>{Ta(shouldAbort(wl)?"abort":"next",wl)});return}return La=501,Fa.json()}).then(Fa=>{if(typeof Fa!="object"||Fa===null){setTimeout(()=>{Fa===404?Ta("abort",Fa):Ta("next",La)});return}setTimeout(()=>{Ta("success",Fa)})}).catch(()=>{Ta("next",La)})},fetchAPIModule={prepare,send};function removeCallback(ta,Ln){ta.forEach(Ta=>{const ja=Ta.loaderCallbacks;ja&&(Ta.loaderCallbacks=ja.filter(La=>La.id!==Ln))})}function updateCallbacks(ta){ta.pendingCallbacksFlag||(ta.pendingCallbacksFlag=!0,setTimeout(()=>{ta.pendingCallbacksFlag=!1;const Ln=ta.loaderCallbacks?ta.loaderCallbacks.slice(0):[];if(!Ln.length)return;let Ta=!1;const ja=ta.provider,La=ta.prefix;Ln.forEach(Fa=>{const wl=Fa.icons,Pl=wl.pending.length;wl.pending=wl.pending.filter(pc=>{if(pc.prefix!==La)return!0;const mc=pc.name;if(ta.icons[mc])wl.loaded.push({provider:ja,prefix:La,name:mc});else if(ta.missing.has(mc))wl.missing.push({provider:ja,prefix:La,name:mc});else return Ta=!0,!0;return!1}),wl.pending.length!==Pl&&(Ta||removeCallback([ta],Fa.id),Fa.callback(wl.loaded.slice(0),wl.missing.slice(0),wl.pending.slice(0),Fa.abort))})}))}let idCounter$1=0;function storeCallback(ta,Ln,Ta){const ja=idCounter$1++,La=removeCallback.bind(null,Ta,ja);if(!Ln.pending.length)return La;const Fa={id:ja,icons:Ln,callback:ta,abort:La};return Ta.forEach(wl=>{(wl.loaderCallbacks||(wl.loaderCallbacks=[])).push(Fa)}),La}function sortIcons(ta){const Ln={loaded:[],missing:[],pending:[]},Ta=Object.create(null);ta.sort((La,Fa)=>La.provider!==Fa.provider?La.provider.localeCompare(Fa.provider):La.prefix!==Fa.prefix?La.prefix.localeCompare(Fa.prefix):La.name.localeCompare(Fa.name));let ja={provider:"",prefix:"",name:""};return ta.forEach(La=>{if(ja.name===La.name&&ja.prefix===La.prefix&&ja.provider===La.provider)return;ja=La;const Fa=La.provider,wl=La.prefix,Pl=La.name,pc=Ta[Fa]||(Ta[Fa]=Object.create(null)),mc=pc[wl]||(pc[wl]=getStorage(Fa,wl));let gc;Pl in mc.icons?gc=Ln.loaded:wl===""||mc.missing.has(Pl)?gc=Ln.missing:gc=Ln.pending;const Vd={provider:Fa,prefix:wl,name:Pl};gc.push(Vd)}),Ln}function listToIcons(ta,Ln=!0,Ta=!1){const ja=[];return ta.forEach(La=>{const Fa=typeof La=="string"?stringToIcon(La,Ln,Ta):La;Fa&&ja.push(Fa)}),ja}const defaultConfig={resources:[],index:0,timeout:2e3,rotate:750,random:!1,dataAfterTimeout:!1};function sendQuery(ta,Ln,Ta,ja){const La=ta.resources.length,Fa=ta.random?Math.floor(Math.random()*La):ta.index;let wl;if(ta.random){let B_=ta.resources.slice(0);for(wl=[];B_.length>1;){const VC=Math.floor(Math.random()*B_.length);wl.push(B_[VC]),B_=B_.slice(0,VC).concat(B_.slice(VC+1))}wl=wl.concat(B_)}else wl=ta.resources.slice(Fa).concat(ta.resources.slice(0,Fa));const Pl=Date.now();let pc="pending",mc=0,gc,Vd=null,Wd=[],kf=[];typeof ja=="function"&&kf.push(ja);function Pf(){Vd&&(clearTimeout(Vd),Vd=null)}function Nf(){pc==="pending"&&(pc="aborted"),Pf(),Wd.forEach(B_=>{B_.status==="pending"&&(B_.status="aborted")}),Wd=[]}function Eh(B_,VC){VC&&(kf=[]),typeof B_=="function"&&kf.push(B_)}function Em(){return{startTime:Pl,payload:Ln,status:pc,queriesSent:mc,queriesPending:Wd.length,subscribe:Eh,abort:Nf}}function qg(){pc="failed",kf.forEach(B_=>{B_(void 0,gc)})}function Ug(){Wd.forEach(B_=>{B_.status==="pending"&&(B_.status="aborted")}),Wd=[]}function Bg(B_,VC,tj){const aB=VC!=="success";switch(Wd=Wd.filter(r6=>r6!==B_),pc){case"pending":break;case"failed":if(aB||!ta.dataAfterTimeout)return;break;default:return}if(VC==="abort"){gc=tj,qg();return}if(aB){gc=tj,Wd.length||(wl.length?U_():qg());return}if(Pf(),Ug(),!ta.random){const r6=ta.resources.indexOf(B_.resource);r6!==-1&&r6!==ta.index&&(ta.index=r6)}pc="completed",kf.forEach(r6=>{r6(tj)})}function U_(){if(pc!=="pending")return;Pf();const B_=wl.shift();if(B_===void 0){if(Wd.length){Vd=setTimeout(()=>{Pf(),pc==="pending"&&(Ug(),qg())},ta.timeout);return}qg();return}const VC={status:"pending",resource:B_,callback:(tj,aB)=>{Bg(VC,tj,aB)}};Wd.push(VC),mc++,Vd=setTimeout(U_,ta.rotate),Ta(B_,Ln,VC.callback)}return setTimeout(U_),Em}function initRedundancy(ta){const Ln={...defaultConfig,...ta};let Ta=[];function ja(){Ta=Ta.filter(Pl=>Pl().status==="pending")}function La(Pl,pc,mc){const gc=sendQuery(Ln,Pl,pc,(Vd,Wd)=>{ja(),mc&&mc(Vd,Wd)});return Ta.push(gc),gc}function Fa(Pl){return Ta.find(pc=>Pl(pc))||null}return{query:La,find:Fa,setIndex:Pl=>{Ln.index=Pl},getIndex:()=>Ln.index,cleanup:ja}}function emptyCallback$1(){}const redundancyCache=Object.create(null);function getRedundancyCache(ta){if(!redundancyCache[ta]){const Ln=getAPIConfig(ta);if(!Ln)return;const Ta=initRedundancy(Ln),ja={config:Ln,redundancy:Ta};redundancyCache[ta]=ja}return redundancyCache[ta]}function sendAPIQuery(ta,Ln,Ta){let ja,La;if(typeof ta=="string"){const Fa=getAPIModule(ta);if(!Fa)return Ta(void 0,424),emptyCallback$1;La=Fa.send;const wl=getRedundancyCache(ta);wl&&(ja=wl.redundancy)}else{const Fa=createAPIConfig(ta);if(Fa){ja=initRedundancy(Fa);const wl=ta.resources?ta.resources[0]:"",Pl=getAPIModule(wl);Pl&&(La=Pl.send)}}return!ja||!La?(Ta(void 0,424),emptyCallback$1):ja.query(Ln,La,Ta)().abort}function emptyCallback(){}function loadedNewIcons(ta){ta.iconsLoaderFlag||(ta.iconsLoaderFlag=!0,setTimeout(()=>{ta.iconsLoaderFlag=!1,updateCallbacks(ta)}))}function checkIconNamesForAPI(ta){const Ln=[],Ta=[];return ta.forEach(ja=>{(ja.match(matchIconName)?Ln:Ta).push(ja)}),{valid:Ln,invalid:Ta}}function parseLoaderResponse(ta,Ln,Ta){function ja(){const La=ta.pendingIcons;Ln.forEach(Fa=>{La&&La.delete(Fa),ta.icons[Fa]||ta.missing.add(Fa)})}if(Ta&&typeof Ta=="object")try{if(!addIconSet(ta,Ta).length){ja();return}}catch(La){console.error(La)}ja(),loadedNewIcons(ta)}function parsePossiblyAsyncResponse(ta,Ln){ta instanceof Promise?ta.then(Ta=>{Ln(Ta)}).catch(()=>{Ln(null)}):Ln(ta)}function loadNewIcons(ta,Ln){ta.iconsToLoad?ta.iconsToLoad=ta.iconsToLoad.concat(Ln).sort():ta.iconsToLoad=Ln,ta.iconsQueueFlag||(ta.iconsQueueFlag=!0,setTimeout(()=>{ta.iconsQueueFlag=!1;const{provider:Ta,prefix:ja}=ta,La=ta.iconsToLoad;if(delete ta.iconsToLoad,!La||!La.length)return;const Fa=ta.loadIcon;if(ta.loadIcons&&(La.length>1||!Fa)){parsePossiblyAsyncResponse(ta.loadIcons(La,ja,Ta),gc=>{parseLoaderResponse(ta,La,gc)});return}if(Fa){La.forEach(gc=>{const Vd=Fa(gc,ja,Ta);parsePossiblyAsyncResponse(Vd,Wd=>{const kf=Wd?{prefix:ja,icons:{[gc]:Wd}}:null;parseLoaderResponse(ta,[gc],kf)})});return}const{valid:wl,invalid:Pl}=checkIconNamesForAPI(La);if(Pl.length&&parseLoaderResponse(ta,Pl,null),!wl.length)return;const pc=ja.match(matchIconName)?getAPIModule(Ta):null;if(!pc){parseLoaderResponse(ta,wl,null);return}pc.prepare(Ta,ja,wl).forEach(gc=>{sendAPIQuery(Ta,gc,Vd=>{parseLoaderResponse(ta,gc.icons,Vd)})})}))}const loadIcons=(ta,Ln)=>{const Ta=listToIcons(ta,!0,allowSimpleNames()),ja=sortIcons(Ta);if(!ja.pending.length){let pc=!0;return Ln&&setTimeout(()=>{pc&&Ln(ja.loaded,ja.missing,ja.pending,emptyCallback)}),()=>{pc=!1}}const La=Object.create(null),Fa=[];let wl,Pl;return ja.pending.forEach(pc=>{const{provider:mc,prefix:gc}=pc;if(gc===Pl&&mc===wl)return;wl=mc,Pl=gc,Fa.push(getStorage(mc,gc));const Vd=La[mc]||(La[mc]=Object.create(null));Vd[gc]||(Vd[gc]=[])}),ja.pending.forEach(pc=>{const{provider:mc,prefix:gc,name:Vd}=pc,Wd=getStorage(mc,gc),kf=Wd.pendingIcons||(Wd.pendingIcons=new Set);kf.has(Vd)||(kf.add(Vd),La[mc][gc].push(Vd))}),Fa.forEach(pc=>{const mc=La[pc.provider][pc.prefix];mc.length&&loadNewIcons(pc,mc)}),Ln?storeCallback(Ln,ja,Fa):emptyCallback};function mergeCustomisations(ta,Ln){const Ta={...ta};for(const ja in Ln){const La=Ln[ja],Fa=typeof La;ja in defaultIconSizeCustomisations?(La===null||La&&(Fa==="string"||Fa==="number"))&&(Ta[ja]=La):Fa===typeof Ta[ja]&&(Ta[ja]=ja==="rotate"?La%4:La)}return Ta}const separator$1=/[\s,]+/;function flipFromString(ta,Ln){Ln.split(separator$1).forEach(Ta=>{switch(Ta.trim()){case"horizontal":ta.hFlip=!0;break;case"vertical":ta.vFlip=!0;break}})}function rotateFromString(ta,Ln=0){const Ta=ta.replace(/^-?[0-9.]*/,"");function ja(La){for(;La<0;)La+=4;return La%4}if(Ta===""){const La=parseInt(ta);return isNaN(La)?0:ja(La)}else if(Ta!==ta){let La=0;switch(Ta){case"%":La=25;break;case"deg":La=90}if(La){let Fa=parseFloat(ta.slice(0,ta.length-Ta.length));return isNaN(Fa)?0:(Fa=Fa/La,Fa%1===0?ja(Fa):0)}}return Ln}function iconToHTML(ta,Ln){let Ta=ta.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(const ja in Ln)Ta+=" "+ja+'="'+Ln[ja]+'"';return'<svg xmlns="http://www.w3.org/2000/svg"'+Ta+">"+ta+"</svg>"}function encodeSVGforURL(ta){return ta.replace(/"/g,"'").replace(/%/g,"%25").replace(/#/g,"%23").replace(/</g,"%3C").replace(/>/g,"%3E").replace(/\s+/g," ")}function svgToData(ta){return"data:image/svg+xml,"+encodeSVGforURL(ta)}function svgToURL(ta){return'url("'+svgToData(ta)+'")'}let policy;function createPolicy(){try{policy=window.trustedTypes.createPolicy("iconify",{createHTML:ta=>ta})}catch{policy=null}}function cleanUpInnerHTML(ta){return policy===void 0&&createPolicy(),policy?policy.createHTML(ta):ta}const defaultExtendedIconCustomisations={...defaultIconCustomisations,inline:!1},svgDefaults={xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink","aria-hidden":!0,role:"img"},commonProps={display:"inline-block"},monotoneProps={backgroundColor:"currentColor"},coloredProps={backgroundColor:"transparent"},propsToAdd={Image:"var(--svg)",Repeat:"no-repeat",Size:"100% 100%"},propsToAddTo={WebkitMask:monotoneProps,mask:monotoneProps,background:coloredProps};for(const ta in propsToAddTo){const Ln=propsToAddTo[ta];for(const Ta in propsToAdd)Ln[ta+Ta]=propsToAdd[Ta]}const inlineDefaults={...defaultExtendedIconCustomisations,inline:!0};function fixSize(ta){return ta+(ta.match(/^[-0-9.]+$/)?"px":"")}const render=(ta,Ln,Ta)=>{const ja=Ln.inline?inlineDefaults:defaultExtendedIconCustomisations,La=mergeCustomisations(ja,Ln),Fa=Ln.mode||"svg",wl={},Pl=Ln.style||{},pc={...Fa==="svg"?svgDefaults:{}};if(Ta){const Eh=stringToIcon(Ta,!1,!0);if(Eh){const Em=["iconify"],qg=["provider","prefix"];for(const Ug of qg)Eh[Ug]&&Em.push("iconify--"+Eh[Ug]);pc.className=Em.join(" ")}}for(let Eh in Ln){const Em=Ln[Eh];if(Em!==void 0)switch(Eh){case"icon":case"style":case"children":case"onLoad":case"mode":case"ssr":case"fallback":break;case"_ref":pc.ref=Em;break;case"className":pc[Eh]=(pc[Eh]?pc[Eh]+" ":"")+Em;break;case"inline":case"hFlip":case"vFlip":La[Eh]=Em===!0||Em==="true"||Em===1;break;case"flip":typeof Em=="string"&&flipFromString(La,Em);break;case"color":wl.color=Em;break;case"rotate":typeof Em=="string"?La[Eh]=rotateFromString(Em):typeof Em=="number"&&(La[Eh]=Em);break;case"ariaHidden":case"aria-hidden":Em!==!0&&Em!=="true"&&delete pc["aria-hidden"];break;default:ja[Eh]===void 0&&(pc[Eh]=Em)}}const mc=iconToSVG(ta,La),gc=mc.attributes;if(La.inline&&(wl.verticalAlign="-0.125em"),Fa==="svg"){pc.style={...wl,...Pl},Object.assign(pc,gc);let Eh=0,Em=Ln.id;return typeof Em=="string"&&(Em=Em.replace(/-/g,"_")),pc.dangerouslySetInnerHTML={__html:cleanUpInnerHTML(replaceIDs(mc.body,Em?()=>Em+"ID"+Eh++:"iconifyReact"))},reactExports$1.createElement("svg",pc)}const{body:Vd,width:Wd,height:kf}=ta,Pf=Fa==="mask"||(Fa==="bg"?!1:Vd.indexOf("currentColor")!==-1),Nf=iconToHTML(Vd,{...gc,width:Wd+"",height:kf+""});return pc.style={...wl,"--svg":svgToURL(Nf),width:fixSize(gc.width),height:fixSize(gc.height),...commonProps,...Pf?monotoneProps:coloredProps,...Pl},reactExports$1.createElement("span",pc)};allowSimpleNames(!0);setAPIModule("",fetchAPIModule);if(typeof document<"u"&&typeof window<"u"){const ta=window;if(ta.IconifyPreload!==void 0){const Ln=ta.IconifyPreload,Ta="Invalid IconifyPreload syntax.";typeof Ln=="object"&&Ln!==null&&(Ln instanceof Array?Ln:[Ln]).forEach(ja=>{try{(typeof ja!="object"||ja===null||ja instanceof Array||typeof ja.icons!="object"||typeof ja.prefix!="string"||!addCollection(ja))&&console.error(Ta)}catch{console.error(Ta)}})}if(ta.IconifyProviders!==void 0){const Ln=ta.IconifyProviders;if(typeof Ln=="object"&&Ln!==null)for(let Ta in Ln){const ja="IconifyProviders["+Ta+"] is invalid.";try{const La=Ln[Ta];if(typeof La!="object"||!La||La.resources===void 0)continue;addAPIProvider(Ta,La)||console.error(ja)}catch{console.error(ja)}}}}function IconComponent(ta){const[Ln,Ta]=reactExports$1.useState(!!ta.ssr),[ja,La]=reactExports$1.useState({});function Fa(kf){if(kf){const Pf=ta.icon;if(typeof Pf=="object")return{name:"",data:Pf};const Nf=getIconData(Pf);if(Nf)return{name:Pf,data:Nf}}return{name:""}}const[wl,Pl]=reactExports$1.useState(Fa(!!ta.ssr));function pc(){const kf=ja.callback;kf&&(kf(),La({}))}function mc(kf){if(JSON.stringify(wl)!==JSON.stringify(kf))return pc(),Pl(kf),!0}function gc(){var kf;const Pf=ta.icon;if(typeof Pf=="object"){mc({name:"",data:Pf});return}const Nf=getIconData(Pf);if(mc({name:Pf,data:Nf}))if(Nf===void 0){const Eh=loadIcons([Pf],gc);La({callback:Eh})}else Nf&&((kf=ta.onLoad)===null||kf===void 0||kf.call(ta,Pf))}reactExports$1.useEffect(()=>(Ta(!0),pc),[]),reactExports$1.useEffect(()=>{Ln&&gc()},[ta.icon,Ln]);const{name:Vd,data:Wd}=wl;return Wd?render({...defaultIconProps,...Wd},ta,Vd):ta.children?ta.children:ta.fallback?ta.fallback:reactExports$1.createElement("span",{})}const Icon=reactExports$1.forwardRef((ta,Ln)=>IconComponent({...ta,_ref:Ln}));reactExports$1.forwardRef((ta,Ln)=>IconComponent({inline:!0,...ta,_ref:Ln}));const getDate=ta=>{const Ln=new Date(ta),Ta=Ln.getMonth()+1,ja=Ln.getDate(),La=Ln.getFullYear(),Fa=Ln.toLocaleString("en-US",{hour:"numeric",minute:"numeric",hour12:!0});return`${Ta}/${ja}/${La} ${Fa}`},registerBase64Icon=(ta,Ln)=>{try{const Ta=Ln.replace(/^data:image\/svg\+xml;base64,/,""),ja=atob(Ta),La=ja.match(/width="([^"]+)"/),Fa=ja.match(/height="([^"]+)"/),wl=La?La[1]:"1536",Pl=Fa?Fa[1]:"1280",pc=ja.replace(/^.*?<svg[^>]*>(.*)<\/svg>.*$/,"$1");addIcon(ta,{body:pc,width:parseInt(wl,10),height:parseInt(Pl,10)})}catch(Ta){console.error(`Failed to register icon: ${ta}`,Ta)}};function extractRepoNameFromUrl(ta){const Ln=ta.split("/");return Ln[Ln.length-1]}function scrollIntoView(ta,Ln=!0){const Ta=document.getElementById(ta);Ta&&Ta.scrollIntoView({behavior:Ln?"smooth":"auto",block:"start",inline:"center"})}function roundTo3Decimals(ta){return ta.toFixed(3)}function convertBytes(ta){return ta<1024?`${ta} bytes`:ta<1024*1024?`${roundTo3Decimals(ta/1024)} KB`:ta<1024*1024*1024?`${roundTo3Decimals(ta/(1024*1024))} MB`:`${roundTo3Decimals(ta/(1024*1024*1024))} GB`}function generateGitHubUrl(ta,Ln,Ta,ja){if(!ta||!Ln)throw new Error("GitHub organization and repository name are required");if(Ta&&ja){const La=Ta.trim(),Fa=ja.trim();return!La||!Fa?(console.warn("GitHub credentials contain only whitespace - falling back to public URL"),`https://github.com/${ta}/${Ln}.git`):`https://${La}:${Fa}@github.com/${ta}/${Ln}.git`}return console.warn(`No GitHub credentials provided for ${ta}/${Ln} - using public URL (may fail for private repositories)`),`https://github.com/${ta}/${Ln}.git`}const useWorkspace=()=>{const ta=axiosInstance("meta"),Ln=useAppStore(gc=>gc.user),Ta=useAppStore(gc=>gc.authData.userProfileId),ja=useAppStore(gc=>gc.authData.username),La=useAppStore(gc=>gc.setUser),Fa=useAppStore(gc=>gc.setWorkspace),wl=async()=>{let gc=Ln?.user_profile_id;if(gc||(gc=Ta||void 0),!gc){const Vd=localStorage.getItem("user_profile_id");Vd&&(gc=Vd)}if(!gc){y$b.error("User Profile ID not found. Please re-login.");return}return gc},Pl=async()=>{try{if(!await wl())throw new Error("User Profile ID not found. Please re-login.");const Wd=await ta.get("/AgentMeta/Workspace");if(console.log("fetchWorkspace response:",Wd.data),!Wd.data||Array.isArray(Wd.data)&&Wd.data.length===0)return console.log("GetWorkspace returned empty or null response - workspace does not exist"),null;let kf;if(Wd.data.id||Wd.data.Id)kf=Wd.data;else if(Array.isArray(Wd.data)&&Wd.data.length>0){const Pf=Wd.data[0];Pf?.Workspace?kf=Pf.Workspace:Pf?.result&&Array.isArray(Pf.result)&&Pf.result.length>0?kf=Pf.result[0]:Pf&&(Pf.id||Pf.Id)&&(kf=Pf)}return kf||(console.log("No workspace found in response"),null)}catch(gc){return console.error("fetchWorkspace error:",gc),null}};return{fetchWorkspace:Pl,createWorkspace:async(gc,Vd)=>{try{if(!await wl())throw new Error("User Profile ID not found. Please re-login.");const Pf=await ta.post("/AgentMeta/Workspace",{name:gc,createdBy:Vd});let Nf;if(Pf.data.UserWorkspace?.Workspace)Nf=Pf.data.UserWorkspace.Workspace;else if(Pf.data.id)Nf=Pf.data;else if(Array.isArray(Pf.data)&&Pf.data.length>0){const Eh=Pf.data[0];Eh?.result&&Array.isArray(Eh.result)&&Eh.result.length>0?Nf=Eh.result[0]:Eh?.Workspace?Nf=Eh.Workspace:Nf=Eh}else if(Pf.data.Workspace)Nf=Pf.data.Workspace;else{const Eh=Object.keys(Pf.data);Eh.length>0&&(Nf=Pf.data[Eh[0]])}return Nf||(console.error("Failed to parse workspace from create response"),null)}catch(Wd){throw console.error("createWorkspace error:",Wd),y$b.error(Wd?.response?.data?.reason||"Failed to create workspace"),Wd}},fetchOrCreateWorkspace:async gc=>{if(!(ja||Ln?.Email))throw new Error("No username found in store");let Wd=await Pl();if(Wd){const kf=Wd.id||Wd.Id;if(kf&&!localStorage.getItem("workspace_id")){localStorage.setItem("workspace_id",kf);try{Ln?La({...Ln,CurrentWorkspace:{Id:kf}}):Fa(kf)}catch{}}}else{console.error(`Workspace '${gc}' not found - workspace creation disabled`);try{if(await wl()){const Nf=await ta.get("/AgentMeta/Workspace");if(Nf.data&&Array.isArray(Nf.data)&&Nf.data.length>0){const Eh=Nf.data[Nf.data.length-1];if(Wd=Eh.Workspace||Eh,Wd){const Em=Wd.id||Wd.Id;if(Em){localStorage.setItem("workspace_id",Em);try{Ln?La({...Ln,CurrentWorkspace:{Id:Em}}):Fa(Em)}catch{}console.log("Using existing workspace instead:",Em)}}}}}catch(kf){console.error("Failed to fetch all workspaces:",kf)}if(!Wd)throw new Error(`Workspace '${gc}' not found and creation is disabled`)}return Wd}}},deletePlaygroundTeam=ta=>[],STORAGE_KEY="playground-workspace-apps",ID_COUNTER_KEY="playground-workspace-id-counter";class PlaygroundWorkspaceStorage{apps=new Map;idCounter=0;constructor(){this.loadFromLocalStorage()}loadFromLocalStorage(){try{const Ln=localStorage.getItem(STORAGE_KEY);if(Ln){const ja=JSON.parse(Ln);ja.forEach(La=>{this.apps.set(La.Id,La)}),console.log(`[PLAYGROUND] Loaded ${ja.length} workspace apps from localStorage`)}const Ta=localStorage.getItem(ID_COUNTER_KEY);Ta&&(this.idCounter=parseInt(Ta,10))}catch(Ln){console.error("[PLAYGROUND] Error loading workspace apps from localStorage:",Ln)}}saveToLocalStorage(){try{const Ln=Array.from(this.apps.values());localStorage.setItem(STORAGE_KEY,JSON.stringify(Ln)),localStorage.setItem(ID_COUNTER_KEY,this.idCounter.toString()),console.log(`[PLAYGROUND] Saved ${Ln.length} workspace apps to localStorage`)}catch(Ln){console.error("[PLAYGROUND] Error saving workspace apps to localStorage:",Ln)}}getApps(){return Array.from(this.apps.values())}addApp(Ln){const Ta=Ln.Id||`playground-app-${++this.idCounter}`,ja={...Ln,Id:Ta};return this.apps.set(Ta,ja),this.saveToLocalStorage(),ja}updateApp(Ln,Ta){const ja=this.apps.get(Ln);if(!ja)return null;const La={...ja,...Ta};return this.apps.set(Ln,La),this.saveToLocalStorage(),La}deleteApp(Ln){const Ta=this.apps.delete(Ln);return Ta&&this.saveToLocalStorage(),Ta}getApp(Ln){return this.apps.get(Ln)||null}clearApps(){this.apps.clear(),this.idCounter=0,this.saveToLocalStorage()}hasApp(Ln){return this.apps.has(Ln)}}const playgroundWorkspaceStorage=new PlaygroundWorkspaceStorage,IS_PLAYGROUND$8=!1,IS_LOCAL_MODE$2=!0,metaAxiosInstance$2=axiosInstance("meta");async function fetchPackageInfo$1(){const Ln=await fetch("http://localhost:4000/info");if(!Ln.ok)return{};const Ta=await Ln.json();return console.log(Ta),Ta}async function fetchBranch(){const ta="http://localhost:4000";try{const Ln=await fetch(`${ta}/branch`);return Ln.ok&&(await Ln.json()).branch||"main"}catch(Ln){return console.warn("Failed to fetch branch:",Ln),"main"}}const useTeams=()=>{const{teamName:ta,modelName:Ln}=useParams(),{pathname:Ta}=useLocation(),ja=useQueryClient(),La=Ta.includes("/design/marketplace/"),Fa=useAppStore(V_=>V_.authData.username),wl=useAppStore(V_=>V_.authData.userProfileId),Pl=useAppStore(V_=>V_.user.CurrentWorkspace?.Id),pc=useAppStore(V_=>V_.user.GitHub.Token)||"",mc=useAppStore(V_=>V_.user.GitHub.Username)||"",{fetchOrCreateWorkspace:gc}=useWorkspace();useAppStore(V_=>V_.authReady),useAppStore(V_=>V_.isAuthenticated);const{data:Vd}=useQuery({queryKey:["localPackageInfo"],queryFn:fetchPackageInfo$1,enabled:IS_LOCAL_MODE$2,staleTime:1/0,refetchOnMount:"always"}),{data:Wd}=useQuery({queryKey:["localBranch"],queryFn:fetchBranch,enabled:IS_LOCAL_MODE$2,staleTime:1/0,refetchOnMount:"always"});console.log("localPackageInfo",Vd);const{data:kf,isLoading:Pf,error:Nf,refetch:Eh}=useQuery({queryKey:["workspace",Pl,"apps",wl],queryFn:async()=>[],enabled:IS_LOCAL_MODE$2,staleTime:120*1e3,gcTime:300*1e3,refetchOnMount:"always",retry:(V_,sP)=>sP?.response?.status===401||sP?.response?.status===403?!1:V_<2}),{mutate:Em}=useMutation({mutationFn:async({appId:V_,isEditable:sP})=>{const Q2=await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`,{isEditable:sP});return transformSimpleTeamToTeam(Q2.data)},onMutate:async V_=>{const{appId:sP,isEditable:Q2}=V_;await ja.cancelQueries({queryKey:["workspace",Pl,"apps",wl]});const q5=ja.getQueryData(["workspace",Pl,"apps",wl]);if(q5){const nj=q5.map(n6=>n6.Id===sP?{...n6,isEditable:Q2}:n6);ja.setQueryData(["workspace",Pl,"apps",wl],nj)}return{previousApps:q5}},onError:(V_,sP,Q2)=>{Q2?.previousApps&&ja.setQueryData(["workspace",Pl,"apps",wl],Q2.previousApps),y$b.error("Failed to update status. Please try again.")},onSettled:()=>{ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]})}}),qg=reactExports$1.useMemo(()=>{{let V_="";if(Vd&&Vd.name)if(V_=Vd.name,V_.startsWith("@")){const sP=V_.substring(1).split("/");sP.length===2&&(V_=sP[1])}else V_=Vd.name;return{Name:V_,isEditable:!0,Type:"Local",GitHubRepo:V_,Branch:Wd||"main"}}},[La,Ln,kf,ta,Vd,Wd]);if(Nf){console.error("fetchWorkspaceApps: Query failed",Nf);let V_="Failed to fetch workspace apps";const sP=Nf;sP?.response?.status===401?V_="Authentication expired. Please sign in again.":sP?.response?.status===403?V_="Access denied. Please check your workspace permissions.":sP?.response?.status===404?V_="Workspace not found. Please verify your workspace access.":sP?.response?.data?.reason?V_=sP.response.data.reason:sP?.message&&(V_=`Network error: ${sP.message}`),y$b.error(V_)}const Ug=async(V_,sP)=>{try{const q5=(await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${sP}`,V_)).data,nj=transformSimpleTeamToTeam(q5);return ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh(),{...nj}}catch(Q2){throw console.error("Error editing workspace app:",Q2),Q2}},Bg=async(V_,sP)=>{try{const q5=(await metaAxiosInstance$2.put(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`,{branch:sP})).data,nj=transformSimpleTeamToTeam(q5);return ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh(),{...nj,Branch:sP}}catch(Q2){throw console.error("Error switching workspace app branch:",Q2),Q2}},U_=async V_=>{try{let sP=Pl;if(!sP){const Q2=await gc("Default");if(Q2)sP=Q2.id||Q2.Id;else throw new Error("Failed to create or fetch Default workspace")}if(!sP)throw new Error("No workspace ID available after all attempts");await metaAxiosInstance$2.post(`/AgentMeta/Workspace/${sP}/WorkspaceApp/App`,V_),ja.invalidateQueries({queryKey:["workspace",sP,"apps",wl]}),ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh()}catch(sP){console.error("Error occurred:",sP),y$b.error(sP?.response?.data?.["status-text"]||sP?.response?.data?.reason||sP?.message||"Operation failed")}},B_=async V_=>{try{await metaAxiosInstance$2.delete(`/AgentMeta/Workspace/${Pl}/WorkspaceApp/App/${V_}`),ja.invalidateQueries({queryKey:["workspace",Pl,"apps",wl]}),await Eh()}catch(sP){console.error("Error occurred:",sP),y$b.error(sP?.response?.data?.["status-text"]||sP?.response?.data?.reason||sP?.message||"Operation failed")}},VC=async(V_,sP,Q2)=>{try{const q5=`/${V_.githubRepo}`,nj=V_.branchSelected&&V_.githubBranch?V_.githubBranch:"main",n6=mc&&mc.trim().length>0,l6=pc&&pc.trim().length>0,i6=generateGitHubUrl(V_.githubOrg,V_.githubRepo,mc,pc);if((!n6||!l6)&&sP("⚠️ GitHub credentials missing. Clone may fail for private repositories. Please set your GitHub username and token in Settings.",!1,!1),await pathExists(q5)){Q2("checking"),sP("Repository exists, checking for updates...",!1,!1);try{const u6=await updateExistingRepository(q5,pc,{branch:nj,checkOnly:!0});if(!u6.success)sP(`Warning: Could not check for updates - ${u6.message}. Using existing repository.`,!1,!1);else if(u6.hasUpdates){Q2("updating"),sP("Fetching latest changes...",!1,!1);const f6=await updateExistingRepository(q5,pc,{branch:nj,force:!0});f6.success?sP("Repository updated successfully!",!0,!1):sP(`Warning: Could not update repository - ${f6.message}. Using existing version.`,!1,!1)}else sP("No updates available",!0,!1)}catch(u6){console.error("Failed to update repository:",u6),sP(`Warning: Could not check for updates - ${u6.message}. Using existing repository.`,!1,!1)}}else{Q2("cloning"),sP("Cloning repository...",!1,!1);try{await cloneRepository(i6,q5,nj,pc),sP("Repository cloned successfully!",!0,!1)}catch(u6){console.error("Failed to clone repository:",u6),sP(`Failed to clone repository: ${u6.message}`,!1,!0);try{await pathExists(q5)&&(console.log(`Cleaning up failed clone: removing ${q5} from IndexedDB`),await removeDirectory(q5))}catch(f6){console.error("Error cleaning up failed clone:",f6)}return Q2("error"),{path:null,fileContent:null}}}try{Q2("processing"),sP("Searching for .al files...",!1,!1);const u6=await findFilesWithExtension(q5,"al");if(u6.length===0)return sP("No .al files found in the repository.",!1,!0),Q2("error"),{path:null,fileContent:null};sP(`Found ${u6.length} .al file(s).`,!0,!1);const f6=u6[0];sP(`Reading file: ${f6}...`,!1,!1);const Rpe=await readRepoFile(q5,f6);try{await readRepoFile(q5,"package.json")}catch{sP("Warning: package.json not found in repository",!1,!1)}try{return Q2("creating"),await flushAllAndLoad(q5,{name:"studio"}),sP(`${f6} loaded successfully!`,!0,!1),Q2("complete"),{path:q5,fileContent:Rpe}}catch(Xae){return console.error(`Failed to load ${f6}:`,Xae),sP(`Failed to load ${f6}: ${Xae.message}`,!1,!0),Q2("error"),{path:null,fileContent:null}}}catch(u6){return console.error("Failed to process .al files:",u6),sP(`Note: .al files not found or could not be read: ${u6.message}`,!1,!0),Q2("error"),{path:q5,fileContent:null}}}catch(q5){return console.error("Failed to execute Git operation:",q5),sP(`Failed to execute Git operation: ${q5.message}`,!1,!0),Q2("error"),{path:null,fileContent:null}}},tj=async(V_,sP,Q2)=>{try{Q2("Saving changes...",!1,!1);const q5=await openRepository(V_);return await writeRepoFile(V_,"README.md",sP),await commitChanges(q5,"README.md","Update README.md",{name:"Fractl Studio User",email:Fa||"user@fractl.studio"}),Q2("Changes saved successfully!",!0,!1),!0}catch(q5){return console.error("Failed to save README:",q5),Q2(`Failed to save: ${q5.message}`,!1,!0),!1}},aB=async(V_,sP)=>{try{sP("Pushing changes to repository...",!1,!1);const Q2=await openRepository(V_);return await pushChanges(Q2,"origin","main",pc),sP("Changes pushed successfully!",!0,!1),!0}catch(Q2){return console.error("Failed to push changes:",Q2),sP(`Failed to push: ${Q2.message}`,!1,!0),!1}},r6=reactExports$1.useCallback(async(V_,sP,Q2=!1)=>{Q2&&await Eh()},[Eh]),J2=qg?.isEditable??!0;return{currentTeam:qg,workspaceApps:kf,isLoadingApps:Pf,appsError:Nf,fetchWorkspaceApps:r6,editWorkspaceApp:Ug,switchWorkspaceAppBranch:Bg,updateWorkspaceAppEditable:Em,addWorkspaceApp:U_,cloneGitRepository:VC,saveReadmeChanges:tj,pushChanges:aB,deleteWorkspaceApp:B_,isEditable:J2}},integrationAxiosInstance$1=axiosInstance("connection-manager"),useLLM=()=>{const ta=useQueryClient(),Ln=useAppStore(kf=>kf.authReady),Ta=useAppStore(kf=>kf.isAuthenticated),ja=kf=>{const{__parent__:Pf,__path__:Nf,...Eh}=kf;return Eh},{data:La,isLoading:Fa,isError:wl,error:Pl,refetch:pc}=useQuery({queryKey:["llms"],queryFn:async()=>{const kf=await integrationAxiosInstance$1.get("/integmanager.core/llm"),{data:Pf,status:Nf}=kf;if(Nf!==200)throw new Error("Failed to fetch llms");return Pf.map(Em=>({...Em.llm,config:JSON.parse(Em.llm.config)}))},enabled:Ln&&Ta&&!0});wl&&Pl&&y$b.error(Pl?.response?.data?.reason||Pl.message);const mc=reactExports$1.useCallback(async kf=>{await pc()},[pc]),gc=reactExports$1.useCallback(async kf=>{try{const Pf=ja(kf),Nf=await integrationAxiosInstance$1.post("/integmanager.core/llm",Pf);if(Nf.status===200||Nf.status===201)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM created successfully");else{const Eh=Nf.data?.reason||Nf.data?.message||`Failed to create LLM (Status: ${Nf.status})`;throw y$b.error(Eh),new Error(Eh)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to create LLM";throw y$b.error(Nf),Pf}},[ta]),Vd=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance$1.delete(`/integmanager.core/llm/${kf}`);if(Pf.status===200||Pf.status===204)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM deleted successfully");else{const Nf=Pf.data?.reason||Pf.data?.message||`Failed to delete LLM (Status: ${Pf.status})`;throw y$b.error(Nf),new Error(Nf)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to delete LLM";throw y$b.error(Nf),Pf}},[ta]),Wd=reactExports$1.useCallback(async(kf,Pf)=>{try{const Nf=ja(Pf),Eh=await integrationAxiosInstance$1.put(`/integmanager.core/llm/${kf}`,Nf);if(Eh.status===200||Eh.status===201||Eh.status===204)ta.invalidateQueries({queryKey:["llms"]}),y$b.success("LLM updated successfully");else{const Em=Eh.data?.reason||Eh.data?.message||`Failed to update LLM (Status: ${Eh.status})`;throw y$b.error(Em),new Error(Em)}}catch(Nf){const Eh=Nf?.response?.data?.reason||Nf?.response?.data?.message||Nf?.message||"Failed to update LLM";throw y$b.error(Eh),Nf}},[ta]);return{llmData:La,isLoadingLLMs:Fa,isErrorLLMs:wl,llmError:Pl,fetchLLMs:mc,createLLM:gc,deleteLLM:Vd,updateLLM:Wd}},integrationAxiosInstance=axiosInstance("connection-manager"),useIntegration=()=>{const ta=useQueryClient(),Ln=useAppStore(kf=>kf.authReady),Ta=useAppStore(kf=>kf.isAuthenticated),ja=async kf=>{try{const Pf=await integrationAxiosInstance.get(`/api/IntegrationManager.Core/Integration/${kf}/ConnectionConfigGroup/ConnectionConfig`),{result:Nf,status:Eh,message:Em}=Pf.data;if(Eh==="ok")return Nf;Eh==="error"&&y$b.error(Em||`Failed to load configs for ${kf}`)}catch(Pf){console.error(`Error fetching configs for ${kf}:`,Pf),y$b.error(`Error fetching configs for ${kf}`)}},{data:La,isLoading:Fa,isError:wl,error:Pl,refetch:pc}=useQuery({queryKey:["integrations"],queryFn:async()=>{const kf=await integrationAxiosInstance.get("/integmanager.core/integration"),{data:Pf,status:Nf}=kf;if(Nf!==200)throw new Error("Failed to fetch integrations");return Pf.map(Em=>({...Em.integration,userData:JSON.parse(Em.integration.userData)}))},enabled:Ln&&Ta&&!0});wl&&Pl&&y$b.error(Pl?.response?.data?.reason||Pl.message);const mc=reactExports$1.useCallback(async()=>{await pc()},[pc]),gc=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance.post("/integmanager.core/integration",kf);(Pf.status===200||Pf.status===201)&&(ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration created successfully"))}catch(Pf){y$b.error(Pf?.response?.data?.reason||"Failed to create integration")}},[ta]),Vd=reactExports$1.useCallback(async kf=>{try{const Pf=await integrationAxiosInstance.delete(`/integmanager.core/integration/${kf}`);if(console.log(Pf.data),Pf.status===200||Pf.status===204)ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration deleted successfully");else{const Nf=Pf.data?.reason||Pf.data?.message||`Failed to delete integration (Status: ${Pf.status})`;throw y$b.error(Nf),new Error(Nf)}}catch(Pf){const Nf=Pf?.response?.data?.reason||Pf?.response?.data?.message||Pf?.message||"Failed to delete integration";throw y$b.error(Nf),Pf}},[ta]),Wd=reactExports$1.useCallback(async(kf,Pf)=>{try{const Nf=await integrationAxiosInstance.put(`/integmanager.core/integration/${kf}`,Pf);if(console.log(Nf.data),Nf.status===200)ta.invalidateQueries({queryKey:["integrations"]}),y$b.success("Integration updated successfully");else{const Eh=Nf.data?.reason||Nf.data?.message||`Failed to update integration (Status: ${Nf.status})`;throw y$b.error(Eh),new Error(Eh)}}catch(Nf){const Eh=Nf?.response?.data?.reason||Nf?.response?.data?.message||Nf?.message||"Failed to update integration";throw y$b.error(Eh),Nf}},[ta]);return{integrationData:La,isLoadingIntegrations:Fa,isErrorIntegrations:wl,integrationsError:Pl,fetchIntegrations:mc,fetchIntegrationConnectionConfigs:ja,createIntegration:gc,deleteIntegration:Vd,updateIntegration:Wd}},IS_PLAYGROUND$7=!1,IS_LOCAL_MODE$1=!0,useDeployments=()=>{const ta=useQueryClient(),Ln=useAppStore(Vd=>Vd.authReady),Ta=useAppStore(Vd=>Vd.isAuthenticated),{data:ja,isLoading:La,isError:Fa,error:wl,refetch:Pl}=useQuery({queryKey:["deployments"],queryFn:async()=>(console.log("[SERVE_MODE] Skipping deployments fetch - returning empty object"),{}),enabled:Ln&&Ta&&!IS_PLAYGROUND$7&&!IS_LOCAL_MODE$1});Fa&&wl&&y$b.error(wl?.response?.data?.reason||wl.message);const pc=reactExports$1.useCallback(async()=>{{console.log("[SERVE_MODE] Skipping deployments fetch");return}},[Pl]),mc=reactExports$1.useCallback(async Vd=>{try{if(IS_PLAYGROUND$7||IS_LOCAL_MODE$1)return console.log(`[${IS_PLAYGROUND$7?"PLAYGROUND":"SERVE_MODE"}] Skipping app deployment`),y$b.success(`App deployed successfully! (${IS_PLAYGROUND$7?"playground":"serve"} mode)`),{success:!0};const Wd=await axiosInstance("deployment").post("/Deployment/DeployApp",Vd);return y$b.success("App deployed successfully!"),ta.invalidateQueries({queryKey:["deployments"]}),Wd.data}catch(Wd){throw y$b.error(Wd?.response?.data?.reason||"Failed to deploy app"),Wd}},[ta]),gc=reactExports$1.useCallback(async Vd=>{try{if(IS_PLAYGROUND$7||IS_LOCAL_MODE$1)return console.log(`[${IS_PLAYGROUND$7?"PLAYGROUND":"SERVE_MODE"}] Skipping app undeployment`),y$b.success(`App undeployed successfully! (${IS_PLAYGROUND$7?"playground":"serve"} mode)`),{success:!0};const Wd=await axiosInstance("deployment").post("/Deployment/UndeployApp",Vd);return y$b.success("App undeployed successfully!"),ta.invalidateQueries({queryKey:["deployments"]}),Wd.data}catch(Wd){throw y$b.error(Wd?.response?.data?.reason||"Failed to undeploy app"),Wd}},[ta]);return{deploymentsData:ja,isLoadingDeployments:La,isErrorDeployments:Fa,deploymentsError:wl,fetchDeployments:pc,deployApp:mc,undeployApp:gc}};let globalInitializationState={isInitializing:!1,isInitialized:!1,error:null,retryCount:0,progress:{userLoaded:!1,workspaceLoaded:!1,dataLoaded:!1}};const listeners=new Set,updateGlobalState=ta=>{globalInitializationState={...globalInitializationState,...ta},listeners.forEach(Ln=>Ln(globalInitializationState))},useAppInitialization=()=>{const[ta,Ln]=reactExports$1.useState(globalInitializationState),Ta=reactExports$1.useRef(!1),{setUser:ja,user:La,lastDataFetch:Fa,setLastDataFetch:wl}=useAppStore(),Pl=axiosInstance("meta"),{fetchWorkspaceApps:pc}=useTeams(),{fetchIntegrations:mc}=useIntegration(),{fetchDeployments:gc}=useDeployments(),{fetchLLMs:Vd}=useLLM();reactExports$1.useEffect(()=>{const U_=B_=>{Ln(B_)};return listeners.add(U_),()=>{listeners.delete(U_)}},[]);const Wd=reactExports$1.useCallback(U_=>{const B_={...globalInitializationState,progress:{...globalInitializationState.progress,...U_}};updateGlobalState(B_)},[]),kf=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("agentlang-studio-store");if(!U_)return!1;try{const B_=JSON.parse(U_),VC=B_.state&&B_.state.user&&B_.state.user.Email,tj=B_.state&&B_.state.workspace&&B_.state.workspace.Id,aB=B_.state&&B_.state.lastDataFetch&&B_.state.lastDataFetch>0;return VC&&tj&&aB}catch(B_){return console.warn("Failed to parse cached store:",B_),!1}},[]),Pf=reactExports$1.useCallback(()=>{if(Fa===0)return!0;const U_=Date.now()-600*1e3;if(Fa>U_)return!1;const B_=Date.now()-300*1e3;return Fa<B_},[Fa]),Nf=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("agentlang-studio-store");if(!U_)return!1;try{const B_=JSON.parse(U_);if(B_.state&&B_.state.user&&B_.state.user.Email)return Wd({userLoaded:!0}),!0}catch(B_){console.warn("Failed to parse cached store:",B_)}return!1},[Wd]),Eh=reactExports$1.useCallback(()=>{if(typeof window>"u")return!1;const U_=localStorage.getItem("workspace_id"),B_=localStorage.getItem("username");return U_&&B_?(Wd({workspaceLoaded:!0}),!0):!1},[Wd]),Em=reactExports$1.useCallback(async(U_,B_,VC=!1)=>{{console.log("[DEV MODE] Skipping app data initialization - no API calls needed"),Wd({dataLoaded:!0});return}},[pc,mc,gc,Vd,Wd,wl]),qg=reactExports$1.useCallback(async(U_=0)=>{if(!Ta.current){console.log("[DEV MODE] Skipping app initialization - no API calls needed"),wl(Date.now()),updateGlobalState({isInitializing:!1,isInitialized:!0,retryCount:0,progress:{userLoaded:!0,workspaceLoaded:!0,dataLoaded:!0}}),y$b.success("App initialized in dev mode");return}},[Pl,ja,La,Em,Wd,kf,Nf,Eh,Pf,wl]),Ug=reactExports$1.useCallback(()=>{updateGlobalState({retryCount:0}),Ta.current=!1,qg()},[qg]),Bg=reactExports$1.useCallback(()=>{updateGlobalState({isInitializing:!1,isInitialized:!1,error:null,retryCount:0,progress:{userLoaded:!1,workspaceLoaded:!1,dataLoaded:!1}}),Ta.current=!1},[]);return reactExports$1.useEffect(()=>()=>{Ta.current=!1},[]),{...ta,initializeApp:qg,retryInitialization:Ug,resetInitialization:Bg}};var t$9=typeof window<"u"?window:void 0,i$a=typeof globalThis<"u"?globalThis:t$9,e$a=Array.prototype,r$d=e$a.forEach,s$f=e$a.indexOf,n$9=i$a?.navigator,o$d=i$a?.document,a$i=i$a?.location,l$9=i$a?.fetch,u$h=i$a!=null&&i$a.XMLHttpRequest&&"withCredentials"in new i$a.XMLHttpRequest?i$a.XMLHttpRequest:void 0,h$c=i$a?.AbortController,d$6=n$9?.userAgent,v$7=t$9??{},c$e={DEBUG:!1,LIB_VERSION:"1.298.0"};function f$g(ta,Ln,Ta,ja,La,Fa,wl){try{var Pl=ta[Fa](wl),pc=Pl.value}catch(mc){return void Ta(mc)}Pl.done?Ln(pc):Promise.resolve(pc).then(ja,La)}function p$d(ta){return function(){var Ln=this,Ta=arguments;return new Promise((function(ja,La){var Fa=ta.apply(Ln,Ta);function wl(pc){f$g(Fa,ja,La,wl,Pl,"next",pc)}function Pl(pc){f$g(Fa,ja,La,wl,Pl,"throw",pc)}wl(void 0)}))}}function g$8(){return g$8=Object.assign?Object.assign.bind():function(ta){for(var Ln=1;Ln<arguments.length;Ln++){var Ta=arguments[Ln];for(var ja in Ta)({}).hasOwnProperty.call(Ta,ja)&&(ta[ja]=Ta[ja])}return ta},g$8.apply(null,arguments)}function _$8(ta,Ln){if(ta==null)return{};var Ta={};for(var ja in ta)if({}.hasOwnProperty.call(ta,ja)){if(Ln.indexOf(ja)!==-1)continue;Ta[ja]=ta[ja]}return Ta}var m$8=["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"],y$a=function(ta,Ln){if(Ln===void 0&&(Ln=[]),!ta)return!1;var Ta=ta.toLowerCase();return m$8.concat(Ln).some((ja=>{var La=ja.toLowerCase();return Ta.indexOf(La)!==-1}))},b$9=["$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$a(ta,Ln){return ta.indexOf(Ln)!==-1}var x$7=function(ta){return ta.trim()},E$8=function(ta){return ta.replace(/^\$/,"")},S$b=Array.isArray,k$b=Object.prototype,P$a=k$b.hasOwnProperty,T$b=k$b.toString,I$9=S$b||function(ta){return T$b.call(ta)==="[object Array]"},R$3=ta=>typeof ta=="function",F$8=ta=>ta===Object(ta)&&!I$9(ta),C$c=ta=>{if(F$8(ta)){for(var Ln in ta)if(P$a.call(ta,Ln))return!1;return!0}return!1},O$6=ta=>ta===void 0,M$7=ta=>T$b.call(ta)=="[object String]",A$8=ta=>M$7(ta)&&ta.trim().length===0,D$b=ta=>ta===null,j$b=ta=>O$6(ta)||D$b(ta),L$6=ta=>T$b.call(ta)=="[object Number]",N$6=ta=>T$b.call(ta)==="[object Boolean]",U$4=ta=>ta instanceof FormData,z$6=ta=>w$a(b$9,ta);function H$9(ta){return ta===null||typeof ta!="object"}function B$6(ta,Ln){return Object.prototype.toString.call(ta)==="[object "+Ln+"]"}function q$6(ta){return!O$6(Event)&&(function(Ln,Ta){try{return Ln instanceof Ta}catch{return!1}})(ta,Event)}var W$4=[!0,"true",1,"1","yes"],G$5=ta=>w$a(W$4,ta),V$7=[!1,"false",0,"0","no"];function J$5(ta,Ln,Ta,ja,La){return Ln>Ta&&(ja.warn("min cannot be greater than max."),Ln=Ta),L$6(ta)?ta>Ta?(ja.warn(" cannot be greater than max: "+Ta+". Using max value instead."),Ta):ta<Ln?(ja.warn(" cannot be less than min: "+Ln+". Using min value instead."),Ln):ta:(ja.warn(" must be a number. using max or fallback. max: "+Ta+", fallback: "+La),J$5(La||Ta,Ln,Ta,ja))}let K$6=class{constructor(Ln){this.t={},this.i=Ln.i,this.o=J$5(Ln.bucketSize,0,100,Ln.h),this.m=J$5(Ln.refillRate,0,this.o,Ln.h),this.$=J$5(Ln.refillInterval,0,864e5,Ln.h)}S(Ln,Ta){var ja=Ta-Ln.lastAccess,La=Math.floor(ja/this.$);if(La>0){var Fa=La*this.m;Ln.tokens=Math.min(Ln.tokens+Fa,this.o),Ln.lastAccess=Ln.lastAccess+La*this.$}}consumeRateLimit(Ln){var Ta,ja=Date.now(),La=String(Ln),Fa=this.t[La];return Fa?this.S(Fa,ja):(Fa={tokens:this.o,lastAccess:ja},this.t[La]=Fa),Fa.tokens===0||(Fa.tokens--,Fa.tokens===0&&((Ta=this.i)==null||Ta.call(this,Ln)),Fa.tokens===0)}stop(){this.t={}}};var Y$3,X$4,Q$5,Z$4=ta=>ta instanceof Error;function tt$1(ta){var Ln=globalThis._posthogChunkIds;if(Ln){var Ta=Object.keys(Ln);return Q$5&&Ta.length===X$4||(X$4=Ta.length,Q$5=Ta.reduce(((ja,La)=>{Y$3||(Y$3={});var Fa=Y$3[La];if(Fa)ja[Fa[0]]=Fa[1];else for(var wl=ta(La),Pl=wl.length-1;Pl>=0;Pl--){var pc=wl[Pl],mc=pc?.filename,gc=Ln[La];if(mc&&gc){ja[mc]=gc,Y$3[La]=[mc,gc];break}}return ja}),{})),Q$5}}let it$1=class{constructor(Ln,Ta,ja){ja===void 0&&(ja=[]),this.coercers=Ln,this.stackParser=Ta,this.modifiers=ja}buildFromUnknown(Ln,Ta){Ta===void 0&&(Ta={});var ja=Ta&&Ta.mechanism||{handled:!0,type:"generic"},La=this.buildCoercingContext(ja,Ta,0).apply(Ln),Fa=this.buildParsingContext(),wl=this.parseStacktrace(La,Fa);return{$exception_list:this.convertToExceptionList(wl,ja),$exception_level:"error"}}modifyFrames(Ln){var Ta=this;return p$d((function*(){for(var ja of Ln)ja.stacktrace&&ja.stacktrace.frames&&I$9(ja.stacktrace.frames)&&(ja.stacktrace.frames=yield Ta.applyModifiers(ja.stacktrace.frames));return Ln}))()}coerceFallback(Ln){var Ta;return{type:"Error",value:"Unknown error",stack:(Ta=Ln.syntheticException)==null?void 0:Ta.stack,synthetic:!0}}parseStacktrace(Ln,Ta){var ja,La;return Ln.cause!=null&&(ja=this.parseStacktrace(Ln.cause,Ta)),Ln.stack!=""&&Ln.stack!=null&&(La=this.applyChunkIds(this.stackParser(Ln.stack,Ln.synthetic?1:0),Ta.chunkIdMap)),g$8({},Ln,{cause:ja,stack:La})}applyChunkIds(Ln,Ta){return Ln.map((ja=>(ja.filename&&Ta&&(ja.chunk_id=Ta[ja.filename]),ja)))}applyCoercers(Ln,Ta){for(var ja of this.coercers)if(ja.match(Ln))return ja.coerce(Ln,Ta);return this.coerceFallback(Ta)}applyModifiers(Ln){var Ta=this;return p$d((function*(){var ja=Ln;for(var La of Ta.modifiers)ja=yield La(ja);return ja}))()}convertToExceptionList(Ln,Ta){var ja,La,Fa,wl={type:Ln.type,value:Ln.value,mechanism:{type:(ja=Ta.type)!==null&&ja!==void 0?ja:"generic",handled:(La=Ta.handled)===null||La===void 0||La,synthetic:(Fa=Ln.synthetic)!==null&&Fa!==void 0&&Fa}};Ln.stack&&(wl.stacktrace={type:"raw",frames:Ln.stack});var Pl=[wl];return Ln.cause!=null&&Pl.push(...this.convertToExceptionList(Ln.cause,g$8({},Ta,{handled:!0}))),Pl}buildParsingContext(){return{chunkIdMap:tt$1(this.stackParser)}}buildCoercingContext(Ln,Ta,ja){ja===void 0&&(ja=0);var La=(Fa,wl)=>{if(wl<=4){var Pl=this.buildCoercingContext(Ln,Ta,wl);return this.applyCoercers(Fa,Pl)}};return g$8({},Ta,{syntheticException:ja==0?Ta.syntheticException:void 0,mechanism:Ln,apply:Fa=>La(Fa,ja),next:Fa=>La(Fa,ja+1)})}};var et$1="?";function rt$1(ta,Ln,Ta,ja,La){var Fa={platform:ta,filename:Ln,function:Ta==="<anonymous>"?et$1:Ta,in_app:!0};return O$6(ja)||(Fa.lineno=ja),O$6(La)||(Fa.colno=La),Fa}var st$1=(ta,Ln)=>{var Ta=ta.indexOf("safari-extension")!==-1,ja=ta.indexOf("safari-web-extension")!==-1;return Ta||ja?[ta.indexOf("@")!==-1?ta.split("@")[0]:et$1,Ta?"safari-extension:"+Ln:"safari-web-extension:"+Ln]:[ta,Ln]},nt$1=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,ot$1=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,at$1=/\((\S*)(?::(\d+))(?::(\d+))\)/,lt$1=(ta,Ln)=>{var Ta=nt$1.exec(ta);if(Ta){var[,ja,La,Fa]=Ta;return rt$1(Ln,ja,et$1,+La,+Fa)}var wl=ot$1.exec(ta);if(wl){if(wl[2]&&wl[2].indexOf("eval")===0){var Pl=at$1.exec(wl[2]);Pl&&(wl[2]=Pl[1],wl[3]=Pl[2],wl[4]=Pl[3])}var[pc,mc]=st$1(wl[1]||et$1,wl[2]);return rt$1(Ln,mc,pc,wl[3]?+wl[3]:void 0,wl[4]?+wl[4]:void 0)}},ut$1=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,ht$1=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,dt$2=(ta,Ln)=>{var Ta=ut$1.exec(ta);if(Ta){if(Ta[3]&&Ta[3].indexOf(" > eval")>-1){var ja=ht$1.exec(Ta[3]);ja&&(Ta[1]=Ta[1]||"eval",Ta[3]=ja[1],Ta[4]=ja[2],Ta[5]="")}var La=Ta[3],Fa=Ta[1]||et$1;return[Fa,La]=st$1(Fa,La),rt$1(Ln,La,Fa,Ta[4]?+Ta[4]:void 0,Ta[5]?+Ta[5]:void 0)}},vt$1=/\(error: (.*)\)/,ct$1=50;function ft$1(ta){for(var Ln=arguments.length,Ta=new Array(Ln>1?Ln-1:0),ja=1;ja<Ln;ja++)Ta[ja-1]=arguments[ja];return function(La,Fa){Fa===void 0&&(Fa=0);for(var wl=[],Pl=La.split(`
|
|
34777
34777
|
`),pc=Fa;pc<Pl.length;pc++){var mc=Pl[pc];if(!(mc.length>1024)){var gc=vt$1.test(mc)?mc.replace(vt$1,"$1"):mc;if(!gc.match(/\S*Error: /)){for(var Vd of Ta){var Wd=Vd(gc,ta);if(Wd){wl.push(Wd);break}}if(wl.length>=ct$1)break}}}return(function(kf){if(!kf.length)return[];var Pf=Array.from(kf);return Pf.reverse(),Pf.slice(0,ct$1).map((Nf=>{return g$8({},Nf,{filename:Nf.filename||(Eh=Pf,Eh[Eh.length-1]||{}).filename,function:Nf.function||et$1});var Eh}))})(wl)}}let pt$1=class{match(Ln){return this.isDOMException(Ln)||this.isDOMError(Ln)}coerce(Ln,Ta){var ja=M$7(Ln.stack);return{type:this.getType(Ln),value:this.getValue(Ln),stack:ja?Ln.stack:void 0,cause:Ln.cause?Ta.next(Ln.cause):void 0,synthetic:!1}}getType(Ln){return this.isDOMError(Ln)?"DOMError":"DOMException"}getValue(Ln){var Ta=Ln.name||(this.isDOMError(Ln)?"DOMError":"DOMException");return Ln.message?Ta+": "+Ln.message:Ta}isDOMException(Ln){return B$6(Ln,"DOMException")}isDOMError(Ln){return B$6(Ln,"DOMError")}},gt$2=class{match(Ln){return(Ta=>Ta instanceof Error)(Ln)}coerce(Ln,Ta){return{type:this.getType(Ln),value:this.getMessage(Ln,Ta),stack:this.getStack(Ln),cause:Ln.cause?Ta.next(Ln.cause):void 0,synthetic:!1}}getType(Ln){return Ln.name||Ln.constructor.name}getMessage(Ln,Ta){var ja=Ln.message;return ja.error&&typeof ja.error.message=="string"?String(ja.error.message):String(ja)}getStack(Ln){return Ln.stacktrace||Ln.stack||void 0}},_t$1=class{constructor(){}match(Ln){return B$6(Ln,"ErrorEvent")&&Ln.error!=null}coerce(Ln,Ta){var ja,La=Ta.apply(Ln.error);return La||{type:"ErrorEvent",value:Ln.message,stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,synthetic:!0}}};var mt$1=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;let yt$1=class{match(Ln){return typeof Ln=="string"}coerce(Ln,Ta){var ja,[La,Fa]=this.getInfos(Ln);return{type:La??"Error",value:Fa??Ln,stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,synthetic:!0}}getInfos(Ln){var Ta="Error",ja=Ln,La=Ln.match(mt$1);return La&&(Ta=La[1],ja=La[2]),[Ta,ja]}};var bt=["fatal","error","warning","log","info","debug"];function wt$1(ta,Ln){Ln===void 0&&(Ln=40);var Ta=Object.keys(ta);if(Ta.sort(),!Ta.length)return"[object has no keys]";for(var ja=Ta.length;ja>0;ja--){var La=Ta.slice(0,ja).join(", ");if(!(La.length>Ln))return ja===Ta.length||La.length<=Ln?La:La.slice(0,Ln)+"..."}return""}class xt{match(Ln){return typeof Ln=="object"&&Ln!==null}coerce(Ln,Ta){var ja,La=this.getErrorPropertyFromObject(Ln);return La?Ta.apply(La):{type:this.getType(Ln),value:this.getValue(Ln),stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,level:this.isSeverityLevel(Ln.level)?Ln.level:"error",synthetic:!0}}getType(Ln){return q$6(Ln)?Ln.constructor.name:"Error"}getValue(Ln){if("name"in Ln&&typeof Ln.name=="string"){var Ta="'"+Ln.name+"' captured as exception";return"message"in Ln&&typeof Ln.message=="string"&&(Ta+=" with message: '"+Ln.message+"'"),Ta}if("message"in Ln&&typeof Ln.message=="string")return Ln.message;var ja=this.getObjectClassName(Ln);return(ja&&ja!=="Object"?"'"+ja+"'":"Object")+" captured as exception with keys: "+wt$1(Ln)}isSeverityLevel(Ln){return M$7(Ln)&&!A$8(Ln)&&bt.indexOf(Ln)>=0}getErrorPropertyFromObject(Ln){for(var Ta in Ln)if(Object.prototype.hasOwnProperty.call(Ln,Ta)){var ja=Ln[Ta];if(Z$4(ja))return ja}}getObjectClassName(Ln){try{var Ta=Object.getPrototypeOf(Ln);return Ta?Ta.constructor.name:void 0}catch{return}}}class $t{match(Ln){return q$6(Ln)}coerce(Ln,Ta){var ja,La=Ln.constructor.name;return{type:La,value:La+" captured as exception with keys: "+wt$1(Ln),stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,synthetic:!0}}}let Et$2=class{match(Ln){return H$9(Ln)}coerce(Ln,Ta){var ja;return{type:"Error",value:"Primitive value captured as exception: "+String(Ln),stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,synthetic:!0}}},St$1=class{match(Ln){return B$6(Ln,"PromiseRejectionEvent")}coerce(Ln,Ta){var ja,La=this.getUnhandledRejectionReason(Ln);return H$9(La)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(La),stack:(ja=Ta.syntheticException)==null?void 0:ja.stack,synthetic:!0}:Ta.apply(La)}getUnhandledRejectionReason(Ln){if(H$9(Ln))return Ln;try{if("reason"in Ln)return Ln.reason;if("detail"in Ln&&"reason"in Ln.detail)return Ln.detail.reason}catch{}return Ln}};var kt$1=function(ta,Ln){var{debugEnabled:Ta}=Ln===void 0?{}:Ln,ja={k:function(La){if(t$9&&(c$e.DEBUG||v$7.POSTHOG_DEBUG||Ta)&&!O$6(t$9.console)&&t$9.console){for(var Fa=("__rrweb_original__"in t$9.console[La])?t$9.console[La].__rrweb_original__:t$9.console[La],wl=arguments.length,Pl=new Array(wl>1?wl-1:0),pc=1;pc<wl;pc++)Pl[pc-1]=arguments[pc];Fa(ta,...Pl)}},info:function(){for(var La=arguments.length,Fa=new Array(La),wl=0;wl<La;wl++)Fa[wl]=arguments[wl];ja.k("log",...Fa)},warn:function(){for(var La=arguments.length,Fa=new Array(La),wl=0;wl<La;wl++)Fa[wl]=arguments[wl];ja.k("warn",...Fa)},error:function(){for(var La=arguments.length,Fa=new Array(La),wl=0;wl<La;wl++)Fa[wl]=arguments[wl];ja.k("error",...Fa)},critical:function(){for(var La=arguments.length,Fa=new Array(La),wl=0;wl<La;wl++)Fa[wl]=arguments[wl];console.error(ta,...Fa)},uninitializedWarning:La=>{ja.error("You must initialize PostHog before calling "+La)},createLogger:(La,Fa)=>kt$1(ta+" "+La,Fa)};return ja},Pt$2=kt$1("[PostHog.js]"),Tt$1=Pt$2.createLogger,It$1=Tt$1("[ExternalScriptsLoader]"),Rt$1=(ta,Ln,Ta)=>{if(ta.config.disable_external_dependency_loading)return It$1.warn(Ln+" was requested but loading of external scripts is disabled."),Ta("Loading of external scripts is disabled");var ja=o$d?.querySelectorAll("script");if(ja){for(var La,Fa=function(){if(ja[wl].src===Ln){var pc=ja[wl];return pc.__posthog_loading_callback_fired?{v:Ta()}:(pc.addEventListener("load",(mc=>{pc.__posthog_loading_callback_fired=!0,Ta(void 0,mc)})),pc.onerror=mc=>Ta(mc),{v:void 0})}},wl=0;wl<ja.length;wl++)if(La=Fa())return La.v}var Pl=()=>{if(!o$d)return Ta("document not found");var pc=o$d.createElement("script");if(pc.type="text/javascript",pc.crossOrigin="anonymous",pc.src=Ln,pc.onload=Vd=>{pc.__posthog_loading_callback_fired=!0,Ta(void 0,Vd)},pc.onerror=Vd=>Ta(Vd),ta.config.prepare_external_dependency_script&&(pc=ta.config.prepare_external_dependency_script(pc)),!pc)return Ta("prepare_external_dependency_script returned null");var mc,gc=o$d.querySelectorAll("body > script");gc.length>0?(mc=gc[0].parentNode)==null||mc.insertBefore(pc,gc[0]):o$d.body.appendChild(pc)};o$d!=null&&o$d.body?Pl():o$d?.addEventListener("DOMContentLoaded",Pl)};v$7.__PosthogExtensions__=v$7.__PosthogExtensions__||{},v$7.__PosthogExtensions__.loadExternalDependency=(ta,Ln,Ta)=>{var ja="/static/"+Ln+".js?v="+ta.version;if(Ln==="remote-config"&&(ja="/array/"+ta.config.token+"/config.js"),Ln==="toolbar"){var La=3e5;ja=ja+"&t="+Math.floor(Date.now()/La)*La}var Fa=ta.requestRouter.endpointFor("assets",ja);Rt$1(ta,Fa,Ta)},v$7.__PosthogExtensions__.loadSiteApp=(ta,Ln,Ta)=>{var ja=ta.requestRouter.endpointFor("api",Ln);Rt$1(ta,ja,Ta)};var Ft$2={};function Ct$1(ta,Ln,Ta){if(I$9(ta)){if(r$d&&ta.forEach===r$d)ta.forEach(Ln,Ta);else if("length"in ta&&ta.length===+ta.length){for(var ja=0,La=ta.length;ja<La;ja++)if(ja in ta&&Ln.call(Ta,ta[ja],ja)===Ft$2)return}}}function Ot(ta,Ln,Ta){if(!j$b(ta)){if(I$9(ta))return Ct$1(ta,Ln,Ta);if(U$4(ta)){for(var ja of ta.entries())if(Ln.call(Ta,ja[1],ja[0])===Ft$2)return}else for(var La in ta)if(P$a.call(ta,La)&&Ln.call(Ta,ta[La],La)===Ft$2)return}}var Mt$2=function(ta){for(var Ln=arguments.length,Ta=new Array(Ln>1?Ln-1:0),ja=1;ja<Ln;ja++)Ta[ja-1]=arguments[ja];return Ct$1(Ta,(function(La){for(var Fa in La)La[Fa]!==void 0&&(ta[Fa]=La[Fa])})),ta},At$1=function(ta){for(var Ln=arguments.length,Ta=new Array(Ln>1?Ln-1:0),ja=1;ja<Ln;ja++)Ta[ja-1]=arguments[ja];return Ct$1(Ta,(function(La){Ct$1(La,(function(Fa){ta.push(Fa)}))})),ta};function Dt$1(ta){for(var Ln=Object.keys(ta),Ta=Ln.length,ja=new Array(Ta);Ta--;)ja[Ta]=[Ln[Ta],ta[Ln[Ta]]];return ja}var jt=function(ta){try{return ta()}catch{return}},Lt=function(ta){return function(){try{for(var Ln=arguments.length,Ta=new Array(Ln),ja=0;ja<Ln;ja++)Ta[ja]=arguments[ja];return ta.apply(this,Ta)}catch(La){Pt$2.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),Pt$2.critical(La)}}},Nt=function(ta){var Ln={};return Ot(ta,(function(Ta,ja){(M$7(Ta)&&Ta.length>0||L$6(Ta))&&(Ln[ja]=Ta)})),Ln};function Ut(ta,Ln){return Ta=ta,ja=Fa=>M$7(Fa)&&!D$b(Ln)?Fa.slice(0,Ln):Fa,La=new Set,(function Fa(wl,Pl){return wl!==Object(wl)?ja?ja(wl,Pl):wl:La.has(wl)?void 0:(La.add(wl),I$9(wl)?(pc=[],Ct$1(wl,(mc=>{pc.push(Fa(mc))}))):(pc={},Ot(wl,((mc,gc)=>{La.has(mc)||(pc[gc]=Fa(mc,gc))}))),pc);var pc})(Ta);var Ta,ja,La}var zt=["herokuapp.com","vercel.app","netlify.app"];function Ht(ta){var Ln=ta?.hostname;if(!M$7(Ln))return!1;var Ta=Ln.split(".").slice(-2).join(".");for(var ja of zt)if(Ta===ja)return!1;return!0}function Bt$1(ta,Ln){for(var Ta=0;Ta<ta.length;Ta++)if(Ln(ta[Ta]))return ta[Ta]}function qt(ta,Ln,Ta,ja){var{capture:La=!1,passive:Fa=!0}=ja??{};ta?.addEventListener(Ln,Ta,{capture:La,passive:Fa})}var Wt="$people_distinct_id",Gt="__alias",Vt="__timers",Jt="$autocapture_disabled_server_side",Kt="$heatmaps_enabled_server_side",Yt="$exception_capture_enabled_server_side",Xt="$error_tracking_suppression_rules",Qt="$error_tracking_capture_extension_exceptions",Zt="$web_vitals_enabled_server_side",ti="$dead_clicks_enabled_server_side",ii="$web_vitals_allowed_metrics",ei="$session_recording_remote_config",ri="$sesid",si="$session_is_sampled",ni="$enabled_feature_flags",oi="$early_access_features",ai="$feature_flag_details",li="$stored_person_properties",ui="$stored_group_properties",hi="$surveys",di="$surveys_activated",vi="$flag_call_reported",ci="$user_state",fi="$client_session_props",pi="$capture_rate_limit",gi="$initial_campaign_params",_i="$initial_referrer_info",mi="$initial_person_info",yi="$epp",bi="__POSTHOG_TOOLBAR__",wi="$posthog_cookieless",xi=[Wt,Gt,"__cmpns",Vt,"$session_recording_enabled_server_side",Kt,ri,ni,Xt,ci,oi,ai,ui,li,hi,vi,fi,pi,gi,_i,yi,mi];function $i(ta){return ta instanceof Element&&(ta.id===bi||!(ta.closest==null||!ta.closest(".toolbar-global-fade-container")))}function Ei(ta){return!!ta&&ta.nodeType===1}function Si(ta,Ln){return!!ta&&!!ta.tagName&&ta.tagName.toLowerCase()===Ln.toLowerCase()}function ki(ta){return!!ta&&ta.nodeType===3}function Pi(ta){return!!ta&&ta.nodeType===11}function Ti(ta){return ta?x$7(ta).split(/\s+/):[]}function Ii(ta){var Ln=t$9?.location.href;return!!(Ln&&ta&&ta.some((Ta=>Ln.match(Ta))))}function Ri(ta){var Ln="";switch(typeof ta.className){case"string":Ln=ta.className;break;case"object":Ln=(ta.className&&"baseVal"in ta.className?ta.className.baseVal:null)||ta.getAttribute("class")||"";break;default:Ln=""}return Ti(Ln)}function Fi(ta){return j$b(ta)?null:x$7(ta).split(/(\s+)/).filter((Ln=>Qi(Ln))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function Ci(ta){var Ln="";return qi(ta)&&!Wi(ta)&&ta.childNodes&&ta.childNodes.length&&Ot(ta.childNodes,(function(Ta){var ja;ki(Ta)&&Ta.textContent&&(Ln+=(ja=Fi(Ta.textContent))!==null&&ja!==void 0?ja:"")})),x$7(Ln)}function Oi(ta){return O$6(ta.target)?ta.srcElement||null:(Ln=ta.target)!=null&&Ln.shadowRoot?ta.composedPath()[0]||null:ta.target||null;var Ln}var Mi=["a","button","form","input","select","textarea","label"];function Ai(ta,Ln){if(O$6(Ln))return!0;var Ta,ja=function(Fa){if(Ln.some((wl=>Fa.matches(wl))))return{v:!0}};for(var La of ta)if(Ta=ja(La))return Ta.v;return!1}function Di(ta){var Ln=ta.parentNode;return!(!Ln||!Ei(Ln))&&Ln}var ji=["next","previous","prev",">","<"],Li=10,Ni=[".ph-no-rageclick",".ph-no-capture"];function Ui(ta,Ln){if(!t$9||zi(ta))return!1;var Ta,ja,La;if(N$6(Ln)?(Ta=!!Ln&&Ni,ja=void 0):(Ta=(La=Ln?.css_selector_ignorelist)!==null&&La!==void 0?La:Ni,ja=Ln?.content_ignorelist),Ta===!1)return!1;var{targetElementList:Fa}=Hi(ta,!1);return!(function(wl,Pl){if(wl===!1||O$6(wl))return!1;var pc;if(wl===!0)pc=ji;else{if(!I$9(wl))return!1;if(wl.length>Li)return Pt$2.error("[PostHog] content_ignorelist array cannot exceed "+Li+" items. Use css_selector_ignorelist for more complex matching."),!1;pc=wl.map((mc=>mc.toLowerCase()))}return Pl.some((mc=>{var{safeText:gc,ariaLabel:Vd}=mc;return pc.some((Wd=>gc.includes(Wd)||Vd.includes(Wd)))}))})(ja,Fa.map((wl=>{var Pl;return{safeText:Ci(wl).toLowerCase(),ariaLabel:((Pl=wl.getAttribute("aria-label"))==null?void 0:Pl.toLowerCase().trim())||""}})))&&!Ai(Fa,Ta)}var zi=ta=>!ta||Si(ta,"html")||!Ei(ta),Hi=(ta,Ln)=>{if(!t$9||zi(ta))return{parentIsUsefulElement:!1,targetElementList:[]};for(var Ta=!1,ja=[ta],La=ta;La.parentNode&&!Si(La,"body");)if(Pi(La.parentNode))ja.push(La.parentNode.host),La=La.parentNode.host;else{var Fa=Di(La);if(!Fa)break;if(Ln||Mi.indexOf(Fa.tagName.toLowerCase())>-1)Ta=!0;else{var wl=t$9.getComputedStyle(Fa);wl&&wl.getPropertyValue("cursor")==="pointer"&&(Ta=!0)}ja.push(Fa),La=Fa}return{parentIsUsefulElement:Ta,targetElementList:ja}};function Bi(ta,Ln,Ta,ja,La){var Fa,wl,Pl,pc;if(Ta===void 0&&(Ta=void 0),!t$9||zi(ta)||(Fa=Ta)!=null&&Fa.url_allowlist&&!Ii(Ta.url_allowlist)||(wl=Ta)!=null&&wl.url_ignorelist&&Ii(Ta.url_ignorelist))return!1;if((Pl=Ta)!=null&&Pl.dom_event_allowlist){var mc=Ta.dom_event_allowlist;if(mc&&!mc.some((Pf=>Ln.type===Pf)))return!1}var{parentIsUsefulElement:gc,targetElementList:Vd}=Hi(ta,ja);if(!(function(Pf,Nf){var Eh=Nf?.element_allowlist;if(O$6(Eh))return!0;var Em,qg=function(Bg){if(Eh.some((U_=>Bg.tagName.toLowerCase()===U_)))return{v:!0}};for(var Ug of Pf)if(Em=qg(Ug))return Em.v;return!1})(Vd,Ta)||!Ai(Vd,(pc=Ta)==null?void 0:pc.css_selector_allowlist))return!1;var Wd=t$9.getComputedStyle(ta);if(Wd&&Wd.getPropertyValue("cursor")==="pointer"&&Ln.type==="click")return!0;var kf=ta.tagName.toLowerCase();switch(kf){case"html":return!1;case"form":return(La||["submit"]).indexOf(Ln.type)>=0;case"input":case"select":case"textarea":return(La||["change","click"]).indexOf(Ln.type)>=0;default:return gc?(La||["click"]).indexOf(Ln.type)>=0:(La||["click"]).indexOf(Ln.type)>=0&&(Mi.indexOf(kf)>-1||ta.getAttribute("contenteditable")==="true")}}function qi(ta){for(var Ln=ta;Ln.parentNode&&!Si(Ln,"body");Ln=Ln.parentNode){var Ta=Ri(Ln);if(w$a(Ta,"ph-sensitive")||w$a(Ta,"ph-no-capture"))return!1}if(w$a(Ri(ta),"ph-include"))return!0;var ja=ta.type||"";if(M$7(ja))switch(ja.toLowerCase()){case"hidden":case"password":return!1}var La=ta.name||ta.id||"";return!(M$7(La)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(La.replace(/[^a-zA-Z0-9]/g,"")))}function Wi(ta){return!!(Si(ta,"input")&&!["button","checkbox","submit","reset"].includes(ta.type)||Si(ta,"select")||Si(ta,"textarea")||ta.getAttribute("contenteditable")==="true")}var Gi="(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})",Vi=new RegExp("^(?:"+Gi+")$"),Ji=new RegExp(Gi),Ki="\\d{3}-?\\d{2}-?\\d{4}",Yi=new RegExp("^("+Ki+")$"),Xi=new RegExp("("+Ki+")");function Qi(ta,Ln){return Ln===void 0&&(Ln=!0),!(j$b(ta)||M$7(ta)&&(ta=x$7(ta),(Ln?Vi:Ji).test((ta||"").replace(/[- ]/g,""))||(Ln?Yi:Xi).test(ta)))}function Zi(ta){var Ln=Ci(ta);return Qi(Ln=(Ln+" "+te$4(ta)).trim())?Ln:""}function te$4(ta){var Ln="";return ta&&ta.childNodes&&ta.childNodes.length&&Ot(ta.childNodes,(function(Ta){var ja;if(Ta&&((ja=Ta.tagName)==null?void 0:ja.toLowerCase())==="span")try{var La=Ci(Ta);Ln=(Ln+" "+La).trim(),Ta.childNodes&&Ta.childNodes.length&&(Ln=(Ln+" "+te$4(Ta)).trim())}catch(Fa){Pt$2.error("[AutoCapture]",Fa)}})),Ln}function ie$3(ta){return(function(Ln){var Ta=Ln.map((ja=>{var La,Fa,wl="";if(ja.tag_name&&(wl+=ja.tag_name),ja.attr_class)for(var Pl of(ja.attr_class.sort(),ja.attr_class))wl+="."+Pl.replace(/"/g,"");var pc=g$8({},ja.text?{text:ja.text}:{},{"nth-child":(La=ja.nth_child)!==null&&La!==void 0?La:0,"nth-of-type":(Fa=ja.nth_of_type)!==null&&Fa!==void 0?Fa:0},ja.href?{href:ja.href}:{},ja.attr_id?{attr_id:ja.attr_id}:{},ja.attributes),mc={};return Dt$1(pc).sort(((gc,Vd)=>{var[Wd]=gc,[kf]=Vd;return Wd.localeCompare(kf)})).forEach((gc=>{var[Vd,Wd]=gc;return mc[ee$4(Vd.toString())]=ee$4(Wd.toString())})),wl+=":",wl+=Dt$1(mc).map((gc=>{var[Vd,Wd]=gc;return Vd+'="'+Wd+'"'})).join("")}));return Ta.join(";")})((function(Ln){return Ln.map((Ta=>{var ja,La,Fa={text:(ja=Ta.$el_text)==null?void 0:ja.slice(0,400),tag_name:Ta.tag_name,href:(La=Ta.attr__href)==null?void 0:La.slice(0,2048),attr_class:re$1(Ta),attr_id:Ta.attr__id,nth_child:Ta.nth_child,nth_of_type:Ta.nth_of_type,attributes:{}};return Dt$1(Ta).filter((wl=>{var[Pl]=wl;return Pl.indexOf("attr__")===0})).forEach((wl=>{var[Pl,pc]=wl;return Fa.attributes[Pl]=pc})),Fa}))})(ta))}function ee$4(ta){return ta.replace(/"|\\"/g,'\\"')}function re$1(ta){var Ln=ta.attr__class;return Ln?I$9(Ln)?Ln:Ti(Ln):void 0}let se$3=class{constructor(Ln){this.disabled=Ln===!1;var Ta=F$8(Ln)?Ln:{};this.thresholdPx=Ta.threshold_px||30,this.timeoutMs=Ta.timeout_ms||1e3,this.clickCount=Ta.click_count||3,this.clicks=[]}isRageClick(Ln,Ta,ja){if(this.disabled)return!1;var La=this.clicks[this.clicks.length-1];if(La&&Math.abs(Ln-La.x)+Math.abs(Ta-La.y)<this.thresholdPx&&ja-La.timestamp<this.timeoutMs){if(this.clicks.push({x:Ln,y:Ta,timestamp:ja}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:Ln,y:Ta,timestamp:ja}];return!1}};var ne$2="$copy_autocapture",oe$2=(function(ta){return ta.GZipJS="gzip-js",ta.Base64="base64",ta})({}),le$2=ta=>{var Ln=o$d?.createElement("a");return O$6(Ln)?null:(Ln.href=ta,Ln)},ue$1=function(ta,Ln){var Ta,ja;Ln===void 0&&(Ln="&");var La=[];return Ot(ta,(function(Fa,wl){O$6(Fa)||O$6(wl)||wl==="undefined"||(Ta=encodeURIComponent((Pl=>Pl instanceof File)(Fa)?Fa.name:Fa.toString()),ja=encodeURIComponent(wl),La[La.length]=ja+"="+Ta)})),La.join(Ln)},he$3=function(ta,Ln){for(var Ta,ja=((ta.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),La=0;La<ja.length;La++){var Fa=ja[La].split("=");if(Fa[0]===Ln){Ta=Fa;break}}if(!I$9(Ta)||Ta.length<2)return"";var wl=Ta[1];try{wl=decodeURIComponent(wl)}catch{Pt$2.error("Skipping decoding for malformed query param: "+wl)}return wl.replace(/\+/g," ")},de$3=function(ta,Ln,Ta){if(!ta||!Ln||!Ln.length)return ta;for(var ja=ta.split("#"),La=ja[0]||"",Fa=ja[1],wl=La.split("?"),Pl=wl[1],pc=wl[0],mc=(Pl||"").split("&"),gc=[],Vd=0;Vd<mc.length;Vd++){var Wd=mc[Vd].split("=");I$9(Wd)&&(Ln.includes(Wd[0])?gc.push(Wd[0]+"="+Ta):gc.push(mc[Vd]))}var kf=pc;return Pl!=null&&(kf+="?"+gc.join("&")),Fa!=null&&(kf+="#"+Fa),kf},ve$2=function(ta,Ln){var Ta=ta.match(new RegExp(Ln+"=([^&]*)"));return Ta?Ta[1]:null},ce$3=Tt$1("[AutoCapture]");function fe$2(ta,Ln){return Ln.length>ta?Ln.slice(0,ta)+"...":Ln}function pe$2(ta){if(ta.previousElementSibling)return ta.previousElementSibling;var Ln=ta;do Ln=Ln.previousSibling;while(Ln&&!Ei(Ln));return Ln}function ge$3(ta,Ln,Ta,ja){var La=ta.tagName.toLowerCase(),Fa={tag_name:La};Mi.indexOf(La)>-1&&!Ta&&(La.toLowerCase()==="a"||La.toLowerCase()==="button"?Fa.$el_text=fe$2(1024,Zi(ta)):Fa.$el_text=fe$2(1024,Ci(ta)));var wl=Ri(ta);wl.length>0&&(Fa.classes=wl.filter((function(gc){return gc!==""}))),Ot(ta.attributes,(function(gc){var Vd;if((!Wi(ta)||["name","id","class","aria-label"].indexOf(gc.name)!==-1)&&(ja==null||!ja.includes(gc.name))&&!Ln&&Qi(gc.value)&&(Vd=gc.name,!M$7(Vd)||Vd.substring(0,10)!=="_ngcontent"&&Vd.substring(0,7)!=="_nghost")){var Wd=gc.value;gc.name==="class"&&(Wd=Ti(Wd).join(" ")),Fa["attr__"+gc.name]=fe$2(1024,Wd)}}));for(var Pl=1,pc=1,mc=ta;mc=pe$2(mc);)Pl++,mc.tagName===ta.tagName&&pc++;return Fa.nth_child=Pl,Fa.nth_of_type=pc,Fa}function _e$1(ta,Ln){for(var Ta,ja,{e:La,maskAllElementAttributes:Fa,maskAllText:wl,elementAttributeIgnoreList:Pl,elementsChainAsString:pc}=Ln,mc=[ta],gc=ta;gc.parentNode&&!Si(gc,"body");)Pi(gc.parentNode)?(mc.push(gc.parentNode.host),gc=gc.parentNode.host):(mc.push(gc.parentNode),gc=gc.parentNode);var Vd,Wd=[],kf={},Pf=!1,Nf=!1;if(Ot(mc,(Bg=>{var U_=qi(Bg);Bg.tagName.toLowerCase()==="a"&&(Pf=Bg.getAttribute("href"),Pf=U_&&Pf&&Qi(Pf)&&Pf),w$a(Ri(Bg),"ph-no-capture")&&(Nf=!0),Wd.push(ge$3(Bg,Fa,wl,Pl));var B_=(function(VC){if(!qi(VC))return{};var tj={};return Ot(VC.attributes,(function(aB){if(aB.name&&aB.name.indexOf("data-ph-capture-attribute")===0){var r6=aB.name.replace("data-ph-capture-attribute-",""),J2=aB.value;r6&&J2&&Qi(J2)&&(tj[r6]=J2)}})),tj})(Bg);Mt$2(kf,B_)})),Nf)return{props:{},explicitNoCapture:Nf};if(wl||(ta.tagName.toLowerCase()==="a"||ta.tagName.toLowerCase()==="button"?Wd[0].$el_text=Zi(ta):Wd[0].$el_text=Ci(ta)),Pf){var Eh,Em;Wd[0].attr__href=Pf;var qg=(Eh=le$2(Pf))==null?void 0:Eh.host,Ug=t$9==null||(Em=t$9.location)==null?void 0:Em.host;qg&&Ug&&qg!==Ug&&(Vd=Pf)}return{props:Mt$2({$event_type:La.type,$ce_version:1},pc?{}:{$elements:Wd},{$elements_chain:ie$3(Wd)},(Ta=Wd[0])!=null&&Ta.$el_text?{$el_text:(ja=Wd[0])==null?void 0:ja.$el_text}:{},Vd&&La.type==="click"?{$external_click_url:Vd}:{},kf)}}let me$2=class{constructor(Ln){this.P=!1,this.T=null,this.I=!1,this.instance=Ln,this.rageclicks=new se$3(Ln.config.rageclick),this.R=null}get F(){var Ln,Ta,ja=F$8(this.instance.config.autocapture)?this.instance.config.autocapture:{};return ja.url_allowlist=(Ln=ja.url_allowlist)==null?void 0:Ln.map((La=>new RegExp(La))),ja.url_ignorelist=(Ta=ja.url_ignorelist)==null?void 0:Ta.map((La=>new RegExp(La))),ja}C(){if(this.isBrowserSupported()){if(t$9&&o$d){var Ln=ja=>{ja=ja||t$9?.event;try{this.O(ja)}catch(La){ce$3.error("Failed to capture event",La)}};if(qt(o$d,"submit",Ln,{capture:!0}),qt(o$d,"change",Ln,{capture:!0}),qt(o$d,"click",Ln,{capture:!0}),this.F.capture_copied_text){var Ta=ja=>{ja=ja||t$9?.event,this.O(ja,ne$2)};qt(o$d,"copy",Ta,{capture:!0}),qt(o$d,"cut",Ta,{capture:!0})}}}else ce$3.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.C(),this.P=!0)}onRemoteConfig(Ln){Ln.elementsChainAsString&&(this.I=Ln.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[Jt]:!!Ln.autocapture_opt_out}),this.T=!!Ln.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(Ln){this.R=Ln}getElementSelectors(Ln){var Ta,ja=[];return(Ta=this.R)==null||Ta.forEach((La=>{var Fa=o$d?.querySelectorAll(La);Fa?.forEach((wl=>{Ln===wl&&ja.push(La)}))})),ja}get isEnabled(){var Ln,Ta,ja=(Ln=this.instance.persistence)==null?void 0:Ln.props[Jt],La=this.T;if(D$b(La)&&!N$6(ja)&&!this.instance.M())return!1;var Fa=(Ta=this.T)!==null&&Ta!==void 0?Ta:!!ja;return!!this.instance.config.autocapture&&!Fa}O(Ln,Ta){if(Ta===void 0&&(Ta="$autocapture"),this.isEnabled){var ja,La=Oi(Ln);ki(La)&&(La=La.parentNode||null),Ta==="$autocapture"&&Ln.type==="click"&&Ln instanceof MouseEvent&&this.instance.config.rageclick&&(ja=this.rageclicks)!=null&&ja.isRageClick(Ln.clientX,Ln.clientY,Ln.timeStamp||new Date().getTime())&&Ui(La,this.instance.config.rageclick)&&this.O(Ln,"$rageclick");var Fa=Ta===ne$2;if(La&&Bi(La,Ln,this.F,Fa,Fa?["copy","cut"]:void 0)){var{props:wl,explicitNoCapture:Pl}=_e$1(La,{e:Ln,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.F.element_attribute_ignorelist,elementsChainAsString:this.I});if(Pl)return!1;var pc=this.getElementSelectors(La);if(pc&&pc.length>0&&(wl.$element_selectors=pc),Ta===ne$2){var mc,gc=Fi(t$9==null||(mc=t$9.getSelection())==null?void 0:mc.toString()),Vd=Ln.type||"clipboard";if(!gc)return!1;wl.$selected_content=gc,wl.$copy_type=Vd}return this.instance.capture(Ta,wl),!0}}}isBrowserSupported(){return R$3(o$d?.querySelectorAll)}};Math.trunc||(Math.trunc=function(ta){return ta<0?Math.ceil(ta):Math.floor(ta)}),Number.isInteger||(Number.isInteger=function(ta){return L$6(ta)&&isFinite(ta)&&Math.floor(ta)===ta});var ye$3="0123456789abcdef";let be$4=class mLe{constructor(Ln){if(this.bytes=Ln,Ln.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(Ln,Ta,ja,La){if(!Number.isInteger(Ln)||!Number.isInteger(Ta)||!Number.isInteger(ja)||!Number.isInteger(La)||Ln<0||Ta<0||ja<0||La<0||Ln>0xffffffffffff||Ta>4095||ja>1073741823||La>4294967295)throw new RangeError("invalid field value");var Fa=new Uint8Array(16);return Fa[0]=Ln/Math.pow(2,40),Fa[1]=Ln/Math.pow(2,32),Fa[2]=Ln/Math.pow(2,24),Fa[3]=Ln/Math.pow(2,16),Fa[4]=Ln/Math.pow(2,8),Fa[5]=Ln,Fa[6]=112|Ta>>>8,Fa[7]=Ta,Fa[8]=128|ja>>>24,Fa[9]=ja>>>16,Fa[10]=ja>>>8,Fa[11]=ja,Fa[12]=La>>>24,Fa[13]=La>>>16,Fa[14]=La>>>8,Fa[15]=La,new mLe(Fa)}toString(){for(var Ln="",Ta=0;Ta<this.bytes.length;Ta++)Ln=Ln+ye$3.charAt(this.bytes[Ta]>>>4)+ye$3.charAt(15&this.bytes[Ta]),Ta!==3&&Ta!==5&&Ta!==7&&Ta!==9||(Ln+="-");if(Ln.length!==36)throw new Error("Invalid UUIDv7 was generated");return Ln}clone(){return new mLe(this.bytes.slice(0))}equals(Ln){return this.compareTo(Ln)===0}compareTo(Ln){for(var Ta=0;Ta<16;Ta++){var ja=this.bytes[Ta]-Ln.bytes[Ta];if(ja!==0)return Math.sign(ja)}return 0}},we$3=class{constructor(){this.A=0,this.D=0,this.j=new Ee$2}generate(){var Ln=this.generateOrAbort();if(O$6(Ln)){this.A=0;var Ta=this.generateOrAbort();if(O$6(Ta))throw new Error("Could not generate UUID after timestamp reset");return Ta}return Ln}generateOrAbort(){var Ln=Date.now();if(Ln>this.A)this.A=Ln,this.L();else{if(!(Ln+1e4>this.A))return;this.D++,this.D>4398046511103&&(this.A++,this.L())}return be$4.fromFieldsV7(this.A,Math.trunc(this.D/Math.pow(2,30)),this.D&Math.pow(2,30)-1,this.j.nextUint32())}L(){this.D=1024*this.j.nextUint32()+(1023&this.j.nextUint32())}};var xe$1,$e=ta=>{if(typeof UUIDV7_DENY_WEAK_RNG<"u"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var Ln=0;Ln<ta.length;Ln++)ta[Ln]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return ta};t$9&&!O$6(t$9.crypto)&&crypto.getRandomValues&&($e=ta=>crypto.getRandomValues(ta));let Ee$2=class{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&($e(this.N),this.U=0),this.N[this.U++]}};var Se$2=()=>ke$3().toString(),ke$3=()=>(xe$1||(xe$1=new we$3)).generate(),Pe="",Te$2=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function Ie$1(ta,Ln){if(Ln){var Ta=(function(La,Fa){if(Fa===void 0&&(Fa=o$d),Pe)return Pe;if(!Fa||["localhost","127.0.0.1"].includes(La))return"";for(var wl=La.split("."),Pl=Math.min(wl.length,8),pc="dmn_chk_"+Se$2();!Pe&&Pl--;){var mc=wl.slice(Pl).join("."),gc=pc+"=1;domain=."+mc+";path=/";Fa.cookie=gc+";max-age=3",Fa.cookie.includes(pc)&&(Fa.cookie=gc+";max-age=0",Pe=mc)}return Pe})(ta);if(!Ta){var ja=(La=>{var Fa=La.match(Te$2);return Fa?Fa[0]:""})(ta);ja!==Ta&&Pt$2.info("Warning: cookie subdomain discovery mismatch",ja,Ta),Ta=ja}return Ta?"; domain=."+Ta:""}return""}var Re$1={H:()=>!!o$d,B:function(ta){Pt$2.error("cookieStore error: "+ta)},q:function(ta){if(o$d){try{for(var Ln=ta+"=",Ta=o$d.cookie.split(";").filter((Fa=>Fa.length)),ja=0;ja<Ta.length;ja++){for(var La=Ta[ja];La.charAt(0)==" ";)La=La.substring(1,La.length);if(La.indexOf(Ln)===0)return decodeURIComponent(La.substring(Ln.length,La.length))}}catch{}return null}},W:function(ta){var Ln;try{Ln=JSON.parse(Re$1.q(ta))||{}}catch{}return Ln},G:function(ta,Ln,Ta,ja,La){if(o$d)try{var Fa="",wl="",Pl=Ie$1(o$d.location.hostname,ja);if(Ta){var pc=new Date;pc.setTime(pc.getTime()+24*Ta*60*60*1e3),Fa="; expires="+pc.toUTCString()}La&&(wl="; secure");var mc=ta+"="+encodeURIComponent(JSON.stringify(Ln))+Fa+"; SameSite=Lax; path=/"+Pl+wl;return mc.length>3686.4&&Pt$2.warn("cookieStore warning: large cookie, len="+mc.length),o$d.cookie=mc,mc}catch{return}},V:function(ta,Ln){if(o$d!=null&&o$d.cookie)try{Re$1.G(ta,"",-1,Ln)}catch{return}}},Fe$2=null,Ce$3={H:function(){if(!D$b(Fe$2))return Fe$2;var ta=!0;if(O$6(t$9))ta=!1;else try{var Ln="__mplssupport__";Ce$3.G(Ln,"xyz"),Ce$3.q(Ln)!=='"xyz"'&&(ta=!1),Ce$3.V(Ln)}catch{ta=!1}return ta||Pt$2.error("localStorage unsupported; falling back to cookie store"),Fe$2=ta,ta},B:function(ta){Pt$2.error("localStorage error: "+ta)},q:function(ta){try{return t$9?.localStorage.getItem(ta)}catch(Ln){Ce$3.B(Ln)}return null},W:function(ta){try{return JSON.parse(Ce$3.q(ta))||{}}catch{}return null},G:function(ta,Ln){try{t$9?.localStorage.setItem(ta,JSON.stringify(Ln))}catch(Ta){Ce$3.B(Ta)}},V:function(ta){try{t$9?.localStorage.removeItem(ta)}catch(Ln){Ce$3.B(Ln)}}},Oe$5=["distinct_id",ri,si,yi,mi],Me$2=g$8({},Ce$3,{W:function(ta){try{var Ln={};try{Ln=Re$1.W(ta)||{}}catch{}var Ta=Mt$2(Ln,JSON.parse(Ce$3.q(ta)||"{}"));return Ce$3.G(ta,Ta),Ta}catch{}return null},G:function(ta,Ln,Ta,ja,La,Fa){try{Ce$3.G(ta,Ln,void 0,void 0,Fa);var wl={};Oe$5.forEach((Pl=>{Ln[Pl]&&(wl[Pl]=Ln[Pl])})),Object.keys(wl).length&&Re$1.G(ta,wl,Ta,ja,La,Fa)}catch(Pl){Ce$3.B(Pl)}},V:function(ta,Ln){try{t$9?.localStorage.removeItem(ta),Re$1.V(ta,Ln)}catch(Ta){Ce$3.B(Ta)}}}),Ae$1={},De$3={H:function(){return!0},B:function(ta){Pt$2.error("memoryStorage error: "+ta)},q:function(ta){return Ae$1[ta]||null},W:function(ta){return Ae$1[ta]||null},G:function(ta,Ln){Ae$1[ta]=Ln},V:function(ta){delete Ae$1[ta]}},je$2=null,Le$1={H:function(){if(!D$b(je$2))return je$2;if(je$2=!0,O$6(t$9))je$2=!1;else try{var ta="__support__";Le$1.G(ta,"xyz"),Le$1.q(ta)!=='"xyz"'&&(je$2=!1),Le$1.V(ta)}catch{je$2=!1}return je$2},B:function(ta){Pt$2.error("sessionStorage error: ",ta)},q:function(ta){try{return t$9?.sessionStorage.getItem(ta)}catch(Ln){Le$1.B(Ln)}return null},W:function(ta){try{return JSON.parse(Le$1.q(ta))||null}catch{}return null},G:function(ta,Ln){try{t$9?.sessionStorage.setItem(ta,JSON.stringify(Ln))}catch(Ta){Le$1.B(Ta)}},V:function(ta){try{t$9?.sessionStorage.removeItem(ta)}catch(Ln){Le$1.B(Ln)}}},Ne$2=(function(ta){return ta[ta.PENDING=-1]="PENDING",ta[ta.DENIED=0]="DENIED",ta[ta.GRANTED=1]="GRANTED",ta})({});let Ue$1=class{constructor(Ln){this._instance=Ln}get F(){return this._instance.config}get consent(){return this.J()?Ne$2.DENIED:this.K}isOptedOut(){return this.F.cookieless_mode==="always"||this.consent===Ne$2.DENIED||this.consent===Ne$2.PENDING&&(this.F.opt_out_capturing_by_default||this.F.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Ne$2.DENIED}optInOut(Ln){this.Y.G(this.X,Ln?1:0,this.F.cookie_expiration,this.F.cross_subdomain_cookie,this.F.secure_cookie)}reset(){this.Y.V(this.X,this.F.cross_subdomain_cookie)}get X(){var{token:Ln,opt_out_capturing_cookie_prefix:Ta,consent_persistence_name:ja}=this._instance.config;return ja||(Ta?Ta+Ln:"__ph_opt_in_out_"+Ln)}get K(){var Ln=this.Y.q(this.X);return G$5(Ln)?Ne$2.GRANTED:w$a(V$7,Ln)?Ne$2.DENIED:Ne$2.PENDING}get Y(){if(!this.Z){var Ln=this.F.opt_out_capturing_persistence_type;this.Z=Ln==="localStorage"?Ce$3:Re$1;var Ta=Ln==="localStorage"?Re$1:Ce$3;Ta.q(this.X)&&(this.Z.q(this.X)||this.optInOut(G$5(Ta.q(this.X))),Ta.V(this.X,this.F.cross_subdomain_cookie))}return this.Z}J(){return!!this.F.respect_dnt&&!!Bt$1([n$9?.doNotTrack,n$9?.msDoNotTrack,v$7.doNotTrack],(Ln=>G$5(Ln)))}};var ze=Tt$1("[Dead Clicks]"),He$2=()=>!0,Be$1=ta=>{var Ln,Ta=!((Ln=ta.instance.persistence)==null||!Ln.get_property(ti)),ja=ta.instance.config.capture_dead_clicks;return N$6(ja)?ja:Ta};class qe{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(Ln,Ta,ja){this.instance=Ln,this.isEnabled=Ta,this.onCapture=ja,this.startIfEnabled()}onRemoteConfig(Ln){this.instance.persistence&&this.instance.persistence.register({[ti]:Ln?.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.initDeadClicksAutocapture&&Ln(),(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this.instance,"dead-clicks-autocapture",(La=>{La?ze.error("failed to load script",La):Ln()}))}et(){var Ln;if(o$d){if(!this.tt&&(Ln=v$7.__PosthogExtensions__)!=null&&Ln.initDeadClicksAutocapture){var Ta=F$8(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};Ta.__onCapture=this.onCapture,this.tt=v$7.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,Ta),this.tt.start(o$d),ze.info("starting...")}}else ze.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,ze.info("stopping..."))}}var We$1=Tt$1("[ExceptionAutocapture]");let Ge$1=class{constructor(Ln){var Ta,ja,La;this.rt=()=>{var Fa;if(t$9&&this.isEnabled&&(Fa=v$7.__PosthogExtensions__)!=null&&Fa.errorWrappingFunctions){var wl=v$7.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,Pl=v$7.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,pc=v$7.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.F.capture_unhandled_errors&&(this.st=wl(this.captureException.bind(this))),!this.nt&&this.F.capture_unhandled_rejections&&(this.nt=Pl(this.captureException.bind(this))),!this.ot&&this.F.capture_console_errors&&(this.ot=pc(this.captureException.bind(this)))}catch(mc){We$1.error("failed to start",mc),this.lt()}}},this._instance=Ln,this.ut=!((Ta=this._instance.persistence)==null||!Ta.props[Yt]),this.F=this.ht(),this.dt=new K$6({refillRate:(ja=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&ja!==void 0?ja:1,bucketSize:(La=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&La!==void 0?La:10,refillInterval:1e4,h:We$1}),this.startIfEnabled()}ht(){var Ln=this._instance.config.capture_exceptions,Ta={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return F$8(Ln)?Ta=g$8({},Ta,Ln):(O$6(Ln)?this.ut:Ln)&&(Ta=g$8({},Ta,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),Ta}get isEnabled(){return this.F.capture_console_errors||this.F.capture_unhandled_errors||this.F.capture_unhandled_rejections}startIfEnabled(){this.isEnabled&&(We$1.info("enabled"),this.it(this.rt))}it(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.errorWrappingFunctions&&Ln(),(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,"exception-autocapture",(La=>{if(La)return We$1.error("failed to load script",La);Ln()}))}lt(){var Ln,Ta,ja;(Ln=this.st)==null||Ln.call(this),this.st=void 0,(Ta=this.nt)==null||Ta.call(this),this.nt=void 0,(ja=this.ot)==null||ja.call(this),this.ot=void 0}onRemoteConfig(Ln){var Ta=Ln.autocaptureExceptions;this.ut=!!Ta||!1,this.F=this.ht(),this._instance.persistence&&this._instance.persistence.register({[Yt]:this.ut}),this.startIfEnabled()}captureException(Ln){var Ta,ja,La=(Ta=Ln==null||(ja=Ln.$exception_list)==null||(ja=ja[0])==null?void 0:ja.type)!==null&&Ta!==void 0?Ta:"Exception";this.dt.consumeRateLimit(La)?We$1.info("Skipping exception capture because of client rate limiting.",{exception:La}):this._instance.exceptions.sendExceptionEvent(Ln)}};function Ve$1(ta,Ln,Ta){try{if(!(Ln in ta))return()=>{};var ja=ta[Ln],La=Ta(ja);return R$3(La)&&(La.prototype=La.prototype||{},Object.defineProperties(La,{__posthog_wrapped__:{enumerable:!1,value:!0}})),ta[Ln]=La,()=>{ta[Ln]=ja}}catch{return()=>{}}}class Je{constructor(Ln){var Ta;this._instance=Ln,this.vt=(t$9==null||(Ta=t$9.location)==null?void 0:Ta.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(Pt$2.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ct&&this.ct(),this.ct=void 0,Pt$2.info("History API monitoring stopped")}monitorHistoryChanges(){var Ln,Ta;if(t$9&&t$9.history){var ja=this;(Ln=t$9.history.pushState)!=null&&Ln.__posthog_wrapped__||Ve$1(t$9.history,"pushState",(La=>function(Fa,wl,Pl){La.call(this,Fa,wl,Pl),ja.ft("pushState")})),(Ta=t$9.history.replaceState)!=null&&Ta.__posthog_wrapped__||Ve$1(t$9.history,"replaceState",(La=>function(Fa,wl,Pl){La.call(this,Fa,wl,Pl),ja.ft("replaceState")})),this.gt()}}ft(Ln){try{var Ta,ja=t$9==null||(Ta=t$9.location)==null?void 0:Ta.pathname;if(!ja)return;ja!==this.vt&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:Ln}),this.vt=ja}catch(La){Pt$2.error("Error capturing "+Ln+" pageview",La)}}gt(){if(!this.ct){var Ln=()=>{this.ft("popstate")};qt(t$9,"popstate",Ln),this.ct=()=>{t$9&&t$9.removeEventListener("popstate",Ln)}}}}var Ke$1=Tt$1("[SegmentIntegration]");function Ye(ta,Ln){var Ta=ta.config.segment;if(!Ta)return Ln();(function(ja,La){var Fa=ja.config.segment;if(!Fa)return La();var wl=pc=>{var mc=()=>pc.anonymousId()||Se$2();ja.config.get_device_id=mc,pc.id()&&(ja.register({distinct_id:pc.id(),$device_id:mc()}),ja.persistence.set_property(ci,"identified")),La()},Pl=Fa.user();"then"in Pl&&R$3(Pl.then)?Pl.then((pc=>wl(pc))):wl(Pl)})(ta,(()=>{Ta.register((ja=>{Promise&&Promise.resolve||Ke$1.warn("This browser does not have Promise support, and can not use the segment integration");var La=(Fa,wl)=>{if(!wl)return Fa;Fa.event.userId||Fa.event.anonymousId===ja.get_distinct_id()||(Ke$1.info("No userId set, resetting PostHog"),ja.reset()),Fa.event.userId&&Fa.event.userId!==ja.get_distinct_id()&&(Ke$1.info("UserId set, identifying with PostHog"),ja.identify(Fa.event.userId));var Pl=ja.calculateEventProperties(wl,Fa.event.properties);return Fa.event.properties=Object.assign({},Pl,Fa.event.properties),Fa};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:Fa=>La(Fa,Fa.event.event),page:Fa=>La(Fa,"$pageview"),identify:Fa=>La(Fa,"$identify"),screen:Fa=>La(Fa,"$screen")}})(ta)).then((()=>{Ln()}))}))}var Xe="posthog-js";function Qe(ta,Ln){var{organization:Ta,projectId:ja,prefix:La,severityAllowList:Fa=["error"],sendExceptionsToPostHog:wl=!0}=Ln===void 0?{}:Ln;return Pl=>{var pc,mc,gc,Vd,Wd;if(!(Fa==="*"||Fa.includes(Pl.level))||!ta.__loaded)return Pl;Pl.tags||(Pl.tags={});var kf=ta.requestRouter.endpointFor("ui","/project/"+ta.config.token+"/person/"+ta.get_distinct_id());Pl.tags["PostHog Person URL"]=kf,ta.sessionRecordingStarted()&&(Pl.tags["PostHog Recording URL"]=ta.get_session_replay_url({withTimestamp:!0}));var Pf=((pc=Pl.exception)==null?void 0:pc.values)||[],Nf=Pf.map((Em=>g$8({},Em,{stacktrace:Em.stacktrace?g$8({},Em.stacktrace,{type:"raw",frames:(Em.stacktrace.frames||[]).map((qg=>g$8({},qg,{platform:"web:javascript"})))}):void 0}))),Eh={$exception_message:((mc=Pf[0])==null?void 0:mc.value)||Pl.message,$exception_type:(gc=Pf[0])==null?void 0:gc.type,$exception_level:Pl.level,$exception_list:Nf,$sentry_event_id:Pl.event_id,$sentry_exception:Pl.exception,$sentry_exception_message:((Vd=Pf[0])==null?void 0:Vd.value)||Pl.message,$sentry_exception_type:(Wd=Pf[0])==null?void 0:Wd.type,$sentry_tags:Pl.tags};return Ta&&ja&&(Eh.$sentry_url=(La||"https://sentry.io/organizations/")+Ta+"/issues/?project="+ja+"&query="+Pl.event_id),wl&&ta.exceptions.sendExceptionEvent(Eh),Pl}}let Ze$1=class{constructor(Ln,Ta,ja,La,Fa,wl){this.name=Xe,this.setupOnce=function(Pl){Pl(Qe(Ln,{organization:Ta,projectId:ja,prefix:La,severityAllowList:Fa,sendExceptionsToPostHog:wl==null||wl}))}}};var tr=t$9!=null&&t$9.location?ve$2(t$9.location.hash,"__posthog")||ve$2(location.hash,"state"):null,ir="_postHogToolbarParams",er=Tt$1("[Toolbar]"),rr=(function(ta){return ta[ta.UNINITIALIZED=0]="UNINITIALIZED",ta[ta.LOADING=1]="LOADING",ta[ta.LOADED=2]="LOADED",ta})(rr||{});class sr{constructor(Ln){this.instance=Ln}_t(Ln){v$7.ph_toolbar_state=Ln}yt(){var Ln;return(Ln=v$7.ph_toolbar_state)!==null&&Ln!==void 0?Ln:rr.UNINITIALIZED}maybeLoadToolbar(Ln,Ta,ja){if(Ln===void 0&&(Ln=void 0),Ta===void 0&&(Ta=void 0),ja===void 0&&(ja=void 0),!t$9||!o$d)return!1;Ln=Ln??t$9.location,ja=ja??t$9.history;try{if(!Ta){try{t$9.localStorage.setItem("test","test"),t$9.localStorage.removeItem("test")}catch{return!1}Ta=t$9?.localStorage}var La,Fa=tr||ve$2(Ln.hash,"__posthog")||ve$2(Ln.hash,"state"),wl=Fa?jt((()=>JSON.parse(atob(decodeURIComponent(Fa)))))||jt((()=>JSON.parse(decodeURIComponent(Fa)))):null;return wl&&wl.action==="ph_authorize"?((La=wl).source="url",La&&Object.keys(La).length>0&&(wl.desiredHash?Ln.hash=wl.desiredHash:ja?ja.replaceState(ja.state,"",Ln.pathname+Ln.search):Ln.hash="")):((La=JSON.parse(Ta.getItem(ir)||"{}")).source="localstorage",delete La.userIntent),!(!La.token||this.instance.config.token!==La.token)&&(this.loadToolbar(La),!0)}catch{return!1}}bt(Ln){var Ta=v$7.ph_load_toolbar||v$7.ph_load_editor;!j$b(Ta)&&R$3(Ta)?Ta(Ln,this.instance):er.warn("No toolbar load function found")}loadToolbar(Ln){var Ta=!(o$d==null||!o$d.getElementById(bi));if(!t$9||Ta)return!1;var ja=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,La=g$8({token:this.instance.config.token},Ln,{apiURL:this.instance.requestRouter.endpointFor("ui")},ja?{instrument:!1}:{});if(t$9.localStorage.setItem(ir,JSON.stringify(g$8({},La,{source:void 0}))),this.yt()===rr.LOADED)this.bt(La);else if(this.yt()===rr.UNINITIALIZED){var Fa;this._t(rr.LOADING),(Fa=v$7.__PosthogExtensions__)==null||Fa.loadExternalDependency==null||Fa.loadExternalDependency(this.instance,"toolbar",(wl=>{if(wl)return er.error("[Toolbar] Failed to load",wl),void this._t(rr.UNINITIALIZED);this._t(rr.LOADED),this.bt(La)})),qt(t$9,"turbolinks:load",(()=>{this._t(rr.UNINITIALIZED),this.loadToolbar(La)}))}return!0}wt(Ln){return this.loadToolbar(Ln)}maybeLoadEditor(Ln,Ta,ja){return Ln===void 0&&(Ln=void 0),Ta===void 0&&(Ta=void 0),ja===void 0&&(ja=void 0),this.maybeLoadToolbar(Ln,Ta,ja)}}var nr=Tt$1("[TracingHeaders]");class or{constructor(Ln){this.xt=void 0,this.$t=void 0,this.rt=()=>{var Ta,ja;O$6(this.xt)&&((Ta=v$7.__PosthogExtensions__)==null||(Ta=Ta.tracingHeadersPatchFns)==null||Ta._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),O$6(this.$t)&&((ja=v$7.__PosthogExtensions__)==null||(ja=ja.tracingHeadersPatchFns)==null||ja._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=Ln}it(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.tracingHeadersPatchFns&&Ln(),(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,"tracing-headers",(La=>{if(La)return nr.error("failed to load script",La);Ln()}))}startIfEnabledOrStop(){var Ln,Ta;this._instance.config.__add_tracing_headers?this.it(this.rt):((Ln=this.xt)==null||Ln.call(this),(Ta=this.$t)==null||Ta.call(this),this.xt=void 0,this.$t=void 0)}}var ar="Mobile",lr="iOS",ur="Android",hr="Tablet",dr=ur+" "+hr,vr="iPad",cr="Apple",fr=cr+" Watch",pr="Safari",gr="BlackBerry",_r="Samsung",mr=_r+"Browser",yr=_r+" Internet",br="Chrome",wr=br+" OS",xr=br+" "+lr,$r="Internet Explorer",Er=$r+" "+ar,Sr="Opera",kr=Sr+" Mini",Pr="Edge",Tr="Microsoft "+Pr,Ir="Firefox",Rr=Ir+" "+lr,Fr="Nintendo",Cr="PlayStation",Or="Xbox",Mr=ur+" "+ar,Ar=ar+" "+pr,Dr="Windows",jr=Dr+" Phone",Lr="Nokia",Nr="Ouya",Ur="Generic",zr=Ur+" "+ar.toLowerCase(),Hr=Ur+" "+hr.toLowerCase(),Br="Konqueror",qr="(\\d+(\\.\\d+)?)",Wr=new RegExp("Version/"+qr),Gr=new RegExp(Or,"i"),Vr=new RegExp(Cr+" \\w+","i"),Jr=new RegExp(Fr+" \\w+","i"),Kr=new RegExp(gr+"|PlayBook|BB10","i"),Yr={"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"},Xr=(ta,Ln)=>Ln&&w$a(Ln,cr)||(function(Ta){return w$a(Ta,pr)&&!w$a(Ta,br)&&!w$a(Ta,ur)})(ta),Qr=function(ta,Ln){return Ln=Ln||"",w$a(ta," OPR/")&&w$a(ta,"Mini")?kr:w$a(ta," OPR/")?Sr:Kr.test(ta)?gr:w$a(ta,"IE"+ar)||w$a(ta,"WPDesktop")?Er:w$a(ta,mr)?yr:w$a(ta,Pr)||w$a(ta,"Edg/")?Tr:w$a(ta,"FBIOS")?"Facebook "+ar:w$a(ta,"UCWEB")||w$a(ta,"UCBrowser")?"UC Browser":w$a(ta,"CriOS")?xr:w$a(ta,"CrMo")||w$a(ta,br)?br:w$a(ta,ur)&&w$a(ta,pr)?Mr:w$a(ta,"FxiOS")?Rr:w$a(ta.toLowerCase(),Br.toLowerCase())?Br:Xr(ta,Ln)?w$a(ta,ar)?Ar:pr:w$a(ta,Ir)?Ir:w$a(ta,"MSIE")||w$a(ta,"Trident/")?$r:w$a(ta,"Gecko")?Ir:""},Zr={[Er]:[new RegExp("rv:"+qr)],[Tr]:[new RegExp(Pr+"?\\/"+qr)],[br]:[new RegExp("("+br+"|CrMo)\\/"+qr)],[xr]:[new RegExp("CriOS\\/"+qr)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+qr)],[pr]:[Wr],[Ar]:[Wr],[Sr]:[new RegExp("(Opera|OPR)\\/"+qr)],[Ir]:[new RegExp(Ir+"\\/"+qr)],[Rr]:[new RegExp("FxiOS\\/"+qr)],[Br]:[new RegExp("Konqueror[:/]?"+qr,"i")],[gr]:[new RegExp(gr+" "+qr),Wr],[Mr]:[new RegExp("android\\s"+qr,"i")],[yr]:[new RegExp(mr+"\\/"+qr)],[$r]:[new RegExp("(rv:|MSIE )"+qr)],Mozilla:[new RegExp("rv:"+qr)]},ts=function(ta,Ln){var Ta=Qr(ta,Ln),ja=Zr[Ta];if(O$6(ja))return null;for(var La=0;La<ja.length;La++){var Fa=ja[La],wl=ta.match(Fa);if(wl)return parseFloat(wl[wl.length-2])}return null},is=[[new RegExp(Or+"; "+Or+" (.*?)[);]","i"),ta=>[Or,ta&&ta[1]||""]],[new RegExp(Fr,"i"),[Fr,""]],[new RegExp(Cr,"i"),[Cr,""]],[Kr,[gr,""]],[new RegExp(Dr,"i"),(ta,Ln)=>{if(/Phone/.test(Ln)||/WPDesktop/.test(Ln))return[jr,""];if(new RegExp(ar).test(Ln)&&!/IEMobile\b/.test(Ln))return[Dr+" "+ar,""];var Ta=/Windows NT ([0-9.]+)/i.exec(Ln);if(Ta&&Ta[1]){var ja=Ta[1],La=Yr[ja]||"";return/arm/i.test(Ln)&&(La="RT"),[Dr,La]}return[Dr,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,ta=>{if(ta&&ta[3]){var Ln=[ta[3],ta[4],ta[5]||"0"];return[lr,Ln.join(".")]}return[lr,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,ta=>{var Ln="";return ta&&ta.length>=3&&(Ln=O$6(ta[2])?ta[3]:ta[2]),["watchOS",Ln]}],[new RegExp("("+ur+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+ur+")","i"),ta=>{if(ta&&ta[2]){var Ln=[ta[2],ta[3],ta[4]||"0"];return[ur,Ln.join(".")]}return[ur,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,ta=>{var Ln=["Mac OS X",""];if(ta&&ta[1]){var Ta=[ta[1],ta[2],ta[3]||"0"];Ln[1]=Ta.join(".")}return Ln}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[wr,""]],[/Linux|debian/i,["Linux",""]]],es=function(ta){return Jr.test(ta)?Fr:Vr.test(ta)?Cr:Gr.test(ta)?Or:new RegExp(Nr,"i").test(ta)?Nr:new RegExp("("+jr+"|WPDesktop)","i").test(ta)?jr:/iPad/.test(ta)?vr:/iPod/.test(ta)?"iPod Touch":/iPhone/.test(ta)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(ta)?fr:Kr.test(ta)?gr:/(kobo)\s(ereader|touch)/i.test(ta)?"Kobo":new RegExp(Lr,"i").test(ta)?Lr:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(ta)||/(kf[a-z]+)( bui|\)).+silk\//i.test(ta)?"Kindle Fire":/(Android|ZTE)/i.test(ta)?!new RegExp(ar).test(ta)||/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(ta)?/pixel[\daxl ]{1,6}/i.test(ta)&&!/pixel c/i.test(ta)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(ta)||/lmy47v/i.test(ta)&&!/QTAQZ3/i.test(ta)?ur:dr:ur:new RegExp("(pda|"+ar+")","i").test(ta)?zr:new RegExp(hr,"i").test(ta)&&!new RegExp(hr+" pc","i").test(ta)?Hr:""},rs="https?://(.*)",ss=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],ns=At$1(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],ss),os="<masked>",as=["li_fat_id"];function ls(ta,Ln,Ta){if(!o$d)return{};var ja,La=Ln?At$1([],ss,Ta||[]):[],Fa=us(de$3(o$d.URL,La,os),ta),wl=(ja={},Ot(as,(function(Pl){var pc=Re$1.q(Pl);ja[Pl]=pc||null})),ja);return Mt$2(wl,Fa)}function us(ta,Ln){var Ta=ns.concat(Ln||[]),ja={};return Ot(Ta,(function(La){var Fa=he$3(ta,La);ja[La]=Fa||null})),ja}function hs(ta){var Ln=(function(Fa){return Fa?Fa.search(rs+"google.([^/?]*)")===0?"google":Fa.search(rs+"bing.com")===0?"bing":Fa.search(rs+"yahoo.com")===0?"yahoo":Fa.search(rs+"duckduckgo.com")===0?"duckduckgo":null:null})(ta),Ta=Ln!="yahoo"?"q":"p",ja={};if(!D$b(Ln)){ja.$search_engine=Ln;var La=o$d?he$3(o$d.referrer,Ta):"";La.length&&(ja.ph_keyword=La)}return ja}function ds(){return navigator.language||navigator.userLanguage}function vs(){return o$d?.referrer||"$direct"}function cs(ta,Ln){var Ta=ta?At$1([],ss,Ln||[]):[],ja=a$i?.href.substring(0,1e3);return{r:vs().substring(0,1e3),u:ja?de$3(ja,Ta,os):void 0}}function fs(ta){var Ln,{r:Ta,u:ja}=ta,La={$referrer:Ta,$referring_domain:Ta==null?void 0:Ta=="$direct"?"$direct":(Ln=le$2(Ta))==null?void 0:Ln.host};if(ja){La.$current_url=ja;var Fa=le$2(ja);La.$host=Fa?.host,La.$pathname=Fa?.pathname;var wl=us(ja);Mt$2(La,wl)}if(Ta){var Pl=hs(Ta);Mt$2(La,Pl)}return La}function ps(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return}}function gs(){try{return new Date().getTimezoneOffset()}catch{return}}function _s(ta,Ln){if(!d$6)return{};var Ta,ja,La,Fa=ta?At$1([],ss,Ln||[]):[],[wl,Pl]=(function(pc){for(var mc=0;mc<is.length;mc++){var[gc,Vd]=is[mc],Wd=gc.exec(pc),kf=Wd&&(R$3(Vd)?Vd(Wd,pc):Vd);if(kf)return kf}return["",""]})(d$6);return Mt$2(Nt({$os:wl,$os_version:Pl,$browser:Qr(d$6,navigator.vendor),$device:es(d$6),$device_type:(ja=d$6,La=es(ja),La===vr||La===dr||La==="Kobo"||La==="Kindle Fire"||La===Hr?hr:La===Fr||La===Or||La===Cr||La===Nr?"Console":La===fr?"Wearable":La?ar:"Desktop"),$timezone:ps(),$timezone_offset:gs()}),{$current_url:de$3(a$i?.href,Fa,os),$host:a$i?.host,$pathname:a$i?.pathname,$raw_user_agent:d$6.length>1e3?d$6.substring(0,997)+"...":d$6,$browser_version:ts(d$6,navigator.vendor),$browser_language:ds(),$browser_language_prefix:(Ta=ds(),typeof Ta=="string"?Ta.split("-")[0]:void 0),$screen_height:t$9?.screen.height,$screen_width:t$9?.screen.width,$viewport_height:t$9?.innerHeight,$viewport_width:t$9?.innerWidth,$lib:"web",$lib_version:c$e.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var ms=Tt$1("[Web Vitals]"),ys=9e5;class bs{constructor(Ln){var Ta;this.Et=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.St=()=>{clearTimeout(this.kt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((ja,La)=>g$8({},ja,{["$web_vitals_"+La.name+"_event"]:g$8({},La),["$web_vitals_"+La.name+"_value"]:La.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.Pt=ja=>{var La,Fa=(La=this._instance.sessionManager)==null?void 0:La.checkAndGetSessionAndWindowId(!0);if(O$6(Fa))ms.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var wl=this.Tt();O$6(wl)||(j$b(ja?.name)||j$b(ja?.value)?ms.error("Invalid metric received",ja):this.It&&ja.value>=this.It?ms.error("Ignoring metric with value >= "+this.It,ja):(this.N.url!==wl&&(this.St(),this.kt=setTimeout(this.St,this.flushToCaptureTimeoutMs)),O$6(this.N.url)&&(this.N.url=wl),this.N.firstMetricTimestamp=O$6(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,ja.attribution&&ja.attribution.interactionTargetElement&&(ja.attribution.interactionTargetElement=void 0),this.N.metrics.push(g$8({},ja,{$current_url:wl,$session_id:Fa.sessionId,$window_id:Fa.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.St()))}},this.rt=()=>{var ja,La,Fa,wl,Pl=v$7.__PosthogExtensions__;O$6(Pl)||O$6(Pl.postHogWebVitalsCallbacks)||({onLCP:ja,onCLS:La,onFCP:Fa,onINP:wl}=Pl.postHogWebVitalsCallbacks),ja&&La&&Fa&&wl?(this.allowedMetrics.indexOf("LCP")>-1&&ja(this.Pt.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&La(this.Pt.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&Fa(this.Pt.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&wl(this.Pt.bind(this)),this.P=!0):ms.error("web vitals callbacks not loaded - not starting")},this._instance=Ln,this.Et=!((Ta=this._instance.persistence)==null||!Ta.props[Zt]),this.startIfEnabled()}get allowedMetrics(){var Ln,Ta,ja=F$8(this._instance.config.capture_performance)?(Ln=this._instance.config.capture_performance)==null?void 0:Ln.web_vitals_allowed_metrics:void 0;return O$6(ja)?((Ta=this._instance.persistence)==null?void 0:Ta.props[ii])||["CLS","FCP","INP","LCP"]:ja}get flushToCaptureTimeoutMs(){return(F$8(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get It(){var Ln=F$8(this._instance.config.capture_performance)&&L$6(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:ys;return 0<Ln&&Ln<=6e4?ys:Ln}get isEnabled(){var Ln=a$i?.protocol;if(Ln!=="http:"&&Ln!=="https:")return ms.info("Web Vitals are disabled on non-http/https protocols"),!1;var Ta=F$8(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:N$6(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return N$6(Ta)?Ta:this.Et}startIfEnabled(){this.isEnabled&&!this.P&&(ms.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(Ln){var Ta=F$8(Ln.capturePerformance)&&!!Ln.capturePerformance.web_vitals,ja=F$8(Ln.capturePerformance)?Ln.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[Zt]:Ta}),this._instance.persistence.register({[ii]:ja})),this.Et=Ta,this.startIfEnabled()}it(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.postHogWebVitalsCallbacks&&Ln(),(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,"web-vitals",(La=>{La?ms.error("failed to load script",La):Ln()}))}Tt(){var Ln=t$9?t$9.location.href:void 0;if(Ln){var Ta=this._instance.config.mask_personal_data_properties,ja=this._instance.config.custom_personal_data_properties,La=Ta?At$1([],ss,ja||[]):[];return de$3(Ln,La,os)}ms.error("Could not determine current URL")}}var ws=Tt$1("[Heatmaps]");function xs(ta){return F$8(ta)&&"clientX"in ta&&"clientY"in ta&&L$6(ta.clientX)&&L$6(ta.clientY)}class $s{constructor(Ln){var Ta;this.Et=!1,this.P=!1,this.Rt=null,this.instance=Ln,this.Et=!((Ta=this.instance.persistence)==null||!Ta.props[Kt]),this.rageclicks=new se$3(Ln.config.rageclick)}get flushIntervalMilliseconds(){var Ln=5e3;return F$8(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(Ln=this.instance.config.capture_heatmaps.flush_interval_milliseconds),Ln}get isEnabled(){return O$6(this.instance.config.capture_heatmaps)?O$6(this.instance.config.enable_heatmaps)?this.Et:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;ws.info("starting..."),this.Ft(),this.Ct()}else{var Ln;clearInterval((Ln=this.Rt)!==null&&Ln!==void 0?Ln:void 0),this.Ot(),this.getAndClearBuffer()}}onRemoteConfig(Ln){var Ta=!!Ln.heatmaps;this.instance.persistence&&this.instance.persistence.register({[Kt]:Ta}),this.Et=Ta,this.startIfEnabled()}getAndClearBuffer(){var Ln=this.N;return this.N=void 0,Ln}Mt(Ln){this.At(Ln.originalEvent,"deadclick")}Ct(){this.Rt&&clearInterval(this.Rt),this.Rt=(function(Ln){return Ln?.visibilityState==="visible"})(o$d)?setInterval(this.Dt.bind(this),this.flushIntervalMilliseconds):null}Ft(){t$9&&o$d&&(this.jt=this.Dt.bind(this),qt(t$9,"beforeunload",this.jt),this.Lt=Ln=>this.At(Ln||t$9?.event),qt(o$d,"click",this.Lt,{capture:!0}),this.Nt=Ln=>this.Ut(Ln||t$9?.event),qt(o$d,"mousemove",this.Nt,{capture:!0}),this.zt=new qe(this.instance,He$2,this.Mt.bind(this)),this.zt.startIfEnabled(),this.Ht=this.Ct.bind(this),qt(o$d,"visibilitychange",this.Ht),this.P=!0)}Ot(){var Ln;t$9&&o$d&&(this.jt&&t$9.removeEventListener("beforeunload",this.jt),this.Lt&&o$d.removeEventListener("click",this.Lt,{capture:!0}),this.Nt&&o$d.removeEventListener("mousemove",this.Nt,{capture:!0}),this.Ht&&o$d.removeEventListener("visibilitychange",this.Ht),clearTimeout(this.Bt),(Ln=this.zt)==null||Ln.stop(),this.P=!1)}qt(Ln,Ta){var ja=this.instance.scrollManager.scrollY(),La=this.instance.scrollManager.scrollX(),Fa=this.instance.scrollManager.scrollElement(),wl=(function(Pl,pc,mc){for(var gc=Pl;gc&&Ei(gc)&&!Si(gc,"body");){if(gc===mc)return!1;if(w$a(pc,t$9?.getComputedStyle(gc).position))return!0;gc=Di(gc)}return!1})(Oi(Ln),["fixed","sticky"],Fa);return{x:Ln.clientX+(wl?0:La),y:Ln.clientY+(wl?0:ja),target_fixed:wl,type:Ta}}At(Ln,Ta){var ja;if(Ta===void 0&&(Ta="click"),!$i(Ln.target)&&xs(Ln)){var La=this.qt(Ln,Ta);(ja=this.rageclicks)!=null&&ja.isRageClick(Ln.clientX,Ln.clientY,new Date().getTime())&&this.Wt(g$8({},La,{type:"rageclick"})),this.Wt(La)}}Ut(Ln){!$i(Ln.target)&&xs(Ln)&&(clearTimeout(this.Bt),this.Bt=setTimeout((()=>{this.Wt(this.qt(Ln,"mousemove"))}),500))}Wt(Ln){if(t$9){var Ta=t$9.location.href,ja=this.instance.config.mask_personal_data_properties,La=this.instance.config.custom_personal_data_properties,Fa=ja?At$1([],ss,La||[]):[],wl=de$3(Ta,Fa,os);this.N=this.N||{},this.N[wl]||(this.N[wl]=[]),this.N[wl].push(Ln)}}Dt(){this.N&&!C$c(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class Es{constructor(Ln){this._instance=Ln}doPageView(Ln,Ta){var ja,La=this.Gt(Ln,Ta);return this.Vt={pathname:(ja=t$9?.location.pathname)!==null&&ja!==void 0?ja:"",pageViewId:Ta,timestamp:Ln},this._instance.scrollManager.resetContext(),La}doPageLeave(Ln){var Ta;return this.Gt(Ln,(Ta=this.Vt)==null?void 0:Ta.pageViewId)}doEvent(){var Ln;return{$pageview_id:(Ln=this.Vt)==null?void 0:Ln.pageViewId}}Gt(Ln,Ta){var ja=this.Vt;if(!ja)return{$pageview_id:Ta};var La={$pageview_id:Ta,$prev_pageview_id:ja.pageViewId},Fa=this._instance.scrollManager.getContext();if(Fa&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:wl,lastScrollY:Pl,maxScrollY:pc,maxContentHeight:mc,lastContentY:gc,maxContentY:Vd}=Fa;if(!(O$6(wl)||O$6(Pl)||O$6(pc)||O$6(mc)||O$6(gc)||O$6(Vd))){wl=Math.ceil(wl),Pl=Math.ceil(Pl),pc=Math.ceil(pc),mc=Math.ceil(mc),gc=Math.ceil(gc),Vd=Math.ceil(Vd);var Wd=wl<=1?1:J$5(Pl/wl,0,1,Pt$2),kf=wl<=1?1:J$5(pc/wl,0,1,Pt$2),Pf=mc<=1?1:J$5(gc/mc,0,1,Pt$2),Nf=mc<=1?1:J$5(Vd/mc,0,1,Pt$2);La=Mt$2(La,{$prev_pageview_last_scroll:Pl,$prev_pageview_last_scroll_percentage:Wd,$prev_pageview_max_scroll:pc,$prev_pageview_max_scroll_percentage:kf,$prev_pageview_last_content:gc,$prev_pageview_last_content_percentage:Pf,$prev_pageview_max_content:Vd,$prev_pageview_max_content_percentage:Nf})}}return ja.pathname&&(La.$prev_pageview_pathname=ja.pathname),ja.timestamp&&(La.$prev_pageview_duration=(Ln.getTime()-ja.timestamp.getTime())/1e3),La}}var Ss=Uint8Array,ks=Uint16Array,Ps=Uint32Array,Ts=new Ss([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]),Is=new Ss([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]),Rs=new Ss([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Fs=function(ta,Ln){for(var Ta=new ks(31),ja=0;ja<31;++ja)Ta[ja]=Ln+=1<<ta[ja-1];var La=new Ps(Ta[30]);for(ja=1;ja<30;++ja)for(var Fa=Ta[ja];Fa<Ta[ja+1];++Fa)La[Fa]=Fa-Ta[ja]<<5|ja;return[Ta,La]},Cs=Fs(Ts,2),Os=Cs[0],Ms=Cs[1];Os[28]=258,Ms[258]=28;for(var As=Fs(Is,0)[1],Ds=new ks(32768),js=0;js<32768;++js){var Ls=(43690&js)>>>1|(21845&js)<<1;Ls=(61680&(Ls=(52428&Ls)>>>2|(13107&Ls)<<2))>>>4|(3855&Ls)<<4,Ds[js]=((65280&Ls)>>>8|(255&Ls)<<8)>>>1}var Ns=function(ta,Ln,Ta){for(var ja=ta.length,La=0,Fa=new ks(Ln);La<ja;++La)++Fa[ta[La]-1];var wl,Pl=new ks(Ln);for(La=0;La<Ln;++La)Pl[La]=Pl[La-1]+Fa[La-1]<<1;for(wl=new ks(ja),La=0;La<ja;++La)wl[La]=Ds[Pl[ta[La]-1]++]>>>15-ta[La];return wl},Us=new Ss(288);for(js=0;js<144;++js)Us[js]=8;for(js=144;js<256;++js)Us[js]=9;for(js=256;js<280;++js)Us[js]=7;for(js=280;js<288;++js)Us[js]=8;var zs=new Ss(32);for(js=0;js<32;++js)zs[js]=5;var Hs=Ns(Us,9),Bs=Ns(zs,5),qs=function(ta){return(ta/8>>0)+(7&ta&&1)},Ws=function(ta,Ln,Ta){(Ta==null||Ta>ta.length)&&(Ta=ta.length);var ja=new(ta instanceof ks?ks:ta instanceof Ps?Ps:Ss)(Ta-Ln);return ja.set(ta.subarray(Ln,Ta)),ja},Gs=function(ta,Ln,Ta){Ta<<=7&Ln;var ja=Ln/8>>0;ta[ja]|=Ta,ta[ja+1]|=Ta>>>8},Vs=function(ta,Ln,Ta){Ta<<=7&Ln;var ja=Ln/8>>0;ta[ja]|=Ta,ta[ja+1]|=Ta>>>8,ta[ja+2]|=Ta>>>16},Js=function(ta,Ln){for(var Ta=[],ja=0;ja<ta.length;++ja)ta[ja]&&Ta.push({s:ja,f:ta[ja]});var La=Ta.length,Fa=Ta.slice();if(!La)return[new Ss(0),0];if(La==1){var wl=new Ss(Ta[0].s+1);return wl[Ta[0].s]=1,[wl,1]}Ta.sort((function(U_,B_){return U_.f-B_.f})),Ta.push({s:-1,f:25001});var Pl=Ta[0],pc=Ta[1],mc=0,gc=1,Vd=2;for(Ta[0]={s:-1,f:Pl.f+pc.f,l:Pl,r:pc};gc!=La-1;)Pl=Ta[Ta[mc].f<Ta[Vd].f?mc++:Vd++],pc=Ta[mc!=gc&&Ta[mc].f<Ta[Vd].f?mc++:Vd++],Ta[gc++]={s:-1,f:Pl.f+pc.f,l:Pl,r:pc};var Wd=Fa[0].s;for(ja=1;ja<La;++ja)Fa[ja].s>Wd&&(Wd=Fa[ja].s);var kf=new ks(Wd+1),Pf=Ks(Ta[gc-1],kf,0);if(Pf>Ln){ja=0;var Nf=0,Eh=Pf-Ln,Em=1<<Eh;for(Fa.sort((function(U_,B_){return kf[B_.s]-kf[U_.s]||U_.f-B_.f}));ja<La;++ja){var qg=Fa[ja].s;if(!(kf[qg]>Ln))break;Nf+=Em-(1<<Pf-kf[qg]),kf[qg]=Ln}for(Nf>>>=Eh;Nf>0;){var Ug=Fa[ja].s;kf[Ug]<Ln?Nf-=1<<Ln-kf[Ug]++-1:++ja}for(;ja>=0&&Nf;--ja){var Bg=Fa[ja].s;kf[Bg]==Ln&&(--kf[Bg],++Nf)}Pf=Ln}return[new Ss(kf),Pf]},Ks=function(ta,Ln,Ta){return ta.s==-1?Math.max(Ks(ta.l,Ln,Ta+1),Ks(ta.r,Ln,Ta+1)):Ln[ta.s]=Ta},Ys=function(ta){for(var Ln=ta.length;Ln&&!ta[--Ln];);for(var Ta=new ks(++Ln),ja=0,La=ta[0],Fa=1,wl=function(pc){Ta[ja++]=pc},Pl=1;Pl<=Ln;++Pl)if(ta[Pl]==La&&Pl!=Ln)++Fa;else{if(!La&&Fa>2){for(;Fa>138;Fa-=138)wl(32754);Fa>2&&(wl(Fa>10?Fa-11<<5|28690:Fa-3<<5|12305),Fa=0)}else if(Fa>3){for(wl(La),--Fa;Fa>6;Fa-=6)wl(8304);Fa>2&&(wl(Fa-3<<5|8208),Fa=0)}for(;Fa--;)wl(La);Fa=1,La=ta[Pl]}return[Ta.subarray(0,ja),Ln]},Xs=function(ta,Ln){for(var Ta=0,ja=0;ja<Ln.length;++ja)Ta+=ta[ja]*Ln[ja];return Ta},Qs=function(ta,Ln,Ta){var ja=Ta.length,La=qs(Ln+2);ta[La]=255&ja,ta[La+1]=ja>>>8,ta[La+2]=255^ta[La],ta[La+3]=255^ta[La+1];for(var Fa=0;Fa<ja;++Fa)ta[La+Fa+4]=Ta[Fa];return 8*(La+4+ja)},Zs=function(ta,Ln,Ta,ja,La,Fa,wl,Pl,pc,mc,gc){Gs(Ln,gc++,Ta),++La[256];for(var Vd=Js(La,15),Wd=Vd[0],kf=Vd[1],Pf=Js(Fa,15),Nf=Pf[0],Eh=Pf[1],Em=Ys(Wd),qg=Em[0],Ug=Em[1],Bg=Ys(Nf),U_=Bg[0],B_=Bg[1],VC=new ks(19),tj=0;tj<qg.length;++tj)VC[31&qg[tj]]++;for(tj=0;tj<U_.length;++tj)VC[31&U_[tj]]++;for(var aB=Js(VC,7),r6=aB[0],J2=aB[1],V_=19;V_>4&&!r6[Rs[V_-1]];--V_);var sP,Q2,q5,nj,n6=mc+5<<3,l6=Xs(La,Us)+Xs(Fa,zs)+wl,i6=Xs(La,Wd)+Xs(Fa,Nf)+wl+14+3*V_+Xs(VC,r6)+(2*VC[16]+3*VC[17]+7*VC[18]);if(n6<=l6&&n6<=i6)return Qs(Ln,gc,ta.subarray(pc,pc+mc));if(Gs(Ln,gc,1+(i6<l6)),gc+=2,i6<l6){sP=Ns(Wd,kf),Q2=Wd,q5=Ns(Nf,Eh),nj=Nf;var s6=Ns(r6,J2);for(Gs(Ln,gc,Ug-257),Gs(Ln,gc+5,B_-1),Gs(Ln,gc+10,V_-4),gc+=14,tj=0;tj<V_;++tj)Gs(Ln,gc+3*tj,r6[Rs[tj]]);gc+=3*V_;for(var u6=[qg,U_],f6=0;f6<2;++f6){var Rpe=u6[f6];for(tj=0;tj<Rpe.length;++tj){var Xae=31&Rpe[tj];Gs(Ln,gc,s6[Xae]),gc+=r6[Xae],Xae>15&&(Gs(Ln,gc,Rpe[tj]>>>5&127),gc+=Rpe[tj]>>>12)}}}else sP=Hs,Q2=Us,q5=Bs,nj=zs;for(tj=0;tj<Pl;++tj)if(ja[tj]>255){Xae=ja[tj]>>>18&31,Vs(Ln,gc,sP[Xae+257]),gc+=Q2[Xae+257],Xae>7&&(Gs(Ln,gc,ja[tj]>>>23&31),gc+=Ts[Xae]);var g$e=31&ja[tj];Vs(Ln,gc,q5[g$e]),gc+=nj[g$e],g$e>3&&(Vs(Ln,gc,ja[tj]>>>5&8191),gc+=Is[g$e])}else Vs(Ln,gc,sP[ja[tj]]),gc+=Q2[ja[tj]];return Vs(Ln,gc,sP[256]),gc+Q2[256]},tn=new Ps([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),en$1=(function(){for(var ta=new Ps(256),Ln=0;Ln<256;++Ln){for(var Ta=Ln,ja=9;--ja;)Ta=(1&Ta&&3988292384)^Ta>>>1;ta[Ln]=Ta}return ta})(),rn$1=function(ta,Ln,Ta,ja,La){return(function(Fa,wl,Pl,pc,mc,gc){var Vd=Fa.length,Wd=new Ss(pc+Vd+5*(1+Math.floor(Vd/7e3))+mc),kf=Wd.subarray(pc,Wd.length-mc),Pf=0;if(!wl||Vd<8)for(var Nf=0;Nf<=Vd;Nf+=65535){var Eh=Nf+65535;Eh<Vd?Pf=Qs(kf,Pf,Fa.subarray(Nf,Eh)):(kf[Nf]=gc,Pf=Qs(kf,Pf,Fa.subarray(Nf,Vd)))}else{for(var Em=tn[wl-1],qg=Em>>>13,Ug=8191&Em,Bg=(1<<Pl)-1,U_=new ks(32768),B_=new ks(Bg+1),VC=Math.ceil(Pl/3),tj=2*VC,aB=function(U$e){return(Fa[U$e]^Fa[U$e+1]<<VC^Fa[U$e+2]<<tj)&Bg},r6=new Ps(25e3),J2=new ks(288),V_=new ks(32),sP=0,Q2=0,q5=(Nf=0,0),nj=0,n6=0;Nf<Vd;++Nf){var l6=aB(Nf),i6=32767&Nf,s6=B_[l6];if(U_[i6]=s6,B_[l6]=i6,nj<=Nf){var u6=Vd-Nf;if((sP>7e3||q5>24576)&&u6>423){Pf=Zs(Fa,kf,0,r6,J2,V_,Q2,q5,n6,Nf-n6,Pf),q5=sP=Q2=0,n6=Nf;for(var f6=0;f6<286;++f6)J2[f6]=0;for(f6=0;f6<30;++f6)V_[f6]=0}var Rpe=2,Xae=0,g$e=Ug,n$e=i6-s6&32767;if(u6>2&&l6==aB(Nf-n$e))for(var v$e=Math.min(qg,u6)-1,S$e=Math.min(32767,Nf),M$e=Math.min(258,u6);n$e<=S$e&&--g$e&&i6!=s6;){if(Fa[Nf+Rpe]==Fa[Nf+Rpe-n$e]){for(var T$e=0;T$e<M$e&&Fa[Nf+T$e]==Fa[Nf+T$e-n$e];++T$e);if(T$e>Rpe){if(Rpe=T$e,Xae=n$e,T$e>v$e)break;var nae=Math.min(n$e,T$e-2),h$e=0;for(f6=0;f6<nae;++f6){var w$e=Nf-n$e+f6+32768&32767,m$e=w$e-U_[w$e]+32768&32767;m$e>h$e&&(h$e=m$e,s6=w$e)}}}n$e+=(i6=s6)-(s6=U_[i6])+32768&32767}if(Xae){r6[q5++]=268435456|Ms[Rpe]<<18|As[Xae];var K$e=31&Ms[Rpe],l1e=31&As[Xae];Q2+=Ts[K$e]+Is[l1e],++J2[257+K$e],++V_[l1e],nj=Nf+Rpe,++sP}else r6[q5++]=Fa[Nf],++J2[Fa[Nf]]}}Pf=Zs(Fa,kf,gc,r6,J2,V_,Q2,q5,n6,Nf-n6,Pf)}return Ws(Wd,0,pc+qs(Pf)+mc)})(ta,Ln.level==null?6:Ln.level,Ln.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(ta.length)))):12+Ln.mem,Ta,ja,!0)},sn$1=function(ta,Ln,Ta){for(;Ta;++Ln)ta[Ln]=Ta,Ta>>>=8};function nn$1(ta,Ln){Ln===void 0&&(Ln={});var Ta=(function(){var Pl=4294967295;return{p:function(pc){for(var mc=Pl,gc=0;gc<pc.length;++gc)mc=en$1[255&mc^pc[gc]]^mc>>>8;Pl=mc},d:function(){return 4294967295^Pl}}})(),ja=ta.length;Ta.p(ta);var La,Fa=rn$1(ta,Ln,10+((La=Ln).filename&&La.filename.length+1||0),8),wl=Fa.length;return(function(Pl,pc){var mc=pc.filename;if(Pl[0]=31,Pl[1]=139,Pl[2]=8,Pl[8]=pc.level<2?4:pc.level==9?2:0,Pl[9]=3,pc.mtime!=0&&sn$1(Pl,4,Math.floor(new Date(pc.mtime||Date.now())/1e3)),mc){Pl[3]=8;for(var gc=0;gc<=mc.length;++gc)Pl[gc+10]=mc.charCodeAt(gc)}})(Fa,Ln),sn$1(Fa,wl-8,Ta.d()),sn$1(Fa,wl-4,ja),Fa}var on$1=function(ta){var Ln,Ta,ja,La,Fa="";for(Ln=Ta=0,ja=(ta=(ta+"").replace(/\r\n/g,`
|
|
34778
34778
|
`).replace(/\r/g,`
|
|
34779
|
-
`)).length,La=0;La<ja;La++){var wl=ta.charCodeAt(La),Pl=null;wl<128?Ta++:Pl=wl>127&&wl<2048?String.fromCharCode(wl>>6|192,63&wl|128):String.fromCharCode(wl>>12|224,wl>>6&63|128,63&wl|128),D$b(Pl)||(Ta>Ln&&(Fa+=ta.substring(Ln,Ta)),Fa+=Pl,Ln=Ta=La+1)}return Ta>Ln&&(Fa+=ta.substring(Ln,ta.length)),Fa},an$1=!!u$h||!!l$9,ln="text/plain",un$1=function(ta,Ln,Ta){var ja;Ta===void 0&&(Ta=!0);var[La,Fa]=ta.split("?"),wl=g$8({},Ln),Pl=(ja=Fa?.split("&").map((mc=>{var gc,[Vd,Wd]=mc.split("="),kf=Ta&&(gc=wl[Vd])!==null&&gc!==void 0?gc:Wd;return delete wl[Vd],Vd+"="+kf})))!==null&&ja!==void 0?ja:[],pc=ue$1(wl);return pc&&Pl.push(pc),La+"?"+Pl.join("&")},hn=(ta,Ln)=>JSON.stringify(ta,((Ta,ja)=>typeof ja=="bigint"?ja.toString():ja),Ln),dn=ta=>{var{data:Ln,compression:Ta}=ta;if(Ln){if(Ta===oe$2.GZipJS){var ja=nn$1((function(pc,mc){var gc=pc.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(pc);for(var Vd=new Ss(pc.length+(pc.length>>>1)),Wd=0,kf=function(Em){Vd[Wd++]=Em},Pf=0;Pf<gc;++Pf){if(Wd+5>Vd.length){var Nf=new Ss(Wd+8+(gc-Pf<<1));Nf.set(Vd),Vd=Nf}var Eh=pc.charCodeAt(Pf);Eh<128||mc?kf(Eh):Eh<2048?(kf(192|Eh>>>6),kf(128|63&Eh)):Eh>55295&&Eh<57344?(kf(240|(Eh=65536+(1047552&Eh)|1023&pc.charCodeAt(++Pf))>>>18),kf(128|Eh>>>12&63),kf(128|Eh>>>6&63),kf(128|63&Eh)):(kf(224|Eh>>>12),kf(128|Eh>>>6&63),kf(128|63&Eh))}return Ws(Vd,0,Wd)})(hn(Ln)),{mtime:0}),La=new Blob([ja],{type:ln});return{contentType:ln,body:La,estimatedSize:La.size}}if(Ta===oe$2.Base64){var Fa=(function(pc){var mc,gc,Vd,Wd,kf,Pf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Nf=0,Eh=0,Em="",qg=[];if(!pc)return pc;pc=on$1(pc);do mc=(kf=pc.charCodeAt(Nf++)<<16|pc.charCodeAt(Nf++)<<8|pc.charCodeAt(Nf++))>>18&63,gc=kf>>12&63,Vd=kf>>6&63,Wd=63&kf,qg[Eh++]=Pf.charAt(mc)+Pf.charAt(gc)+Pf.charAt(Vd)+Pf.charAt(Wd);while(Nf<pc.length);switch(Em=qg.join(""),pc.length%3){case 1:Em=Em.slice(0,-2)+"==";break;case 2:Em=Em.slice(0,-1)+"="}return Em})(hn(Ln)),wl=(pc=>"data="+encodeURIComponent(typeof pc=="string"?pc:hn(pc)))(Fa);return{contentType:"application/x-www-form-urlencoded",body:wl,estimatedSize:new Blob([wl]).size}}var Pl=hn(Ln);return{contentType:"application/json",body:Pl,estimatedSize:new Blob([Pl]).size}}},vn=[];l$9&&vn.push({transport:"fetch",method:ta=>{var Ln,Ta,{contentType:ja,body:La,estimatedSize:Fa}=(Ln=dn(ta))!==null&&Ln!==void 0?Ln:{},wl=new Headers;Ot(ta.headers,(function(gc,Vd){wl.append(Vd,gc)})),ja&&wl.append("Content-Type",ja);var Pl=ta.url,pc=null;if(h$c){var mc=new h$c;pc={signal:mc.signal,timeout:setTimeout((()=>mc.abort()),ta.timeout)}}l$9(Pl,g$8({method:ta?.method||"GET",headers:wl,keepalive:ta.method==="POST"&&(Fa||0)<52428.8,body:La,signal:(Ta=pc)==null?void 0:Ta.signal},ta.fetchOptions)).then((gc=>gc.text().then((Vd=>{var Wd={statusCode:gc.status,text:Vd};if(gc.status===200)try{Wd.json=JSON.parse(Vd)}catch(kf){Pt$2.error(kf)}ta.callback==null||ta.callback(Wd)})))).catch((gc=>{Pt$2.error(gc),ta.callback==null||ta.callback({statusCode:0,text:gc})})).finally((()=>pc?clearTimeout(pc.timeout):null))}}),u$h&&vn.push({transport:"XHR",method:ta=>{var Ln,Ta=new u$h;Ta.open(ta.method||"GET",ta.url,!0);var{contentType:ja,body:La}=(Ln=dn(ta))!==null&&Ln!==void 0?Ln:{};Ot(ta.headers,(function(Fa,wl){Ta.setRequestHeader(wl,Fa)})),ja&&Ta.setRequestHeader("Content-Type",ja),ta.timeout&&(Ta.timeout=ta.timeout),ta.disableXHRCredentials||(Ta.withCredentials=!0),Ta.onreadystatechange=()=>{if(Ta.readyState===4){var Fa={statusCode:Ta.status,text:Ta.responseText};if(Ta.status===200)try{Fa.json=JSON.parse(Ta.responseText)}catch{}ta.callback==null||ta.callback(Fa)}},Ta.send(La)}}),n$9!=null&&n$9.sendBeacon&&vn.push({transport:"sendBeacon",method:ta=>{var Ln=un$1(ta.url,{beacon:"1"});try{var Ta,{contentType:ja,body:La}=(Ta=dn(ta))!==null&&Ta!==void 0?Ta:{},Fa=typeof La=="string"?new Blob([La],{type:ja}):La;n$9.sendBeacon(Ln,Fa)}catch{}}});var cn$1=function(ta,Ln){if(!(function(Ta){try{new RegExp(Ta)}catch{return!1}return!0})(Ln))return!1;try{return new RegExp(Ln).test(ta)}catch{return!1}};function fn$1(ta,Ln,Ta){return hn({distinct_id:ta,userPropertiesToSet:Ln,userPropertiesToSetOnce:Ta})}var pn={exact:(ta,Ln)=>Ln.some((Ta=>ta.some((ja=>Ta===ja)))),is_not:(ta,Ln)=>Ln.every((Ta=>ta.every((ja=>Ta!==ja)))),regex:(ta,Ln)=>Ln.some((Ta=>ta.some((ja=>cn$1(Ta,ja))))),not_regex:(ta,Ln)=>Ln.every((Ta=>ta.every((ja=>!cn$1(Ta,ja))))),icontains:(ta,Ln)=>Ln.map(gn).some((Ta=>ta.map(gn).some((ja=>Ta.includes(ja))))),not_icontains:(ta,Ln)=>Ln.map(gn).every((Ta=>ta.map(gn).every((ja=>!Ta.includes(ja)))))},gn=ta=>ta.toLowerCase(),_n=Tt$1("[Error tracking]");class mn{constructor(Ln){var Ta,ja;this.Jt=[],this.Kt=new it$1([new pt$1,new St$1,new _t$1,new gt$2,new $t,new xt,new yt$1,new Et$2],ft$1("web:javascript",lt$1,dt$2)),this._instance=Ln,this.Jt=(Ta=(ja=this._instance.persistence)==null?void 0:ja.get_property(Xt))!==null&&Ta!==void 0?Ta:[]}onRemoteConfig(Ln){var Ta,ja,La,Fa=(Ta=(ja=Ln.errorTracking)==null?void 0:ja.suppressionRules)!==null&&Ta!==void 0?Ta:[],wl=(La=Ln.errorTracking)==null?void 0:La.captureExtensionExceptions;this.Jt=Fa,this._instance.persistence&&this._instance.persistence.register({[Xt]:this.Jt,[Qt]:wl})}get Yt(){var Ln,Ta=!!this._instance.get_property(Qt),ja=this._instance.config.error_tracking.captureExtensionExceptions;return(Ln=ja??Ta)!==null&&Ln!==void 0&&Ln}buildProperties(Ln,Ta){return this.Kt.buildFromUnknown(Ln,{syntheticException:Ta?.syntheticException,mechanism:{handled:Ta?.handled}})}sendExceptionEvent(Ln){var Ta=Ln.$exception_list;if(this.Xt(Ta)){if(this.Qt(Ta))return void _n.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(Ta))return void _n.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(Ta))return void _n.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",Ln,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(Ln){if(Ln.length===0)return!1;var Ta=Ln.reduce(((ja,La)=>{var{type:Fa,value:wl}=La;return M$7(Fa)&&Fa.length>0&&ja.$exception_types.push(Fa),M$7(wl)&&wl.length>0&&ja.$exception_values.push(wl),ja}),{$exception_types:[],$exception_values:[]});return this.Jt.some((ja=>{var La=ja.values.map((Fa=>{var wl,Pl=pn[Fa.operator],pc=I$9(Fa.value)?Fa.value:[Fa.value],mc=(wl=Ta[Fa.key])!==null&&wl!==void 0?wl:[];return pc.length>0&&Pl(pc,mc)}));return ja.type==="OR"?La.some(Boolean):La.every(Boolean)}))}Zt(Ln){return Ln.flatMap((Ta=>{var ja,La;return(ja=(La=Ta.stacktrace)==null?void 0:La.frames)!==null&&ja!==void 0?ja:[]})).some((Ta=>Ta.filename&&Ta.filename.startsWith("chrome-extension://")))}ti(Ln){if(Ln.length>0){var Ta,ja,La,Fa,wl=(Ta=(ja=Ln[0].stacktrace)==null?void 0:ja.frames)!==null&&Ta!==void 0?Ta:[],Pl=wl[wl.length-1];return(La=Pl==null||(Fa=Pl.filename)==null?void 0:Fa.includes("posthog.com/static"))!==null&&La!==void 0&&La}return!1}Xt(Ln){return!j$b(Ln)&&I$9(Ln)}}var yn=Tt$1("[FeatureFlags]"),bn=Tt$1("[FeatureFlags]",{debugEnabled:!0}),wn="$active_feature_flags",xn="$override_feature_flags",$n="$feature_flag_payloads",En="$override_feature_flag_payloads",Sn="$feature_flag_request_id",kn=ta=>{var Ln={};for(var[Ta,ja]of Dt$1(ta||{}))ja&&(Ln[Ta]=ja);return Ln},Pn=ta=>{var Ln=ta.flags;return Ln?(ta.featureFlags=Object.fromEntries(Object.keys(Ln).map((Ta=>{var ja;return[Ta,(ja=Ln[Ta].variant)!==null&&ja!==void 0?ja:Ln[Ta].enabled]}))),ta.featureFlagPayloads=Object.fromEntries(Object.keys(Ln).filter((Ta=>Ln[Ta].enabled)).filter((Ta=>{var ja;return(ja=Ln[Ta].metadata)==null?void 0:ja.payload})).map((Ta=>{var ja;return[Ta,(ja=Ln[Ta].metadata)==null?void 0:ja.payload]})))):yn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),ta},Tn=(function(ta){return ta.FeatureFlags="feature_flags",ta.Recordings="recordings",ta})({});class In{constructor(Ln){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=Ln,this.featureFlagEventHandlers=[]}li(){var Ln=this._instance.config.evaluation_environments;return Ln!=null&&Ln.length?Ln.filter((Ta=>{var ja=Ta&&typeof Ta=="string"&&Ta.trim().length>0;return ja||yn.error("Invalid evaluation environment found:",Ta,"Expected non-empty string"),ja})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var Ln=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.di({disableFlags:Ln})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var Ln=this._instance.get_property(ai),Ta=this._instance.get_property(xn),ja=this._instance.get_property(En);if(!ja&&!Ta)return Ln||{};var La=Mt$2({},Ln||{}),Fa=[...new Set([...Object.keys(ja||{}),...Object.keys(Ta||{})])];for(var wl of Fa){var Pl,pc,mc=La[wl],gc=Ta?.[wl],Vd=O$6(gc)?(Pl=mc?.enabled)!==null&&Pl!==void 0&&Pl:!!gc,Wd=O$6(gc)?mc.variant:typeof gc=="string"?gc:void 0,kf=ja?.[wl],Pf=g$8({},mc,{enabled:Vd,variant:Vd?Wd??mc?.variant:void 0});Vd!==mc?.enabled&&(Pf.original_enabled=mc?.enabled),Wd!==mc?.variant&&(Pf.original_variant=mc?.variant),kf&&(Pf.metadata=g$8({},mc?.metadata,{payload:kf,original_payload:mc==null||(pc=mc.metadata)==null?void 0:pc.payload})),La[wl]=Pf}return this.ii||(yn.warn(" Overriding feature flag details!",{flagDetails:Ln,overriddenPayloads:ja,finalDetails:La}),this.ii=!0),La}getFlagVariants(){var Ln=this._instance.get_property(ni),Ta=this._instance.get_property(xn);if(!Ta)return Ln||{};for(var ja=Mt$2({},Ln),La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)ja[La[Fa]]=Ta[La[Fa]];return this.ii||(yn.warn(" Overriding feature flags!",{enabledFlags:Ln,overriddenFlags:Ta,finalFlags:ja}),this.ii=!0),ja}getFlagPayloads(){var Ln=this._instance.get_property($n),Ta=this._instance.get_property(En);if(!Ta)return Ln||{};for(var ja=Mt$2({},Ln||{}),La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)ja[La[Fa]]=Ta[La[Fa]];return this.ii||(yn.warn(" Overriding feature flag payloads!",{flagPayloads:Ln,overriddenPayloads:Ta,finalPayloads:ja}),this.ii=!0),ja}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.di()}),5))}vi(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(Ln){this.$anon_distinct_id=Ln}setReloadingPaused(Ln){this.si=Ln}di(Ln){var Ta;if(this.vi(),!this._instance.M())if(this.ri)this.ni=!0;else{var ja={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:g$8({},((Ta=this._instance.persistence)==null?void 0:Ta.get_initial_props())||{},this._instance.get_property(li)||{}),group_properties:this._instance.get_property(ui)};(Ln!=null&&Ln.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(ja.disable_flags=!0),this.ui()&&(ja.evaluation_environments=this.li());var La=this._instance.config.__preview_remote_config,Fa=La?"/flags/?v=2":"/flags/?v=2&config=true",wl=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",Pl=this._instance.requestRouter.endpointFor("flags",Fa+wl);La&&(ja.timezone=ps()),this.ri=!0,this._instance.ci({method:"POST",url:Pl,data:ja,compression:this._instance.config.disable_compression?void 0:oe$2.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:pc=>{var mc,gc,Vd=!0;if(pc.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),Vd=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((gc=pc.json)!==null&&gc!==void 0?gc:{})),!ja.disable_flags||this.ni)if(this.ai=!Vd,pc.json&&(mc=pc.json.quotaLimited)!=null&&mc.includes(Tn.FeatureFlags))yn.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.");else{var Wd;ja.disable_flags||this.receivedFeatureFlags((Wd=pc.json)!==null&&Wd!==void 0?Wd:{},Vd),this.ni&&(this.ni=!1,this.di())}}})}}getFeatureFlag(Ln,Ta){if(Ta===void 0&&(Ta={}),this.ei||this.getFlags()&&this.getFlags().length>0){var ja=this.getFlagVariants()[Ln],La=""+ja,Fa=this._instance.get_property(Sn)||void 0,wl=this._instance.get_property(vi)||{};if((Ta.send_event||!("send_event"in Ta))&&(!(Ln in wl)||!wl[Ln].includes(La))){var Pl,pc,mc,gc,Vd,Wd,kf,Pf,Nf;I$9(wl[Ln])?wl[Ln].push(La):wl[Ln]=[La],(Pl=this._instance.persistence)==null||Pl.register({[vi]:wl});var Eh=this.getFeatureFlagDetails(Ln),Em={$feature_flag:Ln,$feature_flag_response:ja,$feature_flag_payload:this.getFeatureFlagPayload(Ln)||null,$feature_flag_request_id:Fa,$feature_flag_bootstrapped_response:((pc=this._instance.config.bootstrap)==null||(pc=pc.featureFlags)==null?void 0:pc[Ln])||null,$feature_flag_bootstrapped_payload:((mc=this._instance.config.bootstrap)==null||(mc=mc.featureFlagPayloads)==null?void 0:mc[Ln])||null,$used_bootstrap_value:!this.ai};O$6(Eh==null||(gc=Eh.metadata)==null?void 0:gc.version)||(Em.$feature_flag_version=Eh.metadata.version);var qg,Ug=(Vd=Eh==null||(Wd=Eh.reason)==null?void 0:Wd.description)!==null&&Vd!==void 0?Vd:Eh==null||(kf=Eh.reason)==null?void 0:kf.code;Ug&&(Em.$feature_flag_reason=Ug),Eh!=null&&(Pf=Eh.metadata)!=null&&Pf.id&&(Em.$feature_flag_id=Eh.metadata.id),O$6(Eh?.original_variant)&&O$6(Eh?.original_enabled)||(Em.$feature_flag_original_response=O$6(Eh.original_variant)?Eh.original_enabled:Eh.original_variant),Eh!=null&&(Nf=Eh.metadata)!=null&&Nf.original_payload&&(Em.$feature_flag_original_payload=Eh==null||(qg=Eh.metadata)==null?void 0:qg.original_payload),this._instance.capture("$feature_flag_called",Em)}return ja}yn.warn('getFeatureFlag for key "'+Ln+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(Ln){return this.getFlagsWithDetails()[Ln]}getFeatureFlagPayload(Ln){return this.getFlagPayloads()[Ln]}getRemoteConfigPayload(Ln,Ta){var ja=this._instance.config.token,La={distinct_id:this._instance.get_distinct_id(),token:ja};this.ui()&&(La.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:La,compression:this._instance.config.disable_compression?void 0:oe$2.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:Fa=>{var wl,Pl=(wl=Fa.json)==null?void 0:wl.featureFlagPayloads;Ta(Pl?.[Ln]||void 0)}})}isFeatureEnabled(Ln,Ta){if(Ta===void 0&&(Ta={}),this.ei||this.getFlags()&&this.getFlags().length>0){var ja=this.getFeatureFlag(Ln,Ta);return O$6(ja)?void 0:!!ja}yn.warn('isFeatureEnabled for key "'+Ln+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(Ln){this.featureFlagEventHandlers.push(Ln)}removeFeatureFlagsHandler(Ln){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((Ta=>Ta!==Ln))}receivedFeatureFlags(Ln,Ta){if(this._instance.persistence){this.ei=!0;var ja=this.getFlagVariants(),La=this.getFlagPayloads(),Fa=this.getFlagsWithDetails();(function(wl,Pl,pc,mc,gc){pc===void 0&&(pc={}),mc===void 0&&(mc={}),gc===void 0&&(gc={});var Vd=Pn(wl),Wd=Vd.flags,kf=Vd.featureFlags,Pf=Vd.featureFlagPayloads;if(kf){var Nf=wl.requestId;if(I$9(kf)){yn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var Eh={};if(kf)for(var Em=0;Em<kf.length;Em++)Eh[kf[Em]]=!0;Pl&&Pl.register({[wn]:kf,[ni]:Eh})}else{var qg=kf,Ug=Pf,Bg=Wd;wl.errorsWhileComputingFlags&&(qg=g$8({},pc,qg),Ug=g$8({},mc,Ug),Bg=g$8({},gc,Bg)),Pl&&Pl.register(g$8({[wn]:Object.keys(kn(qg)),[ni]:qg||{},[$n]:Ug||{},[ai]:Bg||{}},Nf?{[Sn]:Nf}:{}))}}})(Ln,this._instance.persistence,ja,La,Fa),this.pi(Ta)}}override(Ln,Ta){Ta===void 0&&(Ta=!1),yn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:Ln,suppressWarning:Ta})}overrideFeatureFlags(Ln){if(!this._instance.__loaded||!this._instance.persistence)return yn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(Ln===!1)return this._instance.persistence.unregister(xn),this._instance.persistence.unregister(En),this.pi(),bn.info("All overrides cleared");if(Ln&&typeof Ln=="object"&&("flags"in Ln||"payloads"in Ln)){var Ta,ja=Ln;if(this.ii=!!((Ta=ja.suppressWarning)!==null&&Ta!==void 0&&Ta),"flags"in ja){if(ja.flags===!1)this._instance.persistence.unregister(xn),bn.info("Flag overrides cleared");else if(ja.flags){if(I$9(ja.flags)){for(var La={},Fa=0;Fa<ja.flags.length;Fa++)La[ja.flags[Fa]]=!0;this._instance.persistence.register({[xn]:La})}else this._instance.persistence.register({[xn]:ja.flags});bn.info("Flag overrides set",{flags:ja.flags})}}return"payloads"in ja&&(ja.payloads===!1?(this._instance.persistence.unregister(En),bn.info("Payload overrides cleared")):ja.payloads&&(this._instance.persistence.register({[En]:ja.payloads}),bn.info("Payload overrides set",{payloads:ja.payloads}))),void this.pi()}this.pi()}onFeatureFlags(Ln){if(this.addFeatureFlagsHandler(Ln),this.ei){var{flags:Ta,flagVariants:ja}=this.gi();Ln(Ta,ja)}return()=>this.removeFeatureFlagsHandler(Ln)}updateEarlyAccessFeatureEnrollment(Ln,Ta,ja){var La,Fa=(this._instance.get_property(oi)||[]).find((mc=>mc.flagKey===Ln)),wl={["$feature_enrollment/"+Ln]:Ta},Pl={$feature_flag:Ln,$feature_enrollment:Ta,$set:wl};Fa&&(Pl.$early_access_feature_name=Fa.name),ja&&(Pl.$feature_enrollment_stage=ja),this._instance.capture("$feature_enrollment_update",Pl),this.setPersonPropertiesForFlags(wl,!1);var pc=g$8({},this.getFlagVariants(),{[Ln]:Ta});(La=this._instance.persistence)==null||La.register({[wn]:Object.keys(kn(pc)),[ni]:pc}),this.pi()}getEarlyAccessFeatures(Ln,Ta,ja){Ta===void 0&&(Ta=!1);var La=this._instance.get_property(oi),Fa=ja?"&"+ja.map((wl=>"stage="+wl)).join("&"):"";if(La&&!Ta)return Ln(La);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+Fa),method:"GET",callback:wl=>{var Pl,pc;if(wl.json){var mc=wl.json.earlyAccessFeatures;return(Pl=this._instance.persistence)==null||Pl.unregister(oi),(pc=this._instance.persistence)==null||pc.register({[oi]:mc}),Ln(mc)}}})}gi(){var Ln=this.getFlags(),Ta=this.getFlagVariants();return{flags:Ln.filter((ja=>Ta[ja])),flagVariants:Object.keys(Ta).filter((ja=>Ta[ja])).reduce(((ja,La)=>(ja[La]=Ta[La],ja)),{})}}pi(Ln){var{flags:Ta,flagVariants:ja}=this.gi();this.featureFlagEventHandlers.forEach((La=>La(Ta,ja,{errorsLoading:Ln})))}setPersonPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0);var ja=this._instance.get_property(li)||{};this._instance.register({[li]:g$8({},ja,Ln)}),Ta&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(li)}setGroupPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0);var ja=this._instance.get_property(ui)||{};Object.keys(ja).length!==0&&Object.keys(ja).forEach((La=>{ja[La]=g$8({},ja[La],Ln[La]),delete Ln[La]})),this._instance.register({[ui]:g$8({},ja,Ln)}),Ta&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(Ln){if(Ln){var Ta=this._instance.get_property(ui)||{};this._instance.register({[ui]:g$8({},Ta,{[Ln]:{}})})}else this._instance.unregister(ui)}reset(){this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.$anon_distinct_id=void 0,this.vi(),this.ii=!1}}var Rn=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Fn{constructor(Ln,Ta){this.F=Ln,this.props={},this.mi=!1,this.yi=(ja=>{var La="";return ja.token&&(La=ja.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),ja.persistence_name?"ph_"+ja.persistence_name:"ph_"+La+"_posthog"})(Ln),this.Y=this.bi(Ln),this.load(),Ln.debug&&Pt$2.info("Persistence loaded",Ln.persistence,g$8({},this.props)),this.update_config(Ln,Ln,Ta),this.save()}isDisabled(){return!!this.wi}bi(Ln){Rn.indexOf(Ln.persistence.toLowerCase())===-1&&(Pt$2.critical("Unknown persistence type "+Ln.persistence+"; falling back to localStorage+cookie"),Ln.persistence="localStorage+cookie");var Ta=Ln.persistence.toLowerCase();return Ta==="localstorage"&&Ce$3.H()?Ce$3:Ta==="localstorage+cookie"&&Me$2.H()?Me$2:Ta==="sessionstorage"&&Le$1.H()?Le$1:Ta==="memory"?De$3:Ta==="cookie"?Re$1:Me$2.H()?Me$2:Re$1}properties(){var Ln={};return Ot(this.props,(function(Ta,ja){if(ja===ni&&F$8(Ta))for(var La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)Ln["$feature/"+La[Fa]]=Ta[La[Fa]];else Pl=ja,pc=!1,(D$b(wl=xi)?pc:s$f&&wl.indexOf===s$f?wl.indexOf(Pl)!=-1:(Ot(wl,(function(mc){if(pc||(pc=mc===Pl))return Ft$2})),pc))||(Ln[ja]=Ta);var wl,Pl,pc})),Ln}load(){if(!this.wi){var Ln=this.Y.W(this.yi);Ln&&(this.props=Mt$2({},Ln))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.$i,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(Ln,Ta,ja){if(F$8(Ln)){O$6(Ta)&&(Ta="None"),this.xi=O$6(ja)?this.Si:ja;var La=!1;if(Ot(Ln,((Fa,wl)=>{this.props.hasOwnProperty(wl)&&this.props[wl]!==Ta||(this.props[wl]=Fa,La=!0)})),La)return this.save(),!0}return!1}register(Ln,Ta){if(F$8(Ln)){this.xi=O$6(Ta)?this.Si:Ta;var ja=!1;if(Ot(Ln,((La,Fa)=>{Ln.hasOwnProperty(Fa)&&this.props[Fa]!==La&&(this.props[Fa]=La,ja=!0)})),ja)return this.save(),!0}return!1}unregister(Ln){Ln in this.props&&(delete this.props[Ln],this.save())}update_campaign_params(){if(!this.mi){var Ln=ls(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);C$c(Nt(Ln))||this.register(Ln),this.mi=!0}}update_search_keyword(){var Ln;this.register((Ln=o$d?.referrer)?hs(Ln):{})}update_referrer_info(){var Ln;this.register_once({$referrer:vs(),$referring_domain:o$d!=null&&o$d.referrer&&((Ln=le$2(o$d.referrer))==null?void 0:Ln.host)||"$direct"},void 0)}set_initial_person_info(){this.props[gi]||this.props[_i]||this.register_once({[mi]:cs(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var Ln={};Ot([_i,gi],(wl=>{var Pl=this.props[wl];Pl&&Ot(Pl,(function(pc,mc){Ln["$initial_"+E$8(mc)]=pc}))}));var Ta,ja,La=this.props[mi];if(La){var Fa=(Ta=fs(La),ja={},Ot(Ta,(function(wl,Pl){ja["$initial_"+E$8(Pl)]=wl})),ja);Mt$2(Ln,Fa)}return Ln}safe_merge(Ln){return Ot(this.props,(function(Ta,ja){ja in Ln||(Ln[ja]=Ta)})),Ln}update_config(Ln,Ta,ja){if(this.Si=this.xi=Ln.cookie_expiration,this.set_disabled(Ln.disable_persistence||!!ja),this.set_cross_subdomain(Ln.cross_subdomain_cookie),this.set_secure(Ln.secure_cookie),Ln.persistence!==Ta.persistence){var La=this.bi(Ln),Fa=this.props;this.clear(),this.Y=La,this.props=Fa,this.save()}}set_disabled(Ln){this.wi=Ln,this.wi?this.remove():this.save()}set_cross_subdomain(Ln){Ln!==this.$i&&(this.$i=Ln,this.remove(),this.save())}set_secure(Ln){Ln!==this.Ei&&(this.Ei=Ln,this.remove(),this.save())}set_event_timer(Ln,Ta){var ja=this.props[Vt]||{};ja[Ln]=Ta,this.props[Vt]=ja,this.save()}remove_event_timer(Ln){var Ta=(this.props[Vt]||{})[Ln];return O$6(Ta)||(delete this.props[Vt][Ln],this.save()),Ta}get_property(Ln){return this.props[Ln]}set_property(Ln,Ta){this.props[Ln]=Ta,this.save()}}(function(ta){return ta.Button="button",ta.Tab="tab",ta.Selector="selector",ta})({});(function(ta){return ta.TopLeft="top_left",ta.TopRight="top_right",ta.TopCenter="top_center",ta.MiddleLeft="middle_left",ta.MiddleRight="middle_right",ta.MiddleCenter="middle_center",ta.Left="left",ta.Center="center",ta.Right="right",ta.NextToTrigger="next_to_trigger",ta})({});(function(ta){return ta.Top="top",ta.Left="left",ta.Right="right",ta.Bottom="bottom",ta})({});var An=(function(ta){return ta.Popover="popover",ta.API="api",ta.Widget="widget",ta.ExternalSurvey="external_survey",ta})({});(function(ta){return ta.Open="open",ta.MultipleChoice="multiple_choice",ta.SingleChoice="single_choice",ta.Rating="rating",ta.Link="link",ta})({});(function(ta){return ta.NextQuestion="next_question",ta.End="end",ta.ResponseBased="response_based",ta.SpecificQuestion="specific_question",ta})({});(function(ta){return ta.Once="once",ta.Recurring="recurring",ta.Always="always",ta})({});var Nn=(function(ta){return ta.SHOWN="survey shown",ta.DISMISSED="survey dismissed",ta.SENT="survey sent",ta})({}),Un=(function(ta){return ta.SURVEY_ID="$survey_id",ta.SURVEY_NAME="$survey_name",ta.SURVEY_RESPONSE="$survey_response",ta.SURVEY_ITERATION="$survey_iteration",ta.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",ta.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",ta.SURVEY_SUBMISSION_ID="$survey_submission_id",ta.SURVEY_QUESTIONS="$survey_questions",ta.SURVEY_COMPLETED="$survey_completed",ta})({}),zn=(function(ta){return ta.Popover="popover",ta.Inline="inline",ta})({});class Hn{constructor(){this.ki={},this.ki={}}on(Ln,Ta){return this.ki[Ln]||(this.ki[Ln]=[]),this.ki[Ln].push(Ta),()=>{this.ki[Ln]=this.ki[Ln].filter((ja=>ja!==Ta))}}emit(Ln,Ta){for(var ja of this.ki[Ln]||[])ja(Ta);for(var La of this.ki["*"]||[])La(Ln,Ta)}}class Bn{constructor(Ln){this.Pi=new Hn,this.Ti=(Ta,ja)=>this.Ii(Ta,ja)&&this.Ri(Ta,ja)&&this.Fi(Ta,ja),this.Ii=(Ta,ja)=>ja==null||!ja.event||Ta?.event===ja?.event,this._instance=Ln,this.Ci=new Set,this.Oi=new Set}init(){var Ln;if(!O$6((Ln=this._instance)==null?void 0:Ln.Mi)){var Ta;(Ta=this._instance)==null||Ta.Mi(((ja,La)=>{this.on(ja,La)}))}}register(Ln){var Ta,ja;if(!O$6((Ta=this._instance)==null?void 0:Ta.Mi)&&(Ln.forEach((wl=>{var Pl,pc;(Pl=this.Oi)==null||Pl.add(wl),(pc=wl.steps)==null||pc.forEach((mc=>{var gc;(gc=this.Ci)==null||gc.add(mc?.event||"")}))})),(ja=this._instance)!=null&&ja.autocapture)){var La,Fa=new Set;Ln.forEach((wl=>{var Pl;(Pl=wl.steps)==null||Pl.forEach((pc=>{pc!=null&&pc.selector&&Fa.add(pc?.selector)}))})),(La=this._instance)==null||La.autocapture.setElementSelectors(Fa)}}on(Ln,Ta){var ja;Ta!=null&&Ln.length!=0&&(this.Ci.has(Ln)||this.Ci.has(Ta?.event))&&this.Oi&&((ja=this.Oi)==null?void 0:ja.size)>0&&this.Oi.forEach((La=>{this.Ai(Ta,La)&&this.Pi.emit("actionCaptured",La.name)}))}Di(Ln){this.onAction("actionCaptured",(Ta=>Ln(Ta)))}Ai(Ln,Ta){if(Ta?.steps==null)return!1;for(var ja of Ta.steps)if(this.Ti(Ln,ja))return!0;return!1}onAction(Ln,Ta){return this.Pi.on(Ln,Ta)}Ri(Ln,Ta){if(Ta!=null&&Ta.url){var ja,La=Ln==null||(ja=Ln.properties)==null?void 0:ja.$current_url;if(!La||typeof La!="string"||!Bn.ji(La,Ta?.url,Ta?.url_matching||"contains"))return!1}return!0}static ji(Ln,Ta,ja){switch(ja){case"regex":return!!t$9&&cn$1(Ln,Ta);case"exact":return Ta===Ln;case"contains":var La=Bn.Li(Ta).replace(/_/g,".").replace(/%/g,".*");return cn$1(Ln,La);default:return!1}}static Li(Ln){return Ln.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}Fi(Ln,Ta){if((Ta!=null&&Ta.href||Ta!=null&&Ta.tag_name||Ta!=null&&Ta.text)&&!this.Ni(Ln).some((Fa=>!(Ta!=null&&Ta.href&&!Bn.ji(Fa.href||"",Ta?.href,Ta?.href_matching||"exact"))&&(Ta==null||!Ta.tag_name||Fa.tag_name===Ta?.tag_name)&&!(Ta!=null&&Ta.text&&!Bn.ji(Fa.text||"",Ta?.text,Ta?.text_matching||"exact")&&!Bn.ji(Fa.$el_text||"",Ta?.text,Ta?.text_matching||"exact")))))return!1;if(Ta!=null&&Ta.selector){var ja,La=Ln==null||(ja=Ln.properties)==null?void 0:ja.$element_selectors;if(!La||!La.includes(Ta?.selector))return!1}return!0}Ni(Ln){return Ln?.properties.$elements==null?[]:Ln?.properties.$elements}}var qn=Tt$1("[Surveys]"),Wn="seenSurvey_",Gn=(ta,Ln)=>{var Ta="$survey_"+Ln+"/"+ta.id;return ta.current_iteration&&ta.current_iteration>0&&(Ta="$survey_"+Ln+"/"+ta.id+"/"+ta.current_iteration),Ta},Vn=ta=>{var Ln=""+Wn+ta.id;return ta.current_iteration&&ta.current_iteration>0&&(Ln=""+Wn+ta.id+"_"+ta.current_iteration),Ln},Jn=[An.Popover,An.Widget,An.API],Kn={ignoreConditions:!1,ignoreDelay:!1,displayType:zn.Popover};class Yn{constructor(Ln){this._instance=Ln,this.Ui=new Map,this.zi=new Map}register(Ln){var Ta;O$6((Ta=this._instance)==null?void 0:Ta.Mi)||(this.Hi(Ln),this.Bi(Ln))}Bi(Ln){var Ta=Ln.filter((ja=>{var La,Fa;return((La=ja.conditions)==null?void 0:La.actions)&&((Fa=ja.conditions)==null||(Fa=Fa.actions)==null||(Fa=Fa.values)==null?void 0:Fa.length)>0}));Ta.length!==0&&(this.qi==null&&(this.qi=new Bn(this._instance),this.qi.init(),this.qi.Di((ja=>{this.onAction(ja)}))),Ta.forEach((ja=>{var La,Fa,wl,Pl,pc;ja.conditions&&(La=ja.conditions)!=null&&La.actions&&(Fa=ja.conditions)!=null&&(Fa=Fa.actions)!=null&&Fa.values&&((wl=ja.conditions)==null||(wl=wl.actions)==null||(wl=wl.values)==null?void 0:wl.length)>0&&((Pl=this.qi)==null||Pl.register(ja.conditions.actions.values),(pc=ja.conditions)==null||(pc=pc.actions)==null||(pc=pc.values)==null||pc.forEach((mc=>{if(mc&&mc.name){var gc=this.zi.get(mc.name);gc&&gc.push(ja.id),this.zi.set(mc.name,gc||[ja.id])}})))})))}Hi(Ln){var Ta;Ln.filter((ja=>{var La,Fa;return((La=ja.conditions)==null?void 0:La.events)&&((Fa=ja.conditions)==null||(Fa=Fa.events)==null||(Fa=Fa.values)==null?void 0:Fa.length)>0})).length!==0&&((Ta=this._instance)==null||Ta.Mi(((ja,La)=>{this.onEvent(ja,La)})),Ln.forEach((ja=>{var La;(La=ja.conditions)==null||(La=La.events)==null||(La=La.values)==null||La.forEach((Fa=>{if(Fa&&Fa.name){var wl=this.Ui.get(Fa.name);wl&&wl.push(ja.id),this.Ui.set(Fa.name,wl||[ja.id])}}))})))}onEvent(Ln,Ta){var ja,La,Fa=((ja=this._instance)==null||(ja=ja.persistence)==null?void 0:ja.props[di])||[];if(Nn.SHOWN===Ln&&Ta&&Fa.length>0){var wl;qn.info("survey event matched, removing survey from activated surveys",{event:Ln,eventPayload:Ta,existingActivatedSurveys:Fa});var Pl=Ta==null||(wl=Ta.properties)==null?void 0:wl.$survey_id;if(Pl){var pc=Fa.indexOf(Pl);pc>=0&&(Fa.splice(pc,1),this.Wi(Fa))}}else if(this.Ui.has(Ln)){qn.info("survey event name matched",{event:Ln,eventPayload:Ta,surveys:this.Ui.get(Ln)});var mc=[];(La=this._instance)==null||La.getSurveys((Vd=>{mc=Vd.filter((Wd=>{var kf;return(kf=this.Ui.get(Ln))==null?void 0:kf.includes(Wd.id)}))}));var gc=mc.filter((Vd=>{var Wd,kf=(Wd=Vd.conditions)==null||(Wd=Wd.events)==null||(Wd=Wd.values)==null?void 0:Wd.find((Pf=>Pf.name===Ln));return!!kf&&(!kf.propertyFilters||Object.entries(kf.propertyFilters).every((Pf=>{var Nf,[Eh,Em]=Pf,qg=Ta==null||(Nf=Ta.properties)==null?void 0:Nf[Eh];if(O$6(qg)||D$b(qg))return!1;var Ug=[String(qg)],Bg=pn[Em.operator];return Bg?Bg(Em.values,Ug):(qn.warn("Unknown property comparison operator: "+Em.operator),!1)})))}));this.Wi(Fa.concat(gc.map((Vd=>Vd.id))||[]))}}onAction(Ln){var Ta,ja=((Ta=this._instance)==null||(Ta=Ta.persistence)==null?void 0:Ta.props[di])||[];this.zi.has(Ln)&&this.Wi(ja.concat(this.zi.get(Ln)||[]))}Wi(Ln){var Ta;qn.info("updating activated surveys",{activatedSurveys:Ln}),(Ta=this._instance)==null||(Ta=Ta.persistence)==null||Ta.register({[di]:[...new Set(Ln)]})}getSurveys(){var Ln,Ta=(Ln=this._instance)==null||(Ln=Ln.persistence)==null?void 0:Ln.props[di];return Ta||[]}getEventToSurveys(){return this.Ui}Gi(){return this.qi}}class Xn{constructor(Ln){this.Vi=void 0,this._surveyManager=null,this.Ji=!1,this.Ki=!1,this.Yi=[],this._instance=Ln,this._surveyEventReceiver=null}onRemoteConfig(Ln){if(!this._instance.config.disable_surveys){var Ta=Ln.surveys;if(j$b(Ta))return qn.warn("Flags not loaded yet. Not loading surveys.");var ja=I$9(Ta);this.Vi=ja?Ta.length>0:Ta,qn.info("flags response received, isSurveysEnabled: "+this.Vi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var Ln=[],Ta=0;Ta<localStorage.length;Ta++){var ja=localStorage.key(Ta);(ja!=null&&ja.startsWith(Wn)||ja!=null&&ja.startsWith("inProgressSurvey_"))&&Ln.push(ja)}Ln.forEach((La=>localStorage.removeItem(La)))}loadIfEnabled(){if(!this._surveyManager)if(this.Ki)qn.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)qn.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())qn.info("Not loading surveys in cookieless mode without consent.");else{var Ln=v$7?.__PosthogExtensions__;if(Ln){if(!O$6(this.Vi)||this._instance.config.advanced_enable_surveys){var Ta=this.Vi||this._instance.config.advanced_enable_surveys;this.Ki=!0;try{var ja=Ln.generateSurveys;if(ja)return void this.Xi(ja,Ta);var La=Ln.loadExternalDependency;if(!La)return void this.Qi("PostHog loadExternalDependency extension not found.");La(this._instance,"surveys",(Fa=>{Fa||!Ln.generateSurveys?this.Qi("Could not load surveys script",Fa):this.Xi(Ln.generateSurveys,Ta)}))}catch(Fa){throw this.Qi("Error initializing surveys",Fa),Fa}finally{this.Ki=!1}}}else qn.error("PostHog Extensions not found.")}}Xi(Ln,Ta){this._surveyManager=Ln(this._instance,Ta),this._surveyEventReceiver=new Yn(this._instance),qn.info("Surveys loaded successfully"),this.Zi({isLoaded:!0})}Qi(Ln,Ta){qn.error(Ln,Ta),this.Zi({isLoaded:!1,error:Ln})}onSurveysLoaded(Ln){return this.Yi.push(Ln),this._surveyManager&&this.Zi({isLoaded:!0}),()=>{this.Yi=this.Yi.filter((Ta=>Ta!==Ln))}}getSurveys(Ln,Ta){if(Ta===void 0&&(Ta=!1),this._instance.config.disable_surveys)return qn.info("Disabled. Not loading surveys."),Ln([]);var ja=this._instance.get_property(hi);if(ja&&!Ta)return Ln(ja,{isLoaded:!0});if(this.Ji)return Ln([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.Ji=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:La=>{var Fa;this.Ji=!1;var wl=La.statusCode;if(wl!==200||!La.json){var Pl="Surveys API could not be loaded, status: "+wl;return qn.error(Pl),Ln([],{isLoaded:!1,error:Pl})}var pc,mc=La.json.surveys||[],gc=mc.filter((Vd=>(function(Wd){return!(!Wd.start_date||Wd.end_date)})(Vd)&&((function(Wd){var kf;return!((kf=Wd.conditions)==null||(kf=kf.events)==null||(kf=kf.values)==null||!kf.length)})(Vd)||(function(Wd){var kf;return!((kf=Wd.conditions)==null||(kf=kf.actions)==null||(kf=kf.values)==null||!kf.length)})(Vd))));return gc.length>0&&((pc=this._surveyEventReceiver)==null||pc.register(gc)),(Fa=this._instance.persistence)==null||Fa.register({[hi]:mc}),Ln(mc,{isLoaded:!0})}})}catch(La){throw this.Ji=!1,La}}Zi(Ln){for(var Ta of this.Yi)try{if(!Ln.isLoaded)return Ta([],Ln);this.getSurveys(Ta)}catch(ja){qn.error("Error in survey callback",ja)}}getActiveMatchingSurveys(Ln,Ta){if(Ta===void 0&&(Ta=!1),!j$b(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(Ln,Ta);qn.warn("init was not called")}te(Ln){var Ta=null;return this.getSurveys((ja=>{var La;Ta=(La=ja.find((Fa=>Fa.id===Ln)))!==null&&La!==void 0?La:null})),Ta}ie(Ln){if(j$b(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var Ta=typeof Ln=="string"?this.te(Ln):Ln;return Ta?this._surveyManager.checkSurveyEligibility(Ta):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(Ln){if(j$b(this._surveyManager))return qn.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var Ta=this.ie(Ln);return{visible:Ta.eligible,disabledReason:Ta.reason}}canRenderSurveyAsync(Ln,Ta){return j$b(this._surveyManager)?(qn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((ja=>{this.getSurveys((La=>{var Fa,wl=(Fa=La.find((pc=>pc.id===Ln)))!==null&&Fa!==void 0?Fa:null;if(wl){var Pl=this.ie(wl);ja({visible:Pl.eligible,disabledReason:Pl.reason})}else ja({visible:!1,disabledReason:"Survey not found"})}),Ta)}))}renderSurvey(Ln,Ta){var ja;if(j$b(this._surveyManager))qn.warn("init was not called");else{var La=typeof Ln=="string"?this.te(Ln):Ln;if(La!=null&&La.id)if(Jn.includes(La.type)){var Fa=o$d?.querySelector(Ta);if(Fa)return(ja=La.appearance)!=null&&ja.surveyPopupDelaySeconds?(qn.info("Rendering survey "+La.id+" with delay of "+La.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var wl,Pl;qn.info("Rendering survey "+La.id+" with delay of "+((wl=La.appearance)==null?void 0:wl.surveyPopupDelaySeconds)+" seconds"),(Pl=this._surveyManager)==null||Pl.renderSurvey(La,Fa),qn.info("Survey "+La.id+" rendered")}),1e3*La.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(La,Fa);qn.warn("Survey element not found")}else qn.warn("Surveys of type "+La.type+" cannot be rendered in the app");else qn.warn("Survey not found")}}displaySurvey(Ln,Ta){var ja;if(j$b(this._surveyManager))qn.warn("init was not called");else{var La=this.te(Ln);if(La){var Fa=La;if((ja=La.appearance)!=null&&ja.surveyPopupDelaySeconds&&Ta.ignoreDelay&&(Fa=g$8({},La,{appearance:g$8({},La.appearance,{surveyPopupDelaySeconds:0})})),Ta.ignoreConditions===!1){var wl=this.canRenderSurvey(La);if(!wl.visible)return void qn.warn("Survey is not eligible to be displayed: ",wl.disabledReason)}Ta.displayType!==zn.Inline?this._surveyManager.handlePopoverSurvey(Fa):this.renderSurvey(Fa,Ta.selector)}else qn.warn("Survey not found")}}}var Qn=Tt$1("[RateLimiter]");class Zn{constructor(Ln){var Ta,ja;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=La=>{var Fa=La.text;if(Fa&&Fa.length)try{(JSON.parse(Fa).quota_limited||[]).forEach((wl=>{Qn.info((wl||"events")+" is quota limited."),this.serverLimits[wl]=new Date().getTime()+6e4}))}catch(wl){return void Qn.warn('could not rate limit - continuing. Error: "'+wl?.message+'"',{text:Fa})}},this.instance=Ln,this.captureEventsPerSecond=((Ta=Ln.config.rate_limiting)==null?void 0:Ta.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((ja=Ln.config.rate_limiting)==null?void 0:ja.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(Ln){var Ta,ja,La;Ln===void 0&&(Ln=!1);var Fa=new Date().getTime(),wl=(Ta=(ja=this.instance.persistence)==null?void 0:ja.get_property(pi))!==null&&Ta!==void 0?Ta:{tokens:this.captureEventsBurstLimit,last:Fa};wl.tokens+=(Fa-wl.last)/1e3*this.captureEventsPerSecond,wl.last=Fa,wl.tokens>this.captureEventsBurstLimit&&(wl.tokens=this.captureEventsBurstLimit);var Pl=wl.tokens<1;return Pl||Ln||(wl.tokens=Math.max(0,wl.tokens-1)),!Pl||this.lastEventRateLimited||Ln||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=Pl,(La=this.instance.persistence)==null||La.set_property(pi,wl),{isRateLimited:Pl,remainingTokens:wl.tokens}}isServerRateLimited(Ln){var Ta=this.serverLimits[Ln||"events"]||!1;return Ta!==!1&&new Date().getTime()<Ta}}var to=Tt$1("[RemoteConfig]");class io{constructor(Ln){this._instance=Ln}get remoteConfig(){var Ln;return(Ln=v$7._POSTHOG_REMOTE_CONFIG)==null||(Ln=Ln[this._instance.config.token])==null?void 0:Ln.config}ee(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.loadExternalDependency?(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,"remote-config",(()=>Ln(this.remoteConfig))):(to.error("PostHog Extensions not found. Cannot load remote config."),Ln())}re(Ln){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:Ta=>{Ln(Ta.json)}})}load(){try{if(this.remoteConfig)return to.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.M())return void to.warn("Remote config is disabled. Falling back to local config.");this.ee((Ln=>{if(!Ln)return to.info("No config found after loading remote JS config. Falling back to JSON."),void this.re((Ta=>{this.fi(Ta)}));this.fi(Ln)}))}catch(Ln){to.error("Error loading remote config",Ln)}}fi(Ln){Ln?this._instance.config.__preview_remote_config?(this._instance.fi(Ln),Ln.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):to.info("__preview_remote_config is disabled. Logging config instead",Ln):to.error("Failed to fetch remote config from PostHog.")}}var eo=3e3;class ro{constructor(Ln,Ta){this.se=!0,this.ne=[],this.oe=J$5(Ta?.flush_interval_ms||eo,250,5e3,Pt$2.createLogger("flush interval"),eo),this.ae=Ln}enqueue(Ln){this.ne.push(Ln),this.le||this.ue()}unload(){this.he();var Ln=this.ne.length>0?this.de():{},Ta=Object.values(Ln);[...Ta.filter((ja=>ja.url.indexOf("/e")===0)),...Ta.filter((ja=>ja.url.indexOf("/e")!==0))].map((ja=>{this.ae(g$8({},ja,{transport:"sendBeacon"}))}))}enable(){this.se=!1,this.ue()}ue(){var Ln=this;this.se||(this.le=setTimeout((()=>{if(this.he(),this.ne.length>0){var Ta=this.de(),ja=function(){var Fa=Ta[La],wl=new Date().getTime();Fa.data&&I$9(Fa.data)&&Ot(Fa.data,(Pl=>{Pl.offset=Math.abs(Pl.timestamp-wl),delete Pl.timestamp})),Ln.ae(Fa)};for(var La in Ta)ja()}}),this.oe))}he(){clearTimeout(this.le),this.le=void 0}de(){var Ln={};return Ot(this.ne,(Ta=>{var ja,La=Ta,Fa=(La?La.batchKey:null)||La.url;O$6(Ln[Fa])&&(Ln[Fa]=g$8({},La,{data:[]})),(ja=Ln[Fa].data)==null||ja.push(La.data)})),this.ne=[],Ln}}var so=["retriesPerformedSoFar"];class no{constructor(Ln){this.ve=!1,this.ce=3e3,this.ne=[],this._instance=Ln,this.ne=[],this.fe=!0,!O$6(t$9)&&"onLine"in t$9.navigator&&(this.fe=t$9.navigator.onLine,this.pe=()=>{this.fe=!0,this.Dt()},this.ge=()=>{this.fe=!1},qt(t$9,"online",this.pe),qt(t$9,"offline",this.ge))}get length(){return this.ne.length}retriableRequest(Ln){var{retriesPerformedSoFar:Ta}=Ln,ja=_$8(Ln,so);L$6(Ta)&&Ta>0&&(ja.url=un$1(ja.url,{retry_count:Ta})),this._instance.ci(g$8({},ja,{callback:La=>{La.statusCode!==200&&(La.statusCode<400||La.statusCode>=500)&&(Ta??0)<10?this._e(g$8({retriesPerformedSoFar:Ta},ja)):ja.callback==null||ja.callback(La)}}))}_e(Ln){var Ta=Ln.retriesPerformedSoFar||0;Ln.retriesPerformedSoFar=Ta+1;var ja=(function(wl){var Pl=3e3*Math.pow(2,wl),pc=Pl/2,mc=Math.min(18e5,Pl),gc=(Math.random()-.5)*(mc-pc);return Math.ceil(mc+gc)})(Ta),La=Date.now()+ja;this.ne.push({retryAt:La,requestOptions:Ln});var Fa="Enqueued failed request for retry in "+ja;navigator.onLine||(Fa+=" (Browser is offline)"),Pt$2.warn(Fa),this.ve||(this.ve=!0,this.me())}me(){if(this.ye&&clearTimeout(this.ye),this.ne.length===0)return this.ve=!1,void(this.ye=void 0);this.ye=setTimeout((()=>{this.fe&&this.ne.length>0&&this.Dt(),this.me()}),this.ce)}Dt(){var Ln=Date.now(),Ta=[],ja=this.ne.filter((Fa=>Fa.retryAt<Ln||(Ta.push(Fa),!1)));if(this.ne=Ta,ja.length>0)for(var{requestOptions:La}of ja)this.retriableRequest(La)}unload(){for(var{requestOptions:Ln}of(this.ye&&(clearTimeout(this.ye),this.ye=void 0),this.ve=!1,O$6(t$9)||(this.pe&&(t$9.removeEventListener("online",this.pe),this.pe=void 0),this.ge&&(t$9.removeEventListener("offline",this.ge),this.ge=void 0)),this.ne))try{this._instance.ci(g$8({},Ln,{transport:"sendBeacon"}))}catch(Ta){Pt$2.error(Ta)}this.ne=[]}}class oo{constructor(Ln){this.be=()=>{var Ta,ja,La,Fa;this.we||(this.we={});var wl=this.scrollElement(),Pl=this.scrollY(),pc=wl?Math.max(0,wl.scrollHeight-wl.clientHeight):0,mc=Pl+(wl?.clientHeight||0),gc=wl?.scrollHeight||0;this.we.lastScrollY=Math.ceil(Pl),this.we.maxScrollY=Math.max(Pl,(Ta=this.we.maxScrollY)!==null&&Ta!==void 0?Ta:0),this.we.maxScrollHeight=Math.max(pc,(ja=this.we.maxScrollHeight)!==null&&ja!==void 0?ja:0),this.we.lastContentY=mc,this.we.maxContentY=Math.max(mc,(La=this.we.maxContentY)!==null&&La!==void 0?La:0),this.we.maxContentHeight=Math.max(gc,(Fa=this.we.maxContentHeight)!==null&&Fa!==void 0?Fa:0)},this._instance=Ln}getContext(){return this.we}resetContext(){var Ln=this.we;return setTimeout(this.be,0),Ln}startMeasuringScrollPosition(){qt(t$9,"scroll",this.be,{capture:!0}),qt(t$9,"scrollend",this.be,{capture:!0}),qt(t$9,"resize",this.be)}scrollElement(){if(!this._instance.config.scroll_root_selector)return t$9?.document.documentElement;var Ln=I$9(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var Ta of Ln){var ja=t$9?.document.querySelector(Ta);if(ja)return ja}}scrollY(){if(this._instance.config.scroll_root_selector){var Ln=this.scrollElement();return Ln&&Ln.scrollTop||0}return t$9&&(t$9.scrollY||t$9.pageYOffset||t$9.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var Ln=this.scrollElement();return Ln&&Ln.scrollLeft||0}return t$9&&(t$9.scrollX||t$9.pageXOffset||t$9.document.documentElement.scrollLeft)||0}}var ao=ta=>cs(ta?.config.mask_personal_data_properties,ta?.config.custom_personal_data_properties);let lo$1=class{constructor(Ln,Ta,ja,La){this.xe=Fa=>{var wl=this.$e();if(!wl||wl.sessionId!==Fa){var Pl={sessionId:Fa,props:this.Ee(this._instance)};this.Se.register({[fi]:Pl})}},this._instance=Ln,this.ke=Ta,this.Se=ja,this.Ee=La||ao,this.ke.onSessionId(this.xe)}$e(){return this.Se.props[fi]}getSetOnceProps(){var Ln,Ta=(Ln=this.$e())==null?void 0:Ln.props;return Ta?"r"in Ta?fs(Ta):{$referring_domain:Ta.referringDomain,$pathname:Ta.initialPathName,utm_source:Ta.utm_source,utm_campaign:Ta.utm_campaign,utm_medium:Ta.utm_medium,utm_content:Ta.utm_content,utm_term:Ta.utm_term}:{}}getSessionProps(){var Ln={};return Ot(Nt(this.getSetOnceProps()),((Ta,ja)=>{ja==="$current_url"&&(ja="url"),Ln["$session_entry_"+E$8(ja)]=Ta})),Ln}};var uo=Tt$1("[SessionId]");class ho{on(Ln,Ta){return this.Pe.on(Ln,Ta)}constructor(Ln,Ta,ja){var La;if(this.Te=[],this.Ie=void 0,this.Pe=new Hn,this.Re=(gc,Vd)=>Math.abs(gc-Vd)>this.sessionTimeoutMs,!Ln.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(Ln.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.F=Ln.config,this.Se=Ln.persistence,this.Fe=void 0,this.Ce=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Oe=Ta||Se$2,this.Me=ja||Se$2;var Fa=this.F.persistence_name||this.F.token,wl=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*J$5(wl,60,36e3,uo.createLogger("session_idle_timeout_seconds"),1800),Ln.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Ae(),this.De="ph_"+Fa+"_window_id",this.je="ph_"+Fa+"_primary_window_exists",this.Le()){var Pl=Le$1.W(this.De),pc=Le$1.W(this.je);Pl&&!pc?this.Fe=Pl:Le$1.V(this.De),Le$1.G(this.je,!0)}if((La=this.F.bootstrap)!=null&&La.sessionID)try{var mc=(gc=>{var Vd=gc.replace(/-/g,"");if(Vd.length!==32)throw new Error("Not a valid UUID");if(Vd[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(Vd.substring(0,12),16)})(this.F.bootstrap.sessionID);this.Ne(this.F.bootstrap.sessionID,new Date().getTime(),mc)}catch(gc){uo.error("Invalid sessionID in bootstrap",gc)}this.Ue()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(Ln){return O$6(this.Te)&&(this.Te=[]),this.Te.push(Ln),this.Ce&&Ln(this.Ce,this.Fe),()=>{this.Te=this.Te.filter((Ta=>Ta!==Ln))}}Le(){return this.F.persistence!=="memory"&&!this.Se.wi&&Le$1.H()}ze(Ln){Ln!==this.Fe&&(this.Fe=Ln,this.Le()&&Le$1.G(this.De,Ln))}He(){return this.Fe?this.Fe:this.Le()?Le$1.W(this.De):null}Ne(Ln,Ta,ja){Ln===this.Ce&&Ta===this._sessionActivityTimestamp&&ja===this._sessionStartTimestamp||(this._sessionStartTimestamp=ja,this._sessionActivityTimestamp=Ta,this.Ce=Ln,this.Se.register({[ri]:[Ta,Ln,ja]}))}Be(){if(this.Ce&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this.Ce,this._sessionStartTimestamp];var Ln=this.Se.props[ri];return I$9(Ln)&&Ln.length===2&&Ln.push(Ln[0]),Ln||[0,null,0]}resetSessionId(){this.Ne(null,null,null)}destroy(){clearTimeout(this.qe),this.qe=void 0,this.Ie&&t$9&&(t$9.removeEventListener("beforeunload",this.Ie,{capture:!1}),this.Ie=void 0),this.Te=[]}Ue(){this.Ie=()=>{this.Le()&&Le$1.V(this.je)},qt(t$9,"beforeunload",this.Ie,{capture:!1})}checkAndGetSessionAndWindowId(Ln,Ta){if(Ln===void 0&&(Ln=!1),Ta===void 0&&(Ta=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var ja=Ta||new Date().getTime(),[La,Fa,wl]=this.Be(),Pl=this.He(),pc=L$6(wl)&&wl>0&&Math.abs(ja-wl)>864e5,mc=!1,gc=!Fa,Vd=!gc&&!Ln&&this.Re(ja,La);gc||Vd||pc?(Fa=this.Oe(),Pl=this.Me(),uo.info("new session ID generated",{sessionId:Fa,windowId:Pl,changeReason:{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}}),wl=ja,mc=!0):Pl||(Pl=this.Me(),mc=!0);var Wd=La===0||!Ln||pc?ja:La,kf=wl===0?new Date().getTime():wl;return this.ze(Pl),this.Ne(Fa,Wd,kf),Ln||this.Ae(),mc&&this.Te.forEach((Pf=>Pf(Fa,Pl,mc?{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}:void 0))),{sessionId:Fa,windowId:Pl,sessionStartTimestamp:kf,changeReason:mc?{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}:void 0,lastActivityTimestamp:La}}Ae(){clearTimeout(this.qe),this.qe=setTimeout((()=>{var[Ln]=this.Be();if(this.Re(new Date().getTime(),Ln)){var Ta=this.Ce;this.resetSessionId(),this.Pe.emit("forcedIdleReset",{idleSessionId:Ta})}}),1.1*this.sessionTimeoutMs)}}var vo=["$set_once","$set"],co=Tt$1("[SiteApps]");class fo{constructor(Ln){this._instance=Ln,this.We=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Ge(Ln,Ta){if(Ta){var ja=this.globalsForEvent(Ta);this.We.push(ja),this.We.length>1e3&&(this.We=this.We.slice(10))}}get siteAppLoaders(){var Ln;return(Ln=v$7._POSTHOG_REMOTE_CONFIG)==null||(Ln=Ln[this._instance.config.token])==null?void 0:Ln.siteApps}init(){if(this.isEnabled){var Ln=this._instance.Mi(this.Ge.bind(this));this.Ve=()=>{Ln(),this.We=[],this.Ve=void 0}}}globalsForEvent(Ln){var Ta,ja,La,Fa,wl,Pl,pc;if(!Ln)throw new Error("Event payload is required");var mc={},gc=this._instance.get_property("$groups")||[],Vd=this._instance.get_property("$stored_group_properties")||{};for(var[Wd,kf]of Object.entries(Vd))mc[Wd]={id:gc[Wd],type:Wd,properties:kf};var{$set_once:Pf,$set:Nf}=Ln;return{event:g$8({},_$8(Ln,vo),{properties:g$8({},Ln.properties,Nf?{$set:g$8({},(Ta=(ja=Ln.properties)==null?void 0:ja.$set)!==null&&Ta!==void 0?Ta:{},Nf)}:{},Pf?{$set_once:g$8({},(La=(Fa=Ln.properties)==null?void 0:Fa.$set_once)!==null&&La!==void 0?La:{},Pf)}:{}),elements_chain:(wl=(Pl=Ln.properties)==null?void 0:Pl.$elements_chain)!==null&&wl!==void 0?wl:"",distinct_id:(pc=Ln.properties)==null?void 0:pc.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:mc}}setupSiteApp(Ln){var Ta=this.apps[Ln.id],ja=()=>{var Pl;!Ta.errored&&this.We.length&&(co.info("Processing "+this.We.length+" events for site app with id "+Ln.id),this.We.forEach((pc=>Ta.processEvent==null?void 0:Ta.processEvent(pc))),Ta.processedBuffer=!0),Object.values(this.apps).every((pc=>pc.processedBuffer||pc.errored))&&((Pl=this.Ve)==null||Pl.call(this))},La=!1,Fa=Pl=>{Ta.errored=!Pl,Ta.loaded=!0,co.info("Site app with id "+Ln.id+" "+(Pl?"loaded":"errored")),La&&ja()};try{var{processEvent:wl}=Ln.init({posthog:this._instance,callback:Pl=>{Fa(Pl)}});wl&&(Ta.processEvent=wl),La=!0}catch(Pl){co.error("Error while initializing PostHog app with config id "+Ln.id,Pl),Fa(!1)}if(La&&Ta.loaded)try{ja()}catch(Pl){co.error("Error while processing buffered events PostHog app with config id "+Ln.id,Pl),Ta.errored=!0}}Je(){var Ln=this.siteAppLoaders||[];for(var Ta of Ln)this.apps[Ta.id]={id:Ta.id,loaded:!1,errored:!1,processedBuffer:!1};for(var ja of Ln)this.setupSiteApp(ja)}Ke(Ln){if(Object.keys(this.apps).length!==0){var Ta=this.globalsForEvent(Ln);for(var ja of Object.values(this.apps))try{ja.processEvent==null||ja.processEvent(Ta)}catch(La){co.error("Error while processing event "+Ln.event+" for site app "+ja.id,La)}}}onRemoteConfig(Ln){var Ta,ja,La,Fa=this;if((Ta=this.siteAppLoaders)!=null&&Ta.length)return this.isEnabled?(this.Je(),void this._instance.on("eventCaptured",(mc=>this.Ke(mc)))):void co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((ja=this.Ve)==null||ja.call(this),(La=Ln.siteApps)!=null&&La.length)if(this.isEnabled){var wl=function(mc){var gc;v$7["__$$ph_site_app_"+mc]=Fa._instance,(gc=v$7.__PosthogExtensions__)==null||gc.loadSiteApp==null||gc.loadSiteApp(Fa._instance,pc,(Vd=>{if(Vd)return co.error("Error while initializing PostHog app with config id "+mc,Vd)}))};for(var{id:Pl,url:pc}of Ln.siteApps)wl(Pl)}else co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var po=function(ta,Ln){if(!ta)return!1;var Ta=ta.userAgent;if(Ta&&y$a(Ta,Ln))return!0;try{var ja=ta?.userAgentData;if(ja!=null&&ja.brands&&ja.brands.some((La=>y$a(La?.brand,Ln))))return!0}catch{}return!!ta.webdriver},go=(function(ta){return ta.US="us",ta.EU="eu",ta.CUSTOM="custom",ta})({}),_o="i.posthog.com";class mo{constructor(Ln){this.Ye={},this.instance=Ln}get apiHost(){var Ln=this.instance.config.api_host.trim().replace(/\/$/,"");return Ln==="https://app.posthog.com"?"https://us.i.posthog.com":Ln}get flagsApiHost(){var Ln=this.instance.config.flags_api_host;return Ln?Ln.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var Ln,Ta=(Ln=this.instance.config.ui_host)==null?void 0:Ln.replace(/\/$/,"");return Ta||(Ta=this.apiHost.replace("."+_o,".posthog.com")),Ta==="https://app.posthog.com"?"https://us.posthog.com":Ta}get region(){return this.Ye[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=go.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=go.EU:this.Ye[this.apiHost]=go.CUSTOM),this.Ye[this.apiHost]}endpointFor(Ln,Ta){if(Ta===void 0&&(Ta=""),Ta&&(Ta=Ta[0]==="/"?Ta:"/"+Ta),Ln==="ui")return this.uiHost+Ta;if(Ln==="flags")return this.flagsApiHost+Ta;if(this.region===go.CUSTOM)return this.apiHost+Ta;var ja=_o+Ta;switch(Ln){case"assets":return"https://"+this.region+"-assets."+ja;case"api":return"https://"+this.region+"."+ja}}}var yo={icontains:(ta,Ln)=>!!t$9&&Ln.href.toLowerCase().indexOf(ta.toLowerCase())>-1,not_icontains:(ta,Ln)=>!!t$9&&Ln.href.toLowerCase().indexOf(ta.toLowerCase())===-1,regex:(ta,Ln)=>!!t$9&&cn$1(Ln.href,ta),not_regex:(ta,Ln)=>!!t$9&&!cn$1(Ln.href,ta),exact:(ta,Ln)=>Ln.href===ta,is_not:(ta,Ln)=>Ln.href!==ta};class bo{constructor(Ln){var Ta=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(ja){ja===void 0&&(ja=!1),Ta.getWebExperiments((La=>{bo.Xe("retrieved web experiments from the server"),Ta.Qe=new Map,La.forEach((Fa=>{if(Fa.feature_flag_key){var wl;Ta.Qe&&(bo.Xe("setting flag key ",Fa.feature_flag_key," to web experiment ",Fa),(wl=Ta.Qe)==null||wl.set(Fa.feature_flag_key,Fa));var Pl=Ta._instance.getFeatureFlag(Fa.feature_flag_key);M$7(Pl)&&Fa.variants[Pl]&&Ta.Ze(Fa.name,Pl,Fa.variants[Pl].transforms)}else if(Fa.variants)for(var pc in Fa.variants){var mc=Fa.variants[pc];bo.tr(mc)&&Ta.Ze(Fa.name,pc,mc.transforms)}}))}),ja)},this._instance=Ln,this._instance.onFeatureFlags((ja=>{this.onFeatureFlags(ja)}))}onFeatureFlags(Ln){if(this._is_bot())bo.Xe("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(j$b(this.Qe))return this.Qe=new Map,this.loadIfEnabled(),void this.previewWebExperiment();bo.Xe("applying feature flags",Ln),Ln.forEach((Ta=>{var ja;if(this.Qe&&(ja=this.Qe)!=null&&ja.has(Ta)){var La,Fa=this._instance.getFeatureFlag(Ta),wl=(La=this.Qe)==null?void 0:La.get(Ta);Fa&&wl!=null&&wl.variants[Fa]&&this.Ze(wl.name,Fa,wl.variants[Fa].transforms)}}))}}previewWebExperiment(){var Ln=bo.getWindowLocation();if(Ln!=null&&Ln.search){var Ta=he$3(Ln?.search,"__experiment_id"),ja=he$3(Ln?.search,"__experiment_variant");Ta&&ja&&(bo.Xe("previewing web experiments "+Ta+" && "+ja),this.getWebExperiments((La=>{this.ir(parseInt(Ta),ja,La)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(Ln,Ta,ja){if(this._instance.config.disable_web_experiments&&!ja)return Ln([]);var La=this._instance.get_property("$web_experiments");if(La&&!Ta)return Ln(La);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:Fa=>{if(Fa.statusCode!==200||!Fa.json)return Ln([]);var wl=Fa.json.experiments||[];return Ln(wl)}})}ir(Ln,Ta,ja){var La=ja.filter((Fa=>Fa.id===Ln));La&&La.length>0&&(bo.Xe("Previewing web experiment ["+La[0].name+"] with variant ["+Ta+"]"),this.Ze(La[0].name,Ta,La[0].variants[Ta].transforms))}static tr(Ln){return!j$b(Ln.conditions)&&bo.er(Ln)&&bo.rr(Ln)}static er(Ln){var Ta;if(j$b(Ln.conditions)||j$b((Ta=Ln.conditions)==null?void 0:Ta.url))return!0;var ja,La,Fa,wl=bo.getWindowLocation();return!!wl&&((ja=Ln.conditions)==null||!ja.url||yo[(La=(Fa=Ln.conditions)==null?void 0:Fa.urlMatchType)!==null&&La!==void 0?La:"icontains"](Ln.conditions.url,wl))}static getWindowLocation(){return t$9?.location}static rr(Ln){var Ta;if(j$b(Ln.conditions)||j$b((Ta=Ln.conditions)==null?void 0:Ta.utm))return!0;var ja=ls();if(ja.utm_source){var La,Fa,wl,Pl,pc,mc,gc,Vd,Wd=(La=Ln.conditions)==null||(La=La.utm)==null||!La.utm_campaign||((Fa=Ln.conditions)==null||(Fa=Fa.utm)==null?void 0:Fa.utm_campaign)==ja.utm_campaign,kf=(wl=Ln.conditions)==null||(wl=wl.utm)==null||!wl.utm_source||((Pl=Ln.conditions)==null||(Pl=Pl.utm)==null?void 0:Pl.utm_source)==ja.utm_source,Pf=(pc=Ln.conditions)==null||(pc=pc.utm)==null||!pc.utm_medium||((mc=Ln.conditions)==null||(mc=mc.utm)==null?void 0:mc.utm_medium)==ja.utm_medium,Nf=(gc=Ln.conditions)==null||(gc=gc.utm)==null||!gc.utm_term||((Vd=Ln.conditions)==null||(Vd=Vd.utm)==null?void 0:Vd.utm_term)==ja.utm_term;return Wd&&Pf&&Nf&&kf}return!1}static Xe(Ln){for(var Ta=arguments.length,ja=new Array(Ta>1?Ta-1:0),La=1;La<Ta;La++)ja[La-1]=arguments[La];Pt$2.info("[WebExperiments] "+Ln,ja)}Ze(Ln,Ta,ja){this._is_bot()?bo.Xe("Refusing to render web experiment since the viewer is a likely bot"):Ta!=="control"?ja.forEach((La=>{if(La.selector){var Fa;bo.Xe("applying transform of variant "+Ta+" for experiment "+Ln+" ",La);var wl=(Fa=document)==null?void 0:Fa.querySelectorAll(La.selector);wl?.forEach((Pl=>{var pc=Pl;La.html&&(pc.innerHTML=La.html),La.css&&pc.setAttribute("style",La.css)}))}})):bo.Xe("Control variants leave the page unmodified.")}_is_bot(){return n$9&&this._instance?po(n$9,this._instance.config.custom_blocked_useragents):void 0}}var wo=Tt$1("[PostHog ExternalIntegrations]"),xo={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class $o{constructor(Ln){this._instance=Ln}it(Ln,Ta){var ja;(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,Ln,(La=>{if(La)return wo.error("failed to load script",La);Ta()}))}startIfEnabledOrStop(){var Ln=this,Ta=function(wl){var Pl,pc,mc;!La||(Pl=v$7.__PosthogExtensions__)!=null&&(Pl=Pl.integrations)!=null&&Pl[wl]||Ln.it(xo[wl],(()=>{var gc;(gc=v$7.__PosthogExtensions__)==null||(gc=gc.integrations)==null||(gc=gc[wl])==null||gc.start(Ln._instance)})),!La&&(pc=v$7.__PosthogExtensions__)!=null&&(pc=pc.integrations)!=null&&pc[wl]&&((mc=v$7.__PosthogExtensions__)==null||(mc=mc.integrations)==null||(mc=mc[wl])==null||mc.stop())};for(var[ja,La]of Object.entries((Fa=this._instance.config.integrations)!==null&&Fa!==void 0?Fa:{})){var Fa;Ta(ja)}}}var Eo="[SessionRecording]",So=Tt$1(Eo);class ko{get started(){var Ln;return!((Ln=this.sr)==null||!Ln.isStarted)}get status(){return this.sr?this.sr.status:this.nr&&!this.ar?"disabled":"lazy_loading"}constructor(Ln){if(this._forceAllowLocalhostNetworkCapture=!1,this.nr=!1,this.lr=void 0,this._instance=Ln,!this._instance.sessionManager)throw So.error("started without valid sessionManager"),new Error(Eo+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Eo+' cannot be used with cookieless_mode="always"')}get ar(){var Ln,Ta=!((Ln=this._instance.get_property(ei))==null||!Ln.enabled),ja=!this._instance.config.disable_session_recording,La=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return t$9&&Ta&&ja&&!La}startIfEnabledOrStop(Ln){var Ta;if(!this.ar||(Ta=this.sr)==null||!Ta.isStarted){var ja=!O$6(Object.assign)&&!O$6(Array.from);this.ar&&ja?(this.ur(Ln),So.info("starting")):this.stopRecording()}}ur(Ln){var Ta,ja,La;this.ar&&(v$7!=null&&(Ta=v$7.__PosthogExtensions__)!=null&&(Ta=Ta.rrweb)!=null&&Ta.record&&(ja=v$7.__PosthogExtensions__)!=null&&ja.initSessionRecording?this.hr(Ln):(La=v$7.__PosthogExtensions__)==null||La.loadExternalDependency==null||La.loadExternalDependency(this._instance,this.dr,(Fa=>{if(Fa)return So.error("could not load recorder",Fa);this.hr(Ln)})))}stopRecording(){var Ln,Ta;(Ln=this.lr)==null||Ln.call(this),this.lr=void 0,(Ta=this.sr)==null||Ta.stop()}vr(){var Ln;(Ln=this._instance.persistence)==null||Ln.unregister(si)}cr(Ln){if(this._instance.persistence){var Ta,ja,La=this._instance.persistence,Fa=()=>{var wl=Ln.sessionRecording===!1?void 0:Ln.sessionRecording,Pl=wl?.sampleRate,pc=j$b(Pl)?null:parseFloat(Pl);j$b(pc)&&this.vr();var mc=wl?.minimumDurationMilliseconds;La.register({[ei]:g$8({enabled:!!wl},wl,{networkPayloadCapture:g$8({capturePerformance:Ln.capturePerformance},wl?.networkPayloadCapture),canvasRecording:{enabled:wl?.recordCanvas,fps:wl?.canvasFps,quality:wl?.canvasQuality},sampleRate:pc,minimumDurationMilliseconds:O$6(mc)?null:mc,endpoint:wl?.endpoint,triggerMatchType:wl?.triggerMatchType,masking:wl?.masking,urlTriggers:wl?.urlTriggers})})};Fa(),(Ta=this.lr)==null||Ta.call(this),this.lr=(ja=this._instance.sessionManager)==null?void 0:ja.onSessionId(Fa)}}onRemoteConfig(Ln){"sessionRecording"in Ln?Ln.sessionRecording!==!1?(this.cr(Ln),this.nr=!0,this.startIfEnabledOrStop()):this.nr=!0:So.info("skipping remote config with no sessionRecording",Ln)}log(Ln,Ta){var ja;Ta===void 0&&(Ta="log"),(ja=this.sr)!=null&&ja.log?this.sr.log(Ln,Ta):So.warn("log called before recorder was ready")}get dr(){var Ln,Ta,ja=(Ln=this._instance)==null||(Ln=Ln.persistence)==null?void 0:Ln.get_property(ei);return(ja==null||(Ta=ja.scriptConfig)==null?void 0:Ta.script)||"lazy-recorder"}hr(Ln){var Ta,ja;if((Ta=v$7.__PosthogExtensions__)==null||!Ta.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.sr||(this.sr=(ja=v$7.__PosthogExtensions__)==null?void 0:ja.initSessionRecording(this._instance),this.sr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.sr.start(Ln)}onRRwebEmit(Ln){var Ta;(Ta=this.sr)==null||Ta.onRRwebEmit==null||Ta.onRRwebEmit(Ln)}overrideLinkedFlag(){var Ln,Ta;this.sr||(Ta=this._instance.persistence)==null||Ta.register({$replay_override_linked_flag:!0}),(Ln=this.sr)==null||Ln.overrideLinkedFlag()}overrideSampling(){var Ln,Ta;this.sr||(Ta=this._instance.persistence)==null||Ta.register({$replay_override_sampling:!0}),(Ln=this.sr)==null||Ln.overrideSampling()}overrideTrigger(Ln){var Ta,ja;this.sr||(ja=this._instance.persistence)==null||ja.register({[Ln==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(Ta=this.sr)==null||Ta.overrideTrigger(Ln)}get sdkDebugProperties(){var Ln;return((Ln=this.sr)==null?void 0:Ln.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(Ln,Ta){var ja;return!((ja=this.sr)==null||!ja.tryAddCustomEvent(Ln,Ta))}}var Po={},To=()=>{},Io="posthog",Ro=!an$1&&d$6?.indexOf("MSIE")===-1&&d$6?.indexOf("Mozilla")===-1,Fo=ta=>{var Ln;return g$8({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ht(o$d?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:To,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:ta??"unset",__preview_deferred_init_extensions:!1,debug:a$i&&M$7(a$i?.search)&&a$i.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_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(t$9==null||(Ln=t$9.location)==null?void 0:Ln.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_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:Ta=>{var ja="Bad HTTP status: "+Ta.statusCode+" "+Ta.text;Pt$2.error(ja)},get_device_id:Ta=>Ta,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:eo},error_tracking:{},_onCapture:To,__preview_eager_load_replay:!1},(Ta=>({rageclick:!(Ta&&Ta>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(Ta&&Ta>="2025-05-24")||"history_change",session_recording:Ta&&Ta>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(ta))},Co=ta=>{var Ln={};O$6(ta.process_person)||(Ln.person_profiles=ta.process_person),O$6(ta.xhr_headers)||(Ln.request_headers=ta.xhr_headers),O$6(ta.cookie_name)||(Ln.persistence_name=ta.cookie_name),O$6(ta.disable_cookie)||(Ln.disable_persistence=ta.disable_cookie),O$6(ta.store_google)||(Ln.save_campaign_params=ta.store_google),O$6(ta.verbose)||(Ln.debug=ta.verbose);var Ta=Mt$2({},Ln,ta);return I$9(ta.property_blacklist)&&(O$6(ta.property_denylist)?Ta.property_denylist=ta.property_blacklist:I$9(ta.property_denylist)?Ta.property_denylist=[...ta.property_blacklist,...ta.property_denylist]:Pt$2.error("Invalid value for property_denylist config: "+ta.property_denylist)),Ta};class Oo{constructor(){this.__forceAllowLocalhost=!1}get pr(){return this.__forceAllowLocalhost}set pr(Ln){Pt$2.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=Ln}}let Mo$1=class AUe{get decideEndpointWasHit(){var Ln,Ta;return(Ln=(Ta=this.featureFlags)==null?void 0:Ta.hasLoadedFlags)!==null&&Ln!==void 0&&Ln}get flagsEndpointWasHit(){var Ln,Ta;return(Ln=(Ta=this.featureFlags)==null?void 0:Ta.hasLoadedFlags)!==null&&Ln!==void 0&&Ln}constructor(){this.webPerformance=new Oo,this.gr=!1,this.version=c$e.LIB_VERSION,this._r=new Hn,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Fo(),this.SentryIntegration=Ze$1,this.sentryIntegration=Ln=>(function(Ta,ja){var La=Qe(Ta,ja);return{name:Xe,processEvent:Fa=>La(Fa)}})(this,Ln),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.mr=!1,this.yr=null,this.br=null,this.wr=null,this.featureFlags=new In(this),this.toolbar=new sr(this),this.scrollManager=new oo(this),this.pageViewManager=new Es(this),this.surveys=new Xn(this),this.experiments=new bo(this),this.exceptions=new mn(this),this.rateLimiter=new Zn(this),this.requestRouter=new mo(this),this.consent=new Ue$1(this),this.externalIntegrations=new $o(this),this.people={set:(Ln,Ta,ja)=>{var La=M$7(Ln)?{[Ln]:Ta}:Ln;this.setPersonProperties(La),ja?.({})},set_once:(Ln,Ta,ja)=>{var La=M$7(Ln)?{[Ln]:Ta}:Ln;this.setPersonProperties(void 0,La),ja?.({})}},this.on("eventCaptured",(Ln=>Pt$2.info('send "'+Ln?.event+'"',Ln)))}init(Ln,Ta,ja){if(ja&&ja!==Io){var La,Fa=(La=Po[ja])!==null&&La!==void 0?La:new AUe;return Fa._init(Ln,Ta,ja),Po[ja]=Fa,Po[Io][ja]=Fa,Fa}return this._init(Ln,Ta,ja)}_init(Ln,Ta,ja){var La;if(Ta===void 0&&(Ta={}),O$6(Ln)||A$8(Ln))return Pt$2.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={},Ta.debug=this.$r(Ta.debug),this.Er=Ta,this.Sr=[],Ta.person_profiles&&(this.br=Ta.person_profiles),this.set_config(Mt$2({},Fo(Ta.defaults),Co(Ta),{name:ja,token:Ln})),this.config.on_xhr_error&&Pt$2.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=Ta.disable_compression?void 0:oe$2.GZipJS;var Fa=this.kr();this.persistence=new Fn(this.config,Fa),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fn(g$8({},this.config,{persistence:"sessionStorage"}),Fa);var wl=g$8({},this.persistence.props),Pl=g$8({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Pr=new ro((qg=>this.Tr(qg)),this.config.request_queue_config),this.Ir=new no(this),this.__request_queue=[];var pc=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(pc||(this.sessionManager=new ho(this),this.sessionPropsManager=new lo$1(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Pt$2.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Rr(pc)}),0)):(Pt$2.info("Initializing extensions synchronously"),this.Rr(pc)),c$e.DEBUG=c$e.DEBUG||this.config.debug,c$e.DEBUG&&Pt$2.info("Starting in debug mode",{this:this,config:Ta,thisC:g$8({},this.config),p:wl,s:Pl}),((La=Ta.bootstrap)==null?void 0:La.distinctID)!==void 0){var mc,gc,Vd=this.config.get_device_id(Se$2()),Wd=(mc=Ta.bootstrap)!=null&&mc.isIdentifiedID?Vd:Ta.bootstrap.distinctID;this.persistence.set_property(ci,(gc=Ta.bootstrap)!=null&&gc.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:Ta.bootstrap.distinctID,$device_id:Wd})}if(this.Fr()){var kf,Pf,Nf=Object.keys(((kf=Ta.bootstrap)==null?void 0:kf.featureFlags)||{}).filter((qg=>{var Ug;return!((Ug=Ta.bootstrap)==null||(Ug=Ug.featureFlags)==null||!Ug[qg])})).reduce(((qg,Ug)=>{var Bg;return qg[Ug]=((Bg=Ta.bootstrap)==null||(Bg=Bg.featureFlags)==null?void 0:Bg[Ug])||!1,qg}),{}),Eh=Object.keys(((Pf=Ta.bootstrap)==null?void 0:Pf.featureFlagPayloads)||{}).filter((qg=>Nf[qg])).reduce(((qg,Ug)=>{var Bg,U_;return(Bg=Ta.bootstrap)!=null&&(Bg=Bg.featureFlagPayloads)!=null&&Bg[Ug]&&(qg[Ug]=(U_=Ta.bootstrap)==null||(U_=U_.featureFlagPayloads)==null?void 0:U_[Ug]),qg}),{});this.featureFlags.receivedFeatureFlags({featureFlags:Nf,featureFlagPayloads:Eh})}if(pc)this.register_once({distinct_id:wi,$device_id:null},"");else if(!this.get_distinct_id()){var Em=this.config.get_device_id(Se$2());this.register_once({distinct_id:Em,$device_id:Em},""),this.persistence.set_property(ci,"anonymous")}return qt(t$9,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),Ta.segment?Ye(this,(()=>this.Cr())):this.Cr(),R$3(this.config._onCapture)&&this.config._onCapture!==To&&(Pt$2.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(qg=>this.config._onCapture(qg.event,qg)))),this.config.ip&&Pt$2.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}Rr(Ln){var Ta=performance.now();this.historyAutocapture=new Je(this),this.historyAutocapture.startIfEnabled();var ja=[];ja.push((()=>{new or(this).startIfEnabledOrStop()})),ja.push((()=>{var La;this.siteApps=new fo(this),(La=this.siteApps)==null||La.init()})),Ln||ja.push((()=>{this.sessionRecording=new ko(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||ja.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),ja.push((()=>{this.autocapture=new me$2(this),this.autocapture.startIfEnabled()})),ja.push((()=>{this.surveys.loadIfEnabled()})),ja.push((()=>{this.heatmaps=new $s(this),this.heatmaps.startIfEnabled()})),ja.push((()=>{this.webVitalsAutocapture=new bs(this)})),ja.push((()=>{this.exceptionObserver=new Ge$1(this),this.exceptionObserver.startIfEnabled()})),ja.push((()=>{this.deadClicksAutocapture=new qe(this,Be$1),this.deadClicksAutocapture.startIfEnabled()})),ja.push((()=>{if(this.Or){var La=this.Or;this.Or=void 0,this.fi(La)}})),this.Mr(ja,Ta)}Mr(Ln,Ta){for(;Ln.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-Ta>=30&&Ln.length>0)return void setTimeout((()=>{this.Mr(Ln,Ta)}),0);var ja=Ln.shift();if(ja)try{ja()}catch(Fa){Pt$2.error("Error initializing extension:",Fa)}}var La=Math.round(performance.now()-Ta);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:La}),this.config.__preview_deferred_init_extensions&&Pt$2.info("PostHog extensions initialized ("+La+"ms)")}fi(Ln){var Ta,ja,La,Fa,wl,Pl,pc,mc;if(!o$d||!o$d.body)return Pt$2.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(Ln)}),500);this.config.__preview_deferred_init_extensions&&(this.Or=Ln),this.compression=void 0,Ln.supportedCompression&&!this.config.disable_compression&&(this.compression=w$a(Ln.supportedCompression,oe$2.GZipJS)?oe$2.GZipJS:w$a(Ln.supportedCompression,oe$2.Base64)?oe$2.Base64:void 0),(Ta=Ln.analytics)!=null&&Ta.endpoint&&(this.analyticsDefaultEndpoint=Ln.analytics.endpoint),this.set_config({person_profiles:this.br?this.br:"identified_only"}),(ja=this.siteApps)==null||ja.onRemoteConfig(Ln),(La=this.sessionRecording)==null||La.onRemoteConfig(Ln),(Fa=this.autocapture)==null||Fa.onRemoteConfig(Ln),(wl=this.heatmaps)==null||wl.onRemoteConfig(Ln),this.surveys.onRemoteConfig(Ln),(Pl=this.webVitalsAutocapture)==null||Pl.onRemoteConfig(Ln),(pc=this.exceptionObserver)==null||pc.onRemoteConfig(Ln),this.exceptions.onRemoteConfig(Ln),(mc=this.deadClicksAutocapture)==null||mc.onRemoteConfig(Ln)}Cr(){try{this.config.loaded(this)}catch(Ln){Pt$2.critical("`loaded` function failed",Ln)}this.Ar(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Dr()}),1),new io(this).load(),this.featureFlags.flags()}Ar(){var Ln;this.is_capturing()&&this.config.request_batching&&((Ln=this.Pr)==null||Ln.enable())}_dom_loaded(){this.is_capturing()&&Ct$1(this.__request_queue,(Ln=>this.Tr(Ln))),this.__request_queue=[],this.Ar()}_handle_unload(){var Ln,Ta;this.config.request_batching?(this.jr()&&this.capture("$pageleave"),(Ln=this.Pr)==null||Ln.unload(),(Ta=this.Ir)==null||Ta.unload()):this.jr()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(Ln){this.__loaded&&(Ro?this.__request_queue.push(Ln):this.rateLimiter.isServerRateLimited(Ln.batchKey)||(Ln.transport=Ln.transport||this.config.api_transport,Ln.url=un$1(Ln.url,{ip:this.config.ip?1:0}),Ln.headers=g$8({},this.config.request_headers),Ln.compression=Ln.compression==="best-available"?this.compression:Ln.compression,Ln.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(Ln.disableTransport=["sendBeacon"]),Ln.fetchOptions=Ln.fetchOptions||this.config.fetch_options,(Ta=>{var ja,La,Fa,wl=g$8({},Ta);wl.timeout=wl.timeout||6e4,wl.url=un$1(wl.url,{_:new Date().getTime().toString(),ver:c$e.LIB_VERSION,compression:wl.compression});var Pl=(ja=wl.transport)!==null&&ja!==void 0?ja:"fetch",pc=vn.filter((gc=>!wl.disableTransport||!gc.transport||!wl.disableTransport.includes(gc.transport))),mc=(La=(Fa=Bt$1(pc,(gc=>gc.transport===Pl)))==null?void 0:Fa.method)!==null&&La!==void 0?La:pc[0].method;if(!mc)throw new Error("No available transport method");mc(wl)})(g$8({},Ln,{callback:Ta=>{var ja,La;this.rateLimiter.checkForLimiting(Ta),Ta.statusCode>=400&&((ja=(La=this.config).on_request_error)==null||ja.call(La,Ta)),Ln.callback==null||Ln.callback(Ta)}}))))}Tr(Ln){this.Ir?this.Ir.retriableRequest(Ln):this.ci(Ln)}_execute_array(Ln){var Ta,ja=[],La=[],Fa=[];Ct$1(Ln,(Pl=>{Pl&&(Ta=Pl[0],I$9(Ta)?Fa.push(Pl):R$3(Pl)?Pl.call(this):I$9(Pl)&&Ta==="alias"?ja.push(Pl):I$9(Pl)&&Ta.indexOf("capture")!==-1&&R$3(this[Ta])?Fa.push(Pl):La.push(Pl))}));var wl=function(Pl,pc){Ct$1(Pl,(function(mc){if(I$9(mc[0])){var gc=pc;Ot(mc,(function(Vd){gc=gc[Vd[0]].apply(gc,Vd.slice(1))}))}else this[mc[0]].apply(this,mc.slice(1))}),pc)};wl(ja,this),wl(La,this),wl(Fa,this)}Fr(){var Ln,Ta;return((Ln=this.config.bootstrap)==null?void 0:Ln.featureFlags)&&Object.keys((Ta=this.config.bootstrap)==null?void 0:Ta.featureFlags).length>0||!1}push(Ln){this._execute_array([Ln])}capture(Ln,Ta,ja){var La;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Pr){if(this.is_capturing())if(!O$6(Ln)&&M$7(Ln)){var Fa=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(Fa&&!this.config.__preview_capture_bot_pageviews)){var wl=ja!=null&&ja.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(wl==null||!wl.isRateLimited){Ta!=null&&Ta.$current_url&&!M$7(Ta?.$current_url)&&(Pt$2.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),Ta==null||delete Ta.$current_url),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 Pl=new Date,pc=ja?.timestamp||Pl,mc=Se$2(),gc={uuid:mc,event:Ln,properties:this.calculateEventProperties(Ln,Ta||{},pc,mc)};Ln==="$pageview"&&this.config.__preview_capture_bot_pageviews&&Fa&&(gc.event="$bot_pageview",gc.properties.$browser_type="bot"),wl&&(gc.properties.$lib_rate_limit_remaining_tokens=wl.remainingTokens),ja?.$set&&(gc.$set=ja?.$set);var Vd,Wd=this.Lr(ja?.$set_once);if(Wd&&(gc.$set_once=Wd),(gc=Ut(gc,ja!=null&&ja._noTruncate?null:this.config.properties_string_max_length)).timestamp=pc,O$6(ja?.timestamp)||(gc.properties.$event_time_override_provided=!0,gc.properties.$event_time_override_system_time=Pl),Ln===Nn.DISMISSED||Ln===Nn.SENT){var kf=Ta?.[Un.SURVEY_ID],Pf=Ta?.[Un.SURVEY_ITERATION];Vd={id:kf,current_iteration:Pf},localStorage.getItem(Vn(Vd))||localStorage.setItem(Vn(Vd),"true"),gc.$set=g$8({},gc.$set,{[Gn({id:kf,current_iteration:Pf},Ln===Nn.SENT?"responded":"dismissed")]:!0})}var Nf=g$8({},gc.properties.$set,gc.$set);if(C$c(Nf)||this.setPersonPropertiesForFlags(Nf),!j$b(this.config.before_send)){var Eh=this.Nr(gc);if(!Eh)return;gc=Eh}this._r.emit("eventCaptured",gc);var Em={method:"POST",url:(La=ja?._url)!==null&&La!==void 0?La:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:gc,compression:"best-available",batchKey:ja?._batchKey};return!this.config.request_batching||ja&&(ja==null||!ja._batchKey)||ja!=null&&ja.send_instantly?this.Tr(Em):this.Pr.enqueue(Em),gc}Pt$2.critical("This capture call is ignored due to client rate limiting.")}}else Pt$2.error("No event name provided to posthog.capture")}else Pt$2.uninitializedWarning("posthog.capture")}Mi(Ln){return this.on("eventCaptured",(Ta=>Ln(Ta.event,Ta)))}calculateEventProperties(Ln,Ta,ja,La,Fa){if(ja=ja||new Date,!this.persistence||!this.sessionPersistence)return Ta;var wl=Fa?void 0:this.persistence.remove_event_timer(Ln),Pl=g$8({},Ta);if(Pl.token=this.config.token,Pl.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(Pl.$cookieless_mode=!0),Ln==="$snapshot"){var pc=g$8({},this.persistence.properties(),this.sessionPersistence.properties());return Pl.distinct_id=pc.distinct_id,(!M$7(Pl.distinct_id)&&!L$6(Pl.distinct_id)||A$8(Pl.distinct_id))&&Pt$2.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),Pl}var mc,gc=_s(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:Vd,windowId:Wd}=this.sessionManager.checkAndGetSessionAndWindowId(Fa,ja.getTime());Pl.$session_id=Vd,Pl.$window_id=Wd}this.sessionPropsManager&&Mt$2(Pl,this.sessionPropsManager.getSessionProps());try{var kf;this.sessionRecording&&Mt$2(Pl,this.sessionRecording.sdkDebugProperties),Pl.$sdk_debug_retry_queue_size=(kf=this.Ir)==null?void 0:kf.length}catch(Em){Pl.$sdk_debug_error_capturing_properties=String(Em)}if(this.requestRouter.region===go.CUSTOM&&(Pl.$lib_custom_api_host=this.config.api_host),mc=Ln!=="$pageview"||Fa?Ln!=="$pageleave"||Fa?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(ja):this.pageViewManager.doPageView(ja,La),Pl=Mt$2(Pl,mc),Ln==="$pageview"&&o$d&&(Pl.title=o$d.title),!O$6(wl)){var Pf=ja.getTime()-wl;Pl.$duration=parseFloat((Pf/1e3).toFixed(3))}d$6&&this.config.opt_out_useragent_filter&&(Pl.$browser_type=this._is_bot()?"bot":"browser"),(Pl=Mt$2({},gc,this.persistence.properties(),this.sessionPersistence.properties(),Pl)).$is_identified=this._isIdentified(),I$9(this.config.property_denylist)?Ot(this.config.property_denylist,(function(Em){delete Pl[Em]})):Pt$2.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var Nf=this.config.sanitize_properties;Nf&&(Pt$2.error("sanitize_properties is deprecated. Use before_send instead"),Pl=Nf(Pl,Ln));var Eh=this.Ur();return Pl.$process_person_profile=Eh,Eh&&!Fa&&this.zr("_calculate_event_properties"),Pl}Lr(Ln){var Ta;if(!this.persistence||!this.Ur()||this.gr)return Ln;var ja=this.persistence.get_initial_props(),La=(Ta=this.sessionPropsManager)==null?void 0:Ta.getSetOnceProps(),Fa=Mt$2({},ja,La||{},Ln||{}),wl=this.config.sanitize_properties;return wl&&(Pt$2.error("sanitize_properties is deprecated. Use before_send instead"),Fa=wl(Fa,"$set_once")),this.gr=!0,C$c(Fa)?void 0:Fa}register(Ln,Ta){var ja;(ja=this.persistence)==null||ja.register(Ln,Ta)}register_once(Ln,Ta,ja){var La;(La=this.persistence)==null||La.register_once(Ln,Ta,ja)}register_for_session(Ln){var Ta;(Ta=this.sessionPersistence)==null||Ta.register(Ln)}unregister(Ln){var Ta;(Ta=this.persistence)==null||Ta.unregister(Ln)}unregister_for_session(Ln){var Ta;(Ta=this.sessionPersistence)==null||Ta.unregister(Ln)}Hr(Ln,Ta){this.register({[Ln]:Ta})}getFeatureFlag(Ln,Ta){return this.featureFlags.getFeatureFlag(Ln,Ta)}getFeatureFlagPayload(Ln){var Ta=this.featureFlags.getFeatureFlagPayload(Ln);try{return JSON.parse(Ta)}catch{return Ta}}isFeatureEnabled(Ln,Ta){return this.featureFlags.isFeatureEnabled(Ln,Ta)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(Ln,Ta,ja){this.featureFlags.updateEarlyAccessFeatureEnrollment(Ln,Ta,ja)}getEarlyAccessFeatures(Ln,Ta,ja){return Ta===void 0&&(Ta=!1),this.featureFlags.getEarlyAccessFeatures(Ln,Ta,ja)}on(Ln,Ta){return this._r.on(Ln,Ta)}onFeatureFlags(Ln){return this.featureFlags.onFeatureFlags(Ln)}onSurveysLoaded(Ln){return this.surveys.onSurveysLoaded(Ln)}onSessionId(Ln){var Ta,ja;return(Ta=(ja=this.sessionManager)==null?void 0:ja.onSessionId(Ln))!==null&&Ta!==void 0?Ta:()=>{}}getSurveys(Ln,Ta){Ta===void 0&&(Ta=!1),this.surveys.getSurveys(Ln,Ta)}getActiveMatchingSurveys(Ln,Ta){Ta===void 0&&(Ta=!1),this.surveys.getActiveMatchingSurveys(Ln,Ta)}renderSurvey(Ln,Ta){this.surveys.renderSurvey(Ln,Ta)}displaySurvey(Ln,Ta){Ta===void 0&&(Ta=Kn),this.surveys.displaySurvey(Ln,Ta)}canRenderSurvey(Ln){return this.surveys.canRenderSurvey(Ln)}canRenderSurveyAsync(Ln,Ta){return Ta===void 0&&(Ta=!1),this.surveys.canRenderSurveyAsync(Ln,Ta)}identify(Ln,Ta,ja){if(!this.__loaded||!this.persistence)return Pt$2.uninitializedWarning("posthog.identify");if(L$6(Ln)&&(Ln=Ln.toString(),Pt$2.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),Ln)if(["distinct_id","distinctid"].includes(Ln.toLowerCase()))Pt$2.critical('The string "'+Ln+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(Ln!==wi){if(this.zr("posthog.identify")){var La=this.get_distinct_id();if(this.register({$user_id:Ln}),!this.get_property("$device_id")){var Fa=La;this.register_once({$had_persisted_distinct_id:!0,$device_id:Fa},"")}Ln!==La&&Ln!==this.get_property(Gt)&&(this.unregister(Gt),this.register({distinct_id:Ln}));var wl=(this.persistence.get_property(ci)||"anonymous")==="anonymous";Ln!==La&&wl?(this.persistence.set_property(ci,"identified"),this.setPersonPropertiesForFlags(g$8({},ja||{},Ta||{}),!1),this.capture("$identify",{distinct_id:Ln,$anon_distinct_id:La},{$set:Ta||{},$set_once:ja||{}}),this.wr=fn$1(Ln,Ta,ja),this.featureFlags.setAnonymousDistinctId(La)):(Ta||ja)&&this.setPersonProperties(Ta,ja),Ln!==La&&(this.reloadFeatureFlags(),this.unregister(vi))}}else Pt$2.critical('The string "'+wi+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else Pt$2.error("Unique user id has not been set in posthog.identify")}setPersonProperties(Ln,Ta){if((Ln||Ta)&&this.zr("posthog.setPersonProperties")){var ja=fn$1(this.get_distinct_id(),Ln,Ta);this.wr!==ja?(this.setPersonPropertiesForFlags(g$8({},Ta||{},Ln||{})),this.capture("$set",{$set:Ln||{},$set_once:Ta||{}}),this.wr=ja):Pt$2.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(Ln,Ta,ja){if(Ln&&Ta){if(this.zr("posthog.group")){var La=this.getGroups();La[Ln]!==Ta&&this.resetGroupPropertiesForFlags(Ln),this.register({$groups:g$8({},La,{[Ln]:Ta})}),ja&&(this.capture("$groupidentify",{$group_type:Ln,$group_key:Ta,$group_set:ja}),this.setGroupPropertiesForFlags({[Ln]:ja})),La[Ln]===Ta||ja||this.reloadFeatureFlags()}}else Pt$2.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0),this.featureFlags.setPersonPropertiesForFlags(Ln,Ta)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0),this.zr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(Ln,Ta)}resetGroupPropertiesForFlags(Ln){this.featureFlags.resetGroupPropertiesForFlags(Ln)}reset(Ln){var Ta,ja,La,Fa;if(Pt$2.info("reset"),!this.__loaded)return Pt$2.uninitializedWarning("posthog.reset");var wl=this.get_property("$device_id");if(this.consent.reset(),(Ta=this.persistence)==null||Ta.clear(),(ja=this.sessionPersistence)==null||ja.clear(),this.surveys.reset(),this.featureFlags.reset(),(La=this.persistence)==null||La.set_property(ci,"anonymous"),(Fa=this.sessionManager)==null||Fa.resetSessionId(),this.wr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:wi,$device_id:null},"");else{var Pl=this.config.get_device_id(Se$2());this.register_once({distinct_id:Pl,$device_id:Ln?Pl:wl},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var Ln,Ta;return(Ln=(Ta=this.sessionManager)==null?void 0:Ta.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&Ln!==void 0?Ln:""}get_session_replay_url(Ln){if(!this.sessionManager)return"";var{sessionId:Ta,sessionStartTimestamp:ja}=this.sessionManager.checkAndGetSessionAndWindowId(!0),La=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+Ta);if(Ln!=null&&Ln.withTimestamp&&ja){var Fa,wl=(Fa=Ln.timestampLookBack)!==null&&Fa!==void 0?Fa:10;if(!ja)return La;La+="?t="+Math.max(Math.floor((new Date().getTime()-ja)/1e3)-wl,0)}return La}alias(Ln,Ta){return Ln===this.get_property(Wt)?(Pt$2.critical("Attempting to create alias for existing People user - aborting."),-2):this.zr("posthog.alias")?(O$6(Ta)&&(Ta=this.get_distinct_id()),Ln!==Ta?(this.Hr(Gt,Ln),this.capture("$create_alias",{alias:Ln,distinct_id:Ta})):(Pt$2.warn("alias matches current distinct_id - skipping api call."),this.identify(Ln),-1)):void 0}set_config(Ln){var Ta=g$8({},this.config);if(F$8(Ln)){var ja,La,Fa,wl,Pl;Mt$2(this.config,Co(Ln));var pc=this.kr();(ja=this.persistence)==null||ja.update_config(this.config,Ta,pc),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fn(g$8({},this.config,{persistence:"sessionStorage"}),pc);var mc=this.$r(this.config.debug);N$6(mc)&&(this.config.debug=mc),N$6(this.config.debug)&&(this.config.debug?(c$e.DEBUG=!0,Ce$3.H()&&Ce$3.G("ph_debug","true"),Pt$2.info("set_config",{config:Ln,oldConfig:Ta,newConfig:g$8({},this.config)})):(c$e.DEBUG=!1,Ce$3.H()&&Ce$3.V("ph_debug"))),(La=this.sessionRecording)==null||La.startIfEnabledOrStop(),(Fa=this.autocapture)==null||Fa.startIfEnabled(),(wl=this.heatmaps)==null||wl.startIfEnabled(),this.surveys.loadIfEnabled(),this.Br(),(Pl=this.externalIntegrations)==null||Pl.startIfEnabledOrStop()}}startSessionRecording(Ln){var Ta=Ln===!0,ja={sampling:Ta||!(Ln==null||!Ln.sampling),linked_flag:Ta||!(Ln==null||!Ln.linked_flag),url_trigger:Ta||!(Ln==null||!Ln.url_trigger),event_trigger:Ta||!(Ln==null||!Ln.event_trigger)};if(Object.values(ja).some(Boolean)){var La,Fa,wl,Pl,pc;(La=this.sessionManager)==null||La.checkAndGetSessionAndWindowId(),ja.sampling&&((Fa=this.sessionRecording)==null||Fa.overrideSampling()),ja.linked_flag&&((wl=this.sessionRecording)==null||wl.overrideLinkedFlag()),ja.url_trigger&&((Pl=this.sessionRecording)==null||Pl.overrideTrigger("url")),ja.event_trigger&&((pc=this.sessionRecording)==null||pc.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var Ln;return!((Ln=this.sessionRecording)==null||!Ln.started)}captureException(Ln,Ta){var ja=new Error("PostHog syntheticException"),La=this.exceptions.buildProperties(Ln,{handled:!0,syntheticException:ja});return this.exceptions.sendExceptionEvent(g$8({},La,Ta))}loadToolbar(Ln){return this.toolbar.loadToolbar(Ln)}get_property(Ln){var Ta;return(Ta=this.persistence)==null?void 0:Ta.props[Ln]}getSessionProperty(Ln){var Ta;return(Ta=this.sessionPersistence)==null?void 0:Ta.props[Ln]}toString(){var Ln,Ta=(Ln=this.config.name)!==null&&Ln!==void 0?Ln:Io;return Ta!==Io&&(Ta=Io+"."+Ta),Ta}_isIdentified(){var Ln,Ta;return((Ln=this.persistence)==null?void 0:Ln.get_property(ci))==="identified"||((Ta=this.sessionPersistence)==null?void 0:Ta.get_property(ci))==="identified"}Ur(){var Ln,Ta;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&C$c(this.getGroups())&&((Ln=this.persistence)==null||(Ln=Ln.props)==null||!Ln[Gt])&&((Ta=this.persistence)==null||(Ta=Ta.props)==null||!Ta[yi]))}jr(){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.Ur()||this.zr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}zr(Ln){return this.config.person_profiles==="never"?(Pt$2.error(Ln+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Hr(yi,!0),!0)}kr(){if(this.config.cookieless_mode==="always")return!0;var Ln=this.consent.isOptedOut(),Ta=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||Ln&&!!Ta}Br(){var Ln,Ta,ja,La,Fa=this.kr();return((Ln=this.persistence)==null?void 0:Ln.wi)!==Fa&&((ja=this.persistence)==null||ja.set_disabled(Fa)),((Ta=this.sessionPersistence)==null?void 0:Ta.wi)!==Fa&&((La=this.sessionPersistence)==null||La.set_disabled(Fa)),Fa}opt_in_capturing(Ln){if(this.config.cookieless_mode!=="always"){var Ta,ja;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(Ta=this.sessionManager)==null||Ta.destroy(),this.sessionManager=new ho(this),this.persistence&&(this.sessionPropsManager=new lo$1(this,this.sessionManager,this.persistence)),this.sessionRecording=new ko(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Br(),this.Ar(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(O$6(Ln?.captureEventName)||Ln!=null&&Ln.captureEventName)&&this.capture((ja=Ln?.captureEventName)!==null&&ja!==void 0?ja:"$opt_in",Ln?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Dr()}else Pt$2.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var Ln,Ta;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Br(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:wi,$device_id:null}),(Ln=this.sessionManager)==null||Ln.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(Ta=this.sessionRecording)==null||Ta.stopRecording(),this.sessionRecording=void 0,this.Dr())):Pt$2.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var Ln=this.consent.consent;return Ln===Ne$2.GRANTED?"granted":Ln===Ne$2.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Br()}_is_bot(){return n$9?po(n$9,this.config.custom_blocked_useragents):void 0}Dr(){o$d&&(o$d.visibilityState==="visible"?this.mr||(this.mr=!0,this.capture("$pageview",{title:o$d.title},{send_instantly:!0}),this.yr&&(o$d.removeEventListener("visibilitychange",this.yr),this.yr=null)):this.yr||(this.yr=this.Dr.bind(this),qt(o$d,"visibilitychange",this.yr)))}debug(Ln){Ln===!1?(t$9?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(t$9?.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}))}M(){var Ln,Ta,ja,La,Fa,wl,Pl,pc=this.Er||{};return"advanced_disable_flags"in pc?!!pc.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Pt$2.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):(ja="advanced_disable_decide",La=!1,Fa=Pt$2,wl=(Ta="advanced_disable_flags")in(Ln=pc)&&!O$6(Ln[Ta]),Pl=ja in Ln&&!O$6(Ln[ja]),wl?Ln[Ta]:Pl?(Fa&&Fa.warn("Config field '"+ja+"' is deprecated. Please use '"+Ta+"' instead. The old field will be removed in a future major version."),Ln[ja]):La)}Nr(Ln){if(j$b(this.config.before_send))return Ln;var Ta=I$9(this.config.before_send)?this.config.before_send:[this.config.before_send],ja=Ln;for(var La of Ta){if(ja=La(ja),j$b(ja)){var Fa="Event '"+Ln.event+"' was rejected in beforeSend function";return z$6(Ln.event)?Pt$2.warn(Fa+". This can cause unexpected behavior."):Pt$2.info(Fa),null}ja.properties&&!C$c(ja.properties)||Pt$2.warn("Event '"+Ln.event+"' has no properties after beforeSend function, this is likely an error.")}return ja}getPageViewId(){var Ln;return(Ln=this.pageViewManager.Vt)==null?void 0:Ln.pageViewId}captureTraceFeedback(Ln,Ta){this.capture("$ai_feedback",{$ai_trace_id:String(Ln),$ai_feedback_text:Ta})}captureTraceMetric(Ln,Ta,ja){this.capture("$ai_metric",{$ai_trace_id:String(Ln),$ai_metric_name:Ta,$ai_metric_value:String(ja)})}$r(Ln){var Ta=N$6(Ln)&&!Ln,ja=Ce$3.H()&&Ce$3.q("ph_debug")==="true";return!Ta&&(!!ja||Ln)}};(function(ta,Ln){for(var Ta=0;Ta<Ln.length;Ta++)ta.prototype[Ln[Ta]]=Lt(ta.prototype[Ln[Ta]])})(Mo$1,["identify"]);var Ao,Do=(Ao=Po[Io]=new Mo$1,(function(){function ta(){ta.done||(ta.done=!0,Ro=!1,Ot(Po,(function(Ln){Ln._dom_loaded()})))}o$d!=null&&o$d.addEventListener?o$d.readyState==="complete"?ta():qt(o$d,"DOMContentLoaded",ta,{capture:!1}):t$9&&Pt$2.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),Ao);const IS_PLAYGROUND$6=!1,metaAxiosInstance$1=axiosInstance("meta"),useAuth=()=>{const ta=useNavigate(),Ln=useAppStore(VC=>VC.resetStore),Ta=useAppStore(VC=>VC.user),ja=useAppStore(VC=>VC.setUser),{initializeApp:La,resetInitialization:Fa}=useAppInitialization(),[wl,Pl]=reactExports$1.useState(!1),[pc,mc]=reactExports$1.useState(!1),[gc,Vd]=reactExports$1.useState(null),Wd=useAppStore(VC=>VC.clearAuth),kf=useAppStore(VC=>VC.setAuthState),Pf=useAppStore(VC=>VC.setAuthError),Nf=useAppStore(VC=>VC.setAuthData),Eh=VC=>{try{const tj=VC.split(".")[1];return JSON.parse(atob(tj)).email||null}catch(tj){console.warn(`Failed to decode JWT token: ${tj}`)}},Em=async(VC,tj)=>{try{kf("loading"),Pf(null);const aB=localStorage.getItem("username");if(aB&&aB!==VC){console.log("Switching accounts - clearing previous user data"),localStorage.removeItem("id_token"),localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("user_id"),localStorage.removeItem("session_id"),localStorage.removeItem("username"),localStorage.removeItem("user_profile_id"),localStorage.removeItem("workspace_id"),localStorage.removeItem("agentlang-studio-store"),Ln(),Wd();const{setLastDataFetch:sP}=useAppStore.getState();sP(0)}const{data:r6}=await metaAxiosInstance$1.post("/agentlang_auth/login",{email:VC,password:tj}),J2=r6;if(J2&&typeof J2=="object"&&J2.id_token){const Q2=Eh(J2.id_token)||VC;Nf({token:J2.id_token,accessToken:J2.access_token,refreshToken:J2.refresh_token,userId:J2.userId,sessionId:J2.sessionId,username:Q2});const{setLastDataFetch:q5}=useAppStore.getState();q5(0);try{const nj=String(J2.userId||Q2);Do.identify(nj,{email:Q2,sessionId:J2.sessionId,authMethod:"password"})}catch(nj){console.warn("PostHog identify failed:",nj)}}else if(typeof J2=="string"&&J2.includes("/")){if(console.log("Processing legacy login format:",J2),typeof J2.split!="function")throw console.error("loginResult.split is not a function:",{loginResult:J2,type:typeof J2}),new Error("Invalid login result format - split method not available");const[sP,Q2]=J2.split("/");if(!sP||!Q2)throw console.error("Invalid userId/sessionId format:",{userId:sP,sessionId:Q2,loginResult:J2}),new Error("Invalid login result format - missing userId or sessionId");Nf({userId:sP,sessionId:Q2,username:VC});const{setLastDataFetch:q5}=useAppStore.getState();q5(0);try{const nj=String(sP||VC);Do.identify(nj,{email:VC,sessionId:Q2,authMethod:"password"})}catch(nj){console.warn("PostHog identify failed (legacy):",nj)}}else throw console.error("Login failed - invalid response format:",{loginResult:J2,type:typeof J2,isObject:typeof J2=="object",isString:typeof J2=="string",hasIdToken:J2?.id_token,includesSlash:typeof J2=="string"&&J2.includes("/")}),new Error(`Login failed due to invalid response format. Expected object with id_token or string with '/', got: ${typeof J2}`);y$b.success("Login successful");const{authData:V_}=useAppStore.getState();if(V_.userId)try{const sP=await metaAxiosInstance$1.get(`/agentlang_auth/User/${V_.userId}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(sP.data&&Array.isArray(sP.data)&&sP.data.length>0){const Q2=sP.data[sP.data.length-1].UserProfile;if(Q2.id){localStorage.setItem("user_profile_id",Q2.id),Nf({userProfileId:Q2.id});try{const q5=String(V_.userId||V_.username||"unknown");Do.group("user_profile",Q2.id,{email:Q2.userEmail||V_.username}),Do.identify(q5,{email:Q2.userEmail||V_.username,userProfileId:Q2.id})}catch(q5){console.warn("PostHog person/group update failed:",q5)}}}}catch(sP){console.warn("Failed to fetch user profile after login:",sP)}La(),ta("/home")}catch(aB){console.error("Login error:",aB),y$b.error(aB?.response?.data?.reason||"Login failed"),y$b.error(aB?.response?.data?.message||aB?.message||"Login failed")}},qg=async()=>{if(!wl){Pl(!0);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("userLoggingOut")),IS_PLAYGROUND$6||await metaAxiosInstance$1.post("/agentlang_auth/logout")}catch(VC){console.warn("Logout API call failed, but clearing local data:",VC)}finally{try{Do.reset()}catch(r6){console.warn("PostHog reset failed:",r6)}Wd(),localStorage.removeItem("workspace_id"),localStorage.removeItem("user_profile_id"),localStorage.removeItem("id_token"),localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("user_id"),localStorage.removeItem("session_id"),localStorage.removeItem("username"),Ln(),Fa(),localStorage.removeItem("agentlang-studio-store"),localStorage.removeItem("chatbotMessages");const{setAuthData:VC,setWorkspace:tj,setUser:aB}=useAppStore.getState();VC({token:"",userId:"",sessionId:"",username:"",userProfileId:"",accessToken:"",refreshToken:""}),tj(""),aB({Email:"",CurrentWorkspace:{Id:""},Anthropic:{Key:""},OpenAI:{Key:"",FinetunedModel:""},GitHub:{Username:"",Org:"",Token:""}}),Pl(!1),ta("/")}}},Ug=async(VC,tj)=>{try{const{authData:aB}=useAppStore.getState();if(!aB.token){y$b.error("Authentication token not found. Please login again.");return}await metaAxiosInstance$1.post("/agentlang_auth/changePassword",{newPassword:tj,password:VC}),y$b.success("Password changed successfully")}catch(aB){y$b.error(aB?.response?.data?.reason||"Failed to change password")}},Bg=async VC=>{try{const{authData:tj}=useAppStore.getState(),{username:aB,userId:r6,userProfileId:J2}=tj;if(!r6||!J2){y$b.error("User ID not found. Please re-login.");return}await metaAxiosInstance$1.put(`/agentlang_auth/User/${r6}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile/${J2}`,{userEmail:aB,userKeys:{OpenAI:VC.OpenAI,Anthropic:VC.Anthropic,GitHub:VC.GitHub}}),ja(VC),y$b.success("Profile updated successfully")}catch(tj){y$b.error(tj?.response?.data?.reason||"Failed to update profile")}},U_=reactExports$1.useCallback(async(VC=!1)=>{const{authData:tj}=useAppStore.getState();let{userId:aB,userProfileId:r6,username:J2}=tj;const{token:V_}=tj;if(r6||(r6=localStorage.getItem("user_profile_id")||""),aB||(aB=localStorage.getItem("user_id")||""),J2||(J2=localStorage.getItem("username")||""),!!!(aB&&J2&&V_)){console.log("Auth not ready for profile fetch:",{userId:aB,username:J2,hasToken:!!V_});return}if(!(!VC&&Ta.Email&&!pc))try{if(mc(!0),Vd(null),!r6){const q5=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(q5.data&&Array.isArray(q5.data)&&q5.data.length>0){const nj=q5.data[q5.data.length-1].UserProfile;if(nj.id){localStorage.setItem("user_profile_id",nj.id);const l6=useAppStore.getState().authData;Nf({...l6,userProfileId:nj.id}),console.log("Set userProfileId in auth store:",nj.id)}let n6;try{n6=typeof nj.userKeys=="string"?JSON.parse(nj.userKeys):nj.userKeys}catch{n6={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}ja({Email:nj.userEmail||J2,CurrentWorkspace:{Id:""},...n6});return}console.warn("No user profiles found. User needs to complete signup process to create profile."),Vd("No user profile found. Please contact support if this persists.");return}const Q2=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile/${r6}`);if(!Q2.data||Array.isArray(Q2.data)&&Q2.data.length===0){const q5=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(q5.data&&Array.isArray(q5.data)&&q5.data.length>0){const nj=q5.data[q5.data.length-1].UserProfile;if(nj.id){localStorage.setItem("user_profile_id",nj.id);const l6=useAppStore.getState().authData;Nf({...l6,userProfileId:nj.id}),console.log("Set userProfileId in auth store (fallback):",nj.id);try{const i6=String(l6.userId||l6.username||"unknown");Do.group("user_profile",nj.id,{email:nj.userEmail||l6.username}),Do.identify(i6,{email:nj.userEmail||l6.username,userProfileId:nj.id})}catch(i6){console.warn("PostHog person/group update failed (fallback):",i6)}}let n6;try{n6=typeof nj.userKeys=="string"?JSON.parse(nj.userKeys):nj.userKeys}catch{n6={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}ja({Email:nj.userEmail||J2,CurrentWorkspace:{Id:""},...n6});return}console.warn("No profiles found for user. User needs to complete signup process."),Vd("No user profile found. Please contact support if this persists.");return}if(Q2.data&&Array.isArray(Q2.data)&&Q2.data.length>0){const q5=Q2.data[0].UserProfile;let nj;try{nj=typeof q5.userKeys=="string"?JSON.parse(q5.userKeys):q5.userKeys}catch(l6){console.warn("Failed to parse userKeys JSON:",l6),nj={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}const n6={Email:q5.userEmail||J2||"",CurrentWorkspace:Ta.CurrentWorkspace||{Id:""},Anthropic:nj.Anthropic||{Key:""},OpenAI:nj.OpenAI||{Key:"",FinetunedModel:""},GitHub:nj.GitHub||{Username:"",Org:"",Token:""}};ja(n6)}else throw new Error("Unexpected response format")}catch(Q2){console.error("useAuth: Failed to fetch user profile:",Q2),Vd(Q2?.response?.data?.reason||Q2?.message||"Failed to fetch user profile")}finally{mc(!1)}},[Ta.CurrentWorkspace,Ta.Email,pc,ja,Nf]),B_=useAppStore(VC=>VC.authReady);return reactExports$1.useEffect(()=>{B_&&U_()},[B_,U_]),{login:Em,logoutHandler:qg,changePassword:Ug,setUserProfile:Bg,isLoggingOut:wl,fetchUserProfile:U_,profileLoading:pc,profileError:gc,userProfile:Ta}},IS_PLAYGROUND$5=!1,metaAxiosInstance=axiosInstance("meta"),useSignUp=()=>{const ta=useNavigate(),[Ln,Ta]=reactExports$1.useState(!1),ja=useAppStore(Pl=>Pl.setAuthData),La=useAppStore(Pl=>Pl.setUser),{initializeApp:Fa}=useAppInitialization();return{signUp:reactExports$1.useCallback(async Pl=>{if(Ln)return{success:!1,error:"Sign up already in progress"};Ta(!0);try{console.log("Registering new user:",Pl.email);const pc=await metaAxiosInstance.post("/agentlang_auth/register",{email:Pl.email,password:Pl.password,firstName:Pl.firstName,lastName:Pl.lastName});if(!pc.data)throw new Error("Registration failed - no response received");const{userId:mc,email:gc}=pc.data;if(!mc)throw new Error("Registration failed - no userId received");console.log("Creating user profile and workspace...");const Vd=await metaAxiosInstance.post("/AgentMeta/PostSignUp",{userId:mc,userEmail:gc||Pl.email,userKeys:{OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}});if(!Vd.data||!Array.isArray(Vd.data)||Vd.data.length===0)throw new Error("Failed to create user profile and workspace");const Wd=Vd.data[0];let kf=null,Pf=null;if(Wd?.User?.["AgentMeta/UserHasUserProfile"]?.[0]?.UserProfile){const Em=Wd.User["AgentMeta/UserHasUserProfile"][0].UserProfile;kf=Em.id,Em["AgentMeta/UserWorkspace"]?.[0]?.Workspace&&(Pf=Em["AgentMeta/UserWorkspace"][0].Workspace.id)}if(!kf)throw new Error("Failed to create user profile");console.log("User profile and workspace created successfully:",{userProfileId:kf,workspaceId:Pf}),console.log("Performing automatic login...");const Eh=(await metaAxiosInstance.post("/agentlang_auth/login",{email:Pl.email,password:Pl.password})).data;return Eh&&typeof Eh=="object"&&Eh.id_token?(ja({token:Eh.id_token,accessToken:Eh.access_token,refreshToken:Eh.refresh_token,userId:Eh.userId||mc,sessionId:Eh.sessionId,username:Pl.email,userProfileId:kf}),localStorage.setItem("user_profile_id",kf),Pf&&localStorage.setItem("workspace_id",Pf),La({Email:Pl.email,user_profile_id:kf,CurrentWorkspace:{Id:Pf||""},Anthropic:{Key:""},OpenAI:{Key:"",FinetunedModel:""},GitHub:{Username:"",Org:"",Token:""}}),y$b.success("Account created successfully! Welcome!"),IS_PLAYGROUND$5||await Fa(),ta("/home"),{success:!0,message:"Account created and logged in successfully"}):(y$b.success("Account created successfully! Please login with your credentials."),ta("/"),{success:!0,message:"Account created successfully. Please login."})}catch(pc){console.error("Sign up failed:",pc);const mc=pc?.response?.data?.reason||pc?.response?.data?.message||pc?.message||"Sign up failed. Please try again.";return y$b.error(mc),{success:!1,error:mc}}finally{Ta(!1)}},[ta,ja,La,Fa,Ln]),isSigningUp:Ln}},getEntities=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getEntityNames()}catch(Ln){return console.error("Error fetching module:",Ln),[]}},getRecords=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getRecordNames()}catch(Ln){return console.error("Error fetching records:",Ln),[]}},getEvents=ta=>{if(!ta)return[];try{const Ln=fetchModule$2(ta);return Ln.getEventNames().filter(ja=>!Ln.isPrePostEvent(ja))}catch(Ln){return console.error("Error fetching events:",Ln),[]}},getAgents=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getAgentNames()}catch(Ln){return console.error("Error fetching agents:",Ln),[]}},getDecisions=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getAllDecisions().map(ja=>ja.name)}catch(Ln){return console.error("Error fetching decisions:",Ln),[]}},getRelationships=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getRelationshipNames()}catch(Ln){return console.error("Error fetching relationships:",Ln),[]}},isAgent=(ta,Ln)=>!!fetchModule$2(ta).getAgent(Ln),isEvent=(ta,Ln)=>fetchModule$2(ta).getEventNames().includes(Ln),isRecord=(ta,Ln)=>fetchModule$2(ta).getRecordNames().includes(Ln),isEntity=(ta,Ln)=>fetchModule$2(ta).getEntityNames().includes(Ln),getAgent=(ta,Ln)=>fetchModule$2(ta).getAgent(Ln),useEntity=()=>{const{zoomHandler:ta}=useZoomHandler(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Ug=>Ug.user),{incrementModuleDbChangeCount:La}=useAppStore(),Fa=ja.GitHub.Token,wl=ja.GitHub.Username,Pl=Qn$1(),{saveUISpec:pc}=useSaveUISpec(),mc=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addEntity(Ug,Ta);const Bg=fetchModule$2(Ta).toString();if(saveModuleToGit(Ln,Ta,Bg,`Add entity ${Ug}`,wl,Fa),La(),Pl&&pc)try{const U_=`${Ta}/${Ug}`,B_=repopulateUISchemaForNewEntity(Pl,U_);pc(B_,`Update UI schema for new entity ${Ug}`)}catch(U_){console.error("[useEntity] Failed to repopulate UI schema for new entity:",U_)}setTimeout(()=>{ta(`${Ta}/${Ug}`)},100)},gc=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addRecord$1(Ug,Ta);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add record ${Ug}`,wl,Fa),La(),setTimeout(()=>{ta(`${Ta}/${Ug}`)},100)},Vd=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addEvent(Ug,Ta),addWorkflow(Ug,Ta);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add event ${Ug}`,wl,Fa),La(),setTimeout(()=>{ta(Ug)},200)},Wd=(Ug,Bg)=>{let U_;isFqName$1(Bg)?U_=nameToPath$1(Bg).getEntryName():U_=Bg;const B_=U_.replace(/--workflow$/,"");isEvent(Ta||"",B_)?removeEvent(U_,Ta||""):Ug.removeEntry(U_)};return{addEntity:mc,addRecord:gc,addEvent:Vd,deleteHandler:async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Bg=fetchModule$2(Ta||"");Ug.forEach(VC=>{Wd(Bg,VC)});const U_=Bg.toString(),B_=`Delete entries ${Ug.join(", ")}`;saveModuleToGit(Ln,Ta,U_,B_,wl,Fa),La()},addAttribute:async(Ug,Bg,U_,B_,VC="type",tj=[],aB="",r6)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const J2=fetchModule$2(Ta),V_=J2.getEntry(Ug),sP=VC==="Entity"||VC==="Record",Q2=VC==="@oneof",q5=VC==="@enum";let nj;if(q5&&tj.length>0)nj=enumAttributeSpec(new Set(tj)),aB&&(nj=setDefaultAttributeValue(nj,aB));else if(Q2){if(!r6)throw new Error("Compound type info is required for Entity or Record types");const n6=`${r6.module}/${r6.entity}`;nj=oneOfAttributeSpec(n6)}else if(sP){if(!r6)throw new Error("Compound type info is required for Entity or Record types");nj={type:`${r6.module}/${r6.entity}`,properties:new Map},B_.forEach(n6=>{nj.properties?.set(n6,!0)})}else nj={type:U_,properties:new Map},B_.forEach(n6=>{nj.properties?.set(n6,!0)}),aB&&(nj=setDefaultAttributeValue(nj,aB));if(V_.addAttribute(Bg,nj),saveModuleToGit(Ln,Ta,J2.toString(),`Add attribute ${Bg} to ${Ug}`,wl,Fa),La(),Pl&&pc)try{const n6=`${Ta}/${Ug}`,l6=repopulateUISchemaForNewAttribute(Pl,n6);pc(l6,`Update UI schema for new attribute ${Bg} in ${Ug}`)}catch(n6){console.error(" Failed to repopulate UI schema for new attribute:",n6)}},deleteAttributes:async(Ug,Bg)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta),VC=B_.getEntry(U_);Bg.forEach(tj=>{VC.removeAttribute(tj)}),La(),saveModuleToGit(Ln,Ta,B_.toString(),`Delete attributes ${Bg.join(", ")} from ${Ug}`,wl,Fa)},reorderAttributes:async(Ug,Bg)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta);B_.getEntry(U_).reorderAttributes(Bg),La(),await saveModuleToGit(Ln,Ta,B_.toString(),`Reorder attributes in ${Ug}`,wl,Fa)},setEventPublic:async(Ug,Bg)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta);getEvent$1(U_,Ta).setPublic(Bg);const tj=B_.toString();La(),await saveModuleToGit(Ln,Ta,tj,`Set Public status for Event ${Ug}`,wl,Fa)},getEventPublic:Ug=>{if(!Ta)throw new Error("moduleName is undefined");const Bg=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug;return getEvent$1(Bg,Ta).isPublic()}}},useEntityDetailsChange=ta=>{const Ln=Qn$1();return{onEntityDetailsChange:(ja,La)=>{if(ta&&Ln){const Fa={...Ln,[ja]:{...Ln?.[ja]||{},...La}};ta(Fa,`Update ${ja} entity details`)}}}},useModule=()=>{const{incrementModuleDbChangeCount:ta}=useAppStore(),Ln=useNavigate(),{pathname:Ta}=useLocation(),ja=Ta.split("/"),La=getUserModuleNames(),Fa=mc=>{Ln([...ja.slice(0,-1),mc].join("/"))};return{navigateModule:Fa,addModuleHandler:mc=>{addModule$1(mc),Fa(mc),ta()},deleteModuleHandler:mc=>{if(La.length===1){y$b.error("Cannot delete the last module");return}removeModule(mc);const gc=La.filter(Vd=>mc!==Vd);Fa(gc.length>0?gc[gc.length-1]:""),ta()},getModuleCode:mc=>{try{return isModule$1(mc)?fetchModule$2(mc).toString():""}catch(gc){return console.error(gc),""}}}},useOutsideClickHandler=ta=>{const Ln=reactExports$1.useRef(null);return reactExports$1.useEffect(()=>{const Ta=ja=>{const La=ja.target,Fa=La.closest('[role="option"]')||La.closest(".dropdown-options")||La.closest("[data-headlessui-state]")||La.closest("[data-radix-dropdown-menu-content]")||La.closest("[data-radix-dropdown-menu-sub-content]")||La.closest("[data-query-attribute-menu]")||La.closest("[data-radix-portal]")||La.closest("[data-radix-popper-content-wrapper]"),wl=La.closest(".chatbot-fab-button");Ln.current&&!Ln.current.contains(La)&&!Fa&&!wl&&ta()};return document.addEventListener("click",Ta,!0),()=>{document.removeEventListener("click",Ta,!0)}},[ta]),Ln},useRelationship$1=()=>{const{incrementModuleDbChangeCount:ta}=useAppStore(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Vd=>Vd.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username;return{addRelationship:async(Vd,Wd,kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=new Path$1(Wd.module,Wd.entity),Eh=new Path$1(kf.module,kf.entity),Em={path:Nf,alias:Wd.entity,origName:Nf.asFqName(),origAlias:kf.entity},qg={path:Eh,alias:kf.entity,origName:Eh.asFqName(),origAlias:Wd.entity};Pf==="contains"&&addContainsRelationship(Vd,Ta,[Em,qg]),Pf==="between"&&addBetweenRelationship(Vd,Ta,[Em,qg]);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add ${Pf} relationship ${Vd} between ${Wd.entity} and ${kf.entity}`,Fa,La),ta()},setOneToOne:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setOneToOne(!0);const kf=fetchModule$2(Ta).toString();console.log("moduleData",kf),ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to One-to-One relationship`,Fa,La)},setOneToMany:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setOneToMany(!0);const kf=fetchModule$2(Ta).toString();ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to One-to-Many relationship`,Fa,La)},setManyToMany:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setManyToMany(!0);const kf=fetchModule$2(Ta).toString();ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to Many-to-Many relationship`,Fa,La)},getRelationshipType:Vd=>{if(!Ta)return null;try{const Wd=getRelationship$1(Vd,Ta);return Wd.isOneToOne()?"one-to-one":Wd.isOneToMany()?"one-to-many":Wd.isManyToMany()?"many-to-many":"contains"}catch(Wd){return console.error("Error getting relationship type:",Wd),null}}}},useRouteDataFetching=({routePattern:ta,fetchFunction:Ln,requiresAuth:Ta=!0,dependencies:ja=[]})=>{const La=useLocation(),Fa=reactExports$1.useRef(new Set),wl=reactExports$1.useRef(null),Pl=useAppStore(Eh=>Eh.authData),{token:pc,userId:mc,userProfileId:gc,username:Vd}=Pl,Wd=mc,kf=La.pathname.includes(ta),Pf=reactExports$1.useCallback(Eh=>`${ta}-${Eh}`,[ta]),Nf=reactExports$1.useCallback(async(Eh,Em,qg=!1)=>{const Ug=Pf(Eh);try{await Ln(Eh,Em,qg),Fa.current.add(Ug)}catch(Bg){console.error(`useRouteDataFetching: Failed to fetch data for route ${ta}:`,Bg)}},[Ln,Pf,ta]);return reactExports$1.useEffect(()=>{if(!kf)return;if(wl.current!==Wd&&(Fa.current.clear(),wl.current=Wd),Ta&&!pc){console.log(`useRouteDataFetching: Authentication required for route ${ta}, but no token found`);return}if(!Wd||!Vd||Ta&&!gc){console.log(`useRouteDataFetching: Missing required data for route ${ta}`,{hasWorkspaceId:!!Wd,hasUsername:!!Vd,hasUserProfileId:!!gc,hasAuthToken:!!pc});return}const Eh=Pf(Wd);if(Fa.current.has(Eh)){console.log(`useRouteDataFetching: Data already fetched for route ${ta} and workspace ${Wd}`);return}Nf(Wd,Vd)},[kf,Wd,Vd,gc,pc,Ta,Nf,Pf,ta,...ja]),{refetch:reactExports$1.useCallback((Eh=!1)=>{if(Wd&&Vd&&(!Ta||gc&&pc)){const Em=Pf(Wd);Fa.current.delete(Em),Nf(Wd,Vd,Eh)}},[Wd,Vd,gc,pc,Ta,Nf,Pf,ta]),clearCache:reactExports$1.useCallback(()=>{Fa.current.clear()},[]),isMatchingRoute:kf,hasRequiredData:!!(Wd&&Vd&&(!Ta||gc&&pc))}},useStore=()=>{const{moduleName:ta}=useParams(),Ln=getModuleNames$1().filter(Fa=>Fa!=="agentlang"),{currentTeam:Ta}=useTeams();if(!ta)throw new Error("Module name is undefined");let ja;try{ja=fetchModule$2(ta)}catch(Fa){console.error(Fa)}const La=ja?ja.getEntityNames():[];return{modules:Ln,currentModule:ja,entities:La,currentTeam:Ta}},useRbac=()=>{const{teamName:ta,moduleName:Ln}=useParams(),Ta=useAppStore(i6=>i6.setSelectedRole),ja=useAppStore(i6=>i6.setAppConfig),La=useAppStore(i6=>i6.appConfig),Fa=useAppStore(i6=>i6.user),wl=Fa.GitHub.Token,Pl=Fa.GitHub.Username,{incrementModuleDbChangeCount:pc}=useAppStore(),mc=()=>{if(!ta)throw new Error("Team name is required to save RBAC roles");if(!Ln)throw new Error("Module name is required for RBAC operations")},gc=i6=>{if(!Ln)throw new Error("Module name is required for RBAC operations");const s6=getEntity$1(i6,Ln);if(!s6)throw new Error(`Entity instance for "${i6}" in module "${Ln}" is undefined.`);return s6},Vd=i6=>{if(!Ln||!ta)throw new Error("Module name and team name are required for RBAC operations");const u6=fetchModule$2(Ln).toString();pc(),saveModuleToGit(ta,Ln,u6,i6,Pl,wl)},Wd=(i6,s6,u6,f6="Toggle")=>{try{mc();for(const Xae of i6){const g$e=gc(Xae),n$e=g$e.getRbacSpecifications()||[],v$e=u6([...n$e],s6);g$e.setRbacSpecifications(v$e)}const Rpe=`${f6} all RBAC permissions for role: ${s6}`;Vd(Rpe)}catch(Rpe){throw console.error("Error toggling all RBAC permissions:",Rpe),Rpe}},kf=(i6,s6,u6,f6,Rpe="Toggle")=>{try{mc();for(const g$e of i6){const n$e=gc(g$e),v$e=n$e.getRbacSpecifications()||[],S$e=u6([...v$e],s6,f6);n$e.setRbacSpecifications(S$e)}const Xae=`${Rpe} ${f6} RBAC permission for role: ${s6}`;Vd(Xae)}catch(Xae){throw console.error(`Error toggling ${f6} RBAC permission:`,Xae),Xae}},Pf=(i6,s6,u6,f6="Toggle")=>{try{mc();const Rpe=gc(i6),Xae=Rpe.getRbacSpecifications()||[],g$e=u6([...Xae],s6);Rpe.setRbacSpecifications(g$e);const n$e=`${f6} all RBAC permissions for role: ${s6} on entity: ${i6}`;Vd(n$e)}catch(Rpe){throw console.error("Error toggling all RBAC permissions for entity:",Rpe),Rpe}},Nf=(i6,s6,u6,f6,Rpe="Toggle")=>{try{mc();const Xae=gc(i6),g$e=Xae.getRbacSpecifications()||[],n$e=u6([...g$e],s6,f6);Xae.setRbacSpecifications(n$e);const v$e=`${Rpe} ${f6} RBAC permission for role: ${s6} on entity: ${i6}`;Vd(v$e)}catch(Xae){throw console.error(`Error toggling ${f6} RBAC permission for entity:`,Xae),Xae}},Eh=(i6,s6="Save RBAC roles")=>{mc();const u6={...La,rbac:{roles:i6}};if(ja(u6),!ta)throw new Error("Team name is required to save RBAC roles");saveConfigToGit(ta,JSON.stringify(u6,null,2),s6,Pl,wl)},Em=i6=>{const s6=La?.rbac?.roles||[];Eh([...s6,i6],"Add RBAC role"),Ta(i6)},qg=i6=>{const u6=(La?.rbac?.roles||[]).filter(f6=>f6!==i6);Eh(u6,"Delete RBAC role"),Ta(u6.at(-1)||"")},Ug=(i6,s6)=>{const u6=i6.find(f6=>f6.roles.has(s6));if(u6){if(u6.hasCreatePermission()&&u6.hasReadPermission()&&u6.hasUpdatePermission()&&u6.hasDeletePermission())return i6.filter(Rpe=>Rpe!==u6);u6.setPermissions(["create","read","update","delete"])}else{const f6=new RbacSpecification;f6.setRoles([s6]),f6.setPermissions(["create","read","update","delete"]),i6.push(f6)}return i6},Bg=(i6,s6,u6)=>{const f6=i6.find(Rpe=>Rpe.roles.has(s6));if(f6)if((()=>{switch(u6){case"create":return f6.hasCreatePermission();case"read":return f6.hasReadPermission();case"update":return f6.hasUpdatePermission();case"delete":return f6.hasDeletePermission()}})()){const n$e=Array.from(f6.permissions).map(v$e=>RbacPermissionFlag$1[v$e].toLowerCase()).filter(v$e=>v$e!==u6);if(n$e.length===0)return i6.filter(v$e=>v$e!==f6);f6.setPermissions(n$e)}else{const Xae=Array.from(f6.permissions).map(g$e=>RbacPermissionFlag$1[g$e].toLowerCase());Xae.push(u6),f6.setPermissions(Xae)}else{const Rpe=new RbacSpecification;Rpe.setRoles([s6]),Rpe.setPermissions([u6]),i6.push(Rpe)}return i6};return{saveRbacRoles:Eh,addRole:Em,deleteRole:qg,allHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);Wd(s6,i6,Ug)},createHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"create")},readHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"read")},updateHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"update")},deleteHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"delete")},entityAllHandler:(i6,s6)=>{Pf(i6,s6,Ug)},entityCreateHandler:(i6,s6)=>{Nf(i6,s6,Bg,"create")},entityReadHandler:(i6,s6)=>{Nf(i6,s6,Bg,"read")},entityUpdateHandler:(i6,s6)=>{Nf(i6,s6,Bg,"update")},entityDeleteHandler:(i6,s6)=>{Nf(i6,s6,Bg,"delete")},addExpression:(i6,s6,u6)=>{try{mc();const f6=gc(i6),Rpe=f6.getRbacSpecifications()||[],Xae=Rpe.find(n$e=>n$e.expression),g$e=Object.entries(u6).filter(([n$e,v$e])=>v$e).map(([n$e])=>n$e);if(Xae)Xae.setPermissions(g$e),Xae.setExpression("auth.user",`this.${s6}`);else{const n$e=new RbacSpecification;n$e.setPermissions(g$e),n$e.setExpression("auth.user",`this.${s6}`),Rpe.push(n$e)}f6.setRbacSpecifications(Rpe),Vd(`Add RBAC expression for entity: ${i6}`)}catch(f6){throw console.error("Error setting expression for entity:",f6),f6}},removeExpression:i6=>{try{mc();const s6=gc(i6),f6=(s6.getRbacSpecifications()||[]).filter(Rpe=>!Rpe.expression);s6.setRbacSpecifications(f6),Vd(`Remove RBAC expression for entity: ${i6}`)}catch(s6){throw console.error("Error removing expression for entity:",s6),s6}},getRoleRbacSpec:(i6,s6)=>(mc(),(gc(i6).getRbacSpecifications()||[]).find(Xae=>Xae.roles.has(s6))),getRBACExpression:i6=>(mc(),(gc(i6).getRbacSpecifications()||[]).find(Rpe=>Rpe.expression))}},useWorkflow=ta=>{const{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(kf=>kf.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username,{incrementModuleDbChangeCount:wl}=useAppStore();return{onCreateCrudStatement:async(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta||""),Em=Eh.getWorkflowForEvent(ta);let qg;if(Pf==="create"?qg=newCreatePattern(kf):Pf==="read"?qg=newQueryPattern(kf):Pf==="delete"?qg=newDeletePattern(kf):Pf==="update"&&(qg=newQueryUpdatePattern(kf)),Pf==="loop"?qg=new ForEachPattern$1:Pf==="if-else"&&(qg=new IfPattern$1().setElse()),qg&&Em)await Em.setStatementAt(qg.toString(),Nf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add ${Pf} pattern for ${ta}`,Fa,La)});else throw new Error(`Unknown type: ${Pf}`)},onDeleteStatementHandler:async kf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Pf=fetchModule$2(Ta||"");Pf.getWorkflowForEvent(ta)?.removeStatementAt(kf),wl(),saveModuleToGit(Ln,Ta,Pf.toString(),`Delete pattern for ${ta} at index ${kf}`,Fa,La)},updateStatementHandler:async(kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=fetchModule$2(Ta||"");await Nf.getWorkflowForEvent(ta)?.setStatementAt(Pf,kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Nf.toString(),`Update pattern for ${ta} at index ${kf}`,Fa,La)})},onCreateFunctionCall:async(kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=fetchModule$2(Ta||""),Eh=Nf.getWorkflowForEvent(ta),Em=new FunctionCallPattern$1(Pf,[]);await Eh?.setStatementAt(Em.toString(),kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Nf.toString(),`Add function call pattern for ${ta}`,Fa,La)})},onCreateExpression:async(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta||""),Em=Eh.getWorkflowForEvent(ta),qg=new ExpressionPattern$1(Pf);Nf&&qg.setAlias(Nf),await Em?.setStatementAt(qg.toString(),kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add expression pattern for ${ta}`,Fa,La)})},addTrigger:(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");if(Nf==="after")if(Pf==="create")addAfterCreateWorkflow(kf,Ta);else if(Pf==="delete")addAfterDeleteWorkflow(kf,Ta);else if(Pf==="update")addAfterUpdateWorkflow(kf,Ta);else throw new Error("Invalid trigger type");else if(Nf==="before")if(Pf==="create")addBeforeCreateWorkflow(kf);else if(Pf==="delete")addBeforeDeleteWorkflow(kf);else if(Pf==="update")addBeforeUpdateWorkflow(kf,Ta);else throw new Error("Invalid trigger type");else throw new Error("Invalid trigger time");const Eh=fetchModule$2(Ta||"");wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add ${Nf} ${Pf} trigger for ${kf}`,Fa,La)}}},useAppConfig=()=>{const{teamName:ta}=useParams(),Ln=useAppStore(Pl=>Pl.appConfig),Ta=useAppStore(Pl=>Pl.setAppConfig),ja=useAppStore(Pl=>Pl.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username;return{saveAppConfig:Pl=>{if(!ta)throw new Error("Team name is required to save app integrations");const pc={...Ln,...Pl};Ta(pc),saveConfigToGit(ta,JSON.stringify(pc,null,2),"Save App Configuration",Fa,La)}}},useFlow=()=>{const{zoomHandler:ta}=useZoomHandler(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Nf=>Nf.user),{incrementModuleDbChangeCount:La,setSelectedDecisionId:Fa}=useAppStore(),wl=ja.GitHub.Token,Pl=ja.GitHub.Username;return{addFlow:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);Eh.addFlow(Nf);const Em=Eh.toString();saveModuleToGit(Ln,Ta,Em,`Add flow ${Nf}`,Pl,wl),La(),setTimeout(()=>{ta(Nf)},100)},removeFlow:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);Em.removeFlow(Nf);const qg=Em.toString();saveModuleToGit(Ln,Ta,qg,`Remove flow ${Nf}`,Pl,wl),La(),Eh&&setTimeout(()=>{ta(Eh)},100)},updateFlow:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);Em.removeFlow(Nf),Em.addFlow(Nf);const qg=Em.getFlow(Nf);if(!qg)throw new Error("Flow could not be recreated");Eh.forEach(Bg=>{const U_=new FlowStepPattern$1(Bg.source,Bg.target,Bg.label);qg.appendStep(U_.toString())});const Ug=Em.toString();saveModuleToGit(Ln,Ta,Ug,`Update flow ${Nf}`,Pl,wl)},addDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);if(Eh.getDecision(Nf))return;const qg=new Decision$1(Nf,Eh.name,[]);Eh.addDecision(qg);const Ug=Eh.toString();saveModuleToGit(Ln,Ta,Ug,`Add decision ${Nf}`,Pl,wl),La(),setTimeout(()=>{Fa(Nf),ta(`decision-node-${Nf}`,{openForm:!0})},200)},removeDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);if(!Eh.getDecision(Nf))return;Eh.removeDecision(Nf);const qg=Eh.toString();saveModuleToGit(Ln,Ta,qg,`Remove decision ${Nf}`,Pl,wl)},updateDecision:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);if(!Em.getDecision(Nf))return;Em.removeDecision(Nf);const Ug=new Decision$1(Nf,Em.name,Eh);Em.addDecision(Ug);const Bg=Em.toString();saveModuleToGit(Ln,Ta,Bg,`Update decision ${Nf}`,Pl,wl)},getDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");return fetchModule$2(Ta).getDecision(Nf)}}},useMobile=()=>{const[ta,Ln]=reactExports$1.useState(!1);return reactExports$1.useEffect(()=>{const Ta=()=>{Ln(window.innerWidth<768)};return Ta(),window.addEventListener("resize",Ta),()=>window.removeEventListener("resize",Ta)},[]),ta};function transformApiResponseToMarketplaceModel(ta){return{Id:ta.id||"",Name:ta.name||"",Type:ta.type||"",Description:ta.description||"",Version:ta.version||"",Owner:ta.owner||"",GitHubOrg:ta.gitHubOrg||"",GitHubRepo:ta.gitHubRepo||"",Branch:ta.gitHubBranch||ta.branch||"main",CreatedAt:ta.createdAt||"",LastUpdatedAt:ta.lastUpdatedAt||"",Icon:ta.icon||"",MarketPlaceUrl:ta.marketPlaceUrl||"",ExtraDetails:ta.extraDetails||{},GithubOrg:ta.gitHubOrg||"",Config:{},Dependencies:{FractlModels:[],ClojureLibraries:[]},EntityType:"Model",GithubUrl:ta.githubUrl||`https://github.com/${ta.gitHubOrg}/${ta.gitHubRepo}`,__Id__:ta.id||"",Tags:ta.tags||null,isEditable:!1,isPin:!1,isLoading:!1,isError:!1,ErrorMessage:""}}const useMarketplace=()=>{const{error:ta,refetch:Ln}=useQuery({queryKey:["marketplace","models"],enabled:!1,queryFn:async()=>{const Fa=await axiosInstance("marketplace").get("/MarketplaceMeta/Model");console.log("The response of marketplace model is:",Fa.data);let wl=[];return Array.isArray(Fa.data)?Fa.data.length===0?wl=[]:wl=Fa.data.map(Pl=>Pl.Model||Pl).map(Pl=>transformApiResponseToMarketplaceModel(Pl)):Fa.data?.result&&Array.isArray(Fa.data.result)&&(wl=Fa.data.result.map(Pl=>Pl.Model||Pl).map(Pl=>transformApiResponseToMarketplaceModel(Pl))),wl},staleTime:3e5,gcTime:6e5,retry:(Fa,wl)=>wl?.response?.status===401||wl?.response?.status===403?!1:Fa<2}),Ta=reactExports$1.useCallback(async()=>{await Ln()},[Ln]),ja=reactExports$1.useCallback(async Fa=>{try{const wl=await axiosInstance("marketplace").post("/MarketplaceMeta/Model",Fa);return y$b.success("Model published successfully!"),wl.data}catch(wl){const Pl=wl?.response?.data?.reason||"Failed to publish model";throw y$b.error(Pl),wl}},[]),La=reactExports$1.useCallback(async Fa=>{try{await axiosInstance("marketplace").delete(`/MarketplaceMeta/Model/${Fa}`),y$b.success("Model deleted successfully!"),await Ln()}catch(wl){const Pl=wl?.response?.data?.reason||"Failed to delete model";throw y$b.error(Pl),wl}},[Ln]);return{fetchMarketplaceModels:Ta,publishModel:ja,deleteModel:La,refetchMarketplaceModels:Ln}},useAddTeam=()=>{const{addWorkspaceApp:ta}=useTeams(),Ln=useAppStore(Pf=>Pf.user),Ta=Ln.GitHub.Token,ja=Ln.GitHub.Org,La=Ln.GitHub.Username,Fa=useNavigate(),[wl,Pl]=React.useState(!1),[pc,mc]=React.useState("creating-repo"),[gc,Vd]=React.useState("");return{addTeam:async({name:Pf})=>{Pl(!0),mc("creating-repo"),Vd("Creating GitHub repository...");try{const Eh=(await createGitHubRepo(Ta,Pf.toLowerCase(),{private:!0,auto_init:!0},ja)).name;mc("cloning-repo"),Vd("Cloning repository...");try{const Em=`/${Eh}`,qg="main",Ug=La&&La.trim().length>0,Bg=Ta&&Ta.trim().length>0;if(!Ug||!Bg){alert("⚠️ GitHub credentials missing. Please set your GitHub username and token in Settings.");return}const U_=generateGitHubUrl(ja,Eh,La,Ta),B_=async()=>{try{await pathExists(Em)&&(console.log(`Cleaning up failed clone: removing ${Em} from IndexedDB`),await removeDirectory(Em))}catch(r6){console.error("Error cleaning up failed clone:",r6)}};try{await cloneRepository(U_,Em,qg,Ta)}catch(r6){throw console.error("Failed to clone repository:",r6),await B_(),r6}mc("adding-files"),Vd("Adding initial files...");const VC={name:Eh,version:"0.0.1"},tj=await openRepository(Em);await writeRepoFile(Em,"package.json",JSON.stringify(VC)),await commitChanges(tj,"package.json","Add package.json",{name:La,email:La}),await writeRepoFile(Em,"config.al",JSON.stringify({},null,2)),await commitChanges(tj,"config.al","Add config.al",{name:La,email:La});const aB="src/core.al";await writeRepoFile(Em,aB,`module ${Eh.toLowerCase()}.core`),await commitChanges(tj,aB,"Add core.al ",{name:La,email:La}),mc("pushing-changes"),Vd("Pushing changes to GitHub..."),await pushChanges(tj,"origin",qg,Ta),mc("loading-module"),Vd("Loading module...");try{await flushAllAndLoad(`/${Eh}`,{name:"studio"});const r6=getUserModuleNames();mc("adding-workspace"),Vd("Adding to workspace...");const J2={name:Pf,type:"App",gitHubOrg:ja,gitHubRepo:Eh,branch:qg,description:"",owner:localStorage.getItem("username")||"",version:"0.0.1",isEditable:!0};await ta(J2),Pl(!1),Fa(`/design/data-model/${ja}/${Eh}/${r6[0]}`,{state:{isNewTeam:!0}})}catch(r6){console.error(`Failed to load ${Eh}:`,r6);try{await pathExists(Em)&&(console.log(`Cleaning up failed clone: removing ${Em} from IndexedDB`),await removeDirectory(Em))}catch(J2){console.error("Error cleaning up failed clone:",J2)}Pl(!1)}}catch(Em){console.error(`Failed to clone repository: ${Em}`);try{const qg=`/${Eh}`;await pathExists(qg)&&(console.log(`Cleaning up failed clone: removing ${qg} from IndexedDB`),await removeDirectory(qg))}catch(qg){console.error("Error cleaning up failed clone:",qg)}Pl(!1)}}catch(Nf){console.error("Failed to create GitHub Repository:",Nf),Pl(!1)}},isLoading:wl,currentStep:pc,statusMessage:gc,loadingSteps:[{id:"creating-repo",label:"Creating GitHub repository"},{id:"cloning-repo",label:"Cloning repository"},{id:"adding-files",label:"Adding initial files"},{id:"committing-changes",label:"Committing changes"},{id:"pushing-changes",label:"Pushing to GitHub"},{id:"loading-module",label:"Loading module"},{id:"adding-workspace",label:"Adding to workspace"}]}},getDependenciesRecursive=async(ta,Ln,Ta=new Set)=>{const ja=Object.entries(Ln).filter(([Fa,wl])=>{const Pl=typeof wl=="string"&&wl.startsWith("git+http"),pc=!Ta.has(Fa);return Pl&&pc&&Ta.add(Fa),Pl&&pc});return ja.length===0?[]:(await Promise.all(ja.map(async([Fa])=>{const wl=[Fa];try{const Pl=await readDependencyPackageJsonFromGit(ta,Fa);if(Pl.dependencies){const pc=await getDependenciesRecursive(ta,Pl.dependencies,Ta);wl.push(...pc)}}catch(Pl){console.error(`Failed to process dependency ${Fa}:`,Pl)}return wl}))).flat()},fetchDependencies=async ta=>{const Ta=(await readPackageJsonFromGit(ta)).dependencies||{},ja=Object.entries(Ta).filter(([,Fa])=>typeof Fa=="string"&&Fa.startsWith("git+http")).map(([Fa])=>Fa),La=await getDependenciesRecursive(ta,Ta,new Set(ja));return Array.from(new Set([...ja,...La]))},useDependencies=()=>{const{currentTeam:ta}=useTeams(),Ln=ta?.GitHubRepo,{data:Ta=[],isLoading:ja}=useQuery({queryKey:["dependencies",Ln],queryFn:()=>fetchDependencies(Ln),enabled:!!Ln}),La=getUserModuleNames(),Fa=[Ln,...Ta].map(mc=>({label:mc||"",value:mc||""})),wl=mc=>{const gc=mc.toLowerCase(),Vd=gc.replace(/_/g,"");return La.filter(Wd=>{const kf=Wd.toLowerCase(),Pf=kf.split(".")[0];return kf.startsWith(gc)||Pf===Vd})},Pl=Ln||"",pc=Pl?wl(Pl)[0]:"";return{dependencies:Ta,dependenciesOptions:Fa,loading:ja,getDependenciesModule:wl,defaultDependency:Pl,defaultModule:pc}},useDoubleClick=(ta,Ln,Ta=300)=>{const ja=reactExports$1.useRef(null),La=reactExports$1.useRef(0),Fa=reactExports$1.useCallback(wl=>{wl.stopPropagation(),wl.preventDefault(),La.current+=1,La.current===1?ja.current=setTimeout(()=>{La.current===1&&ta(wl),La.current=0,ja.current=null},Ta):La.current===2&&(ja.current&&(clearTimeout(ja.current),ja.current=null),Ln(wl),La.current=0)},[ta,Ln,Ta]);return reactExports$1.useEffect(()=>()=>{ja.current&&clearTimeout(ja.current)},[]),Fa},useRepositoryClone=()=>{const ta=useNavigate(),[Ln,Ta]=reactExports$1.useState(!1),[ja,La]=reactExports$1.useState(""),[Fa,wl]=reactExports$1.useState(""),Pl=useAppStore(Nf=>Nf.setAppConfig),pc=UCe();useAppStore(Nf=>Nf.user);const mc="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",gc="hamza@fractl.io",Vd=reactExports$1.useCallback(()=>{const Nf=gc.trim().length>0,Eh=mc.trim().length>0;(!Nf||!Eh)&&console.warn("GitHub credentials missing - clone may fail for private repositories")},[mc,gc]),Wd=reactExports$1.useCallback(async(Nf,Eh,Em,qg,Ug)=>{const Bg=await readRepoFile(Nf,"package.json"),U_=JSON.parse(Bg);if(U_.dependencies){const Q2=[];for(const[q5,nj]of Object.entries(U_.dependencies))typeof nj=="string"&&nj.startsWith("git+http")&&Q2.push({appName:q5,url:nj});if(Q2.length>0){La(`Installing ${Q2.length} dependencies...`);const nj=(await cloneDependencies(Nf,Q2,gc,mc,(n6,l6,i6)=>{La(`[${l6}/${i6}] ${n6}`)})).filter(n6=>!n6.success);nj.length>0&&console.warn(`Failed to install ${nj.length} of ${Q2.length} dependencies`,nj.map(n6=>n6.appName))}}La("Loading application modules..."),await flushAllAndLoad(Nf,{name:"studio"});const B_=await loadAppConfig(Nf);Pl({...B_,__repoPath:Nf,__repoName:Eh,__gitHubOrg:qg});const VC=getUserModuleNames(),tj=VC.flatMap(Q2=>{const q5=fetchModule$2(Q2);return q5?q5.getAgentNames().filter(nj=>q5.getAgent(nj)?.isPublic()??!1).map(nj=>`${Q2}/${nj}`):[]}),aB=VC.flatMap(Q2=>fetchModule$2(Q2).getEntityNames().map(q5=>`${Q2}/${q5}`)),r6=VC.flatMap(Q2=>buildGraph(Q2).getRoots().map(nj=>`${nj.entity.getModuleName()}/${nj.entity.getEntryName()}`)),J2={Name:Em,Description:U_.description||"An application generated from "+Em},V_=await loadUISchema(Em,Nf,aB,r6,tj,J2);V_.appInfo||(V_.appInfo={}),V_.appInfo.apiUrl="http://localhost:8080",pc(V_);const sP={githubOrg:qg,teamName:Em,branch:Ug,projectPath:Nf};return __vitePreload(()=>import("./replService-4Oc5i5Yn.js"),__vite__mapDeps([48,6,29,1,42,43,12,17,19,25,20,23,24,18,44,31,26,34,45,11,13,10,9])).then(async({default:Q2})=>{try{await Q2.ensureReplSession(sP),await Q2.initializeFileTracking(Nf)}catch(q5){console.error("❌ Failed to setup REPL deployment:",q5)}}),VC.length>0?VC[0]:null},[Pl,gc,mc,La,pc]),kf=reactExports$1.useCallback(async Nf=>{Ta(!0),wl("");try{Vd();const{GitHubOrg:Eh,GitHubRepo:Em,Name:qg,Branch:Ug}=Nf,Bg=`/${Em}`,U_=generateGitHubUrl(Eh,Em,gc,mc);await pathExists(Bg)?La("Repository already exists. Loading modules..."):(La("Cloning repository..."),await cloneRepository(U_,Bg,Ug,mc)),await Wd(Bg,Em,qg,Eh,Ug)}catch(Eh){const Em=Eh instanceof Error?Eh.message:"Failed to clone repository";wl(Em),console.error("Error during repository clone:",Eh);try{const qg=`/${Nf.GitHubRepo}`;await pathExists(qg)&&(console.log(`Cleaning up failed clone: removing ${qg} from IndexedDB`),await removeDirectory(qg))}catch(qg){console.error("Error cleaning up failed clone:",qg)}}finally{Ta(!1)}},[Vd,gc,mc,Wd]),Pf=reactExports$1.useCallback((Nf,Eh,Em,qg,Ug)=>{const Bg=`/design/${Nf?"agents":"data-model"}/${Eh}/${Em}/${qg}`;Ug?ta(Bg,Ug):ta(Bg)},[ta]);return{isCloning:Ln,error:Fa,loadingMessage:ja,cloneAndProcess:kf,navigateToDesign:Pf,processRepository:Wd}};var I$8=Object.defineProperty,E$7=(ta,Ln,Ta)=>Ln in ta?I$8(ta,Ln,{enumerable:!0,configurable:!0,writable:!0,value:Ta}):ta[Ln]=Ta,w$9=(ta,Ln,Ta)=>E$7(ta,typeof Ln!="symbol"?Ln+"":Ln,Ta);function T$a(ta,Ln){for(var Ta=0;Ta<Ln.length;Ta++){const ja=Ln[Ta];if(typeof ja!="string"&&!Array.isArray(ja)){for(const La in ja)if(La!=="default"&&!(La in ta)){const Fa=Object.getOwnPropertyDescriptor(ja,La);Fa&&Object.defineProperty(ta,La,Fa.get?Fa:{enumerable:!0,get:()=>ja[La]})}}}return Object.freeze(Object.defineProperty(ta,Symbol.toStringTag,{value:"Module"}))}function z$5(ta){return{isFile:()=>ta.isFile(),isDirectory:()=>ta.isDirectory(),isSymbolicLink:()=>ta.isSymbolicLink(),size:ta.size,mtime:ta.mtime}}let j$a=class{async readFile(Ln){return(void 0)(Ln,"utf8")}async readFileBuffer(Ln){return(void 0)(Ln)}async writeFile(Ln,Ta){const ja=(void 0)(Ln);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async exists(Ln){try{return await(void 0)(Ln),!0}catch{return!1}}async mkdir(Ln){try{await(void 0)(Ln)}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async readdir(Ln){return(void 0)(Ln)}async stat(Ln){const Ta=await(void 0)(Ln);return z$5(Ta)}async lstat(Ln){const Ta=await(void 0)(Ln);return z$5(Ta)}async unlink(Ln){return(void 0)(Ln)}async rmdir(Ln){return(void 0)(Ln)}async copyFile(Ln,Ta){const ja=(void 0)(Ta);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async moveFile(Ln,Ta){const ja=(void 0)(Ta);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async ensureDir(Ln){try{await(void 0)(Ln,{recursive:!0})}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async removeDir(Ln){return(void 0)(Ln,{recursive:!0,force:!0})}async readDirectory(Ln){return(void 0)(Ln)}async writeFileSystemFromTree(Ln,Ta,ja){for(const La of Ln){const Fa=(void 0)(Ta,La.path);if(La.type==="directory")await this.ensureDir(Fa),La.children&&await this.writeFileSystemFromTree(La.children,Ta,ja);else{const wl=await ja(La.path);await this.writeFile(Fa,wl)}}}};function p$c(){return new j$a}function _$7(ta){return ta&&ta.__esModule&&Object.prototype.hasOwnProperty.call(ta,"default")?ta.default:ta}var b$8,S$a;function x$6(){if(S$a)return b$8;S$a=1;function ta(La){if(typeof La!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(La))}function Ln(La,Fa){for(var wl="",Pl=0,pc=-1,mc=0,gc,Vd=0;Vd<=La.length;++Vd){if(Vd<La.length)gc=La.charCodeAt(Vd);else{if(gc===47)break;gc=47}if(gc===47){if(!(pc===Vd-1||mc===1))if(pc!==Vd-1&&mc===2){if(wl.length<2||Pl!==2||wl.charCodeAt(wl.length-1)!==46||wl.charCodeAt(wl.length-2)!==46){if(wl.length>2){var Wd=wl.lastIndexOf("/");if(Wd!==wl.length-1){Wd===-1?(wl="",Pl=0):(wl=wl.slice(0,Wd),Pl=wl.length-1-wl.lastIndexOf("/")),pc=Vd,mc=0;continue}}else if(wl.length===2||wl.length===1){wl="",Pl=0,pc=Vd,mc=0;continue}}Fa&&(wl.length>0?wl+="/..":wl="..",Pl=2)}else wl.length>0?wl+="/"+La.slice(pc+1,Vd):wl=La.slice(pc+1,Vd),Pl=Vd-pc-1;pc=Vd,mc=0}else gc===46&&mc!==-1?++mc:mc=-1}return wl}function Ta(La,Fa){var wl=Fa.dir||Fa.root,Pl=Fa.base||(Fa.name||"")+(Fa.ext||"");return wl?wl===Fa.root?wl+Pl:wl+La+Pl:Pl}var ja={resolve:function(){for(var La="",Fa=!1,wl,Pl=arguments.length-1;Pl>=-1&&!Fa;Pl--){var pc;Pl>=0?pc=arguments[Pl]:(wl===void 0&&(wl=process.cwd()),pc=wl),ta(pc),pc.length!==0&&(La=pc+"/"+La,Fa=pc.charCodeAt(0)===47)}return La=Ln(La,!Fa),Fa?La.length>0?"/"+La:"/":La.length>0?La:"."},normalize:function(La){if(ta(La),La.length===0)return".";var Fa=La.charCodeAt(0)===47,wl=La.charCodeAt(La.length-1)===47;return La=Ln(La,!Fa),La.length===0&&!Fa&&(La="."),La.length>0&&wl&&(La+="/"),Fa?"/"+La:La},isAbsolute:function(La){return ta(La),La.length>0&&La.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var La,Fa=0;Fa<arguments.length;++Fa){var wl=arguments[Fa];ta(wl),wl.length>0&&(La===void 0?La=wl:La+="/"+wl)}return La===void 0?".":ja.normalize(La)},relative:function(La,Fa){if(ta(La),ta(Fa),La===Fa||(La=ja.resolve(La),Fa=ja.resolve(Fa),La===Fa))return"";for(var wl=1;wl<La.length&&La.charCodeAt(wl)===47;++wl);for(var Pl=La.length,pc=Pl-wl,mc=1;mc<Fa.length&&Fa.charCodeAt(mc)===47;++mc);for(var gc=Fa.length,Vd=gc-mc,Wd=pc<Vd?pc:Vd,kf=-1,Pf=0;Pf<=Wd;++Pf){if(Pf===Wd){if(Vd>Wd){if(Fa.charCodeAt(mc+Pf)===47)return Fa.slice(mc+Pf+1);if(Pf===0)return Fa.slice(mc+Pf)}else pc>Wd&&(La.charCodeAt(wl+Pf)===47?kf=Pf:Pf===0&&(kf=0));break}var Nf=La.charCodeAt(wl+Pf),Eh=Fa.charCodeAt(mc+Pf);if(Nf!==Eh)break;Nf===47&&(kf=Pf)}var Em="";for(Pf=wl+kf+1;Pf<=Pl;++Pf)(Pf===Pl||La.charCodeAt(Pf)===47)&&(Em.length===0?Em+="..":Em+="/..");return Em.length>0?Em+Fa.slice(mc+kf):(mc+=kf,Fa.charCodeAt(mc)===47&&++mc,Fa.slice(mc))},_makeLong:function(La){return La},dirname:function(La){if(ta(La),La.length===0)return".";for(var Fa=La.charCodeAt(0),wl=Fa===47,Pl=-1,pc=!0,mc=La.length-1;mc>=1;--mc)if(Fa=La.charCodeAt(mc),Fa===47){if(!pc){Pl=mc;break}}else pc=!1;return Pl===-1?wl?"/":".":wl&&Pl===1?"//":La.slice(0,Pl)},basename:function(La,Fa){if(Fa!==void 0&&typeof Fa!="string")throw new TypeError('"ext" argument must be a string');ta(La);var wl=0,Pl=-1,pc=!0,mc;if(Fa!==void 0&&Fa.length>0&&Fa.length<=La.length){if(Fa.length===La.length&&Fa===La)return"";var gc=Fa.length-1,Vd=-1;for(mc=La.length-1;mc>=0;--mc){var Wd=La.charCodeAt(mc);if(Wd===47){if(!pc){wl=mc+1;break}}else Vd===-1&&(pc=!1,Vd=mc+1),gc>=0&&(Wd===Fa.charCodeAt(gc)?--gc===-1&&(Pl=mc):(gc=-1,Pl=Vd))}return wl===Pl?Pl=Vd:Pl===-1&&(Pl=La.length),La.slice(wl,Pl)}else{for(mc=La.length-1;mc>=0;--mc)if(La.charCodeAt(mc)===47){if(!pc){wl=mc+1;break}}else Pl===-1&&(pc=!1,Pl=mc+1);return Pl===-1?"":La.slice(wl,Pl)}},extname:function(La){ta(La);for(var Fa=-1,wl=0,Pl=-1,pc=!0,mc=0,gc=La.length-1;gc>=0;--gc){var Vd=La.charCodeAt(gc);if(Vd===47){if(!pc){wl=gc+1;break}continue}Pl===-1&&(pc=!1,Pl=gc+1),Vd===46?Fa===-1?Fa=gc:mc!==1&&(mc=1):Fa!==-1&&(mc=-1)}return Fa===-1||Pl===-1||mc===0||mc===1&&Fa===Pl-1&&Fa===wl+1?"":La.slice(Fa,Pl)},format:function(La){if(La===null||typeof La!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof La);return Ta("/",La)},parse:function(La){ta(La);var Fa={root:"",dir:"",base:"",ext:"",name:""};if(La.length===0)return Fa;var wl=La.charCodeAt(0),Pl=wl===47,pc;Pl?(Fa.root="/",pc=1):pc=0;for(var mc=-1,gc=0,Vd=-1,Wd=!0,kf=La.length-1,Pf=0;kf>=pc;--kf){if(wl=La.charCodeAt(kf),wl===47){if(!Wd){gc=kf+1;break}continue}Vd===-1&&(Wd=!1,Vd=kf+1),wl===46?mc===-1?mc=kf:Pf!==1&&(Pf=1):mc!==-1&&(Pf=-1)}return mc===-1||Vd===-1||Pf===0||Pf===1&&mc===Vd-1&&mc===gc+1?Vd!==-1&&(gc===0&&Pl?Fa.base=Fa.name=La.slice(1,Vd):Fa.base=Fa.name=La.slice(gc,Vd)):(gc===0&&Pl?(Fa.name=La.slice(1,mc),Fa.base=La.slice(1,Vd)):(Fa.name=La.slice(gc,mc),Fa.base=La.slice(gc,Vd)),Fa.ext=La.slice(mc,Vd)),gc>0?Fa.dir=La.slice(0,gc-1):Pl&&(Fa.dir="/"),Fa},sep:"/",delimiter:":",win32:null,posix:null};return ja.posix=ja,b$8=ja,b$8}var A$7=x$6();const B$5=_$7(A$7),O$5=T$a({__proto__:null,default:B$5},[A$7]);function k$a(ta){if(ta&&typeof ta=="object"){const Ln=ta,Ta=typeof Ln.isFile=="function"?Ln.isFile():typeof Ln.isFile=="boolean"?Ln.isFile:Ln.type==="file"||!Ln.type&&!Ln.isDirectory,ja=typeof Ln.isDirectory=="function"?Ln.isDirectory():typeof Ln.isDirectory=="boolean"?Ln.isDirectory:Ln.type==="dir"||Ln.type==="directory",La=typeof Ln.size=="number"?Ln.size:0;let Fa;return Ln.mtime instanceof Date?Fa=Ln.mtime:typeof Ln.mtime=="number"?Fa=new Date(Ln.mtime):typeof Ln.mtimeMs=="number"?Fa=new Date(Ln.mtimeMs):Fa=new Date,{isFile:()=>Ta,isDirectory:()=>ja,isSymbolicLink:()=>!1,size:La,mtime:Fa}}return{isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1,size:0,mtime:new Date}}let P$9=class{constructor(){w$9(this,"fs"),w$9(this,"initialized",!1),w$9(this,"path",O$5)}async initialize(Ln={}){if(this.initialized)return;const Ta=Ln.name||"fs",ja=new L$9(Ta,{wipe:Ln.wipe});this.fs=ja.promises,this.initialized=!0}ensureInitialized(){if(!this.initialized)throw new Error("LightningFileSystem is not initialized. Call initialize() first.")}async readFile(Ln){return this.ensureInitialized(),(await this.fs.readFile(Ln,{encoding:"utf8"})).toString()}async readFileBuffer(Ln){return this.ensureInitialized(),this.fs.readFile(Ln)}async writeFile(Ln,Ta){this.ensureInitialized();const ja=Ln.substring(0,Ln.lastIndexOf("/"));return ja&&await this.ensureDir(ja),this.fs.writeFile(Ln,Ta)}async exists(Ln){this.ensureInitialized();try{return await this.fs.stat(Ln),!0}catch{return!1}}async mkdir(Ln,Ta){this.ensureInitialized();try{return await this.fs.mkdir(Ln,Ta)}catch(ja){if(ja&&typeof ja=="object"&&"code"in ja&&ja.code!=="EEXIST")throw ja}}async readdir(Ln){return this.ensureInitialized(),this.fs.readdir(Ln)}async stat(Ln){this.ensureInitialized();const Ta=await this.fs.stat(Ln);return k$a(Ta)}async lstat(Ln){this.ensureInitialized();const Ta=await this.fs.stat(Ln);return k$a(Ta)}async unlink(Ln){return this.ensureInitialized(),this.fs.unlink(Ln)}async rmdir(Ln){return this.ensureInitialized(),this.fs.rmdir(Ln)}async copyFile(Ln,Ta){this.ensureInitialized();const ja=Ta.substring(0,Ta.lastIndexOf("/"));ja&&await this.ensureDir(ja);const La=await this.readFileBuffer(Ln);return this.writeFile(Ta,La)}async moveFile(Ln,Ta){this.ensureInitialized();const ja=Ta.substring(0,Ta.lastIndexOf("/"));ja&&await this.ensureDir(ja),await this.copyFile(Ln,Ta),await this.unlink(Ln)}async ensureDir(Ln){if(this.ensureInitialized(),!await this.exists(Ln))try{await this.fs.mkdir(Ln,{recursive:!0})}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async removeDir(Ln){if(this.ensureInitialized(),!await this.exists(Ln))return;if((await this.stat(Ln)).isFile())return this.unlink(Ln);const Ta=await this.readdir(Ln);for(const ja of Ta){const La=`${Ln}/${ja}`;await this.removeDir(La)}return this.rmdir(Ln)}async readDirectory(Ln){return this.ensureInitialized(),this.fs.readdir(Ln)}async writeFileSystemFromTree(Ln,Ta,ja){for(const La of Ln){const Fa=this.path.join(Ta,La.path);if(La.type==="directory")await this.mkdir(Fa,{recursive:!0}),La.children&&await this.writeFileSystemFromTree(La.children,Ta,ja);else{const wl=await ja(La.path);await this.writeFile(Fa,wl)}}}};async function M$6(ta){const Ln=new P$9;return await Ln.initialize(ta),Ln}async function $$6(ta){return typeof window>"u"?p$c():M$6(ta)}let fsInstance=null,isLocalModeInstance=!1;const getFS=async()=>((!fsInstance||!isLocalModeInstance)&&(fsInstance=null,fsInstance=await $$6({name:"local-studio",wipe:!0}),isLocalModeInstance=!0),fsInstance);async function fetchFileTree(){const Ln=await fetch("http://localhost:4000/files");if(!Ln.ok)throw new Error("Failed to fetch file tree");return Ln.json()}async function fetchFileContent(ta){const Ta=await fetch(`http://localhost:4000/file?path=${encodeURIComponent(ta)}`);if(!Ta.ok)throw new Error(`Failed to fetch file content for: ${ta}`);const{content:ja}=await Ta.json();return ja}async function fetchPackageInfo(ta){const ja=await fetch("http://localhost:4000/info");return ja.ok?await ja.json():{}}const useServeMode=()=>{const ta=useNavigate(),Ln=useMatches(),Ta=useQueryClient(),{processRepository:ja}=useRepositoryClone(),[La,Fa]=reactExports$1.useState(""),[wl,Pl]=reactExports$1.useState(null);return{initializeServeMode:reactExports$1.useCallback(async()=>{Fa("Connecting to local server..."),Pl(null),Ta.invalidateQueries({queryKey:["localPackageInfo"]});try{const mc=await fetchFileTree(),gc=await fetchPackageInfo();console.log(gc);let Vd="",Wd="";if(gc&&gc.name)if(Vd=gc.name,Vd.startsWith("@")){const U_=Vd.substring(1).split("/");U_.length===2&&(Wd=U_[0],Vd=U_[1])}else Wd="local-org",Vd=gc.name;const kf=Wd,Pf=Vd,Nf=`/${Pf}`;Fa("Loading file system..."),await(await getFS()).writeFileSystemFromTree(mc,Nf,fetchFileContent),Fa("Processing project...");const Em=await ja(Nf,Pf,Pf,kf,"main"),Ug=Ln[Ln.length-1]?.id;if(["data-model","marketplace-data-model","agents","workflow","security","ui","settings"].includes(Ug))return;ta(Em?`/design/agents/${kf}/${Pf}/${Em}`:`/design/agents/${kf}/${Pf}`)}catch(mc){const gc=mc instanceof Error?mc.message:"An unknown error occurred";Pl(gc),console.error("Failed to initialize serve mode:",mc)}finally{Fa("")}},[ja,ta,Ln,Ta]),loadingMessage:La,error:wl}},validationScehma=create$3().shape({email:create$6().email("Invalid email").required("Email is required"),password:create$6().required("Password is required")}),SignIn=()=>{const{login:ta}=useAuth(),Ln=useNavigate();return reactExports$1.useEffect(()=>{localStorage.getItem("id_token")&&Ln("/home")}),jsxRuntimeExports$1.jsx(Formik,{initialValues:{email:"",password:""},validationSchema:validationScehma,onSubmit:Ta=>{const{email:ja,password:La}=Ta;ta(ja,La)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-2 items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Sign In"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Get started with building your team of AI Agents"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx("div",{className:"auth-link text-right",onClick:()=>Ln("/forgot-password"),children:"Forgot password?"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Sign in"}),jsxRuntimeExports$1.jsxs("p",{className:"flex justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"No account ?"}),jsxRuntimeExports$1.jsx(Link,{className:"auth-link font-bold",to:"/signup",children:"Sign Up"})]})]})})},uppercaseRegex=/[A-Z]/,lowercaseRegex=/[a-z]/,numberRegex=/[0-9]/,specialCharRegex=/[!@#$%^&*(),.?":{}|<>]/,validationSchema$e=create$3().shape({firstName:create$6().required("First Name is required").min(2,"First Name must be at least 2 characters").max(50,"First Name must be less than 50 characters"),lastName:create$6().required("Last Name is required").min(2,"Last Name must be at least 2 characters").max(50,"Last Name must be less than 50 characters"),email:create$6().required("Email is required").email("Invalid email address"),password:create$6().required("Password is required").min(8,"Password must be at least 8 characters").matches(uppercaseRegex,"Password must contain at least one uppercase letter").matches(lowercaseRegex,"Password must contain at least one lowercase letter").matches(numberRegex,"Password must contain at least one number").matches(specialCharRegex,"Password must contain at least one special character"),confirmPassword:create$6().required("Confirm Password is required").oneOf([create$9("password")],"Passwords don't match")}),SignUp=()=>{const ta=useNavigate(),{signUp:Ln,isSigningUp:Ta}=useSignUp(),[ja,La]=reactExports$1.useState(null);return jsxRuntimeExports$1.jsx(Formik,{initialValues:{firstName:"",lastName:"",email:"",password:"",confirmPassword:""},validationSchema:validationSchema$e,onSubmit:async(Fa,{setSubmitting:wl})=>{La(null);try{const Pl=await Ln({firstName:Fa.firstName,lastName:Fa.lastName,email:Fa.email,password:Fa.password});!Pl.success&&Pl.error&&La(Pl.error)}catch{La("An unexpected error occurred. Please try again.")}finally{wl(!1)}},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-2 items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Sign Up"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Get started with building your team of AI Agents"})]}),jsxRuntimeExports$1.jsxs("div",{className:"md:grid flex flex-col md:grid-cols-2 gap-2",children:[jsxRuntimeExports$1.jsx(lAe,{name:"firstName",placeholder:"First Name"}),jsxRuntimeExports$1.jsx(lAe,{name:"lastName",placeholder:"Last Name"}),jsxRuntimeExports$1.jsx("div",{className:"col-span-2",children:jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"})}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx(fAe,{name:"confirmPassword",placeholder:"Confirm Password"})]}),ja&&jsxRuntimeExports$1.jsx("div",{className:"text-red-500 text-sm text-center p-2",children:ja}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",disabled:Ta,children:Ta?"Creating Account...":"Create Account"}),jsxRuntimeExports$1.jsxs("p",{className:"flex justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already have an account ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})},validationSchema$d=create$3().shape({email:create$6().required("Email is required").email("Invalid email address")}),ForgotPassword=()=>{const ta=useNavigate();return jsxRuntimeExports$1.jsx(Formik,{initialValues:{email:""},validationSchema:validationSchema$d,onSubmit:Ln=>{const{email:Ta}=Ln;console.log(Ta)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Reset Password"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Send confirmation code to your email"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Send confirmation code"}),jsxRuntimeExports$1.jsxs("p",{className:"flex flex-col md:flex-row justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already recovered your password ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})},numberOnlyRegex=/^[0-9]+$/,validationSchema$c=create$3().shape({email:create$6().required("Email is required").email("Invalid email address"),password:create$6().required("Password is required"),code:create$6().matches(numberOnlyRegex,"Code must contain only numbers")}),RecoverPassword=()=>{const ta=useNavigate();return jsxRuntimeExports$1.jsx(Formik,{validationSchema:validationSchema$c,initialValues:{email:"",password:"",code:""},onSubmit:Ln=>{const{email:Ta,password:ja,code:La}=Ln;console.log(Ta,ja,La)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Reset Password"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Set new password"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx(fAe,{name:"code",placeholder:"Code"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Set new password"}),jsxRuntimeExports$1.jsxs("p",{className:"flex flex-col md:flex-row justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already recovered your password ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})};var classnames={exports:{}};/*!
|
|
34779
|
+
`)).length,La=0;La<ja;La++){var wl=ta.charCodeAt(La),Pl=null;wl<128?Ta++:Pl=wl>127&&wl<2048?String.fromCharCode(wl>>6|192,63&wl|128):String.fromCharCode(wl>>12|224,wl>>6&63|128,63&wl|128),D$b(Pl)||(Ta>Ln&&(Fa+=ta.substring(Ln,Ta)),Fa+=Pl,Ln=Ta=La+1)}return Ta>Ln&&(Fa+=ta.substring(Ln,ta.length)),Fa},an$1=!!u$h||!!l$9,ln="text/plain",un$1=function(ta,Ln,Ta){var ja;Ta===void 0&&(Ta=!0);var[La,Fa]=ta.split("?"),wl=g$8({},Ln),Pl=(ja=Fa?.split("&").map((mc=>{var gc,[Vd,Wd]=mc.split("="),kf=Ta&&(gc=wl[Vd])!==null&&gc!==void 0?gc:Wd;return delete wl[Vd],Vd+"="+kf})))!==null&&ja!==void 0?ja:[],pc=ue$1(wl);return pc&&Pl.push(pc),La+"?"+Pl.join("&")},hn=(ta,Ln)=>JSON.stringify(ta,((Ta,ja)=>typeof ja=="bigint"?ja.toString():ja),Ln),dn=ta=>{var{data:Ln,compression:Ta}=ta;if(Ln){if(Ta===oe$2.GZipJS){var ja=nn$1((function(pc,mc){var gc=pc.length;if(typeof TextEncoder<"u")return new TextEncoder().encode(pc);for(var Vd=new Ss(pc.length+(pc.length>>>1)),Wd=0,kf=function(Em){Vd[Wd++]=Em},Pf=0;Pf<gc;++Pf){if(Wd+5>Vd.length){var Nf=new Ss(Wd+8+(gc-Pf<<1));Nf.set(Vd),Vd=Nf}var Eh=pc.charCodeAt(Pf);Eh<128||mc?kf(Eh):Eh<2048?(kf(192|Eh>>>6),kf(128|63&Eh)):Eh>55295&&Eh<57344?(kf(240|(Eh=65536+(1047552&Eh)|1023&pc.charCodeAt(++Pf))>>>18),kf(128|Eh>>>12&63),kf(128|Eh>>>6&63),kf(128|63&Eh)):(kf(224|Eh>>>12),kf(128|Eh>>>6&63),kf(128|63&Eh))}return Ws(Vd,0,Wd)})(hn(Ln)),{mtime:0}),La=new Blob([ja],{type:ln});return{contentType:ln,body:La,estimatedSize:La.size}}if(Ta===oe$2.Base64){var Fa=(function(pc){var mc,gc,Vd,Wd,kf,Pf="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Nf=0,Eh=0,Em="",qg=[];if(!pc)return pc;pc=on$1(pc);do mc=(kf=pc.charCodeAt(Nf++)<<16|pc.charCodeAt(Nf++)<<8|pc.charCodeAt(Nf++))>>18&63,gc=kf>>12&63,Vd=kf>>6&63,Wd=63&kf,qg[Eh++]=Pf.charAt(mc)+Pf.charAt(gc)+Pf.charAt(Vd)+Pf.charAt(Wd);while(Nf<pc.length);switch(Em=qg.join(""),pc.length%3){case 1:Em=Em.slice(0,-2)+"==";break;case 2:Em=Em.slice(0,-1)+"="}return Em})(hn(Ln)),wl=(pc=>"data="+encodeURIComponent(typeof pc=="string"?pc:hn(pc)))(Fa);return{contentType:"application/x-www-form-urlencoded",body:wl,estimatedSize:new Blob([wl]).size}}var Pl=hn(Ln);return{contentType:"application/json",body:Pl,estimatedSize:new Blob([Pl]).size}}},vn=[];l$9&&vn.push({transport:"fetch",method:ta=>{var Ln,Ta,{contentType:ja,body:La,estimatedSize:Fa}=(Ln=dn(ta))!==null&&Ln!==void 0?Ln:{},wl=new Headers;Ot(ta.headers,(function(gc,Vd){wl.append(Vd,gc)})),ja&&wl.append("Content-Type",ja);var Pl=ta.url,pc=null;if(h$c){var mc=new h$c;pc={signal:mc.signal,timeout:setTimeout((()=>mc.abort()),ta.timeout)}}l$9(Pl,g$8({method:ta?.method||"GET",headers:wl,keepalive:ta.method==="POST"&&(Fa||0)<52428.8,body:La,signal:(Ta=pc)==null?void 0:Ta.signal},ta.fetchOptions)).then((gc=>gc.text().then((Vd=>{var Wd={statusCode:gc.status,text:Vd};if(gc.status===200)try{Wd.json=JSON.parse(Vd)}catch(kf){Pt$2.error(kf)}ta.callback==null||ta.callback(Wd)})))).catch((gc=>{Pt$2.error(gc),ta.callback==null||ta.callback({statusCode:0,text:gc})})).finally((()=>pc?clearTimeout(pc.timeout):null))}}),u$h&&vn.push({transport:"XHR",method:ta=>{var Ln,Ta=new u$h;Ta.open(ta.method||"GET",ta.url,!0);var{contentType:ja,body:La}=(Ln=dn(ta))!==null&&Ln!==void 0?Ln:{};Ot(ta.headers,(function(Fa,wl){Ta.setRequestHeader(wl,Fa)})),ja&&Ta.setRequestHeader("Content-Type",ja),ta.timeout&&(Ta.timeout=ta.timeout),ta.disableXHRCredentials||(Ta.withCredentials=!0),Ta.onreadystatechange=()=>{if(Ta.readyState===4){var Fa={statusCode:Ta.status,text:Ta.responseText};if(Ta.status===200)try{Fa.json=JSON.parse(Ta.responseText)}catch{}ta.callback==null||ta.callback(Fa)}},Ta.send(La)}}),n$9!=null&&n$9.sendBeacon&&vn.push({transport:"sendBeacon",method:ta=>{var Ln=un$1(ta.url,{beacon:"1"});try{var Ta,{contentType:ja,body:La}=(Ta=dn(ta))!==null&&Ta!==void 0?Ta:{},Fa=typeof La=="string"?new Blob([La],{type:ja}):La;n$9.sendBeacon(Ln,Fa)}catch{}}});var cn$1=function(ta,Ln){if(!(function(Ta){try{new RegExp(Ta)}catch{return!1}return!0})(Ln))return!1;try{return new RegExp(Ln).test(ta)}catch{return!1}};function fn$1(ta,Ln,Ta){return hn({distinct_id:ta,userPropertiesToSet:Ln,userPropertiesToSetOnce:Ta})}var pn={exact:(ta,Ln)=>Ln.some((Ta=>ta.some((ja=>Ta===ja)))),is_not:(ta,Ln)=>Ln.every((Ta=>ta.every((ja=>Ta!==ja)))),regex:(ta,Ln)=>Ln.some((Ta=>ta.some((ja=>cn$1(Ta,ja))))),not_regex:(ta,Ln)=>Ln.every((Ta=>ta.every((ja=>!cn$1(Ta,ja))))),icontains:(ta,Ln)=>Ln.map(gn).some((Ta=>ta.map(gn).some((ja=>Ta.includes(ja))))),not_icontains:(ta,Ln)=>Ln.map(gn).every((Ta=>ta.map(gn).every((ja=>!Ta.includes(ja)))))},gn=ta=>ta.toLowerCase(),_n=Tt$1("[Error tracking]");class mn{constructor(Ln){var Ta,ja;this.Jt=[],this.Kt=new it$1([new pt$1,new St$1,new _t$1,new gt$2,new $t,new xt,new yt$1,new Et$2],ft$1("web:javascript",lt$1,dt$2)),this._instance=Ln,this.Jt=(Ta=(ja=this._instance.persistence)==null?void 0:ja.get_property(Xt))!==null&&Ta!==void 0?Ta:[]}onRemoteConfig(Ln){var Ta,ja,La,Fa=(Ta=(ja=Ln.errorTracking)==null?void 0:ja.suppressionRules)!==null&&Ta!==void 0?Ta:[],wl=(La=Ln.errorTracking)==null?void 0:La.captureExtensionExceptions;this.Jt=Fa,this._instance.persistence&&this._instance.persistence.register({[Xt]:this.Jt,[Qt]:wl})}get Yt(){var Ln,Ta=!!this._instance.get_property(Qt),ja=this._instance.config.error_tracking.captureExtensionExceptions;return(Ln=ja??Ta)!==null&&Ln!==void 0&&Ln}buildProperties(Ln,Ta){return this.Kt.buildFromUnknown(Ln,{syntheticException:Ta?.syntheticException,mechanism:{handled:Ta?.handled}})}sendExceptionEvent(Ln){var Ta=Ln.$exception_list;if(this.Xt(Ta)){if(this.Qt(Ta))return void _n.info("Skipping exception capture because a suppression rule matched");if(!this.Yt&&this.Zt(Ta))return void _n.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ti(Ta))return void _n.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",Ln,{_noTruncate:!0,_batchKey:"exceptionEvent"})}Qt(Ln){if(Ln.length===0)return!1;var Ta=Ln.reduce(((ja,La)=>{var{type:Fa,value:wl}=La;return M$7(Fa)&&Fa.length>0&&ja.$exception_types.push(Fa),M$7(wl)&&wl.length>0&&ja.$exception_values.push(wl),ja}),{$exception_types:[],$exception_values:[]});return this.Jt.some((ja=>{var La=ja.values.map((Fa=>{var wl,Pl=pn[Fa.operator],pc=I$9(Fa.value)?Fa.value:[Fa.value],mc=(wl=Ta[Fa.key])!==null&&wl!==void 0?wl:[];return pc.length>0&&Pl(pc,mc)}));return ja.type==="OR"?La.some(Boolean):La.every(Boolean)}))}Zt(Ln){return Ln.flatMap((Ta=>{var ja,La;return(ja=(La=Ta.stacktrace)==null?void 0:La.frames)!==null&&ja!==void 0?ja:[]})).some((Ta=>Ta.filename&&Ta.filename.startsWith("chrome-extension://")))}ti(Ln){if(Ln.length>0){var Ta,ja,La,Fa,wl=(Ta=(ja=Ln[0].stacktrace)==null?void 0:ja.frames)!==null&&Ta!==void 0?Ta:[],Pl=wl[wl.length-1];return(La=Pl==null||(Fa=Pl.filename)==null?void 0:Fa.includes("posthog.com/static"))!==null&&La!==void 0&&La}return!1}Xt(Ln){return!j$b(Ln)&&I$9(Ln)}}var yn=Tt$1("[FeatureFlags]"),bn=Tt$1("[FeatureFlags]",{debugEnabled:!0}),wn="$active_feature_flags",xn="$override_feature_flags",$n="$feature_flag_payloads",En="$override_feature_flag_payloads",Sn="$feature_flag_request_id",kn=ta=>{var Ln={};for(var[Ta,ja]of Dt$1(ta||{}))ja&&(Ln[Ta]=ja);return Ln},Pn=ta=>{var Ln=ta.flags;return Ln?(ta.featureFlags=Object.fromEntries(Object.keys(Ln).map((Ta=>{var ja;return[Ta,(ja=Ln[Ta].variant)!==null&&ja!==void 0?ja:Ln[Ta].enabled]}))),ta.featureFlagPayloads=Object.fromEntries(Object.keys(Ln).filter((Ta=>Ln[Ta].enabled)).filter((Ta=>{var ja;return(ja=Ln[Ta].metadata)==null?void 0:ja.payload})).map((Ta=>{var ja;return[Ta,(ja=Ln[Ta].metadata)==null?void 0:ja.payload]})))):yn.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),ta},Tn=(function(ta){return ta.FeatureFlags="feature_flags",ta.Recordings="recordings",ta})({});class In{constructor(Ln){this.ii=!1,this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this._instance=Ln,this.featureFlagEventHandlers=[]}li(){var Ln=this._instance.config.evaluation_environments;return Ln!=null&&Ln.length?Ln.filter((Ta=>{var ja=Ta&&typeof Ta=="string"&&Ta.trim().length>0;return ja||yn.error("Invalid evaluation environment found:",Ta,"Expected non-empty string"),ja})):[]}ui(){return this.li().length>0}flags(){if(this._instance.config.__preview_remote_config)this.oi=!0;else{var Ln=!this.hi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.di({disableFlags:Ln})}}get hasLoadedFlags(){return this.ei}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var Ln=this._instance.get_property(ai),Ta=this._instance.get_property(xn),ja=this._instance.get_property(En);if(!ja&&!Ta)return Ln||{};var La=Mt$2({},Ln||{}),Fa=[...new Set([...Object.keys(ja||{}),...Object.keys(Ta||{})])];for(var wl of Fa){var Pl,pc,mc=La[wl],gc=Ta?.[wl],Vd=O$6(gc)?(Pl=mc?.enabled)!==null&&Pl!==void 0&&Pl:!!gc,Wd=O$6(gc)?mc.variant:typeof gc=="string"?gc:void 0,kf=ja?.[wl],Pf=g$8({},mc,{enabled:Vd,variant:Vd?Wd??mc?.variant:void 0});Vd!==mc?.enabled&&(Pf.original_enabled=mc?.enabled),Wd!==mc?.variant&&(Pf.original_variant=mc?.variant),kf&&(Pf.metadata=g$8({},mc?.metadata,{payload:kf,original_payload:mc==null||(pc=mc.metadata)==null?void 0:pc.payload})),La[wl]=Pf}return this.ii||(yn.warn(" Overriding feature flag details!",{flagDetails:Ln,overriddenPayloads:ja,finalDetails:La}),this.ii=!0),La}getFlagVariants(){var Ln=this._instance.get_property(ni),Ta=this._instance.get_property(xn);if(!Ta)return Ln||{};for(var ja=Mt$2({},Ln),La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)ja[La[Fa]]=Ta[La[Fa]];return this.ii||(yn.warn(" Overriding feature flags!",{enabledFlags:Ln,overriddenFlags:Ta,finalFlags:ja}),this.ii=!0),ja}getFlagPayloads(){var Ln=this._instance.get_property($n),Ta=this._instance.get_property(En);if(!Ta)return Ln||{};for(var ja=Mt$2({},Ln||{}),La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)ja[La[Fa]]=Ta[La[Fa]];return this.ii||(yn.warn(" Overriding feature flag payloads!",{flagPayloads:Ln,overriddenPayloads:Ta,finalPayloads:ja}),this.ii=!0),ja}reloadFeatureFlags(){this.si||this._instance.config.advanced_disable_feature_flags||this.hi||(this.hi=setTimeout((()=>{this.di()}),5))}vi(){clearTimeout(this.hi),this.hi=void 0}ensureFlagsLoaded(){this.ei||this.ri||this.hi||this.reloadFeatureFlags()}setAnonymousDistinctId(Ln){this.$anon_distinct_id=Ln}setReloadingPaused(Ln){this.si=Ln}di(Ln){var Ta;if(this.vi(),!this._instance.M())if(this.ri)this.ni=!0;else{var ja={token:this._instance.config.token,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:g$8({},((Ta=this._instance.persistence)==null?void 0:Ta.get_initial_props())||{},this._instance.get_property(li)||{}),group_properties:this._instance.get_property(ui)};(Ln!=null&&Ln.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(ja.disable_flags=!0),this.ui()&&(ja.evaluation_environments=this.li());var La=this._instance.config.__preview_remote_config,Fa=La?"/flags/?v=2":"/flags/?v=2&config=true",wl=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",Pl=this._instance.requestRouter.endpointFor("flags",Fa+wl);La&&(ja.timezone=ps()),this.ri=!0,this._instance.ci({method:"POST",url:Pl,data:ja,compression:this._instance.config.disable_compression?void 0:oe$2.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:pc=>{var mc,gc,Vd=!0;if(pc.statusCode===200&&(this.ni||(this.$anon_distinct_id=void 0),Vd=!1),this.ri=!1,this.oi||(this.oi=!0,this._instance.fi((gc=pc.json)!==null&&gc!==void 0?gc:{})),!ja.disable_flags||this.ni)if(this.ai=!Vd,pc.json&&(mc=pc.json.quotaLimited)!=null&&mc.includes(Tn.FeatureFlags))yn.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.");else{var Wd;ja.disable_flags||this.receivedFeatureFlags((Wd=pc.json)!==null&&Wd!==void 0?Wd:{},Vd),this.ni&&(this.ni=!1,this.di())}}})}}getFeatureFlag(Ln,Ta){if(Ta===void 0&&(Ta={}),this.ei||this.getFlags()&&this.getFlags().length>0){var ja=this.getFlagVariants()[Ln],La=""+ja,Fa=this._instance.get_property(Sn)||void 0,wl=this._instance.get_property(vi)||{};if((Ta.send_event||!("send_event"in Ta))&&(!(Ln in wl)||!wl[Ln].includes(La))){var Pl,pc,mc,gc,Vd,Wd,kf,Pf,Nf;I$9(wl[Ln])?wl[Ln].push(La):wl[Ln]=[La],(Pl=this._instance.persistence)==null||Pl.register({[vi]:wl});var Eh=this.getFeatureFlagDetails(Ln),Em={$feature_flag:Ln,$feature_flag_response:ja,$feature_flag_payload:this.getFeatureFlagPayload(Ln)||null,$feature_flag_request_id:Fa,$feature_flag_bootstrapped_response:((pc=this._instance.config.bootstrap)==null||(pc=pc.featureFlags)==null?void 0:pc[Ln])||null,$feature_flag_bootstrapped_payload:((mc=this._instance.config.bootstrap)==null||(mc=mc.featureFlagPayloads)==null?void 0:mc[Ln])||null,$used_bootstrap_value:!this.ai};O$6(Eh==null||(gc=Eh.metadata)==null?void 0:gc.version)||(Em.$feature_flag_version=Eh.metadata.version);var qg,Ug=(Vd=Eh==null||(Wd=Eh.reason)==null?void 0:Wd.description)!==null&&Vd!==void 0?Vd:Eh==null||(kf=Eh.reason)==null?void 0:kf.code;Ug&&(Em.$feature_flag_reason=Ug),Eh!=null&&(Pf=Eh.metadata)!=null&&Pf.id&&(Em.$feature_flag_id=Eh.metadata.id),O$6(Eh?.original_variant)&&O$6(Eh?.original_enabled)||(Em.$feature_flag_original_response=O$6(Eh.original_variant)?Eh.original_enabled:Eh.original_variant),Eh!=null&&(Nf=Eh.metadata)!=null&&Nf.original_payload&&(Em.$feature_flag_original_payload=Eh==null||(qg=Eh.metadata)==null?void 0:qg.original_payload),this._instance.capture("$feature_flag_called",Em)}return ja}yn.warn('getFeatureFlag for key "'+Ln+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(Ln){return this.getFlagsWithDetails()[Ln]}getFeatureFlagPayload(Ln){return this.getFlagPayloads()[Ln]}getRemoteConfigPayload(Ln,Ta){var ja=this._instance.config.token,La={distinct_id:this._instance.get_distinct_id(),token:ja};this.ui()&&(La.evaluation_environments=this.li()),this._instance.ci({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:La,compression:this._instance.config.disable_compression?void 0:oe$2.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:Fa=>{var wl,Pl=(wl=Fa.json)==null?void 0:wl.featureFlagPayloads;Ta(Pl?.[Ln]||void 0)}})}isFeatureEnabled(Ln,Ta){if(Ta===void 0&&(Ta={}),this.ei||this.getFlags()&&this.getFlags().length>0){var ja=this.getFeatureFlag(Ln,Ta);return O$6(ja)?void 0:!!ja}yn.warn('isFeatureEnabled for key "'+Ln+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(Ln){this.featureFlagEventHandlers.push(Ln)}removeFeatureFlagsHandler(Ln){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((Ta=>Ta!==Ln))}receivedFeatureFlags(Ln,Ta){if(this._instance.persistence){this.ei=!0;var ja=this.getFlagVariants(),La=this.getFlagPayloads(),Fa=this.getFlagsWithDetails();(function(wl,Pl,pc,mc,gc){pc===void 0&&(pc={}),mc===void 0&&(mc={}),gc===void 0&&(gc={});var Vd=Pn(wl),Wd=Vd.flags,kf=Vd.featureFlags,Pf=Vd.featureFlagPayloads;if(kf){var Nf=wl.requestId;if(I$9(kf)){yn.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var Eh={};if(kf)for(var Em=0;Em<kf.length;Em++)Eh[kf[Em]]=!0;Pl&&Pl.register({[wn]:kf,[ni]:Eh})}else{var qg=kf,Ug=Pf,Bg=Wd;wl.errorsWhileComputingFlags&&(qg=g$8({},pc,qg),Ug=g$8({},mc,Ug),Bg=g$8({},gc,Bg)),Pl&&Pl.register(g$8({[wn]:Object.keys(kn(qg)),[ni]:qg||{},[$n]:Ug||{},[ai]:Bg||{}},Nf?{[Sn]:Nf}:{}))}}})(Ln,this._instance.persistence,ja,La,Fa),this.pi(Ta)}}override(Ln,Ta){Ta===void 0&&(Ta=!1),yn.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:Ln,suppressWarning:Ta})}overrideFeatureFlags(Ln){if(!this._instance.__loaded||!this._instance.persistence)return yn.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(Ln===!1)return this._instance.persistence.unregister(xn),this._instance.persistence.unregister(En),this.pi(),bn.info("All overrides cleared");if(Ln&&typeof Ln=="object"&&("flags"in Ln||"payloads"in Ln)){var Ta,ja=Ln;if(this.ii=!!((Ta=ja.suppressWarning)!==null&&Ta!==void 0&&Ta),"flags"in ja){if(ja.flags===!1)this._instance.persistence.unregister(xn),bn.info("Flag overrides cleared");else if(ja.flags){if(I$9(ja.flags)){for(var La={},Fa=0;Fa<ja.flags.length;Fa++)La[ja.flags[Fa]]=!0;this._instance.persistence.register({[xn]:La})}else this._instance.persistence.register({[xn]:ja.flags});bn.info("Flag overrides set",{flags:ja.flags})}}return"payloads"in ja&&(ja.payloads===!1?(this._instance.persistence.unregister(En),bn.info("Payload overrides cleared")):ja.payloads&&(this._instance.persistence.register({[En]:ja.payloads}),bn.info("Payload overrides set",{payloads:ja.payloads}))),void this.pi()}this.pi()}onFeatureFlags(Ln){if(this.addFeatureFlagsHandler(Ln),this.ei){var{flags:Ta,flagVariants:ja}=this.gi();Ln(Ta,ja)}return()=>this.removeFeatureFlagsHandler(Ln)}updateEarlyAccessFeatureEnrollment(Ln,Ta,ja){var La,Fa=(this._instance.get_property(oi)||[]).find((mc=>mc.flagKey===Ln)),wl={["$feature_enrollment/"+Ln]:Ta},Pl={$feature_flag:Ln,$feature_enrollment:Ta,$set:wl};Fa&&(Pl.$early_access_feature_name=Fa.name),ja&&(Pl.$feature_enrollment_stage=ja),this._instance.capture("$feature_enrollment_update",Pl),this.setPersonPropertiesForFlags(wl,!1);var pc=g$8({},this.getFlagVariants(),{[Ln]:Ta});(La=this._instance.persistence)==null||La.register({[wn]:Object.keys(kn(pc)),[ni]:pc}),this.pi()}getEarlyAccessFeatures(Ln,Ta,ja){Ta===void 0&&(Ta=!1);var La=this._instance.get_property(oi),Fa=ja?"&"+ja.map((wl=>"stage="+wl)).join("&"):"";if(La&&!Ta)return Ln(La);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+Fa),method:"GET",callback:wl=>{var Pl,pc;if(wl.json){var mc=wl.json.earlyAccessFeatures;return(Pl=this._instance.persistence)==null||Pl.unregister(oi),(pc=this._instance.persistence)==null||pc.register({[oi]:mc}),Ln(mc)}}})}gi(){var Ln=this.getFlags(),Ta=this.getFlagVariants();return{flags:Ln.filter((ja=>Ta[ja])),flagVariants:Object.keys(Ta).filter((ja=>Ta[ja])).reduce(((ja,La)=>(ja[La]=Ta[La],ja)),{})}}pi(Ln){var{flags:Ta,flagVariants:ja}=this.gi();this.featureFlagEventHandlers.forEach((La=>La(Ta,ja,{errorsLoading:Ln})))}setPersonPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0);var ja=this._instance.get_property(li)||{};this._instance.register({[li]:g$8({},ja,Ln)}),Ta&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(li)}setGroupPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0);var ja=this._instance.get_property(ui)||{};Object.keys(ja).length!==0&&Object.keys(ja).forEach((La=>{ja[La]=g$8({},ja[La],Ln[La]),delete Ln[La]})),this._instance.register({[ui]:g$8({},ja,Ln)}),Ta&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(Ln){if(Ln){var Ta=this._instance.get_property(ui)||{};this._instance.register({[ui]:g$8({},Ta,{[Ln]:{}})})}else this._instance.unregister(ui)}reset(){this.ei=!1,this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.$anon_distinct_id=void 0,this.vi(),this.ii=!1}}var Rn=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class Fn{constructor(Ln,Ta){this.F=Ln,this.props={},this.mi=!1,this.yi=(ja=>{var La="";return ja.token&&(La=ja.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),ja.persistence_name?"ph_"+ja.persistence_name:"ph_"+La+"_posthog"})(Ln),this.Y=this.bi(Ln),this.load(),Ln.debug&&Pt$2.info("Persistence loaded",Ln.persistence,g$8({},this.props)),this.update_config(Ln,Ln,Ta),this.save()}isDisabled(){return!!this.wi}bi(Ln){Rn.indexOf(Ln.persistence.toLowerCase())===-1&&(Pt$2.critical("Unknown persistence type "+Ln.persistence+"; falling back to localStorage+cookie"),Ln.persistence="localStorage+cookie");var Ta=Ln.persistence.toLowerCase();return Ta==="localstorage"&&Ce$3.H()?Ce$3:Ta==="localstorage+cookie"&&Me$2.H()?Me$2:Ta==="sessionstorage"&&Le$1.H()?Le$1:Ta==="memory"?De$3:Ta==="cookie"?Re$1:Me$2.H()?Me$2:Re$1}properties(){var Ln={};return Ot(this.props,(function(Ta,ja){if(ja===ni&&F$8(Ta))for(var La=Object.keys(Ta),Fa=0;Fa<La.length;Fa++)Ln["$feature/"+La[Fa]]=Ta[La[Fa]];else Pl=ja,pc=!1,(D$b(wl=xi)?pc:s$f&&wl.indexOf===s$f?wl.indexOf(Pl)!=-1:(Ot(wl,(function(mc){if(pc||(pc=mc===Pl))return Ft$2})),pc))||(Ln[ja]=Ta);var wl,Pl,pc})),Ln}load(){if(!this.wi){var Ln=this.Y.W(this.yi);Ln&&(this.props=Mt$2({},Ln))}}save(){this.wi||this.Y.G(this.yi,this.props,this.xi,this.$i,this.Ei,this.F.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(Ln,Ta,ja){if(F$8(Ln)){O$6(Ta)&&(Ta="None"),this.xi=O$6(ja)?this.Si:ja;var La=!1;if(Ot(Ln,((Fa,wl)=>{this.props.hasOwnProperty(wl)&&this.props[wl]!==Ta||(this.props[wl]=Fa,La=!0)})),La)return this.save(),!0}return!1}register(Ln,Ta){if(F$8(Ln)){this.xi=O$6(Ta)?this.Si:Ta;var ja=!1;if(Ot(Ln,((La,Fa)=>{Ln.hasOwnProperty(Fa)&&this.props[Fa]!==La&&(this.props[Fa]=La,ja=!0)})),ja)return this.save(),!0}return!1}unregister(Ln){Ln in this.props&&(delete this.props[Ln],this.save())}update_campaign_params(){if(!this.mi){var Ln=ls(this.F.custom_campaign_params,this.F.mask_personal_data_properties,this.F.custom_personal_data_properties);C$c(Nt(Ln))||this.register(Ln),this.mi=!0}}update_search_keyword(){var Ln;this.register((Ln=o$d?.referrer)?hs(Ln):{})}update_referrer_info(){var Ln;this.register_once({$referrer:vs(),$referring_domain:o$d!=null&&o$d.referrer&&((Ln=le$2(o$d.referrer))==null?void 0:Ln.host)||"$direct"},void 0)}set_initial_person_info(){this.props[gi]||this.props[_i]||this.register_once({[mi]:cs(this.F.mask_personal_data_properties,this.F.custom_personal_data_properties)},void 0)}get_initial_props(){var Ln={};Ot([_i,gi],(wl=>{var Pl=this.props[wl];Pl&&Ot(Pl,(function(pc,mc){Ln["$initial_"+E$8(mc)]=pc}))}));var Ta,ja,La=this.props[mi];if(La){var Fa=(Ta=fs(La),ja={},Ot(Ta,(function(wl,Pl){ja["$initial_"+E$8(Pl)]=wl})),ja);Mt$2(Ln,Fa)}return Ln}safe_merge(Ln){return Ot(this.props,(function(Ta,ja){ja in Ln||(Ln[ja]=Ta)})),Ln}update_config(Ln,Ta,ja){if(this.Si=this.xi=Ln.cookie_expiration,this.set_disabled(Ln.disable_persistence||!!ja),this.set_cross_subdomain(Ln.cross_subdomain_cookie),this.set_secure(Ln.secure_cookie),Ln.persistence!==Ta.persistence){var La=this.bi(Ln),Fa=this.props;this.clear(),this.Y=La,this.props=Fa,this.save()}}set_disabled(Ln){this.wi=Ln,this.wi?this.remove():this.save()}set_cross_subdomain(Ln){Ln!==this.$i&&(this.$i=Ln,this.remove(),this.save())}set_secure(Ln){Ln!==this.Ei&&(this.Ei=Ln,this.remove(),this.save())}set_event_timer(Ln,Ta){var ja=this.props[Vt]||{};ja[Ln]=Ta,this.props[Vt]=ja,this.save()}remove_event_timer(Ln){var Ta=(this.props[Vt]||{})[Ln];return O$6(Ta)||(delete this.props[Vt][Ln],this.save()),Ta}get_property(Ln){return this.props[Ln]}set_property(Ln,Ta){this.props[Ln]=Ta,this.save()}}(function(ta){return ta.Button="button",ta.Tab="tab",ta.Selector="selector",ta})({});(function(ta){return ta.TopLeft="top_left",ta.TopRight="top_right",ta.TopCenter="top_center",ta.MiddleLeft="middle_left",ta.MiddleRight="middle_right",ta.MiddleCenter="middle_center",ta.Left="left",ta.Center="center",ta.Right="right",ta.NextToTrigger="next_to_trigger",ta})({});(function(ta){return ta.Top="top",ta.Left="left",ta.Right="right",ta.Bottom="bottom",ta})({});var An=(function(ta){return ta.Popover="popover",ta.API="api",ta.Widget="widget",ta.ExternalSurvey="external_survey",ta})({});(function(ta){return ta.Open="open",ta.MultipleChoice="multiple_choice",ta.SingleChoice="single_choice",ta.Rating="rating",ta.Link="link",ta})({});(function(ta){return ta.NextQuestion="next_question",ta.End="end",ta.ResponseBased="response_based",ta.SpecificQuestion="specific_question",ta})({});(function(ta){return ta.Once="once",ta.Recurring="recurring",ta.Always="always",ta})({});var Nn=(function(ta){return ta.SHOWN="survey shown",ta.DISMISSED="survey dismissed",ta.SENT="survey sent",ta})({}),Un=(function(ta){return ta.SURVEY_ID="$survey_id",ta.SURVEY_NAME="$survey_name",ta.SURVEY_RESPONSE="$survey_response",ta.SURVEY_ITERATION="$survey_iteration",ta.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",ta.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",ta.SURVEY_SUBMISSION_ID="$survey_submission_id",ta.SURVEY_QUESTIONS="$survey_questions",ta.SURVEY_COMPLETED="$survey_completed",ta})({}),zn=(function(ta){return ta.Popover="popover",ta.Inline="inline",ta})({});class Hn{constructor(){this.ki={},this.ki={}}on(Ln,Ta){return this.ki[Ln]||(this.ki[Ln]=[]),this.ki[Ln].push(Ta),()=>{this.ki[Ln]=this.ki[Ln].filter((ja=>ja!==Ta))}}emit(Ln,Ta){for(var ja of this.ki[Ln]||[])ja(Ta);for(var La of this.ki["*"]||[])La(Ln,Ta)}}class Bn{constructor(Ln){this.Pi=new Hn,this.Ti=(Ta,ja)=>this.Ii(Ta,ja)&&this.Ri(Ta,ja)&&this.Fi(Ta,ja),this.Ii=(Ta,ja)=>ja==null||!ja.event||Ta?.event===ja?.event,this._instance=Ln,this.Ci=new Set,this.Oi=new Set}init(){var Ln;if(!O$6((Ln=this._instance)==null?void 0:Ln.Mi)){var Ta;(Ta=this._instance)==null||Ta.Mi(((ja,La)=>{this.on(ja,La)}))}}register(Ln){var Ta,ja;if(!O$6((Ta=this._instance)==null?void 0:Ta.Mi)&&(Ln.forEach((wl=>{var Pl,pc;(Pl=this.Oi)==null||Pl.add(wl),(pc=wl.steps)==null||pc.forEach((mc=>{var gc;(gc=this.Ci)==null||gc.add(mc?.event||"")}))})),(ja=this._instance)!=null&&ja.autocapture)){var La,Fa=new Set;Ln.forEach((wl=>{var Pl;(Pl=wl.steps)==null||Pl.forEach((pc=>{pc!=null&&pc.selector&&Fa.add(pc?.selector)}))})),(La=this._instance)==null||La.autocapture.setElementSelectors(Fa)}}on(Ln,Ta){var ja;Ta!=null&&Ln.length!=0&&(this.Ci.has(Ln)||this.Ci.has(Ta?.event))&&this.Oi&&((ja=this.Oi)==null?void 0:ja.size)>0&&this.Oi.forEach((La=>{this.Ai(Ta,La)&&this.Pi.emit("actionCaptured",La.name)}))}Di(Ln){this.onAction("actionCaptured",(Ta=>Ln(Ta)))}Ai(Ln,Ta){if(Ta?.steps==null)return!1;for(var ja of Ta.steps)if(this.Ti(Ln,ja))return!0;return!1}onAction(Ln,Ta){return this.Pi.on(Ln,Ta)}Ri(Ln,Ta){if(Ta!=null&&Ta.url){var ja,La=Ln==null||(ja=Ln.properties)==null?void 0:ja.$current_url;if(!La||typeof La!="string"||!Bn.ji(La,Ta?.url,Ta?.url_matching||"contains"))return!1}return!0}static ji(Ln,Ta,ja){switch(ja){case"regex":return!!t$9&&cn$1(Ln,Ta);case"exact":return Ta===Ln;case"contains":var La=Bn.Li(Ta).replace(/_/g,".").replace(/%/g,".*");return cn$1(Ln,La);default:return!1}}static Li(Ln){return Ln.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}Fi(Ln,Ta){if((Ta!=null&&Ta.href||Ta!=null&&Ta.tag_name||Ta!=null&&Ta.text)&&!this.Ni(Ln).some((Fa=>!(Ta!=null&&Ta.href&&!Bn.ji(Fa.href||"",Ta?.href,Ta?.href_matching||"exact"))&&(Ta==null||!Ta.tag_name||Fa.tag_name===Ta?.tag_name)&&!(Ta!=null&&Ta.text&&!Bn.ji(Fa.text||"",Ta?.text,Ta?.text_matching||"exact")&&!Bn.ji(Fa.$el_text||"",Ta?.text,Ta?.text_matching||"exact")))))return!1;if(Ta!=null&&Ta.selector){var ja,La=Ln==null||(ja=Ln.properties)==null?void 0:ja.$element_selectors;if(!La||!La.includes(Ta?.selector))return!1}return!0}Ni(Ln){return Ln?.properties.$elements==null?[]:Ln?.properties.$elements}}var qn=Tt$1("[Surveys]"),Wn="seenSurvey_",Gn=(ta,Ln)=>{var Ta="$survey_"+Ln+"/"+ta.id;return ta.current_iteration&&ta.current_iteration>0&&(Ta="$survey_"+Ln+"/"+ta.id+"/"+ta.current_iteration),Ta},Vn=ta=>{var Ln=""+Wn+ta.id;return ta.current_iteration&&ta.current_iteration>0&&(Ln=""+Wn+ta.id+"_"+ta.current_iteration),Ln},Jn=[An.Popover,An.Widget,An.API],Kn={ignoreConditions:!1,ignoreDelay:!1,displayType:zn.Popover};class Yn{constructor(Ln){this._instance=Ln,this.Ui=new Map,this.zi=new Map}register(Ln){var Ta;O$6((Ta=this._instance)==null?void 0:Ta.Mi)||(this.Hi(Ln),this.Bi(Ln))}Bi(Ln){var Ta=Ln.filter((ja=>{var La,Fa;return((La=ja.conditions)==null?void 0:La.actions)&&((Fa=ja.conditions)==null||(Fa=Fa.actions)==null||(Fa=Fa.values)==null?void 0:Fa.length)>0}));Ta.length!==0&&(this.qi==null&&(this.qi=new Bn(this._instance),this.qi.init(),this.qi.Di((ja=>{this.onAction(ja)}))),Ta.forEach((ja=>{var La,Fa,wl,Pl,pc;ja.conditions&&(La=ja.conditions)!=null&&La.actions&&(Fa=ja.conditions)!=null&&(Fa=Fa.actions)!=null&&Fa.values&&((wl=ja.conditions)==null||(wl=wl.actions)==null||(wl=wl.values)==null?void 0:wl.length)>0&&((Pl=this.qi)==null||Pl.register(ja.conditions.actions.values),(pc=ja.conditions)==null||(pc=pc.actions)==null||(pc=pc.values)==null||pc.forEach((mc=>{if(mc&&mc.name){var gc=this.zi.get(mc.name);gc&&gc.push(ja.id),this.zi.set(mc.name,gc||[ja.id])}})))})))}Hi(Ln){var Ta;Ln.filter((ja=>{var La,Fa;return((La=ja.conditions)==null?void 0:La.events)&&((Fa=ja.conditions)==null||(Fa=Fa.events)==null||(Fa=Fa.values)==null?void 0:Fa.length)>0})).length!==0&&((Ta=this._instance)==null||Ta.Mi(((ja,La)=>{this.onEvent(ja,La)})),Ln.forEach((ja=>{var La;(La=ja.conditions)==null||(La=La.events)==null||(La=La.values)==null||La.forEach((Fa=>{if(Fa&&Fa.name){var wl=this.Ui.get(Fa.name);wl&&wl.push(ja.id),this.Ui.set(Fa.name,wl||[ja.id])}}))})))}onEvent(Ln,Ta){var ja,La,Fa=((ja=this._instance)==null||(ja=ja.persistence)==null?void 0:ja.props[di])||[];if(Nn.SHOWN===Ln&&Ta&&Fa.length>0){var wl;qn.info("survey event matched, removing survey from activated surveys",{event:Ln,eventPayload:Ta,existingActivatedSurveys:Fa});var Pl=Ta==null||(wl=Ta.properties)==null?void 0:wl.$survey_id;if(Pl){var pc=Fa.indexOf(Pl);pc>=0&&(Fa.splice(pc,1),this.Wi(Fa))}}else if(this.Ui.has(Ln)){qn.info("survey event name matched",{event:Ln,eventPayload:Ta,surveys:this.Ui.get(Ln)});var mc=[];(La=this._instance)==null||La.getSurveys((Vd=>{mc=Vd.filter((Wd=>{var kf;return(kf=this.Ui.get(Ln))==null?void 0:kf.includes(Wd.id)}))}));var gc=mc.filter((Vd=>{var Wd,kf=(Wd=Vd.conditions)==null||(Wd=Wd.events)==null||(Wd=Wd.values)==null?void 0:Wd.find((Pf=>Pf.name===Ln));return!!kf&&(!kf.propertyFilters||Object.entries(kf.propertyFilters).every((Pf=>{var Nf,[Eh,Em]=Pf,qg=Ta==null||(Nf=Ta.properties)==null?void 0:Nf[Eh];if(O$6(qg)||D$b(qg))return!1;var Ug=[String(qg)],Bg=pn[Em.operator];return Bg?Bg(Em.values,Ug):(qn.warn("Unknown property comparison operator: "+Em.operator),!1)})))}));this.Wi(Fa.concat(gc.map((Vd=>Vd.id))||[]))}}onAction(Ln){var Ta,ja=((Ta=this._instance)==null||(Ta=Ta.persistence)==null?void 0:Ta.props[di])||[];this.zi.has(Ln)&&this.Wi(ja.concat(this.zi.get(Ln)||[]))}Wi(Ln){var Ta;qn.info("updating activated surveys",{activatedSurveys:Ln}),(Ta=this._instance)==null||(Ta=Ta.persistence)==null||Ta.register({[di]:[...new Set(Ln)]})}getSurveys(){var Ln,Ta=(Ln=this._instance)==null||(Ln=Ln.persistence)==null?void 0:Ln.props[di];return Ta||[]}getEventToSurveys(){return this.Ui}Gi(){return this.qi}}class Xn{constructor(Ln){this.Vi=void 0,this._surveyManager=null,this.Ji=!1,this.Ki=!1,this.Yi=[],this._instance=Ln,this._surveyEventReceiver=null}onRemoteConfig(Ln){if(!this._instance.config.disable_surveys){var Ta=Ln.surveys;if(j$b(Ta))return qn.warn("Flags not loaded yet. Not loading surveys.");var ja=I$9(Ta);this.Vi=ja?Ta.length>0:Ta,qn.info("flags response received, isSurveysEnabled: "+this.Vi),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var Ln=[],Ta=0;Ta<localStorage.length;Ta++){var ja=localStorage.key(Ta);(ja!=null&&ja.startsWith(Wn)||ja!=null&&ja.startsWith("inProgressSurvey_"))&&Ln.push(ja)}Ln.forEach((La=>localStorage.removeItem(La)))}loadIfEnabled(){if(!this._surveyManager)if(this.Ki)qn.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)qn.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())qn.info("Not loading surveys in cookieless mode without consent.");else{var Ln=v$7?.__PosthogExtensions__;if(Ln){if(!O$6(this.Vi)||this._instance.config.advanced_enable_surveys){var Ta=this.Vi||this._instance.config.advanced_enable_surveys;this.Ki=!0;try{var ja=Ln.generateSurveys;if(ja)return void this.Xi(ja,Ta);var La=Ln.loadExternalDependency;if(!La)return void this.Qi("PostHog loadExternalDependency extension not found.");La(this._instance,"surveys",(Fa=>{Fa||!Ln.generateSurveys?this.Qi("Could not load surveys script",Fa):this.Xi(Ln.generateSurveys,Ta)}))}catch(Fa){throw this.Qi("Error initializing surveys",Fa),Fa}finally{this.Ki=!1}}}else qn.error("PostHog Extensions not found.")}}Xi(Ln,Ta){this._surveyManager=Ln(this._instance,Ta),this._surveyEventReceiver=new Yn(this._instance),qn.info("Surveys loaded successfully"),this.Zi({isLoaded:!0})}Qi(Ln,Ta){qn.error(Ln,Ta),this.Zi({isLoaded:!1,error:Ln})}onSurveysLoaded(Ln){return this.Yi.push(Ln),this._surveyManager&&this.Zi({isLoaded:!0}),()=>{this.Yi=this.Yi.filter((Ta=>Ta!==Ln))}}getSurveys(Ln,Ta){if(Ta===void 0&&(Ta=!1),this._instance.config.disable_surveys)return qn.info("Disabled. Not loading surveys."),Ln([]);var ja=this._instance.get_property(hi);if(ja&&!Ta)return Ln(ja,{isLoaded:!0});if(this.Ji)return Ln([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.Ji=!0,this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:La=>{var Fa;this.Ji=!1;var wl=La.statusCode;if(wl!==200||!La.json){var Pl="Surveys API could not be loaded, status: "+wl;return qn.error(Pl),Ln([],{isLoaded:!1,error:Pl})}var pc,mc=La.json.surveys||[],gc=mc.filter((Vd=>(function(Wd){return!(!Wd.start_date||Wd.end_date)})(Vd)&&((function(Wd){var kf;return!((kf=Wd.conditions)==null||(kf=kf.events)==null||(kf=kf.values)==null||!kf.length)})(Vd)||(function(Wd){var kf;return!((kf=Wd.conditions)==null||(kf=kf.actions)==null||(kf=kf.values)==null||!kf.length)})(Vd))));return gc.length>0&&((pc=this._surveyEventReceiver)==null||pc.register(gc)),(Fa=this._instance.persistence)==null||Fa.register({[hi]:mc}),Ln(mc,{isLoaded:!0})}})}catch(La){throw this.Ji=!1,La}}Zi(Ln){for(var Ta of this.Yi)try{if(!Ln.isLoaded)return Ta([],Ln);this.getSurveys(Ta)}catch(ja){qn.error("Error in survey callback",ja)}}getActiveMatchingSurveys(Ln,Ta){if(Ta===void 0&&(Ta=!1),!j$b(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(Ln,Ta);qn.warn("init was not called")}te(Ln){var Ta=null;return this.getSurveys((ja=>{var La;Ta=(La=ja.find((Fa=>Fa.id===Ln)))!==null&&La!==void 0?La:null})),Ta}ie(Ln){if(j$b(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var Ta=typeof Ln=="string"?this.te(Ln):Ln;return Ta?this._surveyManager.checkSurveyEligibility(Ta):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(Ln){if(j$b(this._surveyManager))return qn.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var Ta=this.ie(Ln);return{visible:Ta.eligible,disabledReason:Ta.reason}}canRenderSurveyAsync(Ln,Ta){return j$b(this._surveyManager)?(qn.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((ja=>{this.getSurveys((La=>{var Fa,wl=(Fa=La.find((pc=>pc.id===Ln)))!==null&&Fa!==void 0?Fa:null;if(wl){var Pl=this.ie(wl);ja({visible:Pl.eligible,disabledReason:Pl.reason})}else ja({visible:!1,disabledReason:"Survey not found"})}),Ta)}))}renderSurvey(Ln,Ta){var ja;if(j$b(this._surveyManager))qn.warn("init was not called");else{var La=typeof Ln=="string"?this.te(Ln):Ln;if(La!=null&&La.id)if(Jn.includes(La.type)){var Fa=o$d?.querySelector(Ta);if(Fa)return(ja=La.appearance)!=null&&ja.surveyPopupDelaySeconds?(qn.info("Rendering survey "+La.id+" with delay of "+La.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var wl,Pl;qn.info("Rendering survey "+La.id+" with delay of "+((wl=La.appearance)==null?void 0:wl.surveyPopupDelaySeconds)+" seconds"),(Pl=this._surveyManager)==null||Pl.renderSurvey(La,Fa),qn.info("Survey "+La.id+" rendered")}),1e3*La.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(La,Fa);qn.warn("Survey element not found")}else qn.warn("Surveys of type "+La.type+" cannot be rendered in the app");else qn.warn("Survey not found")}}displaySurvey(Ln,Ta){var ja;if(j$b(this._surveyManager))qn.warn("init was not called");else{var La=this.te(Ln);if(La){var Fa=La;if((ja=La.appearance)!=null&&ja.surveyPopupDelaySeconds&&Ta.ignoreDelay&&(Fa=g$8({},La,{appearance:g$8({},La.appearance,{surveyPopupDelaySeconds:0})})),Ta.ignoreConditions===!1){var wl=this.canRenderSurvey(La);if(!wl.visible)return void qn.warn("Survey is not eligible to be displayed: ",wl.disabledReason)}Ta.displayType!==zn.Inline?this._surveyManager.handlePopoverSurvey(Fa):this.renderSurvey(Fa,Ta.selector)}else qn.warn("Survey not found")}}}var Qn=Tt$1("[RateLimiter]");class Zn{constructor(Ln){var Ta,ja;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=La=>{var Fa=La.text;if(Fa&&Fa.length)try{(JSON.parse(Fa).quota_limited||[]).forEach((wl=>{Qn.info((wl||"events")+" is quota limited."),this.serverLimits[wl]=new Date().getTime()+6e4}))}catch(wl){return void Qn.warn('could not rate limit - continuing. Error: "'+wl?.message+'"',{text:Fa})}},this.instance=Ln,this.captureEventsPerSecond=((Ta=Ln.config.rate_limiting)==null?void 0:Ta.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((ja=Ln.config.rate_limiting)==null?void 0:ja.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(Ln){var Ta,ja,La;Ln===void 0&&(Ln=!1);var Fa=new Date().getTime(),wl=(Ta=(ja=this.instance.persistence)==null?void 0:ja.get_property(pi))!==null&&Ta!==void 0?Ta:{tokens:this.captureEventsBurstLimit,last:Fa};wl.tokens+=(Fa-wl.last)/1e3*this.captureEventsPerSecond,wl.last=Fa,wl.tokens>this.captureEventsBurstLimit&&(wl.tokens=this.captureEventsBurstLimit);var Pl=wl.tokens<1;return Pl||Ln||(wl.tokens=Math.max(0,wl.tokens-1)),!Pl||this.lastEventRateLimited||Ln||this.instance.capture("$$client_ingestion_warning",{$$client_ingestion_warning_message:"posthog-js client rate limited. Config is set to "+this.captureEventsPerSecond+" events per second and "+this.captureEventsBurstLimit+" events burst limit."},{skip_client_rate_limiting:!0}),this.lastEventRateLimited=Pl,(La=this.instance.persistence)==null||La.set_property(pi,wl),{isRateLimited:Pl,remainingTokens:wl.tokens}}isServerRateLimited(Ln){var Ta=this.serverLimits[Ln||"events"]||!1;return Ta!==!1&&new Date().getTime()<Ta}}var to=Tt$1("[RemoteConfig]");class io{constructor(Ln){this._instance=Ln}get remoteConfig(){var Ln;return(Ln=v$7._POSTHOG_REMOTE_CONFIG)==null||(Ln=Ln[this._instance.config.token])==null?void 0:Ln.config}ee(Ln){var Ta,ja;(Ta=v$7.__PosthogExtensions__)!=null&&Ta.loadExternalDependency?(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,"remote-config",(()=>Ln(this.remoteConfig))):(to.error("PostHog Extensions not found. Cannot load remote config."),Ln())}re(Ln){this._instance.ci({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:Ta=>{Ln(Ta.json)}})}load(){try{if(this.remoteConfig)return to.info("Using preloaded remote config",this.remoteConfig),void this.fi(this.remoteConfig);if(this._instance.M())return void to.warn("Remote config is disabled. Falling back to local config.");this.ee((Ln=>{if(!Ln)return to.info("No config found after loading remote JS config. Falling back to JSON."),void this.re((Ta=>{this.fi(Ta)}));this.fi(Ln)}))}catch(Ln){to.error("Error loading remote config",Ln)}}fi(Ln){Ln?this._instance.config.__preview_remote_config?(this._instance.fi(Ln),Ln.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):to.info("__preview_remote_config is disabled. Logging config instead",Ln):to.error("Failed to fetch remote config from PostHog.")}}var eo=3e3;class ro{constructor(Ln,Ta){this.se=!0,this.ne=[],this.oe=J$5(Ta?.flush_interval_ms||eo,250,5e3,Pt$2.createLogger("flush interval"),eo),this.ae=Ln}enqueue(Ln){this.ne.push(Ln),this.le||this.ue()}unload(){this.he();var Ln=this.ne.length>0?this.de():{},Ta=Object.values(Ln);[...Ta.filter((ja=>ja.url.indexOf("/e")===0)),...Ta.filter((ja=>ja.url.indexOf("/e")!==0))].map((ja=>{this.ae(g$8({},ja,{transport:"sendBeacon"}))}))}enable(){this.se=!1,this.ue()}ue(){var Ln=this;this.se||(this.le=setTimeout((()=>{if(this.he(),this.ne.length>0){var Ta=this.de(),ja=function(){var Fa=Ta[La],wl=new Date().getTime();Fa.data&&I$9(Fa.data)&&Ot(Fa.data,(Pl=>{Pl.offset=Math.abs(Pl.timestamp-wl),delete Pl.timestamp})),Ln.ae(Fa)};for(var La in Ta)ja()}}),this.oe))}he(){clearTimeout(this.le),this.le=void 0}de(){var Ln={};return Ot(this.ne,(Ta=>{var ja,La=Ta,Fa=(La?La.batchKey:null)||La.url;O$6(Ln[Fa])&&(Ln[Fa]=g$8({},La,{data:[]})),(ja=Ln[Fa].data)==null||ja.push(La.data)})),this.ne=[],Ln}}var so=["retriesPerformedSoFar"];class no{constructor(Ln){this.ve=!1,this.ce=3e3,this.ne=[],this._instance=Ln,this.ne=[],this.fe=!0,!O$6(t$9)&&"onLine"in t$9.navigator&&(this.fe=t$9.navigator.onLine,this.pe=()=>{this.fe=!0,this.Dt()},this.ge=()=>{this.fe=!1},qt(t$9,"online",this.pe),qt(t$9,"offline",this.ge))}get length(){return this.ne.length}retriableRequest(Ln){var{retriesPerformedSoFar:Ta}=Ln,ja=_$8(Ln,so);L$6(Ta)&&Ta>0&&(ja.url=un$1(ja.url,{retry_count:Ta})),this._instance.ci(g$8({},ja,{callback:La=>{La.statusCode!==200&&(La.statusCode<400||La.statusCode>=500)&&(Ta??0)<10?this._e(g$8({retriesPerformedSoFar:Ta},ja)):ja.callback==null||ja.callback(La)}}))}_e(Ln){var Ta=Ln.retriesPerformedSoFar||0;Ln.retriesPerformedSoFar=Ta+1;var ja=(function(wl){var Pl=3e3*Math.pow(2,wl),pc=Pl/2,mc=Math.min(18e5,Pl),gc=(Math.random()-.5)*(mc-pc);return Math.ceil(mc+gc)})(Ta),La=Date.now()+ja;this.ne.push({retryAt:La,requestOptions:Ln});var Fa="Enqueued failed request for retry in "+ja;navigator.onLine||(Fa+=" (Browser is offline)"),Pt$2.warn(Fa),this.ve||(this.ve=!0,this.me())}me(){if(this.ye&&clearTimeout(this.ye),this.ne.length===0)return this.ve=!1,void(this.ye=void 0);this.ye=setTimeout((()=>{this.fe&&this.ne.length>0&&this.Dt(),this.me()}),this.ce)}Dt(){var Ln=Date.now(),Ta=[],ja=this.ne.filter((Fa=>Fa.retryAt<Ln||(Ta.push(Fa),!1)));if(this.ne=Ta,ja.length>0)for(var{requestOptions:La}of ja)this.retriableRequest(La)}unload(){for(var{requestOptions:Ln}of(this.ye&&(clearTimeout(this.ye),this.ye=void 0),this.ve=!1,O$6(t$9)||(this.pe&&(t$9.removeEventListener("online",this.pe),this.pe=void 0),this.ge&&(t$9.removeEventListener("offline",this.ge),this.ge=void 0)),this.ne))try{this._instance.ci(g$8({},Ln,{transport:"sendBeacon"}))}catch(Ta){Pt$2.error(Ta)}this.ne=[]}}class oo{constructor(Ln){this.be=()=>{var Ta,ja,La,Fa;this.we||(this.we={});var wl=this.scrollElement(),Pl=this.scrollY(),pc=wl?Math.max(0,wl.scrollHeight-wl.clientHeight):0,mc=Pl+(wl?.clientHeight||0),gc=wl?.scrollHeight||0;this.we.lastScrollY=Math.ceil(Pl),this.we.maxScrollY=Math.max(Pl,(Ta=this.we.maxScrollY)!==null&&Ta!==void 0?Ta:0),this.we.maxScrollHeight=Math.max(pc,(ja=this.we.maxScrollHeight)!==null&&ja!==void 0?ja:0),this.we.lastContentY=mc,this.we.maxContentY=Math.max(mc,(La=this.we.maxContentY)!==null&&La!==void 0?La:0),this.we.maxContentHeight=Math.max(gc,(Fa=this.we.maxContentHeight)!==null&&Fa!==void 0?Fa:0)},this._instance=Ln}getContext(){return this.we}resetContext(){var Ln=this.we;return setTimeout(this.be,0),Ln}startMeasuringScrollPosition(){qt(t$9,"scroll",this.be,{capture:!0}),qt(t$9,"scrollend",this.be,{capture:!0}),qt(t$9,"resize",this.be)}scrollElement(){if(!this._instance.config.scroll_root_selector)return t$9?.document.documentElement;var Ln=I$9(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var Ta of Ln){var ja=t$9?.document.querySelector(Ta);if(ja)return ja}}scrollY(){if(this._instance.config.scroll_root_selector){var Ln=this.scrollElement();return Ln&&Ln.scrollTop||0}return t$9&&(t$9.scrollY||t$9.pageYOffset||t$9.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var Ln=this.scrollElement();return Ln&&Ln.scrollLeft||0}return t$9&&(t$9.scrollX||t$9.pageXOffset||t$9.document.documentElement.scrollLeft)||0}}var ao=ta=>cs(ta?.config.mask_personal_data_properties,ta?.config.custom_personal_data_properties);let lo$1=class{constructor(Ln,Ta,ja,La){this.xe=Fa=>{var wl=this.$e();if(!wl||wl.sessionId!==Fa){var Pl={sessionId:Fa,props:this.Ee(this._instance)};this.Se.register({[fi]:Pl})}},this._instance=Ln,this.ke=Ta,this.Se=ja,this.Ee=La||ao,this.ke.onSessionId(this.xe)}$e(){return this.Se.props[fi]}getSetOnceProps(){var Ln,Ta=(Ln=this.$e())==null?void 0:Ln.props;return Ta?"r"in Ta?fs(Ta):{$referring_domain:Ta.referringDomain,$pathname:Ta.initialPathName,utm_source:Ta.utm_source,utm_campaign:Ta.utm_campaign,utm_medium:Ta.utm_medium,utm_content:Ta.utm_content,utm_term:Ta.utm_term}:{}}getSessionProps(){var Ln={};return Ot(Nt(this.getSetOnceProps()),((Ta,ja)=>{ja==="$current_url"&&(ja="url"),Ln["$session_entry_"+E$8(ja)]=Ta})),Ln}};var uo=Tt$1("[SessionId]");class ho{on(Ln,Ta){return this.Pe.on(Ln,Ta)}constructor(Ln,Ta,ja){var La;if(this.Te=[],this.Ie=void 0,this.Pe=new Hn,this.Re=(gc,Vd)=>Math.abs(gc-Vd)>this.sessionTimeoutMs,!Ln.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(Ln.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.F=Ln.config,this.Se=Ln.persistence,this.Fe=void 0,this.Ce=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.Oe=Ta||Se$2,this.Me=ja||Se$2;var Fa=this.F.persistence_name||this.F.token,wl=this.F.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*J$5(wl,60,36e3,uo.createLogger("session_idle_timeout_seconds"),1800),Ln.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.Ae(),this.De="ph_"+Fa+"_window_id",this.je="ph_"+Fa+"_primary_window_exists",this.Le()){var Pl=Le$1.W(this.De),pc=Le$1.W(this.je);Pl&&!pc?this.Fe=Pl:Le$1.V(this.De),Le$1.G(this.je,!0)}if((La=this.F.bootstrap)!=null&&La.sessionID)try{var mc=(gc=>{var Vd=gc.replace(/-/g,"");if(Vd.length!==32)throw new Error("Not a valid UUID");if(Vd[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(Vd.substring(0,12),16)})(this.F.bootstrap.sessionID);this.Ne(this.F.bootstrap.sessionID,new Date().getTime(),mc)}catch(gc){uo.error("Invalid sessionID in bootstrap",gc)}this.Ue()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(Ln){return O$6(this.Te)&&(this.Te=[]),this.Te.push(Ln),this.Ce&&Ln(this.Ce,this.Fe),()=>{this.Te=this.Te.filter((Ta=>Ta!==Ln))}}Le(){return this.F.persistence!=="memory"&&!this.Se.wi&&Le$1.H()}ze(Ln){Ln!==this.Fe&&(this.Fe=Ln,this.Le()&&Le$1.G(this.De,Ln))}He(){return this.Fe?this.Fe:this.Le()?Le$1.W(this.De):null}Ne(Ln,Ta,ja){Ln===this.Ce&&Ta===this._sessionActivityTimestamp&&ja===this._sessionStartTimestamp||(this._sessionStartTimestamp=ja,this._sessionActivityTimestamp=Ta,this.Ce=Ln,this.Se.register({[ri]:[Ta,Ln,ja]}))}Be(){if(this.Ce&&this._sessionActivityTimestamp&&this._sessionStartTimestamp)return[this._sessionActivityTimestamp,this.Ce,this._sessionStartTimestamp];var Ln=this.Se.props[ri];return I$9(Ln)&&Ln.length===2&&Ln.push(Ln[0]),Ln||[0,null,0]}resetSessionId(){this.Ne(null,null,null)}destroy(){clearTimeout(this.qe),this.qe=void 0,this.Ie&&t$9&&(t$9.removeEventListener("beforeunload",this.Ie,{capture:!1}),this.Ie=void 0),this.Te=[]}Ue(){this.Ie=()=>{this.Le()&&Le$1.V(this.je)},qt(t$9,"beforeunload",this.Ie,{capture:!1})}checkAndGetSessionAndWindowId(Ln,Ta){if(Ln===void 0&&(Ln=!1),Ta===void 0&&(Ta=null),this.F.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var ja=Ta||new Date().getTime(),[La,Fa,wl]=this.Be(),Pl=this.He(),pc=L$6(wl)&&wl>0&&Math.abs(ja-wl)>864e5,mc=!1,gc=!Fa,Vd=!gc&&!Ln&&this.Re(ja,La);gc||Vd||pc?(Fa=this.Oe(),Pl=this.Me(),uo.info("new session ID generated",{sessionId:Fa,windowId:Pl,changeReason:{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}}),wl=ja,mc=!0):Pl||(Pl=this.Me(),mc=!0);var Wd=La===0||!Ln||pc?ja:La,kf=wl===0?new Date().getTime():wl;return this.ze(Pl),this.Ne(Fa,Wd,kf),Ln||this.Ae(),mc&&this.Te.forEach((Pf=>Pf(Fa,Pl,mc?{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}:void 0))),{sessionId:Fa,windowId:Pl,sessionStartTimestamp:kf,changeReason:mc?{noSessionId:gc,activityTimeout:Vd,sessionPastMaximumLength:pc}:void 0,lastActivityTimestamp:La}}Ae(){clearTimeout(this.qe),this.qe=setTimeout((()=>{var[Ln]=this.Be();if(this.Re(new Date().getTime(),Ln)){var Ta=this.Ce;this.resetSessionId(),this.Pe.emit("forcedIdleReset",{idleSessionId:Ta})}}),1.1*this.sessionTimeoutMs)}}var vo=["$set_once","$set"],co=Tt$1("[SiteApps]");class fo{constructor(Ln){this._instance=Ln,this.We=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}Ge(Ln,Ta){if(Ta){var ja=this.globalsForEvent(Ta);this.We.push(ja),this.We.length>1e3&&(this.We=this.We.slice(10))}}get siteAppLoaders(){var Ln;return(Ln=v$7._POSTHOG_REMOTE_CONFIG)==null||(Ln=Ln[this._instance.config.token])==null?void 0:Ln.siteApps}init(){if(this.isEnabled){var Ln=this._instance.Mi(this.Ge.bind(this));this.Ve=()=>{Ln(),this.We=[],this.Ve=void 0}}}globalsForEvent(Ln){var Ta,ja,La,Fa,wl,Pl,pc;if(!Ln)throw new Error("Event payload is required");var mc={},gc=this._instance.get_property("$groups")||[],Vd=this._instance.get_property("$stored_group_properties")||{};for(var[Wd,kf]of Object.entries(Vd))mc[Wd]={id:gc[Wd],type:Wd,properties:kf};var{$set_once:Pf,$set:Nf}=Ln;return{event:g$8({},_$8(Ln,vo),{properties:g$8({},Ln.properties,Nf?{$set:g$8({},(Ta=(ja=Ln.properties)==null?void 0:ja.$set)!==null&&Ta!==void 0?Ta:{},Nf)}:{},Pf?{$set_once:g$8({},(La=(Fa=Ln.properties)==null?void 0:Fa.$set_once)!==null&&La!==void 0?La:{},Pf)}:{}),elements_chain:(wl=(Pl=Ln.properties)==null?void 0:Pl.$elements_chain)!==null&&wl!==void 0?wl:"",distinct_id:(pc=Ln.properties)==null?void 0:pc.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:mc}}setupSiteApp(Ln){var Ta=this.apps[Ln.id],ja=()=>{var Pl;!Ta.errored&&this.We.length&&(co.info("Processing "+this.We.length+" events for site app with id "+Ln.id),this.We.forEach((pc=>Ta.processEvent==null?void 0:Ta.processEvent(pc))),Ta.processedBuffer=!0),Object.values(this.apps).every((pc=>pc.processedBuffer||pc.errored))&&((Pl=this.Ve)==null||Pl.call(this))},La=!1,Fa=Pl=>{Ta.errored=!Pl,Ta.loaded=!0,co.info("Site app with id "+Ln.id+" "+(Pl?"loaded":"errored")),La&&ja()};try{var{processEvent:wl}=Ln.init({posthog:this._instance,callback:Pl=>{Fa(Pl)}});wl&&(Ta.processEvent=wl),La=!0}catch(Pl){co.error("Error while initializing PostHog app with config id "+Ln.id,Pl),Fa(!1)}if(La&&Ta.loaded)try{ja()}catch(Pl){co.error("Error while processing buffered events PostHog app with config id "+Ln.id,Pl),Ta.errored=!0}}Je(){var Ln=this.siteAppLoaders||[];for(var Ta of Ln)this.apps[Ta.id]={id:Ta.id,loaded:!1,errored:!1,processedBuffer:!1};for(var ja of Ln)this.setupSiteApp(ja)}Ke(Ln){if(Object.keys(this.apps).length!==0){var Ta=this.globalsForEvent(Ln);for(var ja of Object.values(this.apps))try{ja.processEvent==null||ja.processEvent(Ta)}catch(La){co.error("Error while processing event "+Ln.event+" for site app "+ja.id,La)}}}onRemoteConfig(Ln){var Ta,ja,La,Fa=this;if((Ta=this.siteAppLoaders)!=null&&Ta.length)return this.isEnabled?(this.Je(),void this._instance.on("eventCaptured",(mc=>this.Ke(mc)))):void co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((ja=this.Ve)==null||ja.call(this),(La=Ln.siteApps)!=null&&La.length)if(this.isEnabled){var wl=function(mc){var gc;v$7["__$$ph_site_app_"+mc]=Fa._instance,(gc=v$7.__PosthogExtensions__)==null||gc.loadSiteApp==null||gc.loadSiteApp(Fa._instance,pc,(Vd=>{if(Vd)return co.error("Error while initializing PostHog app with config id "+mc,Vd)}))};for(var{id:Pl,url:pc}of Ln.siteApps)wl(Pl)}else co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var po=function(ta,Ln){if(!ta)return!1;var Ta=ta.userAgent;if(Ta&&y$a(Ta,Ln))return!0;try{var ja=ta?.userAgentData;if(ja!=null&&ja.brands&&ja.brands.some((La=>y$a(La?.brand,Ln))))return!0}catch{}return!!ta.webdriver},go=(function(ta){return ta.US="us",ta.EU="eu",ta.CUSTOM="custom",ta})({}),_o="i.posthog.com";class mo{constructor(Ln){this.Ye={},this.instance=Ln}get apiHost(){var Ln=this.instance.config.api_host.trim().replace(/\/$/,"");return Ln==="https://app.posthog.com"?"https://us.i.posthog.com":Ln}get flagsApiHost(){var Ln=this.instance.config.flags_api_host;return Ln?Ln.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var Ln,Ta=(Ln=this.instance.config.ui_host)==null?void 0:Ln.replace(/\/$/,"");return Ta||(Ta=this.apiHost.replace("."+_o,".posthog.com")),Ta==="https://app.posthog.com"?"https://us.posthog.com":Ta}get region(){return this.Ye[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=go.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.Ye[this.apiHost]=go.EU:this.Ye[this.apiHost]=go.CUSTOM),this.Ye[this.apiHost]}endpointFor(Ln,Ta){if(Ta===void 0&&(Ta=""),Ta&&(Ta=Ta[0]==="/"?Ta:"/"+Ta),Ln==="ui")return this.uiHost+Ta;if(Ln==="flags")return this.flagsApiHost+Ta;if(this.region===go.CUSTOM)return this.apiHost+Ta;var ja=_o+Ta;switch(Ln){case"assets":return"https://"+this.region+"-assets."+ja;case"api":return"https://"+this.region+"."+ja}}}var yo={icontains:(ta,Ln)=>!!t$9&&Ln.href.toLowerCase().indexOf(ta.toLowerCase())>-1,not_icontains:(ta,Ln)=>!!t$9&&Ln.href.toLowerCase().indexOf(ta.toLowerCase())===-1,regex:(ta,Ln)=>!!t$9&&cn$1(Ln.href,ta),not_regex:(ta,Ln)=>!!t$9&&!cn$1(Ln.href,ta),exact:(ta,Ln)=>Ln.href===ta,is_not:(ta,Ln)=>Ln.href!==ta};class bo{constructor(Ln){var Ta=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(ja){ja===void 0&&(ja=!1),Ta.getWebExperiments((La=>{bo.Xe("retrieved web experiments from the server"),Ta.Qe=new Map,La.forEach((Fa=>{if(Fa.feature_flag_key){var wl;Ta.Qe&&(bo.Xe("setting flag key ",Fa.feature_flag_key," to web experiment ",Fa),(wl=Ta.Qe)==null||wl.set(Fa.feature_flag_key,Fa));var Pl=Ta._instance.getFeatureFlag(Fa.feature_flag_key);M$7(Pl)&&Fa.variants[Pl]&&Ta.Ze(Fa.name,Pl,Fa.variants[Pl].transforms)}else if(Fa.variants)for(var pc in Fa.variants){var mc=Fa.variants[pc];bo.tr(mc)&&Ta.Ze(Fa.name,pc,mc.transforms)}}))}),ja)},this._instance=Ln,this._instance.onFeatureFlags((ja=>{this.onFeatureFlags(ja)}))}onFeatureFlags(Ln){if(this._is_bot())bo.Xe("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(j$b(this.Qe))return this.Qe=new Map,this.loadIfEnabled(),void this.previewWebExperiment();bo.Xe("applying feature flags",Ln),Ln.forEach((Ta=>{var ja;if(this.Qe&&(ja=this.Qe)!=null&&ja.has(Ta)){var La,Fa=this._instance.getFeatureFlag(Ta),wl=(La=this.Qe)==null?void 0:La.get(Ta);Fa&&wl!=null&&wl.variants[Fa]&&this.Ze(wl.name,Fa,wl.variants[Fa].transforms)}}))}}previewWebExperiment(){var Ln=bo.getWindowLocation();if(Ln!=null&&Ln.search){var Ta=he$3(Ln?.search,"__experiment_id"),ja=he$3(Ln?.search,"__experiment_variant");Ta&&ja&&(bo.Xe("previewing web experiments "+Ta+" && "+ja),this.getWebExperiments((La=>{this.ir(parseInt(Ta),ja,La)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(Ln,Ta,ja){if(this._instance.config.disable_web_experiments&&!ja)return Ln([]);var La=this._instance.get_property("$web_experiments");if(La&&!Ta)return Ln(La);this._instance.ci({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:Fa=>{if(Fa.statusCode!==200||!Fa.json)return Ln([]);var wl=Fa.json.experiments||[];return Ln(wl)}})}ir(Ln,Ta,ja){var La=ja.filter((Fa=>Fa.id===Ln));La&&La.length>0&&(bo.Xe("Previewing web experiment ["+La[0].name+"] with variant ["+Ta+"]"),this.Ze(La[0].name,Ta,La[0].variants[Ta].transforms))}static tr(Ln){return!j$b(Ln.conditions)&&bo.er(Ln)&&bo.rr(Ln)}static er(Ln){var Ta;if(j$b(Ln.conditions)||j$b((Ta=Ln.conditions)==null?void 0:Ta.url))return!0;var ja,La,Fa,wl=bo.getWindowLocation();return!!wl&&((ja=Ln.conditions)==null||!ja.url||yo[(La=(Fa=Ln.conditions)==null?void 0:Fa.urlMatchType)!==null&&La!==void 0?La:"icontains"](Ln.conditions.url,wl))}static getWindowLocation(){return t$9?.location}static rr(Ln){var Ta;if(j$b(Ln.conditions)||j$b((Ta=Ln.conditions)==null?void 0:Ta.utm))return!0;var ja=ls();if(ja.utm_source){var La,Fa,wl,Pl,pc,mc,gc,Vd,Wd=(La=Ln.conditions)==null||(La=La.utm)==null||!La.utm_campaign||((Fa=Ln.conditions)==null||(Fa=Fa.utm)==null?void 0:Fa.utm_campaign)==ja.utm_campaign,kf=(wl=Ln.conditions)==null||(wl=wl.utm)==null||!wl.utm_source||((Pl=Ln.conditions)==null||(Pl=Pl.utm)==null?void 0:Pl.utm_source)==ja.utm_source,Pf=(pc=Ln.conditions)==null||(pc=pc.utm)==null||!pc.utm_medium||((mc=Ln.conditions)==null||(mc=mc.utm)==null?void 0:mc.utm_medium)==ja.utm_medium,Nf=(gc=Ln.conditions)==null||(gc=gc.utm)==null||!gc.utm_term||((Vd=Ln.conditions)==null||(Vd=Vd.utm)==null?void 0:Vd.utm_term)==ja.utm_term;return Wd&&Pf&&Nf&&kf}return!1}static Xe(Ln){for(var Ta=arguments.length,ja=new Array(Ta>1?Ta-1:0),La=1;La<Ta;La++)ja[La-1]=arguments[La];Pt$2.info("[WebExperiments] "+Ln,ja)}Ze(Ln,Ta,ja){this._is_bot()?bo.Xe("Refusing to render web experiment since the viewer is a likely bot"):Ta!=="control"?ja.forEach((La=>{if(La.selector){var Fa;bo.Xe("applying transform of variant "+Ta+" for experiment "+Ln+" ",La);var wl=(Fa=document)==null?void 0:Fa.querySelectorAll(La.selector);wl?.forEach((Pl=>{var pc=Pl;La.html&&(pc.innerHTML=La.html),La.css&&pc.setAttribute("style",La.css)}))}})):bo.Xe("Control variants leave the page unmodified.")}_is_bot(){return n$9&&this._instance?po(n$9,this._instance.config.custom_blocked_useragents):void 0}}var wo=Tt$1("[PostHog ExternalIntegrations]"),xo={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class $o{constructor(Ln){this._instance=Ln}it(Ln,Ta){var ja;(ja=v$7.__PosthogExtensions__)==null||ja.loadExternalDependency==null||ja.loadExternalDependency(this._instance,Ln,(La=>{if(La)return wo.error("failed to load script",La);Ta()}))}startIfEnabledOrStop(){var Ln=this,Ta=function(wl){var Pl,pc,mc;!La||(Pl=v$7.__PosthogExtensions__)!=null&&(Pl=Pl.integrations)!=null&&Pl[wl]||Ln.it(xo[wl],(()=>{var gc;(gc=v$7.__PosthogExtensions__)==null||(gc=gc.integrations)==null||(gc=gc[wl])==null||gc.start(Ln._instance)})),!La&&(pc=v$7.__PosthogExtensions__)!=null&&(pc=pc.integrations)!=null&&pc[wl]&&((mc=v$7.__PosthogExtensions__)==null||(mc=mc.integrations)==null||(mc=mc[wl])==null||mc.stop())};for(var[ja,La]of Object.entries((Fa=this._instance.config.integrations)!==null&&Fa!==void 0?Fa:{})){var Fa;Ta(ja)}}}var Eo="[SessionRecording]",So=Tt$1(Eo);class ko{get started(){var Ln;return!((Ln=this.sr)==null||!Ln.isStarted)}get status(){return this.sr?this.sr.status:this.nr&&!this.ar?"disabled":"lazy_loading"}constructor(Ln){if(this._forceAllowLocalhostNetworkCapture=!1,this.nr=!1,this.lr=void 0,this._instance=Ln,!this._instance.sessionManager)throw So.error("started without valid sessionManager"),new Error(Eo+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(Eo+' cannot be used with cookieless_mode="always"')}get ar(){var Ln,Ta=!((Ln=this._instance.get_property(ei))==null||!Ln.enabled),ja=!this._instance.config.disable_session_recording,La=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return t$9&&Ta&&ja&&!La}startIfEnabledOrStop(Ln){var Ta;if(!this.ar||(Ta=this.sr)==null||!Ta.isStarted){var ja=!O$6(Object.assign)&&!O$6(Array.from);this.ar&&ja?(this.ur(Ln),So.info("starting")):this.stopRecording()}}ur(Ln){var Ta,ja,La;this.ar&&(v$7!=null&&(Ta=v$7.__PosthogExtensions__)!=null&&(Ta=Ta.rrweb)!=null&&Ta.record&&(ja=v$7.__PosthogExtensions__)!=null&&ja.initSessionRecording?this.hr(Ln):(La=v$7.__PosthogExtensions__)==null||La.loadExternalDependency==null||La.loadExternalDependency(this._instance,this.dr,(Fa=>{if(Fa)return So.error("could not load recorder",Fa);this.hr(Ln)})))}stopRecording(){var Ln,Ta;(Ln=this.lr)==null||Ln.call(this),this.lr=void 0,(Ta=this.sr)==null||Ta.stop()}vr(){var Ln;(Ln=this._instance.persistence)==null||Ln.unregister(si)}cr(Ln){if(this._instance.persistence){var Ta,ja,La=this._instance.persistence,Fa=()=>{var wl=Ln.sessionRecording===!1?void 0:Ln.sessionRecording,Pl=wl?.sampleRate,pc=j$b(Pl)?null:parseFloat(Pl);j$b(pc)&&this.vr();var mc=wl?.minimumDurationMilliseconds;La.register({[ei]:g$8({enabled:!!wl},wl,{networkPayloadCapture:g$8({capturePerformance:Ln.capturePerformance},wl?.networkPayloadCapture),canvasRecording:{enabled:wl?.recordCanvas,fps:wl?.canvasFps,quality:wl?.canvasQuality},sampleRate:pc,minimumDurationMilliseconds:O$6(mc)?null:mc,endpoint:wl?.endpoint,triggerMatchType:wl?.triggerMatchType,masking:wl?.masking,urlTriggers:wl?.urlTriggers})})};Fa(),(Ta=this.lr)==null||Ta.call(this),this.lr=(ja=this._instance.sessionManager)==null?void 0:ja.onSessionId(Fa)}}onRemoteConfig(Ln){"sessionRecording"in Ln?Ln.sessionRecording!==!1?(this.cr(Ln),this.nr=!0,this.startIfEnabledOrStop()):this.nr=!0:So.info("skipping remote config with no sessionRecording",Ln)}log(Ln,Ta){var ja;Ta===void 0&&(Ta="log"),(ja=this.sr)!=null&&ja.log?this.sr.log(Ln,Ta):So.warn("log called before recorder was ready")}get dr(){var Ln,Ta,ja=(Ln=this._instance)==null||(Ln=Ln.persistence)==null?void 0:Ln.get_property(ei);return(ja==null||(Ta=ja.scriptConfig)==null?void 0:Ta.script)||"lazy-recorder"}hr(Ln){var Ta,ja;if((Ta=v$7.__PosthogExtensions__)==null||!Ta.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.sr||(this.sr=(ja=v$7.__PosthogExtensions__)==null?void 0:ja.initSessionRecording(this._instance),this.sr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.sr.start(Ln)}onRRwebEmit(Ln){var Ta;(Ta=this.sr)==null||Ta.onRRwebEmit==null||Ta.onRRwebEmit(Ln)}overrideLinkedFlag(){var Ln,Ta;this.sr||(Ta=this._instance.persistence)==null||Ta.register({$replay_override_linked_flag:!0}),(Ln=this.sr)==null||Ln.overrideLinkedFlag()}overrideSampling(){var Ln,Ta;this.sr||(Ta=this._instance.persistence)==null||Ta.register({$replay_override_sampling:!0}),(Ln=this.sr)==null||Ln.overrideSampling()}overrideTrigger(Ln){var Ta,ja;this.sr||(ja=this._instance.persistence)==null||ja.register({[Ln==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(Ta=this.sr)==null||Ta.overrideTrigger(Ln)}get sdkDebugProperties(){var Ln;return((Ln=this.sr)==null?void 0:Ln.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(Ln,Ta){var ja;return!((ja=this.sr)==null||!ja.tryAddCustomEvent(Ln,Ta))}}var Po={},To=()=>{},Io="posthog",Ro=!an$1&&d$6?.indexOf("MSIE")===-1&&d$6?.indexOf("Mozilla")===-1,Fo=ta=>{var Ln;return g$8({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:Ht(o$d?.location),persistence:"localStorage+cookie",persistence_name:"",loaded:To,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:ta??"unset",__preview_deferred_init_extensions:!1,debug:a$i&&M$7(a$i?.search)&&a$i.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_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(t$9==null||(Ln=t$9.location)==null?void 0:Ln.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_enable_surveys:!1,advanced_disable_toolbar_metrics:!1,feature_flag_request_timeout_ms:3e3,surveys_request_timeout_ms:1e4,on_request_error:Ta=>{var ja="Bad HTTP status: "+Ta.statusCode+" "+Ta.text;Pt$2.error(ja)},get_device_id:Ta=>Ta,capture_performance:void 0,name:"posthog",bootstrap:{},disable_compression:!1,session_idle_timeout_seconds:1800,person_profiles:"identified_only",before_send:void 0,request_queue_config:{flush_interval_ms:eo},error_tracking:{},_onCapture:To,__preview_eager_load_replay:!1},(Ta=>({rageclick:!(Ta&&Ta>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(Ta&&Ta>="2025-05-24")||"history_change",session_recording:Ta&&Ta>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(ta))},Co=ta=>{var Ln={};O$6(ta.process_person)||(Ln.person_profiles=ta.process_person),O$6(ta.xhr_headers)||(Ln.request_headers=ta.xhr_headers),O$6(ta.cookie_name)||(Ln.persistence_name=ta.cookie_name),O$6(ta.disable_cookie)||(Ln.disable_persistence=ta.disable_cookie),O$6(ta.store_google)||(Ln.save_campaign_params=ta.store_google),O$6(ta.verbose)||(Ln.debug=ta.verbose);var Ta=Mt$2({},Ln,ta);return I$9(ta.property_blacklist)&&(O$6(ta.property_denylist)?Ta.property_denylist=ta.property_blacklist:I$9(ta.property_denylist)?Ta.property_denylist=[...ta.property_blacklist,...ta.property_denylist]:Pt$2.error("Invalid value for property_denylist config: "+ta.property_denylist)),Ta};class Oo{constructor(){this.__forceAllowLocalhost=!1}get pr(){return this.__forceAllowLocalhost}set pr(Ln){Pt$2.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=Ln}}let Mo$1=class AUe{get decideEndpointWasHit(){var Ln,Ta;return(Ln=(Ta=this.featureFlags)==null?void 0:Ta.hasLoadedFlags)!==null&&Ln!==void 0&&Ln}get flagsEndpointWasHit(){var Ln,Ta;return(Ln=(Ta=this.featureFlags)==null?void 0:Ta.hasLoadedFlags)!==null&&Ln!==void 0&&Ln}constructor(){this.webPerformance=new Oo,this.gr=!1,this.version=c$e.LIB_VERSION,this._r=new Hn,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=Fo(),this.SentryIntegration=Ze$1,this.sentryIntegration=Ln=>(function(Ta,ja){var La=Qe(Ta,ja);return{name:Xe,processEvent:Fa=>La(Fa)}})(this,Ln),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.mr=!1,this.yr=null,this.br=null,this.wr=null,this.featureFlags=new In(this),this.toolbar=new sr(this),this.scrollManager=new oo(this),this.pageViewManager=new Es(this),this.surveys=new Xn(this),this.experiments=new bo(this),this.exceptions=new mn(this),this.rateLimiter=new Zn(this),this.requestRouter=new mo(this),this.consent=new Ue$1(this),this.externalIntegrations=new $o(this),this.people={set:(Ln,Ta,ja)=>{var La=M$7(Ln)?{[Ln]:Ta}:Ln;this.setPersonProperties(La),ja?.({})},set_once:(Ln,Ta,ja)=>{var La=M$7(Ln)?{[Ln]:Ta}:Ln;this.setPersonProperties(void 0,La),ja?.({})}},this.on("eventCaptured",(Ln=>Pt$2.info('send "'+Ln?.event+'"',Ln)))}init(Ln,Ta,ja){if(ja&&ja!==Io){var La,Fa=(La=Po[ja])!==null&&La!==void 0?La:new AUe;return Fa._init(Ln,Ta,ja),Po[ja]=Fa,Po[Io][ja]=Fa,Fa}return this._init(Ln,Ta,ja)}_init(Ln,Ta,ja){var La;if(Ta===void 0&&(Ta={}),O$6(Ln)||A$8(Ln))return Pt$2.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={},Ta.debug=this.$r(Ta.debug),this.Er=Ta,this.Sr=[],Ta.person_profiles&&(this.br=Ta.person_profiles),this.set_config(Mt$2({},Fo(Ta.defaults),Co(Ta),{name:ja,token:Ln})),this.config.on_xhr_error&&Pt$2.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=Ta.disable_compression?void 0:oe$2.GZipJS;var Fa=this.kr();this.persistence=new Fn(this.config,Fa),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fn(g$8({},this.config,{persistence:"sessionStorage"}),Fa);var wl=g$8({},this.persistence.props),Pl=g$8({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Pr=new ro((qg=>this.Tr(qg)),this.config.request_queue_config),this.Ir=new no(this),this.__request_queue=[];var pc=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(pc||(this.sessionManager=new ho(this),this.sessionPropsManager=new lo$1(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(Pt$2.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Rr(pc)}),0)):(Pt$2.info("Initializing extensions synchronously"),this.Rr(pc)),c$e.DEBUG=c$e.DEBUG||this.config.debug,c$e.DEBUG&&Pt$2.info("Starting in debug mode",{this:this,config:Ta,thisC:g$8({},this.config),p:wl,s:Pl}),((La=Ta.bootstrap)==null?void 0:La.distinctID)!==void 0){var mc,gc,Vd=this.config.get_device_id(Se$2()),Wd=(mc=Ta.bootstrap)!=null&&mc.isIdentifiedID?Vd:Ta.bootstrap.distinctID;this.persistence.set_property(ci,(gc=Ta.bootstrap)!=null&&gc.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:Ta.bootstrap.distinctID,$device_id:Wd})}if(this.Fr()){var kf,Pf,Nf=Object.keys(((kf=Ta.bootstrap)==null?void 0:kf.featureFlags)||{}).filter((qg=>{var Ug;return!((Ug=Ta.bootstrap)==null||(Ug=Ug.featureFlags)==null||!Ug[qg])})).reduce(((qg,Ug)=>{var Bg;return qg[Ug]=((Bg=Ta.bootstrap)==null||(Bg=Bg.featureFlags)==null?void 0:Bg[Ug])||!1,qg}),{}),Eh=Object.keys(((Pf=Ta.bootstrap)==null?void 0:Pf.featureFlagPayloads)||{}).filter((qg=>Nf[qg])).reduce(((qg,Ug)=>{var Bg,U_;return(Bg=Ta.bootstrap)!=null&&(Bg=Bg.featureFlagPayloads)!=null&&Bg[Ug]&&(qg[Ug]=(U_=Ta.bootstrap)==null||(U_=U_.featureFlagPayloads)==null?void 0:U_[Ug]),qg}),{});this.featureFlags.receivedFeatureFlags({featureFlags:Nf,featureFlagPayloads:Eh})}if(pc)this.register_once({distinct_id:wi,$device_id:null},"");else if(!this.get_distinct_id()){var Em=this.config.get_device_id(Se$2());this.register_once({distinct_id:Em,$device_id:Em},""),this.persistence.set_property(ci,"anonymous")}return qt(t$9,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),Ta.segment?Ye(this,(()=>this.Cr())):this.Cr(),R$3(this.config._onCapture)&&this.config._onCapture!==To&&(Pt$2.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(qg=>this.config._onCapture(qg.event,qg)))),this.config.ip&&Pt$2.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}Rr(Ln){var Ta=performance.now();this.historyAutocapture=new Je(this),this.historyAutocapture.startIfEnabled();var ja=[];ja.push((()=>{new or(this).startIfEnabledOrStop()})),ja.push((()=>{var La;this.siteApps=new fo(this),(La=this.siteApps)==null||La.init()})),Ln||ja.push((()=>{this.sessionRecording=new ko(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||ja.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),ja.push((()=>{this.autocapture=new me$2(this),this.autocapture.startIfEnabled()})),ja.push((()=>{this.surveys.loadIfEnabled()})),ja.push((()=>{this.heatmaps=new $s(this),this.heatmaps.startIfEnabled()})),ja.push((()=>{this.webVitalsAutocapture=new bs(this)})),ja.push((()=>{this.exceptionObserver=new Ge$1(this),this.exceptionObserver.startIfEnabled()})),ja.push((()=>{this.deadClicksAutocapture=new qe(this,Be$1),this.deadClicksAutocapture.startIfEnabled()})),ja.push((()=>{if(this.Or){var La=this.Or;this.Or=void 0,this.fi(La)}})),this.Mr(ja,Ta)}Mr(Ln,Ta){for(;Ln.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-Ta>=30&&Ln.length>0)return void setTimeout((()=>{this.Mr(Ln,Ta)}),0);var ja=Ln.shift();if(ja)try{ja()}catch(Fa){Pt$2.error("Error initializing extension:",Fa)}}var La=Math.round(performance.now()-Ta);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:La}),this.config.__preview_deferred_init_extensions&&Pt$2.info("PostHog extensions initialized ("+La+"ms)")}fi(Ln){var Ta,ja,La,Fa,wl,Pl,pc,mc;if(!o$d||!o$d.body)return Pt$2.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.fi(Ln)}),500);this.config.__preview_deferred_init_extensions&&(this.Or=Ln),this.compression=void 0,Ln.supportedCompression&&!this.config.disable_compression&&(this.compression=w$a(Ln.supportedCompression,oe$2.GZipJS)?oe$2.GZipJS:w$a(Ln.supportedCompression,oe$2.Base64)?oe$2.Base64:void 0),(Ta=Ln.analytics)!=null&&Ta.endpoint&&(this.analyticsDefaultEndpoint=Ln.analytics.endpoint),this.set_config({person_profiles:this.br?this.br:"identified_only"}),(ja=this.siteApps)==null||ja.onRemoteConfig(Ln),(La=this.sessionRecording)==null||La.onRemoteConfig(Ln),(Fa=this.autocapture)==null||Fa.onRemoteConfig(Ln),(wl=this.heatmaps)==null||wl.onRemoteConfig(Ln),this.surveys.onRemoteConfig(Ln),(Pl=this.webVitalsAutocapture)==null||Pl.onRemoteConfig(Ln),(pc=this.exceptionObserver)==null||pc.onRemoteConfig(Ln),this.exceptions.onRemoteConfig(Ln),(mc=this.deadClicksAutocapture)==null||mc.onRemoteConfig(Ln)}Cr(){try{this.config.loaded(this)}catch(Ln){Pt$2.critical("`loaded` function failed",Ln)}this.Ar(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.Dr()}),1),new io(this).load(),this.featureFlags.flags()}Ar(){var Ln;this.is_capturing()&&this.config.request_batching&&((Ln=this.Pr)==null||Ln.enable())}_dom_loaded(){this.is_capturing()&&Ct$1(this.__request_queue,(Ln=>this.Tr(Ln))),this.__request_queue=[],this.Ar()}_handle_unload(){var Ln,Ta;this.config.request_batching?(this.jr()&&this.capture("$pageleave"),(Ln=this.Pr)==null||Ln.unload(),(Ta=this.Ir)==null||Ta.unload()):this.jr()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}ci(Ln){this.__loaded&&(Ro?this.__request_queue.push(Ln):this.rateLimiter.isServerRateLimited(Ln.batchKey)||(Ln.transport=Ln.transport||this.config.api_transport,Ln.url=un$1(Ln.url,{ip:this.config.ip?1:0}),Ln.headers=g$8({},this.config.request_headers),Ln.compression=Ln.compression==="best-available"?this.compression:Ln.compression,Ln.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(Ln.disableTransport=["sendBeacon"]),Ln.fetchOptions=Ln.fetchOptions||this.config.fetch_options,(Ta=>{var ja,La,Fa,wl=g$8({},Ta);wl.timeout=wl.timeout||6e4,wl.url=un$1(wl.url,{_:new Date().getTime().toString(),ver:c$e.LIB_VERSION,compression:wl.compression});var Pl=(ja=wl.transport)!==null&&ja!==void 0?ja:"fetch",pc=vn.filter((gc=>!wl.disableTransport||!gc.transport||!wl.disableTransport.includes(gc.transport))),mc=(La=(Fa=Bt$1(pc,(gc=>gc.transport===Pl)))==null?void 0:Fa.method)!==null&&La!==void 0?La:pc[0].method;if(!mc)throw new Error("No available transport method");mc(wl)})(g$8({},Ln,{callback:Ta=>{var ja,La;this.rateLimiter.checkForLimiting(Ta),Ta.statusCode>=400&&((ja=(La=this.config).on_request_error)==null||ja.call(La,Ta)),Ln.callback==null||Ln.callback(Ta)}}))))}Tr(Ln){this.Ir?this.Ir.retriableRequest(Ln):this.ci(Ln)}_execute_array(Ln){var Ta,ja=[],La=[],Fa=[];Ct$1(Ln,(Pl=>{Pl&&(Ta=Pl[0],I$9(Ta)?Fa.push(Pl):R$3(Pl)?Pl.call(this):I$9(Pl)&&Ta==="alias"?ja.push(Pl):I$9(Pl)&&Ta.indexOf("capture")!==-1&&R$3(this[Ta])?Fa.push(Pl):La.push(Pl))}));var wl=function(Pl,pc){Ct$1(Pl,(function(mc){if(I$9(mc[0])){var gc=pc;Ot(mc,(function(Vd){gc=gc[Vd[0]].apply(gc,Vd.slice(1))}))}else this[mc[0]].apply(this,mc.slice(1))}),pc)};wl(ja,this),wl(La,this),wl(Fa,this)}Fr(){var Ln,Ta;return((Ln=this.config.bootstrap)==null?void 0:Ln.featureFlags)&&Object.keys((Ta=this.config.bootstrap)==null?void 0:Ta.featureFlags).length>0||!1}push(Ln){this._execute_array([Ln])}capture(Ln,Ta,ja){var La;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Pr){if(this.is_capturing())if(!O$6(Ln)&&M$7(Ln)){var Fa=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(Fa&&!this.config.__preview_capture_bot_pageviews)){var wl=ja!=null&&ja.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(wl==null||!wl.isRateLimited){Ta!=null&&Ta.$current_url&&!M$7(Ta?.$current_url)&&(Pt$2.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),Ta==null||delete Ta.$current_url),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 Pl=new Date,pc=ja?.timestamp||Pl,mc=Se$2(),gc={uuid:mc,event:Ln,properties:this.calculateEventProperties(Ln,Ta||{},pc,mc)};Ln==="$pageview"&&this.config.__preview_capture_bot_pageviews&&Fa&&(gc.event="$bot_pageview",gc.properties.$browser_type="bot"),wl&&(gc.properties.$lib_rate_limit_remaining_tokens=wl.remainingTokens),ja?.$set&&(gc.$set=ja?.$set);var Vd,Wd=this.Lr(ja?.$set_once);if(Wd&&(gc.$set_once=Wd),(gc=Ut(gc,ja!=null&&ja._noTruncate?null:this.config.properties_string_max_length)).timestamp=pc,O$6(ja?.timestamp)||(gc.properties.$event_time_override_provided=!0,gc.properties.$event_time_override_system_time=Pl),Ln===Nn.DISMISSED||Ln===Nn.SENT){var kf=Ta?.[Un.SURVEY_ID],Pf=Ta?.[Un.SURVEY_ITERATION];Vd={id:kf,current_iteration:Pf},localStorage.getItem(Vn(Vd))||localStorage.setItem(Vn(Vd),"true"),gc.$set=g$8({},gc.$set,{[Gn({id:kf,current_iteration:Pf},Ln===Nn.SENT?"responded":"dismissed")]:!0})}var Nf=g$8({},gc.properties.$set,gc.$set);if(C$c(Nf)||this.setPersonPropertiesForFlags(Nf),!j$b(this.config.before_send)){var Eh=this.Nr(gc);if(!Eh)return;gc=Eh}this._r.emit("eventCaptured",gc);var Em={method:"POST",url:(La=ja?._url)!==null&&La!==void 0?La:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:gc,compression:"best-available",batchKey:ja?._batchKey};return!this.config.request_batching||ja&&(ja==null||!ja._batchKey)||ja!=null&&ja.send_instantly?this.Tr(Em):this.Pr.enqueue(Em),gc}Pt$2.critical("This capture call is ignored due to client rate limiting.")}}else Pt$2.error("No event name provided to posthog.capture")}else Pt$2.uninitializedWarning("posthog.capture")}Mi(Ln){return this.on("eventCaptured",(Ta=>Ln(Ta.event,Ta)))}calculateEventProperties(Ln,Ta,ja,La,Fa){if(ja=ja||new Date,!this.persistence||!this.sessionPersistence)return Ta;var wl=Fa?void 0:this.persistence.remove_event_timer(Ln),Pl=g$8({},Ta);if(Pl.token=this.config.token,Pl.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(Pl.$cookieless_mode=!0),Ln==="$snapshot"){var pc=g$8({},this.persistence.properties(),this.sessionPersistence.properties());return Pl.distinct_id=pc.distinct_id,(!M$7(Pl.distinct_id)&&!L$6(Pl.distinct_id)||A$8(Pl.distinct_id))&&Pt$2.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),Pl}var mc,gc=_s(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:Vd,windowId:Wd}=this.sessionManager.checkAndGetSessionAndWindowId(Fa,ja.getTime());Pl.$session_id=Vd,Pl.$window_id=Wd}this.sessionPropsManager&&Mt$2(Pl,this.sessionPropsManager.getSessionProps());try{var kf;this.sessionRecording&&Mt$2(Pl,this.sessionRecording.sdkDebugProperties),Pl.$sdk_debug_retry_queue_size=(kf=this.Ir)==null?void 0:kf.length}catch(Em){Pl.$sdk_debug_error_capturing_properties=String(Em)}if(this.requestRouter.region===go.CUSTOM&&(Pl.$lib_custom_api_host=this.config.api_host),mc=Ln!=="$pageview"||Fa?Ln!=="$pageleave"||Fa?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(ja):this.pageViewManager.doPageView(ja,La),Pl=Mt$2(Pl,mc),Ln==="$pageview"&&o$d&&(Pl.title=o$d.title),!O$6(wl)){var Pf=ja.getTime()-wl;Pl.$duration=parseFloat((Pf/1e3).toFixed(3))}d$6&&this.config.opt_out_useragent_filter&&(Pl.$browser_type=this._is_bot()?"bot":"browser"),(Pl=Mt$2({},gc,this.persistence.properties(),this.sessionPersistence.properties(),Pl)).$is_identified=this._isIdentified(),I$9(this.config.property_denylist)?Ot(this.config.property_denylist,(function(Em){delete Pl[Em]})):Pt$2.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var Nf=this.config.sanitize_properties;Nf&&(Pt$2.error("sanitize_properties is deprecated. Use before_send instead"),Pl=Nf(Pl,Ln));var Eh=this.Ur();return Pl.$process_person_profile=Eh,Eh&&!Fa&&this.zr("_calculate_event_properties"),Pl}Lr(Ln){var Ta;if(!this.persistence||!this.Ur()||this.gr)return Ln;var ja=this.persistence.get_initial_props(),La=(Ta=this.sessionPropsManager)==null?void 0:Ta.getSetOnceProps(),Fa=Mt$2({},ja,La||{},Ln||{}),wl=this.config.sanitize_properties;return wl&&(Pt$2.error("sanitize_properties is deprecated. Use before_send instead"),Fa=wl(Fa,"$set_once")),this.gr=!0,C$c(Fa)?void 0:Fa}register(Ln,Ta){var ja;(ja=this.persistence)==null||ja.register(Ln,Ta)}register_once(Ln,Ta,ja){var La;(La=this.persistence)==null||La.register_once(Ln,Ta,ja)}register_for_session(Ln){var Ta;(Ta=this.sessionPersistence)==null||Ta.register(Ln)}unregister(Ln){var Ta;(Ta=this.persistence)==null||Ta.unregister(Ln)}unregister_for_session(Ln){var Ta;(Ta=this.sessionPersistence)==null||Ta.unregister(Ln)}Hr(Ln,Ta){this.register({[Ln]:Ta})}getFeatureFlag(Ln,Ta){return this.featureFlags.getFeatureFlag(Ln,Ta)}getFeatureFlagPayload(Ln){var Ta=this.featureFlags.getFeatureFlagPayload(Ln);try{return JSON.parse(Ta)}catch{return Ta}}isFeatureEnabled(Ln,Ta){return this.featureFlags.isFeatureEnabled(Ln,Ta)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(Ln,Ta,ja){this.featureFlags.updateEarlyAccessFeatureEnrollment(Ln,Ta,ja)}getEarlyAccessFeatures(Ln,Ta,ja){return Ta===void 0&&(Ta=!1),this.featureFlags.getEarlyAccessFeatures(Ln,Ta,ja)}on(Ln,Ta){return this._r.on(Ln,Ta)}onFeatureFlags(Ln){return this.featureFlags.onFeatureFlags(Ln)}onSurveysLoaded(Ln){return this.surveys.onSurveysLoaded(Ln)}onSessionId(Ln){var Ta,ja;return(Ta=(ja=this.sessionManager)==null?void 0:ja.onSessionId(Ln))!==null&&Ta!==void 0?Ta:()=>{}}getSurveys(Ln,Ta){Ta===void 0&&(Ta=!1),this.surveys.getSurveys(Ln,Ta)}getActiveMatchingSurveys(Ln,Ta){Ta===void 0&&(Ta=!1),this.surveys.getActiveMatchingSurveys(Ln,Ta)}renderSurvey(Ln,Ta){this.surveys.renderSurvey(Ln,Ta)}displaySurvey(Ln,Ta){Ta===void 0&&(Ta=Kn),this.surveys.displaySurvey(Ln,Ta)}canRenderSurvey(Ln){return this.surveys.canRenderSurvey(Ln)}canRenderSurveyAsync(Ln,Ta){return Ta===void 0&&(Ta=!1),this.surveys.canRenderSurveyAsync(Ln,Ta)}identify(Ln,Ta,ja){if(!this.__loaded||!this.persistence)return Pt$2.uninitializedWarning("posthog.identify");if(L$6(Ln)&&(Ln=Ln.toString(),Pt$2.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),Ln)if(["distinct_id","distinctid"].includes(Ln.toLowerCase()))Pt$2.critical('The string "'+Ln+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(Ln!==wi){if(this.zr("posthog.identify")){var La=this.get_distinct_id();if(this.register({$user_id:Ln}),!this.get_property("$device_id")){var Fa=La;this.register_once({$had_persisted_distinct_id:!0,$device_id:Fa},"")}Ln!==La&&Ln!==this.get_property(Gt)&&(this.unregister(Gt),this.register({distinct_id:Ln}));var wl=(this.persistence.get_property(ci)||"anonymous")==="anonymous";Ln!==La&&wl?(this.persistence.set_property(ci,"identified"),this.setPersonPropertiesForFlags(g$8({},ja||{},Ta||{}),!1),this.capture("$identify",{distinct_id:Ln,$anon_distinct_id:La},{$set:Ta||{},$set_once:ja||{}}),this.wr=fn$1(Ln,Ta,ja),this.featureFlags.setAnonymousDistinctId(La)):(Ta||ja)&&this.setPersonProperties(Ta,ja),Ln!==La&&(this.reloadFeatureFlags(),this.unregister(vi))}}else Pt$2.critical('The string "'+wi+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else Pt$2.error("Unique user id has not been set in posthog.identify")}setPersonProperties(Ln,Ta){if((Ln||Ta)&&this.zr("posthog.setPersonProperties")){var ja=fn$1(this.get_distinct_id(),Ln,Ta);this.wr!==ja?(this.setPersonPropertiesForFlags(g$8({},Ta||{},Ln||{})),this.capture("$set",{$set:Ln||{},$set_once:Ta||{}}),this.wr=ja):Pt$2.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(Ln,Ta,ja){if(Ln&&Ta){if(this.zr("posthog.group")){var La=this.getGroups();La[Ln]!==Ta&&this.resetGroupPropertiesForFlags(Ln),this.register({$groups:g$8({},La,{[Ln]:Ta})}),ja&&(this.capture("$groupidentify",{$group_type:Ln,$group_key:Ta,$group_set:ja}),this.setGroupPropertiesForFlags({[Ln]:ja})),La[Ln]===Ta||ja||this.reloadFeatureFlags()}}else Pt$2.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0),this.featureFlags.setPersonPropertiesForFlags(Ln,Ta)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(Ln,Ta){Ta===void 0&&(Ta=!0),this.zr("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(Ln,Ta)}resetGroupPropertiesForFlags(Ln){this.featureFlags.resetGroupPropertiesForFlags(Ln)}reset(Ln){var Ta,ja,La,Fa;if(Pt$2.info("reset"),!this.__loaded)return Pt$2.uninitializedWarning("posthog.reset");var wl=this.get_property("$device_id");if(this.consent.reset(),(Ta=this.persistence)==null||Ta.clear(),(ja=this.sessionPersistence)==null||ja.clear(),this.surveys.reset(),this.featureFlags.reset(),(La=this.persistence)==null||La.set_property(ci,"anonymous"),(Fa=this.sessionManager)==null||Fa.resetSessionId(),this.wr=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:wi,$device_id:null},"");else{var Pl=this.config.get_device_id(Se$2());this.register_once({distinct_id:Pl,$device_id:Ln?Pl:wl},"")}this.register({$last_posthog_reset:new Date().toISOString()},1)}get_distinct_id(){return this.get_property("distinct_id")}getGroups(){return this.get_property("$groups")||{}}get_session_id(){var Ln,Ta;return(Ln=(Ta=this.sessionManager)==null?void 0:Ta.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&Ln!==void 0?Ln:""}get_session_replay_url(Ln){if(!this.sessionManager)return"";var{sessionId:Ta,sessionStartTimestamp:ja}=this.sessionManager.checkAndGetSessionAndWindowId(!0),La=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+Ta);if(Ln!=null&&Ln.withTimestamp&&ja){var Fa,wl=(Fa=Ln.timestampLookBack)!==null&&Fa!==void 0?Fa:10;if(!ja)return La;La+="?t="+Math.max(Math.floor((new Date().getTime()-ja)/1e3)-wl,0)}return La}alias(Ln,Ta){return Ln===this.get_property(Wt)?(Pt$2.critical("Attempting to create alias for existing People user - aborting."),-2):this.zr("posthog.alias")?(O$6(Ta)&&(Ta=this.get_distinct_id()),Ln!==Ta?(this.Hr(Gt,Ln),this.capture("$create_alias",{alias:Ln,distinct_id:Ta})):(Pt$2.warn("alias matches current distinct_id - skipping api call."),this.identify(Ln),-1)):void 0}set_config(Ln){var Ta=g$8({},this.config);if(F$8(Ln)){var ja,La,Fa,wl,Pl;Mt$2(this.config,Co(Ln));var pc=this.kr();(ja=this.persistence)==null||ja.update_config(this.config,Ta,pc),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new Fn(g$8({},this.config,{persistence:"sessionStorage"}),pc);var mc=this.$r(this.config.debug);N$6(mc)&&(this.config.debug=mc),N$6(this.config.debug)&&(this.config.debug?(c$e.DEBUG=!0,Ce$3.H()&&Ce$3.G("ph_debug","true"),Pt$2.info("set_config",{config:Ln,oldConfig:Ta,newConfig:g$8({},this.config)})):(c$e.DEBUG=!1,Ce$3.H()&&Ce$3.V("ph_debug"))),(La=this.sessionRecording)==null||La.startIfEnabledOrStop(),(Fa=this.autocapture)==null||Fa.startIfEnabled(),(wl=this.heatmaps)==null||wl.startIfEnabled(),this.surveys.loadIfEnabled(),this.Br(),(Pl=this.externalIntegrations)==null||Pl.startIfEnabledOrStop()}}startSessionRecording(Ln){var Ta=Ln===!0,ja={sampling:Ta||!(Ln==null||!Ln.sampling),linked_flag:Ta||!(Ln==null||!Ln.linked_flag),url_trigger:Ta||!(Ln==null||!Ln.url_trigger),event_trigger:Ta||!(Ln==null||!Ln.event_trigger)};if(Object.values(ja).some(Boolean)){var La,Fa,wl,Pl,pc;(La=this.sessionManager)==null||La.checkAndGetSessionAndWindowId(),ja.sampling&&((Fa=this.sessionRecording)==null||Fa.overrideSampling()),ja.linked_flag&&((wl=this.sessionRecording)==null||wl.overrideLinkedFlag()),ja.url_trigger&&((Pl=this.sessionRecording)==null||Pl.overrideTrigger("url")),ja.event_trigger&&((pc=this.sessionRecording)==null||pc.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var Ln;return!((Ln=this.sessionRecording)==null||!Ln.started)}captureException(Ln,Ta){var ja=new Error("PostHog syntheticException"),La=this.exceptions.buildProperties(Ln,{handled:!0,syntheticException:ja});return this.exceptions.sendExceptionEvent(g$8({},La,Ta))}loadToolbar(Ln){return this.toolbar.loadToolbar(Ln)}get_property(Ln){var Ta;return(Ta=this.persistence)==null?void 0:Ta.props[Ln]}getSessionProperty(Ln){var Ta;return(Ta=this.sessionPersistence)==null?void 0:Ta.props[Ln]}toString(){var Ln,Ta=(Ln=this.config.name)!==null&&Ln!==void 0?Ln:Io;return Ta!==Io&&(Ta=Io+"."+Ta),Ta}_isIdentified(){var Ln,Ta;return((Ln=this.persistence)==null?void 0:Ln.get_property(ci))==="identified"||((Ta=this.sessionPersistence)==null?void 0:Ta.get_property(ci))==="identified"}Ur(){var Ln,Ta;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&C$c(this.getGroups())&&((Ln=this.persistence)==null||(Ln=Ln.props)==null||!Ln[Gt])&&((Ta=this.persistence)==null||(Ta=Ta.props)==null||!Ta[yi]))}jr(){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.Ur()||this.zr("posthog.createPersonProfile")&&this.setPersonProperties({},{})}zr(Ln){return this.config.person_profiles==="never"?(Pt$2.error(Ln+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.Hr(yi,!0),!0)}kr(){if(this.config.cookieless_mode==="always")return!0;var Ln=this.consent.isOptedOut(),Ta=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||Ln&&!!Ta}Br(){var Ln,Ta,ja,La,Fa=this.kr();return((Ln=this.persistence)==null?void 0:Ln.wi)!==Fa&&((ja=this.persistence)==null||ja.set_disabled(Fa)),((Ta=this.sessionPersistence)==null?void 0:Ta.wi)!==Fa&&((La=this.sessionPersistence)==null||La.set_disabled(Fa)),Fa}opt_in_capturing(Ln){if(this.config.cookieless_mode!=="always"){var Ta,ja;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(Ta=this.sessionManager)==null||Ta.destroy(),this.sessionManager=new ho(this),this.persistence&&(this.sessionPropsManager=new lo$1(this,this.sessionManager,this.persistence)),this.sessionRecording=new ko(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.Br(),this.Ar(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(O$6(Ln?.captureEventName)||Ln!=null&&Ln.captureEventName)&&this.capture((ja=Ln?.captureEventName)!==null&&ja!==void 0?ja:"$opt_in",Ln?.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.Dr()}else Pt$2.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var Ln,Ta;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.Br(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:wi,$device_id:null}),(Ln=this.sessionManager)==null||Ln.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(Ta=this.sessionRecording)==null||Ta.stopRecording(),this.sessionRecording=void 0,this.Dr())):Pt$2.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}has_opted_in_capturing(){return this.consent.isOptedIn()}has_opted_out_capturing(){return this.consent.isOptedOut()}get_explicit_consent_status(){var Ln=this.consent.consent;return Ln===Ne$2.GRANTED?"granted":Ln===Ne$2.DENIED?"denied":"pending"}is_capturing(){return this.config.cookieless_mode==="always"||(this.config.cookieless_mode==="on_reject"?this.consent.isExplicitlyOptedOut()||this.consent.isOptedIn():!this.has_opted_out_capturing())}clear_opt_in_out_capturing(){this.consent.reset(),this.Br()}_is_bot(){return n$9?po(n$9,this.config.custom_blocked_useragents):void 0}Dr(){o$d&&(o$d.visibilityState==="visible"?this.mr||(this.mr=!0,this.capture("$pageview",{title:o$d.title},{send_instantly:!0}),this.yr&&(o$d.removeEventListener("visibilitychange",this.yr),this.yr=null)):this.yr||(this.yr=this.Dr.bind(this),qt(o$d,"visibilitychange",this.yr)))}debug(Ln){Ln===!1?(t$9?.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(t$9?.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}))}M(){var Ln,Ta,ja,La,Fa,wl,Pl,pc=this.Er||{};return"advanced_disable_flags"in pc?!!pc.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(Pt$2.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):(ja="advanced_disable_decide",La=!1,Fa=Pt$2,wl=(Ta="advanced_disable_flags")in(Ln=pc)&&!O$6(Ln[Ta]),Pl=ja in Ln&&!O$6(Ln[ja]),wl?Ln[Ta]:Pl?(Fa&&Fa.warn("Config field '"+ja+"' is deprecated. Please use '"+Ta+"' instead. The old field will be removed in a future major version."),Ln[ja]):La)}Nr(Ln){if(j$b(this.config.before_send))return Ln;var Ta=I$9(this.config.before_send)?this.config.before_send:[this.config.before_send],ja=Ln;for(var La of Ta){if(ja=La(ja),j$b(ja)){var Fa="Event '"+Ln.event+"' was rejected in beforeSend function";return z$6(Ln.event)?Pt$2.warn(Fa+". This can cause unexpected behavior."):Pt$2.info(Fa),null}ja.properties&&!C$c(ja.properties)||Pt$2.warn("Event '"+Ln.event+"' has no properties after beforeSend function, this is likely an error.")}return ja}getPageViewId(){var Ln;return(Ln=this.pageViewManager.Vt)==null?void 0:Ln.pageViewId}captureTraceFeedback(Ln,Ta){this.capture("$ai_feedback",{$ai_trace_id:String(Ln),$ai_feedback_text:Ta})}captureTraceMetric(Ln,Ta,ja){this.capture("$ai_metric",{$ai_trace_id:String(Ln),$ai_metric_name:Ta,$ai_metric_value:String(ja)})}$r(Ln){var Ta=N$6(Ln)&&!Ln,ja=Ce$3.H()&&Ce$3.q("ph_debug")==="true";return!Ta&&(!!ja||Ln)}};(function(ta,Ln){for(var Ta=0;Ta<Ln.length;Ta++)ta.prototype[Ln[Ta]]=Lt(ta.prototype[Ln[Ta]])})(Mo$1,["identify"]);var Ao,Do=(Ao=Po[Io]=new Mo$1,(function(){function ta(){ta.done||(ta.done=!0,Ro=!1,Ot(Po,(function(Ln){Ln._dom_loaded()})))}o$d!=null&&o$d.addEventListener?o$d.readyState==="complete"?ta():qt(o$d,"DOMContentLoaded",ta,{capture:!1}):t$9&&Pt$2.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),Ao);const IS_PLAYGROUND$6=!1,metaAxiosInstance$1=axiosInstance("meta"),useAuth=()=>{const ta=useNavigate(),Ln=useAppStore(VC=>VC.resetStore),Ta=useAppStore(VC=>VC.user),ja=useAppStore(VC=>VC.setUser),{initializeApp:La,resetInitialization:Fa}=useAppInitialization(),[wl,Pl]=reactExports$1.useState(!1),[pc,mc]=reactExports$1.useState(!1),[gc,Vd]=reactExports$1.useState(null),Wd=useAppStore(VC=>VC.clearAuth),kf=useAppStore(VC=>VC.setAuthState),Pf=useAppStore(VC=>VC.setAuthError),Nf=useAppStore(VC=>VC.setAuthData),Eh=VC=>{try{const tj=VC.split(".")[1];return JSON.parse(atob(tj)).email||null}catch(tj){console.warn(`Failed to decode JWT token: ${tj}`)}},Em=async(VC,tj)=>{try{kf("loading"),Pf(null);const aB=localStorage.getItem("username");if(aB&&aB!==VC){console.log("Switching accounts - clearing previous user data"),localStorage.removeItem("id_token"),localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("user_id"),localStorage.removeItem("session_id"),localStorage.removeItem("username"),localStorage.removeItem("user_profile_id"),localStorage.removeItem("workspace_id"),localStorage.removeItem("agentlang-studio-store"),Ln(),Wd();const{setLastDataFetch:sP}=useAppStore.getState();sP(0)}const{data:r6}=await metaAxiosInstance$1.post("/agentlang_auth/login",{email:VC,password:tj}),J2=r6;if(J2&&typeof J2=="object"&&J2.id_token){const Q2=Eh(J2.id_token)||VC;Nf({token:J2.id_token,accessToken:J2.access_token,refreshToken:J2.refresh_token,userId:J2.userId,sessionId:J2.sessionId,username:Q2});const{setLastDataFetch:q5}=useAppStore.getState();q5(0);try{const nj=String(J2.userId||Q2);Do.identify(nj,{email:Q2,sessionId:J2.sessionId,authMethod:"password"})}catch(nj){console.warn("PostHog identify failed:",nj)}}else if(typeof J2=="string"&&J2.includes("/")){if(console.log("Processing legacy login format:",J2),typeof J2.split!="function")throw console.error("loginResult.split is not a function:",{loginResult:J2,type:typeof J2}),new Error("Invalid login result format - split method not available");const[sP,Q2]=J2.split("/");if(!sP||!Q2)throw console.error("Invalid userId/sessionId format:",{userId:sP,sessionId:Q2,loginResult:J2}),new Error("Invalid login result format - missing userId or sessionId");Nf({userId:sP,sessionId:Q2,username:VC});const{setLastDataFetch:q5}=useAppStore.getState();q5(0);try{const nj=String(sP||VC);Do.identify(nj,{email:VC,sessionId:Q2,authMethod:"password"})}catch(nj){console.warn("PostHog identify failed (legacy):",nj)}}else throw console.error("Login failed - invalid response format:",{loginResult:J2,type:typeof J2,isObject:typeof J2=="object",isString:typeof J2=="string",hasIdToken:J2?.id_token,includesSlash:typeof J2=="string"&&J2.includes("/")}),new Error(`Login failed due to invalid response format. Expected object with id_token or string with '/', got: ${typeof J2}`);y$b.success("Login successful");const{authData:V_}=useAppStore.getState();if(V_.userId)try{const sP=await metaAxiosInstance$1.get(`/agentlang_auth/User/${V_.userId}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(sP.data&&Array.isArray(sP.data)&&sP.data.length>0){const Q2=sP.data[sP.data.length-1].UserProfile;if(Q2.id){localStorage.setItem("user_profile_id",Q2.id),Nf({userProfileId:Q2.id});try{const q5=String(V_.userId||V_.username||"unknown");Do.group("user_profile",Q2.id,{email:Q2.userEmail||V_.username}),Do.identify(q5,{email:Q2.userEmail||V_.username,userProfileId:Q2.id})}catch(q5){console.warn("PostHog person/group update failed:",q5)}}}}catch(sP){console.warn("Failed to fetch user profile after login:",sP)}La(),ta("/home")}catch(aB){console.error("Login error:",aB),y$b.error(aB?.response?.data?.reason||"Login failed"),y$b.error(aB?.response?.data?.message||aB?.message||"Login failed")}},qg=async()=>{if(!wl){Pl(!0);try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("userLoggingOut")),IS_PLAYGROUND$6||await metaAxiosInstance$1.post("/agentlang_auth/logout")}catch(VC){console.warn("Logout API call failed, but clearing local data:",VC)}finally{try{Do.reset()}catch(r6){console.warn("PostHog reset failed:",r6)}Wd(),localStorage.removeItem("workspace_id"),localStorage.removeItem("user_profile_id"),localStorage.removeItem("id_token"),localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),localStorage.removeItem("user_id"),localStorage.removeItem("session_id"),localStorage.removeItem("username"),Ln(),Fa(),localStorage.removeItem("agentlang-studio-store"),localStorage.removeItem("chatbotMessages");const{setAuthData:VC,setWorkspace:tj,setUser:aB}=useAppStore.getState();VC({token:"",userId:"",sessionId:"",username:"",userProfileId:"",accessToken:"",refreshToken:""}),tj(""),aB({Email:"",CurrentWorkspace:{Id:""},Anthropic:{Key:""},OpenAI:{Key:"",FinetunedModel:""},GitHub:{Username:"",Org:"",Token:""}}),Pl(!1),ta("/")}}},Ug=async(VC,tj)=>{try{const{authData:aB}=useAppStore.getState();if(!aB.token){y$b.error("Authentication token not found. Please login again.");return}await metaAxiosInstance$1.post("/agentlang_auth/changePassword",{newPassword:tj,password:VC}),y$b.success("Password changed successfully")}catch(aB){y$b.error(aB?.response?.data?.reason||"Failed to change password")}},Bg=async VC=>{try{const{authData:tj}=useAppStore.getState(),{username:aB,userId:r6,userProfileId:J2}=tj;if(!r6||!J2){y$b.error("User ID not found. Please re-login.");return}await metaAxiosInstance$1.put(`/agentlang_auth/User/${r6}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile/${J2}`,{userEmail:aB,userKeys:{OpenAI:VC.OpenAI,Anthropic:VC.Anthropic,GitHub:VC.GitHub}}),ja(VC),y$b.success("Profile updated successfully")}catch(tj){y$b.error(tj?.response?.data?.reason||"Failed to update profile")}},U_=reactExports$1.useCallback(async(VC=!1)=>{const{authData:tj}=useAppStore.getState();let{userId:aB,userProfileId:r6,username:J2}=tj;const{token:V_}=tj;if(r6||(r6=localStorage.getItem("user_profile_id")||""),aB||(aB=localStorage.getItem("user_id")||""),J2||(J2=localStorage.getItem("username")||""),!!!(aB&&J2&&V_)){console.log("Auth not ready for profile fetch:",{userId:aB,username:J2,hasToken:!!V_});return}if(!(!VC&&Ta.Email&&!pc))try{if(mc(!0),Vd(null),!r6){const q5=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(q5.data&&Array.isArray(q5.data)&&q5.data.length>0){const nj=q5.data[q5.data.length-1].UserProfile;if(nj.id){localStorage.setItem("user_profile_id",nj.id);const l6=useAppStore.getState().authData;Nf({...l6,userProfileId:nj.id}),console.log("Set userProfileId in auth store:",nj.id)}let n6;try{n6=typeof nj.userKeys=="string"?JSON.parse(nj.userKeys):nj.userKeys}catch{n6={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}ja({Email:nj.userEmail||J2,CurrentWorkspace:{Id:""},...n6});return}console.warn("No user profiles found. User needs to complete signup process to create profile."),Vd("No user profile found. Please contact support if this persists.");return}const Q2=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile/${r6}`);if(!Q2.data||Array.isArray(Q2.data)&&Q2.data.length===0){const q5=await metaAxiosInstance$1.get(`/agentlang_auth/User/${aB}/AgentMeta$UserHasUserProfile/AgentMeta$UserProfile`);if(q5.data&&Array.isArray(q5.data)&&q5.data.length>0){const nj=q5.data[q5.data.length-1].UserProfile;if(nj.id){localStorage.setItem("user_profile_id",nj.id);const l6=useAppStore.getState().authData;Nf({...l6,userProfileId:nj.id}),console.log("Set userProfileId in auth store (fallback):",nj.id);try{const i6=String(l6.userId||l6.username||"unknown");Do.group("user_profile",nj.id,{email:nj.userEmail||l6.username}),Do.identify(i6,{email:nj.userEmail||l6.username,userProfileId:nj.id})}catch(i6){console.warn("PostHog person/group update failed (fallback):",i6)}}let n6;try{n6=typeof nj.userKeys=="string"?JSON.parse(nj.userKeys):nj.userKeys}catch{n6={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}ja({Email:nj.userEmail||J2,CurrentWorkspace:{Id:""},...n6});return}console.warn("No profiles found for user. User needs to complete signup process."),Vd("No user profile found. Please contact support if this persists.");return}if(Q2.data&&Array.isArray(Q2.data)&&Q2.data.length>0){const q5=Q2.data[0].UserProfile;let nj;try{nj=typeof q5.userKeys=="string"?JSON.parse(q5.userKeys):q5.userKeys}catch(l6){console.warn("Failed to parse userKeys JSON:",l6),nj={OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}}const n6={Email:q5.userEmail||J2||"",CurrentWorkspace:Ta.CurrentWorkspace||{Id:""},Anthropic:nj.Anthropic||{Key:""},OpenAI:nj.OpenAI||{Key:"",FinetunedModel:""},GitHub:nj.GitHub||{Username:"",Org:"",Token:""}};ja(n6)}else throw new Error("Unexpected response format")}catch(Q2){console.error("useAuth: Failed to fetch user profile:",Q2),Vd(Q2?.response?.data?.reason||Q2?.message||"Failed to fetch user profile")}finally{mc(!1)}},[Ta.CurrentWorkspace,Ta.Email,pc,ja,Nf]),B_=useAppStore(VC=>VC.authReady);return reactExports$1.useEffect(()=>{B_&&U_()},[B_,U_]),{login:Em,logoutHandler:qg,changePassword:Ug,setUserProfile:Bg,isLoggingOut:wl,fetchUserProfile:U_,profileLoading:pc,profileError:gc,userProfile:Ta}},IS_PLAYGROUND$5=!1,metaAxiosInstance=axiosInstance("meta"),useSignUp=()=>{const ta=useNavigate(),[Ln,Ta]=reactExports$1.useState(!1),ja=useAppStore(Pl=>Pl.setAuthData),La=useAppStore(Pl=>Pl.setUser),{initializeApp:Fa}=useAppInitialization();return{signUp:reactExports$1.useCallback(async Pl=>{if(Ln)return{success:!1,error:"Sign up already in progress"};Ta(!0);try{console.log("Registering new user:",Pl.email);const pc=await metaAxiosInstance.post("/agentlang_auth/register",{email:Pl.email,password:Pl.password,firstName:Pl.firstName,lastName:Pl.lastName});if(!pc.data)throw new Error("Registration failed - no response received");const{userId:mc,email:gc}=pc.data;if(!mc)throw new Error("Registration failed - no userId received");console.log("Creating user profile and workspace...");const Vd=await metaAxiosInstance.post("/AgentMeta/PostSignUp",{userId:mc,userEmail:gc||Pl.email,userKeys:{OpenAI:{Key:"",FinetunedModel:""},Anthropic:{Key:""},GitHub:{Username:"",Org:"",Token:""}}});if(!Vd.data||!Array.isArray(Vd.data)||Vd.data.length===0)throw new Error("Failed to create user profile and workspace");const Wd=Vd.data[0];let kf=null,Pf=null;if(Wd?.User?.["AgentMeta/UserHasUserProfile"]?.[0]?.UserProfile){const Em=Wd.User["AgentMeta/UserHasUserProfile"][0].UserProfile;kf=Em.id,Em["AgentMeta/UserWorkspace"]?.[0]?.Workspace&&(Pf=Em["AgentMeta/UserWorkspace"][0].Workspace.id)}if(!kf)throw new Error("Failed to create user profile");console.log("User profile and workspace created successfully:",{userProfileId:kf,workspaceId:Pf}),console.log("Performing automatic login...");const Eh=(await metaAxiosInstance.post("/agentlang_auth/login",{email:Pl.email,password:Pl.password})).data;return Eh&&typeof Eh=="object"&&Eh.id_token?(ja({token:Eh.id_token,accessToken:Eh.access_token,refreshToken:Eh.refresh_token,userId:Eh.userId||mc,sessionId:Eh.sessionId,username:Pl.email,userProfileId:kf}),localStorage.setItem("user_profile_id",kf),Pf&&localStorage.setItem("workspace_id",Pf),La({Email:Pl.email,user_profile_id:kf,CurrentWorkspace:{Id:Pf||""},Anthropic:{Key:""},OpenAI:{Key:"",FinetunedModel:""},GitHub:{Username:"",Org:"",Token:""}}),y$b.success("Account created successfully! Welcome!"),IS_PLAYGROUND$5||await Fa(),ta("/home"),{success:!0,message:"Account created and logged in successfully"}):(y$b.success("Account created successfully! Please login with your credentials."),ta("/"),{success:!0,message:"Account created successfully. Please login."})}catch(pc){console.error("Sign up failed:",pc);const mc=pc?.response?.data?.reason||pc?.response?.data?.message||pc?.message||"Sign up failed. Please try again.";return y$b.error(mc),{success:!1,error:mc}}finally{Ta(!1)}},[ta,ja,La,Fa,Ln]),isSigningUp:Ln}},getEntities=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getEntityNames()}catch(Ln){return console.error("Error fetching module:",Ln),[]}},getRecords=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getRecordNames()}catch(Ln){return console.error("Error fetching records:",Ln),[]}},getEvents=ta=>{if(!ta)return[];try{const Ln=fetchModule$2(ta);return Ln.getEventNames().filter(ja=>!Ln.isPrePostEvent(ja))}catch(Ln){return console.error("Error fetching events:",Ln),[]}},getAgents=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getAgentNames()}catch(Ln){return console.error("Error fetching agents:",Ln),[]}},getDecisions=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getAllDecisions().map(ja=>ja.name)}catch(Ln){return console.error("Error fetching decisions:",Ln),[]}},getRelationships=ta=>{if(!ta)return[];try{return fetchModule$2(ta).getRelationshipNames()}catch(Ln){return console.error("Error fetching relationships:",Ln),[]}},isAgent=(ta,Ln)=>!!fetchModule$2(ta).getAgent(Ln),isEvent=(ta,Ln)=>fetchModule$2(ta).getEventNames().includes(Ln),isRecord=(ta,Ln)=>fetchModule$2(ta).getRecordNames().includes(Ln),isEntity=(ta,Ln)=>fetchModule$2(ta).getEntityNames().includes(Ln),getAgent=(ta,Ln)=>fetchModule$2(ta).getAgent(Ln),useEntity=()=>{const{zoomHandler:ta}=useZoomHandler(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Ug=>Ug.user),{incrementModuleDbChangeCount:La}=useAppStore(),Fa=ja.GitHub.Token,wl=ja.GitHub.Username,Pl=Qn$1(),{saveUISpec:pc}=useSaveUISpec(),mc=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addEntity(Ug,Ta);const Bg=fetchModule$2(Ta).toString();if(saveModuleToGit(Ln,Ta,Bg,`Add entity ${Ug}`,wl,Fa),La(),Pl&&pc)try{const U_=`${Ta}/${Ug}`,B_=repopulateUISchemaForNewEntity(Pl,U_);pc(B_,`Update UI schema for new entity ${Ug}`)}catch(U_){console.error("[useEntity] Failed to repopulate UI schema for new entity:",U_)}setTimeout(()=>{ta(`${Ta}/${Ug}`)},100)},gc=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addRecord$1(Ug,Ta);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add record ${Ug}`,wl,Fa),La(),setTimeout(()=>{ta(`${Ta}/${Ug}`)},100)},Vd=async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");addEvent(Ug,Ta),addWorkflow(Ug,Ta);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add event ${Ug}`,wl,Fa),La(),setTimeout(()=>{ta(Ug)},200)},Wd=(Ug,Bg)=>{let U_;isFqName$1(Bg)?U_=nameToPath$1(Bg).getEntryName():U_=Bg;const B_=U_.replace(/--workflow$/,"");isEvent(Ta||"",B_)?removeEvent(U_,Ta||""):Ug.removeEntry(U_)};return{addEntity:mc,addRecord:gc,addEvent:Vd,deleteHandler:async Ug=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Bg=fetchModule$2(Ta||"");Ug.forEach(VC=>{Wd(Bg,VC)});const U_=Bg.toString(),B_=`Delete entries ${Ug.join(", ")}`;saveModuleToGit(Ln,Ta,U_,B_,wl,Fa),La()},addAttribute:async(Ug,Bg,U_,B_,VC="type",tj=[],aB="",r6)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const J2=fetchModule$2(Ta),V_=J2.getEntry(Ug),sP=VC==="Entity"||VC==="Record",Q2=VC==="@oneof",q5=VC==="@enum";let nj;if(q5&&tj.length>0)nj=enumAttributeSpec(new Set(tj)),aB&&(nj=setDefaultAttributeValue(nj,aB));else if(Q2){if(!r6)throw new Error("Compound type info is required for Entity or Record types");const n6=`${r6.module}/${r6.entity}`;nj=oneOfAttributeSpec(n6)}else if(sP){if(!r6)throw new Error("Compound type info is required for Entity or Record types");nj={type:`${r6.module}/${r6.entity}`,properties:new Map},B_.forEach(n6=>{nj.properties?.set(n6,!0)})}else nj={type:U_,properties:new Map},B_.forEach(n6=>{nj.properties?.set(n6,!0)}),aB&&(nj=setDefaultAttributeValue(nj,aB));if(V_.addAttribute(Bg,nj),saveModuleToGit(Ln,Ta,J2.toString(),`Add attribute ${Bg} to ${Ug}`,wl,Fa),La(),Pl&&pc)try{const n6=`${Ta}/${Ug}`,l6=repopulateUISchemaForNewAttribute(Pl,n6);pc(l6,`Update UI schema for new attribute ${Bg} in ${Ug}`)}catch(n6){console.error(" Failed to repopulate UI schema for new attribute:",n6)}},deleteAttributes:async(Ug,Bg)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta),VC=B_.getEntry(U_);Bg.forEach(tj=>{VC.removeAttribute(tj)}),La(),saveModuleToGit(Ln,Ta,B_.toString(),`Delete attributes ${Bg.join(", ")} from ${Ug}`,wl,Fa)},reorderAttributes:async(Ug,Bg)=>{if(!Ta)throw new Error("moduleName is undefined");if(!Ln)throw new Error("teamName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta);B_.getEntry(U_).reorderAttributes(Bg),La(),await saveModuleToGit(Ln,Ta,B_.toString(),`Reorder attributes in ${Ug}`,wl,Fa)},setEventPublic:async(Ug,Bg)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const U_=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug,B_=fetchModule$2(Ta);getEvent$1(U_,Ta).setPublic(Bg);const tj=B_.toString();La(),await saveModuleToGit(Ln,Ta,tj,`Set Public status for Event ${Ug}`,wl,Fa)},getEventPublic:Ug=>{if(!Ta)throw new Error("moduleName is undefined");const Bg=isFqName$1(Ug)?nameToPath$1(Ug).getEntryName():Ug;return getEvent$1(Bg,Ta).isPublic()}}},useEntityDetailsChange=ta=>{const Ln=Qn$1();return{onEntityDetailsChange:(ja,La)=>{if(ta&&Ln){const Fa={...Ln,[ja]:{...Ln?.[ja]||{},...La}};ta(Fa,`Update ${ja} entity details`)}}}},useModule=()=>{const{incrementModuleDbChangeCount:ta}=useAppStore(),Ln=useNavigate(),{pathname:Ta}=useLocation(),ja=Ta.split("/"),La=getUserModuleNames(),Fa=mc=>{Ln([...ja.slice(0,-1),mc].join("/"))};return{navigateModule:Fa,addModuleHandler:mc=>{addModule$1(mc),Fa(mc),ta()},deleteModuleHandler:mc=>{if(La.length===1){y$b.error("Cannot delete the last module");return}removeModule(mc);const gc=La.filter(Vd=>mc!==Vd);Fa(gc.length>0?gc[gc.length-1]:""),ta()},getModuleCode:mc=>{try{return isModule$1(mc)?fetchModule$2(mc).toString():""}catch(gc){return console.error(gc),""}}}},useOutsideClickHandler=ta=>{const Ln=reactExports$1.useRef(null);return reactExports$1.useEffect(()=>{const Ta=ja=>{const La=ja.target,Fa=La.closest('[role="option"]')||La.closest(".dropdown-options")||La.closest("[data-headlessui-state]")||La.closest("[data-radix-dropdown-menu-content]")||La.closest("[data-radix-dropdown-menu-sub-content]")||La.closest("[data-query-attribute-menu]")||La.closest("[data-radix-portal]")||La.closest("[data-radix-popper-content-wrapper]"),wl=La.closest(".chatbot-fab-button");Ln.current&&!Ln.current.contains(La)&&!Fa&&!wl&&ta()};return document.addEventListener("click",Ta,!0),()=>{document.removeEventListener("click",Ta,!0)}},[ta]),Ln},useRelationship$1=()=>{const{incrementModuleDbChangeCount:ta}=useAppStore(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Vd=>Vd.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username;return{addRelationship:async(Vd,Wd,kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=new Path$1(Wd.module,Wd.entity),Eh=new Path$1(kf.module,kf.entity),Em={path:Nf,alias:Wd.entity,origName:Nf.asFqName(),origAlias:kf.entity},qg={path:Eh,alias:kf.entity,origName:Eh.asFqName(),origAlias:Wd.entity};Pf==="contains"&&addContainsRelationship(Vd,Ta,[Em,qg]),Pf==="between"&&addBetweenRelationship(Vd,Ta,[Em,qg]);const Bg=fetchModule$2(Ta).toString();saveModuleToGit(Ln,Ta,Bg,`Add ${Pf} relationship ${Vd} between ${Wd.entity} and ${kf.entity}`,Fa,La),ta()},setOneToOne:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setOneToOne(!0);const kf=fetchModule$2(Ta).toString();console.log("moduleData",kf),ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to One-to-One relationship`,Fa,La)},setOneToMany:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setOneToMany(!0);const kf=fetchModule$2(Ta).toString();ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to One-to-Many relationship`,Fa,La)},setManyToMany:Vd=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");getRelationship$1(Vd,Ta).setManyToMany(!0);const kf=fetchModule$2(Ta).toString();ta(),saveModuleToGit(Ln,Ta,kf,`Set ${Vd} to Many-to-Many relationship`,Fa,La)},getRelationshipType:Vd=>{if(!Ta)return null;try{const Wd=getRelationship$1(Vd,Ta);return Wd.isOneToOne()?"one-to-one":Wd.isOneToMany()?"one-to-many":Wd.isManyToMany()?"many-to-many":"contains"}catch(Wd){return console.error("Error getting relationship type:",Wd),null}}}},useRouteDataFetching=({routePattern:ta,fetchFunction:Ln,requiresAuth:Ta=!0,dependencies:ja=[]})=>{const La=useLocation(),Fa=reactExports$1.useRef(new Set),wl=reactExports$1.useRef(null),Pl=useAppStore(Eh=>Eh.authData),{token:pc,userId:mc,userProfileId:gc,username:Vd}=Pl,Wd=mc,kf=La.pathname.includes(ta),Pf=reactExports$1.useCallback(Eh=>`${ta}-${Eh}`,[ta]),Nf=reactExports$1.useCallback(async(Eh,Em,qg=!1)=>{const Ug=Pf(Eh);try{await Ln(Eh,Em,qg),Fa.current.add(Ug)}catch(Bg){console.error(`useRouteDataFetching: Failed to fetch data for route ${ta}:`,Bg)}},[Ln,Pf,ta]);return reactExports$1.useEffect(()=>{if(!kf)return;if(wl.current!==Wd&&(Fa.current.clear(),wl.current=Wd),Ta&&!pc){console.log(`useRouteDataFetching: Authentication required for route ${ta}, but no token found`);return}if(!Wd||!Vd||Ta&&!gc){console.log(`useRouteDataFetching: Missing required data for route ${ta}`,{hasWorkspaceId:!!Wd,hasUsername:!!Vd,hasUserProfileId:!!gc,hasAuthToken:!!pc});return}const Eh=Pf(Wd);if(Fa.current.has(Eh)){console.log(`useRouteDataFetching: Data already fetched for route ${ta} and workspace ${Wd}`);return}Nf(Wd,Vd)},[kf,Wd,Vd,gc,pc,Ta,Nf,Pf,ta,...ja]),{refetch:reactExports$1.useCallback((Eh=!1)=>{if(Wd&&Vd&&(!Ta||gc&&pc)){const Em=Pf(Wd);Fa.current.delete(Em),Nf(Wd,Vd,Eh)}},[Wd,Vd,gc,pc,Ta,Nf,Pf,ta]),clearCache:reactExports$1.useCallback(()=>{Fa.current.clear()},[]),isMatchingRoute:kf,hasRequiredData:!!(Wd&&Vd&&(!Ta||gc&&pc))}},useStore=()=>{const{moduleName:ta}=useParams(),Ln=getModuleNames$1().filter(Fa=>Fa!=="agentlang"),{currentTeam:Ta}=useTeams();if(!ta)throw new Error("Module name is undefined");let ja;try{ja=fetchModule$2(ta)}catch(Fa){console.error(Fa)}const La=ja?ja.getEntityNames():[];return{modules:Ln,currentModule:ja,entities:La,currentTeam:Ta}},useRbac=()=>{const{teamName:ta,moduleName:Ln}=useParams(),Ta=useAppStore(i6=>i6.setSelectedRole),ja=useAppStore(i6=>i6.setAppConfig),La=useAppStore(i6=>i6.appConfig),Fa=useAppStore(i6=>i6.user),wl=Fa.GitHub.Token,Pl=Fa.GitHub.Username,{incrementModuleDbChangeCount:pc}=useAppStore(),mc=()=>{if(!ta)throw new Error("Team name is required to save RBAC roles");if(!Ln)throw new Error("Module name is required for RBAC operations")},gc=i6=>{if(!Ln)throw new Error("Module name is required for RBAC operations");const s6=getEntity$1(i6,Ln);if(!s6)throw new Error(`Entity instance for "${i6}" in module "${Ln}" is undefined.`);return s6},Vd=i6=>{if(!Ln||!ta)throw new Error("Module name and team name are required for RBAC operations");const u6=fetchModule$2(Ln).toString();pc(),saveModuleToGit(ta,Ln,u6,i6,Pl,wl)},Wd=(i6,s6,u6,f6="Toggle")=>{try{mc();for(const Xae of i6){const g$e=gc(Xae),n$e=g$e.getRbacSpecifications()||[],v$e=u6([...n$e],s6);g$e.setRbacSpecifications(v$e)}const Rpe=`${f6} all RBAC permissions for role: ${s6}`;Vd(Rpe)}catch(Rpe){throw console.error("Error toggling all RBAC permissions:",Rpe),Rpe}},kf=(i6,s6,u6,f6,Rpe="Toggle")=>{try{mc();for(const g$e of i6){const n$e=gc(g$e),v$e=n$e.getRbacSpecifications()||[],S$e=u6([...v$e],s6,f6);n$e.setRbacSpecifications(S$e)}const Xae=`${Rpe} ${f6} RBAC permission for role: ${s6}`;Vd(Xae)}catch(Xae){throw console.error(`Error toggling ${f6} RBAC permission:`,Xae),Xae}},Pf=(i6,s6,u6,f6="Toggle")=>{try{mc();const Rpe=gc(i6),Xae=Rpe.getRbacSpecifications()||[],g$e=u6([...Xae],s6);Rpe.setRbacSpecifications(g$e);const n$e=`${f6} all RBAC permissions for role: ${s6} on entity: ${i6}`;Vd(n$e)}catch(Rpe){throw console.error("Error toggling all RBAC permissions for entity:",Rpe),Rpe}},Nf=(i6,s6,u6,f6,Rpe="Toggle")=>{try{mc();const Xae=gc(i6),g$e=Xae.getRbacSpecifications()||[],n$e=u6([...g$e],s6,f6);Xae.setRbacSpecifications(n$e);const v$e=`${Rpe} ${f6} RBAC permission for role: ${s6} on entity: ${i6}`;Vd(v$e)}catch(Xae){throw console.error(`Error toggling ${f6} RBAC permission for entity:`,Xae),Xae}},Eh=(i6,s6="Save RBAC roles")=>{mc();const u6={...La,rbac:{roles:i6}};if(ja(u6),!ta)throw new Error("Team name is required to save RBAC roles");saveConfigToGit(ta,JSON.stringify(u6,null,2),s6,Pl,wl)},Em=i6=>{const s6=La?.rbac?.roles||[];Eh([...s6,i6],"Add RBAC role"),Ta(i6)},qg=i6=>{const u6=(La?.rbac?.roles||[]).filter(f6=>f6!==i6);Eh(u6,"Delete RBAC role"),Ta(u6.at(-1)||"")},Ug=(i6,s6)=>{const u6=i6.find(f6=>f6.roles.has(s6));if(u6){if(u6.hasCreatePermission()&&u6.hasReadPermission()&&u6.hasUpdatePermission()&&u6.hasDeletePermission())return i6.filter(Rpe=>Rpe!==u6);u6.setPermissions(["create","read","update","delete"])}else{const f6=new RbacSpecification;f6.setRoles([s6]),f6.setPermissions(["create","read","update","delete"]),i6.push(f6)}return i6},Bg=(i6,s6,u6)=>{const f6=i6.find(Rpe=>Rpe.roles.has(s6));if(f6)if((()=>{switch(u6){case"create":return f6.hasCreatePermission();case"read":return f6.hasReadPermission();case"update":return f6.hasUpdatePermission();case"delete":return f6.hasDeletePermission()}})()){const n$e=Array.from(f6.permissions).map(v$e=>RbacPermissionFlag$1[v$e].toLowerCase()).filter(v$e=>v$e!==u6);if(n$e.length===0)return i6.filter(v$e=>v$e!==f6);f6.setPermissions(n$e)}else{const Xae=Array.from(f6.permissions).map(g$e=>RbacPermissionFlag$1[g$e].toLowerCase());Xae.push(u6),f6.setPermissions(Xae)}else{const Rpe=new RbacSpecification;Rpe.setRoles([s6]),Rpe.setPermissions([u6]),i6.push(Rpe)}return i6};return{saveRbacRoles:Eh,addRole:Em,deleteRole:qg,allHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);Wd(s6,i6,Ug)},createHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"create")},readHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"read")},updateHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"update")},deleteHandler:i6=>{if(!Ln)return;const s6=getEntities(Ln);kf(s6,i6,Bg,"delete")},entityAllHandler:(i6,s6)=>{Pf(i6,s6,Ug)},entityCreateHandler:(i6,s6)=>{Nf(i6,s6,Bg,"create")},entityReadHandler:(i6,s6)=>{Nf(i6,s6,Bg,"read")},entityUpdateHandler:(i6,s6)=>{Nf(i6,s6,Bg,"update")},entityDeleteHandler:(i6,s6)=>{Nf(i6,s6,Bg,"delete")},addExpression:(i6,s6,u6)=>{try{mc();const f6=gc(i6),Rpe=f6.getRbacSpecifications()||[],Xae=Rpe.find(n$e=>n$e.expression),g$e=Object.entries(u6).filter(([n$e,v$e])=>v$e).map(([n$e])=>n$e);if(Xae)Xae.setPermissions(g$e),Xae.setExpression("auth.user",`this.${s6}`);else{const n$e=new RbacSpecification;n$e.setPermissions(g$e),n$e.setExpression("auth.user",`this.${s6}`),Rpe.push(n$e)}f6.setRbacSpecifications(Rpe),Vd(`Add RBAC expression for entity: ${i6}`)}catch(f6){throw console.error("Error setting expression for entity:",f6),f6}},removeExpression:i6=>{try{mc();const s6=gc(i6),f6=(s6.getRbacSpecifications()||[]).filter(Rpe=>!Rpe.expression);s6.setRbacSpecifications(f6),Vd(`Remove RBAC expression for entity: ${i6}`)}catch(s6){throw console.error("Error removing expression for entity:",s6),s6}},getRoleRbacSpec:(i6,s6)=>(mc(),(gc(i6).getRbacSpecifications()||[]).find(Xae=>Xae.roles.has(s6))),getRBACExpression:i6=>(mc(),(gc(i6).getRbacSpecifications()||[]).find(Rpe=>Rpe.expression))}},useWorkflow=ta=>{const{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(kf=>kf.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username,{incrementModuleDbChangeCount:wl}=useAppStore();return{onCreateCrudStatement:async(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta||""),Em=Eh.getWorkflowForEvent(ta);let qg;if(Pf==="create"?qg=newCreatePattern(kf):Pf==="read"?qg=newQueryPattern(kf):Pf==="delete"?qg=newDeletePattern(kf):Pf==="update"&&(qg=newQueryUpdatePattern(kf)),Pf==="loop"?qg=new ForEachPattern$1:Pf==="if-else"&&(qg=new IfPattern$1().setElse()),qg&&Em)await Em.setStatementAt(qg.toString(),Nf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add ${Pf} pattern for ${ta}`,Fa,La)});else throw new Error(`Unknown type: ${Pf}`)},onDeleteStatementHandler:async kf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Pf=fetchModule$2(Ta||"");Pf.getWorkflowForEvent(ta)?.removeStatementAt(kf),wl(),saveModuleToGit(Ln,Ta,Pf.toString(),`Delete pattern for ${ta} at index ${kf}`,Fa,La)},updateStatementHandler:async(kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=fetchModule$2(Ta||"");await Nf.getWorkflowForEvent(ta)?.setStatementAt(Pf,kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Nf.toString(),`Update pattern for ${ta} at index ${kf}`,Fa,La)})},onCreateFunctionCall:async(kf,Pf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Nf=fetchModule$2(Ta||""),Eh=Nf.getWorkflowForEvent(ta),Em=new FunctionCallPattern$1(Pf,[]);await Eh?.setStatementAt(Em.toString(),kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Nf.toString(),`Add function call pattern for ${ta}`,Fa,La)})},onCreateExpression:async(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta||""),Em=Eh.getWorkflowForEvent(ta),qg=new ExpressionPattern$1(Pf);Nf&&qg.setAlias(Nf),await Em?.setStatementAt(qg.toString(),kf).then(async()=>{wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add expression pattern for ${ta}`,Fa,La)})},addTrigger:(kf,Pf,Nf)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");if(Nf==="after")if(Pf==="create")addAfterCreateWorkflow(kf,Ta);else if(Pf==="delete")addAfterDeleteWorkflow(kf,Ta);else if(Pf==="update")addAfterUpdateWorkflow(kf,Ta);else throw new Error("Invalid trigger type");else if(Nf==="before")if(Pf==="create")addBeforeCreateWorkflow(kf);else if(Pf==="delete")addBeforeDeleteWorkflow(kf);else if(Pf==="update")addBeforeUpdateWorkflow(kf,Ta);else throw new Error("Invalid trigger type");else throw new Error("Invalid trigger time");const Eh=fetchModule$2(Ta||"");wl(),saveModuleToGit(Ln,Ta,Eh.toString(),`Add ${Nf} ${Pf} trigger for ${kf}`,Fa,La)}}},useAppConfig=()=>{const{teamName:ta}=useParams(),Ln=useAppStore(Pl=>Pl.appConfig),Ta=useAppStore(Pl=>Pl.setAppConfig),ja=useAppStore(Pl=>Pl.user),La=ja.GitHub.Token,Fa=ja.GitHub.Username;return{saveAppConfig:Pl=>{if(!ta)throw new Error("Team name is required to save app integrations");const pc={...Ln,...Pl};Ta(pc),saveConfigToGit(ta,JSON.stringify(pc,null,2),"Save App Configuration",Fa,La)}}},useFlow=()=>{const{zoomHandler:ta}=useZoomHandler(),{teamName:Ln,moduleName:Ta}=useParams(),ja=useAppStore(Nf=>Nf.user),{incrementModuleDbChangeCount:La,setSelectedDecisionId:Fa}=useAppStore(),wl=ja.GitHub.Token,Pl=ja.GitHub.Username;return{addFlow:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);Eh.addFlow(Nf);const Em=Eh.toString();saveModuleToGit(Ln,Ta,Em,`Add flow ${Nf}`,Pl,wl),La(),setTimeout(()=>{ta(Nf)},100)},removeFlow:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);Em.removeFlow(Nf);const qg=Em.toString();saveModuleToGit(Ln,Ta,qg,`Remove flow ${Nf}`,Pl,wl),La(),Eh&&setTimeout(()=>{ta(Eh)},100)},updateFlow:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);Em.removeFlow(Nf),Em.addFlow(Nf);const qg=Em.getFlow(Nf);if(!qg)throw new Error("Flow could not be recreated");Eh.forEach(Bg=>{const U_=new FlowStepPattern$1(Bg.source,Bg.target,Bg.label);qg.appendStep(U_.toString())});const Ug=Em.toString();saveModuleToGit(Ln,Ta,Ug,`Update flow ${Nf}`,Pl,wl)},addDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);if(Eh.getDecision(Nf))return;const qg=new Decision$1(Nf,Eh.name,[]);Eh.addDecision(qg);const Ug=Eh.toString();saveModuleToGit(Ln,Ta,Ug,`Add decision ${Nf}`,Pl,wl),La(),setTimeout(()=>{Fa(Nf),ta(`decision-node-${Nf}`,{openForm:!0})},200)},removeDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Eh=fetchModule$2(Ta);if(!Eh.getDecision(Nf))return;Eh.removeDecision(Nf);const qg=Eh.toString();saveModuleToGit(Ln,Ta,qg,`Remove decision ${Nf}`,Pl,wl)},updateDecision:(Nf,Eh)=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");const Em=fetchModule$2(Ta);if(!Em.getDecision(Nf))return;Em.removeDecision(Nf);const Ug=new Decision$1(Nf,Em.name,Eh);Em.addDecision(Ug);const Bg=Em.toString();saveModuleToGit(Ln,Ta,Bg,`Update decision ${Nf}`,Pl,wl)},getDecision:Nf=>{if(!Ln)throw new Error("teamName is undefined");if(!Ta)throw new Error("moduleName is undefined");return fetchModule$2(Ta).getDecision(Nf)}}},useMobile=()=>{const[ta,Ln]=reactExports$1.useState(!1);return reactExports$1.useEffect(()=>{const Ta=()=>{Ln(window.innerWidth<768)};return Ta(),window.addEventListener("resize",Ta),()=>window.removeEventListener("resize",Ta)},[]),ta};function transformApiResponseToMarketplaceModel(ta){return{Id:ta.id||"",Name:ta.name||"",Type:ta.type||"",Description:ta.description||"",Version:ta.version||"",Owner:ta.owner||"",GitHubOrg:ta.gitHubOrg||"",GitHubRepo:ta.gitHubRepo||"",Branch:ta.gitHubBranch||ta.branch||"main",CreatedAt:ta.createdAt||"",LastUpdatedAt:ta.lastUpdatedAt||"",Icon:ta.icon||"",MarketPlaceUrl:ta.marketPlaceUrl||"",ExtraDetails:ta.extraDetails||{},GithubOrg:ta.gitHubOrg||"",Config:{},Dependencies:{FractlModels:[],ClojureLibraries:[]},EntityType:"Model",GithubUrl:ta.githubUrl||`https://github.com/${ta.gitHubOrg}/${ta.gitHubRepo}`,__Id__:ta.id||"",Tags:ta.tags||null,isEditable:!1,isPin:!1,isLoading:!1,isError:!1,ErrorMessage:""}}const useMarketplace=()=>{const{error:ta,refetch:Ln}=useQuery({queryKey:["marketplace","models"],enabled:!1,queryFn:async()=>{const Fa=await axiosInstance("marketplace").get("/MarketplaceMeta/Model");console.log("The response of marketplace model is:",Fa.data);let wl=[];return Array.isArray(Fa.data)?Fa.data.length===0?wl=[]:wl=Fa.data.map(Pl=>Pl.Model||Pl).map(Pl=>transformApiResponseToMarketplaceModel(Pl)):Fa.data?.result&&Array.isArray(Fa.data.result)&&(wl=Fa.data.result.map(Pl=>Pl.Model||Pl).map(Pl=>transformApiResponseToMarketplaceModel(Pl))),wl},staleTime:3e5,gcTime:6e5,retry:(Fa,wl)=>wl?.response?.status===401||wl?.response?.status===403?!1:Fa<2}),Ta=reactExports$1.useCallback(async()=>{await Ln()},[Ln]),ja=reactExports$1.useCallback(async Fa=>{try{const wl=await axiosInstance("marketplace").post("/MarketplaceMeta/Model",Fa);return y$b.success("Model published successfully!"),wl.data}catch(wl){const Pl=wl?.response?.data?.reason||"Failed to publish model";throw y$b.error(Pl),wl}},[]),La=reactExports$1.useCallback(async Fa=>{try{await axiosInstance("marketplace").delete(`/MarketplaceMeta/Model/${Fa}`),y$b.success("Model deleted successfully!"),await Ln()}catch(wl){const Pl=wl?.response?.data?.reason||"Failed to delete model";throw y$b.error(Pl),wl}},[Ln]);return{fetchMarketplaceModels:Ta,publishModel:ja,deleteModel:La,refetchMarketplaceModels:Ln}},useAddTeam=()=>{const{addWorkspaceApp:ta}=useTeams(),Ln=useAppStore(Pf=>Pf.user),Ta=Ln.GitHub.Token,ja=Ln.GitHub.Org,La=Ln.GitHub.Username,Fa=useNavigate(),[wl,Pl]=React.useState(!1),[pc,mc]=React.useState("creating-repo"),[gc,Vd]=React.useState("");return{addTeam:async({name:Pf})=>{Pl(!0),mc("creating-repo"),Vd("Creating GitHub repository...");try{const Eh=(await createGitHubRepo(Ta,Pf.toLowerCase(),{private:!0,auto_init:!0},ja)).name;mc("cloning-repo"),Vd("Cloning repository...");try{const Em=`/${Eh}`,qg="main",Ug=La&&La.trim().length>0,Bg=Ta&&Ta.trim().length>0;if(!Ug||!Bg){alert("⚠️ GitHub credentials missing. Please set your GitHub username and token in Settings.");return}const U_=generateGitHubUrl(ja,Eh,La,Ta),B_=async()=>{try{await pathExists(Em)&&(console.log(`Cleaning up failed clone: removing ${Em} from IndexedDB`),await removeDirectory(Em))}catch(r6){console.error("Error cleaning up failed clone:",r6)}};try{await cloneRepository(U_,Em,qg,Ta)}catch(r6){throw console.error("Failed to clone repository:",r6),await B_(),r6}mc("adding-files"),Vd("Adding initial files...");const VC={name:Eh,version:"0.0.1"},tj=await openRepository(Em);await writeRepoFile(Em,"package.json",JSON.stringify(VC)),await commitChanges(tj,"package.json","Add package.json",{name:La,email:La}),await writeRepoFile(Em,"config.al",JSON.stringify({},null,2)),await commitChanges(tj,"config.al","Add config.al",{name:La,email:La});const aB="src/core.al";await writeRepoFile(Em,aB,`module ${Eh.toLowerCase()}.core`),await commitChanges(tj,aB,"Add core.al ",{name:La,email:La}),mc("pushing-changes"),Vd("Pushing changes to GitHub..."),await pushChanges(tj,"origin",qg,Ta),mc("loading-module"),Vd("Loading module...");try{await flushAllAndLoad(`/${Eh}`,{name:"studio"});const r6=getUserModuleNames();mc("adding-workspace"),Vd("Adding to workspace...");const J2={name:Pf,type:"App",gitHubOrg:ja,gitHubRepo:Eh,branch:qg,description:"",owner:localStorage.getItem("username")||"",version:"0.0.1",isEditable:!0};await ta(J2),Pl(!1),Fa(`/design/data-model/${ja}/${Eh}/${r6[0]}`,{state:{isNewTeam:!0}})}catch(r6){console.error(`Failed to load ${Eh}:`,r6);try{await pathExists(Em)&&(console.log(`Cleaning up failed clone: removing ${Em} from IndexedDB`),await removeDirectory(Em))}catch(J2){console.error("Error cleaning up failed clone:",J2)}Pl(!1)}}catch(Em){console.error(`Failed to clone repository: ${Em}`);try{const qg=`/${Eh}`;await pathExists(qg)&&(console.log(`Cleaning up failed clone: removing ${qg} from IndexedDB`),await removeDirectory(qg))}catch(qg){console.error("Error cleaning up failed clone:",qg)}Pl(!1)}}catch(Nf){console.error("Failed to create GitHub Repository:",Nf),Pl(!1)}},isLoading:wl,currentStep:pc,statusMessage:gc,loadingSteps:[{id:"creating-repo",label:"Creating GitHub repository"},{id:"cloning-repo",label:"Cloning repository"},{id:"adding-files",label:"Adding initial files"},{id:"committing-changes",label:"Committing changes"},{id:"pushing-changes",label:"Pushing to GitHub"},{id:"loading-module",label:"Loading module"},{id:"adding-workspace",label:"Adding to workspace"}]}},getDependenciesRecursive=async(ta,Ln,Ta=new Set)=>{const ja=Object.entries(Ln).filter(([Fa,wl])=>{const Pl=typeof wl=="string"&&wl.startsWith("git+http"),pc=!Ta.has(Fa);return Pl&&pc&&Ta.add(Fa),Pl&&pc});return ja.length===0?[]:(await Promise.all(ja.map(async([Fa])=>{const wl=[Fa];try{const Pl=await readDependencyPackageJsonFromGit(ta,Fa);if(Pl.dependencies){const pc=await getDependenciesRecursive(ta,Pl.dependencies,Ta);wl.push(...pc)}}catch(Pl){console.error(`Failed to process dependency ${Fa}:`,Pl)}return wl}))).flat()},fetchDependencies=async ta=>{const Ta=(await readPackageJsonFromGit(ta)).dependencies||{},ja=Object.entries(Ta).filter(([,Fa])=>typeof Fa=="string"&&Fa.startsWith("git+http")).map(([Fa])=>Fa),La=await getDependenciesRecursive(ta,Ta,new Set(ja));return Array.from(new Set([...ja,...La]))},useDependencies=()=>{const{currentTeam:ta}=useTeams(),Ln=ta?.GitHubRepo,{data:Ta=[],isLoading:ja}=useQuery({queryKey:["dependencies",Ln],queryFn:()=>fetchDependencies(Ln),enabled:!!Ln}),La=getUserModuleNames(),Fa=[Ln,...Ta].map(mc=>({label:mc||"",value:mc||""})),wl=mc=>{const gc=mc.toLowerCase(),Vd=gc.replace(/_/g,"");return La.filter(Wd=>{const kf=Wd.toLowerCase(),Pf=kf.split(".")[0];return kf.startsWith(gc)||Pf===Vd})},Pl=Ln||"",pc=Pl?wl(Pl)[0]:"";return{dependencies:Ta,dependenciesOptions:Fa,loading:ja,getDependenciesModule:wl,defaultDependency:Pl,defaultModule:pc}},useDoubleClick=(ta,Ln,Ta=300)=>{const ja=reactExports$1.useRef(null),La=reactExports$1.useRef(0),Fa=reactExports$1.useCallback(wl=>{wl.stopPropagation(),wl.preventDefault(),La.current+=1,La.current===1?ja.current=setTimeout(()=>{La.current===1&&ta(wl),La.current=0,ja.current=null},Ta):La.current===2&&(ja.current&&(clearTimeout(ja.current),ja.current=null),Ln(wl),La.current=0)},[ta,Ln,Ta]);return reactExports$1.useEffect(()=>()=>{ja.current&&clearTimeout(ja.current)},[]),Fa},useRepositoryClone=()=>{const ta=useNavigate(),[Ln,Ta]=reactExports$1.useState(!1),[ja,La]=reactExports$1.useState(""),[Fa,wl]=reactExports$1.useState(""),Pl=useAppStore(Nf=>Nf.setAppConfig),pc=UCe();useAppStore(Nf=>Nf.user);const mc="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",gc="hamza@fractl.io",Vd=reactExports$1.useCallback(()=>{const Nf=gc.trim().length>0,Eh=mc.trim().length>0;(!Nf||!Eh)&&console.warn("GitHub credentials missing - clone may fail for private repositories")},[mc,gc]),Wd=reactExports$1.useCallback(async(Nf,Eh,Em,qg,Ug)=>{const Bg=await readRepoFile(Nf,"package.json"),U_=JSON.parse(Bg);if(U_.dependencies){const Q2=[];for(const[q5,nj]of Object.entries(U_.dependencies))typeof nj=="string"&&nj.startsWith("git+http")&&Q2.push({appName:q5,url:nj});if(Q2.length>0){La(`Installing ${Q2.length} dependencies...`);const nj=(await cloneDependencies(Nf,Q2,gc,mc,(n6,l6,i6)=>{La(`[${l6}/${i6}] ${n6}`)})).filter(n6=>!n6.success);nj.length>0&&console.warn(`Failed to install ${nj.length} of ${Q2.length} dependencies`,nj.map(n6=>n6.appName))}}La("Loading application modules..."),await flushAllAndLoad(Nf,{name:"studio"});const B_=await loadAppConfig(Nf);Pl({...B_,__repoPath:Nf,__repoName:Eh,__gitHubOrg:qg});const VC=getUserModuleNames(),tj=VC.flatMap(Q2=>{const q5=fetchModule$2(Q2);return q5?q5.getAgentNames().filter(nj=>q5.getAgent(nj)?.isPublic()??!1).map(nj=>`${Q2}/${nj}`):[]}),aB=VC.flatMap(Q2=>fetchModule$2(Q2).getEntityNames().map(q5=>`${Q2}/${q5}`)),r6=VC.flatMap(Q2=>buildGraph(Q2).getRoots().map(nj=>`${nj.entity.getModuleName()}/${nj.entity.getEntryName()}`)),J2={Name:Em,Description:U_.description||"An application generated from "+Em},V_=await loadUISchema(Em,Nf,aB,r6,tj,J2);V_.appInfo||(V_.appInfo={}),V_.appInfo.apiUrl="http://localhost:8080",pc(V_);const sP={githubOrg:qg,teamName:Em,branch:Ug,projectPath:Nf};return __vitePreload(()=>import("./replService-CStUCo8F.js"),__vite__mapDeps([48,6,29,1,42,43,12,17,19,25,20,23,24,18,44,31,26,34,45,11,13,10,9])).then(async({default:Q2})=>{try{await Q2.ensureReplSession(sP),await Q2.initializeFileTracking(Nf)}catch(q5){console.error("❌ Failed to setup REPL deployment:",q5)}}),VC.length>0?VC[0]:null},[Pl,gc,mc,La,pc]),kf=reactExports$1.useCallback(async Nf=>{Ta(!0),wl("");try{Vd();const{GitHubOrg:Eh,GitHubRepo:Em,Name:qg,Branch:Ug}=Nf,Bg=`/${Em}`,U_=generateGitHubUrl(Eh,Em,gc,mc);await pathExists(Bg)?La("Repository already exists. Loading modules..."):(La("Cloning repository..."),await cloneRepository(U_,Bg,Ug,mc)),await Wd(Bg,Em,qg,Eh,Ug)}catch(Eh){const Em=Eh instanceof Error?Eh.message:"Failed to clone repository";wl(Em),console.error("Error during repository clone:",Eh);try{const qg=`/${Nf.GitHubRepo}`;await pathExists(qg)&&(console.log(`Cleaning up failed clone: removing ${qg} from IndexedDB`),await removeDirectory(qg))}catch(qg){console.error("Error cleaning up failed clone:",qg)}}finally{Ta(!1)}},[Vd,gc,mc,Wd]),Pf=reactExports$1.useCallback((Nf,Eh,Em,qg,Ug)=>{const Bg=`/design/${Nf?"agents":"data-model"}/${Eh}/${Em}/${qg}`;Ug?ta(Bg,Ug):ta(Bg)},[ta]);return{isCloning:Ln,error:Fa,loadingMessage:ja,cloneAndProcess:kf,navigateToDesign:Pf,processRepository:Wd}};var I$8=Object.defineProperty,E$7=(ta,Ln,Ta)=>Ln in ta?I$8(ta,Ln,{enumerable:!0,configurable:!0,writable:!0,value:Ta}):ta[Ln]=Ta,w$9=(ta,Ln,Ta)=>E$7(ta,typeof Ln!="symbol"?Ln+"":Ln,Ta);function T$a(ta,Ln){for(var Ta=0;Ta<Ln.length;Ta++){const ja=Ln[Ta];if(typeof ja!="string"&&!Array.isArray(ja)){for(const La in ja)if(La!=="default"&&!(La in ta)){const Fa=Object.getOwnPropertyDescriptor(ja,La);Fa&&Object.defineProperty(ta,La,Fa.get?Fa:{enumerable:!0,get:()=>ja[La]})}}}return Object.freeze(Object.defineProperty(ta,Symbol.toStringTag,{value:"Module"}))}function z$5(ta){return{isFile:()=>ta.isFile(),isDirectory:()=>ta.isDirectory(),isSymbolicLink:()=>ta.isSymbolicLink(),size:ta.size,mtime:ta.mtime}}let j$a=class{async readFile(Ln){return(void 0)(Ln,"utf8")}async readFileBuffer(Ln){return(void 0)(Ln)}async writeFile(Ln,Ta){const ja=(void 0)(Ln);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async exists(Ln){try{return await(void 0)(Ln),!0}catch{return!1}}async mkdir(Ln){try{await(void 0)(Ln)}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async readdir(Ln){return(void 0)(Ln)}async stat(Ln){const Ta=await(void 0)(Ln);return z$5(Ta)}async lstat(Ln){const Ta=await(void 0)(Ln);return z$5(Ta)}async unlink(Ln){return(void 0)(Ln)}async rmdir(Ln){return(void 0)(Ln)}async copyFile(Ln,Ta){const ja=(void 0)(Ta);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async moveFile(Ln,Ta){const ja=(void 0)(Ta);return await this.ensureDir(ja),(void 0)(Ln,Ta)}async ensureDir(Ln){try{await(void 0)(Ln,{recursive:!0})}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async removeDir(Ln){return(void 0)(Ln,{recursive:!0,force:!0})}async readDirectory(Ln){return(void 0)(Ln)}async writeFileSystemFromTree(Ln,Ta,ja){for(const La of Ln){const Fa=(void 0)(Ta,La.path);if(La.type==="directory")await this.ensureDir(Fa),La.children&&await this.writeFileSystemFromTree(La.children,Ta,ja);else{const wl=await ja(La.path);await this.writeFile(Fa,wl)}}}};function p$c(){return new j$a}function _$7(ta){return ta&&ta.__esModule&&Object.prototype.hasOwnProperty.call(ta,"default")?ta.default:ta}var b$8,S$a;function x$6(){if(S$a)return b$8;S$a=1;function ta(La){if(typeof La!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(La))}function Ln(La,Fa){for(var wl="",Pl=0,pc=-1,mc=0,gc,Vd=0;Vd<=La.length;++Vd){if(Vd<La.length)gc=La.charCodeAt(Vd);else{if(gc===47)break;gc=47}if(gc===47){if(!(pc===Vd-1||mc===1))if(pc!==Vd-1&&mc===2){if(wl.length<2||Pl!==2||wl.charCodeAt(wl.length-1)!==46||wl.charCodeAt(wl.length-2)!==46){if(wl.length>2){var Wd=wl.lastIndexOf("/");if(Wd!==wl.length-1){Wd===-1?(wl="",Pl=0):(wl=wl.slice(0,Wd),Pl=wl.length-1-wl.lastIndexOf("/")),pc=Vd,mc=0;continue}}else if(wl.length===2||wl.length===1){wl="",Pl=0,pc=Vd,mc=0;continue}}Fa&&(wl.length>0?wl+="/..":wl="..",Pl=2)}else wl.length>0?wl+="/"+La.slice(pc+1,Vd):wl=La.slice(pc+1,Vd),Pl=Vd-pc-1;pc=Vd,mc=0}else gc===46&&mc!==-1?++mc:mc=-1}return wl}function Ta(La,Fa){var wl=Fa.dir||Fa.root,Pl=Fa.base||(Fa.name||"")+(Fa.ext||"");return wl?wl===Fa.root?wl+Pl:wl+La+Pl:Pl}var ja={resolve:function(){for(var La="",Fa=!1,wl,Pl=arguments.length-1;Pl>=-1&&!Fa;Pl--){var pc;Pl>=0?pc=arguments[Pl]:(wl===void 0&&(wl=process.cwd()),pc=wl),ta(pc),pc.length!==0&&(La=pc+"/"+La,Fa=pc.charCodeAt(0)===47)}return La=Ln(La,!Fa),Fa?La.length>0?"/"+La:"/":La.length>0?La:"."},normalize:function(La){if(ta(La),La.length===0)return".";var Fa=La.charCodeAt(0)===47,wl=La.charCodeAt(La.length-1)===47;return La=Ln(La,!Fa),La.length===0&&!Fa&&(La="."),La.length>0&&wl&&(La+="/"),Fa?"/"+La:La},isAbsolute:function(La){return ta(La),La.length>0&&La.charCodeAt(0)===47},join:function(){if(arguments.length===0)return".";for(var La,Fa=0;Fa<arguments.length;++Fa){var wl=arguments[Fa];ta(wl),wl.length>0&&(La===void 0?La=wl:La+="/"+wl)}return La===void 0?".":ja.normalize(La)},relative:function(La,Fa){if(ta(La),ta(Fa),La===Fa||(La=ja.resolve(La),Fa=ja.resolve(Fa),La===Fa))return"";for(var wl=1;wl<La.length&&La.charCodeAt(wl)===47;++wl);for(var Pl=La.length,pc=Pl-wl,mc=1;mc<Fa.length&&Fa.charCodeAt(mc)===47;++mc);for(var gc=Fa.length,Vd=gc-mc,Wd=pc<Vd?pc:Vd,kf=-1,Pf=0;Pf<=Wd;++Pf){if(Pf===Wd){if(Vd>Wd){if(Fa.charCodeAt(mc+Pf)===47)return Fa.slice(mc+Pf+1);if(Pf===0)return Fa.slice(mc+Pf)}else pc>Wd&&(La.charCodeAt(wl+Pf)===47?kf=Pf:Pf===0&&(kf=0));break}var Nf=La.charCodeAt(wl+Pf),Eh=Fa.charCodeAt(mc+Pf);if(Nf!==Eh)break;Nf===47&&(kf=Pf)}var Em="";for(Pf=wl+kf+1;Pf<=Pl;++Pf)(Pf===Pl||La.charCodeAt(Pf)===47)&&(Em.length===0?Em+="..":Em+="/..");return Em.length>0?Em+Fa.slice(mc+kf):(mc+=kf,Fa.charCodeAt(mc)===47&&++mc,Fa.slice(mc))},_makeLong:function(La){return La},dirname:function(La){if(ta(La),La.length===0)return".";for(var Fa=La.charCodeAt(0),wl=Fa===47,Pl=-1,pc=!0,mc=La.length-1;mc>=1;--mc)if(Fa=La.charCodeAt(mc),Fa===47){if(!pc){Pl=mc;break}}else pc=!1;return Pl===-1?wl?"/":".":wl&&Pl===1?"//":La.slice(0,Pl)},basename:function(La,Fa){if(Fa!==void 0&&typeof Fa!="string")throw new TypeError('"ext" argument must be a string');ta(La);var wl=0,Pl=-1,pc=!0,mc;if(Fa!==void 0&&Fa.length>0&&Fa.length<=La.length){if(Fa.length===La.length&&Fa===La)return"";var gc=Fa.length-1,Vd=-1;for(mc=La.length-1;mc>=0;--mc){var Wd=La.charCodeAt(mc);if(Wd===47){if(!pc){wl=mc+1;break}}else Vd===-1&&(pc=!1,Vd=mc+1),gc>=0&&(Wd===Fa.charCodeAt(gc)?--gc===-1&&(Pl=mc):(gc=-1,Pl=Vd))}return wl===Pl?Pl=Vd:Pl===-1&&(Pl=La.length),La.slice(wl,Pl)}else{for(mc=La.length-1;mc>=0;--mc)if(La.charCodeAt(mc)===47){if(!pc){wl=mc+1;break}}else Pl===-1&&(pc=!1,Pl=mc+1);return Pl===-1?"":La.slice(wl,Pl)}},extname:function(La){ta(La);for(var Fa=-1,wl=0,Pl=-1,pc=!0,mc=0,gc=La.length-1;gc>=0;--gc){var Vd=La.charCodeAt(gc);if(Vd===47){if(!pc){wl=gc+1;break}continue}Pl===-1&&(pc=!1,Pl=gc+1),Vd===46?Fa===-1?Fa=gc:mc!==1&&(mc=1):Fa!==-1&&(mc=-1)}return Fa===-1||Pl===-1||mc===0||mc===1&&Fa===Pl-1&&Fa===wl+1?"":La.slice(Fa,Pl)},format:function(La){if(La===null||typeof La!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof La);return Ta("/",La)},parse:function(La){ta(La);var Fa={root:"",dir:"",base:"",ext:"",name:""};if(La.length===0)return Fa;var wl=La.charCodeAt(0),Pl=wl===47,pc;Pl?(Fa.root="/",pc=1):pc=0;for(var mc=-1,gc=0,Vd=-1,Wd=!0,kf=La.length-1,Pf=0;kf>=pc;--kf){if(wl=La.charCodeAt(kf),wl===47){if(!Wd){gc=kf+1;break}continue}Vd===-1&&(Wd=!1,Vd=kf+1),wl===46?mc===-1?mc=kf:Pf!==1&&(Pf=1):mc!==-1&&(Pf=-1)}return mc===-1||Vd===-1||Pf===0||Pf===1&&mc===Vd-1&&mc===gc+1?Vd!==-1&&(gc===0&&Pl?Fa.base=Fa.name=La.slice(1,Vd):Fa.base=Fa.name=La.slice(gc,Vd)):(gc===0&&Pl?(Fa.name=La.slice(1,mc),Fa.base=La.slice(1,Vd)):(Fa.name=La.slice(gc,mc),Fa.base=La.slice(gc,Vd)),Fa.ext=La.slice(mc,Vd)),gc>0?Fa.dir=La.slice(0,gc-1):Pl&&(Fa.dir="/"),Fa},sep:"/",delimiter:":",win32:null,posix:null};return ja.posix=ja,b$8=ja,b$8}var A$7=x$6();const B$5=_$7(A$7),O$5=T$a({__proto__:null,default:B$5},[A$7]);function k$a(ta){if(ta&&typeof ta=="object"){const Ln=ta,Ta=typeof Ln.isFile=="function"?Ln.isFile():typeof Ln.isFile=="boolean"?Ln.isFile:Ln.type==="file"||!Ln.type&&!Ln.isDirectory,ja=typeof Ln.isDirectory=="function"?Ln.isDirectory():typeof Ln.isDirectory=="boolean"?Ln.isDirectory:Ln.type==="dir"||Ln.type==="directory",La=typeof Ln.size=="number"?Ln.size:0;let Fa;return Ln.mtime instanceof Date?Fa=Ln.mtime:typeof Ln.mtime=="number"?Fa=new Date(Ln.mtime):typeof Ln.mtimeMs=="number"?Fa=new Date(Ln.mtimeMs):Fa=new Date,{isFile:()=>Ta,isDirectory:()=>ja,isSymbolicLink:()=>!1,size:La,mtime:Fa}}return{isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1,size:0,mtime:new Date}}let P$9=class{constructor(){w$9(this,"fs"),w$9(this,"initialized",!1),w$9(this,"path",O$5)}async initialize(Ln={}){if(this.initialized)return;const Ta=Ln.name||"fs",ja=new L$9(Ta,{wipe:Ln.wipe});this.fs=ja.promises,this.initialized=!0}ensureInitialized(){if(!this.initialized)throw new Error("LightningFileSystem is not initialized. Call initialize() first.")}async readFile(Ln){return this.ensureInitialized(),(await this.fs.readFile(Ln,{encoding:"utf8"})).toString()}async readFileBuffer(Ln){return this.ensureInitialized(),this.fs.readFile(Ln)}async writeFile(Ln,Ta){this.ensureInitialized();const ja=Ln.substring(0,Ln.lastIndexOf("/"));return ja&&await this.ensureDir(ja),this.fs.writeFile(Ln,Ta)}async exists(Ln){this.ensureInitialized();try{return await this.fs.stat(Ln),!0}catch{return!1}}async mkdir(Ln,Ta){this.ensureInitialized();try{return await this.fs.mkdir(Ln,Ta)}catch(ja){if(ja&&typeof ja=="object"&&"code"in ja&&ja.code!=="EEXIST")throw ja}}async readdir(Ln){return this.ensureInitialized(),this.fs.readdir(Ln)}async stat(Ln){this.ensureInitialized();const Ta=await this.fs.stat(Ln);return k$a(Ta)}async lstat(Ln){this.ensureInitialized();const Ta=await this.fs.stat(Ln);return k$a(Ta)}async unlink(Ln){return this.ensureInitialized(),this.fs.unlink(Ln)}async rmdir(Ln){return this.ensureInitialized(),this.fs.rmdir(Ln)}async copyFile(Ln,Ta){this.ensureInitialized();const ja=Ta.substring(0,Ta.lastIndexOf("/"));ja&&await this.ensureDir(ja);const La=await this.readFileBuffer(Ln);return this.writeFile(Ta,La)}async moveFile(Ln,Ta){this.ensureInitialized();const ja=Ta.substring(0,Ta.lastIndexOf("/"));ja&&await this.ensureDir(ja),await this.copyFile(Ln,Ta),await this.unlink(Ln)}async ensureDir(Ln){if(this.ensureInitialized(),!await this.exists(Ln))try{await this.fs.mkdir(Ln,{recursive:!0})}catch(Ta){if(Ta&&typeof Ta=="object"&&"code"in Ta&&Ta.code!=="EEXIST")throw Ta}}async removeDir(Ln){if(this.ensureInitialized(),!await this.exists(Ln))return;if((await this.stat(Ln)).isFile())return this.unlink(Ln);const Ta=await this.readdir(Ln);for(const ja of Ta){const La=`${Ln}/${ja}`;await this.removeDir(La)}return this.rmdir(Ln)}async readDirectory(Ln){return this.ensureInitialized(),this.fs.readdir(Ln)}async writeFileSystemFromTree(Ln,Ta,ja){for(const La of Ln){const Fa=this.path.join(Ta,La.path);if(La.type==="directory")await this.mkdir(Fa,{recursive:!0}),La.children&&await this.writeFileSystemFromTree(La.children,Ta,ja);else{const wl=await ja(La.path);await this.writeFile(Fa,wl)}}}};async function M$6(ta){const Ln=new P$9;return await Ln.initialize(ta),Ln}async function $$6(ta){return typeof window>"u"?p$c():M$6(ta)}let fsInstance=null;const getFS=async()=>(fsInstance||(fsInstance=await $$6({name:"studio",wipe:!0})),fsInstance);async function fetchFileTree(){const Ln=await fetch("http://localhost:4000/files");if(!Ln.ok)throw new Error("Failed to fetch file tree");return Ln.json()}async function fetchFileContent(ta){const Ta=await fetch(`http://localhost:4000/file?path=${encodeURIComponent(ta)}`);if(!Ta.ok)throw new Error(`Failed to fetch file content for: ${ta}`);const{content:ja}=await Ta.json();return ja}async function fetchPackageInfo(){const Ln=await fetch("http://localhost:4000/info");return Ln.ok?await Ln.json():{}}const useServeMode=()=>{const ta=useNavigate(),Ln=useMatches(),{processRepository:Ta}=useRepositoryClone(),[ja,La]=reactExports$1.useState(""),[Fa,wl]=reactExports$1.useState(null);return{initializeServeMode:reactExports$1.useCallback(async()=>{La("Connecting to local server..."),wl(null);try{const pc=await fetchFileTree(),mc=await fetchPackageInfo();console.log(mc);let gc="",Vd="";if(mc&&mc.name)if(gc=mc.name,gc.startsWith("@")){const Bg=gc.substring(1).split("/");Bg.length===2&&(Vd=Bg[0],gc=Bg[1])}else Vd="local-org",gc=mc.name;const Wd=Vd,kf=gc,Pf=`/${kf}`;La("Loading file system..."),await(await getFS()).writeFileSystemFromTree(pc,Pf,fetchFileContent),La("Processing project...");const Eh=await Ta(Pf,kf,kf,Wd,"main"),qg=Ln[Ln.length-1]?.id;if(["data-model","marketplace-data-model","agents","workflow","security","ui","settings"].includes(qg))return;ta(Eh?`/design/agents/${Wd}/${kf}/${Eh}`:`/design/agents/${Wd}/${kf}`)}catch(pc){const mc=pc instanceof Error?pc.message:"An unknown error occurred";wl(mc),console.error("Failed to initialize serve mode:",pc)}finally{La("")}},[Ta,ta,Ln]),loadingMessage:ja,error:Fa}},validationScehma=create$3().shape({email:create$6().email("Invalid email").required("Email is required"),password:create$6().required("Password is required")}),SignIn=()=>{const{login:ta}=useAuth(),Ln=useNavigate();return reactExports$1.useEffect(()=>{localStorage.getItem("id_token")&&Ln("/home")}),jsxRuntimeExports$1.jsx(Formik,{initialValues:{email:"",password:""},validationSchema:validationScehma,onSubmit:Ta=>{const{email:ja,password:La}=Ta;ta(ja,La)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-2 items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Sign In"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Get started with building your team of AI Agents"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx("div",{className:"auth-link text-right",onClick:()=>Ln("/forgot-password"),children:"Forgot password?"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Sign in"}),jsxRuntimeExports$1.jsxs("p",{className:"flex justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"No account ?"}),jsxRuntimeExports$1.jsx(Link,{className:"auth-link font-bold",to:"/signup",children:"Sign Up"})]})]})})},uppercaseRegex=/[A-Z]/,lowercaseRegex=/[a-z]/,numberRegex=/[0-9]/,specialCharRegex=/[!@#$%^&*(),.?":{}|<>]/,validationSchema$e=create$3().shape({firstName:create$6().required("First Name is required").min(2,"First Name must be at least 2 characters").max(50,"First Name must be less than 50 characters"),lastName:create$6().required("Last Name is required").min(2,"Last Name must be at least 2 characters").max(50,"Last Name must be less than 50 characters"),email:create$6().required("Email is required").email("Invalid email address"),password:create$6().required("Password is required").min(8,"Password must be at least 8 characters").matches(uppercaseRegex,"Password must contain at least one uppercase letter").matches(lowercaseRegex,"Password must contain at least one lowercase letter").matches(numberRegex,"Password must contain at least one number").matches(specialCharRegex,"Password must contain at least one special character"),confirmPassword:create$6().required("Confirm Password is required").oneOf([create$9("password")],"Passwords don't match")}),SignUp=()=>{const ta=useNavigate(),{signUp:Ln,isSigningUp:Ta}=useSignUp(),[ja,La]=reactExports$1.useState(null);return jsxRuntimeExports$1.jsx(Formik,{initialValues:{firstName:"",lastName:"",email:"",password:"",confirmPassword:""},validationSchema:validationSchema$e,onSubmit:async(Fa,{setSubmitting:wl})=>{La(null);try{const Pl=await Ln({firstName:Fa.firstName,lastName:Fa.lastName,email:Fa.email,password:Fa.password});!Pl.success&&Pl.error&&La(Pl.error)}catch{La("An unexpected error occurred. Please try again.")}finally{wl(!1)}},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-2 items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Sign Up"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Get started with building your team of AI Agents"})]}),jsxRuntimeExports$1.jsxs("div",{className:"md:grid flex flex-col md:grid-cols-2 gap-2",children:[jsxRuntimeExports$1.jsx(lAe,{name:"firstName",placeholder:"First Name"}),jsxRuntimeExports$1.jsx(lAe,{name:"lastName",placeholder:"Last Name"}),jsxRuntimeExports$1.jsx("div",{className:"col-span-2",children:jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"})}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx(fAe,{name:"confirmPassword",placeholder:"Confirm Password"})]}),ja&&jsxRuntimeExports$1.jsx("div",{className:"text-red-500 text-sm text-center p-2",children:ja}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",disabled:Ta,children:Ta?"Creating Account...":"Create Account"}),jsxRuntimeExports$1.jsxs("p",{className:"flex justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already have an account ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})},validationSchema$d=create$3().shape({email:create$6().required("Email is required").email("Invalid email address")}),ForgotPassword=()=>{const ta=useNavigate();return jsxRuntimeExports$1.jsx(Formik,{initialValues:{email:""},validationSchema:validationSchema$d,onSubmit:Ln=>{const{email:Ta}=Ln;console.log(Ta)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Reset Password"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Send confirmation code to your email"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Send confirmation code"}),jsxRuntimeExports$1.jsxs("p",{className:"flex flex-col md:flex-row justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already recovered your password ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})},numberOnlyRegex=/^[0-9]+$/,validationSchema$c=create$3().shape({email:create$6().required("Email is required").email("Invalid email address"),password:create$6().required("Password is required"),code:create$6().matches(numberOnlyRegex,"Code must contain only numbers")}),RecoverPassword=()=>{const ta=useNavigate();return jsxRuntimeExports$1.jsx(Formik,{validationSchema:validationSchema$c,initialValues:{email:"",password:"",code:""},onSubmit:Ln=>{const{email:Ta,password:ja,code:La}=Ln;console.log(Ta,ja,La)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"auth-input-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center",children:[jsxRuntimeExports$1.jsx("h1",{className:"text-center",children:"Reset Password"}),jsxRuntimeExports$1.jsx("p",{className:"text-center",children:"Set new password"})]}),jsxRuntimeExports$1.jsx(lAe,{name:"email",placeholder:"Email",type:"email"}),jsxRuntimeExports$1.jsx(fAe,{name:"password",placeholder:"Password"}),jsxRuntimeExports$1.jsx(fAe,{name:"code",placeholder:"Code"}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"submit-button",children:"Set new password"}),jsxRuntimeExports$1.jsxs("p",{className:"flex flex-col md:flex-row justify-center items-center gap-2",children:[jsxRuntimeExports$1.jsx("span",{children:"Already recovered your password ?"}),jsxRuntimeExports$1.jsx("span",{className:"auth-link font-bold",onClick:()=>ta("/"),children:"Sign In"})]})]})})};var classnames={exports:{}};/*!
|
|
34780
34780
|
Copyright (c) 2018 Jed Watson.
|
|
34781
34781
|
Licensed under the MIT License (MIT), see
|
|
34782
34782
|
http://jedwatson.github.io/classnames
|
|
@@ -35644,7 +35644,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
35644
35644
|
monaco.config({ paths: { vs: '...' } })
|
|
35645
35645
|
|
|
35646
35646
|
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
35647
|
-
`},errorHandler=curry(throwError)(errorMessages),validators={config:validateConfig},compose=function ta(){for(var Ln=arguments.length,Ta=new Array(Ln),ja=0;ja<Ln;ja++)Ta[ja]=arguments[ja];return function(La){return Ta.reduceRight(function(Fa,wl){return wl(Fa)},La)}};function merge(ta,Ln){return Object.keys(Ln).forEach(function(Ta){Ln[Ta]instanceof Object&&ta[Ta]&&Object.assign(Ln[Ta],merge(ta[Ta],Ln[Ta]))}),_objectSpread2$1(_objectSpread2$1({},ta),Ln)}var CANCELATION_MESSAGE={type:"cancelation",msg:"operation is manually canceled"};function makeCancelable(ta){var Ln=!1,Ta=new Promise(function(ja,La){ta.then(function(Fa){return Ln?La(CANCELATION_MESSAGE):ja(Fa)}),ta.catch(La)});return Ta.cancel=function(){return Ln=!0},Ta}var _excluded=["monaco"],_state$create=index.create({config:config$1,isInitialized:!1,resolve:null,reject:null,monaco:null}),_state$create2=_slicedToArray(_state$create,2),getState=_state$create2[0],setState=_state$create2[1];function config(ta){var Ln=validators.config(ta),Ta=Ln.monaco,ja=_objectWithoutProperties(Ln,_excluded);setState(function(La){return{config:merge(La.config,ja),monaco:Ta}})}function init(){var ta=getState(function(Ln){var Ta=Ln.monaco,ja=Ln.isInitialized,La=Ln.resolve;return{monaco:Ta,isInitialized:ja,resolve:La}});if(!ta.isInitialized){if(setState({isInitialized:!0}),ta.monaco)return ta.resolve(ta.monaco),makeCancelable(wrapperPromise);if(window.monaco&&window.monaco.editor)return storeMonacoInstance(window.monaco),ta.resolve(window.monaco),makeCancelable(wrapperPromise);compose(injectScripts,getMonacoLoaderScript)(configureLoader)}return makeCancelable(wrapperPromise)}function injectScripts(ta){return document.body.appendChild(ta)}function createScript(ta){var Ln=document.createElement("script");return ta&&(Ln.src=ta),Ln}function getMonacoLoaderScript(ta){var Ln=getState(function(ja){var La=ja.config,Fa=ja.reject;return{config:La,reject:Fa}}),Ta=createScript("".concat(Ln.config.paths.vs,"/loader.js"));return Ta.onload=function(){return ta()},Ta.onerror=Ln.reject,Ta}function configureLoader(){var ta=getState(function(Ta){var ja=Ta.config,La=Ta.resolve,Fa=Ta.reject;return{config:ja,resolve:La,reject:Fa}}),Ln=window.require;Ln.config(ta.config),Ln(["vs/editor/editor.main"],function(Ta){var ja=Ta.m||Ta;storeMonacoInstance(ja),ta.resolve(ja)},function(Ta){ta.reject(Ta)})}function storeMonacoInstance(ta){getState().monaco||setState({monaco:ta})}function __getMonacoInstance(){return getState(function(ta){var Ln=ta.monaco;return Ln})}var wrapperPromise=new Promise(function(ta,Ln){return setState({resolve:ta,reject:Ln})}),loader={config,init,__getMonacoInstance},le={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},v=le,ae={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Y=ae;function Me({children:ta}){return React.createElement("div",{style:Y.container},ta)}var Z=Me,$=Z;function Ee({width:ta,height:Ln,isEditorReady:Ta,loading:ja,_ref:La,className:Fa,wrapperProps:wl}){return React.createElement("section",{style:{...v.wrapper,width:ta,height:Ln},...wl},!Ta&&React.createElement($,null,ja),React.createElement("div",{ref:La,style:{...v.fullWidth,...!Ta&&v.hide},className:Fa}))}var ee=Ee,H=reactExports$1.memo(ee);function Ce(ta){reactExports$1.useEffect(ta,[])}var k=Ce;function he(ta,Ln,Ta=!0){let ja=reactExports$1.useRef(!0);reactExports$1.useEffect(ja.current||!Ta?()=>{ja.current=!1}:ta,Ln)}var l=he;function D(){}function h(ta,Ln,Ta,ja){return De(ta,ja)||be(ta,Ln,Ta,ja)}function De(ta,Ln){return ta.editor.getModel(te(ta,Ln))}function be(ta,Ln,Ta,ja){return ta.editor.createModel(Ln,Ta,ja?te(ta,ja):void 0)}function te(ta,Ln){return ta.Uri.parse(Ln)}function Oe({original:ta,modified:Ln,language:Ta,originalLanguage:ja,modifiedLanguage:La,originalModelPath:Fa,modifiedModelPath:wl,keepCurrentOriginalModel:Pl=!1,keepCurrentModifiedModel:pc=!1,theme:mc="light",loading:gc="Loading...",options:Vd={},height:Wd="100%",width:kf="100%",className:Pf,wrapperProps:Nf={},beforeMount:Eh=D,onMount:Em=D}){let[qg,Ug]=reactExports$1.useState(!1),[Bg,U_]=reactExports$1.useState(!0),B_=reactExports$1.useRef(null),VC=reactExports$1.useRef(null),tj=reactExports$1.useRef(null),aB=reactExports$1.useRef(Em),r6=reactExports$1.useRef(Eh),J2=reactExports$1.useRef(!1);k(()=>{let q5=loader.init();return q5.then(nj=>(VC.current=nj)&&U_(!1)).catch(nj=>nj?.type!=="cancelation"&&console.error("Monaco initialization: error:",nj)),()=>B_.current?Q2():q5.cancel()}),l(()=>{if(B_.current&&VC.current){let q5=B_.current.getOriginalEditor(),nj=h(VC.current,ta||"",ja||Ta||"text",Fa||"");nj!==q5.getModel()&&q5.setModel(nj)}},[Fa],qg),l(()=>{if(B_.current&&VC.current){let q5=B_.current.getModifiedEditor(),nj=h(VC.current,Ln||"",La||Ta||"text",wl||"");nj!==q5.getModel()&&q5.setModel(nj)}},[wl],qg),l(()=>{let q5=B_.current.getModifiedEditor();q5.getOption(VC.current.editor.EditorOption.readOnly)?q5.setValue(Ln||""):Ln!==q5.getValue()&&(q5.executeEdits("",[{range:q5.getModel().getFullModelRange(),text:Ln||"",forceMoveMarkers:!0}]),q5.pushUndoStop())},[Ln],qg),l(()=>{B_.current?.getModel()?.original.setValue(ta||"")},[ta],qg),l(()=>{let{original:q5,modified:nj}=B_.current.getModel();VC.current.editor.setModelLanguage(q5,ja||Ta||"text"),VC.current.editor.setModelLanguage(nj,La||Ta||"text")},[Ta,ja,La],qg),l(()=>{VC.current?.editor.setTheme(mc)},[mc],qg),l(()=>{B_.current?.updateOptions(Vd)},[Vd],qg);let V_=reactExports$1.useCallback(()=>{if(!VC.current)return;r6.current(VC.current);let q5=h(VC.current,ta||"",ja||Ta||"text",Fa||""),nj=h(VC.current,Ln||"",La||Ta||"text",wl||"");B_.current?.setModel({original:q5,modified:nj})},[Ta,Ln,La,ta,ja,Fa,wl]),sP=reactExports$1.useCallback(()=>{!J2.current&&tj.current&&(B_.current=VC.current.editor.createDiffEditor(tj.current,{automaticLayout:!0,...Vd}),V_(),VC.current?.editor.setTheme(mc),Ug(!0),J2.current=!0)},[Vd,mc,V_]);reactExports$1.useEffect(()=>{qg&&aB.current(B_.current,VC.current)},[qg]),reactExports$1.useEffect(()=>{!Bg&&!qg&&sP()},[Bg,qg,sP]);function Q2(){let q5=B_.current?.getModel();Pl||q5?.original?.dispose(),pc||q5?.modified?.dispose(),B_.current?.dispose()}return React.createElement(H,{width:kf,height:Wd,isEditorReady:qg,loading:gc,_ref:tj,className:Pf,wrapperProps:Nf})}var ie=Oe;reactExports$1.memo(ie);function He(ta){let Ln=reactExports$1.useRef();return reactExports$1.useEffect(()=>{Ln.current=ta},[ta]),Ln.current}var se=He,_=new Map;function Ve({defaultValue:ta,defaultLanguage:Ln,defaultPath:Ta,value:ja,language:La,path:Fa,theme:wl="light",line:Pl,loading:pc="Loading...",options:mc={},overrideServices:gc={},saveViewState:Vd=!0,keepCurrentModel:Wd=!1,width:kf="100%",height:Pf="100%",className:Nf,wrapperProps:Eh={},beforeMount:Em=D,onMount:qg=D,onChange:Ug,onValidate:Bg=D}){let[U_,B_]=reactExports$1.useState(!1),[VC,tj]=reactExports$1.useState(!0),aB=reactExports$1.useRef(null),r6=reactExports$1.useRef(null),J2=reactExports$1.useRef(null),V_=reactExports$1.useRef(qg),sP=reactExports$1.useRef(Em),Q2=reactExports$1.useRef(),q5=reactExports$1.useRef(ja),nj=se(Fa),n6=reactExports$1.useRef(!1),l6=reactExports$1.useRef(!1);k(()=>{let u6=loader.init();return u6.then(f6=>(aB.current=f6)&&tj(!1)).catch(f6=>f6?.type!=="cancelation"&&console.error("Monaco initialization: error:",f6)),()=>r6.current?s6():u6.cancel()}),l(()=>{let u6=h(aB.current,ta||ja||"",Ln||La||"",Fa||Ta||"");u6!==r6.current?.getModel()&&(Vd&&_.set(nj,r6.current?.saveViewState()),r6.current?.setModel(u6),Vd&&r6.current?.restoreViewState(_.get(Fa)))},[Fa],U_),l(()=>{r6.current?.updateOptions(mc)},[mc],U_),l(()=>{!r6.current||ja===void 0||(r6.current.getOption(aB.current.editor.EditorOption.readOnly)?r6.current.setValue(ja):ja!==r6.current.getValue()&&(l6.current=!0,r6.current.executeEdits("",[{range:r6.current.getModel().getFullModelRange(),text:ja,forceMoveMarkers:!0}]),r6.current.pushUndoStop(),l6.current=!1))},[ja],U_),l(()=>{let u6=r6.current?.getModel();u6&&La&&aB.current?.editor.setModelLanguage(u6,La)},[La],U_),l(()=>{Pl!==void 0&&r6.current?.revealLine(Pl)},[Pl],U_),l(()=>{aB.current?.editor.setTheme(wl)},[wl],U_);let i6=reactExports$1.useCallback(()=>{if(!(!J2.current||!aB.current)&&!n6.current){sP.current(aB.current);let u6=Fa||Ta,f6=h(aB.current,ja||ta||"",Ln||La||"",u6||"");r6.current=aB.current?.editor.create(J2.current,{model:f6,automaticLayout:!0,...mc},gc),Vd&&r6.current.restoreViewState(_.get(u6)),aB.current.editor.setTheme(wl),Pl!==void 0&&r6.current.revealLine(Pl),B_(!0),n6.current=!0}},[ta,Ln,Ta,ja,La,Fa,mc,gc,Vd,wl,Pl]);reactExports$1.useEffect(()=>{U_&&V_.current(r6.current,aB.current)},[U_]),reactExports$1.useEffect(()=>{!VC&&!U_&&i6()},[VC,U_,i6]),q5.current=ja,reactExports$1.useEffect(()=>{U_&&Ug&&(Q2.current?.dispose(),Q2.current=r6.current?.onDidChangeModelContent(u6=>{l6.current||Ug(r6.current.getValue(),u6)}))},[U_,Ug]),reactExports$1.useEffect(()=>{if(U_){let u6=aB.current.editor.onDidChangeMarkers(f6=>{let Rpe=r6.current.getModel()?.uri;if(Rpe&&f6.find(Xae=>Xae.path===Rpe.path)){let Xae=aB.current.editor.getModelMarkers({resource:Rpe});Bg?.(Xae)}});return()=>{u6?.dispose()}}return()=>{}},[U_,Bg]);function s6(){Q2.current?.dispose(),Wd?Vd&&_.set(Fa,r6.current.saveViewState()):r6.current.getModel()?.dispose(),r6.current.dispose()}return React.createElement(H,{width:kf,height:Pf,isEditorReady:U_,loading:pc,_ref:J2,className:Nf,wrapperProps:Eh})}var fe=Ve,de=reactExports$1.memo(fe),Ft=de;const CodeEditor=()=>{const ta=reactExports$1.useRef(null),{scrollToText:Ln,setScrollToText:Ta}=useAppStore(),{moduleName:ja}=useParams(),[La,Fa]=reactExports$1.useState(!1),[wl,Pl]=reactExports$1.useState(""),{getModuleCode:pc}=useModule(),mc=useMatches(),{currentTeam:gc}=useTeams(),[Vd,Wd]=reactExports$1.useState(""),[kf,Pf]=reactExports$1.useState(""),Eh=(mc.length>1?mc[mc.length-1].id:"")==="settings";reactExports$1.useEffect(()=>{if(ta.current&&Ln){const Bg=ta.current.getModel();if(!Bg)return;const U_=Bg.findMatches(Ln,!0,!1,!1,null,!0);if(U_.length>0){const B_=U_[0].range;ta.current.revealRangeInCenter(B_),ta.current.setSelection(B_),ta.current.focus()}Ta(null)}},[Ln,Ta]);const Em=Bg=>{Bg.editor.defineTheme("agentlang-editor",{base:"vs-dark",inherit:!0,rules:[],colors:{"editor.background":"#122247"}})};reactExports$1.useEffect(()=>{if(ja){const Bg=pc(ja||"");Pl(Bg||"")}},[ja,pc]);const qg=async()=>{if(Eh&&gc)try{const Bg=await readPackageJsonFromGit(gc.GitHubRepo);Wd(JSON.stringify(Bg,null,2));const U_=await readRepoFile(`/${gc.GitHubRepo}`,"config.al");Pf(U_)}catch(Bg){console.error("Failed to fetch files for editor:",Bg),Wd("// Failed to load package.json"),Pf("// Failed to load config.al")}Fa(!La)},Ug=document.getElementById(Eh?"team-settings-container":"canvas-area");return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"header-action-icon",onClick:qg,children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.code})}),Ug&&reactDomExports$1.createPortal(jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(motion.div,{animate:{width:La?"100%":"0px"},initial:{width:"0px"},transition:{duration:.5},className:"absolute top-0 right-0 bottom-0 z-998 overflow-hidden bg-primary",children:Eh?jsxRuntimeExports$1.jsxs("div",{className:"flex h-full flex-col",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex w-full",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1/2 text-white text-center py-2 bg-[#1E1E1E]",children:"package.json"}),jsxRuntimeExports$1.jsx("div",{className:"w-1/2 text-white text-center py-2 bg-[#1E1E1E]",children:"config.al"})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex h-full",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1/2 h-full",children:jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{enabled:!1}},language:"json",theme:"agentlang-editor",value:Vd,path:"package.json"})}),jsxRuntimeExports$1.jsx("div",{className:"w-1/2 h-full",children:jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{enabled:!1}},language:"agentlang",theme:"agentlang-editor",value:kf,path:"config.al"})})]})]}):jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{autohide:!0},scrollbar:{vertical:"hidden"}},beforeMount:Em,language:"agentlang",theme:"agentlang-editor",value:wl})}),La&&jsxRuntimeExports$1.jsx(motion.div,{transition:{duration:.5},initial:{left:"calc(100% - 32px)"},animate:{left:"0px"},onClick:()=>Fa(!1),className:"bg-blue hover:bg-blue-hover text-primary-font h-8 w-8 text-base rounded-full flex items-center justify-center absolute top-1/2 -translate-y-1/2 cursor-pointer z-999 duraation-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:"ph:caret-right-bold"})})]}),Ug)]})},PageLoader=({message:ta,header:Ln})=>jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col h-full",children:[Ln,jsxRuntimeExports$1.jsx("div",{className:"flex flex-1 items-center justify-center",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center gap-6",children:[jsxRuntimeExports$1.jsxs("div",{className:"relative animate-float",children:[jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-blue rounded-full flex items-center justify-center animate-pulse-glow",children:jsxRuntimeExports$1.jsx(Icon,{icon:"lucide:download-cloud",className:"w-8 h-8 text-white"})}),jsxRuntimeExports$1.jsx("div",{className:"absolute inset-0 w-16 h-16 border-4 border-blue-hover border-t-transparent rounded-full animate-spin"})]}),jsxRuntimeExports$1.jsxs("div",{className:"text-center",children:[jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-2",children:"Fetching Repository"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm",children:ta||"Please wait while we fetch the repository..."})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex space-x-1",children:[jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue rounded-full animate-bounce"}),jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue-hover rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-primary-font rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]})]})})]}),CanvasError=({message:ta})=>{const Ln=useNavigate();return jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[jsxRuntimeExports$1.jsx("div",{className:"relative ",children:jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center ",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.error,className:"w-8 h-8 text-red-400"})})}),jsxRuntimeExports$1.jsxs("div",{children:[jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-2",children:"Failed to Load Repository"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm max-w-sm",children:"There was an issue cloning or processing the repository."})]}),jsxRuntimeExports$1.jsx("button",{onClick:()=>Ln("/design/dashboard"),className:"go-back-button bg-primary hover:bg-hover text-primary-font font-medium py-2 px-6 rounded-lg border border-border-color transition-all duration-200",children:"Go to Dashboard"}),ta&&jsxRuntimeExports$1.jsxs("details",{className:"error-details bg-secondary/50 p-3 rounded-lg text-left w-full max-w-sm max-h-50 overflow-y-auto overflow-x-hidden",children:[jsxRuntimeExports$1.jsx("summary",{className:"cursor-pointer text-sm font-medium text-secondary-font hover:text-primary-font",children:"Error Details"}),jsxRuntimeExports$1.jsx("pre",{className:"p-4 bg-black/20 rounded text-xs text-red-400 whitespace-pre-wrap wrap-break-word overflow-x-hidden",children:ta})]})]})})},getIcon=ta=>{switch(ta){case"entity":case"entity-attribute":return icons.entity;case"record":case"record-attribute":return icons.record;case"relationship":case"relationship-attribute":return icons.relationship;case"event":case"event-attribute":return icons.action;case"agent":return icons.agent;default:return icons.datamodel}},getTypeLabel=ta=>{switch(ta){case"entity":return"Entity";case"record":return"Record";case"relationship":return"Relationship";case"event":return"Event";case"agent":return"Agent";case"entity-attribute":return"Entity Attribute";case"record-attribute":return"Record Attribute";case"relationship-attribute":return"Relationship Attribute";case"event-attribute":return"Event Attribute";default:return""}},Search=()=>{const{teamName:ta,githubOrg:Ln,modelName:Ta}=useParams(),ja=useNavigate(),{pathname:La}=useLocation(),Fa=La.includes("/design/marketplace/"),[wl,Pl]=reactExports$1.useState(""),[pc,mc]=reactExports$1.useState(!1),gc=reactExports$1.useMemo(()=>{const Pf=getUserModuleNames(),Nf=[];return Pf.forEach(Eh=>{getEntities(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"entity",moduleName:Eh});try{(getEntity$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"entity-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for entity ${Em}:`,qg)}}),getRecords(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"record",moduleName:Eh});try{(getRecord(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"record-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for record ${Em}:`,qg)}}),getEvents(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"event",moduleName:Eh});try{(getEvent$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"event-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for event ${Em}:`,qg)}}),getRelationships(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"relationship",moduleName:Eh});try{(getRelationship$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"relationship-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for relationship ${Em}:`,qg)}}),getAgents(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"agent",moduleName:Eh})})}),Nf},[]),Vd=reactExports$1.useDeferredValue(wl),Wd=reactExports$1.useMemo(()=>{const Pf=Vd.trim().toLowerCase();return!pc||!Pf?[]:gc.filter(Nf=>Nf.searchText.includes(Pf)).slice(0,50)},[Vd,gc,pc]),kf=Pf=>{const Nf=Pf.moduleName;let Eh=Pf.name,Em=Pf.type;if((Pf.type==="entity-attribute"||Pf.type==="record-attribute"||Pf.type==="relationship-attribute"||Pf.type==="event-attribute")&&(Eh=Pf.parentName||Pf.name,Pf.type==="entity-attribute"?Em="entity":Pf.type==="record-attribute"?Em="record":Pf.type==="relationship-attribute"?Em="relationship":Pf.type==="event-attribute"&&(Em="event")),Fa)ja(`/design/marketplace/${Ln}/${Ta}/${Nf}`);else{const qg=ta;if(Em==="entity"||Em==="record"||Em==="relationship"){const Ug=`${Nf}/${Eh}`;ja(`/design/data-model/${Ln}/${qg}/${Nf}`,{state:{focusEntityId:Ug}})}else Em==="event"?ja(`/design/workflow/${Ln}/${qg}/${Nf}`,{state:{focusEventId:Eh}}):Em==="agent"&&ja(`/design/agents/${Ln}/${qg}/${Nf}`,{state:{focusAgentId:Eh}})}Pl(""),mc(!1)};return jsxRuntimeExports$1.jsxs("div",{className:"relative w-full min-w-0",children:[jsxRuntimeExports$1.jsx("div",{className:"relative",children:jsxRuntimeExports$1.jsx("input",{type:"text",placeholder:"Search",value:wl,onChange:Pf=>Pl(Pf.target.value),onFocus:()=>mc(!0),onBlur:()=>setTimeout(()=>mc(!1),200),className:"w-full text-sm sm:text-base"})}),pc&&Wd.length>0&&jsxRuntimeExports$1.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-primary border border-border-color rounded-md shadow-lg z-50 max-h-[150px] overflow-auto scrollbar-none",children:Wd.map(Pf=>jsxRuntimeExports$1.jsxs("div",{onClick:()=>kf(Pf),className:"flex items-center gap-2 px-3 py-2 hover:bg-secondary cursor-pointer transition-colors",children:[jsxRuntimeExports$1.jsx(Icon,{icon:getIcon(Pf.type),className:"w-4 h-4 text-secondary-font"}),jsxRuntimeExports$1.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports$1.jsx("div",{className:"text-sm text-primary-font truncate",children:Pf.displayName}),jsxRuntimeExports$1.jsxs("div",{className:"text-xs text-secondary-font truncate",children:[getTypeLabel(Pf.type)," in ",Pf.moduleName]})]})]},`${Pf.moduleName}:${Pf.name}`))})]})},DesignHistoryNavigationButtons=()=>{const ta=useNavigate(),Ln=useLocation(),Ta=useNavigationType(),ja=useMatches(),La=ja[ja.length-1]?.id||"",[Fa,wl]=reactExports$1.useState(!1),[Pl,pc]=reactExports$1.useState(!1),mc=useAppStore(VC=>VC.previouslyFocusedNode),gc=useAppStore(VC=>VC.setPreviouslyFocusedNode),Vd=useAppStore(VC=>VC.focusedNodeStack),Wd=useAppStore(VC=>VC.focusedNodeForwardStack),kf=useAppStore(VC=>VC.popFocusedNode),Pf=useAppStore(VC=>VC.popFocusedForward),Nf=useAppStore(VC=>VC.currentFocusedNode),{zoomHandler:Eh,restoreInitialViewport:Em}=useZoomHandler(),{getNode:qg}=useReactFlow(),Ug=La==="security",Bg=La==="data-model"||La==="marketplace-data-model"||La==="workflow"||Ug;reactExports$1.useEffect(()=>{const VC=window.history.state&&window.history.state.idx||0,tj="rr_max_idx",aB=sessionStorage.getItem(tj);let r6=aB?parseInt(aB,10):VC;(Ta==="PUSH"||VC>r6)&&(r6=VC),sessionStorage.setItem(tj,String(r6)),wl(VC>0||Vd&&Vd.length>0),pc(VC<r6||(Wd||[]).length>0)},[Ln,Ta,Vd,Wd]);const U_=()=>{if(Fa){if(Bg)if(Nf&&Nf!==INITIAL_VIEWPORT_NODE_ID&&qg(Nf)){if(Vd&&Vd.length>0){const tj=kf();if(tj===INITIAL_VIEWPORT_NODE_ID){Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}else if(tj&&qg(tj)){Eh(tj,{openForm:!0,mode:"back"}),gc(null);return}}Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}else{if(Vd&&Vd.length>0&&Vd[Vd.length-1]===INITIAL_VIEWPORT_NODE_ID){kf(),Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}ta(-1);return}if(Vd&&Vd.length>0){const VC=kf();if(VC&&VC!==INITIAL_VIEWPORT_NODE_ID&&qg(VC)){Eh(VC,{openForm:!0,mode:"back"}),gc(null);return}else if(VC===INITIAL_VIEWPORT_NODE_ID){Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}}if(mc&&!!qg(mc)){Eh(mc,{openForm:!0}),gc(null);return}ta(-1)}},B_=()=>{if(Pl){if(Wd&&Wd.length>0){const VC=Pf();if(VC&&qg(VC)){Eh(VC,{openForm:!0,mode:"forward"}),gc(null);return}}if(mc&&!!qg(mc)){Eh(mc,{openForm:!0}),gc(null);return}ta(1)}};return jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports$1.jsx("button",{type:"button",onClick:U_,className:`header-action-icon !bg-transparent hover:!bg-hover ${Fa?"":"opacity-40 cursor-not-allowed pointer-events-none"}`,disabled:!Fa,title:Fa?"Back":"No previous page",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.back})}),jsxRuntimeExports$1.jsx("button",{type:"button",onClick:B_,className:`header-action-icon !bg-transparent hover:!bg-hover ${Pl?"":"opacity-40 cursor-not-allowed pointer-events-none"}`,disabled:!Pl,title:Pl?"Forward":"No next page",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.forward})})]})},getNestedInitialValues=(ta,Ln,Ta,ja)=>{ta.forEach((La,Fa)=>{const wl=typeof La=="object"&&La!==void 0,Pl=wl&&La.properties?.get("default"),pc=`${Ln}.${Fa}`,mc=jve$1(Fa,La,Ta);mc.isNested&&mc.nestedAttributes?getNestedInitialValues(mc.nestedAttributes,pc,mc.referencedModule,ja):Pl!==void 0?ja[pc]=Pl:(wl?La.type:String(La))==="Boolean"?ja[pc]=!1:ja[pc]=""})},getInitialValues=ta=>{const Ln={};return ta.forEach(Ta=>{const ja=Ta.attributes,La=Ta.entityName,wl=parseEntityPath(Ta.entityName)?.moduleName||null;getNestedInitialValues(ja,La,wl,Ln)}),Ln},handleSubmit=ta=>{const Ln={};Object.entries(ta).forEach(([Ta,ja])=>{const[La,Fa]=Ta.split(".",2);Ln[La]||(Ln[La]={}),Ln[La][Fa]=ja}),console.log("All config values submitted:",Ln)},parseEntityPath=ta=>{const Ln=ta.lastIndexOf("/");if(Ln<=0)return null;const Ta=ta.substring(0,Ln),ja=ta.substring(Ln+1);let La,Fa;if(ja.includes(".")){const[wl,Pl]=ja.split(".",2);La=`${Ta}.${wl}`,Fa=Pl}else La=Ta,Fa=ja;return{moduleName:La,entityName:Fa}},useConfigEntities=()=>{const{currentTeam:ta}=useTeams(),[Ln,Ta]=reactExports$1.useState([]),[ja,La]=reactExports$1.useState(!0),[Fa,wl]=reactExports$1.useState(null),Pl=ta?.GitHubRepo;return reactExports$1.useEffect(()=>{(async()=>{if(!Pl){La(!1);return}La(!0),wl(null);const mc=[];try{const Vd=(await readPackageJsonFromGit(Pl)).dependencies||{},Wd=await getDependenciesRecursive(Pl,Vd,new Set),kf=[Pl,...Wd];for(const Pf of kf)try{let Nf;if(Pf===Pl?Nf=await readPackageJsonFromGit(Pf):Nf=await readDependencyPackageJsonFromGit(Pl,Pf),Nf?.agentlang?.config&&Array.isArray(Nf.agentlang.config))for(const Eh of Nf.agentlang.config)try{const Em=parseEntityPath(Eh);if(!Em)continue;const{moduleName:qg,entityName:Ug}=Em,Bg=getEntity$1(Ug,qg);if(Bg){const U_=`${qg}.${Ug}`;mc.push({name:Pf,entityName:U_,attributes:Bg.getUserAttributes()})}}catch(Em){console.error(`Failed to get entity for ${Eh}:`,Em)}}catch(Nf){console.error(`Failed to read package.json for ${Pf}:`,Nf)}}catch(gc){console.error("Failed to fetch config entities:",gc),wl("Failed to load deployment configurations.")}finally{Ta(mc),La(!1)}})()},[Pl]),{configEntities:Ln,isLoading:ja,error:Fa}},DeploymentConfigurationForm=({closeHandler:ta})=>{const{configEntities:Ln,isLoading:Ta,error:ja}=useConfigEntities();if(Ta)return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50}),jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50}),jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50})]});if(ja)return jsxRuntimeExports$1.jsx("div",{className:"text-center py-8 text-red-500",children:ja});if(Ln.length===0)return jsxRuntimeExports$1.jsx("div",{className:"text-center py-8 text-gray-400",children:"No configuration entities found"});const La=new Map;return Ln.forEach(Fa=>{const wl=Fa.name;La.has(wl)||La.set(wl,[]);const Pl=La.get(wl);Pl&&Pl.push(Fa)}),jsxRuntimeExports$1.jsx(Formik,{initialValues:getInitialValues(Ln),onSubmit:handleSubmit,enableReinitialize:!0,children:jsxRuntimeExports$1.jsxs(Form$6,{children:[jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:Array.from(La.entries()).map(([Fa,wl])=>jsxRuntimeExports$1.jsxs("div",{className:"p-4 highlight-color rounded-md",children:[jsxRuntimeExports$1.jsx("h3",{className:"text-lg font-semibold text-primary-font mb-4",children:Fa}),jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:wl.map(Pl=>{const pc=Pl.entityName.split("."),mc=pc[pc.length-1];return jsxRuntimeExports$1.jsx(P_,{label:mc,defaultOpen:!0,className:"bg-primary! rounded-md",children:jsxRuntimeExports$1.jsx("div",{className:"space-y-4 pt-2 pl-4",children:Array.from(Pl.attributes.entries()).map(([gc,Vd])=>{const kf=parseEntityPath(Pl.entityName)?.moduleName||null,Pf=`${Pl.entityName}.${gc}`;return jsxRuntimeExports$1.jsx(MV,{attrName:gc,spec:Vd,currentModule:kf,depth:0,fieldPrefix:Pl.entityName},Pf)})})},Pl.entityName)})})]},Fa))}),jsxRuntimeExports$1.jsx(Divider,{color:"white",sx:{opacity:.2,marginTop:"1rem"}}),jsxRuntimeExports$1.jsx("div",{className:"mt-4",children:jsxRuntimeExports$1.jsx(Footer,{label:"Save",closeHandler:ta})})]})})},DeploymentConfiguration=({closeHandler:ta})=>{const{isLoading:Ln,error:Ta}=useConfigEntities(),ja=useOutsideClickHandler(ta);let La;return Ln?La=jsxRuntimeExports$1.jsx("div",{className:"text-center p-8",children:"Loading..."}):Ta?La=jsxRuntimeExports$1.jsx("div",{className:"text-center p-8 text-red-500",children:Ta}):La=jsxRuntimeExports$1.jsx(DeploymentConfigurationForm,{closeHandler:ta}),jsxRuntimeExports$1.jsx("div",{className:"modal-container",onClick:Fa=>Fa.stopPropagation(),children:jsxRuntimeExports$1.jsxs("div",{className:"modal-content w-[clamp(600px,50vw,800px)]",ref:ja,children:[jsxRuntimeExports$1.jsxs("div",{className:"modal-header",children:[jsxRuntimeExports$1.jsx("div",{className:"modal-title",children:"Deployment Configuration"}),jsxRuntimeExports$1.jsx(Icon,{icon:icons.cross,className:"cursor-pointer text-secondary-font duration-300 hover:text-maroon",onClick:ta})]}),jsxRuntimeExports$1.jsx(Divider,{color:"white",sx:{opacity:.2}}),jsxRuntimeExports$1.jsx("div",{className:"modal-body",children:La})]})})},IS_LOCAL_MODE=!0,DesignLayout=()=>{const{teamName:ta,moduleName:Ln,githubOrg:Ta}=useParams(),ja=useNavigate(),{state:La}=useLocation(),Fa=useMatches(),wl=Fa.length>1?Fa[Fa.length-1].id:"",Pl=wl.includes("marketplace"),pc=wl!=="settings",{currentTeam:mc,isEditable:gc}=useTeams(),[Vd,Wd]=reactExports$1.useState(!1),{isCloning:kf,cloneAndProcess:Pf,error:Nf,loadingMessage:Eh}=useRepositoryClone(),{setIsArchitectDrawerOpen:Em}=useAppStore();reactExports$1.useEffect(()=>{Em(!1)},[Em]),reactExports$1.useRef(null);const qg=mc?`${mc.GitHubOrg}/${mc.GitHubRepo}`:null;return reactExports$1.useEffect(()=>{!mc||La?.isNewTeam},[qg,La?.isNewTeam,Pf,ja,mc]),jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[Vd&&reactDomExports$1.createPortal(jsxRuntimeExports$1.jsx(DeploymentConfiguration,{closeHandler:()=>Wd(!1)}),document.body),jsxRuntimeExports$1.jsx("div",{className:"flex flex-col h-screen ",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[!IS_LOCAL_MODE,jsxRuntimeExports$1.jsx("div",{id:"editor",className:"flex flex-col flex-1 overflow-hidden",children:kf?jsxRuntimeExports$1.jsx(PageLoader,{message:Eh,header:jsxRuntimeExports$1.jsxs("div",{id:"dashboard-header",className:"flex justify-between gap-2 py-2 px-4 bg-transparent border-b border-border-color border-solid",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex gap-3 items-center animate-pulse",children:[jsxRuntimeExports$1.jsx("div",{className:"h-6 w-6 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-5 w-28 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-5 w-16 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-6 w-10 bg-secondary rounded"})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center animate-pulse",children:[jsxRuntimeExports$1.jsx("div",{className:"h-8 w-8 bg-secondary rounded-full"}),jsxRuntimeExports$1.jsx("div",{className:"h-8 w-8 bg-secondary rounded-full"})]})]})}):Nf?jsxRuntimeExports$1.jsx(CanvasError,{message:Nf}):jsxRuntimeExports$1.jsxs(ReactFlowProvider,{children:[jsxRuntimeExports$1.jsxs("div",{id:"dashboard-header",className:"flex justify-between gap-2 py-2 px-4 bg-transparent border-b border-border-color border-solid",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center",children:[!IS_LOCAL_MODE,jsxRuntimeExports$1.jsx("div",{className:"dashboard-model-icon text-xl!",children:jsxRuntimeExports$1.jsx(TeamOrDepIcon,{name:mc?.GitHubRepo||icons.agent})}),jsxRuntimeExports$1.jsx("h4",{children:mc?.Name}),!IS_LOCAL_MODE,!IS_LOCAL_MODE]}),gc&&jsxRuntimeExports$1.jsxs("div",{className:"flex flex-1 gap-2 items-center text-sm min-w-0 max-w-2xl",children:[jsxRuntimeExports$1.jsx(DesignHistoryNavigationButtons,{}),jsxRuntimeExports$1.jsx(Search,{})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center text-sm",children:[jsxRuntimeExports$1.jsx(CodeEditor,{}),gc&&!0&&!IS_LOCAL_MODE,!Pl&&jsxRuntimeExports$1.jsx(TooltipComponent,{text:"Settings",children:jsxRuntimeExports$1.jsx("div",{onClick:()=>ja(`/design/settings/${Ta}/${ta}/${Ln}`),className:"header-action-icon",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.setting})})})]})]}),pc?jsxRuntimeExports$1.jsxs("div",{className:" flex flex-1 overflow-hidden",children:[jsxRuntimeExports$1.jsx(DesignNavigator,{}),jsxRuntimeExports$1.jsx("div",{className:"relative w-full flex overflow-hidden",id:"canvas-area",children:jsxRuntimeExports$1.jsx(Outlet,{})})]}):jsxRuntimeExports$1.jsx(Outlet,{})]})})]})})]})};reactExports$1.createContext(void 0);var PostHogContext=reactExports$1.createContext({client:Do,bootstrap:void 0});function isDeepEqual(ta,Ln,Ta){if(Ta===void 0&&(Ta=new WeakMap),ta===Ln)return!0;if(typeof ta!="object"||ta===null||typeof Ln!="object"||Ln===null)return!1;if(Ta.has(ta)&&Ta.get(ta)===Ln)return!0;Ta.set(ta,Ln);var ja=Object.keys(ta),La=Object.keys(Ln);if(ja.length!==La.length)return!1;for(var Fa=0,wl=ja;Fa<wl.length;Fa++){var Pl=wl[Fa];if(!La.includes(Pl)||!isDeepEqual(ta[Pl],Ln[Pl],Ta))return!1}return!0}function PostHogProvider(ta){var Ln,Ta,ja=ta.children,La=ta.client,Fa=ta.apiKey,wl=ta.options,Pl=reactExports$1.useRef(null),pc=reactExports$1.useMemo(function(){return La?(Fa&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),wl&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),La):(Fa||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),Do)},[La,Fa,JSON.stringify(wl)]);return reactExports$1.useEffect(function(){if(!La){var mc=Pl.current;mc?(Fa!==mc.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),wl&&!isDeepEqual(wl,mc.options)&&Do.set_config(wl),Pl.current={apiKey:Fa,options:wl??{}}):(Do.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Do.init(Fa,wl),Pl.current={apiKey:Fa,options:wl??{}})}},[La,Fa,JSON.stringify(wl)]),React.createElement(PostHogContext.Provider,{value:{client:pc,bootstrap:(Ln=wl?.bootstrap)!==null&&Ln!==void 0?Ln:(Ta=La?.config)===null||Ta===void 0?void 0:Ta.bootstrap}},ja)}var isFunction=function(ta){return typeof ta=="function"},extendStatics=function(ta,Ln){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Ta,ja){Ta.__proto__=ja}||function(Ta,ja){for(var La in ja)Object.prototype.hasOwnProperty.call(ja,La)&&(Ta[La]=ja[La])},extendStatics(ta,Ln)};function __extends(ta,Ln){if(typeof Ln!="function"&&Ln!==null)throw new TypeError("Class extends value "+String(Ln)+" is not a constructor or null");extendStatics(ta,Ln);function Ta(){this.constructor=ta}ta.prototype=Ln===null?Object.create(Ln):(Ta.prototype=Ln.prototype,new Ta)}typeof SuppressedError=="function"&&SuppressedError;var INITIAL_STATE={componentStack:null,exceptionEvent:null,error:null},__POSTHOG_ERROR_MESSAGES={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(ta){__extends(Ln,ta);function Ln(Ta){var ja=ta.call(this,Ta)||this;return ja.state=INITIAL_STATE,ja}return Ln.prototype.componentDidCatch=function(Ta,ja){var La=this.props.additionalProperties,Fa;isFunction(La)?Fa=La(Ta):typeof La=="object"&&(Fa=La);var wl=this.context.client,Pl=wl.captureException(Ta,Fa),pc=ja.componentStack;this.setState({error:Ta,componentStack:pc,exceptionEvent:Pl})},Ln.prototype.render=function(){var Ta=this.props,ja=Ta.children,La=Ta.fallback,Fa=this.state;if(Fa.componentStack==null)return isFunction(ja)?ja():ja;var wl=isFunction(La)?React.createElement(La,{error:Fa.error,componentStack:Fa.componentStack,exceptionEvent:Fa.exceptionEvent}):La;return React.isValidElement(wl)?wl:(console.warn(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK),React.createElement(React.Fragment,null))},Ln.contextType=PostHogContext,Ln})(React.Component);const validationSchema=create$3().shape({title:create$6().required("Title is required")}),Header=({saveUISpec:ta,authType:Ln})=>{const{teamName:Ta}=useParams(),ja=Qn$1();return ja?jsxRuntimeExports$1.jsx(Formik,{initialValues:{...ja[Ln].header,title:ja[Ln].header.title||Ta},onSubmit:La=>{const Fa={...ja,[Ln]:{...ja[Ln]||{},header:La}};ta&&ta(Fa,"Update theme")},validationSchema,children:jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[jsxRuntimeExports$1.jsx(lAe,{name:"title",placeholder:"Welcome Message",isFloating:!1}),jsxRuntimeExports$1.jsx(lAe,{name:"subTitle",placeholder:"Subtitle",isFloating:!1}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}):null},FormSettings$1=({saveUISpec:ta,authType:Ln})=>{const Ta=Qn$1();return Ta?jsxRuntimeExports$1.jsx(Formik,{initialValues:Ta[Ln].form.placeholder,onSubmit:ja=>{const La={...Ta,[Ln]:{...Ta[Ln],form:{...Ta[Ln].form,placeholder:ja}}};ta&&ta(La,"Update theme")},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[Object.keys(Ta[Ln].form.placeholder).map(ja=>jsxRuntimeExports$1.jsx(lAe,{name:ja,placeholder:`${Ft$5(ja)} Placeholder`,isFloating:!1},ja)),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}):null},socialNetworks=["git","google","microsoft","linkedin"],SocialNetworks=({saveUISpec:ta,authType:Ln})=>{const Ta=Qn$1();return Ta?jsxRuntimeExports$1.jsx(Formik,{initialValues:Ta[Ln].socialNetworks,onSubmit:ja=>{const La={...Ta,[Ln]:{...Ta[Ln],socialNetworks:ja}};ta&&ta(La,"Update theme")},children:ja=>{const{values:La,setValues:Fa}=ja,wl=La.icons,Pl=socialNetworks.every(pc=>wl.includes(pc));return jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[jsxRuntimeExports$1.jsx(lAe,{name:"label",placeholder:"Label",isFloating:!1}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-end cursor-pointer",onClick:()=>{Fa({...La,icons:Pl?[]:socialNetworks})},children:[jsxRuntimeExports$1.jsx(Icon,{icon:Pl?Ot$2.checkboxSelected:Ot$2.checkbox,className:classNames(["text-xl",Pl?"text-checkbox-selected":"text-secondary-font"])}),"Show social networks"]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),socialNetworks.map(pc=>{const mc=wl.includes(pc);return jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-end cursor-pointer",onClick:()=>{Fa({...La,icons:mc?La.icons.filter(gc=>gc!==pc):[...La.icons,pc]})},children:[jsxRuntimeExports$1.jsx(Icon,{icon:mc?Ot$2.checkboxSelected:Ot$2.checkbox,className:classNames(["text-xl",mc?"text-checkbox-selected":"text-secondary-font"])}),Ft$5(pc)]},pc)}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}}):null},Auth=({saveUISpec:ta,authType:Ln})=>jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(P_,{label:"Header",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(Header,{saveUISpec:ta,authType:Ln})}),jsxRuntimeExports$1.jsx(P_,{label:"Social Networks",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(SocialNetworks,{saveUISpec:ta,authType:Ln})}),jsxRuntimeExports$1.jsx(P_,{label:"Form",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(FormSettings$1,{saveUISpec:ta,authType:Ln})})]}),getTopLevelAttributes=(ta,Ln)=>ta.order?.length>0?ta.order:Array.from(Ln.keys()),initializeNestedFormSchema=ta=>{const Ln={Form:{},order:[]};return ta.forEach((Ta,ja)=>{const La=Ta.properties?.get("optional")===!0,wl=typeof Ta=="object"&&Ta!==void 0?Ta.type:String(Ta),Pl=getInputType(wl);Ln.Form[ja]={inputType:Pl,required:!La,displayOptions:{label:Ft$5(ja),placeholder:`Enter ${ja}`}},Ln.order.push(ja)}),Ln},ensureCompleteNestedFormSchema=(ta,Ln)=>{const Ta=ta||{Form:{},order:[]};return Ln.forEach((ja,La)=>{if(!Ta.Form[La]){const Fa=ja.properties?.get("optional")===!0,Pl=typeof ja=="object"&&ja!==void 0?ja.type:String(ja),pc=getInputType(Pl);Ta.Form[La]={inputType:pc,required:!Fa,displayOptions:{label:Ft$5(La),placeholder:`Enter ${La}`}},Ta.order.includes(La)||Ta.order.push(La)}}),Ta},NestedFields=({entityName:ta,attrName:Ln,nestedFormSchema:Ta,nestedAttributes:ja,referencedModule:La,updateNestedFormSchema:Fa,depth:wl})=>{const[Pl,pc]=reactExports$1.useState(null);let mc=Ta;!mc&&ja&&(mc=initializeNestedFormSchema(ja),Fa(mc));const gc=ensureCompleteNestedFormSchema(mc,ja),Vd=gc.order?.length>0?gc.order.filter(Eh=>gc.Form[Eh]):Array.from(ja.keys()),Wd=[],kf=[];Vd.forEach(Eh=>{gc.Form[Eh]?.required??!1?Wd.push(Eh):kf.push(Eh)});const Pf=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),Nf=Eh=>{const{active:Em,over:qg}=Eh;if(qg&&Em.id!==qg.id){const Ug=tj=>{const aB=tj;return aB.includes(".")&&aB.split(".").pop()||aB},Bg=Ug(Em.id),U_=Ug(qg.id),B_=gc.order.indexOf(Bg),VC=gc.order.indexOf(U_);if(B_!==-1&&VC!==-1){const tj=[...gc.order],[aB]=tj.splice(B_,1);tj.splice(VC,0,aB);const r6={...gc,order:tj};Fa(r6)}}pc(null)};return jsxRuntimeExports$1.jsx(DndContext,{sensors:Pf,collisionDetection:closestCenter,onDragCancel:()=>pc(null),onDragStart:Eh=>{pc(Eh.active.id)},onDragEnd:Nf,children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container pt-2",children:[jsxRuntimeExports$1.jsxs(SortableContext,{items:Vd.map(Eh=>Ln?`${Ln}.${Eh}`:Eh),strategy:verticalListSortingStrategy,children:[Wd.length>0&&jsxRuntimeExports$1.jsx("div",{className:"flex flex-col gap-2",children:Wd.map(Eh=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Eh,formSchema:gc,updateFormSchema:Fa,isRequired:!0,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1},Eh))}),kf.length>0&&jsxRuntimeExports$1.jsx("div",{children:kf.map(Eh=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Eh,formSchema:gc,updateFormSchema:Fa,isRequired:!1,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1},Eh))})]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:Pl?(()=>{const Em=(Bg=>Bg.includes(".")&&Bg.split(".").pop()||Bg)(Pl),Ug=gc.Form[Em]?.required??!1;return jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Fa,isRequired:Ug,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1})})():null})]})})},AttributeField$1=({entityName:ta,attrName:Ln,formSchema:Ta,updateFormSchema:ja,isRequired:La=!0,nestedPath:Fa,nestedAttributes:wl,referencedModule:Pl,depth:pc=0})=>{const[mc,gc]=reactExports$1.useState(!1),Vd=Ta.Form[Ln]?.isHidden||!1,{attributes:Wd,listeners:kf,setNodeRef:Pf,transform:Nf,transition:Eh,isDragging:Em}=useSortable({id:Fa?`${Fa}.${Ln}`:Ln}),qg=(()=>{try{const[sP,Q2]=ta.split("/");return getEntity$1(Q2,sP)?.getUserAttributes()||new Map}catch(sP){return console.error("Error getting entity schema:",sP),new Map}})(),Bg=(wl||qg).get(Ln),U_=Bg&&typeof Bg=="object"?Bg.type:String(Bg||"text"),B_=Ta.Form[Ln]?.inputType||getInputType(U_),VC=Pl||ta.split("/")[0],tj=Bg?jve$1(Ln,Bg,VC):{isNested:!1,nestedAttributes:null,referencedModule:null},aB=tj.isNested&&tj.nestedAttributes!==null,r6=Ta.Form[Ln]?.nestedForm,J2=[{label:"Text",value:"text"},{label:"Number",value:"number"},{label:"Email",value:"email"},{label:"Password",value:"password"},{label:"Date",value:"date"},{label:"Checkbox",value:"checkbox"},{label:"Select",value:"select"},...aB?[{label:"Nested Form",value:"nested"}]:[]],V_=sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],nestedForm:sP}}};ja(Q2)};return jsxRuntimeExports$1.jsxs("div",{ref:Pf,style:{opacity:Em?.5:1,transform:CSS$1.Translate.toString(Nf),transition:Eh},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>gc(!mc),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[jsxRuntimeExports$1.jsx("span",{...Wd,...kf,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsxs("span",{children:[Ft$5(Ln),aB&&jsxRuntimeExports$1.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:["(",tj.type==="entity"?"Entity":tj.type==="record"?"Record":"OneOf",": ",tj.referencedName,")"]})]})]}),!La&&jsxRuntimeExports$1.jsx("div",{onClick:sP=>sP.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!Vd,onChangeHandler:sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],isHidden:!sP}}};ja(Q2)}})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:mc&&!aB&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx("div",{className:"setting-toggle-body",children:jsxRuntimeExports$1.jsxs("div",{className:"mb-4",children:[jsxRuntimeExports$1.jsx("label",{className:"text-sm mb-2 block",children:"Input Type"}),jsxRuntimeExports$1.jsx(FV,{value:B_,options:J2,onChange:sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],inputType:sP}}};ja(Q2)}})]})})})}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:mc&&aB&&tj.nestedAttributes&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx("div",{children:jsxRuntimeExports$1.jsx(NestedFields,{entityName:ta,attrName:Ln,nestedFormSchema:r6,nestedAttributes:tj.nestedAttributes,referencedModule:tj.referencedModule,updateNestedFormSchema:V_,depth:pc})})})})]})},FormSettings=({entityName:ta,saveUISpec:Ln})=>{const[Ta,ja]=reactExports$1.useState(null),[La,Fa]=ta.split("/"),Pl=getEntity$1(Fa,La)?.getUserAttributes()||new Map,pc=Qn$1(),mc=`${ta}.ui.form`,gc=pc[mc],Wd=getTopLevelAttributes(gc,Pl).filter(Em=>gc.Form[Em]).sort((Em,qg)=>{const Ug=gc.order.indexOf(Em),Bg=gc.order.indexOf(qg);return Ug===-1?1:Bg===-1?-1:Ug-Bg}),kf=[],Pf=[];Wd.forEach(Em=>{gc.Form[Em]?.required??!1?kf.push(Em):Pf.push(Em)});const Nf=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),Eh=Em=>{if(Ln){const qg=`${ta}.ui.form`,Ug={...pc,[qg]:Em};Ln(Ug,"Update form settings")}};return jsxRuntimeExports$1.jsx(DndContext,{sensors:Nf,collisionDetection:closestCenter,onDragCancel:()=>ja(null),onDragStart:Em=>{ja(Em.active.id)},onDragEnd:Em=>{const{active:qg,over:Ug}=Em;if(Ug&&qg.id!==Ug.id){const Bg=gc.order.indexOf(qg.id),U_=gc.order.indexOf(Ug.id),B_=[...gc.order],[VC]=B_.splice(Bg,1);B_.splice(U_,0,VC);const tj={...gc,order:B_};console.log("newFormSchema",tj),Eh(tj)}ja(null)},children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsxs(SortableContext,{items:Wd,strategy:verticalListSortingStrategy,children:[kf.length>0&&jsxRuntimeExports$1.jsx(P_,{label:"Required",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:kf.map(Em=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Eh,isRequired:!0},Em))})}),Pf.length>0&&jsxRuntimeExports$1.jsx(P_,{label:"Optional",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:Pf.map(Em=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Eh,isRequired:!1},Em))})})]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:Ta?jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Ta,formSchema:gc,updateFormSchema:Eh}):null})]})})},HeaderSettings=({headerSchema:ta,updateHeaderSchema:Ln})=>{if(Array.isArray(ta)||typeof ta!="object"||ta===null)return null;const Ta=ta.view,{showBreadcrumbs:ja}=Ta?.Heading||{};return jsxRuntimeExports$1.jsx(P_,{label:"Header",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:jsxRuntimeExports$1.jsx(Formik,{initialValues:{showBreadcrumbs:ja??!1},onSubmit:La=>{const Fa={...Ta.Heading,...La},wl={...ta,view:{...Ta,Heading:Fa}};Ln(wl)},children:({values:La,setFieldValue:Fa})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Show Breadcrumbs"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:La.showBreadcrumbs,onChangeHandler:wl=>Fa("showBreadcrumbs",wl)})]})}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})};function capitalizeFirstLetter(ta){return ta&&ta.charAt(0).toUpperCase()+ta.slice(1)}const DateOptionMenu=()=>{const[ta,,Ln]=useField({name:"dateFormat"}),Ta=ta.value;return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Date Format"}),jsxRuntimeExports$1.jsx(FV,{value:Ta||"MM/DD/YY",options:[{label:"DD/MM/YY",value:"DD/MM/YY"},{label:"MM/DD/YY",value:"MM/DD/YY"}],onChange:ja=>Ln.setValue(ja)})]})},FontWeightMenu$1=()=>{const[ta,,Ln]=useField({name:"fontWeight"}),Ta=ta.value||"normal";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Weight"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"Normal",value:"normal"},{label:"Bold",value:"bold"},{label:"Bolder",value:"bolder"},{label:"Lighter",value:"lighter"}],onChange:ja=>Ln.setValue(ja)})]})},FontStyleMenu$1=()=>{const[ta,,Ln]=useField({name:"fontStyle"}),Ta=ta.value||"normal";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Style"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"Normal",value:"normal"},{label:"Italic",value:"italic"},{label:"Oblique",value:"oblique"},{label:"Lighter",value:"lighter"}],onChange:ja=>Ln.setValue(ja)})]})},TextDecorationMenu$1=()=>{const[ta,,Ln]=useField({name:"textDecorationLine"}),Ta=ta.value||"none";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Text Decoration"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"None",value:"none"},{label:"Underline",value:"underline"},{label:"Overline",value:"overline"},{label:"Line Through",value:"line-through"}],onChange:ja=>Ln.setValue(ja)})]})},ColumnField=({entityName:ta,attributeName:Ln,uiAttributeSchema:Ta={},onFieldUpdate:ja,onAttributeUpdate:La,disabled:Fa=!1})=>{const[wl,Pl]=reactExports$1.useState(!1),{attributes:pc,listeners:mc,setNodeRef:gc,transform:Vd,transition:Wd,isDragging:kf}=useSortable({id:Ln,disabled:Fa}),[Pf,Nf]=ta.split("/"),qg=getEntity$1(Nf,Pf)?.getUserAttributes()?.get(Ln),Ug=typeof qg=="object"?qg.type:String(qg),Bg=()=>{if(Object.keys(Ta).length===0){const U_={colSpan:1,fontWeight:"normal",fontStyle:"normal",textDecorationLine:"none"};switch(Ug){case"DateTime":return{...U_,dateFormat:"MM/DD/YY"};case"Float":case"Decimal":return{...U_,precision:2};default:return U_}}return Ta};return jsxRuntimeExports$1.jsxs("div",{ref:gc,style:{opacity:kf?.5:1,transform:CSS$1.Translate.toString(Vd),transition:Wd},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>Pl(!wl),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[!Fa&&jsxRuntimeExports$1.jsx("span",{...pc,...mc,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("span",{children:capitalizeFirstLetter(Ln)})]}),ja&&jsxRuntimeExports$1.jsx("div",{onClick:U_=>U_.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!Fa,onChangeHandler:ja})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:wl&&!Fa&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx(Formik,{initialValues:Bg(),validate:U_=>{const B_={};return U_.colSpan||(B_.colSpan="Col span is required"),["Float","Decimal"].includes(Ug)&&!U_.precision&&(B_.precision="Precision is required"),B_},onSubmit:U_=>{La&&La(Ln,U_)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-toggle-body",style:{height:"max-content"},children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Col Span"}),jsxRuntimeExports$1.jsx(Field,{type:"number",step:"1",placeholder:"ColSpan",name:"colSpan",className:"form-input"}),jsxRuntimeExports$1.jsx(ErrorMessage,{name:"colSpan",children:U_=>jsxRuntimeExports$1.jsxs("div",{className:"error-message",children:[jsxRuntimeExports$1.jsx(Icon,{icon:"ph:warning-bold"}),U_]})})]}),Ug==="DateTime"&&jsxRuntimeExports$1.jsx(DateOptionMenu,{}),["Float","Decimal"].includes(Ug)&&jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Precision"}),jsxRuntimeExports$1.jsx(Field,{type:"number",step:"1",placeholder:"Precision",name:"precision",className:"form-input"}),jsxRuntimeExports$1.jsx(ErrorMessage,{name:"precision",children:U_=>jsxRuntimeExports$1.jsxs("div",{className:"error-message",children:[jsxRuntimeExports$1.jsx(Icon,{icon:"ph:warning-bold"}),U_]})})]}),jsxRuntimeExports$1.jsx(FontWeightMenu$1,{}),jsxRuntimeExports$1.jsx(FontStyleMenu$1,{}),jsxRuntimeExports$1.jsx(TextDecorationMenu$1,{}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})]})},FieldSettings$1=({entityName:ta,collectionSchema:Ln,onFieldUpdate:Ta,onAttributeUpdate:ja})=>{const[La,Fa]=reactExports$1.useState(null),[wl,Pl]=ta.split("/"),mc=getEntity$1(Pl,wl)?.getUserAttributes(),gc=Array.from(mc?.keys()||[]),Vd=Object.keys(Ln)[0],Wd=Ln[Vd],kf=Wd?.fields,Pf=Array.isArray(kf)?kf:[],Nf=gc.filter(Em=>!Pf.includes(Em)),Eh=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates}));return jsxRuntimeExports$1.jsx(DndContext,{sensors:Eh,collisionDetection:closestCenter,onDragCancel:()=>Fa(null),onDragStart:Em=>{Fa(Em.active.id)},onDragEnd:Em=>{const{active:qg,over:Ug}=Em;if(Ug&&qg.id!==Ug.id){const Bg=Pf.indexOf(qg.id),U_=Pf.indexOf(Ug.id),B_=arrayMove(Pf,Bg,U_);Ta(B_)}Fa(null)},children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(SortableContext,{items:Pf,strategy:verticalListSortingStrategy,children:Pf.map(Em=>jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:Em,uiAttributeSchema:Wd[Em]||{},onFieldUpdate:qg=>{qg||Ta(Pf.filter(Ug=>Ug!==Em))},onAttributeUpdate:ja,disabled:!1},Em))}),Nf.length>0&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),Nf.map(Em=>jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:Em,onFieldUpdate:qg=>{qg&&Ta([...Pf,Em])},onAttributeUpdate:ja,disabled:!0},Em))]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:La?jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:La}):null})]})})},CreateButtonSettings=({actionSchema:ta,updateActionSchema:Ln})=>jsxRuntimeExports$1.jsx(P_,{label:"Create Button",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:jsxRuntimeExports$1.jsx(Formik,{initialValues:{text:ta?.create?.text||"",icon:ta?.create?.icon||"mdi:plus"},onSubmit:Ta=>{Ln({create:{...ta.create,...Ta}})},children:({values:Ta,setFieldValue:ja})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Button Text"}),jsxRuntimeExports$1.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports$1.jsx(lxe,{icon:Ta.icon,onIconChange:La=>ja("icon",La),children:jsxRuntimeExports$1.jsx("button",{type:"button",className:"w-8 h-8 bg-secondary border border-transparent hover:border-white/40 rounded-md flex items-center justify-center cursor-pointer transition-all duration-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:Ta.icon,width:"16",height:"16"})})}),jsxRuntimeExports$1.jsx(Field,{type:"text",placeholder:"Button Text",name:"text",className:"form-input"})]})]}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})}),EntityCollectionSettings=({entityName:ta,bodySchema:Ln,updateBodySchema:Ta})=>{if(Array.isArray(Ln)||typeof Ln!="object"||Ln===null)return null;const ja=Ln.view,La=Object.keys(ja)[0],{showGlobalFilter:Fa,showColumnFilter:wl}=Object.values(ja)[0],Pl=pc=>{const mc=ja[La];Ta({...Ln,view:{[pc]:mc}})};return jsxRuntimeExports$1.jsx(P_,{label:"Collection",defaultOpen:!0,children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-options",children:[jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-option","data-selected":La==="Table",onClick:()=>Pl("Table"),children:[jsxRuntimeExports$1.jsx(Icon,{icon:"tabler:table",height:"20",width:"20"}),"Table"]}),jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-option","data-selected":La==="Cards",onClick:()=>Pl("Cards"),children:[jsxRuntimeExports$1.jsx(Icon,{icon:"mdi:cards-outline",height:"20",width:"20"}),"Cards"]})]}),jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Global Filtering"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:Fa||!1,onChangeHandler:pc=>{Ta({...Ln,view:{[La]:{...ja[La],showGlobalFilter:pc}}})}})]})}),jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Column Filtering"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:wl||!1,onChangeHandler:pc=>{Ta({...Ln,view:{[La]:{...ja[La],showColumnFilter:pc}}})}})]})})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(FieldSettings$1,{entityName:ta,collectionSchema:ja,onFieldUpdate:pc=>{const mc=La;Ta({...Ln,view:{[mc]:{...ja[mc],fields:pc}}})},onAttributeUpdate:(pc,mc)=>{const gc=La;Ta({...Ln,view:{[gc]:{...ja[gc],[pc]:mc}}})}})]})})},CollectionViewSettings=({entityName:ta,saveUISpec:Ln,showHeader:Ta=!0})=>{const ja=Qn$1(),{onEntityDetailsChange:La}=useEntityDetailsChange(Ln),Fa=`${ta}.ui.dashboard`,wl=ja?.[Fa],Pl=ja?.[ta],pc=wl?.find(Pf=>Pf.includes(".header")),mc=pc?ja?.[pc]:void 0,gc=wl?.find(Pf=>Pf.includes(".body")),Vd=gc?ja?.[gc]:void 0,Wd=Pf=>{if(Ln&&pc){const Nf={...ja,[`${pc}.header`]:Pf};Ln(Nf,"Update dashboard header settings")}},kf=Pf=>{if(Ln){const Nf={...ja,[`${gc}.body`]:Pf};Ln(Nf,"Update dashboard body settings")}};return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[mc&&Ta&&jsxRuntimeExports$1.jsx(HeaderSettings,{headerSchema:mc,updateHeaderSchema:Wd}),jsxRuntimeExports$1.jsx(_Ae,{onEntityDetailsChange:Pf=>La(ta,Pf),initialDetails:Pl}),Vd&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(CreateButtonSettings,{actionSchema:Vd.actions||{},updateActionSchema:Pf=>{const Nf={...Vd,actions:Pf};kf(Nf)}}),jsxRuntimeExports$1.jsx(EntityCollectionSettings,{entityName:ta,bodySchema:Vd,updateBodySchema:kf})]})]})},FontWeightMenu=()=>{const[ta,,Ln]=useField({name:"fontWeight"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Weight"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"normal",options:["normal","bold","bolder","lighter"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},FontStyleMenu=()=>{const[ta,,Ln]=useField({name:"fontStyle"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Style"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"normal",options:["normal","italic","oblique"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},TextDecorationMenu=()=>{const[ta,,Ln]=useField({name:"textDecorationLine"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Text Decoration"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"none",options:["none","underline","overline","line-through"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},ButtonSettings=({buttonType:ta,buttonSchema:Ln,updateButtonSchema:Ta,entityName:ja})=>{const La=ja.split("/")[1],Fa={text:Ln?.text||ta,icon:Ln?.icon||(ta==="Edit"?"mdi:pencil":"mdi:delete"),style:Ln?.style||(ta==="Edit"?"secondary":"danger")};return jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx("div",{className:"font-bold",children:`${ta} Button`}),jsxRuntimeExports$1.jsx(Formik,{initialValues:Fa,onSubmit:wl=>{const Pl={...Ln||{type:"button",actionType:ta==="Edit"?"navigation":"modal",action:`${La}/${ta.toLowerCase()}`},...wl};Ta(Pl)},enableReinitialize:!0,children:({values:wl,setFieldValue:Pl})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsx("div",{className:"form-item",children:jsxRuntimeExports$1.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports$1.jsx(lxe,{icon:wl.icon,onIconChange:pc=>Pl("icon",pc),children:jsxRuntimeExports$1.jsx("button",{type:"button",className:"w-8 h-8 bg-secondary border border-transparent hover:border-white/40 rounded-md flex items-center justify-center cursor-pointer transition-all duration-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:wl.icon,width:"16",height:"16",className:"text-white"})})}),jsxRuntimeExports$1.jsx(Field,{type:"text",name:"text",placeholder:"Button Text",className:"form-input flex-1"})]})}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})]})},AttributeField=({attributeName:ta,uiAttributeSchema:Ln={},onFieldUpdate:Ta,onAttributeUpdate:ja,disabled:La=!1})=>{const[Fa,wl]=reactExports$1.useState(!1),{attributes:Pl,listeners:pc,setNodeRef:mc,transform:gc,transition:Vd,isDragging:Wd}=useSortable({id:ta,disabled:La});return jsxRuntimeExports$1.jsxs("div",{ref:mc,style:{opacity:Wd?.5:1,transform:CSS$1.Translate.toString(gc),transition:Vd},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>wl(!Fa),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[!La&&jsxRuntimeExports$1.jsx("span",{...Pl,...pc,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("span",{children:Ft$5(ta)})]}),Ta&&jsxRuntimeExports$1.jsx("div",{onClick:kf=>kf.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!La,onChangeHandler:Ta})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:Fa&&!La&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx(Formik,{initialValues:Ln,onSubmit:kf=>ja?.(ta,kf),children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-toggle-body",style:{height:"max-content"},children:[jsxRuntimeExports$1.jsx(FontWeightMenu,{}),jsxRuntimeExports$1.jsx(FontStyleMenu,{}),jsxRuntimeExports$1.jsx(TextDecorationMenu,{}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})]})},FieldSettings=({entityName:ta,summarySchema:Ln,onFieldUpdate:Ta,onAttributeUpdate:ja})=>{const[La,Fa]=reactExports$1.useState(null),[wl,Pl]=ta.split("/"),pc=getEntity$1(Pl,wl),mc=Array.from(pc?.getUserAttributes().keys()||[]),gc=Ln.fields||[],Vd=mc.filter(kf=>!gc.includes(kf)),Wd=useSensors(useSensor(PointerSensor),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates}));return jsxRuntimeExports$1.jsx(DndContext,{sensors:Wd,collisionDetection:closestCenter,onDragStart:kf=>Fa(kf.active.id),onDragEnd:kf=>{const{active:Pf,over:Nf}=kf;if(Nf&&Pf.id!==Nf.id){const Eh=gc.indexOf(Pf.id),Em=gc.indexOf(Nf.id);Ta(arrayMove(gc,Eh,Em))}Fa(null)},onDragCancel:()=>Fa(null),children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(SortableContext,{items:gc,strategy:verticalListSortingStrategy,children:gc.map(kf=>jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:kf,uiAttributeSchema:Ln[kf]||{},onFieldUpdate:Pf=>!Pf&&Ta(gc.filter(Nf=>Nf!==kf)),onAttributeUpdate:ja},kf))}),Vd.length>0&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),Vd.map(kf=>jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:kf,onFieldUpdate:Pf=>Pf&&Ta([...gc,kf]),onAttributeUpdate:ja,disabled:!0},kf))]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:La?jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:La}):null})]})})},InstanceSummarySettings=({entityName:ta,summaryKey:Ln,saveUISpec:Ta})=>{const ja=Qn$1(),La=ja?.[Ln]||{view:{Card:{}}},Fa=La.view.Card,wl=La.actions,Pl=mc=>{if(Ta){const gc={...ja,[Ln]:{...La,actions:mc}};Ta(gc,`Update ${ta} instance summary actions`)}},pc=mc=>{if(Ta){const gc={...ja,[Ln]:{...La,view:{...La.view,Card:mc}}};Ta(gc,`Update ${ta} instance summary`)}};return jsxRuntimeExports$1.jsx(P_,{label:"Instance Summary",defaultOpen:!0,children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports$1.jsx(Formik,{initialValues:{layout:Fa.layout||"grid",columns:Fa.columns||2},onSubmit:mc=>{pc({...Fa,...mc})},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container !gap-3",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(ButtonSettings,{buttonType:"Edit",buttonSchema:wl?.edit,updateButtonSchema:mc=>Pl({...wl,edit:mc}),entityName:ta}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(ButtonSettings,{buttonType:"Delete",buttonSchema:wl?.delete,updateButtonSchema:mc=>Pl({...wl,delete:mc}),entityName:ta})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(SU,{fieldName:"layout",placeholder:"Layout",options:[{label:"Grid",value:"grid"},{label:"List",value:"list"}]}),jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Columns"}),jsxRuntimeExports$1.jsx(Field,{type:"number",name:"columns",className:"form-input"})]}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save Layout"})]})}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(FieldSettings,{entityName:ta,summarySchema:Fa,onFieldUpdate:mc=>pc({...Fa,fields:mc}),onAttributeUpdate:(mc,gc)=>{pc({...Fa,[mc]:gc})}})]})})},InstanceViewSettings=({entityName:ta,saveUISpec:Ln})=>{const Ta=Qn$1(),ja=`${ta}.ui.instance`,La=Ta?.[ja],Fa=w6();return La?jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:La.map(wl=>{const Pl=Ta?.[wl];if(!Pl||Array.isArray(Pl))return null;const pc=Pl.view,mc=Object.keys(pc)[0],gc=Fa===wl;if(mc==="Heading")return jsxRuntimeExports$1.jsx(HeaderSettings,{headerSchema:Pl,isTitleRequired:!0,updateHeaderSchema:Wd=>{if(Ln){const kf={...Ta,[wl]:Wd};Ln(kf,"Update instance header settings")}}},wl);if(mc==="Card"&&gc)return jsxRuntimeExports$1.jsx(InstanceSummarySettings,{entityName:ta,summaryKey:wl,saveUISpec:Ln},wl);if((mc==="Table"||mc==="Cards")&&gc){const Wd=wl.match(/^(.*?)\.ui\./),kf=Wd?Wd[1]:"";return jsxRuntimeExports$1.jsx(CollectionViewSettings,{entityName:kf,saveUISpec:Ln,showHeader:!1},wl)}return null})}):jsxRuntimeExports$1.jsx("div",{children:"No instance view settings found for this entity."})};function SortableEntityItem({entity:ta,index:Ln,onVisibilityChange:Ta,uiSpec:ja,onEntityDetailsChange:La}){const[Fa,wl]=reactExports$1.useState(!1),Pl=ja?.[ta.name],{attributes:pc,listeners:mc,setNodeRef:gc,transform:Vd,transition:Wd,isDragging:kf}=useSortable({id:ta.name}),Pf={transform:CSS$1.Transform.toString(Vd),transition:Wd,opacity:kf?.5:1};return jsxRuntimeExports$1.jsxs("div",{ref:gc,style:Pf,className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header flex items-center justify-between",onClick:()=>wl(!Fa),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle flex items-center gap-2 flex-1 min-w-0",children:[jsxRuntimeExports$1.jsx("div",{...pc,...mc,className:"drag-handle flex-shrink-0",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("div",{className:"min-w-0 flex-1",children:jsxRuntimeExports$1.jsx("p",{className:"font-medium text-font truncate",children:Pl?.displayName||`${ta.name.split("/")[1]}s`})})]}),jsxRuntimeExports$1.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:jsxRuntimeExports$1.jsx("div",{className:"flex-shrink-0",onClick:Nf=>Nf.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:ta.visible,onChangeHandler:Nf=>Ta(Ln,Nf)})})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:Fa&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:jsxRuntimeExports$1.jsx("div",{className:"mt-2",children:jsxRuntimeExports$1.jsx(_Ae,{onEntityDetailsChange:Nf=>La(ta.name,Nf),initialDetails:Pl})})})})]})}const DashboardCustomizationPanel=({schema:ta,uiSpec:Ln,onSave:Ta,saveUISpec:ja})=>{const[La,Fa]=reactExports$1.useState(ta),{onEntityDetailsChange:wl}=useEntityDetailsChange(ja),Pl=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),pc=Wd=>{const kf={...La,title:Wd};Fa(kf),Ta(kf)},mc=Wd=>{const kf={...La,subtitle:Wd};Fa(kf),Ta(kf)},gc=(Wd,kf)=>{const Pf={...La,items:{...La.items,entities:La.items.entities.map((Nf,Eh)=>Eh===Wd?{...Nf,visible:kf}:Nf)}};Fa(Pf),Ta(Pf)},Vd=Wd=>{const{active:kf,over:Pf}=Wd;if(Pf&&kf.id!==Pf.id){const Nf=La.items.entities.findIndex(qg=>qg.name===kf.id),Eh=La.items.entities.findIndex(qg=>qg.name===Pf.id),Em={...La,items:{...La.items,entities:arrayMove(La.items.entities,Nf,Eh)}};Fa(Em),Ta(Em)}};return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("label",{className:"label",children:"Dashboard Title"}),jsxRuntimeExports$1.jsx("input",{type:"text",value:La.title,onChange:Wd=>pc(Wd.target.value),className:"form-input",placeholder:"Enter dashboard title"})]}),jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("label",{className:"label",children:"Dashboard Subtitle"}),jsxRuntimeExports$1.jsx("input",{type:"text",value:La.subtitle,onChange:Wd=>mc(Wd.target.value),className:"form-input",placeholder:"Enter dashboard subtitle"})]})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx("div",{children:jsxRuntimeExports$1.jsx(DndContext,{sensors:Pl,collisionDetection:closestCenter,onDragEnd:Vd,children:jsxRuntimeExports$1.jsx(SortableContext,{items:La.items.entities.map(Wd=>Wd.name),strategy:verticalListSortingStrategy,children:jsxRuntimeExports$1.jsx("div",{className:"space-y-3",children:La.items.entities.map((Wd,kf)=>jsxRuntimeExports$1.jsx(SortableEntityItem,{entity:Wd,index:kf,onVisibilityChange:gc,uiSpec:Ln,onEntityDetailsChange:wl},Wd.name))})})})})]})},Settings=({saveUISpec:ta})=>{const{isEntity:Ln,getActiveEntityorAgent:Ta}=Of(),{"*":ja}=useParams(),La=ja??"",Fa=La.split("/"),wl=Fa.at(-1)??"",Pl=Fa[1],pc=wl===""||wl==="signin",mc=wl==="signup",gc=wl==="edit"||wl==="new",Vd=Fa.length>3,Wd=wl==="dashboard",kf=Qn$1();return useEntityDetailsChange(ta),jsxRuntimeExports$1.jsxs("div",{className:"border-l border-l-border w-1/5 flex flex-col gap-4 p-4 settings-panel overflow-auto scrollbar-none",children:[pc&&jsxRuntimeExports$1.jsx(Auth,{saveUISpec:ta,authType:"login"}),mc&&jsxRuntimeExports$1.jsx(Auth,{saveUISpec:ta,authType:"signUp"}),gc&&jsxRuntimeExports$1.jsx(FormSettings,{entityName:Ta(La),saveUISpec:ta}),!pc&&!mc&&!gc&&(Wd?jsxRuntimeExports$1.jsx(DashboardCustomizationPanel,{schema:kf?.homeDashboard||{title:"",subtitle:"",items:{entities:[]}},uiSpec:kf,onSave:Pf=>{if(ta&&kf){const Nf={...kf,homeDashboard:Pf};ta(Nf,"Update home dashboard configuration")}},saveUISpec:ta}):Vd?jsxRuntimeExports$1.jsx(InstanceViewSettings,{entityName:Ta(La),saveUISpec:ta}):Ln(`${Pl}/${wl}`)?jsxRuntimeExports$1.jsx(CollectionViewSettings,{entityName:Ta(La),saveUISpec:ta}):null)]})},UI=()=>{const{isAgent:ta}=Of(),{"*":Ln}=useParams(),{pathParts:Ta}=Lt$3(Ln),ja=ta(`${Ta[1]}/${Ta[2]}`),{saveUISpec:La}=useSaveUISpec(),Fa=Qn$1(),wl=b6(),{teamName:Pl,moduleName:pc,githubOrg:mc}=useParams(),gc=useAppStore(Pf=>Pf.user),Vd=useAppStore(Pf=>Pf.appConfig),[Wd,kf]=reactExports$1.useState(null);return reactExports$1.useRef(!1),reactExports$1.useEffect(()=>{{kf("DISABLED");return}},[Pl,pc,mc,gc.GitHub?.Token,Vd.__repoPath]),reactExports$1.useEffect(()=>{typeof window<"u"&&(window.currentReplStatus=Wd,window.getReplStatus=()=>Wd)},[Wd]),!Fa||!Fa.login||!Fa.signUp?null:jsxRuntimeExports$1.jsxs("div",{className:"flex w-full",children:[jsxRuntimeExports$1.jsx(AAe,{schema:Fa,saveUISpec:La}),!wl&&!ja&&jsxRuntimeExports$1.jsx(Settings,{saveUISpec:La})]})},ServeModeInitializer=({children:ta})=>{const{initializeServeMode:Ln,loadingMessage:Ta,error:ja}=useServeMode();useEffectOnce(()=>{Ln()});const La=reactExports$1.useMemo(()=>{const mc=[{key:"connecting",label:"Connecting to local server",completed:!1},{key:"filesystem",label:"Loading file system",completed:!1},{key:"processing",label:"Processing project",completed:!1}];return Ta==="Connecting to local server..."||(Ta==="Loading file system..."?mc[0].completed=!0:Ta==="Processing project..."&&(mc[0].completed=!0,mc[1].completed=!0)),mc},[Ta]),Fa=La.filter(mc=>mc.completed).length,wl=La.findIndex(mc=>!mc.completed),Pl=wl===-1?La.length:wl,pc=Math.min(100,Math.max(5,(Fa+(Ta?.5:0))/La.length*100));return!Ta&&!ja?ta:ja?jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"linear-gradient(128.1deg, #0a142b 16.64%, #02050d 89.76%)"},children:jsxRuntimeExports$1.jsx("div",{className:"bg-secondary backdrop-blur-lg rounded-2xl shadow-card p-8 max-w-md w-full mx-4 border border-border-color animate-slide-in-up",children:jsxRuntimeExports$1.jsxs("div",{className:"text-center",children:[jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-del-icon rounded-full flex items-center justify-center mx-auto mb-6",children:jsxRuntimeExports$1.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntimeExports$1.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),jsxRuntimeExports$1.jsx("h2",{className:"text-xl font-semibold text-primary-font mb-3",children:"Initialization Failed"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font mb-6 text-sm",children:ja}),jsxRuntimeExports$1.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports$1.jsx("button",{onClick:()=>Ln(),className:"w-full sure-button px-6 py-3 rounded-lg transition-all duration-200 font-medium shadow-lg hover:shadow-xl transform hover:scale-105",children:"Retry Initialization"}),jsxRuntimeExports$1.jsx("button",{onClick:()=>window.location.reload(),className:"w-full cancel-button px-6 py-3 rounded-lg transition-all duration-200 font-medium",children:"Refresh Page"})]})]})})}):jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"linear-gradient(128.1deg, #0a142b 16.64%, #02050d 89.76%)"},children:jsxRuntimeExports$1.jsxs("div",{className:"bg-secondary backdrop-blur-lg rounded-2xl shadow-card p-8 max-w-lg w-full mx-4 border border-border-color animate-slide-in-up",children:[jsxRuntimeExports$1.jsxs("div",{className:"text-center mb-8",children:[jsxRuntimeExports$1.jsx("div",{className:"relative mb-6 animate-float",children:jsxRuntimeExports$1.jsx("div",{className:"w-20 h-20 bg-blue rounded-full flex items-center justify-center mx-auto animate-pulse-glow",children:jsxRuntimeExports$1.jsx("svg",{className:"w-10 h-10 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntimeExports$1.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})})}),jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-3",children:"Initializing Application"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm",children:Ta||"Setting up your workspace..."})]}),jsxRuntimeExports$1.jsxs("div",{className:"mb-8",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex justify-between text-sm text-secondary-font mb-3",children:[jsxRuntimeExports$1.jsx("span",{className:"font-medium",children:"Overall Progress"}),jsxRuntimeExports$1.jsxs("span",{className:"font-bold",children:[Math.round(pc),"%"]})]}),jsxRuntimeExports$1.jsx("div",{className:"w-full bg-hover rounded-full h-3 overflow-hidden",children:jsxRuntimeExports$1.jsx("div",{className:"bg-blue h-3 rounded-full transition-all duration-700 ease-out shadow-lg",style:{width:`${pc}%`}})})]}),jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:La.map((mc,gc)=>jsxRuntimeExports$1.jsxs("div",{className:"flex items-center p-3 rounded-lg transition-all duration-300 hover:highlight-color",children:[jsxRuntimeExports$1.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center mr-4 transition-all duration-300 ${mc.completed?"bg-entity-icon text-white shadow-lg":"bg-secondary text-secondary-font border border-border-color"}`,children:mc.completed?jsxRuntimeExports$1.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20",children:jsxRuntimeExports$1.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}):jsxRuntimeExports$1.jsx("span",{className:"text-sm font-bold",children:gc+1})}),jsxRuntimeExports$1.jsxs("div",{className:"flex-1",children:[jsxRuntimeExports$1.jsx("span",{className:`text-sm font-medium transition-all duration-300 ${mc.completed?"text-entity-icon":"text-secondary-font"}`,children:mc.label}),mc.completed&&jsxRuntimeExports$1.jsx("div",{className:"text-xs text-entity-icon mt-1",children:"✓ Completed"})]}),!mc.completed&&gc===Pl&&jsxRuntimeExports$1.jsx("div",{className:"ml-2",children:jsxRuntimeExports$1.jsxs("div",{className:"flex space-x-1",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-blue rounded-full animate-bounce"}),jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-blue-hover rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-primary-font rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]})})]},mc.key))}),jsxRuntimeExports$1.jsx("div",{className:"mt-6 text-center",children:jsxRuntimeExports$1.jsxs("div",{className:"inline-flex items-center text-sm text-secondary-font bg-secondary px-4 py-2 rounded-full border border-border-color",children:[jsxRuntimeExports$1.jsx("div",{className:"animate-pulse mr-2",children:jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue rounded-full"})}),jsxRuntimeExports$1.jsx("span",{className:"font-medium",children:"Loading..."})]})})]})})},AppContent=()=>jsxRuntimeExports$1.jsx(ServeModeInitializer,{children:jsxRuntimeExports$1.jsx(Outlet,{})}),router=createBrowserRouter([{path:"/",element:jsxRuntimeExports$1.jsx(AppContent,{}),children:[{path:"/",element:jsxRuntimeExports$1.jsx(AuthLayout,{}),children:[{path:"/",id:"signin",element:jsxRuntimeExports$1.jsx(SignIn,{})},{path:"/signup",id:"signup",element:jsxRuntimeExports$1.jsx(SignUp,{})},{path:"/forgotPassword",id:"forgot-password",element:jsxRuntimeExports$1.jsx(ForgotPassword,{})},{path:"/recoverPassword",id:"recover-password",element:jsxRuntimeExports$1.jsx(RecoverPassword,{})}]},{path:"/",element:jsxRuntimeExports$1.jsx(DashboardLayout,{}),children:[{path:"/home",id:"home",element:jsxRuntimeExports$1.jsx(Home,{})},{path:"/deployment/:deploymentId",id:"deployment-detail",element:jsxRuntimeExports$1.jsx(DeploymentDetail,{})},{path:"/hub",id:"marketplace",element:jsxRuntimeExports$1.jsx(Marketplace,{})},{path:"/configuration",id:"user-configuration",element:jsxRuntimeExports$1.jsx(UserConfiguration,{isModal:!1})},{path:"/design/dashboard",id:"teams",element:jsxRuntimeExports$1.jsx(Teams,{})},{path:"/design/integrations",id:"integrations",element:jsxRuntimeExports$1.jsx(Integrations,{})},{path:"/design/documents",id:"documents",element:jsxRuntimeExports$1.jsx(Documents,{})},{path:"/design/llms",id:"llms",element:jsxRuntimeExports$1.jsx(LLM,{})}]},{path:"/",element:jsxRuntimeExports$1.jsx(DesignLayout,{}),children:[{path:"/design/data-model/:githubOrg/:teamName/:moduleName",id:"data-model",element:jsxRuntimeExports$1.jsx(DataModel,{})},{path:"/design/marketplace/:githubOrg/:modelName/:moduleName",id:"marketplace-data-model",element:jsxRuntimeExports$1.jsx(DataModel,{})},{path:"/design/workflow/:githubOrg/:teamName/:moduleName",id:"workflow",element:jsxRuntimeExports$1.jsx(Workflow,{})},{path:"/design/security/:githubOrg/:teamName/:moduleName",id:"security",element:jsxRuntimeExports$1.jsx(Security,{})},{path:"/design/agents/:githubOrg/:teamName/:moduleName",id:"agents",element:jsxRuntimeExports$1.jsx(AgentFlow,{})},{path:"/design/ui/:githubOrg/:teamName/:moduleName/*",id:"ui",element:jsxRuntimeExports$1.jsx(UI,{})},{path:"/design/settings/:githubOrg/:teamName/:moduleName",id:"settings",element:jsxRuntimeExports$1.jsx(Settings$1,{})}]},{path:"*",id:"not-found",element:jsxRuntimeExports$1.jsx(NotFound,{})}]}]);function App(){return jsxRuntimeExports$1.jsx(PostHogProvider,{client:Do,children:jsxRuntimeExports$1.jsxs("div",{className:"relative h-screen","data-theme":"default",children:[jsxRuntimeExports$1.jsx("img",{src:"/assets/bg-gradient.png",alt:"",className:"bg-gradient"}),jsxRuntimeExports$1.jsx(RouterProvider,{router}),jsxRuntimeExports$1.jsx(Lt$1,{position:"top-center",autoClose:2e3,hideProgressBar:!0,newestOnTop:!1,closeOnClick:!0,rtl:!1,pauseOnFocusLoss:!1,pauseOnHover:!1,draggable:!1,theme:"dark"})]})})}var cacheEventTypes=["added","removed","updated"];function isCacheEventType(ta){return cacheEventTypes.includes(ta)}async function persistQueryClientRestore({queryClient:ta,persister:Ln,maxAge:Ta=1e3*60*60*24,buster:ja="",hydrateOptions:La}){try{const Fa=await Ln.restoreClient();if(Fa)if(Fa.timestamp){const wl=Date.now()-Fa.timestamp>Ta,Pl=Fa.buster!==ja;if(wl||Pl)return Ln.removeClient();hydrate(ta,Fa.clientState,La)}else return Ln.removeClient()}catch(Fa){throw await Ln.removeClient(),Fa}}async function persistQueryClientSave({queryClient:ta,persister:Ln,buster:Ta="",dehydrateOptions:ja}){const La={buster:Ta,timestamp:Date.now(),clientState:dehydrate(ta,ja)};await Ln.persistClient(La)}function persistQueryClientSubscribe(ta){const Ln=ta.queryClient.getQueryCache().subscribe(ja=>{isCacheEventType(ja.type)&&persistQueryClientSave(ta)}),Ta=ta.queryClient.getMutationCache().subscribe(ja=>{isCacheEventType(ja.type)&&persistQueryClientSave(ta)});return()=>{Ln(),Ta()}}function persistQueryClient(ta){let Ln=!1,Ta;const ja=()=>{Ln=!0,Ta?.()},La=persistQueryClientRestore(ta).then(()=>{Ln||(Ta=persistQueryClientSubscribe(ta))});return[ja,La]}console.log("IS_PLAYGROUND:",!1);console.log("IS_LOCAL_MODE:",!0);console.log("IS_REGULAR_MODE:",!1);console.log("POSTHOG_ENABLED:",!1);const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:120*1e3,gcTime:300*1e3,retry:(ta,Ln)=>Ln?.response?.status===401||Ln?.response?.status===403||Ln?.response?.status>=400&&Ln?.response?.status<500?!1:ta<3,retryDelay:ta=>Math.min(1e3*2**ta,3e4),refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchOnMount:!0}}}),persister={persistClient:async ta=>{const Ln=localStorage.getItem("workspace_id")||"default",Ta=localStorage.getItem("user_profile_id")||"default",ja={clientState:ta,timestamp:Date.now(),workspaceId:Ln,userProfileId:Ta};localStorage.setItem("agentlang-query-cache",JSON.stringify(ja))},restoreClient:async()=>{try{const ta=localStorage.getItem("agentlang-query-cache");if(!ta)return;const Ln=JSON.parse(ta),Ta=localStorage.getItem("workspace_id")||"default",ja=localStorage.getItem("user_profile_id")||"default";if(Ln.workspaceId!==Ta||Ln.userProfileId!==ja){console.warn("Workspace or user profile changed, invalidating query cache"),localStorage.removeItem("agentlang-query-cache");return}const La=720*60*1e3;if(Date.now()-Ln.timestamp>La){console.warn("Query cache expired, clearing"),localStorage.removeItem("agentlang-query-cache");return}return Ln.clientState}catch(ta){console.warn("Failed to restore query cache:",ta),localStorage.removeItem("agentlang-query-cache");return}},removeClient:async()=>{localStorage.removeItem("agentlang-query-cache")}};persistQueryClient({queryClient,persister,maxAge:1440*60*1e3});typeof window<"u"&&(window.replService=replService,window.entityReplService=replService);const rootElement=document.getElementById("root");if(!rootElement)throw new Error("Root element not found");async function initializeAndRenderApp(){try{await initializeAgentLang();const ta=document.getElementById("root");if(!ta)throw new Error("Root element not found");clientExports.createRoot(ta).render(jsxRuntimeExports$1.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports$1.jsx(App,{})}))}catch(ta){console.error("❌ Failed to initialize app:",ta);const Ln=document.getElementById("root");Ln&&(Ln.innerHTML=`
|
|
35647
|
+
`},errorHandler=curry(throwError)(errorMessages),validators={config:validateConfig},compose=function ta(){for(var Ln=arguments.length,Ta=new Array(Ln),ja=0;ja<Ln;ja++)Ta[ja]=arguments[ja];return function(La){return Ta.reduceRight(function(Fa,wl){return wl(Fa)},La)}};function merge(ta,Ln){return Object.keys(Ln).forEach(function(Ta){Ln[Ta]instanceof Object&&ta[Ta]&&Object.assign(Ln[Ta],merge(ta[Ta],Ln[Ta]))}),_objectSpread2$1(_objectSpread2$1({},ta),Ln)}var CANCELATION_MESSAGE={type:"cancelation",msg:"operation is manually canceled"};function makeCancelable(ta){var Ln=!1,Ta=new Promise(function(ja,La){ta.then(function(Fa){return Ln?La(CANCELATION_MESSAGE):ja(Fa)}),ta.catch(La)});return Ta.cancel=function(){return Ln=!0},Ta}var _excluded=["monaco"],_state$create=index.create({config:config$1,isInitialized:!1,resolve:null,reject:null,monaco:null}),_state$create2=_slicedToArray(_state$create,2),getState=_state$create2[0],setState=_state$create2[1];function config(ta){var Ln=validators.config(ta),Ta=Ln.monaco,ja=_objectWithoutProperties(Ln,_excluded);setState(function(La){return{config:merge(La.config,ja),monaco:Ta}})}function init(){var ta=getState(function(Ln){var Ta=Ln.monaco,ja=Ln.isInitialized,La=Ln.resolve;return{monaco:Ta,isInitialized:ja,resolve:La}});if(!ta.isInitialized){if(setState({isInitialized:!0}),ta.monaco)return ta.resolve(ta.monaco),makeCancelable(wrapperPromise);if(window.monaco&&window.monaco.editor)return storeMonacoInstance(window.monaco),ta.resolve(window.monaco),makeCancelable(wrapperPromise);compose(injectScripts,getMonacoLoaderScript)(configureLoader)}return makeCancelable(wrapperPromise)}function injectScripts(ta){return document.body.appendChild(ta)}function createScript(ta){var Ln=document.createElement("script");return ta&&(Ln.src=ta),Ln}function getMonacoLoaderScript(ta){var Ln=getState(function(ja){var La=ja.config,Fa=ja.reject;return{config:La,reject:Fa}}),Ta=createScript("".concat(Ln.config.paths.vs,"/loader.js"));return Ta.onload=function(){return ta()},Ta.onerror=Ln.reject,Ta}function configureLoader(){var ta=getState(function(Ta){var ja=Ta.config,La=Ta.resolve,Fa=Ta.reject;return{config:ja,resolve:La,reject:Fa}}),Ln=window.require;Ln.config(ta.config),Ln(["vs/editor/editor.main"],function(Ta){var ja=Ta.m||Ta;storeMonacoInstance(ja),ta.resolve(ja)},function(Ta){ta.reject(Ta)})}function storeMonacoInstance(ta){getState().monaco||setState({monaco:ta})}function __getMonacoInstance(){return getState(function(ta){var Ln=ta.monaco;return Ln})}var wrapperPromise=new Promise(function(ta,Ln){return setState({resolve:ta,reject:Ln})}),loader={config,init,__getMonacoInstance},le={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},v=le,ae={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},Y=ae;function Me({children:ta}){return React.createElement("div",{style:Y.container},ta)}var Z=Me,$=Z;function Ee({width:ta,height:Ln,isEditorReady:Ta,loading:ja,_ref:La,className:Fa,wrapperProps:wl}){return React.createElement("section",{style:{...v.wrapper,width:ta,height:Ln},...wl},!Ta&&React.createElement($,null,ja),React.createElement("div",{ref:La,style:{...v.fullWidth,...!Ta&&v.hide},className:Fa}))}var ee=Ee,H=reactExports$1.memo(ee);function Ce(ta){reactExports$1.useEffect(ta,[])}var k=Ce;function he(ta,Ln,Ta=!0){let ja=reactExports$1.useRef(!0);reactExports$1.useEffect(ja.current||!Ta?()=>{ja.current=!1}:ta,Ln)}var l=he;function D(){}function h(ta,Ln,Ta,ja){return De(ta,ja)||be(ta,Ln,Ta,ja)}function De(ta,Ln){return ta.editor.getModel(te(ta,Ln))}function be(ta,Ln,Ta,ja){return ta.editor.createModel(Ln,Ta,ja?te(ta,ja):void 0)}function te(ta,Ln){return ta.Uri.parse(Ln)}function Oe({original:ta,modified:Ln,language:Ta,originalLanguage:ja,modifiedLanguage:La,originalModelPath:Fa,modifiedModelPath:wl,keepCurrentOriginalModel:Pl=!1,keepCurrentModifiedModel:pc=!1,theme:mc="light",loading:gc="Loading...",options:Vd={},height:Wd="100%",width:kf="100%",className:Pf,wrapperProps:Nf={},beforeMount:Eh=D,onMount:Em=D}){let[qg,Ug]=reactExports$1.useState(!1),[Bg,U_]=reactExports$1.useState(!0),B_=reactExports$1.useRef(null),VC=reactExports$1.useRef(null),tj=reactExports$1.useRef(null),aB=reactExports$1.useRef(Em),r6=reactExports$1.useRef(Eh),J2=reactExports$1.useRef(!1);k(()=>{let q5=loader.init();return q5.then(nj=>(VC.current=nj)&&U_(!1)).catch(nj=>nj?.type!=="cancelation"&&console.error("Monaco initialization: error:",nj)),()=>B_.current?Q2():q5.cancel()}),l(()=>{if(B_.current&&VC.current){let q5=B_.current.getOriginalEditor(),nj=h(VC.current,ta||"",ja||Ta||"text",Fa||"");nj!==q5.getModel()&&q5.setModel(nj)}},[Fa],qg),l(()=>{if(B_.current&&VC.current){let q5=B_.current.getModifiedEditor(),nj=h(VC.current,Ln||"",La||Ta||"text",wl||"");nj!==q5.getModel()&&q5.setModel(nj)}},[wl],qg),l(()=>{let q5=B_.current.getModifiedEditor();q5.getOption(VC.current.editor.EditorOption.readOnly)?q5.setValue(Ln||""):Ln!==q5.getValue()&&(q5.executeEdits("",[{range:q5.getModel().getFullModelRange(),text:Ln||"",forceMoveMarkers:!0}]),q5.pushUndoStop())},[Ln],qg),l(()=>{B_.current?.getModel()?.original.setValue(ta||"")},[ta],qg),l(()=>{let{original:q5,modified:nj}=B_.current.getModel();VC.current.editor.setModelLanguage(q5,ja||Ta||"text"),VC.current.editor.setModelLanguage(nj,La||Ta||"text")},[Ta,ja,La],qg),l(()=>{VC.current?.editor.setTheme(mc)},[mc],qg),l(()=>{B_.current?.updateOptions(Vd)},[Vd],qg);let V_=reactExports$1.useCallback(()=>{if(!VC.current)return;r6.current(VC.current);let q5=h(VC.current,ta||"",ja||Ta||"text",Fa||""),nj=h(VC.current,Ln||"",La||Ta||"text",wl||"");B_.current?.setModel({original:q5,modified:nj})},[Ta,Ln,La,ta,ja,Fa,wl]),sP=reactExports$1.useCallback(()=>{!J2.current&&tj.current&&(B_.current=VC.current.editor.createDiffEditor(tj.current,{automaticLayout:!0,...Vd}),V_(),VC.current?.editor.setTheme(mc),Ug(!0),J2.current=!0)},[Vd,mc,V_]);reactExports$1.useEffect(()=>{qg&&aB.current(B_.current,VC.current)},[qg]),reactExports$1.useEffect(()=>{!Bg&&!qg&&sP()},[Bg,qg,sP]);function Q2(){let q5=B_.current?.getModel();Pl||q5?.original?.dispose(),pc||q5?.modified?.dispose(),B_.current?.dispose()}return React.createElement(H,{width:kf,height:Wd,isEditorReady:qg,loading:gc,_ref:tj,className:Pf,wrapperProps:Nf})}var ie=Oe;reactExports$1.memo(ie);function He(ta){let Ln=reactExports$1.useRef();return reactExports$1.useEffect(()=>{Ln.current=ta},[ta]),Ln.current}var se=He,_=new Map;function Ve({defaultValue:ta,defaultLanguage:Ln,defaultPath:Ta,value:ja,language:La,path:Fa,theme:wl="light",line:Pl,loading:pc="Loading...",options:mc={},overrideServices:gc={},saveViewState:Vd=!0,keepCurrentModel:Wd=!1,width:kf="100%",height:Pf="100%",className:Nf,wrapperProps:Eh={},beforeMount:Em=D,onMount:qg=D,onChange:Ug,onValidate:Bg=D}){let[U_,B_]=reactExports$1.useState(!1),[VC,tj]=reactExports$1.useState(!0),aB=reactExports$1.useRef(null),r6=reactExports$1.useRef(null),J2=reactExports$1.useRef(null),V_=reactExports$1.useRef(qg),sP=reactExports$1.useRef(Em),Q2=reactExports$1.useRef(),q5=reactExports$1.useRef(ja),nj=se(Fa),n6=reactExports$1.useRef(!1),l6=reactExports$1.useRef(!1);k(()=>{let u6=loader.init();return u6.then(f6=>(aB.current=f6)&&tj(!1)).catch(f6=>f6?.type!=="cancelation"&&console.error("Monaco initialization: error:",f6)),()=>r6.current?s6():u6.cancel()}),l(()=>{let u6=h(aB.current,ta||ja||"",Ln||La||"",Fa||Ta||"");u6!==r6.current?.getModel()&&(Vd&&_.set(nj,r6.current?.saveViewState()),r6.current?.setModel(u6),Vd&&r6.current?.restoreViewState(_.get(Fa)))},[Fa],U_),l(()=>{r6.current?.updateOptions(mc)},[mc],U_),l(()=>{!r6.current||ja===void 0||(r6.current.getOption(aB.current.editor.EditorOption.readOnly)?r6.current.setValue(ja):ja!==r6.current.getValue()&&(l6.current=!0,r6.current.executeEdits("",[{range:r6.current.getModel().getFullModelRange(),text:ja,forceMoveMarkers:!0}]),r6.current.pushUndoStop(),l6.current=!1))},[ja],U_),l(()=>{let u6=r6.current?.getModel();u6&&La&&aB.current?.editor.setModelLanguage(u6,La)},[La],U_),l(()=>{Pl!==void 0&&r6.current?.revealLine(Pl)},[Pl],U_),l(()=>{aB.current?.editor.setTheme(wl)},[wl],U_);let i6=reactExports$1.useCallback(()=>{if(!(!J2.current||!aB.current)&&!n6.current){sP.current(aB.current);let u6=Fa||Ta,f6=h(aB.current,ja||ta||"",Ln||La||"",u6||"");r6.current=aB.current?.editor.create(J2.current,{model:f6,automaticLayout:!0,...mc},gc),Vd&&r6.current.restoreViewState(_.get(u6)),aB.current.editor.setTheme(wl),Pl!==void 0&&r6.current.revealLine(Pl),B_(!0),n6.current=!0}},[ta,Ln,Ta,ja,La,Fa,mc,gc,Vd,wl,Pl]);reactExports$1.useEffect(()=>{U_&&V_.current(r6.current,aB.current)},[U_]),reactExports$1.useEffect(()=>{!VC&&!U_&&i6()},[VC,U_,i6]),q5.current=ja,reactExports$1.useEffect(()=>{U_&&Ug&&(Q2.current?.dispose(),Q2.current=r6.current?.onDidChangeModelContent(u6=>{l6.current||Ug(r6.current.getValue(),u6)}))},[U_,Ug]),reactExports$1.useEffect(()=>{if(U_){let u6=aB.current.editor.onDidChangeMarkers(f6=>{let Rpe=r6.current.getModel()?.uri;if(Rpe&&f6.find(Xae=>Xae.path===Rpe.path)){let Xae=aB.current.editor.getModelMarkers({resource:Rpe});Bg?.(Xae)}});return()=>{u6?.dispose()}}return()=>{}},[U_,Bg]);function s6(){Q2.current?.dispose(),Wd?Vd&&_.set(Fa,r6.current.saveViewState()):r6.current.getModel()?.dispose(),r6.current.dispose()}return React.createElement(H,{width:kf,height:Pf,isEditorReady:U_,loading:pc,_ref:J2,className:Nf,wrapperProps:Eh})}var fe=Ve,de=reactExports$1.memo(fe),Ft=de;const CodeEditor=()=>{const ta=reactExports$1.useRef(null),{scrollToText:Ln,setScrollToText:Ta}=useAppStore(),{moduleName:ja}=useParams(),[La,Fa]=reactExports$1.useState(!1),[wl,Pl]=reactExports$1.useState(""),{getModuleCode:pc}=useModule(),mc=useMatches(),{currentTeam:gc}=useTeams(),[Vd,Wd]=reactExports$1.useState(""),[kf,Pf]=reactExports$1.useState(""),Eh=(mc.length>1?mc[mc.length-1].id:"")==="settings";reactExports$1.useEffect(()=>{if(ta.current&&Ln){const Bg=ta.current.getModel();if(!Bg)return;const U_=Bg.findMatches(Ln,!0,!1,!1,null,!0);if(U_.length>0){const B_=U_[0].range;ta.current.revealRangeInCenter(B_),ta.current.setSelection(B_),ta.current.focus()}Ta(null)}},[Ln,Ta]);const Em=Bg=>{Bg.editor.defineTheme("agentlang-editor",{base:"vs-dark",inherit:!0,rules:[],colors:{"editor.background":"#122247"}})};reactExports$1.useEffect(()=>{if(ja){const Bg=pc(ja||"");Pl(Bg||"")}},[ja,pc]);const qg=async()=>{if(Eh&&gc)try{const Bg=await readPackageJsonFromGit(gc.GitHubRepo);Wd(JSON.stringify(Bg,null,2));const U_=await readRepoFile(`/${gc.GitHubRepo}`,"config.al");Pf(U_)}catch(Bg){console.error("Failed to fetch files for editor:",Bg),Wd("// Failed to load package.json"),Pf("// Failed to load config.al")}Fa(!La)},Ug=document.getElementById(Eh?"team-settings-container":"canvas-area");return jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"header-action-icon",onClick:qg,children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.code})}),Ug&&reactDomExports$1.createPortal(jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(motion.div,{animate:{width:La?"100%":"0px"},initial:{width:"0px"},transition:{duration:.5},className:"absolute top-0 right-0 bottom-0 z-998 overflow-hidden bg-primary",children:Eh?jsxRuntimeExports$1.jsxs("div",{className:"flex h-full flex-col",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex w-full",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1/2 text-white text-center py-2 bg-[#1E1E1E]",children:"package.json"}),jsxRuntimeExports$1.jsx("div",{className:"w-1/2 text-white text-center py-2 bg-[#1E1E1E]",children:"config.al"})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex h-full",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1/2 h-full",children:jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{enabled:!1}},language:"json",theme:"agentlang-editor",value:Vd,path:"package.json"})}),jsxRuntimeExports$1.jsx("div",{className:"w-1/2 h-full",children:jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{enabled:!1}},language:"agentlang",theme:"agentlang-editor",value:kf,path:"config.al"})})]})]}):jsxRuntimeExports$1.jsx(Ft,{options:{minimap:{autohide:!0},scrollbar:{vertical:"hidden"}},beforeMount:Em,language:"agentlang",theme:"agentlang-editor",value:wl})}),La&&jsxRuntimeExports$1.jsx(motion.div,{transition:{duration:.5},initial:{left:"calc(100% - 32px)"},animate:{left:"0px"},onClick:()=>Fa(!1),className:"bg-blue hover:bg-blue-hover text-primary-font h-8 w-8 text-base rounded-full flex items-center justify-center absolute top-1/2 -translate-y-1/2 cursor-pointer z-999 duraation-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:"ph:caret-right-bold"})})]}),Ug)]})},useModuleReload=()=>{const{isReloadingModules:ta,reloadModules:Ln}=useAppStore(),[Ta,ja]=reactExports$1.useState(null),La=reactExports$1.useCallback(async wl=>{try{ja(null),await Ln(wl)}catch(Pl){const pc=Pl instanceof Error?Pl.message:"Failed to reload modules";throw ja(pc),Pl}},[Ln]),Fa=reactExports$1.useCallback(()=>{ja(null)},[]);return{isReloading:ta,error:Ta,reloadModules:La,clearError:Fa}},Branch=()=>{const{currentTeam:ta}=useTeams(),{user:Ln}=useAppStore();useModuleReload();const[Ta,ja]=reactExports$1.useState(ta?.Branch||"main");reactExports$1.useEffect(()=>{ta?.Branch&&ja(ta.Branch)},[ta?.Branch,ta?.Id]),Ln?.GitHub?.Token,Ln?.GitHub?.Username;const[La,Fa]=reactExports$1.useState([]),[wl,Pl]=reactExports$1.useState(!1),[pc,mc]=reactExports$1.useState(!1),[gc,Vd]=reactExports$1.useState(!1);return jsxRuntimeExports$1.jsxs("div",{className:"highlight-color rounded-md p-3 flex items-center gap-2 text-primary-font w-full",children:[jsxRuntimeExports$1.jsx(Icon,{icon:"fluent:branch-16-regular"}),jsxRuntimeExports$1.jsx("span",{className:"line-clamp-1",children:Ta})]})},PageLoader=({message:ta,header:Ln})=>jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col h-full",children:[Ln,jsxRuntimeExports$1.jsx("div",{className:"flex flex-1 items-center justify-center",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center gap-6",children:[jsxRuntimeExports$1.jsxs("div",{className:"relative animate-float",children:[jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-blue rounded-full flex items-center justify-center animate-pulse-glow",children:jsxRuntimeExports$1.jsx(Icon,{icon:"lucide:download-cloud",className:"w-8 h-8 text-white"})}),jsxRuntimeExports$1.jsx("div",{className:"absolute inset-0 w-16 h-16 border-4 border-blue-hover border-t-transparent rounded-full animate-spin"})]}),jsxRuntimeExports$1.jsxs("div",{className:"text-center",children:[jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-2",children:"Fetching Repository"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm",children:ta||"Please wait while we fetch the repository..."})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex space-x-1",children:[jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue rounded-full animate-bounce"}),jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue-hover rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-primary-font rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]})]})})]}),CanvasError=({message:ta})=>{const Ln=useNavigate();return jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center h-full",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[jsxRuntimeExports$1.jsx("div",{className:"relative ",children:jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-red-500/20 rounded-full flex items-center justify-center ",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.error,className:"w-8 h-8 text-red-400"})})}),jsxRuntimeExports$1.jsxs("div",{children:[jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-2",children:"Failed to Load Repository"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm max-w-sm",children:"There was an issue cloning or processing the repository."})]}),jsxRuntimeExports$1.jsx("button",{onClick:()=>Ln("/design/dashboard"),className:"go-back-button bg-primary hover:bg-hover text-primary-font font-medium py-2 px-6 rounded-lg border border-border-color transition-all duration-200",children:"Go to Dashboard"}),ta&&jsxRuntimeExports$1.jsxs("details",{className:"error-details bg-secondary/50 p-3 rounded-lg text-left w-full max-w-sm max-h-50 overflow-y-auto overflow-x-hidden",children:[jsxRuntimeExports$1.jsx("summary",{className:"cursor-pointer text-sm font-medium text-secondary-font hover:text-primary-font",children:"Error Details"}),jsxRuntimeExports$1.jsx("pre",{className:"p-4 bg-black/20 rounded text-xs text-red-400 whitespace-pre-wrap wrap-break-word overflow-x-hidden",children:ta})]})]})})},getIcon=ta=>{switch(ta){case"entity":case"entity-attribute":return icons.entity;case"record":case"record-attribute":return icons.record;case"relationship":case"relationship-attribute":return icons.relationship;case"event":case"event-attribute":return icons.action;case"agent":return icons.agent;default:return icons.datamodel}},getTypeLabel=ta=>{switch(ta){case"entity":return"Entity";case"record":return"Record";case"relationship":return"Relationship";case"event":return"Event";case"agent":return"Agent";case"entity-attribute":return"Entity Attribute";case"record-attribute":return"Record Attribute";case"relationship-attribute":return"Relationship Attribute";case"event-attribute":return"Event Attribute";default:return""}},Search=()=>{const{teamName:ta,githubOrg:Ln,modelName:Ta}=useParams(),ja=useNavigate(),{pathname:La}=useLocation(),Fa=La.includes("/design/marketplace/"),[wl,Pl]=reactExports$1.useState(""),[pc,mc]=reactExports$1.useState(!1),gc=reactExports$1.useMemo(()=>{const Pf=getUserModuleNames(),Nf=[];return Pf.forEach(Eh=>{getEntities(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"entity",moduleName:Eh});try{(getEntity$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"entity-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for entity ${Em}:`,qg)}}),getRecords(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"record",moduleName:Eh});try{(getRecord(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"record-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for record ${Em}:`,qg)}}),getEvents(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"event",moduleName:Eh});try{(getEvent$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"event-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for event ${Em}:`,qg)}}),getRelationships(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"relationship",moduleName:Eh});try{(getRelationship$1(Em,Eh)?.getUserAttributeNames()||[]).forEach(Bg=>{Nf.push({name:`${Eh}.${Em}/${Bg}`,displayName:`${Eh}.${Em}/${Bg}`,searchText:`${Eh}.${Em}/${Bg}`.toLowerCase(),type:"relationship-attribute",moduleName:Eh,parentName:Em})})}catch(qg){console.error(`Error getting attributes for relationship ${Em}:`,qg)}}),getAgents(Eh).forEach(Em=>{Nf.push({name:Em,displayName:Em,searchText:Em.toLowerCase(),type:"agent",moduleName:Eh})})}),Nf},[]),Vd=reactExports$1.useDeferredValue(wl),Wd=reactExports$1.useMemo(()=>{const Pf=Vd.trim().toLowerCase();return!pc||!Pf?[]:gc.filter(Nf=>Nf.searchText.includes(Pf)).slice(0,50)},[Vd,gc,pc]),kf=Pf=>{const Nf=Pf.moduleName;let Eh=Pf.name,Em=Pf.type;if((Pf.type==="entity-attribute"||Pf.type==="record-attribute"||Pf.type==="relationship-attribute"||Pf.type==="event-attribute")&&(Eh=Pf.parentName||Pf.name,Pf.type==="entity-attribute"?Em="entity":Pf.type==="record-attribute"?Em="record":Pf.type==="relationship-attribute"?Em="relationship":Pf.type==="event-attribute"&&(Em="event")),Fa)ja(`/design/marketplace/${Ln}/${Ta}/${Nf}`);else{const qg=ta;if(Em==="entity"||Em==="record"||Em==="relationship"){const Ug=`${Nf}/${Eh}`;ja(`/design/data-model/${Ln}/${qg}/${Nf}`,{state:{focusEntityId:Ug}})}else Em==="event"?ja(`/design/workflow/${Ln}/${qg}/${Nf}`,{state:{focusEventId:Eh}}):Em==="agent"&&ja(`/design/agents/${Ln}/${qg}/${Nf}`,{state:{focusAgentId:Eh}})}Pl(""),mc(!1)};return jsxRuntimeExports$1.jsxs("div",{className:"relative w-full min-w-0",children:[jsxRuntimeExports$1.jsx("div",{className:"relative",children:jsxRuntimeExports$1.jsx("input",{type:"text",placeholder:"Search",value:wl,onChange:Pf=>Pl(Pf.target.value),onFocus:()=>mc(!0),onBlur:()=>setTimeout(()=>mc(!1),200),className:"w-full text-sm sm:text-base"})}),pc&&Wd.length>0&&jsxRuntimeExports$1.jsx("div",{className:"absolute top-full left-0 right-0 mt-1 bg-primary border border-border-color rounded-md shadow-lg z-50 max-h-[150px] overflow-auto scrollbar-none",children:Wd.map(Pf=>jsxRuntimeExports$1.jsxs("div",{onClick:()=>kf(Pf),className:"flex items-center gap-2 px-3 py-2 hover:bg-secondary cursor-pointer transition-colors",children:[jsxRuntimeExports$1.jsx(Icon,{icon:getIcon(Pf.type),className:"w-4 h-4 text-secondary-font"}),jsxRuntimeExports$1.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports$1.jsx("div",{className:"text-sm text-primary-font truncate",children:Pf.displayName}),jsxRuntimeExports$1.jsxs("div",{className:"text-xs text-secondary-font truncate",children:[getTypeLabel(Pf.type)," in ",Pf.moduleName]})]})]},`${Pf.moduleName}:${Pf.name}`))})]})},DesignHistoryNavigationButtons=()=>{const ta=useNavigate(),Ln=useLocation(),Ta=useNavigationType(),ja=useMatches(),La=ja[ja.length-1]?.id||"",[Fa,wl]=reactExports$1.useState(!1),[Pl,pc]=reactExports$1.useState(!1),mc=useAppStore(VC=>VC.previouslyFocusedNode),gc=useAppStore(VC=>VC.setPreviouslyFocusedNode),Vd=useAppStore(VC=>VC.focusedNodeStack),Wd=useAppStore(VC=>VC.focusedNodeForwardStack),kf=useAppStore(VC=>VC.popFocusedNode),Pf=useAppStore(VC=>VC.popFocusedForward),Nf=useAppStore(VC=>VC.currentFocusedNode),{zoomHandler:Eh,restoreInitialViewport:Em}=useZoomHandler(),{getNode:qg}=useReactFlow(),Ug=La==="security",Bg=La==="data-model"||La==="marketplace-data-model"||La==="workflow"||Ug;reactExports$1.useEffect(()=>{const VC=window.history.state&&window.history.state.idx||0,tj="rr_max_idx",aB=sessionStorage.getItem(tj);let r6=aB?parseInt(aB,10):VC;(Ta==="PUSH"||VC>r6)&&(r6=VC),sessionStorage.setItem(tj,String(r6)),wl(VC>0||Vd&&Vd.length>0),pc(VC<r6||(Wd||[]).length>0)},[Ln,Ta,Vd,Wd]);const U_=()=>{if(Fa){if(Bg)if(Nf&&Nf!==INITIAL_VIEWPORT_NODE_ID&&qg(Nf)){if(Vd&&Vd.length>0){const tj=kf();if(tj===INITIAL_VIEWPORT_NODE_ID){Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}else if(tj&&qg(tj)){Eh(tj,{openForm:!0,mode:"back"}),gc(null);return}}Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}else{if(Vd&&Vd.length>0&&Vd[Vd.length-1]===INITIAL_VIEWPORT_NODE_ID){kf(),Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}ta(-1);return}if(Vd&&Vd.length>0){const VC=kf();if(VC&&VC!==INITIAL_VIEWPORT_NODE_ID&&qg(VC)){Eh(VC,{openForm:!0,mode:"back"}),gc(null);return}else if(VC===INITIAL_VIEWPORT_NODE_ID){Em({x:100,y:Ug?120:50,zoom:.6}),gc(null);return}}if(mc&&!!qg(mc)){Eh(mc,{openForm:!0}),gc(null);return}ta(-1)}},B_=()=>{if(Pl){if(Wd&&Wd.length>0){const VC=Pf();if(VC&&qg(VC)){Eh(VC,{openForm:!0,mode:"forward"}),gc(null);return}}if(mc&&!!qg(mc)){Eh(mc,{openForm:!0}),gc(null);return}ta(1)}};return jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports$1.jsx("button",{type:"button",onClick:U_,className:`header-action-icon !bg-transparent hover:!bg-hover ${Fa?"":"opacity-40 cursor-not-allowed pointer-events-none"}`,disabled:!Fa,title:Fa?"Back":"No previous page",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.back})}),jsxRuntimeExports$1.jsx("button",{type:"button",onClick:B_,className:`header-action-icon !bg-transparent hover:!bg-hover ${Pl?"":"opacity-40 cursor-not-allowed pointer-events-none"}`,disabled:!Pl,title:Pl?"Forward":"No next page",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.forward})})]})},getNestedInitialValues=(ta,Ln,Ta,ja)=>{ta.forEach((La,Fa)=>{const wl=typeof La=="object"&&La!==void 0,Pl=wl&&La.properties?.get("default"),pc=`${Ln}.${Fa}`,mc=jve$1(Fa,La,Ta);mc.isNested&&mc.nestedAttributes?getNestedInitialValues(mc.nestedAttributes,pc,mc.referencedModule,ja):Pl!==void 0?ja[pc]=Pl:(wl?La.type:String(La))==="Boolean"?ja[pc]=!1:ja[pc]=""})},getInitialValues=ta=>{const Ln={};return ta.forEach(Ta=>{const ja=Ta.attributes,La=Ta.entityName,wl=parseEntityPath(Ta.entityName)?.moduleName||null;getNestedInitialValues(ja,La,wl,Ln)}),Ln},handleSubmit=ta=>{const Ln={};Object.entries(ta).forEach(([Ta,ja])=>{const[La,Fa]=Ta.split(".",2);Ln[La]||(Ln[La]={}),Ln[La][Fa]=ja}),console.log("All config values submitted:",Ln)},parseEntityPath=ta=>{const Ln=ta.lastIndexOf("/");if(Ln<=0)return null;const Ta=ta.substring(0,Ln),ja=ta.substring(Ln+1);let La,Fa;if(ja.includes(".")){const[wl,Pl]=ja.split(".",2);La=`${Ta}.${wl}`,Fa=Pl}else La=Ta,Fa=ja;return{moduleName:La,entityName:Fa}},useConfigEntities=()=>{const{currentTeam:ta}=useTeams(),[Ln,Ta]=reactExports$1.useState([]),[ja,La]=reactExports$1.useState(!0),[Fa,wl]=reactExports$1.useState(null),Pl=ta?.GitHubRepo;return reactExports$1.useEffect(()=>{(async()=>{if(!Pl){La(!1);return}La(!0),wl(null);const mc=[];try{const Vd=(await readPackageJsonFromGit(Pl)).dependencies||{},Wd=await getDependenciesRecursive(Pl,Vd,new Set),kf=[Pl,...Wd];for(const Pf of kf)try{let Nf;if(Pf===Pl?Nf=await readPackageJsonFromGit(Pf):Nf=await readDependencyPackageJsonFromGit(Pl,Pf),Nf?.agentlang?.config&&Array.isArray(Nf.agentlang.config))for(const Eh of Nf.agentlang.config)try{const Em=parseEntityPath(Eh);if(!Em)continue;const{moduleName:qg,entityName:Ug}=Em,Bg=getEntity$1(Ug,qg);if(Bg){const U_=`${qg}.${Ug}`;mc.push({name:Pf,entityName:U_,attributes:Bg.getUserAttributes()})}}catch(Em){console.error(`Failed to get entity for ${Eh}:`,Em)}}catch(Nf){console.error(`Failed to read package.json for ${Pf}:`,Nf)}}catch(gc){console.error("Failed to fetch config entities:",gc),wl("Failed to load deployment configurations.")}finally{Ta(mc),La(!1)}})()},[Pl]),{configEntities:Ln,isLoading:ja,error:Fa}},DeploymentConfigurationForm=({closeHandler:ta})=>{const{configEntities:Ln,isLoading:Ta,error:ja}=useConfigEntities();if(Ta)return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50}),jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50}),jsxRuntimeExports$1.jsx(Skeleton,{variant:"rounded",height:50})]});if(ja)return jsxRuntimeExports$1.jsx("div",{className:"text-center py-8 text-red-500",children:ja});if(Ln.length===0)return jsxRuntimeExports$1.jsx("div",{className:"text-center py-8 text-gray-400",children:"No configuration entities found"});const La=new Map;return Ln.forEach(Fa=>{const wl=Fa.name;La.has(wl)||La.set(wl,[]);const Pl=La.get(wl);Pl&&Pl.push(Fa)}),jsxRuntimeExports$1.jsx(Formik,{initialValues:getInitialValues(Ln),onSubmit:handleSubmit,enableReinitialize:!0,children:jsxRuntimeExports$1.jsxs(Form$6,{children:[jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:Array.from(La.entries()).map(([Fa,wl])=>jsxRuntimeExports$1.jsxs("div",{className:"p-4 highlight-color rounded-md",children:[jsxRuntimeExports$1.jsx("h3",{className:"text-lg font-semibold text-primary-font mb-4",children:Fa}),jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:wl.map(Pl=>{const pc=Pl.entityName.split("."),mc=pc[pc.length-1];return jsxRuntimeExports$1.jsx(P_,{label:mc,defaultOpen:!0,className:"bg-primary! rounded-md",children:jsxRuntimeExports$1.jsx("div",{className:"space-y-4 pt-2 pl-4",children:Array.from(Pl.attributes.entries()).map(([gc,Vd])=>{const kf=parseEntityPath(Pl.entityName)?.moduleName||null,Pf=`${Pl.entityName}.${gc}`;return jsxRuntimeExports$1.jsx(MV,{attrName:gc,spec:Vd,currentModule:kf,depth:0,fieldPrefix:Pl.entityName},Pf)})})},Pl.entityName)})})]},Fa))}),jsxRuntimeExports$1.jsx(Divider,{color:"white",sx:{opacity:.2,marginTop:"1rem"}}),jsxRuntimeExports$1.jsx("div",{className:"mt-4",children:jsxRuntimeExports$1.jsx(Footer,{label:"Save",closeHandler:ta})})]})})},DeploymentConfiguration=({closeHandler:ta})=>{const{isLoading:Ln,error:Ta}=useConfigEntities(),ja=useOutsideClickHandler(ta);let La;return Ln?La=jsxRuntimeExports$1.jsx("div",{className:"text-center p-8",children:"Loading..."}):Ta?La=jsxRuntimeExports$1.jsx("div",{className:"text-center p-8 text-red-500",children:Ta}):La=jsxRuntimeExports$1.jsx(DeploymentConfigurationForm,{closeHandler:ta}),jsxRuntimeExports$1.jsx("div",{className:"modal-container",onClick:Fa=>Fa.stopPropagation(),children:jsxRuntimeExports$1.jsxs("div",{className:"modal-content w-[clamp(600px,50vw,800px)]",ref:ja,children:[jsxRuntimeExports$1.jsxs("div",{className:"modal-header",children:[jsxRuntimeExports$1.jsx("div",{className:"modal-title",children:"Deployment Configuration"}),jsxRuntimeExports$1.jsx(Icon,{icon:icons.cross,className:"cursor-pointer text-secondary-font duration-300 hover:text-maroon",onClick:ta})]}),jsxRuntimeExports$1.jsx(Divider,{color:"white",sx:{opacity:.2}}),jsxRuntimeExports$1.jsx("div",{className:"modal-body",children:La})]})})},IS_LOCAL_MODE=!0,DesignLayout=()=>{const{teamName:ta,moduleName:Ln,githubOrg:Ta}=useParams(),ja=useNavigate(),{state:La}=useLocation(),Fa=useMatches(),wl=Fa.length>1?Fa[Fa.length-1].id:"",Pl=wl.includes("marketplace"),pc=wl!=="settings",{currentTeam:mc,isEditable:gc}=useTeams(),[Vd,Wd]=reactExports$1.useState(!1),{isCloning:kf,cloneAndProcess:Pf,error:Nf,loadingMessage:Eh}=useRepositoryClone(),{setIsArchitectDrawerOpen:Em}=useAppStore();reactExports$1.useEffect(()=>{Em(!1)},[Em]),reactExports$1.useRef(null);const qg=mc?`${mc.GitHubOrg}/${mc.GitHubRepo}`:null;return reactExports$1.useEffect(()=>{!mc||La?.isNewTeam},[qg,La?.isNewTeam,Pf,ja,mc]),jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[Vd&&reactDomExports$1.createPortal(jsxRuntimeExports$1.jsx(DeploymentConfiguration,{closeHandler:()=>Wd(!1)}),document.body),jsxRuntimeExports$1.jsx("div",{className:"flex flex-col h-screen ",children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[!IS_LOCAL_MODE,jsxRuntimeExports$1.jsx("div",{id:"editor",className:"flex flex-col flex-1 overflow-hidden",children:kf?jsxRuntimeExports$1.jsx(PageLoader,{message:Eh,header:jsxRuntimeExports$1.jsxs("div",{id:"dashboard-header",className:"flex justify-between gap-2 py-2 px-4 bg-transparent border-b border-border-color border-solid",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex gap-3 items-center animate-pulse",children:[jsxRuntimeExports$1.jsx("div",{className:"h-6 w-6 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-5 w-28 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-5 w-16 bg-secondary rounded"}),jsxRuntimeExports$1.jsx("div",{className:"h-6 w-10 bg-secondary rounded"})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center animate-pulse",children:[jsxRuntimeExports$1.jsx("div",{className:"h-8 w-8 bg-secondary rounded-full"}),jsxRuntimeExports$1.jsx("div",{className:"h-8 w-8 bg-secondary rounded-full"})]})]})}):Nf?jsxRuntimeExports$1.jsx(CanvasError,{message:Nf}):jsxRuntimeExports$1.jsxs(ReactFlowProvider,{children:[jsxRuntimeExports$1.jsxs("div",{id:"dashboard-header",className:"flex justify-between gap-2 py-2 px-4 bg-transparent border-b border-border-color border-solid",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center",children:[!IS_LOCAL_MODE,jsxRuntimeExports$1.jsx("div",{className:"dashboard-model-icon text-xl!",children:jsxRuntimeExports$1.jsx(TeamOrDepIcon,{name:mc?.GitHubRepo||icons.agent})}),jsxRuntimeExports$1.jsx("h4",{children:mc?.Name}),jsxRuntimeExports$1.jsx(Branch,{}),!IS_LOCAL_MODE]}),gc&&jsxRuntimeExports$1.jsxs("div",{className:"flex flex-1 gap-2 items-center text-sm min-w-0 max-w-2xl",children:[jsxRuntimeExports$1.jsx(DesignHistoryNavigationButtons,{}),jsxRuntimeExports$1.jsx(Search,{})]}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-center text-sm",children:[jsxRuntimeExports$1.jsx(CodeEditor,{}),gc&&!0&&!IS_LOCAL_MODE,!Pl&&jsxRuntimeExports$1.jsx(TooltipComponent,{text:"Settings",children:jsxRuntimeExports$1.jsx("div",{onClick:()=>ja(`/design/settings/${Ta}/${ta}/${Ln}`),className:"header-action-icon",children:jsxRuntimeExports$1.jsx(Icon,{icon:icons.setting})})})]})]}),pc?jsxRuntimeExports$1.jsxs("div",{className:" flex flex-1 overflow-hidden",children:[jsxRuntimeExports$1.jsx(DesignNavigator,{}),jsxRuntimeExports$1.jsx("div",{className:"relative w-full flex overflow-hidden",id:"canvas-area",children:jsxRuntimeExports$1.jsx(Outlet,{})})]}):jsxRuntimeExports$1.jsx(Outlet,{})]})})]})})]})};reactExports$1.createContext(void 0);var PostHogContext=reactExports$1.createContext({client:Do,bootstrap:void 0});function isDeepEqual(ta,Ln,Ta){if(Ta===void 0&&(Ta=new WeakMap),ta===Ln)return!0;if(typeof ta!="object"||ta===null||typeof Ln!="object"||Ln===null)return!1;if(Ta.has(ta)&&Ta.get(ta)===Ln)return!0;Ta.set(ta,Ln);var ja=Object.keys(ta),La=Object.keys(Ln);if(ja.length!==La.length)return!1;for(var Fa=0,wl=ja;Fa<wl.length;Fa++){var Pl=wl[Fa];if(!La.includes(Pl)||!isDeepEqual(ta[Pl],Ln[Pl],Ta))return!1}return!0}function PostHogProvider(ta){var Ln,Ta,ja=ta.children,La=ta.client,Fa=ta.apiKey,wl=ta.options,Pl=reactExports$1.useRef(null),pc=reactExports$1.useMemo(function(){return La?(Fa&&console.warn("[PostHog.js] You have provided both `client` and `apiKey` to `PostHogProvider`. `apiKey` will be ignored in favour of `client`."),wl&&console.warn("[PostHog.js] You have provided both `client` and `options` to `PostHogProvider`. `options` will be ignored in favour of `client`."),La):(Fa||console.warn("[PostHog.js] No `apiKey` or `client` were provided to `PostHogProvider`. Using default global `window.posthog` instance. You must initialize it manually. This is not recommended behavior."),Do)},[La,Fa,JSON.stringify(wl)]);return reactExports$1.useEffect(function(){if(!La){var mc=Pl.current;mc?(Fa!==mc.apiKey&&console.warn("[PostHog.js] You have provided a different `apiKey` to `PostHogProvider` than the one that was already initialized. This is not supported by our provider and we'll keep using the previous key. If you need to toggle between API Keys you need to control the `client` yourself and pass it in as a prop rather than an `apiKey` prop."),wl&&!isDeepEqual(wl,mc.options)&&Do.set_config(wl),Pl.current={apiKey:Fa,options:wl??{}}):(Do.__loaded&&console.warn("[PostHog.js] `posthog` was already loaded elsewhere. This may cause issues."),Do.init(Fa,wl),Pl.current={apiKey:Fa,options:wl??{}})}},[La,Fa,JSON.stringify(wl)]),React.createElement(PostHogContext.Provider,{value:{client:pc,bootstrap:(Ln=wl?.bootstrap)!==null&&Ln!==void 0?Ln:(Ta=La?.config)===null||Ta===void 0?void 0:Ta.bootstrap}},ja)}var isFunction=function(ta){return typeof ta=="function"},extendStatics=function(ta,Ln){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Ta,ja){Ta.__proto__=ja}||function(Ta,ja){for(var La in ja)Object.prototype.hasOwnProperty.call(ja,La)&&(Ta[La]=ja[La])},extendStatics(ta,Ln)};function __extends(ta,Ln){if(typeof Ln!="function"&&Ln!==null)throw new TypeError("Class extends value "+String(Ln)+" is not a constructor or null");extendStatics(ta,Ln);function Ta(){this.constructor=ta}ta.prototype=Ln===null?Object.create(Ln):(Ta.prototype=Ln.prototype,new Ta)}typeof SuppressedError=="function"&&SuppressedError;var INITIAL_STATE={componentStack:null,exceptionEvent:null,error:null},__POSTHOG_ERROR_MESSAGES={INVALID_FALLBACK:"[PostHog.js][PostHogErrorBoundary] Invalid fallback prop, provide a valid React element or a function that returns a valid React element."};(function(ta){__extends(Ln,ta);function Ln(Ta){var ja=ta.call(this,Ta)||this;return ja.state=INITIAL_STATE,ja}return Ln.prototype.componentDidCatch=function(Ta,ja){var La=this.props.additionalProperties,Fa;isFunction(La)?Fa=La(Ta):typeof La=="object"&&(Fa=La);var wl=this.context.client,Pl=wl.captureException(Ta,Fa),pc=ja.componentStack;this.setState({error:Ta,componentStack:pc,exceptionEvent:Pl})},Ln.prototype.render=function(){var Ta=this.props,ja=Ta.children,La=Ta.fallback,Fa=this.state;if(Fa.componentStack==null)return isFunction(ja)?ja():ja;var wl=isFunction(La)?React.createElement(La,{error:Fa.error,componentStack:Fa.componentStack,exceptionEvent:Fa.exceptionEvent}):La;return React.isValidElement(wl)?wl:(console.warn(__POSTHOG_ERROR_MESSAGES.INVALID_FALLBACK),React.createElement(React.Fragment,null))},Ln.contextType=PostHogContext,Ln})(React.Component);const validationSchema=create$3().shape({title:create$6().required("Title is required")}),Header=({saveUISpec:ta,authType:Ln})=>{const{teamName:Ta}=useParams(),ja=Qn$1();return ja?jsxRuntimeExports$1.jsx(Formik,{initialValues:{...ja[Ln].header,title:ja[Ln].header.title||Ta},onSubmit:La=>{const Fa={...ja,[Ln]:{...ja[Ln]||{},header:La}};ta&&ta(Fa,"Update theme")},validationSchema,children:jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[jsxRuntimeExports$1.jsx(lAe,{name:"title",placeholder:"Welcome Message",isFloating:!1}),jsxRuntimeExports$1.jsx(lAe,{name:"subTitle",placeholder:"Subtitle",isFloating:!1}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}):null},FormSettings$1=({saveUISpec:ta,authType:Ln})=>{const Ta=Qn$1();return Ta?jsxRuntimeExports$1.jsx(Formik,{initialValues:Ta[Ln].form.placeholder,onSubmit:ja=>{const La={...Ta,[Ln]:{...Ta[Ln],form:{...Ta[Ln].form,placeholder:ja}}};ta&&ta(La,"Update theme")},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[Object.keys(Ta[Ln].form.placeholder).map(ja=>jsxRuntimeExports$1.jsx(lAe,{name:ja,placeholder:`${Ft$5(ja)} Placeholder`,isFloating:!1},ja)),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}):null},socialNetworks=["git","google","microsoft","linkedin"],SocialNetworks=({saveUISpec:ta,authType:Ln})=>{const Ta=Qn$1();return Ta?jsxRuntimeExports$1.jsx(Formik,{initialValues:Ta[Ln].socialNetworks,onSubmit:ja=>{const La={...Ta,[Ln]:{...Ta[Ln],socialNetworks:ja}};ta&&ta(La,"Update theme")},children:ja=>{const{values:La,setValues:Fa}=ja,wl=La.icons,Pl=socialNetworks.every(pc=>wl.includes(pc));return jsxRuntimeExports$1.jsxs(Form$6,{className:"flex flex-col gap-4",children:[jsxRuntimeExports$1.jsx(lAe,{name:"label",placeholder:"Label",isFloating:!1}),jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-end cursor-pointer",onClick:()=>{Fa({...La,icons:Pl?[]:socialNetworks})},children:[jsxRuntimeExports$1.jsx(Icon,{icon:Pl?Ot$2.checkboxSelected:Ot$2.checkbox,className:classNames(["text-xl",Pl?"text-checkbox-selected":"text-secondary-font"])}),"Show social networks"]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),socialNetworks.map(pc=>{const mc=wl.includes(pc);return jsxRuntimeExports$1.jsxs("div",{className:"flex gap-2 items-end cursor-pointer",onClick:()=>{Fa({...La,icons:mc?La.icons.filter(gc=>gc!==pc):[...La.icons,pc]})},children:[jsxRuntimeExports$1.jsx(Icon,{icon:mc?Ot$2.checkboxSelected:Ot$2.checkbox,className:classNames(["text-xl",mc?"text-checkbox-selected":"text-secondary-font"])}),Ft$5(pc)]},pc)}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",children:"Save"})]})}}):null},Auth=({saveUISpec:ta,authType:Ln})=>jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(P_,{label:"Header",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(Header,{saveUISpec:ta,authType:Ln})}),jsxRuntimeExports$1.jsx(P_,{label:"Social Networks",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(SocialNetworks,{saveUISpec:ta,authType:Ln})}),jsxRuntimeExports$1.jsx(P_,{label:"Form",defaultOpen:!0,children:jsxRuntimeExports$1.jsx(FormSettings$1,{saveUISpec:ta,authType:Ln})})]}),getTopLevelAttributes=(ta,Ln)=>ta.order?.length>0?ta.order:Array.from(Ln.keys()),initializeNestedFormSchema=ta=>{const Ln={Form:{},order:[]};return ta.forEach((Ta,ja)=>{const La=Ta.properties?.get("optional")===!0,wl=typeof Ta=="object"&&Ta!==void 0?Ta.type:String(Ta),Pl=getInputType(wl);Ln.Form[ja]={inputType:Pl,required:!La,displayOptions:{label:Ft$5(ja),placeholder:`Enter ${ja}`}},Ln.order.push(ja)}),Ln},ensureCompleteNestedFormSchema=(ta,Ln)=>{const Ta=ta||{Form:{},order:[]};return Ln.forEach((ja,La)=>{if(!Ta.Form[La]){const Fa=ja.properties?.get("optional")===!0,Pl=typeof ja=="object"&&ja!==void 0?ja.type:String(ja),pc=getInputType(Pl);Ta.Form[La]={inputType:pc,required:!Fa,displayOptions:{label:Ft$5(La),placeholder:`Enter ${La}`}},Ta.order.includes(La)||Ta.order.push(La)}}),Ta},NestedFields=({entityName:ta,attrName:Ln,nestedFormSchema:Ta,nestedAttributes:ja,referencedModule:La,updateNestedFormSchema:Fa,depth:wl})=>{const[Pl,pc]=reactExports$1.useState(null);let mc=Ta;!mc&&ja&&(mc=initializeNestedFormSchema(ja),Fa(mc));const gc=ensureCompleteNestedFormSchema(mc,ja),Vd=gc.order?.length>0?gc.order.filter(Eh=>gc.Form[Eh]):Array.from(ja.keys()),Wd=[],kf=[];Vd.forEach(Eh=>{gc.Form[Eh]?.required??!1?Wd.push(Eh):kf.push(Eh)});const Pf=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),Nf=Eh=>{const{active:Em,over:qg}=Eh;if(qg&&Em.id!==qg.id){const Ug=tj=>{const aB=tj;return aB.includes(".")&&aB.split(".").pop()||aB},Bg=Ug(Em.id),U_=Ug(qg.id),B_=gc.order.indexOf(Bg),VC=gc.order.indexOf(U_);if(B_!==-1&&VC!==-1){const tj=[...gc.order],[aB]=tj.splice(B_,1);tj.splice(VC,0,aB);const r6={...gc,order:tj};Fa(r6)}}pc(null)};return jsxRuntimeExports$1.jsx(DndContext,{sensors:Pf,collisionDetection:closestCenter,onDragCancel:()=>pc(null),onDragStart:Eh=>{pc(Eh.active.id)},onDragEnd:Nf,children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container pt-2",children:[jsxRuntimeExports$1.jsxs(SortableContext,{items:Vd.map(Eh=>Ln?`${Ln}.${Eh}`:Eh),strategy:verticalListSortingStrategy,children:[Wd.length>0&&jsxRuntimeExports$1.jsx("div",{className:"flex flex-col gap-2",children:Wd.map(Eh=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Eh,formSchema:gc,updateFormSchema:Fa,isRequired:!0,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1},Eh))}),kf.length>0&&jsxRuntimeExports$1.jsx("div",{children:kf.map(Eh=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Eh,formSchema:gc,updateFormSchema:Fa,isRequired:!1,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1},Eh))})]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:Pl?(()=>{const Em=(Bg=>Bg.includes(".")&&Bg.split(".").pop()||Bg)(Pl),Ug=gc.Form[Em]?.required??!1;return jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Fa,isRequired:Ug,nestedPath:Ln,nestedAttributes:ja,referencedModule:La,depth:wl+1})})():null})]})})},AttributeField$1=({entityName:ta,attrName:Ln,formSchema:Ta,updateFormSchema:ja,isRequired:La=!0,nestedPath:Fa,nestedAttributes:wl,referencedModule:Pl,depth:pc=0})=>{const[mc,gc]=reactExports$1.useState(!1),Vd=Ta.Form[Ln]?.isHidden||!1,{attributes:Wd,listeners:kf,setNodeRef:Pf,transform:Nf,transition:Eh,isDragging:Em}=useSortable({id:Fa?`${Fa}.${Ln}`:Ln}),qg=(()=>{try{const[sP,Q2]=ta.split("/");return getEntity$1(Q2,sP)?.getUserAttributes()||new Map}catch(sP){return console.error("Error getting entity schema:",sP),new Map}})(),Bg=(wl||qg).get(Ln),U_=Bg&&typeof Bg=="object"?Bg.type:String(Bg||"text"),B_=Ta.Form[Ln]?.inputType||getInputType(U_),VC=Pl||ta.split("/")[0],tj=Bg?jve$1(Ln,Bg,VC):{isNested:!1,nestedAttributes:null,referencedModule:null},aB=tj.isNested&&tj.nestedAttributes!==null,r6=Ta.Form[Ln]?.nestedForm,J2=[{label:"Text",value:"text"},{label:"Number",value:"number"},{label:"Email",value:"email"},{label:"Password",value:"password"},{label:"Date",value:"date"},{label:"Checkbox",value:"checkbox"},{label:"Select",value:"select"},...aB?[{label:"Nested Form",value:"nested"}]:[]],V_=sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],nestedForm:sP}}};ja(Q2)};return jsxRuntimeExports$1.jsxs("div",{ref:Pf,style:{opacity:Em?.5:1,transform:CSS$1.Translate.toString(Nf),transition:Eh},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>gc(!mc),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[jsxRuntimeExports$1.jsx("span",{...Wd,...kf,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsxs("span",{children:[Ft$5(Ln),aB&&jsxRuntimeExports$1.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:["(",tj.type==="entity"?"Entity":tj.type==="record"?"Record":"OneOf",": ",tj.referencedName,")"]})]})]}),!La&&jsxRuntimeExports$1.jsx("div",{onClick:sP=>sP.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!Vd,onChangeHandler:sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],isHidden:!sP}}};ja(Q2)}})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:mc&&!aB&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx("div",{className:"setting-toggle-body",children:jsxRuntimeExports$1.jsxs("div",{className:"mb-4",children:[jsxRuntimeExports$1.jsx("label",{className:"text-sm mb-2 block",children:"Input Type"}),jsxRuntimeExports$1.jsx(FV,{value:B_,options:J2,onChange:sP=>{const Q2={...Ta,Form:{...Ta.Form,[Ln]:{...Ta.Form[Ln],inputType:sP}}};ja(Q2)}})]})})})}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:mc&&aB&&tj.nestedAttributes&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx("div",{children:jsxRuntimeExports$1.jsx(NestedFields,{entityName:ta,attrName:Ln,nestedFormSchema:r6,nestedAttributes:tj.nestedAttributes,referencedModule:tj.referencedModule,updateNestedFormSchema:V_,depth:pc})})})})]})},FormSettings=({entityName:ta,saveUISpec:Ln})=>{const[Ta,ja]=reactExports$1.useState(null),[La,Fa]=ta.split("/"),Pl=getEntity$1(Fa,La)?.getUserAttributes()||new Map,pc=Qn$1(),mc=`${ta}.ui.form`,gc=pc[mc],Wd=getTopLevelAttributes(gc,Pl).filter(Em=>gc.Form[Em]).sort((Em,qg)=>{const Ug=gc.order.indexOf(Em),Bg=gc.order.indexOf(qg);return Ug===-1?1:Bg===-1?-1:Ug-Bg}),kf=[],Pf=[];Wd.forEach(Em=>{gc.Form[Em]?.required??!1?kf.push(Em):Pf.push(Em)});const Nf=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),Eh=Em=>{if(Ln){const qg=`${ta}.ui.form`,Ug={...pc,[qg]:Em};Ln(Ug,"Update form settings")}};return jsxRuntimeExports$1.jsx(DndContext,{sensors:Nf,collisionDetection:closestCenter,onDragCancel:()=>ja(null),onDragStart:Em=>{ja(Em.active.id)},onDragEnd:Em=>{const{active:qg,over:Ug}=Em;if(Ug&&qg.id!==Ug.id){const Bg=gc.order.indexOf(qg.id),U_=gc.order.indexOf(Ug.id),B_=[...gc.order],[VC]=B_.splice(Bg,1);B_.splice(U_,0,VC);const tj={...gc,order:B_};console.log("newFormSchema",tj),Eh(tj)}ja(null)},children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsxs(SortableContext,{items:Wd,strategy:verticalListSortingStrategy,children:[kf.length>0&&jsxRuntimeExports$1.jsx(P_,{label:"Required",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:kf.map(Em=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Eh,isRequired:!0},Em))})}),Pf.length>0&&jsxRuntimeExports$1.jsx(P_,{label:"Optional",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:Pf.map(Em=>jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Em,formSchema:gc,updateFormSchema:Eh,isRequired:!1},Em))})})]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:Ta?jsxRuntimeExports$1.jsx(AttributeField$1,{entityName:ta,attrName:Ta,formSchema:gc,updateFormSchema:Eh}):null})]})})},HeaderSettings=({headerSchema:ta,updateHeaderSchema:Ln})=>{if(Array.isArray(ta)||typeof ta!="object"||ta===null)return null;const Ta=ta.view,{showBreadcrumbs:ja}=Ta?.Heading||{};return jsxRuntimeExports$1.jsx(P_,{label:"Header",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:jsxRuntimeExports$1.jsx(Formik,{initialValues:{showBreadcrumbs:ja??!1},onSubmit:La=>{const Fa={...Ta.Heading,...La},wl={...ta,view:{...Ta,Heading:Fa}};Ln(wl)},children:({values:La,setFieldValue:Fa})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Show Breadcrumbs"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:La.showBreadcrumbs,onChangeHandler:wl=>Fa("showBreadcrumbs",wl)})]})}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})};function capitalizeFirstLetter(ta){return ta&&ta.charAt(0).toUpperCase()+ta.slice(1)}const DateOptionMenu=()=>{const[ta,,Ln]=useField({name:"dateFormat"}),Ta=ta.value;return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Date Format"}),jsxRuntimeExports$1.jsx(FV,{value:Ta||"MM/DD/YY",options:[{label:"DD/MM/YY",value:"DD/MM/YY"},{label:"MM/DD/YY",value:"MM/DD/YY"}],onChange:ja=>Ln.setValue(ja)})]})},FontWeightMenu$1=()=>{const[ta,,Ln]=useField({name:"fontWeight"}),Ta=ta.value||"normal";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Weight"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"Normal",value:"normal"},{label:"Bold",value:"bold"},{label:"Bolder",value:"bolder"},{label:"Lighter",value:"lighter"}],onChange:ja=>Ln.setValue(ja)})]})},FontStyleMenu$1=()=>{const[ta,,Ln]=useField({name:"fontStyle"}),Ta=ta.value||"normal";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Style"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"Normal",value:"normal"},{label:"Italic",value:"italic"},{label:"Oblique",value:"oblique"},{label:"Lighter",value:"lighter"}],onChange:ja=>Ln.setValue(ja)})]})},TextDecorationMenu$1=()=>{const[ta,,Ln]=useField({name:"textDecorationLine"}),Ta=ta.value||"none";return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Text Decoration"}),jsxRuntimeExports$1.jsx(FV,{value:Ta,options:[{label:"None",value:"none"},{label:"Underline",value:"underline"},{label:"Overline",value:"overline"},{label:"Line Through",value:"line-through"}],onChange:ja=>Ln.setValue(ja)})]})},ColumnField=({entityName:ta,attributeName:Ln,uiAttributeSchema:Ta={},onFieldUpdate:ja,onAttributeUpdate:La,disabled:Fa=!1})=>{const[wl,Pl]=reactExports$1.useState(!1),{attributes:pc,listeners:mc,setNodeRef:gc,transform:Vd,transition:Wd,isDragging:kf}=useSortable({id:Ln,disabled:Fa}),[Pf,Nf]=ta.split("/"),qg=getEntity$1(Nf,Pf)?.getUserAttributes()?.get(Ln),Ug=typeof qg=="object"?qg.type:String(qg),Bg=()=>{if(Object.keys(Ta).length===0){const U_={colSpan:1,fontWeight:"normal",fontStyle:"normal",textDecorationLine:"none"};switch(Ug){case"DateTime":return{...U_,dateFormat:"MM/DD/YY"};case"Float":case"Decimal":return{...U_,precision:2};default:return U_}}return Ta};return jsxRuntimeExports$1.jsxs("div",{ref:gc,style:{opacity:kf?.5:1,transform:CSS$1.Translate.toString(Vd),transition:Wd},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>Pl(!wl),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[!Fa&&jsxRuntimeExports$1.jsx("span",{...pc,...mc,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("span",{children:capitalizeFirstLetter(Ln)})]}),ja&&jsxRuntimeExports$1.jsx("div",{onClick:U_=>U_.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!Fa,onChangeHandler:ja})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:wl&&!Fa&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx(Formik,{initialValues:Bg(),validate:U_=>{const B_={};return U_.colSpan||(B_.colSpan="Col span is required"),["Float","Decimal"].includes(Ug)&&!U_.precision&&(B_.precision="Precision is required"),B_},onSubmit:U_=>{La&&La(Ln,U_)},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-toggle-body",style:{height:"max-content"},children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Col Span"}),jsxRuntimeExports$1.jsx(Field,{type:"number",step:"1",placeholder:"ColSpan",name:"colSpan",className:"form-input"}),jsxRuntimeExports$1.jsx(ErrorMessage,{name:"colSpan",children:U_=>jsxRuntimeExports$1.jsxs("div",{className:"error-message",children:[jsxRuntimeExports$1.jsx(Icon,{icon:"ph:warning-bold"}),U_]})})]}),Ug==="DateTime"&&jsxRuntimeExports$1.jsx(DateOptionMenu,{}),["Float","Decimal"].includes(Ug)&&jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Precision"}),jsxRuntimeExports$1.jsx(Field,{type:"number",step:"1",placeholder:"Precision",name:"precision",className:"form-input"}),jsxRuntimeExports$1.jsx(ErrorMessage,{name:"precision",children:U_=>jsxRuntimeExports$1.jsxs("div",{className:"error-message",children:[jsxRuntimeExports$1.jsx(Icon,{icon:"ph:warning-bold"}),U_]})})]}),jsxRuntimeExports$1.jsx(FontWeightMenu$1,{}),jsxRuntimeExports$1.jsx(FontStyleMenu$1,{}),jsxRuntimeExports$1.jsx(TextDecorationMenu$1,{}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})]})},FieldSettings$1=({entityName:ta,collectionSchema:Ln,onFieldUpdate:Ta,onAttributeUpdate:ja})=>{const[La,Fa]=reactExports$1.useState(null),[wl,Pl]=ta.split("/"),mc=getEntity$1(Pl,wl)?.getUserAttributes(),gc=Array.from(mc?.keys()||[]),Vd=Object.keys(Ln)[0],Wd=Ln[Vd],kf=Wd?.fields,Pf=Array.isArray(kf)?kf:[],Nf=gc.filter(Em=>!Pf.includes(Em)),Eh=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates}));return jsxRuntimeExports$1.jsx(DndContext,{sensors:Eh,collisionDetection:closestCenter,onDragCancel:()=>Fa(null),onDragStart:Em=>{Fa(Em.active.id)},onDragEnd:Em=>{const{active:qg,over:Ug}=Em;if(Ug&&qg.id!==Ug.id){const Bg=Pf.indexOf(qg.id),U_=Pf.indexOf(Ug.id),B_=arrayMove(Pf,Bg,U_);Ta(B_)}Fa(null)},children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(SortableContext,{items:Pf,strategy:verticalListSortingStrategy,children:Pf.map(Em=>jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:Em,uiAttributeSchema:Wd[Em]||{},onFieldUpdate:qg=>{qg||Ta(Pf.filter(Ug=>Ug!==Em))},onAttributeUpdate:ja,disabled:!1},Em))}),Nf.length>0&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),Nf.map(Em=>jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:Em,onFieldUpdate:qg=>{qg&&Ta([...Pf,Em])},onAttributeUpdate:ja,disabled:!0},Em))]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:La?jsxRuntimeExports$1.jsx(ColumnField,{entityName:ta,attributeName:La}):null})]})})},CreateButtonSettings=({actionSchema:ta,updateActionSchema:Ln})=>jsxRuntimeExports$1.jsx(P_,{label:"Create Button",defaultOpen:!0,children:jsxRuntimeExports$1.jsx("div",{className:"setting-container",children:jsxRuntimeExports$1.jsx(Formik,{initialValues:{text:ta?.create?.text||"",icon:ta?.create?.icon||"mdi:plus"},onSubmit:Ta=>{Ln({create:{...ta.create,...Ta}})},children:({values:Ta,setFieldValue:ja})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Button Text"}),jsxRuntimeExports$1.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports$1.jsx(lxe,{icon:Ta.icon,onIconChange:La=>ja("icon",La),children:jsxRuntimeExports$1.jsx("button",{type:"button",className:"w-8 h-8 bg-secondary border border-transparent hover:border-white/40 rounded-md flex items-center justify-center cursor-pointer transition-all duration-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:Ta.icon,width:"16",height:"16"})})}),jsxRuntimeExports$1.jsx(Field,{type:"text",placeholder:"Button Text",name:"text",className:"form-input"})]})]}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})}),EntityCollectionSettings=({entityName:ta,bodySchema:Ln,updateBodySchema:Ta})=>{if(Array.isArray(Ln)||typeof Ln!="object"||Ln===null)return null;const ja=Ln.view,La=Object.keys(ja)[0],{showGlobalFilter:Fa,showColumnFilter:wl}=Object.values(ja)[0],Pl=pc=>{const mc=ja[La];Ta({...Ln,view:{[pc]:mc}})};return jsxRuntimeExports$1.jsx(P_,{label:"Collection",defaultOpen:!0,children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-options",children:[jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-option","data-selected":La==="Table",onClick:()=>Pl("Table"),children:[jsxRuntimeExports$1.jsx(Icon,{icon:"tabler:table",height:"20",width:"20"}),"Table"]}),jsxRuntimeExports$1.jsxs("div",{className:"entity-collection-option","data-selected":La==="Cards",onClick:()=>Pl("Cards"),children:[jsxRuntimeExports$1.jsx(Icon,{icon:"mdi:cards-outline",height:"20",width:"20"}),"Cards"]})]}),jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Global Filtering"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:Fa||!1,onChangeHandler:pc=>{Ta({...Ln,view:{[La]:{...ja[La],showGlobalFilter:pc}}})}})]})}),jsxRuntimeExports$1.jsx("div",{className:"setting-toggle",children:jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",children:[jsxRuntimeExports$1.jsx("span",{children:"Column Filtering"}),jsxRuntimeExports$1.jsx(TAe,{isChecked:wl||!1,onChangeHandler:pc=>{Ta({...Ln,view:{[La]:{...ja[La],showColumnFilter:pc}}})}})]})})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(FieldSettings$1,{entityName:ta,collectionSchema:ja,onFieldUpdate:pc=>{const mc=La;Ta({...Ln,view:{[mc]:{...ja[mc],fields:pc}}})},onAttributeUpdate:(pc,mc)=>{const gc=La;Ta({...Ln,view:{[gc]:{...ja[gc],[pc]:mc}}})}})]})})},CollectionViewSettings=({entityName:ta,saveUISpec:Ln,showHeader:Ta=!0})=>{const ja=Qn$1(),{onEntityDetailsChange:La}=useEntityDetailsChange(Ln),Fa=`${ta}.ui.dashboard`,wl=ja?.[Fa],Pl=ja?.[ta],pc=wl?.find(Pf=>Pf.includes(".header")),mc=pc?ja?.[pc]:void 0,gc=wl?.find(Pf=>Pf.includes(".body")),Vd=gc?ja?.[gc]:void 0,Wd=Pf=>{if(Ln&&pc){const Nf={...ja,[`${pc}.header`]:Pf};Ln(Nf,"Update dashboard header settings")}},kf=Pf=>{if(Ln){const Nf={...ja,[`${gc}.body`]:Pf};Ln(Nf,"Update dashboard body settings")}};return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[mc&&Ta&&jsxRuntimeExports$1.jsx(HeaderSettings,{headerSchema:mc,updateHeaderSchema:Wd}),jsxRuntimeExports$1.jsx(_Ae,{onEntityDetailsChange:Pf=>La(ta,Pf),initialDetails:Pl}),Vd&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx(CreateButtonSettings,{actionSchema:Vd.actions||{},updateActionSchema:Pf=>{const Nf={...Vd,actions:Pf};kf(Nf)}}),jsxRuntimeExports$1.jsx(EntityCollectionSettings,{entityName:ta,bodySchema:Vd,updateBodySchema:kf})]})]})},FontWeightMenu=()=>{const[ta,,Ln]=useField({name:"fontWeight"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Weight"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"normal",options:["normal","bold","bolder","lighter"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},FontStyleMenu=()=>{const[ta,,Ln]=useField({name:"fontStyle"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Font Style"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"normal",options:["normal","italic","oblique"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},TextDecorationMenu=()=>{const[ta,,Ln]=useField({name:"textDecorationLine"});return jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Text Decoration"}),jsxRuntimeExports$1.jsx(FV,{value:ta.value||"none",options:["none","underline","overline","line-through"].map(Ta=>({label:Ta,value:Ta})),onChange:Ta=>Ln.setValue(Ta)})]})},ButtonSettings=({buttonType:ta,buttonSchema:Ln,updateButtonSchema:Ta,entityName:ja})=>{const La=ja.split("/")[1],Fa={text:Ln?.text||ta,icon:Ln?.icon||(ta==="Edit"?"mdi:pencil":"mdi:delete"),style:Ln?.style||(ta==="Edit"?"secondary":"danger")};return jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx("div",{className:"font-bold",children:`${ta} Button`}),jsxRuntimeExports$1.jsx(Formik,{initialValues:Fa,onSubmit:wl=>{const Pl={...Ln||{type:"button",actionType:ta==="Edit"?"navigation":"modal",action:`${La}/${ta.toLowerCase()}`},...wl};Ta(Pl)},enableReinitialize:!0,children:({values:wl,setFieldValue:Pl})=>jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container",style:{gap:"8px"},children:[jsxRuntimeExports$1.jsx("div",{className:"form-item",children:jsxRuntimeExports$1.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports$1.jsx(lxe,{icon:wl.icon,onIconChange:pc=>Pl("icon",pc),children:jsxRuntimeExports$1.jsx("button",{type:"button",className:"w-8 h-8 bg-secondary border border-transparent hover:border-white/40 rounded-md flex items-center justify-center cursor-pointer transition-all duration-300",children:jsxRuntimeExports$1.jsx(Icon,{icon:wl.icon,width:"16",height:"16",className:"text-white"})})}),jsxRuntimeExports$1.jsx(Field,{type:"text",name:"text",placeholder:"Button Text",className:"form-input flex-1"})]})}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})]})},AttributeField=({attributeName:ta,uiAttributeSchema:Ln={},onFieldUpdate:Ta,onAttributeUpdate:ja,disabled:La=!1})=>{const[Fa,wl]=reactExports$1.useState(!1),{attributes:Pl,listeners:pc,setNodeRef:mc,transform:gc,transition:Vd,isDragging:Wd}=useSortable({id:ta,disabled:La});return jsxRuntimeExports$1.jsxs("div",{ref:mc,style:{opacity:Wd?.5:1,transform:CSS$1.Translate.toString(gc),transition:Vd},className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header",onClick:()=>wl(!Fa),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle",children:[!La&&jsxRuntimeExports$1.jsx("span",{...Pl,...pc,className:"drag-handle",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("span",{children:Ft$5(ta)})]}),Ta&&jsxRuntimeExports$1.jsx("div",{onClick:kf=>kf.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:!La,onChangeHandler:Ta})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:Fa&&!La&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0},animate:{height:"auto"},exit:{height:0},style:{overflow:"hidden"},children:jsxRuntimeExports$1.jsx(Formik,{initialValues:Ln,onSubmit:kf=>ja?.(ta,kf),children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-toggle-body",style:{height:"max-content"},children:[jsxRuntimeExports$1.jsx(FontWeightMenu,{}),jsxRuntimeExports$1.jsx(FontStyleMenu,{}),jsxRuntimeExports$1.jsx(TextDecorationMenu,{}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save"})]})})})})]})},FieldSettings=({entityName:ta,summarySchema:Ln,onFieldUpdate:Ta,onAttributeUpdate:ja})=>{const[La,Fa]=reactExports$1.useState(null),[wl,Pl]=ta.split("/"),pc=getEntity$1(Pl,wl),mc=Array.from(pc?.getUserAttributes().keys()||[]),gc=Ln.fields||[],Vd=mc.filter(kf=>!gc.includes(kf)),Wd=useSensors(useSensor(PointerSensor),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates}));return jsxRuntimeExports$1.jsx(DndContext,{sensors:Wd,collisionDetection:closestCenter,onDragStart:kf=>Fa(kf.active.id),onDragEnd:kf=>{const{active:Pf,over:Nf}=kf;if(Nf&&Pf.id!==Nf.id){const Eh=gc.indexOf(Pf.id),Em=gc.indexOf(Nf.id);Ta(arrayMove(gc,Eh,Em))}Fa(null)},onDragCancel:()=>Fa(null),children:jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(SortableContext,{items:gc,strategy:verticalListSortingStrategy,children:gc.map(kf=>jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:kf,uiAttributeSchema:Ln[kf]||{},onFieldUpdate:Pf=>!Pf&&Ta(gc.filter(Nf=>Nf!==kf)),onAttributeUpdate:ja},kf))}),Vd.length>0&&jsxRuntimeExports$1.jsxs(jsxRuntimeExports$1.Fragment,{children:[jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),Vd.map(kf=>jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:kf,onFieldUpdate:Pf=>Pf&&Ta([...gc,kf]),onAttributeUpdate:ja,disabled:!0},kf))]}),jsxRuntimeExports$1.jsx(DragOverlay,{children:La?jsxRuntimeExports$1.jsx(AttributeField,{entityName:ta,attributeName:La}):null})]})})},InstanceSummarySettings=({entityName:ta,summaryKey:Ln,saveUISpec:Ta})=>{const ja=Qn$1(),La=ja?.[Ln]||{view:{Card:{}}},Fa=La.view.Card,wl=La.actions,Pl=mc=>{if(Ta){const gc={...ja,[Ln]:{...La,actions:mc}};Ta(gc,`Update ${ta} instance summary actions`)}},pc=mc=>{if(Ta){const gc={...ja,[Ln]:{...La,view:{...La.view,Card:mc}}};Ta(gc,`Update ${ta} instance summary`)}};return jsxRuntimeExports$1.jsx(P_,{label:"Instance Summary",defaultOpen:!0,children:jsxRuntimeExports$1.jsxs("div",{className:"flex flex-col gap-3",children:[jsxRuntimeExports$1.jsx(Formik,{initialValues:{layout:Fa.layout||"grid",columns:Fa.columns||2},onSubmit:mc=>{pc({...Fa,...mc})},children:jsxRuntimeExports$1.jsxs(Form$6,{className:"setting-container !gap-3",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-container",children:[jsxRuntimeExports$1.jsx(ButtonSettings,{buttonType:"Edit",buttonSchema:wl?.edit,updateButtonSchema:mc=>Pl({...wl,edit:mc}),entityName:ta}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(ButtonSettings,{buttonType:"Delete",buttonSchema:wl?.delete,updateButtonSchema:mc=>Pl({...wl,delete:mc}),entityName:ta})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(SU,{fieldName:"layout",placeholder:"Layout",options:[{label:"Grid",value:"grid"},{label:"List",value:"list"}]}),jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("span",{className:"label",children:"Columns"}),jsxRuntimeExports$1.jsx(Field,{type:"number",name:"columns",className:"form-input"})]}),jsxRuntimeExports$1.jsx("button",{type:"submit",className:"fx-button",style:{justifyContent:"center"},children:"Save Layout"})]})}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx(FieldSettings,{entityName:ta,summarySchema:Fa,onFieldUpdate:mc=>pc({...Fa,fields:mc}),onAttributeUpdate:(mc,gc)=>{pc({...Fa,[mc]:gc})}})]})})},InstanceViewSettings=({entityName:ta,saveUISpec:Ln})=>{const Ta=Qn$1(),ja=`${ta}.ui.instance`,La=Ta?.[ja],Fa=w6();return La?jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:La.map(wl=>{const Pl=Ta?.[wl];if(!Pl||Array.isArray(Pl))return null;const pc=Pl.view,mc=Object.keys(pc)[0],gc=Fa===wl;if(mc==="Heading")return jsxRuntimeExports$1.jsx(HeaderSettings,{headerSchema:Pl,isTitleRequired:!0,updateHeaderSchema:Wd=>{if(Ln){const kf={...Ta,[wl]:Wd};Ln(kf,"Update instance header settings")}}},wl);if(mc==="Card"&&gc)return jsxRuntimeExports$1.jsx(InstanceSummarySettings,{entityName:ta,summaryKey:wl,saveUISpec:Ln},wl);if((mc==="Table"||mc==="Cards")&&gc){const Wd=wl.match(/^(.*?)\.ui\./),kf=Wd?Wd[1]:"";return jsxRuntimeExports$1.jsx(CollectionViewSettings,{entityName:kf,saveUISpec:Ln,showHeader:!1},wl)}return null})}):jsxRuntimeExports$1.jsx("div",{children:"No instance view settings found for this entity."})};function SortableEntityItem({entity:ta,index:Ln,onVisibilityChange:Ta,uiSpec:ja,onEntityDetailsChange:La}){const[Fa,wl]=reactExports$1.useState(!1),Pl=ja?.[ta.name],{attributes:pc,listeners:mc,setNodeRef:gc,transform:Vd,transition:Wd,isDragging:kf}=useSortable({id:ta.name}),Pf={transform:CSS$1.Transform.toString(Vd),transition:Wd,opacity:kf?.5:1};return jsxRuntimeExports$1.jsxs("div",{ref:gc,style:Pf,className:"setting-toggle",children:[jsxRuntimeExports$1.jsxs("div",{className:"setting-toggle-header flex items-center justify-between",onClick:()=>wl(!Fa),children:[jsxRuntimeExports$1.jsxs("div",{className:"label-with-drag-handle flex items-center gap-2 flex-1 min-w-0",children:[jsxRuntimeExports$1.jsx("div",{...pc,...mc,className:"drag-handle flex-shrink-0",children:jsxRuntimeExports$1.jsx(Icon,{icon:"icon-park-outline:drag"})}),jsxRuntimeExports$1.jsx("div",{className:"min-w-0 flex-1",children:jsxRuntimeExports$1.jsx("p",{className:"font-medium text-font truncate",children:Pl?.displayName||`${ta.name.split("/")[1]}s`})})]}),jsxRuntimeExports$1.jsx("div",{className:"flex items-center gap-2 flex-shrink-0",children:jsxRuntimeExports$1.jsx("div",{className:"flex-shrink-0",onClick:Nf=>Nf.stopPropagation(),children:jsxRuntimeExports$1.jsx(TAe,{isChecked:ta.visible,onChangeHandler:Nf=>Ta(Ln,Nf)})})})]}),jsxRuntimeExports$1.jsx(AnimatePresence,{children:Fa&&jsxRuntimeExports$1.jsx(motion.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2},className:"overflow-hidden",children:jsxRuntimeExports$1.jsx("div",{className:"mt-2",children:jsxRuntimeExports$1.jsx(_Ae,{onEntityDetailsChange:Nf=>La(ta.name,Nf),initialDetails:Pl})})})})]})}const DashboardCustomizationPanel=({schema:ta,uiSpec:Ln,onSave:Ta,saveUISpec:ja})=>{const[La,Fa]=reactExports$1.useState(ta),{onEntityDetailsChange:wl}=useEntityDetailsChange(ja),Pl=useSensors(useSensor(PointerSensor,{activationConstraint:{distance:10}}),useSensor(KeyboardSensor,{coordinateGetter:sortableKeyboardCoordinates})),pc=Wd=>{const kf={...La,title:Wd};Fa(kf),Ta(kf)},mc=Wd=>{const kf={...La,subtitle:Wd};Fa(kf),Ta(kf)},gc=(Wd,kf)=>{const Pf={...La,items:{...La.items,entities:La.items.entities.map((Nf,Eh)=>Eh===Wd?{...Nf,visible:kf}:Nf)}};Fa(Pf),Ta(Pf)},Vd=Wd=>{const{active:kf,over:Pf}=Wd;if(Pf&&kf.id!==Pf.id){const Nf=La.items.entities.findIndex(qg=>qg.name===kf.id),Eh=La.items.entities.findIndex(qg=>qg.name===Pf.id),Em={...La,items:{...La.items,entities:arrayMove(La.items.entities,Nf,Eh)}};Fa(Em),Ta(Em)}};return jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("label",{className:"label",children:"Dashboard Title"}),jsxRuntimeExports$1.jsx("input",{type:"text",value:La.title,onChange:Wd=>pc(Wd.target.value),className:"form-input",placeholder:"Enter dashboard title"})]}),jsxRuntimeExports$1.jsxs("div",{className:"form-item",children:[jsxRuntimeExports$1.jsx("label",{className:"label",children:"Dashboard Subtitle"}),jsxRuntimeExports$1.jsx("input",{type:"text",value:La.subtitle,onChange:Wd=>mc(Wd.target.value),className:"form-input",placeholder:"Enter dashboard subtitle"})]})]}),jsxRuntimeExports$1.jsx("div",{className:"fx-divider"}),jsxRuntimeExports$1.jsx("div",{children:jsxRuntimeExports$1.jsx(DndContext,{sensors:Pl,collisionDetection:closestCenter,onDragEnd:Vd,children:jsxRuntimeExports$1.jsx(SortableContext,{items:La.items.entities.map(Wd=>Wd.name),strategy:verticalListSortingStrategy,children:jsxRuntimeExports$1.jsx("div",{className:"space-y-3",children:La.items.entities.map((Wd,kf)=>jsxRuntimeExports$1.jsx(SortableEntityItem,{entity:Wd,index:kf,onVisibilityChange:gc,uiSpec:Ln,onEntityDetailsChange:wl},Wd.name))})})})})]})},Settings=({saveUISpec:ta})=>{const{isEntity:Ln,getActiveEntityorAgent:Ta}=Of(),{"*":ja}=useParams(),La=ja??"",Fa=La.split("/"),wl=Fa.at(-1)??"",Pl=Fa[1],pc=wl===""||wl==="signin",mc=wl==="signup",gc=wl==="edit"||wl==="new",Vd=Fa.length>3,Wd=wl==="dashboard",kf=Qn$1();return useEntityDetailsChange(ta),jsxRuntimeExports$1.jsxs("div",{className:"border-l border-l-border w-1/5 flex flex-col gap-4 p-4 settings-panel overflow-auto scrollbar-none",children:[pc&&jsxRuntimeExports$1.jsx(Auth,{saveUISpec:ta,authType:"login"}),mc&&jsxRuntimeExports$1.jsx(Auth,{saveUISpec:ta,authType:"signUp"}),gc&&jsxRuntimeExports$1.jsx(FormSettings,{entityName:Ta(La),saveUISpec:ta}),!pc&&!mc&&!gc&&(Wd?jsxRuntimeExports$1.jsx(DashboardCustomizationPanel,{schema:kf?.homeDashboard||{title:"",subtitle:"",items:{entities:[]}},uiSpec:kf,onSave:Pf=>{if(ta&&kf){const Nf={...kf,homeDashboard:Pf};ta(Nf,"Update home dashboard configuration")}},saveUISpec:ta}):Vd?jsxRuntimeExports$1.jsx(InstanceViewSettings,{entityName:Ta(La),saveUISpec:ta}):Ln(`${Pl}/${wl}`)?jsxRuntimeExports$1.jsx(CollectionViewSettings,{entityName:Ta(La),saveUISpec:ta}):null)]})},UI=()=>{const{isAgent:ta}=Of(),{"*":Ln}=useParams(),{pathParts:Ta}=Lt$3(Ln),ja=ta(`${Ta[1]}/${Ta[2]}`),{saveUISpec:La}=useSaveUISpec(),Fa=Qn$1(),wl=b6(),{teamName:Pl,moduleName:pc,githubOrg:mc}=useParams(),gc=useAppStore(Pf=>Pf.user),Vd=useAppStore(Pf=>Pf.appConfig),[Wd,kf]=reactExports$1.useState(null);return reactExports$1.useRef(!1),reactExports$1.useEffect(()=>{{kf("DISABLED");return}},[Pl,pc,mc,gc.GitHub?.Token,Vd.__repoPath]),reactExports$1.useEffect(()=>{typeof window<"u"&&(window.currentReplStatus=Wd,window.getReplStatus=()=>Wd)},[Wd]),!Fa||!Fa.login||!Fa.signUp?null:jsxRuntimeExports$1.jsxs("div",{className:"flex w-full",children:[jsxRuntimeExports$1.jsx(AAe,{schema:Fa,saveUISpec:La}),!wl&&!ja&&jsxRuntimeExports$1.jsx(Settings,{saveUISpec:La})]})},ServeModeInitializer=({children:ta})=>{const{initializeServeMode:Ln,loadingMessage:Ta,error:ja}=useServeMode();useEffectOnce(()=>{Ln()});const La=reactExports$1.useMemo(()=>{const mc=[{key:"connecting",label:"Connecting to local server",completed:!1},{key:"filesystem",label:"Loading file system",completed:!1},{key:"processing",label:"Processing project",completed:!1}];return Ta==="Connecting to local server..."||(Ta==="Loading file system..."?mc[0].completed=!0:Ta==="Processing project..."&&(mc[0].completed=!0,mc[1].completed=!0)),mc},[Ta]),Fa=La.filter(mc=>mc.completed).length,wl=La.findIndex(mc=>!mc.completed),Pl=wl===-1?La.length:wl,pc=Math.min(100,Math.max(5,(Fa+(Ta?.5:0))/La.length*100));return!Ta&&!ja?ta:ja?jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"linear-gradient(128.1deg, #0a142b 16.64%, #02050d 89.76%)"},children:jsxRuntimeExports$1.jsx("div",{className:"bg-secondary backdrop-blur-lg rounded-2xl shadow-card p-8 max-w-md w-full mx-4 border border-border-color animate-slide-in-up",children:jsxRuntimeExports$1.jsxs("div",{className:"text-center",children:[jsxRuntimeExports$1.jsx("div",{className:"w-16 h-16 bg-del-icon rounded-full flex items-center justify-center mx-auto mb-6",children:jsxRuntimeExports$1.jsx("svg",{className:"w-8 h-8 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntimeExports$1.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),jsxRuntimeExports$1.jsx("h2",{className:"text-xl font-semibold text-primary-font mb-3",children:"Initialization Failed"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font mb-6 text-sm",children:ja}),jsxRuntimeExports$1.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports$1.jsx("button",{onClick:()=>Ln(),className:"w-full sure-button px-6 py-3 rounded-lg transition-all duration-200 font-medium shadow-lg hover:shadow-xl transform hover:scale-105",children:"Retry Initialization"}),jsxRuntimeExports$1.jsx("button",{onClick:()=>window.location.reload(),className:"w-full cancel-button px-6 py-3 rounded-lg transition-all duration-200 font-medium",children:"Refresh Page"})]})]})})}):jsxRuntimeExports$1.jsx("div",{className:"flex items-center justify-center min-h-screen",style:{background:"linear-gradient(128.1deg, #0a142b 16.64%, #02050d 89.76%)"},children:jsxRuntimeExports$1.jsxs("div",{className:"bg-secondary backdrop-blur-lg rounded-2xl shadow-card p-8 max-w-lg w-full mx-4 border border-border-color animate-slide-in-up",children:[jsxRuntimeExports$1.jsxs("div",{className:"text-center mb-8",children:[jsxRuntimeExports$1.jsx("div",{className:"relative mb-6 animate-float",children:jsxRuntimeExports$1.jsx("div",{className:"w-20 h-20 bg-blue rounded-full flex items-center justify-center mx-auto animate-pulse-glow",children:jsxRuntimeExports$1.jsx("svg",{className:"w-10 h-10 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsxRuntimeExports$1.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"})})})}),jsxRuntimeExports$1.jsx("h2",{className:"text-2xl font-bold text-primary-font mb-3",children:"Initializing Application"}),jsxRuntimeExports$1.jsx("p",{className:"text-secondary-font text-sm",children:Ta||"Setting up your workspace..."})]}),jsxRuntimeExports$1.jsxs("div",{className:"mb-8",children:[jsxRuntimeExports$1.jsxs("div",{className:"flex justify-between text-sm text-secondary-font mb-3",children:[jsxRuntimeExports$1.jsx("span",{className:"font-medium",children:"Overall Progress"}),jsxRuntimeExports$1.jsxs("span",{className:"font-bold",children:[Math.round(pc),"%"]})]}),jsxRuntimeExports$1.jsx("div",{className:"w-full bg-hover rounded-full h-3 overflow-hidden",children:jsxRuntimeExports$1.jsx("div",{className:"bg-blue h-3 rounded-full transition-all duration-700 ease-out shadow-lg",style:{width:`${pc}%`}})})]}),jsxRuntimeExports$1.jsx("div",{className:"space-y-4",children:La.map((mc,gc)=>jsxRuntimeExports$1.jsxs("div",{className:"flex items-center p-3 rounded-lg transition-all duration-300 hover:highlight-color",children:[jsxRuntimeExports$1.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center mr-4 transition-all duration-300 ${mc.completed?"bg-entity-icon text-white shadow-lg":"bg-secondary text-secondary-font border border-border-color"}`,children:mc.completed?jsxRuntimeExports$1.jsx("svg",{className:"w-5 h-5",fill:"currentColor",viewBox:"0 0 20 20",children:jsxRuntimeExports$1.jsx("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})}):jsxRuntimeExports$1.jsx("span",{className:"text-sm font-bold",children:gc+1})}),jsxRuntimeExports$1.jsxs("div",{className:"flex-1",children:[jsxRuntimeExports$1.jsx("span",{className:`text-sm font-medium transition-all duration-300 ${mc.completed?"text-entity-icon":"text-secondary-font"}`,children:mc.label}),mc.completed&&jsxRuntimeExports$1.jsx("div",{className:"text-xs text-entity-icon mt-1",children:"✓ Completed"})]}),!mc.completed&&gc===Pl&&jsxRuntimeExports$1.jsx("div",{className:"ml-2",children:jsxRuntimeExports$1.jsxs("div",{className:"flex space-x-1",children:[jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-blue rounded-full animate-bounce"}),jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-blue-hover rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),jsxRuntimeExports$1.jsx("div",{className:"w-1.5 h-1.5 bg-primary-font rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]})})]},mc.key))}),jsxRuntimeExports$1.jsx("div",{className:"mt-6 text-center",children:jsxRuntimeExports$1.jsxs("div",{className:"inline-flex items-center text-sm text-secondary-font bg-secondary px-4 py-2 rounded-full border border-border-color",children:[jsxRuntimeExports$1.jsx("div",{className:"animate-pulse mr-2",children:jsxRuntimeExports$1.jsx("div",{className:"w-2 h-2 bg-blue rounded-full"})}),jsxRuntimeExports$1.jsx("span",{className:"font-medium",children:"Loading..."})]})})]})})},AppContent=()=>jsxRuntimeExports$1.jsx(ServeModeInitializer,{children:jsxRuntimeExports$1.jsx(Outlet,{})}),router=createBrowserRouter([{path:"/",element:jsxRuntimeExports$1.jsx(AppContent,{}),children:[{path:"/",element:jsxRuntimeExports$1.jsx(AuthLayout,{}),children:[{path:"/",id:"signin",element:jsxRuntimeExports$1.jsx(SignIn,{})},{path:"/signup",id:"signup",element:jsxRuntimeExports$1.jsx(SignUp,{})},{path:"/forgotPassword",id:"forgot-password",element:jsxRuntimeExports$1.jsx(ForgotPassword,{})},{path:"/recoverPassword",id:"recover-password",element:jsxRuntimeExports$1.jsx(RecoverPassword,{})}]},{path:"/",element:jsxRuntimeExports$1.jsx(DashboardLayout,{}),children:[{path:"/home",id:"home",element:jsxRuntimeExports$1.jsx(Home,{})},{path:"/deployment/:deploymentId",id:"deployment-detail",element:jsxRuntimeExports$1.jsx(DeploymentDetail,{})},{path:"/hub",id:"marketplace",element:jsxRuntimeExports$1.jsx(Marketplace,{})},{path:"/configuration",id:"user-configuration",element:jsxRuntimeExports$1.jsx(UserConfiguration,{isModal:!1})},{path:"/design/dashboard",id:"teams",element:jsxRuntimeExports$1.jsx(Teams,{})},{path:"/design/integrations",id:"integrations",element:jsxRuntimeExports$1.jsx(Integrations,{})},{path:"/design/documents",id:"documents",element:jsxRuntimeExports$1.jsx(Documents,{})},{path:"/design/llms",id:"llms",element:jsxRuntimeExports$1.jsx(LLM,{})}]},{path:"/",element:jsxRuntimeExports$1.jsx(DesignLayout,{}),children:[{path:"/design/data-model/:githubOrg/:teamName/:moduleName",id:"data-model",element:jsxRuntimeExports$1.jsx(DataModel,{})},{path:"/design/marketplace/:githubOrg/:modelName/:moduleName",id:"marketplace-data-model",element:jsxRuntimeExports$1.jsx(DataModel,{})},{path:"/design/workflow/:githubOrg/:teamName/:moduleName",id:"workflow",element:jsxRuntimeExports$1.jsx(Workflow,{})},{path:"/design/security/:githubOrg/:teamName/:moduleName",id:"security",element:jsxRuntimeExports$1.jsx(Security,{})},{path:"/design/agents/:githubOrg/:teamName/:moduleName",id:"agents",element:jsxRuntimeExports$1.jsx(AgentFlow,{})},{path:"/design/ui/:githubOrg/:teamName/:moduleName/*",id:"ui",element:jsxRuntimeExports$1.jsx(UI,{})},{path:"/design/settings/:githubOrg/:teamName/:moduleName",id:"settings",element:jsxRuntimeExports$1.jsx(Settings$1,{})}]},{path:"*",id:"not-found",element:jsxRuntimeExports$1.jsx(NotFound,{})}]}]);function App(){return jsxRuntimeExports$1.jsx(PostHogProvider,{client:Do,children:jsxRuntimeExports$1.jsxs("div",{className:"relative h-screen","data-theme":"default",children:[jsxRuntimeExports$1.jsx("img",{src:"/assets/bg-gradient.png",alt:"",className:"bg-gradient"}),jsxRuntimeExports$1.jsx(RouterProvider,{router}),jsxRuntimeExports$1.jsx(Lt$1,{position:"top-center",autoClose:2e3,hideProgressBar:!0,newestOnTop:!1,closeOnClick:!0,rtl:!1,pauseOnFocusLoss:!1,pauseOnHover:!1,draggable:!1,theme:"dark"})]})})}var cacheEventTypes=["added","removed","updated"];function isCacheEventType(ta){return cacheEventTypes.includes(ta)}async function persistQueryClientRestore({queryClient:ta,persister:Ln,maxAge:Ta=1e3*60*60*24,buster:ja="",hydrateOptions:La}){try{const Fa=await Ln.restoreClient();if(Fa)if(Fa.timestamp){const wl=Date.now()-Fa.timestamp>Ta,Pl=Fa.buster!==ja;if(wl||Pl)return Ln.removeClient();hydrate(ta,Fa.clientState,La)}else return Ln.removeClient()}catch(Fa){throw await Ln.removeClient(),Fa}}async function persistQueryClientSave({queryClient:ta,persister:Ln,buster:Ta="",dehydrateOptions:ja}){const La={buster:Ta,timestamp:Date.now(),clientState:dehydrate(ta,ja)};await Ln.persistClient(La)}function persistQueryClientSubscribe(ta){const Ln=ta.queryClient.getQueryCache().subscribe(ja=>{isCacheEventType(ja.type)&&persistQueryClientSave(ta)}),Ta=ta.queryClient.getMutationCache().subscribe(ja=>{isCacheEventType(ja.type)&&persistQueryClientSave(ta)});return()=>{Ln(),Ta()}}function persistQueryClient(ta){let Ln=!1,Ta;const ja=()=>{Ln=!0,Ta?.()},La=persistQueryClientRestore(ta).then(()=>{Ln||(Ta=persistQueryClientSubscribe(ta))});return[ja,La]}console.log("IS_PLAYGROUND:",!1);console.log("IS_LOCAL_MODE:",!0);console.log("IS_REGULAR_MODE:",!1);console.log("POSTHOG_ENABLED:",!1);const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:120*1e3,gcTime:300*1e3,retry:(ta,Ln)=>Ln?.response?.status===401||Ln?.response?.status===403||Ln?.response?.status>=400&&Ln?.response?.status<500?!1:ta<3,retryDelay:ta=>Math.min(1e3*2**ta,3e4),refetchOnWindowFocus:!0,refetchOnReconnect:!0,refetchOnMount:!0}}}),persister={persistClient:async ta=>{const Ln=localStorage.getItem("workspace_id")||"default",Ta=localStorage.getItem("user_profile_id")||"default",ja={clientState:ta,timestamp:Date.now(),workspaceId:Ln,userProfileId:Ta};localStorage.setItem("agentlang-query-cache",JSON.stringify(ja))},restoreClient:async()=>{try{const ta=localStorage.getItem("agentlang-query-cache");if(!ta)return;const Ln=JSON.parse(ta),Ta=localStorage.getItem("workspace_id")||"default",ja=localStorage.getItem("user_profile_id")||"default";if(Ln.workspaceId!==Ta||Ln.userProfileId!==ja){console.warn("Workspace or user profile changed, invalidating query cache"),localStorage.removeItem("agentlang-query-cache");return}const La=720*60*1e3;if(Date.now()-Ln.timestamp>La){console.warn("Query cache expired, clearing"),localStorage.removeItem("agentlang-query-cache");return}return Ln.clientState}catch(ta){console.warn("Failed to restore query cache:",ta),localStorage.removeItem("agentlang-query-cache");return}},removeClient:async()=>{localStorage.removeItem("agentlang-query-cache")}};persistQueryClient({queryClient,persister,maxAge:1440*60*1e3});typeof window<"u"&&(window.replService=replService,window.entityReplService=replService);const rootElement=document.getElementById("root");if(!rootElement)throw new Error("Root element not found");async function initializeAndRenderApp(){try{await initializeAgentLang();const ta=document.getElementById("root");if(!ta)throw new Error("Root element not found");clientExports.createRoot(ta).render(jsxRuntimeExports$1.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports$1.jsx(App,{})}))}catch(ta){console.error("❌ Failed to initialize app:",ta);const Ln=document.getElementById("root");Ln&&(Ln.innerHTML=`
|
|
35648
35648
|
<div style="padding: 20px; color: red; font-family: monospace;">
|
|
35649
35649
|
<h2>🚨 AgentLang Initialization Failed</h2>
|
|
35650
35650
|
<p>Error: ${ta instanceof Error?ta.message:String(ta)}</p>
|