@ensofinance/checkout-widget 0.1.6 → 0.1.7

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.
@@ -225,7 +225,7 @@ ${JSON.stringify(i.slice(-10),null,2)}. `:"",s="\nCatch the `SendTransactionErro
225
225
  ${r}. `+o+s;break;case"simulate":a=`Simulation failed.
226
226
  Message: ${r}.
227
227
  `+o+s;break;default:a=`Unknown action '${(l=>l)(e)}'`}super(a),this.signature=void 0,this.transactionMessage=void 0,this.transactionLogs=void 0,this.signature=n,this.transactionMessage=r,this.transactionLogs=i||void 0}get transactionError(){return{message:this.transactionMessage,logs:Array.isArray(this.transactionLogs)?this.transactionLogs:void 0}}get logs(){const e=this.transactionLogs;if(!(e!=null&&typeof e=="object"&&"then"in e))return e}async getLogs(e){return Array.isArray(this.transactionLogs)||(this.transactionLogs=new Promise((n,r)=>{e.getTransaction(this.signature).then(i=>{if(i&&i.meta&&i.meta.logMessages){const o=i.meta.logMessages;this.transactionLogs=o,n(o)}else r(new Error("Log messages not found"))}).catch(r)})),await this.transactionLogs}}class Ee extends Error{constructor({code:e,message:n,data:r},i){super(i!=null?`${i}: ${n}`:n),this.code=void 0,this.data=void 0,this.code=e,this.data=r,this.name="SolanaJSONRPCError"}}function Xs(t){return new Promise(e=>setTimeout(e,t))}const l9=q.nu64("lamportsPerSignature"),eE=q.struct([q.u32("version"),q.u32("state"),ze("authorizedPubkey"),ze("nonce"),q.struct([l9],"feeCalculator")]);eE.span;class rp{constructor(e){this.authorizedPubkey=void 0,this.nonce=void 0,this.feeCalculator=void 0,this.authorizedPubkey=e.authorizedPubkey,this.nonce=e.nonce,this.feeCalculator=e.feeCalculator}static fromAccountData(e){const n=eE.decode(Gs(e),0);return new rp({authorizedPubkey:new Re(n.authorizedPubkey),nonce:new Re(n.nonce).toString(),feeCalculator:n.feeCalculator})}}function Zs(t){const e=q.blob(8,t),n=e.decode.bind(e),r=e.encode.bind(e),i=e,o=nH();return i.decode=(s,a)=>{const l=n(s,a);return o.decode(l)},i.encode=(s,a,l)=>{const c=o.encode(s);return r(c,a,l)},i}Object.freeze({Create:{index:0,layout:q.struct([q.u32("instruction"),q.ns64("lamports"),q.ns64("space"),ze("programId")])},Assign:{index:1,layout:q.struct([q.u32("instruction"),ze("programId")])},Transfer:{index:2,layout:q.struct([q.u32("instruction"),Zs("lamports")])},CreateWithSeed:{index:3,layout:q.struct([q.u32("instruction"),ze("base"),Ys("seed"),q.ns64("lamports"),q.ns64("space"),ze("programId")])},AdvanceNonceAccount:{index:4,layout:q.struct([q.u32("instruction")])},WithdrawNonceAccount:{index:5,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},InitializeNonceAccount:{index:6,layout:q.struct([q.u32("instruction"),ze("authorized")])},AuthorizeNonceAccount:{index:7,layout:q.struct([q.u32("instruction"),ze("authorized")])},Allocate:{index:8,layout:q.struct([q.u32("instruction"),q.ns64("space")])},AllocateWithSeed:{index:9,layout:q.struct([q.u32("instruction"),ze("base"),Ys("seed"),q.ns64("space"),ze("programId")])},AssignWithSeed:{index:10,layout:q.struct([q.u32("instruction"),ze("base"),Ys("seed"),ze("programId")])},TransferWithSeed:{index:11,layout:q.struct([q.u32("instruction"),Zs("lamports"),Ys("seed"),ze("programId")])},UpgradeNonceAccount:{index:12,layout:q.struct([q.u32("instruction")])}}),new Re("11111111111111111111111111111111"),new Re("BPFLoader2111111111111111111111111111111111");function c9(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var ip,tE;function u9(){if(tE)return ip;tE=1;var t=Object.prototype.toString,e=Object.keys||function(r){var i=[];for(var o in r)i.push(o);return i};function n(r,i){var o,s,a,l,c,u,h;if(r===!0)return"true";if(r===!1)return"false";switch(typeof r){case"object":if(r===null)return null;if(r.toJSON&&typeof r.toJSON=="function")return n(r.toJSON(),i);if(h=t.call(r),h==="[object Array]"){for(a="[",s=r.length-1,o=0;o<s;o++)a+=n(r[o],!0)+",";return s>-1&&(a+=n(r[o],!0)),a+"]"}else if(h==="[object Object]"){for(l=e(r).sort(),s=l.length,a="",o=0;o<s;)c=l[o],u=n(r[c],!1),u!==void 0&&(a&&(a+=","),a+=JSON.stringify(c)+":"+u),o++;return"{"+a+"}"}else return JSON.stringify(r);case"function":case"undefined":return i?null:void 0;case"string":return JSON.stringify(r);default:return isFinite(r)?r:null}}return ip=function(r){var i=n(r,!1);if(i!==void 0)return""+i},ip}var d9=u9(),nE=c9(d9);const Cl=32;function op(t){let e=0;for(;t>1;)t/=2,e++;return e}function h9(t){return t===0?1:(t--,t|=t>>1,t|=t>>2,t|=t>>4,t|=t>>8,t|=t>>16,t|=t>>32,t+1)}class f9{constructor(e,n,r,i,o){this.slotsPerEpoch=void 0,this.leaderScheduleSlotOffset=void 0,this.warmup=void 0,this.firstNormalEpoch=void 0,this.firstNormalSlot=void 0,this.slotsPerEpoch=e,this.leaderScheduleSlotOffset=n,this.warmup=r,this.firstNormalEpoch=i,this.firstNormalSlot=o}getEpoch(e){return this.getEpochAndSlotIndex(e)[0]}getEpochAndSlotIndex(e){if(e<this.firstNormalSlot){const n=op(h9(e+Cl+1))-op(Cl)-1,r=this.getSlotsInEpoch(n),i=e-(r-Cl);return[n,i]}else{const n=e-this.firstNormalSlot,r=Math.floor(n/this.slotsPerEpoch),i=this.firstNormalEpoch+r,o=n%this.slotsPerEpoch;return[i,o]}}getFirstSlotInEpoch(e){return e<=this.firstNormalEpoch?(Math.pow(2,e)-1)*Cl:(e-this.firstNormalEpoch)*this.slotsPerEpoch+this.firstNormalSlot}getLastSlotInEpoch(e){return this.getFirstSlotInEpoch(e)+this.getSlotsInEpoch(e)-1}getSlotsInEpoch(e){return e<this.firstNormalEpoch?Math.pow(2,e+op(Cl)):this.slotsPerEpoch}}var g9=globalThis.fetch;class p9 extends BH{constructor(e,n,r){const i=o=>{const s=LH(o,{autoconnect:!0,max_reconnects:5,reconnect:!0,reconnect_interval:1e3,...n});return"socket"in s?this.underlyingSocket=s.socket:this.underlyingSocket=s,s};super(i,e,n,r),this.underlyingSocket=void 0}call(...e){var r;const n=(r=this.underlyingSocket)==null?void 0:r.readyState;return n===1?super.call(...e):Promise.reject(new Error("Tried to call a JSON-RPC method `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+n+")"))}notify(...e){var r;const n=(r=this.underlyingSocket)==null?void 0:r.readyState;return n===1?super.notify(...e):Promise.reject(new Error("Tried to send a JSON-RPC notification `"+e[0]+"` but the socket was not `CONNECTING` or `OPEN` (`readyState` was "+n+")"))}}function m9(t,e){let n;try{n=t.layout.decode(e)}catch(r){throw new Error("invalid instruction; "+r)}if(n.typeIndex!==t.index)throw new Error(`invalid account data; account type mismatch ${n.typeIndex} != ${t.index}`);return n}const rE=56;class iE{constructor(e){this.key=void 0,this.state=void 0,this.key=e.key,this.state=e.state}isActive(){const e=BigInt("0xffffffffffffffff");return this.state.deactivationSlot===e}static deserialize(e){const n=m9(v9,e),r=e.length-rE;pt(r>=0,"lookup table is invalid"),pt(r%32===0,"lookup table is invalid");const i=r/32,{addresses:o}=q.struct([q.seq(ze(),i,"addresses")]).decode(e.slice(rE));return{deactivationSlot:n.deactivationSlot,lastExtendedSlot:n.lastExtendedSlot,lastExtendedSlotStartIndex:n.lastExtendedStartIndex,authority:n.authority.length!==0?new Re(n.authority[0]):void 0,addresses:o.map(s=>new Re(s))}}}const v9={index:1,layout:q.struct([q.u32("typeIndex"),Zs("deactivationSlot"),q.nu64("lastExtendedSlot"),q.u8("lastExtendedStartIndex"),q.u8(),q.seq(ze(),q.offset(q.u8(),-1),"authority")])},y9=/^[^:]+:\/\/([^:[]+|\[[^\]]+\])(:\d+)?(.*)/i;function b9(t){const e=t.match(y9);if(e==null)throw TypeError(`Failed to validate endpoint URL \`${t}\``);const[n,r,i,o]=e,s=t.startsWith("https:")?"wss:":"ws:",a=i==null?null:parseInt(i.slice(1),10),l=a==null?"":`:${a+1}`;return`${s}//${r}${l}${o}`}const yt=El(Wg(Re),de(),t=>new Re(t)),oE=Hg([de(),vt("base64")]),sp=El(Wg($e.Buffer),oE,t=>$e.Buffer.from(t[0],"base64")),_9=30*1e3;function x9(t){if(/^https?:/.test(t)===!1)throw new TypeError("Endpoint URL must start with `http:` or `https:`.");return t}function ct(t){let e,n;if(typeof t=="string")e=t;else if(t){const{commitment:r,...i}=t;e=r,n=i}return{commitment:e,config:n}}function sE(t){return t.map(e=>{var n;return"memcmp"in e?{...e,memcmp:{...e.memcmp,encoding:(n=e.memcmp.encoding)!=null?n:"base58"}}:e})}function aE(t){return Nn([ce({jsonrpc:vt("2.0"),id:de(),result:t}),ce({jsonrpc:vt("2.0"),id:de(),error:ce({code:Hs(),message:de(),data:Ce(cH())})})])}const w9=aE(Hs());function Fe(t){return El(aE(t),w9,e=>"error"in e?e:{...e,result:he(e.result,t)})}function Ct(t){return Fe(ce({context:ce({slot:ne()}),value:t}))}function nd(t){return ce({context:ce({slot:ne()}),value:t})}function ap(t,e){return t===0?new Il({header:e.header,staticAccountKeys:e.accountKeys.map(n=>new Re(n)),recentBlockhash:e.recentBlockhash,compiledInstructions:e.instructions.map(n=>({programIdIndex:n.programIdIndex,accountKeyIndexes:n.accounts,data:mn.decode(n.data)})),addressTableLookups:e.addressTableLookups}):new Ii(e)}const E9=ce({foundation:ne(),foundationTerm:ne(),initial:ne(),taper:ne(),terminal:ne()}),S9=Fe(ge(pe(ce({epoch:ne(),effectiveSlot:ne(),amount:ne(),postBalance:ne(),commission:Ce(pe(ne()))})))),I9=ge(ce({slot:ne(),prioritizationFee:ne()})),C9=ce({total:ne(),validator:ne(),foundation:ne(),epoch:ne()}),A9=ce({epoch:ne(),slotIndex:ne(),slotsInEpoch:ne(),absoluteSlot:ne(),blockHeight:Ce(ne()),transactionCount:Ce(ne())}),O9=ce({slotsPerEpoch:ne(),leaderScheduleSlotOffset:ne(),warmup:Jr(),firstNormalEpoch:ne(),firstNormalSlot:ne()}),k9=Tw(de(),ge(ne())),$o=pe(Nn([ce({}),de()])),T9=ce({err:$o}),R9=vt("receivedSignature"),N9=ce({"solana-core":de(),"feature-set":Ce(ne())}),P9=ce({program:de(),programId:yt,parsed:Hs()}),L9=ce({programId:yt,accounts:ge(yt),data:de()}),lE=Ct(ce({err:pe(Nn([ce({}),de()])),logs:pe(ge(de())),accounts:Ce(pe(ge(pe(ce({executable:Jr(),owner:de(),lamports:ne(),data:ge(de()),rentEpoch:Ce(ne())}))))),unitsConsumed:Ce(ne()),returnData:Ce(pe(ce({programId:de(),data:Hg([de(),vt("base64")])}))),innerInstructions:Ce(pe(ge(ce({index:ne(),instructions:ge(Nn([P9,L9]))}))))})),M9=Ct(ce({byIdentity:Tw(de(),ge(ne())),range:ce({firstSlot:ne(),lastSlot:ne()})}));function B9(t,e,n,r,i,o){const s=n||g9;let a;o!=null&&console.warn("You have supplied an `httpAgent` when creating a `Connection` in a browser environment.It has been ignored; `httpAgent` is only used in Node environments.");let l;return r&&(l=async(u,h)=>{const p=await new Promise((g,b)=>{try{r(u,h,(m,x)=>g([m,x]))}catch(m){b(m)}});return await s(...p)}),new NH(async(u,h)=>{const p={method:"POST",body:u,agent:a,headers:Object.assign({"Content-Type":"application/json"},e||{},Bj)};try{let g=5,b,m=500;for(;l?b=await l(t,p):b=await s(t,p),!(b.status!==429||i===!0||(g-=1,g===0));)console.error(`Server responded with ${b.status} ${b.statusText}. Retrying after ${m}ms delay...`),await Xs(m),m*=2;const x=await b.text();b.ok?h(null,x):h(new Error(`${b.status} ${b.statusText}: ${x}`))}catch(g){g instanceof Error&&h(g)}},{})}function F9(t){return(e,n)=>new Promise((r,i)=>{t.request(e,n,(o,s)=>{if(o){i(o);return}r(s)})})}function D9(t){return e=>new Promise((n,r)=>{e.length===0&&n([]);const i=e.map(o=>t.request(o.methodName,o.args));t.request(i,(o,s)=>{if(o){r(o);return}n(s)})})}const V9=Fe(E9),$9=Fe(C9),z9=Fe(I9),U9=Fe(A9),W9=Fe(O9),H9=Fe(k9),j9=Fe(ne()),q9=Ct(ce({total:ne(),circulating:ne(),nonCirculating:ne(),nonCirculatingAccounts:ge(yt)})),lp=ce({amount:de(),uiAmount:pe(ne()),decimals:ne(),uiAmountString:Ce(de())}),G9=Ct(ge(ce({address:yt,amount:de(),uiAmount:pe(ne()),decimals:ne(),uiAmountString:Ce(de())}))),K9=Ct(ge(ce({pubkey:yt,account:ce({executable:Jr(),owner:yt,lamports:ne(),data:sp,rentEpoch:ne()})}))),cp=ce({program:de(),parsed:Hs(),space:ne()}),Y9=Ct(ge(ce({pubkey:yt,account:ce({executable:Jr(),owner:yt,lamports:ne(),data:cp,rentEpoch:ne()})}))),X9=Ct(ge(ce({lamports:ne(),address:yt}))),Al=ce({executable:Jr(),owner:yt,lamports:ne(),data:sp,rentEpoch:ne()}),Z9=ce({pubkey:yt,account:Al}),J9=El(Nn([Wg($e.Buffer),cp]),Nn([oE,cp]),t=>Array.isArray(t)?he(t,sp):t),up=ce({executable:Jr(),owner:yt,lamports:ne(),data:J9,rentEpoch:ne()}),Q9=ce({pubkey:yt,account:up}),ej=ce({state:Nn([vt("active"),vt("inactive"),vt("activating"),vt("deactivating")]),active:ne(),inactive:ne()}),tj=Fe(ge(ce({signature:de(),slot:ne(),err:$o,memo:pe(de()),blockTime:Ce(pe(ne()))}))),nj=Fe(ge(ce({signature:de(),slot:ne(),err:$o,memo:pe(de()),blockTime:Ce(pe(ne()))}))),rj=ce({subscription:ne(),result:nd(Al)}),ij=ce({pubkey:yt,account:Al}),oj=ce({subscription:ne(),result:nd(ij)}),sj=ce({parent:ne(),slot:ne(),root:ne()}),aj=ce({subscription:ne(),result:sj}),lj=Nn([ce({type:Nn([vt("firstShredReceived"),vt("completed"),vt("optimisticConfirmation"),vt("root")]),slot:ne(),timestamp:ne()}),ce({type:vt("createdBank"),parent:ne(),slot:ne(),timestamp:ne()}),ce({type:vt("frozen"),slot:ne(),timestamp:ne(),stats:ce({numTransactionEntries:ne(),numSuccessfulTransactions:ne(),numFailedTransactions:ne(),maxTransactionsPerEntry:ne()})}),ce({type:vt("dead"),slot:ne(),timestamp:ne(),err:de()})]),cj=ce({subscription:ne(),result:lj}),uj=ce({subscription:ne(),result:nd(Nn([T9,R9]))}),dj=ce({subscription:ne(),result:ne()}),hj=ce({pubkey:de(),gossip:pe(de()),tpu:pe(de()),rpc:pe(de()),version:pe(de())}),cE=ce({votePubkey:de(),nodePubkey:de(),activatedStake:ne(),epochVoteAccount:Jr(),epochCredits:ge(Hg([ne(),ne(),ne()])),commission:ne(),lastVote:ne(),rootSlot:pe(ne())}),fj=Fe(ce({current:ge(cE),delinquent:ge(cE)})),gj=Nn([vt("processed"),vt("confirmed"),vt("finalized")]),pj=ce({slot:ne(),confirmations:pe(ne()),err:$o,confirmationStatus:Ce(gj)}),mj=Ct(ge(pe(pj))),vj=Fe(ne()),uE=ce({accountKey:yt,writableIndexes:ge(ne()),readonlyIndexes:ge(ne())}),dp=ce({signatures:ge(de()),message:ce({accountKeys:ge(de()),header:ce({numRequiredSignatures:ne(),numReadonlySignedAccounts:ne(),numReadonlyUnsignedAccounts:ne()}),instructions:ge(ce({accounts:ge(ne()),data:de(),programIdIndex:ne()})),recentBlockhash:de(),addressTableLookups:Ce(ge(uE))})}),dE=ce({pubkey:yt,signer:Jr(),writable:Jr(),source:Ce(Nn([vt("transaction"),vt("lookupTable")]))}),hE=ce({accountKeys:ge(dE),signatures:ge(de())}),fE=ce({parsed:Hs(),program:de(),programId:yt}),gE=ce({accounts:ge(yt),data:de(),programId:yt}),yj=Nn([gE,fE]),bj=Nn([ce({parsed:Hs(),program:de(),programId:de()}),ce({accounts:ge(de()),data:de(),programId:de()})]),pE=El(yj,bj,t=>"accounts"in t?he(t,gE):he(t,fE)),mE=ce({signatures:ge(de()),message:ce({accountKeys:ge(dE),instructions:ge(pE),recentBlockhash:de(),addressTableLookups:Ce(pe(ge(uE)))})}),rd=ce({accountIndex:ne(),mint:de(),owner:Ce(de()),programId:Ce(de()),uiTokenAmount:lp}),vE=ce({writable:ge(yt),readonly:ge(yt)}),id=ce({err:$o,fee:ne(),innerInstructions:Ce(pe(ge(ce({index:ne(),instructions:ge(ce({accounts:ge(ne()),data:de(),programIdIndex:ne()}))})))),preBalances:ge(ne()),postBalances:ge(ne()),logMessages:Ce(pe(ge(de()))),preTokenBalances:Ce(pe(ge(rd))),postTokenBalances:Ce(pe(ge(rd))),loadedAddresses:Ce(vE),computeUnitsConsumed:Ce(ne()),costUnits:Ce(ne())}),hp=ce({err:$o,fee:ne(),innerInstructions:Ce(pe(ge(ce({index:ne(),instructions:ge(pE)})))),preBalances:ge(ne()),postBalances:ge(ne()),logMessages:Ce(pe(ge(de()))),preTokenBalances:Ce(pe(ge(rd))),postTokenBalances:Ce(pe(ge(rd))),loadedAddresses:Ce(vE),computeUnitsConsumed:Ce(ne()),costUnits:Ce(ne())}),Js=Nn([vt(0),vt("legacy")]),zo=ce({pubkey:de(),lamports:ne(),postBalance:pe(ne()),rewardType:pe(de()),commission:Ce(pe(ne()))}),_j=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),transactions:ge(ce({transaction:dp,meta:pe(id),version:Ce(Js)})),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),xj=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),wj=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),transactions:ge(ce({transaction:hE,meta:pe(id),version:Ce(Js)})),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),Ej=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),transactions:ge(ce({transaction:mE,meta:pe(hp),version:Ce(Js)})),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),Sj=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),transactions:ge(ce({transaction:hE,meta:pe(hp),version:Ce(Js)})),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),Ij=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),rewards:Ce(ge(zo)),blockTime:pe(ne()),blockHeight:pe(ne())}))),Cj=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),transactions:ge(ce({transaction:dp,meta:pe(id)})),rewards:Ce(ge(zo)),blockTime:pe(ne())}))),yE=Fe(pe(ce({blockhash:de(),previousBlockhash:de(),parentSlot:ne(),signatures:ge(de()),blockTime:pe(ne())}))),fp=Fe(pe(ce({slot:ne(),meta:pe(id),blockTime:Ce(pe(ne())),transaction:dp,version:Ce(Js)}))),od=Fe(pe(ce({slot:ne(),transaction:mE,meta:pe(hp),blockTime:Ce(pe(ne())),version:Ce(Js)}))),Aj=Ct(ce({blockhash:de(),lastValidBlockHeight:ne()})),Oj=Ct(Jr()),kj=ce({slot:ne(),numTransactions:ne(),numSlots:ne(),samplePeriodSecs:ne()}),Tj=Fe(ge(kj)),Rj=Ct(pe(ce({feeCalculator:ce({lamportsPerSignature:ne()})}))),Nj=Fe(de()),Pj=Fe(de()),Lj=ce({err:$o,logs:ge(de()),signature:de()}),Mj=ce({result:nd(Lj),subscription:ne()}),Bj={"solana-client":"js/1.0.0-maintenance"};class Fj{constructor(e,n){this._commitment=void 0,this._confirmTransactionInitialTimeout=void 0,this._rpcEndpoint=void 0,this._rpcWsEndpoint=void 0,this._rpcClient=void 0,this._rpcRequest=void 0,this._rpcBatchRequest=void 0,this._rpcWebSocket=void 0,this._rpcWebSocketConnected=!1,this._rpcWebSocketHeartbeat=null,this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketGeneration=0,this._disableBlockhashCaching=!1,this._pollingBlockhash=!1,this._blockhashInfo={latestBlockhash:null,lastFetch:0,transactionSignatures:[],simulatedSignatures:[]},this._nextClientSubscriptionId=0,this._subscriptionDisposeFunctionsByClientSubscriptionId={},this._subscriptionHashByClientSubscriptionId={},this._subscriptionStateChangeCallbacksByHash={},this._subscriptionCallbacksByServerSubscriptionId={},this._subscriptionsByHash={},this._subscriptionsAutoDisposedByRpc=new Set,this.getBlockHeight=(()=>{const c={};return async u=>{var m;const{commitment:h,config:p}=ct(u),g=this._buildArgs([],h,void 0,p),b=nE(g);return c[b]=(m=c[b])!=null?m:(async()=>{try{const x=await this._rpcRequest("getBlockHeight",g),I=he(x,Fe(ne()));if("error"in I)throw new Ee(I.error,"failed to get block height information");return I.result}finally{delete c[b]}})(),await c[b]}})();let r,i,o,s,a,l;n&&typeof n=="string"?this._commitment=n:n&&(this._commitment=n.commitment,this._confirmTransactionInitialTimeout=n.confirmTransactionInitialTimeout,r=n.wsEndpoint,i=n.httpHeaders,o=n.fetch,s=n.fetchMiddleware,a=n.disableRetryOnRateLimit,l=n.httpAgent),this._rpcEndpoint=x9(e),this._rpcWsEndpoint=r||b9(e),this._rpcClient=B9(e,i,o,s,a,l),this._rpcRequest=F9(this._rpcClient),this._rpcBatchRequest=D9(this._rpcClient),this._rpcWebSocket=new p9(this._rpcWsEndpoint,{autoconnect:!1,max_reconnects:1/0}),this._rpcWebSocket.on("open",this._wsOnOpen.bind(this)),this._rpcWebSocket.on("error",this._wsOnError.bind(this)),this._rpcWebSocket.on("close",this._wsOnClose.bind(this)),this._rpcWebSocket.on("accountNotification",this._wsOnAccountNotification.bind(this)),this._rpcWebSocket.on("programNotification",this._wsOnProgramAccountNotification.bind(this)),this._rpcWebSocket.on("slotNotification",this._wsOnSlotNotification.bind(this)),this._rpcWebSocket.on("slotsUpdatesNotification",this._wsOnSlotUpdatesNotification.bind(this)),this._rpcWebSocket.on("signatureNotification",this._wsOnSignatureNotification.bind(this)),this._rpcWebSocket.on("rootNotification",this._wsOnRootNotification.bind(this)),this._rpcWebSocket.on("logsNotification",this._wsOnLogsNotification.bind(this))}get commitment(){return this._commitment}get rpcEndpoint(){return this._rpcEndpoint}async getBalanceAndContext(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgs([e.toBase58()],r,void 0,i),s=await this._rpcRequest("getBalance",o),a=he(s,Ct(ne()));if("error"in a)throw new Ee(a.error,`failed to get balance for ${e.toBase58()}`);return a.result}async getBalance(e,n){return await this.getBalanceAndContext(e,n).then(r=>r.value).catch(r=>{throw new Error("failed to get balance of account "+e.toBase58()+": "+r)})}async getBlockTime(e){const n=await this._rpcRequest("getBlockTime",[e]),r=he(n,Fe(pe(ne())));if("error"in r)throw new Ee(r.error,`failed to get block time for slot ${e}`);return r.result}async getMinimumLedgerSlot(){const e=await this._rpcRequest("minimumLedgerSlot",[]),n=he(e,Fe(ne()));if("error"in n)throw new Ee(n.error,"failed to get minimum ledger slot");return n.result}async getFirstAvailableBlock(){const e=await this._rpcRequest("getFirstAvailableBlock",[]),n=he(e,j9);if("error"in n)throw new Ee(n.error,"failed to get first available block");return n.result}async getSupply(e){let n={};typeof e=="string"?n={commitment:e}:e?n={...e,commitment:e&&e.commitment||this.commitment}:n={commitment:this.commitment};const r=await this._rpcRequest("getSupply",[n]),i=he(r,q9);if("error"in i)throw new Ee(i.error,"failed to get supply");return i.result}async getTokenSupply(e,n){const r=this._buildArgs([e.toBase58()],n),i=await this._rpcRequest("getTokenSupply",r),o=he(i,Ct(lp));if("error"in o)throw new Ee(o.error,"failed to get token supply");return o.result}async getTokenAccountBalance(e,n){const r=this._buildArgs([e.toBase58()],n),i=await this._rpcRequest("getTokenAccountBalance",r),o=he(i,Ct(lp));if("error"in o)throw new Ee(o.error,"failed to get token account balance");return o.result}async getTokenAccountsByOwner(e,n,r){const{commitment:i,config:o}=ct(r);let s=[e.toBase58()];"mint"in n?s.push({mint:n.mint.toBase58()}):s.push({programId:n.programId.toBase58()});const a=this._buildArgs(s,i,"base64",o),l=await this._rpcRequest("getTokenAccountsByOwner",a),c=he(l,K9);if("error"in c)throw new Ee(c.error,`failed to get token accounts owned by account ${e.toBase58()}`);return c.result}async getParsedTokenAccountsByOwner(e,n,r){let i=[e.toBase58()];"mint"in n?i.push({mint:n.mint.toBase58()}):i.push({programId:n.programId.toBase58()});const o=this._buildArgs(i,r,"jsonParsed"),s=await this._rpcRequest("getTokenAccountsByOwner",o),a=he(s,Y9);if("error"in a)throw new Ee(a.error,`failed to get token accounts owned by account ${e.toBase58()}`);return a.result}async getLargestAccounts(e){const n={...e,commitment:e&&e.commitment||this.commitment},r=n.filter||n.commitment?[n]:[],i=await this._rpcRequest("getLargestAccounts",r),o=he(i,X9);if("error"in o)throw new Ee(o.error,"failed to get largest accounts");return o.result}async getTokenLargestAccounts(e,n){const r=this._buildArgs([e.toBase58()],n),i=await this._rpcRequest("getTokenLargestAccounts",r),o=he(i,G9);if("error"in o)throw new Ee(o.error,"failed to get token largest accounts");return o.result}async getAccountInfoAndContext(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgs([e.toBase58()],r,"base64",i),s=await this._rpcRequest("getAccountInfo",o),a=he(s,Ct(pe(Al)));if("error"in a)throw new Ee(a.error,`failed to get info about account ${e.toBase58()}`);return a.result}async getParsedAccountInfo(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgs([e.toBase58()],r,"jsonParsed",i),s=await this._rpcRequest("getAccountInfo",o),a=he(s,Ct(pe(up)));if("error"in a)throw new Ee(a.error,`failed to get info about account ${e.toBase58()}`);return a.result}async getAccountInfo(e,n){try{return(await this.getAccountInfoAndContext(e,n)).value}catch(r){throw new Error("failed to get info about account "+e.toBase58()+": "+r)}}async getMultipleParsedAccounts(e,n){const{commitment:r,config:i}=ct(n),o=e.map(c=>c.toBase58()),s=this._buildArgs([o],r,"jsonParsed",i),a=await this._rpcRequest("getMultipleAccounts",s),l=he(a,Ct(ge(pe(up))));if("error"in l)throw new Ee(l.error,`failed to get info for accounts ${o}`);return l.result}async getMultipleAccountsInfoAndContext(e,n){const{commitment:r,config:i}=ct(n),o=e.map(c=>c.toBase58()),s=this._buildArgs([o],r,"base64",i),a=await this._rpcRequest("getMultipleAccounts",s),l=he(a,Ct(ge(pe(Al))));if("error"in l)throw new Ee(l.error,`failed to get info for accounts ${o}`);return l.result}async getMultipleAccountsInfo(e,n){return(await this.getMultipleAccountsInfoAndContext(e,n)).value}async getStakeActivation(e,n,r){const{commitment:i,config:o}=ct(n),s=this._buildArgs([e.toBase58()],i,void 0,{...o,epoch:r!=null?r:o==null?void 0:o.epoch}),a=await this._rpcRequest("getStakeActivation",s),l=he(a,Fe(ej));if("error"in l)throw new Ee(l.error,`failed to get Stake Activation ${e.toBase58()}`);return l.result}async getProgramAccounts(e,n){const{commitment:r,config:i}=ct(n),{encoding:o,...s}=i||{},a=this._buildArgs([e.toBase58()],r,o||"base64",{...s,...s.filters?{filters:sE(s.filters)}:null}),l=await this._rpcRequest("getProgramAccounts",a),c=ge(Z9),u=s.withContext===!0?he(l,Ct(c)):he(l,Fe(c));if("error"in u)throw new Ee(u.error,`failed to get accounts owned by program ${e.toBase58()}`);return u.result}async getParsedProgramAccounts(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgs([e.toBase58()],r,"jsonParsed",i),s=await this._rpcRequest("getProgramAccounts",o),a=he(s,Fe(ge(Q9)));if("error"in a)throw new Ee(a.error,`failed to get accounts owned by program ${e.toBase58()}`);return a.result}async confirmTransaction(e,n){var o;let r;if(typeof e=="string")r=e;else{const s=e;if((o=s.abortSignal)!=null&&o.aborted)return Promise.reject(s.abortSignal.reason);r=s.signature}let i;try{i=mn.decode(r)}catch(s){throw new Error("signature must be base58 encoded: "+r)}return pt(i.length===64,"signature has invalid length"),typeof e=="string"?await this.confirmTransactionUsingLegacyTimeoutStrategy({commitment:n||this.commitment,signature:r}):"lastValidBlockHeight"in e?await this.confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:n||this.commitment,strategy:e}):await this.confirmTransactionUsingDurableNonceStrategy({commitment:n||this.commitment,strategy:e})}getCancellationPromise(e){return new Promise((n,r)=>{e!=null&&(e.aborted?r(e.reason):e.addEventListener("abort",()=>{r(e.reason)}))})}getTransactionConfirmationPromise({commitment:e,signature:n}){let r,i,o=!1;const s=new Promise((l,c)=>{try{r=this.onSignature(n,(h,p)=>{r=void 0;const g={context:p,value:h};l({__type:no.PROCESSED,response:g})},e);const u=new Promise(h=>{r==null?h():i=this._onSubscriptionStateChange(r,p=>{p==="subscribed"&&h()})});(async()=>{if(await u,o)return;const h=await this.getSignatureStatus(n);if(o||h==null)return;const{context:p,value:g}=h;if(g!=null)if(g!=null&&g.err)c(g.err);else{switch(e){case"confirmed":case"single":case"singleGossip":{if(g.confirmationStatus==="processed")return;break}case"finalized":case"max":case"root":{if(g.confirmationStatus==="processed"||g.confirmationStatus==="confirmed")return;break}case"processed":case"recent":}o=!0,l({__type:no.PROCESSED,response:{context:p,value:g}})}})()}catch(u){c(u)}});return{abortConfirmation:()=>{i&&(i(),i=void 0),r!=null&&(this.removeSignatureListener(r),r=void 0)},confirmationPromise:s}}async confirmTransactionUsingBlockHeightExceedanceStrategy({commitment:e,strategy:{abortSignal:n,lastValidBlockHeight:r,signature:i}}){let o=!1;const s=new Promise(h=>{const p=async()=>{try{return await this.getBlockHeight(e)}catch(g){return-1}};(async()=>{let g=await p();if(!o){for(;g<=r;)if(await Xs(1e3),o||(g=await p(),o))return;h({__type:no.BLOCKHEIGHT_EXCEEDED})}})()}),{abortConfirmation:a,confirmationPromise:l}=this.getTransactionConfirmationPromise({commitment:e,signature:i}),c=this.getCancellationPromise(n);let u;try{const h=await Promise.race([c,l,s]);if(h.__type===no.PROCESSED)u=h.response;else throw new Kw(i)}finally{o=!0,a()}return u}async confirmTransactionUsingDurableNonceStrategy({commitment:e,strategy:{abortSignal:n,minContextSlot:r,nonceAccountPubkey:i,nonceValue:o,signature:s}}){var g;let a=!1;const l=new Promise(b=>{let m=o,x=null;const I=async()=>{try{const{context:N,value:T}=await this.getNonceAndContext(i,{commitment:e,minContextSlot:r});return x=N.slot,T==null?void 0:T.nonce}catch(N){return m}};(async()=>{if(m=await I(),!a)for(;;){if(o!==m){b({__type:no.NONCE_INVALID,slotInWhichNonceDidAdvance:x});return}if(await Xs(2e3),a||(m=await I(),a))return}})()}),{abortConfirmation:c,confirmationPromise:u}=this.getTransactionConfirmationPromise({commitment:e,signature:s}),h=this.getCancellationPromise(n);let p;try{const b=await Promise.race([h,u,l]);if(b.__type===no.PROCESSED)p=b.response;else{let m;for(;;){const x=await this.getSignatureStatus(s);if(x==null)break;if(x.context.slot<((g=b.slotInWhichNonceDidAdvance)!=null?g:r)){await Xs(400);continue}m=x;break}if(m!=null&&m.value){const x=e||"finalized",{confirmationStatus:I}=m.value;switch(x){case"processed":case"recent":if(I!=="processed"&&I!=="confirmed"&&I!=="finalized")throw new Sl(s);break;case"confirmed":case"single":case"singleGossip":if(I!=="confirmed"&&I!=="finalized")throw new Sl(s);break;case"finalized":case"max":case"root":if(I!=="finalized")throw new Sl(s);break;default:}p={context:m.context,value:{err:m.value.err}}}else throw new Sl(s)}}finally{a=!0,c()}return p}async confirmTransactionUsingLegacyTimeoutStrategy({commitment:e,signature:n}){let r;const i=new Promise(l=>{let c=this._confirmTransactionInitialTimeout||6e4;switch(e){case"processed":case"recent":case"single":case"confirmed":case"singleGossip":{c=this._confirmTransactionInitialTimeout||3e4;break}}r=setTimeout(()=>l({__type:no.TIMED_OUT,timeoutMs:c}),c)}),{abortConfirmation:o,confirmationPromise:s}=this.getTransactionConfirmationPromise({commitment:e,signature:n});let a;try{const l=await Promise.race([s,i]);if(l.__type===no.PROCESSED)a=l.response;else throw new Yw(n,l.timeoutMs/1e3)}finally{clearTimeout(r),o()}return a}async getClusterNodes(){const e=await this._rpcRequest("getClusterNodes",[]),n=he(e,Fe(ge(hj)));if("error"in n)throw new Ee(n.error,"failed to get cluster nodes");return n.result}async getVoteAccounts(e){const n=this._buildArgs([],e),r=await this._rpcRequest("getVoteAccounts",n),i=he(r,fj);if("error"in i)throw new Ee(i.error,"failed to get vote accounts");return i.result}async getSlot(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,void 0,r),o=await this._rpcRequest("getSlot",i),s=he(o,Fe(ne()));if("error"in s)throw new Ee(s.error,"failed to get slot");return s.result}async getSlotLeader(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,void 0,r),o=await this._rpcRequest("getSlotLeader",i),s=he(o,Fe(de()));if("error"in s)throw new Ee(s.error,"failed to get slot leader");return s.result}async getSlotLeaders(e,n){const r=[e,n],i=await this._rpcRequest("getSlotLeaders",r),o=he(i,Fe(ge(yt)));if("error"in o)throw new Ee(o.error,"failed to get slot leaders");return o.result}async getSignatureStatus(e,n){const{context:r,value:i}=await this.getSignatureStatuses([e],n);pt(i.length===1);const o=i[0];return{context:r,value:o}}async getSignatureStatuses(e,n){const r=[e];n&&r.push(n);const i=await this._rpcRequest("getSignatureStatuses",r),o=he(i,mj);if("error"in o)throw new Ee(o.error,"failed to get signature status");return o.result}async getTransactionCount(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,void 0,r),o=await this._rpcRequest("getTransactionCount",i),s=he(o,Fe(ne()));if("error"in s)throw new Ee(s.error,"failed to get transaction count");return s.result}async getTotalSupply(e){return(await this.getSupply({commitment:e,excludeNonCirculatingAccountsList:!0})).value.total}async getInflationGovernor(e){const n=this._buildArgs([],e),r=await this._rpcRequest("getInflationGovernor",n),i=he(r,V9);if("error"in i)throw new Ee(i.error,"failed to get inflation");return i.result}async getInflationReward(e,n,r){const{commitment:i,config:o}=ct(r),s=this._buildArgs([e.map(c=>c.toBase58())],i,void 0,{...o,epoch:n!=null?n:o==null?void 0:o.epoch}),a=await this._rpcRequest("getInflationReward",s),l=he(a,S9);if("error"in l)throw new Ee(l.error,"failed to get inflation reward");return l.result}async getInflationRate(){const e=await this._rpcRequest("getInflationRate",[]),n=he(e,$9);if("error"in n)throw new Ee(n.error,"failed to get inflation rate");return n.result}async getEpochInfo(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,void 0,r),o=await this._rpcRequest("getEpochInfo",i),s=he(o,U9);if("error"in s)throw new Ee(s.error,"failed to get epoch info");return s.result}async getEpochSchedule(){const e=await this._rpcRequest("getEpochSchedule",[]),n=he(e,W9);if("error"in n)throw new Ee(n.error,"failed to get epoch schedule");const r=n.result;return new f9(r.slotsPerEpoch,r.leaderScheduleSlotOffset,r.warmup,r.firstNormalEpoch,r.firstNormalSlot)}async getLeaderSchedule(){const e=await this._rpcRequest("getLeaderSchedule",[]),n=he(e,H9);if("error"in n)throw new Ee(n.error,"failed to get leader schedule");return n.result}async getMinimumBalanceForRentExemption(e,n){const r=this._buildArgs([e],n),i=await this._rpcRequest("getMinimumBalanceForRentExemption",r),o=he(i,vj);return"error"in o?(console.warn("Unable to fetch minimum balance for rent exemption"),0):o.result}async getRecentBlockhashAndContext(e){const{context:n,value:{blockhash:r}}=await this.getLatestBlockhashAndContext(e);return{context:n,value:{blockhash:r,feeCalculator:{get lamportsPerSignature(){throw new Error("The capability to fetch `lamportsPerSignature` using the `getRecentBlockhash` API is no longer offered by the network. Use the `getFeeForMessage` API to obtain the fee for a given message.")},toJSON(){return{}}}}}}async getRecentPerformanceSamples(e){const n=await this._rpcRequest("getRecentPerformanceSamples",e?[e]:[]),r=he(n,Tj);if("error"in r)throw new Ee(r.error,"failed to get recent performance samples");return r.result}async getFeeCalculatorForBlockhash(e,n){const r=this._buildArgs([e],n),i=await this._rpcRequest("getFeeCalculatorForBlockhash",r),o=he(i,Rj);if("error"in o)throw new Ee(o.error,"failed to get fee calculator");const{context:s,value:a}=o.result;return{context:s,value:a!==null?a.feeCalculator:null}}async getFeeForMessage(e,n){const r=Gs(e.serialize()).toString("base64"),i=this._buildArgs([r],n),o=await this._rpcRequest("getFeeForMessage",i),s=he(o,Ct(pe(ne())));if("error"in s)throw new Ee(s.error,"failed to get fee for message");if(s.result===null)throw new Error("invalid blockhash");return s.result}async getRecentPrioritizationFees(e){var s;const n=(s=e==null?void 0:e.lockedWritableAccounts)==null?void 0:s.map(a=>a.toBase58()),r=n!=null&&n.length?[n]:[],i=await this._rpcRequest("getRecentPrioritizationFees",r),o=he(i,z9);if("error"in o)throw new Ee(o.error,"failed to get recent prioritization fees");return o.result}async getRecentBlockhash(e){try{return(await this.getRecentBlockhashAndContext(e)).value}catch(n){throw new Error("failed to get recent blockhash: "+n)}}async getLatestBlockhash(e){try{return(await this.getLatestBlockhashAndContext(e)).value}catch(n){throw new Error("failed to get recent blockhash: "+n)}}async getLatestBlockhashAndContext(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,void 0,r),o=await this._rpcRequest("getLatestBlockhash",i),s=he(o,Aj);if("error"in s)throw new Ee(s.error,"failed to get latest blockhash");return s.result}async isBlockhashValid(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgs([e],r,void 0,i),s=await this._rpcRequest("isBlockhashValid",o),a=he(s,Oj);if("error"in a)throw new Ee(a.error,"failed to determine if the blockhash `"+e+"`is valid");return a.result}async getVersion(){const e=await this._rpcRequest("getVersion",[]),n=he(e,Fe(N9));if("error"in n)throw new Ee(n.error,"failed to get version");return n.result}async getGenesisHash(){const e=await this._rpcRequest("getGenesisHash",[]),n=he(e,Fe(de()));if("error"in n)throw new Ee(n.error,"failed to get genesis hash");return n.result}async getBlock(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgsAtLeastConfirmed([e],r,void 0,i),s=await this._rpcRequest("getBlock",o);try{switch(i==null?void 0:i.transactionDetails){case"accounts":{const a=he(s,wj);if("error"in a)throw a.error;return a.result}case"none":{const a=he(s,xj);if("error"in a)throw a.error;return a.result}default:{const a=he(s,_j);if("error"in a)throw a.error;const{result:l}=a;return l?{...l,transactions:l.transactions.map(({transaction:c,meta:u,version:h})=>({meta:u,transaction:{...c,message:ap(h,c.message)},version:h}))}:null}}}catch(a){throw new Ee(a,"failed to get confirmed block")}}async getParsedBlock(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",i),s=await this._rpcRequest("getBlock",o);try{switch(i==null?void 0:i.transactionDetails){case"accounts":{const a=he(s,Sj);if("error"in a)throw a.error;return a.result}case"none":{const a=he(s,Ij);if("error"in a)throw a.error;return a.result}default:{const a=he(s,Ej);if("error"in a)throw a.error;return a.result}}}catch(a){throw new Ee(a,"failed to get block")}}async getBlockProduction(e){let n,r;if(typeof e=="string")r=e;else if(e){const{commitment:a,...l}=e;r=a,n=l}const i=this._buildArgs([],r,"base64",n),o=await this._rpcRequest("getBlockProduction",i),s=he(o,M9);if("error"in s)throw new Ee(s.error,"failed to get block production information");return s.result}async getTransaction(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgsAtLeastConfirmed([e],r,void 0,i),s=await this._rpcRequest("getTransaction",o),a=he(s,fp);if("error"in a)throw new Ee(a.error,"failed to get transaction");const l=a.result;return l&&{...l,transaction:{...l.transaction,message:ap(l.version,l.transaction.message)}}}async getParsedTransaction(e,n){const{commitment:r,config:i}=ct(n),o=this._buildArgsAtLeastConfirmed([e],r,"jsonParsed",i),s=await this._rpcRequest("getTransaction",o),a=he(s,od);if("error"in a)throw new Ee(a.error,"failed to get transaction");return a.result}async getParsedTransactions(e,n){const{commitment:r,config:i}=ct(n),o=e.map(l=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([l],r,"jsonParsed",i)}));return(await this._rpcBatchRequest(o)).map(l=>{const c=he(l,od);if("error"in c)throw new Ee(c.error,"failed to get transactions");return c.result})}async getTransactions(e,n){const{commitment:r,config:i}=ct(n),o=e.map(l=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([l],r,void 0,i)}));return(await this._rpcBatchRequest(o)).map(l=>{const c=he(l,fp);if("error"in c)throw new Ee(c.error,"failed to get transactions");const u=c.result;return u&&{...u,transaction:{...u.transaction,message:ap(u.version,u.transaction.message)}}})}async getConfirmedBlock(e,n){const r=this._buildArgsAtLeastConfirmed([e],n),i=await this._rpcRequest("getBlock",r),o=he(i,Cj);if("error"in o)throw new Ee(o.error,"failed to get confirmed block");const s=o.result;if(!s)throw new Error("Confirmed block "+e+" not found");const a={...s,transactions:s.transactions.map(({transaction:l,meta:c})=>{const u=new Ii(l.message);return{meta:c,transaction:{...l,message:u}}})};return{...a,transactions:a.transactions.map(({transaction:l,meta:c})=>({meta:c,transaction:cr.populate(l.message,l.signatures)}))}}async getBlocks(e,n,r){const i=this._buildArgsAtLeastConfirmed(n!==void 0?[e,n]:[e],r),o=await this._rpcRequest("getBlocks",i),s=he(o,Fe(ge(ne())));if("error"in s)throw new Ee(s.error,"failed to get blocks");return s.result}async getBlockSignatures(e,n){const r=this._buildArgsAtLeastConfirmed([e],n,void 0,{transactionDetails:"signatures",rewards:!1}),i=await this._rpcRequest("getBlock",r),o=he(i,yE);if("error"in o)throw new Ee(o.error,"failed to get block");const s=o.result;if(!s)throw new Error("Block "+e+" not found");return s}async getConfirmedBlockSignatures(e,n){const r=this._buildArgsAtLeastConfirmed([e],n,void 0,{transactionDetails:"signatures",rewards:!1}),i=await this._rpcRequest("getBlock",r),o=he(i,yE);if("error"in o)throw new Ee(o.error,"failed to get confirmed block");const s=o.result;if(!s)throw new Error("Confirmed block "+e+" not found");return s}async getConfirmedTransaction(e,n){const r=this._buildArgsAtLeastConfirmed([e],n),i=await this._rpcRequest("getTransaction",r),o=he(i,fp);if("error"in o)throw new Ee(o.error,"failed to get transaction");const s=o.result;if(!s)return s;const a=new Ii(s.transaction.message),l=s.transaction.signatures;return{...s,transaction:cr.populate(a,l)}}async getParsedConfirmedTransaction(e,n){const r=this._buildArgsAtLeastConfirmed([e],n,"jsonParsed"),i=await this._rpcRequest("getTransaction",r),o=he(i,od);if("error"in o)throw new Ee(o.error,"failed to get confirmed transaction");return o.result}async getParsedConfirmedTransactions(e,n){const r=e.map(s=>({methodName:"getTransaction",args:this._buildArgsAtLeastConfirmed([s],n,"jsonParsed")}));return(await this._rpcBatchRequest(r)).map(s=>{const a=he(s,od);if("error"in a)throw new Ee(a.error,"failed to get confirmed transactions");return a.result})}async getConfirmedSignaturesForAddress(e,n,r){let i={},o=await this.getFirstAvailableBlock();for(;!("until"in i)&&(n--,!(n<=0||n<o));)try{const l=await this.getConfirmedBlockSignatures(n,"finalized");l.signatures.length>0&&(i.until=l.signatures[l.signatures.length-1].toString())}catch(l){if(l instanceof Error&&l.message.includes("skipped"))continue;throw l}let s=await this.getSlot("finalized");for(;!("before"in i)&&(r++,!(r>s));)try{const l=await this.getConfirmedBlockSignatures(r);l.signatures.length>0&&(i.before=l.signatures[l.signatures.length-1].toString())}catch(l){if(l instanceof Error&&l.message.includes("skipped"))continue;throw l}return(await this.getConfirmedSignaturesForAddress2(e,i)).map(l=>l.signature)}async getConfirmedSignaturesForAddress2(e,n,r){const i=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,n),o=await this._rpcRequest("getConfirmedSignaturesForAddress2",i),s=he(o,tj);if("error"in s)throw new Ee(s.error,"failed to get confirmed signatures for address");return s.result}async getSignaturesForAddress(e,n,r){const i=this._buildArgsAtLeastConfirmed([e.toBase58()],r,void 0,n),o=await this._rpcRequest("getSignaturesForAddress",i),s=he(o,nj);if("error"in s)throw new Ee(s.error,"failed to get signatures for address");return s.result}async getAddressLookupTable(e,n){const{context:r,value:i}=await this.getAccountInfoAndContext(e,n);let o=null;return i!==null&&(o=new iE({key:e,state:iE.deserialize(i.data)})),{context:r,value:o}}async getNonceAndContext(e,n){const{context:r,value:i}=await this.getAccountInfoAndContext(e,n);let o=null;return i!==null&&(o=rp.fromAccountData(i.data)),{context:r,value:o}}async getNonce(e,n){return await this.getNonceAndContext(e,n).then(r=>r.value).catch(r=>{throw new Error("failed to get nonce for account "+e.toBase58()+": "+r)})}async requestAirdrop(e,n){const r=await this._rpcRequest("requestAirdrop",[e.toBase58(),n]),i=he(r,Nj);if("error"in i)throw new Ee(i.error,`airdrop to ${e.toBase58()} failed`);return i.result}async _blockhashWithExpiryBlockHeight(e){if(!e){for(;this._pollingBlockhash;)await Xs(100);const r=Date.now()-this._blockhashInfo.lastFetch>=_9;if(this._blockhashInfo.latestBlockhash!==null&&!r)return this._blockhashInfo.latestBlockhash}return await this._pollNewBlockhash()}async _pollNewBlockhash(){this._pollingBlockhash=!0;try{const e=Date.now(),n=this._blockhashInfo.latestBlockhash,r=n?n.blockhash:null;for(let i=0;i<50;i++){const o=await this.getLatestBlockhash("finalized");if(r!==o.blockhash)return this._blockhashInfo={latestBlockhash:o,lastFetch:Date.now(),transactionSignatures:[],simulatedSignatures:[]},o;await Xs(a9/2)}throw new Error(`Unable to obtain a new blockhash after ${Date.now()-e}ms`)}finally{this._pollingBlockhash=!1}}async getStakeMinimumDelegation(e){const{commitment:n,config:r}=ct(e),i=this._buildArgs([],n,"base64",r),o=await this._rpcRequest("getStakeMinimumDelegation",i),s=he(o,Ct(ne()));if("error"in s)throw new Ee(s.error,"failed to get stake minimum delegation");return s.result}async simulateTransaction(e,n,r){if("message"in e){const m=e.serialize(),x=$e.Buffer.from(m).toString("base64");if(Array.isArray(n)||r!==void 0)throw new Error("Invalid arguments");const I=n||{};I.encoding="base64","commitment"in I||(I.commitment=this.commitment),n&&typeof n=="object"&&"innerInstructions"in n&&(I.innerInstructions=n.innerInstructions);const N=[x,I],T=await this._rpcRequest("simulateTransaction",N),$=he(T,lE);if("error"in $)throw new Error("failed to simulate transaction: "+$.error.message);return $.result}let i;if(e instanceof cr){let b=e;i=new cr,i.feePayer=b.feePayer,i.instructions=e.instructions,i.nonceInfo=b.nonceInfo,i.signatures=b.signatures}else i=cr.populate(e),i._message=i._json=void 0;if(n!==void 0&&!Array.isArray(n))throw new Error("Invalid arguments");const o=n;if(i.nonceInfo&&o)i.sign(...o);else{let b=this._disableBlockhashCaching;for(;;){const m=await this._blockhashWithExpiryBlockHeight(b);if(i.lastValidBlockHeight=m.lastValidBlockHeight,i.recentBlockhash=m.blockhash,!o)break;if(i.sign(...o),!i.signature)throw new Error("!signature");const x=i.signature.toString("base64");if(!this._blockhashInfo.simulatedSignatures.includes(x)&&!this._blockhashInfo.transactionSignatures.includes(x)){this._blockhashInfo.simulatedSignatures.push(x);break}else b=!0}}const s=i._compile(),a=s.serialize(),c=i._serialize(a).toString("base64"),u={encoding:"base64",commitment:this.commitment};if(r){const b=(Array.isArray(r)?r:s.nonProgramIds()).map(m=>m.toBase58());u.accounts={encoding:"base64",addresses:b}}o&&(u.sigVerify=!0),n&&typeof n=="object"&&"innerInstructions"in n&&(u.innerInstructions=n.innerInstructions);const h=[c,u],p=await this._rpcRequest("simulateTransaction",h),g=he(p,lE);if("error"in g){let b;if("data"in g.error&&(b=g.error.data.logs,b&&Array.isArray(b))){const m=`
228
- `,x=m+b.join(m);console.error(g.error.message,x)}throw new Qw({action:"simulate",signature:"",transactionMessage:g.error.message,logs:b})}return g.result}async sendTransaction(e,n,r){if("version"in e){if(n&&Array.isArray(n))throw new Error("Invalid arguments");const s=e.serialize();return await this.sendRawTransaction(s,n)}if(n===void 0||!Array.isArray(n))throw new Error("Invalid arguments");const i=n;if(e.nonceInfo)e.sign(...i);else{let s=this._disableBlockhashCaching;for(;;){const a=await this._blockhashWithExpiryBlockHeight(s);if(e.lastValidBlockHeight=a.lastValidBlockHeight,e.recentBlockhash=a.blockhash,e.sign(...i),!e.signature)throw new Error("!signature");const l=e.signature.toString("base64");if(this._blockhashInfo.transactionSignatures.includes(l))s=!0;else{this._blockhashInfo.transactionSignatures.push(l);break}}}const o=e.serialize();return await this.sendRawTransaction(o,r)}async sendRawTransaction(e,n){const r=Gs(e).toString("base64");return await this.sendEncodedTransaction(r,n)}async sendEncodedTransaction(e,n){const r={encoding:"base64"},i=n&&n.skipPreflight,o=i===!0?"processed":n&&n.preflightCommitment||this.commitment;n&&n.maxRetries!=null&&(r.maxRetries=n.maxRetries),n&&n.minContextSlot!=null&&(r.minContextSlot=n.minContextSlot),i&&(r.skipPreflight=i),o&&(r.preflightCommitment=o);const s=[e,r],a=await this._rpcRequest("sendTransaction",s),l=he(a,Pj);if("error"in l){let c;throw"data"in l.error&&(c=l.error.data.logs),new Qw({action:i?"send":"simulate",signature:"",transactionMessage:l.error.message,logs:c})}return l.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch(e){}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){if(this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),e===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([n,r])=>{this._setSubscription(n,{...r,state:"pending"})})}_setSubscription(e,n){var i;const r=(i=this._subscriptionsByHash[e])==null?void 0:i.state;if(this._subscriptionsByHash[e]=n,r!==n.state){const o=this._subscriptionStateChangeCallbacksByHash[e];o&&o.forEach(s=>{try{s(n.state)}catch(a){}})}}_onSubscriptionStateChange(e,n){var o;const r=this._subscriptionHashByClientSubscriptionId[e];if(r==null)return()=>{};const i=(o=this._subscriptionStateChangeCallbacksByHash)[r]||(o[r]=new Set);return i.add(n),()=>{i.delete(n),i.size===0&&delete this._subscriptionStateChangeCallbacksByHash[r]}}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).length===0){this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(r){r instanceof Error&&console.log(`Error when closing socket connection: ${r.message}`)}},500));return}if(this._rpcWebSocketIdleTimeout!==null&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}const e=this._rpcWebSocketGeneration,n=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async r=>{const i=this._subscriptionsByHash[r];if(i!==void 0)switch(i.state){case"pending":case"unsubscribed":if(i.callbacks.size===0){delete this._subscriptionsByHash[r],i.state==="unsubscribed"&&delete this._subscriptionCallbacksByServerSubscriptionId[i.serverSubscriptionId],await this._updateSubscriptions();return}await(async()=>{const{args:o,method:s}=i;try{this._setSubscription(r,{...i,state:"subscribing"});const a=await this._rpcWebSocket.call(s,o);this._setSubscription(r,{...i,serverSubscriptionId:a,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[a]=i.callbacks,await this._updateSubscriptions()}catch(a){if(console.error(`Received ${a instanceof Error?"":"JSON-RPC "}error calling \`${s}\``,{args:o,error:a}),!n())return;this._setSubscription(r,{...i,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":i.callbacks.size===0&&await(async()=>{const{serverSubscriptionId:o,unsubscribeMethod:s}=i;if(this._subscriptionsAutoDisposedByRpc.has(o))this._subscriptionsAutoDisposedByRpc.delete(o);else{this._setSubscription(r,{...i,state:"unsubscribing"}),this._setSubscription(r,{...i,state:"unsubscribing"});try{await this._rpcWebSocket.call(s,[o])}catch(a){if(a instanceof Error&&console.error(`${s} error:`,a.message),!n())return;this._setSubscription(r,{...i,state:"subscribed"}),await this._updateSubscriptions();return}}this._setSubscription(r,{...i,state:"unsubscribed"}),await this._updateSubscriptions()})();break}}))}_handleServerNotification(e,n){const r=this._subscriptionCallbacksByServerSubscriptionId[e];r!==void 0&&r.forEach(i=>{try{i(...n)}catch(o){console.error(o)}})}_wsOnAccountNotification(e){const{result:n,subscription:r}=he(e,rj);this._handleServerNotification(r,[n.value,n.context])}_makeSubscription(e,n){const r=this._nextClientSubscriptionId++,i=nE([e.method,n]),o=this._subscriptionsByHash[i];return o===void 0?this._subscriptionsByHash[i]={...e,args:n,callbacks:new Set([e.callback]),state:"pending"}:o.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[r]=i,this._subscriptionDisposeFunctionsByClientSubscriptionId[r]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[r],delete this._subscriptionHashByClientSubscriptionId[r];const s=this._subscriptionsByHash[i];pt(s!==void 0,`Could not find a \`Subscription\` when tearing down client subscription #${r}`),s.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),r}onAccountChange(e,n,r){const{commitment:i,config:o}=ct(r),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o);return this._makeSubscription({callback:n,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},s)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:n,subscription:r}=he(e,oj);this._handleServerNotification(r,[{accountId:n.value.pubkey,accountInfo:n.value.account},n.context])}onProgramAccountChange(e,n,r,i){const{commitment:o,config:s}=ct(r),a=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",s||(i?{filters:sE(i)}:void 0));return this._makeSubscription({callback:n,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},a)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,n,r){const i=this._buildArgs([typeof e=="object"?{mentions:[e.toString()]}:e],r||this._commitment||"finalized");return this._makeSubscription({callback:n,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},i)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:n,subscription:r}=he(e,Mj);this._handleServerNotification(r,[n.value,n.context])}_wsOnSlotNotification(e){const{result:n,subscription:r}=he(e,aj);this._handleServerNotification(r,[n])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:n,subscription:r}=he(e,cj);this._handleServerNotification(r,[n])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,n){const r=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];r?await r():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${n}' events could not be found.`)}_buildArgs(e,n,r,i){const o=n||this._commitment;if(o||r||i){let s={};r&&(s.encoding=r),o&&(s.commitment=o),i&&(s=Object.assign(s,i)),e.push(s)}return e}_buildArgsAtLeastConfirmed(e,n,r,i){const o=n||this._commitment;if(o&&!["confirmed","finalized"].includes(o))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,n,r,i)}_wsOnSignatureNotification(e){const{result:n,subscription:r}=he(e,uj);n.value!=="receivedSignature"&&this._subscriptionsAutoDisposedByRpc.add(r),this._handleServerNotification(r,n.value==="receivedSignature"?[{type:"received"},n.context]:[{type:"status",result:n.value},n.context])}onSignature(e,n,r){const i=this._buildArgs([e],r||this._commitment||"finalized"),o=this._makeSubscription({callback:(s,a)=>{if(s.type==="status"){n(s.result,a);try{this.removeSignatureListener(o)}catch(l){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return o}onSignatureWithOptions(e,n,r){const{commitment:i,...o}={...r,commitment:r&&r.commitment||this._commitment||"finalized"},s=this._buildArgs([e],i,void 0,o),a=this._makeSubscription({callback:(l,c)=>{n(l,c);try{this.removeSignatureListener(a)}catch(u){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},s);return a}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:n,subscription:r}=he(e,dj);this._handleServerNotification(r,[n])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}Object.freeze({CreateLookupTable:{index:0,layout:q.struct([q.u32("instruction"),Zs("recentSlot"),q.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:q.struct([q.u32("instruction")])},ExtendLookupTable:{index:2,layout:q.struct([q.u32("instruction"),Zs(),q.seq(ze(),q.offset(q.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:q.struct([q.u32("instruction")])},CloseLookupTable:{index:4,layout:q.struct([q.u32("instruction")])}}),new Re("AddressLookupTab1e1111111111111111111111111"),Object.freeze({RequestUnits:{index:0,layout:q.struct([q.u8("instruction"),q.u32("units"),q.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:q.struct([q.u8("instruction"),q.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:q.struct([q.u8("instruction"),q.u32("units")])},SetComputeUnitPrice:{index:3,layout:q.struct([q.u8("instruction"),Zs("microLamports")])}}),new Re("ComputeBudget111111111111111111111111111111"),q.struct([q.u8("numSignatures"),q.u8("padding"),q.u16("signatureOffset"),q.u16("signatureInstructionIndex"),q.u16("publicKeyOffset"),q.u16("publicKeyInstructionIndex"),q.u16("messageDataOffset"),q.u16("messageDataSize"),q.u16("messageInstructionIndex")]),new Re("Ed25519SigVerify111111111111111111111111111"),XH.utils.isValidPrivateKey,q.struct([q.u8("numSignatures"),q.u16("signatureOffset"),q.u8("signatureInstructionIndex"),q.u16("ethAddressOffset"),q.u8("ethAddressInstructionIndex"),q.u16("messageDataOffset"),q.u16("messageDataSize"),q.u8("messageInstructionIndex"),q.blob(20,"ethAddress"),q.blob(64,"signature"),q.u8("recoveryId")]),new Re("KeccakSecp256k11111111111111111111111111111");var bE;new Re("StakeConfig11111111111111111111111111111111");class _E{constructor(e,n,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=n,this.custodian=r}}bE=_E,_E.default=new bE(0,0,Re.default),Object.freeze({Initialize:{index:0,layout:q.struct([q.u32("instruction"),n9(),r9()])},Authorize:{index:1,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:q.struct([q.u32("instruction")])},Split:{index:3,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},Withdraw:{index:4,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},Deactivate:{index:5,layout:q.struct([q.u32("instruction")])},Merge:{index:7,layout:q.struct([q.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("stakeAuthorizationType"),Ys("authoritySeed"),ze("authorityOwner")])}}),new Re("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:q.struct([q.u32("instruction"),i9()])},Authorize:{index:1,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:q.struct([q.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:q.struct([q.u32("instruction"),o9()])}}),new Re("Vote111111111111111111111111111111111111111"),new Re("Va1idator1nfo111111111111111111111111111111"),ce({name:de(),website:Ce(de()),details:Ce(de()),iconUrl:Ce(de()),keybaseUsername:Ce(de())}),new Re("Vote111111111111111111111111111111111111111"),q.struct([ze("nodePubkey"),ze("authorizedWithdrawer"),q.u8("commission"),q.nu64(),q.seq(q.struct([q.nu64("slot"),q.u32("confirmationCount")]),q.offset(q.u32(),-8),"votes"),q.u8("rootSlotValid"),q.nu64("rootSlot"),q.nu64(),q.seq(q.struct([q.nu64("epoch"),ze("authorizedVoter")]),q.offset(q.u32(),-8),"authorizedVoters"),q.struct([q.seq(q.struct([ze("authorizedPubkey"),q.nu64("epochOfLastAuthorizedSwitch"),q.nu64("targetEpoch")]),32,"buf"),q.nu64("idx"),q.u8("isEmpty")],"priorVoters"),q.nu64(),q.seq(q.struct([q.nu64("epoch"),q.nu64("credits"),q.nu64("prevCredits")]),q.offset(q.u32(),-8),"epochCredits"),q.struct([q.nu64("slot"),q.nu64("timestamp")],"lastTimestamp")]);function gp(t){switch(t){case"processed":case"confirmed":case"finalized":case void 0:return t;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const xE="solana:mainnet",Dj="solana:devnet",Vj="solana:testnet",$j="solana:localnet",zj="https://api.mainnet-beta.solana.com";function Uj(t){return t.includes(zj)?xE:/\bdevnet\b/i.test(t)?Dj:/\btestnet\b/i.test(t)?Vj:/\blocalhost\b/i.test(t)||/\b127\.0\.0\.1\b/.test(t)?$j:xE}function Wj(t,e){if(t===e)return!0;const n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}function Hj(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<t.length;c++){const u=t.charAt(c),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=c}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),o=Math.log(256)/Math.log(n);function s(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let u=0,h=0,p=0;const g=c.length;for(;p!==g&&c[p]===0;)p++,u++;const b=(g-p)*o+1>>>0,m=new Uint8Array(b);for(;p!==g;){let N=c[p],T=0;for(let $=b-1;(N!==0||T<h)&&$!==-1;$--,T++)N+=256*m[$]>>>0,m[$]=N%n>>>0,N=N/n>>>0;if(N!==0)throw new Error("Non-zero carry");h=T,p++}let x=b-h;for(;x!==b&&m[x]===0;)x++;let I=r.repeat(u);for(;x<b;++x)I+=t.charAt(m[x]);return I}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let u=0,h=0,p=0;for(;c[u]===r;)h++,u++;const g=(c.length-u)*i+1>>>0,b=new Uint8Array(g);for(;u<c.length;){const N=c.charCodeAt(u);if(N>255)return;let T=e[N];if(T===255)return;let $=0;for(let B=g-1;(T!==0||$<p)&&B!==-1;B--,$++)T+=n*b[B]>>>0,b[B]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");p=$,u++}let m=g-p;for(;m!==g&&b[m]===0;)m++;const x=new Uint8Array(h+(g-m));let I=h;for(;m!==g;)x[I++]=b[m++];return x}function l(c){const u=a(c);if(u)return u;throw new Error("Non-base"+n+" character")}return{encode:s,decodeUnsafe:a,decode:l}}var jj="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const qj=Hj(jj);var we=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},Mt=function(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n},yn,Hn,Uo,Wo,Ho,Ol,sd,qe,ad,pp,ld,mp,kl,vp,wE,EE,SE,IE;class Gj extends zV{get name(){return we(this,qe,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return we(this,qe,"f").icon}get readyState(){return we(this,ad,"f")}get publicKey(){return we(this,Uo,"f")}get connecting(){return we(this,Wo,"f")}get supportedTransactionVersions(){return we(this,sd,"f")}get wallet(){return we(this,qe,"f")}get standard(){return!0}constructor({wallet:e}){super(),yn.add(this),Hn.set(this,void 0),Uo.set(this,void 0),Wo.set(this,void 0),Ho.set(this,void 0),Ol.set(this,void 0),sd.set(this,void 0),qe.set(this,void 0),ad.set(this,typeof window=="undefined"||typeof document=="undefined"?fl.Unsupported:fl.Installed),vp.set(this,n=>{if("accounts"in n){const r=we(this,qe,"f").accounts[0];we(this,Hn,"f")&&!we(this,Ho,"f")&&r!==we(this,Hn,"f")&&(r?we(this,yn,"m",ld).call(this,r):(this.emit("error",new FV),we(this,yn,"m",mp).call(this)))}"features"in n&&we(this,yn,"m",kl).call(this)}),Mt(this,qe,e,"f"),Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),Mt(this,Wo,!1,"f"),Mt(this,Ho,!1,"f"),Mt(this,Ol,we(this,qe,"f").features[P1].on("change",we(this,vp,"f")),"f"),we(this,yn,"m",kl).call(this)}destroy(){Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),Mt(this,Wo,!1,"f"),Mt(this,Ho,!1,"f");const e=we(this,Ol,"f");e&&(Mt(this,Ol,null,"f"),e())}async autoConnect(){return we(this,yn,"m",pp).call(this,{silent:!0})}async connect(){return we(this,yn,"m",pp).call(this)}async disconnect(){if(N1 in we(this,qe,"f").features)try{Mt(this,Ho,!0,"f"),await we(this,qe,"f").features[N1].disconnect()}catch(e){this.emit("error",new DV(e==null?void 0:e.message,e))}finally{Mt(this,Ho,!1,"f")}we(this,yn,"m",mp).call(this)}async sendTransaction(e,n,r={}){try{const i=we(this,Hn,"f");if(!i)throw new hl;let o;if(Ji in we(this,qe,"f").features)if(i.features.includes(Ji))o=Ji;else if(gn in we(this,qe,"f").features&&i.features.includes(gn))o=gn;else throw new Vs;else if(gn in we(this,qe,"f").features){if(!i.features.includes(gn))throw new Vs;o=gn}else throw new dl;const s=Uj(n.rpcEndpoint);if(!i.chains.includes(s))throw new O1;try{const{signers:a,...l}=r;let c;if(gl(e)?(a!=null&&a.length&&e.sign(a),c=e.serialize()):(e=await this.prepareTransaction(e,n,l),a!=null&&a.length&&e.partialSign(...a),c=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),o===Ji){const[u]=await we(this,qe,"f").features[Ji].signAndSendTransaction({account:i,chain:s,transaction:c,options:{preflightCommitment:gp(l.preflightCommitment||n.commitment),skipPreflight:l.skipPreflight,maxRetries:l.maxRetries,minContextSlot:l.minContextSlot}});return qj.encode(u.signature)}else{const[u]=await we(this,qe,"f").features[gn].signTransaction({account:i,chain:s,transaction:c,options:{preflightCommitment:gp(l.preflightCommitment||n.commitment),minContextSlot:l.minContextSlot}});return await n.sendRawTransaction(u.signedTransaction,{...l,preflightCommitment:gp(l.preflightCommitment||n.commitment)})}}catch(a){throw a instanceof Un?a:new O1(a==null?void 0:a.message,a)}}catch(i){throw this.emit("error",i),i}}}Hn=new WeakMap,Uo=new WeakMap,Wo=new WeakMap,Ho=new WeakMap,Ol=new WeakMap,sd=new WeakMap,qe=new WeakMap,ad=new WeakMap,vp=new WeakMap,yn=new WeakSet,pp=async function(e){try{if(this.connected||this.connecting)return;if(we(this,ad,"f")!==fl.Installed)throw new MV;if(Mt(this,Wo,!0,"f"),!we(this,qe,"f").accounts.length)try{await we(this,qe,"f").features[R1].connect(e)}catch(r){throw new BV(r==null?void 0:r.message,r)}const n=we(this,qe,"f").accounts[0];if(!n)throw new Vs;we(this,yn,"m",ld).call(this,n)}catch(n){throw this.emit("error",n),n}finally{Mt(this,Wo,!1,"f")}},ld=function(e){let n;try{n=new Re(e.address)}catch(r){throw new VV(r==null?void 0:r.message,r)}Mt(this,Hn,e,"f"),Mt(this,Uo,n,"f"),we(this,yn,"m",kl).call(this),this.emit("connect",n)},mp=function(){Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),we(this,yn,"m",kl).call(this),this.emit("disconnect")},kl=function(){var n,r;const e=Ji in we(this,qe,"f").features?we(this,qe,"f").features[Ji].supportedTransactionVersions:we(this,qe,"f").features[gn].supportedTransactionVersions;Mt(this,sd,Wj(e,["legacy"])?null:new Set(e),"f"),gn in we(this,qe,"f").features&&((n=we(this,Hn,"f"))!=null&&n.features.includes(gn))?(this.signTransaction=we(this,yn,"m",wE),this.signAllTransactions=we(this,yn,"m",EE)):(delete this.signTransaction,delete this.signAllTransactions),pl in we(this,qe,"f").features&&((r=we(this,Hn,"f"))!=null&&r.features.includes(pl))?this.signMessage=we(this,yn,"m",SE):delete this.signMessage,Eg in we(this,qe,"f").features?this.signIn=we(this,yn,"m",IE):delete this.signIn},wE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(gn in we(this,qe,"f").features))throw new dl;if(!n.features.includes(gn))throw new Vs;try{const i=(await we(this,qe,"f").features[gn].signTransaction({account:n,transaction:gl(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return gl(e)?Vo.deserialize(i):cr.from(i)}catch(r){throw r instanceof Un?r:new k1(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},EE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(gn in we(this,qe,"f").features))throw new dl;if(!n.features.includes(gn))throw new Vs;try{const r=await we(this,qe,"f").features[gn].signTransaction(...e.map(i=>({account:n,transaction:gl(i)?i.serialize():new Uint8Array(i.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((i,o)=>{const s=r[o].signedTransaction;return gl(i)?Vo.deserialize(s):cr.from(s)})}catch(r){throw new k1(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},SE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(pl in we(this,qe,"f").features))throw new dl;if(!n.features.includes(pl))throw new Vs;try{return(await we(this,qe,"f").features[pl].signMessage({account:n,message:e}))[0].signature}catch(r){throw new $V(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},IE=async function(e={}){try{if(!(Eg in we(this,qe,"f").features))throw new dl;let n;try{[n]=await we(this,qe,"f").features[Eg].signIn(e)}catch(r){throw new T1(r==null?void 0:r.message,r)}if(!n)throw new T1;return we(this,yn,"m",ld).call(this,n.account),n}catch(n){throw this.emit("error",n),n}};class Kj{constructor(e){mt(this,"iframe");mt(this,"handshakeComplete",!1);mt(this,"parentAPI",null);mt(this,"endpoint",null);if(!e)throw new Error("BridgeParent requires an iframe element");this.iframe=e,this.initializeConnection()}async initializeConnection(){if(!this.iframe||!this.iframe.contentWindow)return;const e=await this.discoverWallets(),n=this.getSolanaWallets();this.parentAPI={eip6963Wallets:e,eip6963WalletsReady:!0,walletStandardWallets:n,walletStandardWalletsReady:!0},this.endpoint=EV(this.iframe.contentWindow,window,"*"),bg(this.parentAPI,this.endpoint),this.handshakeComplete=!0}isConnected(){return this.handshakeComplete}async discoverWallets(){return new Promise(e=>{const n=[],i=o=>{const s=o,{info:a,provider:l}=s.detail;n.findIndex(u=>u.uuid===a.uuid)===-1&&n.push({uuid:a.uuid,name:a.name,icon:a.icon,rdns:a.rdns,provider:l})};window.addEventListener("eip6963:announceProvider",i),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{window.removeEventListener("eip6963:announceProvider",i),e(n)},1e3)})}getSolanaWallets(){const{get:e}=kV(),n=e(),r=[],i=new Set;for(const o of n)if(this.isSolanaWallet(o)){let s;UV(o)&&(s=new Gj({wallet:o})),r.push({uuid:this.generateWalletId(o),name:o.name,chains:o.chains||[],features:Object.keys(o.features),adapter:s?{name:s.name,url:s.url,icon:s.icon,readyState:s.readyState,publicKey:S1({get value(){return s.publicKey},toBase58:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBase58()},toJSON:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toJSON()},toBytes:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBytes()},toBuffer:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBuffer()},toString:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toString()}}),connecting:s.connecting,connected:s.connected,supportedTransactionVersions:s.supportedTransactionVersions,wallet:s.wallet,standard:s.standard,destroy:async()=>await s.destroy(),autoConnect:async()=>await s.autoConnect(),connect:async()=>await s.connect(),disconnect:async()=>await s.disconnect(),sendTransaction:async(a,l,c)=>await s.sendTransaction(a,l,c),signTransaction:async a=>s.signTransaction!==void 0?await s.signTransaction(a):new Error("Adapter does not support signTransaction"),signAllTransactions:async a=>s.signAllTransactions!==void 0?await s.signAllTransactions(a):new Error("Adapter does not support signAllTransactions"),signMessage:async a=>s.signMessage!==void 0?await s.signMessage(a):new Error("Adapter does not support signMessage"),signIn:async a=>s.signIn!==void 0?await s.signIn(a):new Error("Adapter does not support signIn"),customFunctions:["sendSerializedTransaction","signAllSerializedTransactions","signSerializedTransaction"],sendSerializedTransaction:async(a,l)=>{const c=new Fj(l),u=new Uint8Array(a);let h;try{h=Vo.deserialize(u)}catch(p){try{h=cr.from(u)}catch(g){throw new Error("Failed to deserialize transaction as either versioned or legacy format")}}return await s.sendTransaction(h,c)},signSerializedTransaction:async a=>{if(s.signTransaction===void 0)return new Error("Adapter does not support signTransaction");const l=new Uint8Array(a);let c;try{c=Vo.deserialize(l)}catch(u){try{c=cr.from(l)}catch(h){return new Error("Failed to deserialize transaction as either versioned or legacy format")}}return await s.signTransaction(c)},signAllSerializedTransactions:async a=>{if(s.signAllTransactions===void 0)return new Error("Adapter does not support signAllTransactions");const l=[];for(const c of a){const u=new Uint8Array(c);let h;try{h=Vo.deserialize(u)}catch(p){try{h=cr.from(u)}catch(g){return new Error("Failed to deserialize one or more transactions")}}l.push(h)}return await s.signAllTransactions(l)}}:void 0}),i.add(o.name)}return r}isSolanaWallet(e){return(e.chains||[]).some(i=>i.startsWith("solana:"))}generateWalletId(e){var r;const n=((r=e.chains)==null?void 0:r[0])||"unknown";return`${e.name}-${n}`.toLowerCase().replace(/\s+/g,"-")}destroy(){this.handshakeComplete=!1,this.parentAPI&&(this.parentAPI.eip6963Wallets=[],this.parentAPI.walletStandardWallets=[],this.parentAPI=null),this.endpoint=null,this.iframe=null}}var yp=function(){return yp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},yp.apply(this,arguments)},CE=function(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(u){try{c(r.next(u))}catch(h){s(h)}}function l(u){try{c(r.throw(u))}catch(h){s(h)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},AE=function(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(n=0)),n;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,i=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){n.label=c[1];break}if(c[0]===6&&n.label<o[1]){n.label=o[1],o=c;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(c);break}o[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},Ae,OE,cd,bp=mg,jo=null,kE=function(){return document.getElementById(bp)};function _p(t){var e,n=kE();if(!n){console.warn("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe - no iframe element found"));return}if(!cd){console.warn("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe - no link token origin found"));return}try{(e=n.contentWindow)===null||e===void 0||e.postMessage(t,cd)}catch(r){console.error("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe")),console.error(r)}}function Yj(t){return CE(this,void 0,void 0,function(){var e,e,e,e,n,r,i,o,s,a,l,c,u,h;return AE(this,function(p){switch(t.data.type){case"brokerageAccountAccessToken":{e={accessToken:t.data.payload},(n=Ae==null?void 0:Ae.onEvent)===null||n===void 0||n.call(Ae,{type:"integrationConnected",payload:e}),(r=Ae==null?void 0:Ae.onIntegrationConnected)===null||r===void 0||r.call(Ae,e);break}case"delayedAuthentication":{e={delayedAuth:t.data.payload},(i=Ae==null?void 0:Ae.onEvent)===null||i===void 0||i.call(Ae,{type:"integrationConnected",payload:e}),(o=Ae==null?void 0:Ae.onIntegrationConnected)===null||o===void 0||o.call(Ae,e);break}case"transferFinished":{e=t.data.payload,(s=Ae==null?void 0:Ae.onEvent)===null||s===void 0||s.call(Ae,{type:"transferCompleted",payload:e}),(a=Ae==null?void 0:Ae.onTransferFinished)===null||a===void 0||a.call(Ae,e);break}case"close":case"done":{e=(l=t.data)===null||l===void 0?void 0:l.payload,(c=Ae==null?void 0:Ae.onExit)===null||c===void 0||c.call(Ae,e==null?void 0:e.errorMessage,e),jo==null||jo.destroy(),vg();break}case"loaded":{_p({type:"meshSDKSpecs",payload:yp({},dV)}),Ae!=null&&Ae.accessTokens&&_p({type:"frontAccessTokens",payload:Ae.accessTokens}),Ae!=null&&Ae.transferDestinationTokens&&_p({type:"frontTransferDestinationTokens",payload:Ae.transferDestinationTokens}),(u=Ae==null?void 0:Ae.onEvent)===null||u===void 0||u.call(Ae,{type:"pageLoaded"});break}default:{sV(t.data.type)&&((h=Ae==null?void 0:Ae.onEvent)===null||h===void 0||h.call(Ae,t.data));break}}return[2]})})}function xp(t){return CE(this,void 0,void 0,function(){return AE(this,function(e){switch(e.label){case 0:return t.origin!==OE&&t.origin!==cd?(console.warn("Received message from untrusted origin:",t.origin),[3,3]):[3,1];case 1:return[4,Yj(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})}var TE=function(t){var e=function(r,i){var o,s;if(!r){(o=t==null?void 0:t.onExit)===null||o===void 0||o.call(t,"Invalid link token!");return}Ae=t;var a=window.atob(r),l=a.startsWith("http://")||a.startsWith("https://");if(!l){(s=t==null?void 0:t.onExit)===null||s===void 0||s.call(t,"Invalid link token!");return}if(a=Xj(a,Ae==null?void 0:Ae.language),a=Zj(a,Ae==null?void 0:Ae.displayFiatCurrency),a=Jj(a,Ae==null?void 0:Ae.theme),cd=new URL(a).origin,window.removeEventListener("message",xp),i){var c=document.getElementById(i);c?(c.allow="clipboard-read *; clipboard-write *",c.src=a,bp=i):console.warn("Mesh SDK: No iframe found with id ".concat(i))}else bp=mg,cV(a);window.addEventListener("message",xp),OE=window.location.origin;var u=kE();u&&(jo=new Kj(u))},n=function(){var r;jo==null||jo.destroy(),vg(),window.removeEventListener("message",xp),(r=t.onExit)===null||r===void 0||r.call(t)};return{openLink:e,closeLink:n}};function Xj(t,e){return e==="system"&&(e=typeof navigator!="undefined"&&navigator.language?encodeURIComponent(navigator.language):void 0),"".concat(t).concat(t.includes("?")?"&":"?","lng=").concat(e||"en")}function Zj(t,e){return e?"".concat(t).concat(t.includes("?")?"&":"?","fiatCur=").concat(e):t}function Jj(t,e){return e?"".concat(t).concat(t.includes("?")?"&":"?","th=").concat(e):t}const Qj="Swap not found for a required underlying of defi route, please make sure your amount is within an acceptable range",eq="coingecko",tq=t=>t.includes(eq)?t.replace("/thumb/","/large/"):t,RE=({token:t,chainId:e,size:n=32})=>w.jsxs(ue,{position:"relative",borderRadius:"50%",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:t!=null&&t.logoURI?tq(t==null?void 0:t.logoURI):Is,title:t==null?void 0:t.symbol,alt:t==null?void 0:t.symbol,width:`${n}px`,height:`${n}px`})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid",borderColor:"bg",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),ud=()=>{const{address:t}=et.useAccount(),{walletIcon:e,walletDisplayName:n}=f1(),{chainIdOut:r,effectiveTokenOutData:i,tokenInData:o,amountIn:s,chainIdIn:a,selectedIntegration:l,isNontokenized:c}=yr(),{routeLoading:u,routeData:h,routeFetched:p,routerError:g}=Ms(),b=u||!p&&!g,m=h!=null&&h.error||(h==null?void 0:h.statusCode)===500?Qj:null,x=Iu({hash:t,chainId:a,type:"/address"}),I=Iu({hash:t,chainId:r,type:"/address"}),N=K.useMemo(()=>{if(l!=null&&l.type){const T=hd[l.type],$=l.name||l.type;return w.jsxs(w.Fragment,{children:[T&&w.jsx(Rn,{src:T,width:"16px",height:"16px",borderRadius:"full"}),w.jsx(Te,{children:$})]})}return w.jsxs(w.Fragment,{children:[typeof e=="string"?w.jsx(Rn,{src:e,width:"16px",height:"16px"}):e,w.jsx(Kf,{content:n,children:w.jsx(Te,{children:t&&n+" "+ug(t,!0)})}),x&&w.jsx(Vf,{href:x,target:"_blank",children:w.jsx(on,{as:H_,color:"fg.muted",width:"16px",height:"16px"})})]})},[l,e,n,t,x]);return w.jsxs(w.Fragment,{children:[w.jsx(hu,{size:"sm",variant:"outline",width:"100%",borderRadius:"sm",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Source"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(ue,{display:"flex",gap:"8px",alignItems:"center",children:N})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Destination"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(jr,{loading:b,width:b?"80px":"auto",children:w.jsxs(tr,{gap:"8px",alignItems:"center",children:[w.jsx(Rn,{src:dg(r),width:"16px",height:"16px"}),w.jsx(Te,{children:l1(r)})," - ",w.jsx(Kf,{content:n,children:w.jsx(Te,{children:t&&ug(t)})}),I&&w.jsx(Vf,{href:I,target:"_blank",children:w.jsx(on,{as:H_,color:"fg.muted",width:"16px",height:"16px"})})]})})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Estimated time"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(jr,{loading:b,width:b?"80px":"auto",children:w.jsx(Te,{children:l!=null&&l.type?"~2min":a!==r?"~1 min":"instant"})})})]})]})},"line"),m?w.jsx(Te,{fontSize:"xs",color:"error",children:m}):w.jsx(hu,{size:"sm",variant:"outline",bg:"bg.subtle",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"You send"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsxs(ue,{display:"flex",gap:"8px",alignItems:"center",children:[w.jsxs(Te,{children:[kr(ir(s,o==null?void 0:o.decimals))," ",o==null?void 0:o.symbol]}),w.jsx(RE,{token:o,chainId:a,size:24})]})})]}),w.jsxs(En,{children:[w.jsx(je,{children:c&&(i!=null&&i.protocol)?`Deposit into ${i.protocolName||i.protocol}`:"You receive"}),w.jsxs(je,{display:"flex",textAlign:"end",justifyContent:"end",children:[" ",w.jsx(jr,{loading:b,width:b?"156px":"auto",children:w.jsxs(ue,{display:"flex",gap:"8px",alignItems:"center",children:[w.jsxs(Te,{children:[kr(ir(h==null?void 0:h.amountOut,i==null?void 0:i.decimals))," ",i==null?void 0:i.symbol]}),c&&(i!=null&&i.protocol)?w.jsxs(ue,{position:"relative",minW:"24px",minH:"24px",children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:"24px",height:"24px",children:w.jsx("img",{src:i.protocolLogo||Is,title:i.protocol,alt:i.protocol,width:"24px",height:"24px",onError:T=>{T.currentTarget.src=Is}})}),r&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:"12px",height:"12px",borderRadius:"50%",overflow:"hidden",border:"1px solid",borderColor:"bg",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[r]}.svg`,alt:`Chain ${r}`,width:"100%",height:"100%"})})]}):w.jsx(RE,{token:i,chainId:r,size:24})]})})]})]})]})},"line")]})},nq=()=>{var l;const{routeData:t}=Ms(),{tokenIn:e,chainIdIn:n,amountIn:r}=yr(),{data:i}=ll(n,Pt),{data:[o]}=Ls(Pt,n),s=K.useMemo(()=>{var u,h;let c=+((h=(u=t==null?void 0:t.tx)==null?void 0:u.value)!=null?h:0);return Ro(e,Pt)&&(c-=+r),ir(Math.max(0,c).toString(),18)},[(l=t==null?void 0:t.tx)==null?void 0:l.value,e,r]),a=+s*+(i!=null?i:0);return w.jsxs(Te,{title:"Bridging fee",cursor:"default",display:"flex",alignItems:"center",gap:1,color:"fg.subtle",fontSize:"xs",children:[w.jsx(q4,{size:12}),w.jsx(Kf,{content:`${kr(s,!0)} ${o==null?void 0:o.symbol}`,children:w.jsx(Te,{fontSize:"xs",color:"fg.subtle",children:Tr(a)})})]})};We("div",{base:{display:"flex",justifyContent:"space-between",alignItems:"center",h:"36px",p:"8px 12px",borderRadius:"8px",bg:"bg",w:"100%"}});const dd=()=>{const{routeData:t}=Ms(),{chainIdIn:e,chainIdOut:n,selectedIntegration:r}=yr(),i=Me(c=>c.slippage),[o,s]=K.useState(!1),l=[{detail:`${t!=null&&t.priceImpact?(-(t==null?void 0:t.priceImpact)/100).toFixed(2):"0.00"}%`,label:"Est. price impact"},{detail:`${i/100}%`,label:"Max. slippage"},{detail:r!=null&&r.type?"~2min":e!==n?"~1 min":"instant",label:"Est. processing time"}];return w.jsx(x4,{open:o,onOpenChange:c=>s(c.open),w:"full",children:w.jsxs(ue,{width:"100%",bg:"bg.subtle",borderRadius:"md",padding:"12px",transition:"all 0.2s",children:[w.jsx(w4,{asChild:!0,children:w.jsxs(tr,{align:"center",justify:"space-between",width:"100%",cursor:"pointer",children:[w.jsxs(tr,{align:"center",gap:2,children:[w.jsx(Vi,{color:"fg.muted",fontSize:"sm",children:"Transaction details"}),w.jsx(on,{as:H4,width:"14px",height:"14px",color:"fg.muted",transform:o?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"})]}),w.jsx(nq,{})]})}),w.jsx(E4,{children:w.jsx(ue,{marginTop:"12px",paddingTop:"12px",borderTop:"1px solid",borderColor:"border",children:l.map((c,u)=>w.jsxs(tr,{justify:"space-between",align:"center",paddingY:"6px",children:[w.jsx(Vi,{fontSize:"sm",color:"fg.muted",children:c.label}),w.jsx(Vi,{fontSize:"sm",color:"fg",fontWeight:"medium",children:c.detail})]},u))})})]})})},rq=We("div",{base:{w:"58px",h:"58px",borderRadius:"full",border:"1px solid",borderColor:"border",display:"flex",alignItems:"center",justifyContent:"center"}}),NE=({onFinish:t,start:e,duration:n=60})=>{const[r,i]=K.useState(n);K.useEffect(()=>{i(n)},[n]),K.useEffect(()=>{if(!e)return;const s=setInterval(()=>{i(a=>a<=1?(clearInterval(s),t==null||t(),0):a-1)},1e3);return()=>clearInterval(s)},[e,t]);const o=s=>{const a=Math.floor(s/60).toString().padStart(2,"0"),l=(s%60).toString().padStart(2,"0");return`${a}:${l}`};return w.jsx(Es,{children:w.jsx(rq,{children:w.jsx(Te,{fontSize:"xs",color:"fg.muted",fontWeight:"medium",children:o(r)})})})},iq="data:image/svg+xml,%3csvg%20width='17'%20height='16'%20viewBox='0%200%2017%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_126_8587)'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M16.3686%2010.6232C16.3715%2010.6146%2016.359%2010.6097%2016.355%2010.6179C14.975%2013.5085%2012.2144%2015.5112%208.66017%2015.5112C4.88611%2015.5112%201.35008%2012.688%201.35008%208.37011C1.35008%204.65011%204.30812%201.56104%207.74213%201.56104C10.6321%201.56104%2012.6382%203.28819%2012.6382%204.51714C12.6382%205.08189%2012.2642%205.48041%2011.6862%205.48041C10.3602%205.48041%209.85022%203.15536%207.33413%203.15536C4.78406%203.15536%202.6081%205.54683%202.6081%208.37011C2.6081%2012.0238%205.56614%2014.4153%208.52417%2014.4153C9.68043%2014.4153%2010.322%2014.1182%2010.5073%2014.0169C10.515%2014.0126%2010.51%2014.0012%2010.5017%2014.0037C10.3174%2014.0604%209.73839%2014.2159%208.93211%2014.2159C5.29405%2014.2159%203.83206%2011.4591%203.83206%209.66544C3.83206%208.30367%204.71606%207.73906%205.43016%207.73906C7.33413%207.73906%207.06219%2011.7248%2011.7542%2011.7248C14.2023%2011.7248%2016.4803%2010.0972%2016.4803%206.87544C16.4803%203.22178%2012.9442%200%208.66017%200C4.17214%200%200.5%203.554%200.5%207.97156C0.5%2012.4223%204.30812%2015.9763%208.66017%2015.9763C12.4804%2015.9763%2015.3429%2013.5242%2016.3686%2010.6232Z'%20fill='%231E171F'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_126_8587'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(0.5)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",oq="data:image/svg+xml,%3csvg%20width='32'%20height='33'%20viewBox='0%200%2032%2033'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20y='0.5'%20width='32'%20height='32'%20rx='16'%20fill='%232F2B32'/%3e%3cpath%20d='M22.5582%2020.6133L16.0006%2027.1709L9.4469%2020.6172L9.44397%2020.6133L11.858%2018.2061L16.0006%2022.3496L20.1481%2018.2021L22.5582%2020.6133ZM18.4469%2016.502L16.0006%2018.9521L13.5543%2016.5059V16.498L13.984%2016.0693L14.194%2015.8633L16.0006%2014.0557L18.4469%2016.502ZM26.6666%2016.5029L24.2565%2018.9131L21.8473%2016.5029L24.2565%2014.0928L26.6666%2016.5029ZM10.153%2016.501L7.7428%2018.9111L5.33264%2016.501L7.7428%2014.0908L10.153%2016.501ZM22.5582%2012.3906L20.1481%2014.8018L16.0006%2010.6543L11.858%2014.7979L9.4469%2012.3867L16.0006%205.83301L22.5582%2012.3906Z'%20fill='%23F3BA2F'/%3e%3c/svg%3e",wp=({icon:t,title:e,description:n})=>w.jsxs(ue,{display:"flex",flexDirection:"row",gap:"16px",width:"100%",alignItems:"flex-start",children:[w.jsx(on,{as:t,color:"fg.muted",width:"20px",height:"20px",marginTop:"2px"}),w.jsxs(ue,{display:"flex",flexDirection:"column",gap:"4px",flex:"1",children:[w.jsx(ue,{fontWeight:"600",fontSize:"14px",lineHeight:"120%",color:"fg",children:e}),w.jsx(ue,{fontWeight:"400",fontSize:"12px",lineHeight:"140%",color:"fg.subtle",children:n})]})]}),sq=({onConfirm:t,exchangeName:e="your exchange",exchangeIcon:n})=>w.jsxs(tn,{children:[w.jsx(ue,{display:"flex",justifyContent:"center",width:"100%",children:w.jsx(Rn,{w:"48px",h:"48px",borderRadius:"full",src:n||oq})}),w.jsxs(ue,{fontWeight:"600",fontSize:"16px",lineHeight:"140%",color:"fg",textAlign:"center",children:["Enso Checkout uses a 3rd party to connect your ",e," account."]}),w.jsxs(ue,{display:"flex",flexDirection:"column",gap:"12px",width:"100%",children:[w.jsx(wp,{icon:G4,title:"Your sign-in credentials are never stored",description:"All data is encrypted between enso and Binance"}),w.jsx(wp,{icon:Y4,title:"2fa always required",description:"Transfers cannot be made without your approval."}),w.jsx(wp,{icon:K4,title:"Assets never touch 3rd parties",description:"Your funds are transferred directly to your wallet."}),w.jsxs(mB,{children:[w.jsx(Rn,{src:iq,color:"gray",w:"24px"}),"Enso securely encrypts all user data."]})]}),w.jsx(nr,{onClick:t,children:"Continue to 3rd Party"})]}),PE="data:image/svg+xml,%3csvg%20width='58'%20height='58'%20viewBox='0%200%2058%2058'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='29'%20cy='29'%20r='29'%20fill='%2314AE5C'/%3e%3cpath%20d='M36.2929%2022.2929C36.6834%2021.9024%2037.3164%2021.9024%2037.707%2022.2929C38.0975%2022.6834%2038.0975%2023.3164%2037.707%2023.707L26.707%2034.707C26.3164%2035.0975%2025.6834%2035.0975%2025.2929%2034.707L20.2929%2029.707C19.9024%2029.3164%2019.9024%2028.6834%2020.2929%2028.2929C20.659%2027.9268%2021.238%2027.9042%2021.6308%2028.2245L21.707%2028.2929L25.9999%2032.5859L36.2929%2022.2929Z'%20fill='white'/%3e%3c/svg%3e",LE="data:image/svg+xml,%3csvg%20width='58'%20height='58'%20viewBox='0%200%2058%2058'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='29'%20cy='29'%20r='29'%20fill='%23E84142'/%3e%3cpath%20d='M34.2929%2022.2929C34.6834%2021.9024%2035.3164%2021.9024%2035.707%2022.2929C36.0975%2022.6834%2036.0975%2023.3164%2035.707%2023.707L23.707%2035.707C23.3164%2036.0975%2022.6834%2036.0975%2022.2929%2035.707C21.9024%2035.3164%2021.9024%2034.6834%2022.2929%2034.2929L34.2929%2022.2929Z'%20fill='white'/%3e%3cpath%20d='M22.2929%2022.2929C22.6834%2021.9024%2023.3164%2021.9024%2023.707%2022.2929L35.707%2034.2929L35.7753%2034.3691C36.0957%2034.7618%2036.0731%2035.3408%2035.707%2035.707C35.3408%2036.0731%2034.7618%2036.0957%2034.3691%2035.7753L34.2929%2035.707L22.2929%2023.707C21.9024%2023.3164%2021.9024%2022.6834%2022.2929%2022.2929Z'%20fill='white'/%3e%3c/svg%3e";var Qr=(t=>(t.Binance="binance",t.Kraken="kraken",t.Coinbase="coinbase",t.Bybit="bybit",t))(Qr||{});const Qs=ox(t=>({txs:[],addTx:e=>t(n=>({txs:[...n.txs,e]})),removeTx:e=>t(n=>({txs:n.txs.filter(r=>r.hash!==e)})),updateTx:(e,n)=>t(r=>({txs:r.txs.map(i=>i.hash===e?{...i,...n}:i)}))})),aq=t=>{const{txs:e}=Qs();return e.find(n=>n.hash===t)},lq=()=>{const{addTx:t}=Qs();return{track:K.useCallback(n=>{n.hash&&t(n)},[])}},cq=(t,e=!0)=>{var l,c;const{data:n,isLoading:r}=Kn.useQuery({queryKey:["layerZeroStatus",t||"none"],queryFn:async()=>t?fetch(`https://scan.layerzero-api.com/v1/messages/tx/${t}`).then(u=>u.json()).then(u=>{var h,p;return(p=(h=u.data)==null?void 0:h[0])!=null?p:null}):null,refetchInterval:2e3,enabled:e&&!!t}),i=(l=n==null?void 0:n.status)==null?void 0:l.name,o=(c=n==null?void 0:n.source)==null?void 0:c.status;let s=0,a="Waiting for bridge transaction...";return o&&o!=="SUCCEEDED"?(s=1,a="Waiting for funds to be sent on destination"):i==="INFLIGHT"?(s=2,a="Waiting for funds to be delivered on destination"):i==="CONFIRMING"?(s=3,a="Waiting for destination execution"):i==="DELIVERED"&&(s=4,a="Bridging is complete"),{data:n,isLoading:r,status:i,sourceStatus:o,step:s,message:a,isComplete:i==="DELIVERED",isFailed:i==="FAILED"}},uq=(t,e)=>{const n=Qs(i=>i.updateTx),{data:r}=Kn.useQuery({queryKey:["layerZeroUrl",t||"none",!!e],queryFn:async()=>t?fetch(`https://scan.layerzero-api.com/v1/messages/tx/${t}`).then(i=>i.json()).then(i=>i.data[0]):null,refetchInterval:2e3,enabled:!!(e&&t)});K.useEffect(()=>{var i,o,s,a;t&&((i=r==null?void 0:r.source)!=null&&i.status&&r.source.status!=="SUCCEEDED"?n(t,{status:"(1/4) Waiting for funds to be sent on destination"}):((o=r==null?void 0:r.status)==null?void 0:o.name)==="DELIVERED"?(e==null||e(),n(t,{status:"(4/4) Bridging is complete",isActive:!1})):((s=r==null?void 0:r.status)==null?void 0:s.name)==="CONFIRMING"?n(t,{status:"(3/4) Waiting for destination execution"}):((a=r==null?void 0:r.status)==null?void 0:a.name)==="INFLIGHT"&&n(t,{status:"(2/4) Waiting for funds to be delivered on destination"}))},[r,t])},dq=(t,e,n,r,i)=>{const o=Iu({hash:t,chainId:e}),s=Qs(a=>a.updateTx);K.useEffect(()=>{i&&(r.error?s(t,{status:"Transaction Failed",isActive:!1}):r.data&&(i==null||i(),s(t,{status:"Transaction Confirmed",isActive:!1})))},[r.data,r.error,r.isLoading,n,o,i])},hq=({hash:t,chainId:e,message:n="Transaction confirmed",onConfirmed:r})=>{const{removeTx:i}=Qs(),o=et.useWaitForTransactionReceipt({hash:t,chainId:e});return K.useEffect(()=>{o.data&&(r==null||r(o.data))},[o.data,r]),dq(t,e,n,o,()=>i(t)),null},fq=({hash:t,chainId:e,onConfirmed:n})=>{const r=et.useWaitForTransactionReceipt({hash:t,chainId:e});return uq(r.data?t:void 0,()=>n==null?void 0:n(r.data)),null},gq=t=>t.crosschain?w.jsx(fq,{...t}):w.jsx(hq,{...t}),pq=()=>{const{txs:t}=Qs();return w.jsx(w.Fragment,{children:t.filter(e=>e.isActive).map(e=>w.jsx(gq,{...e},e.hash))})},mq="0x0000000071727de22e5e9d8baf0edac6f37da032",ea={[Qr.Binance]:"binanceInternationalDirect",[Qr.Kraken]:"krakenDirect",[Qr.Coinbase]:"coinbase",[Qr.Bybit]:"bybitDirect"},hd={[ea[Qr.Binance]]:"https://assets.coingecko.com/markets/images/52/large/binance.jpg",[ea[Qr.Kraken]]:"https://assets.coingecko.com/markets/images/29/large/kraken.jpg",[ea[Qr.Coinbase]]:"https://assets.coingecko.com/markets/images/23/large/Coinbase_Coin_Primary.png",[ea[Qr.Bybit]]:"https://assets.coingecko.com/markets/images/698/large/bybit_spot.png"},vq=t=>t==="delayed",Tl="https://mesh-bff.enso-checkout.workers.dev";var fd=(t=>(t[t.CheckSessionKey=0]="CheckSessionKey",t[t.ChooseExchange=1]="ChooseExchange",t[t.ChooseExchangeAsset=2]="ChooseExchangeAsset",t[t.ChooseBalanceAsset=3]="ChooseBalanceAsset",t[t.ChooseAmount=4]="ChooseAmount",t[t.SignUserOp=5]="SignUserOp",t[t.InitiateWithdrawal=6]="InitiateWithdrawal",t[t.TrackUserOp=7]="TrackUserOp",t))(fd||{});const ME=[1,2,4,5,6],yq=[3,4,5],Ep={1:"e3c7fdd8-b1fc-4e51-85ae-bb276e075611",8453:"aa883b03-120d-477c-a588-37c2afd3ca71",42161:"a34f2431-0ddd-4de4-bc22-4a8143287aeb",137:"7436e9d0-ba42-4d2b-b4c0-8e4e606b2c12",10:"18fa36b0-88a8-43ca-83db-9a874e0a2288",43114:"bad16371-c22a-4bf4-a311-274d046cd760",56:"ed0ebeec-b166-4c8b-8574-cb078f7af8cf",146:"385f0b3a-8471-4b8f-884f-c4f4496f1603"},BE=Object.keys(Ep).map(Number),bq=t=>Ep[t]||Ep[8453],FE=()=>{const{setMeshAccessToken:t}=Me(),e=gd(),n=Me(r=>r.selectedIntegration);return K.useCallback((r,i)=>{t(r),sessionStorage.setItem(`${e}:${n==null?void 0:n.type}`,JSON.stringify({accessTokenPayload:r,sessionId:i,timestamp:Date.now()}))},[e,n==null?void 0:n.type])},_q=({setStep:t})=>{var b;const{chainIdOut:e,setChainIdIn:n}=Me(),[r,i]=K.useState([]),[o,s]=K.useState(!0),[a,l]=K.useState(null),c=Me(m=>m.setSelectedIntegration),{enableExchange:u,cexBridgeChainMapping:h}=K.useContext(ic),p=h!=null?h:Jf,g=(b=RB(e,p))!=null?b:e;return K.useEffect(()=>{g&&n(g)},[g,n]),K.useEffect(()=>{(async()=>{try{const I=await(await fetch(`${Tl}/integrations`)).json(),N=u.map($=>ea[$]).filter(Boolean),T=I==null?void 0:I.filter($=>$.networks.some(B=>+B.chainId===g)&&N.includes($.type));i(T)}catch(x){console.error("Failed to fetch integrations",x),l("Failed to load exchanges")}finally{s(!1)}})()},[g]),o?w.jsx(Es,{children:w.jsx(Co,{m:5})}):a?w.jsx(tn,{children:w.jsx(ue,{p:5,color:"red.500",children:a})}):w.jsx(tn,{children:(r==null?void 0:r.length)>0?w.jsx(Oo,{children:r.map(m=>w.jsx(Eu,{icon:hd[m.type],title:m.name,balance:"",usdBalance:"",tag:"",loading:!1,selected:!1,onClick:()=>{c({id:m.id,type:m.type,name:m.name}),t(0)}},m.id))}):w.jsx(ue,{textAlign:"center",fontSize:"sm",color:"fg.subtle",py:3,children:"No exchanges available for specified target chain"})})},xq=({setStep:t})=>{const{chainIdIn:e,chainIdOut:n,setMeshAccessToken:r,setSessionId:i}=Me(),{address:o}=et.useAccount(),s=gd(),[a,l]=K.useState(!1),c=Me(b=>b.selectedIntegration),u=e!==n,h=n&&!BE.includes(n)&&!u,p=FE();K.useEffect(()=>{if(!c){t(1);return}if(h)return;const b=sessionStorage.getItem(`${s}:${c.type}`);if(b)try{const m=JSON.parse(b);if(m!=null&&m.accessTokenPayload&&(m!=null&&m.sessionId)){r(m.accessTokenPayload),i(m.sessionId),t(2);return}}catch(m){console.error("Failed to parse saved Mesh connection",m)}l(!0)},[s,h,c]);const g=()=>{const b=c==null?void 0:c.type;fetch(`${Tl}/linktoken?brokerType=${encodeURIComponent(b)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:s,integrationId:c==null?void 0:c.id,address:o})}).then(m=>m.json()).then(m=>{i(m.content.sessionId);const x=TE({clientId:o,onIntegrationConnected:I=>{console.log("onIntegrationConnected",I),x.closeLink(),t(2),p(I.accessToken,m.content.sessionId)},onExit:I=>{console.log("onExit",I)},onTransferFinished:I=>{console.log("onTransferFinished",I)},onEvent:I=>{console.log(I)}});x.openLink(m.content.linkToken)}).catch(m=>console.error(m))};return h?w.jsx(tn,{children:w.jsxs(ue,{textAlign:"center",py:8,children:[w.jsx(Te,{fontSize:"lg",fontWeight:"bold",color:"red.500",mb:4,children:"Unsupported Network"}),w.jsxs(Te,{color:"fg.muted",mb:6,children:["The selected network (Chain ID: ",n,") is not supported for exchange transactions. Please switch to a supported network such as: ",BE.join(", ")]})]})}):a?w.jsx(sq,{onConfirm:g,exchangeName:c==null?void 0:c.name,exchangeIcon:c!=null&&c.type?hd[c.type]:void 0}):w.jsx(Co,{m:5})},DE="meshDeviceId",gd=()=>K.useMemo(()=>{let t=localStorage.getItem(DE);return t||(t=`device_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,localStorage.setItem(DE,t)),t},[]),wq=({setStep:t,onTokenSelect:e})=>{const[n,r]=K.useState([]),[i,o]=K.useState(null),[s,a]=K.useState(!0),[l,c]=K.useState(null),{address:u}=et.useAccount(),{meshAccessToken:h,sessionId:p,setMeshAccessToken:g,setSessionId:b,setTokenIn:m,chainIdIn:x}=Me(),I=gd(),N=Me($=>$.selectedIntegration);K.useEffect(()=>{h&&p&&x&&N&&(async()=>{var B,G,Z,Y;try{const V=await(await fetch(`${Tl}/holdings`,{method:"POST",headers:{"Content-Type":"application/json","x-session-id":p},body:JSON.stringify({authToken:(G=(B=h==null?void 0:h.accountTokens)==null?void 0:B[0])==null?void 0:G.accessToken,brokerType:N==null?void 0:N.type})})).json();if(console.log("Holdings data:",V),V.status!=="ok"||!((Z=V.content)!=null&&Z.cryptocurrencyPositions))throw V.errorType==="invalidIntegrationToken"&&(console.log("Invalid integration token"),t(0),g(null),b(null),sessionStorage.removeItem(`${I}:${N==null?void 0:N.type}`)),new Error(V.message||"Failed to fetch holdings");const W=await(await fetch(`${Tl}/tokens?chainId=${x}&brokerType=${encodeURIComponent((N==null?void 0:N.type)||"")}`)).json();if(W.status==="success"&&((Y=W.content)!=null&&Y.tokens)){const A=W.content.tokens.map(d=>{const y=V.content.cryptocurrencyPositions.find(S=>S.symbol===d.symbol);return y?{...d,balance:y.amount,marketValue:y.marketValue,holding:y}:null}).filter(d=>d!==null&&d.marketValue>5).sort((d,y)=>y.marketValue-d.marketValue);console.log("Matched tokens with balances:",A),r(A)}else throw new Error(W.message||"Failed to fetch supported tokens")}catch(F){debugger;console.error("Error fetching data:",F),c(F instanceof Error?F.message:"Failed to fetch data")}finally{a(!1)}})()},[u,x,h,p,N]);const T=$D(n.map($=>$.symbol),x);return s?w.jsx(Es,{children:w.jsx(Co,{m:5})}):l?w.jsxs(ue,{p:5,color:"red.500",children:["Error: ",l]}):w.jsxs(tn,{children:[w.jsxs(ue,{mb:4,width:"100%",textAlign:"left",children:[w.jsx(Ao,{children:"Your Holdings"}),w.jsxs(Zf,{children:["Found ",n.length," token balances above $5"]})]}),w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:n.map(($,B)=>{var G,Z;return w.jsx(Eu,{chainId:x,icon:(Z=(G=T==null?void 0:T[B])==null?void 0:G.logoURI)==null?void 0:Z.replace("/thumb/","/large/"),title:$.name,balance:`${kr($.balance)} ${$.symbol}`,usdBalance:Tr($.marketValue||0),tag:"",loading:!1,selected:i===$.symbol,onClick:()=>{var Y;o($.symbol),e($),m((Y=T==null?void 0:T[B])==null?void 0:Y.address)}},`${$.symbol}-${B}`)})})}),n.length===0&&w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No tokens with balances found for this chain"}),w.jsx(nr,{disabled:!i,onClick:()=>{t(4)},children:"Continue"})]})},Eq=({setStep:t,onTokenSelect:e})=>{const{chainIdIn:n,setTokenIn:r,setChainIdIn:i}=Me(),[o,s]=K.useState(null),{holdingsList:a,total:l,isLoading:c}=h1(1),u=Me(h=>h.setSelectedIntegration);return K.useEffect(()=>{u({type:"delayed",name:"Smart account",id:""})},[]),c?w.jsx(Es,{children:w.jsx(Co,{m:5})}):w.jsxs(tn,{children:[w.jsx(ue,{mb:4,width:"100%",textAlign:"left",children:w.jsxs(Zf,{children:["Smart Account Balance: ",Tr(l)]})}),w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:a==null?void 0:a.map(h=>w.jsx(Eu,{chainId:h.chainId,icon:h.logoUri,title:h.name,balance:`${kr(ir(h.amount,h.decimals))} ${h.symbol}`,usdBalance:Tr(h.total),tag:"",loading:!1,selected:o===h.token&&n===h.chainId,onClick:()=>{s(h.token),r(h.token),i(h.chainId);const p={symbol:h.symbol,name:h.name,networkId:h.chainId.toString(),chainId:h.chainId,integrationNetworks:[],balance:Number(ir(h.amount,h.decimals)),marketValue:h.total};e(p)}},`${h.token}-${h.chainId}`))})}),(a==null?void 0:a.length)===0&&w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No tokens found in smart account"}),w.jsx(nr,{disabled:!o,onClick:()=>{t(4)},children:"Continue"})]})},Sq=({setStep:t,selectedToken:e})=>{var Y;const[n,r]=K.useState({tokenAmount:"",usdAmount:"",mode:"usd"}),i=Me(F=>F.setAmountIn),{tokenInData:o,selectedIntegration:s}=yr(),l=(e==null?void 0:e.symbol.toLowerCase().includes("USD"))?2:6,c=n.tokenAmount,u=n.usdAmount,h=!vq(s.type),p=e?h?(e.marketValue-ax).toFixed(2):e.marketValue.toFixed(2):0,g=K.useMemo(()=>{if(!(!e||!e.balance))return e.marketValue/e.balance},[e]),b=K.useCallback(F=>{if(!e)return;const V=e.marketValue*F/100;let U,W;if(h){const A=sx[e.symbol]||0;U=Math.max(A,Math.min(V,+p));const d=e.marketValue/e.balance;W=Math.min(U/d,e.balance)}else U=V,W=e.balance*F/100;return{tokenAmount:Cu(W,l),usdAmount:U.toFixed(2)}},[e,h,p,l]);K.useEffect(()=>{if(e){const F=b(100);if(!F)return;r(V=>({...V,...F}))}},[e,b]),K.useEffect(()=>{if(!(o!=null&&o.decimals))return;const F=c.endsWith(".")?c.slice(0,-1):c;if(!F||F==="."){i("0");return}try{i(r1(F,o.decimals))}catch(V){i("0")}},[c,o==null?void 0:o.decimals,i]);const m=fg(c),x=m!==null,I=!!u&&u!==".",N=e?x&&m!==null&&m>e.balance:!0,T=I&&(Y=fg(u))!=null?Y:0,$=h&&e?sx[e.symbol]:0,B=h&&e&&x&&T>0&&$&&m!==null&&m<$,G=h&&e&&x&&T>0&&T>+p,Z=!x||B||G||N;return e?w.jsxs(tn,{children:[w.jsxs(ue,{mb:4,width:"100%",textAlign:"left",children:[w.jsx(Ao,{children:"Enter Amount"}),w.jsxs(Zf,{children:["Available: ",kr(e.balance)," ",e.symbol," (",Tr(e.marketValue),")"]})]}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"8px",width:"100%",children:w.jsx(g1,{value:n,onChange:r,tokenSymbol:e.symbol,tokenPriceUsd:g,roundingPrecision:l,onPercentSelect:b})}),w.jsx(ue,{textAlign:"center",color:"fg.subtle",fontSize:"xs",h:3,m:-1,visibility:Z?"visible":"hidden",children:x?B?`Minimum amount is ${kr($)} ${e.symbol}`:G?`Maximum amount is ${Tr(p)} (balance - $${ax})`:N?"Amount exceeds available balance":"":"Please enter an amount"}),w.jsx(nr,{onClick:()=>Z?void 0:t(5),disabled:Z,children:"Continue"})]}):w.jsx(tn,{children:w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No token selected"})})},Iq=({setStep:t,setUserOp:e,nextStep:n})=>{const{chainIdIn:r}=yr(),{routeLoading:i,usdAmountIn:o,routeData:s}=Ms(),{signMessageAsync:a}=et.useSignMessage(),{address:l}=et.useAccount(),[c,u]=K.useState(!1),h=async()=>{if(!s||s!=null&&s.error){console.error("No valid router data available");return}try{u(!0);const p=s==null?void 0:s.userOp;if(!p){console.error("No userOperation found in routeData");return}console.log("Signing userOperation:",p);const g=rV({userOperation:p,entryPointAddress:mq,entryPointVersion:"0.7",chainId:r}),b=await a({account:l,message:{raw:g}}),m={...p,signature:b};console.log("signedUserOp",JSON.stringify(m)),e(m),t(n)}catch(p){console.error("Failed to sign userOperation:",p)}finally{u(!1)}};return w.jsxs(tn,{children:[w.jsxs(tr,{flexDirection:"column",gap:"16px",alignItems:"center",width:"100%",children:[w.jsx(jr,{loading:i,width:i?"156px":"auto",children:w.jsx(Yf,{readOnly:!0,marginY:"8px",variant:"text",placeholder:"$10.00",value:o})}),w.jsx(ud,{})]}),w.jsx(dd,{}),w.jsx(nr,{disabled:!!(s!=null&&s.message)||i||c,loading:i||c,onClick:h,children:i?"Loading quote":c?"Signing...":"Sign Transaction"})]})},Cq=({selectedToken:t,userOp:e,setStep:n})=>{const{meshAccessToken:r,amountIn:i,chainIdIn:o}=Me(),{address:s}=et.useAccount(),{tokenInData:a}=yr(),l=Me(x=>x.sessionId),[c,u]=K.useState(!0),[h,p]=K.useState(null),g=Me(x=>x.selectedIntegration),b=FE(),m=gd();return K.useEffect(()=>{if(!t||!e||!r){console.error("Missing required data for withdrawal initiation");return}const x=a!=null&&a.decimals?ir(i,a.decimals):0;console.log("transferAmount",x),(async()=>{try{const N=[{networkId:bq(o),symbol:t.symbol,address:e.sender,amount:x}],T={restrictMultipleAccounts:!0,userId:m,integrationId:g==null?void 0:g.id,transferOptions:{toAddresses:N}};console.log("link request body",T);const B=await(await fetch(`${Tl}/linktoken?brokerType=${encodeURIComponent((g==null?void 0:g.type)||"")}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restrictMultipleAccounts:!0,userId:m,integrationId:g==null?void 0:g.id,transferOptions:{toAddresses:N}})})).json();console.log("Link token response:",B);const G=r.accountTokens.map(F=>({...F,accountId:F.account.accountId,accountName:F.account.accountName,brokerName:g==null?void 0:g.name,brokerType:g==null?void 0:g.type}));console.log("accessTokens",G);let Z=!1;const Y=TE({clientId:s,accessTokens:G,onIntegrationConnected:F=>{b(F.accessToken,l),console.log("Integration connected",F)},onTransferFinished:F=>{console.log("Transfer finished:",F),u(!1)},onExit:F=>{console.log("Mesh link exited:",F),!Z&&(u(!1),n(2))},onEvent:F=>{var V;if(console.log("Mesh event:",F),F.type==="transferExecuted")console.log("Transfer executed, closing mesh link and moving to TrackUserOp step"),Z=!0,Y.closeLink(),n(7);else if(F.type==="transferExecutionError"){const U=((V=F.payload)==null?void 0:V.errorMessage)||"Transfer failed. Please try again.";console.error("Mesh transfer error:",U),Z=!0,Y.closeLink(),p(U),u(!1)}}});Y.openLink(B.content.linkToken)}catch(N){console.error("Failed to fetch link token:",N),u(!1)}})()},[t,e]),h?w.jsx(tn,{children:w.jsxs(tr,{direction:"column",align:"center",justify:"center",flex:1,p:6,gap:4,children:[w.jsx(tr,{align:"center",justify:"center",w:12,h:12,borderRadius:"full",bg:"orange.100",children:w.jsx(on,{as:X4,boxSize:6,color:"orange.500"})}),w.jsx(Te,{fontSize:"md",textAlign:"center",color:"gray.700",children:h})]})}):w.jsx(tn,{children:w.jsx(Es,{children:w.jsx(Te,{mt:4,children:c?w.jsxs(tr,{alignItems:"center",gap:2,children:[w.jsx(Co,{m:5}),w.jsx(Te,{children:"Intiating Mesh"})]}):"Transfer completed"})})})},Aq=({currentPhase:t,phases:e})=>w.jsx(ue,{display:"flex",gap:4,justifyContent:"center",mb:4,children:e.map((n,r)=>w.jsxs(ue,{display:"flex",alignItems:"center",gap:2,children:[w.jsx(ue,{w:6,h:6,borderRadius:"full",bg:r<t?"green.500":r===t?"blue.500":"gray.300",display:"flex",alignItems:"center",justifyContent:"center",color:"white",fontSize:"xs",fontWeight:"bold",children:r<t?"✓":r+1}),w.jsx(Te,{fontSize:"sm",color:r===t?"fg":"fg.muted",fontWeight:r===t?"semibold":"normal",children:n})]},n))}),Oq=({selectedToken:t,userOp:e,setStep:n})=>{const{chainIdIn:r,chainIdOut:i,tokenInData:o}=yr(),{amountIn:s}=Me(),a=r!==i,[l,c]=K.useState("cex"),[u,h]=K.useState(null),[p,g]=K.useState("sending"),[b,m]=K.useState("Sending operation to tracker..."),[x,I]=K.useState(null),[N,T]=K.useState(!1),[$,B]=K.useState(null),[G,Z]=K.useState(!1),[Y,F]=K.useState(null),[V,U]=K.useState(null),[W,A]=K.useState(null),d=cq(x!=null?x:void 0,a&&l==="bridge");K.useEffect(()=>{(async()=>{if(!t||!e||!o){console.error("Missing required data for tracking"),g("failed"),m("Missing required data"),c("failed");return}try{const M=await(await fetch("https://alpha-scanners-dev-054573dc8549.herokuapp.com/operations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userOperationData:{sender:e.sender,nonce:e.nonce,factory:e.factory,factoryData:e.factoryData,callData:e.callData,callGasLimit:e.callGasLimit,verificationGasLimit:e.verificationGasLimit,preVerificationGas:e.preVerificationGas,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,paymaster:e.paymaster,paymasterData:e.paymasterData,paymasterVerificationGasLimit:e.paymasterVerificationGasLimit,paymasterPostOpGasLimit:e.paymasterPostOpGasLimit,signature:e.signature},chainId:r,expectedBalance:s,tokenAddress:o.address})})).json();if(console.log("Operation tracking response:",M),M.success&&M.operationId)h(M.operationId),g("tracking"),m(a?"Funds forwarding in progress...":"Tracking operation progress...");else throw new Error(M.message||"Failed to send operation to tracker")}catch(k){console.error("Failed to send operation to tracker:",k),g("failed"),m("Failed to send operation to tracker"),c("failed")}})()},[]),K.useEffect(()=>{if(!u||p!=="tracking")return;const k=setInterval(async()=>{var M,H,Q;try{const j=await(await fetch(`https://alpha-scanners-dev-054573dc8549.herokuapp.com/operations/${u}/status`)).json();console.log("Operation status:",j),((M=j.operation)==null?void 0:M.status)==="completed"?(g("completed"),a?(m("Funds forwarding completed!"),(H=j.operation)!=null&&H.bundleTxHash?(I(j.operation.bundleTxHash),c("bridge")):(console.warn("No bundleTxHash returned from indexer, cannot track bridge"),c("completed"))):(m("Operation completed successfully!"),c("completed")),$&&(clearInterval($),B(null))):["failed","failed_permanent"].includes((Q=j.operation)==null?void 0:Q.status)&&(g("failed"),m(a?"Bridging failed. Please select Smart-account balance as a source to use withdrawn funds":"Operation failed"),c("failed"),$&&(clearInterval($),B(null)))}catch(X){console.error("Failed to fetch operation status:",X)}},3e3);return B(k),()=>{k&&clearInterval(k)}},[u,p,a]),K.useEffect(()=>{if(!(!a||l!=="bridge")){if(d.isFailed){c("failed");return}d.isComplete&&!G&&x&&r&&(async()=>{var k;try{const M=await fetch(`https://api.enso.build/api/v1/layerzero/bridge/check?chainId=${r}&txHash=${x}`);if(!M.ok){Z(!0),F(!0),c("completed");return}const H=await M.json();Z(!0),A(H.destinationTxHash||null),H.status==="success"?(F(!0),c("completed")):H.status==="failed"?(F(!1),U(((k=H.ensoDestinationEvent)==null?void 0:k.refundDetails)||null),c("failed")):(F(!0),c("completed"))}catch(M){console.error("Failed to verify destination:",M),Z(!0),F(!0),c("completed")}})()}},[l,d.isComplete,d.isFailed,a,G,x,r]);const y=()=>{T(!0)},S=()=>l==="failed"?"failed":l==="completed"?"completed":"processing",C=()=>{switch(S()){case"completed":return"#14AE5C";case"failed":return"#E84142";default:return"#1E171F"}},R=()=>{switch(S()){case"completed":return"Success";case"failed":return"Failed";default:return"Processing"}},D=()=>a?l==="cex"?`(1/2) ${b}`:l==="bridge"?`(2/2) ${d.message}`:l==="completed"?"Transfer completed successfully!":V?"Destination execution failed. Funds refunded to smart account.":"Transfer failed":l==="completed"?"Operation completed successfully!":l==="failed"?"Operation failed":b,L=()=>l==="cex"||l==="bridge"?w.jsx(NE,{start:p==="tracking"||l==="bridge",onFinish:y,duration:a?180:120}):l==="completed"?w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:PE,boxShadow:"0px 0px 20px #14AE5C",borderRadius:"90%",width:"58px",height:"58px"})}):w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:LE,boxShadow:"0px 0px 20px #E84142",borderRadius:"90%",width:"58px",height:"58px"})}),O=r?ko[r]:"Unknown",f=i?ko[i]:"Unknown";return w.jsxs(tn,{children:[a&&w.jsx(Aq,{currentPhase:l==="cex"?0:l==="bridge"?1:2,phases:["Forward funds","Bridge"]}),w.jsxs(ue,{display:"flex",flexDirection:"column",paddingBottom:"16px",alignItems:"center",width:"100%",children:[L(),w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",marginTop:"16px",textAlign:"center",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"8px",children:D()}),(l==="cex"||l==="bridge")&&N&&w.jsx(Te,{fontSize:"sm",color:"fg.muted",maxWidth:"280px",children:"Your operation is being processed – no action is required from you."})]})]}),w.jsx(hu,{size:"sm",variant:"outline",width:"100%",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Status"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{color:C(),children:R()})})]}),a&&w.jsxs(w.Fragment,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Current Phase"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{children:l==="cex"?"Awaiting funds":l==="bridge"?"Bridging":l==="completed"?"Complete":"Failed"})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Intermediate Chain"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{textTransform:"capitalize",children:O})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Final Destination"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{textTransform:"capitalize",children:f})})]})]}),u&&w.jsxs(En,{children:[w.jsx(je,{children:"Operation ID"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"fg.muted",children:u})})]}),a&&x&&w.jsxs(En,{children:[w.jsx(je,{children:"Bridge TX"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"blue.500",cursor:"pointer",onClick:()=>window.open(`https://layerzeroscan.com/tx/${x}`,"_blank"),children:"View on LayerZero"})})]}),a&&W&&w.jsxs(En,{children:[w.jsx(je,{children:"Destination TX"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"blue.500",cursor:"pointer",onClick:()=>{const v=ux[i]||"https://etherscan.io";window.open(`${v}/tx/${W}`,"_blank")},children:"View on Explorer"})})]}),a&&l==="bridge"&&w.jsxs(En,{children:[w.jsx(je,{children:"Bridge Progress"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsxs(Te,{children:["(",d.step,"/4)"]})})]}),a&&V&&w.jsxs(En,{children:[w.jsx(je,{children:"Refund"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"orange.500",children:"Funds refunded to smart account"})})]})]})},"status"),w.jsx(ud,{}),w.jsx(dd,{}),(l==="completed"||l==="failed")&&w.jsx(nr,{onClick:()=>n(0),visual:"solid",children:l==="completed"?"New Deposit":"Retry Deposit"})]})},kq=({setFlow:t,initialStep:e=1})=>{const{handleClose:n,enforceFlow:r}=K.useContext(ic),[i,o]=K.useState(e),[s,a]=K.useState(null),[l,c]=K.useState(null),u=Me(g=>g.setSelectedIntegration),h=Me(g=>g.selectedIntegration);K.useEffect(()=>()=>u(null),[]);const p=(()=>{switch(i){case 1:return w.jsx(_q,{setStep:o});case 0:return w.jsx(xq,{setStep:o});case 2:return w.jsx(wq,{setStep:o,onTokenSelect:a});case 3:return w.jsx(Eq,{setStep:o,onTokenSelect:a});case 4:return w.jsx(Sq,{setStep:o,selectedToken:s});case 5:return w.jsx(Iq,{nextStep:s.holding?6:7,setStep:o,setUserOp:c});case 6:return w.jsx(Cq,{selectedToken:s,userOp:l,setStep:o});case 7:return w.jsx(Oq,{selectedToken:s,userOp:l,setStep:o});default:return null}})();return w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(nx,{children:[!(r&&(i===1||i===3))&&w.jsx(gi,{minWidth:"16px",minHeight:"16px",maxWidth:"16px",onClick:()=>{const g=((h==null?void 0:h.type)==="delayed"?yq:ME).findIndex(b=>b===i)-1;g>=0?o(ME[g]):t("")},children:w.jsx(on,{as:U_,color:"gray",width:"16px",height:"16px"})}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center",width:"100%",children:w.jsxs(Ao,{children:["Deposit from ",h==null?void 0:h.name]})}),n&&w.jsx(gi,{onClick:n,minWidth:"16px",minHeight:"16px",maxWidth:"16px",marginLeft:"auto",children:w.jsx(on,{as:Ss,color:"gray",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:p})]})},VE=({setStep:t})=>{const e=Me(h=>h.setSelectedIntegration),n=Me(h=>h.setTokenIn),r=Me(h=>h.tokenIn),i=Me(h=>h.setChainIdIn),o=Me(h=>h.chainIdIn),s=Me(h=>h.tokenOut),a=Me(h=>h.chainIdOut),{holdingsList:l,isLoading:c}=i1(),u=l==null?void 0:l.filter(h=>!(h.token.toLowerCase()===s.toLowerCase()&&h.chainId===a));return K.useEffect(()=>{e(null)},[]),w.jsxs(tn,{children:[w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:c?Array.from({length:10}).map((h,p)=>w.jsx(jr,{height:"40px",width:"300px"},p)):u==null?void 0:u.map(h=>w.jsx(Eu,{chainId:h.chainId,icon:h.logoUri,title:h.name,balance:`${kr(ir(h.amount,h.decimals))} ${h.symbol}`,usdBalance:Tr(h.total),tag:"",loading:!1,selected:h.token===r&&h.chainId===o,onClick:()=>{n(h.token),i(h.chainId)}},`${h.token}-${h.chainId}`))})}),w.jsx(nr,{onClick:()=>{t("selectAmount")},disabled:!r,children:"Continue"})]})},Tq="coingecko",Rq=We("div",{base:{display:"flex",gap:"8px",alignItems:"center",justifyContent:"center",p:"8px 12px",borderRadius:"114px",bg:"bg.subtle",w:"fit-content"}}),Nq=t=>t.includes(Tq)?t.replace("/thumb/","/large/"):t,Pq=({token:t,chainId:e,size:n=32})=>w.jsxs(ue,{position:"relative",borderRadius:"50%",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:t!=null&&t.logoURI?Nq(t==null?void 0:t.logoURI):Is,title:t==null?void 0:t.symbol,alt:t==null?void 0:t.symbol,width:`${n}px`,height:`${n}px`})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid white",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),$E=({token:t,chainId:e,size:n=32,title:r,subTitle:i})=>w.jsxs(tr,{align:"center",gap:2,children:[w.jsx(Pq,{token:t,chainId:e,size:n}),w.jsxs(ue,{children:[w.jsx(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:r}),w.jsx(Te,{fontSize:"xs",color:"fg",children:i})]})]}),Lq=({token:t,chainId:e,size:n=32})=>{const r=(t==null?void 0:t.protocolName)||(t==null?void 0:t.protocol),i=t==null?void 0:t.protocolLogo;return w.jsxs(tr,{align:"center",gap:2,children:[w.jsxs(ue,{position:"relative",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:i||Is,title:r,alt:r,width:`${n}px`,height:`${n}px`,onError:o=>{o.currentTarget.src=Is}})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid white",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),w.jsxs(ue,{children:[w.jsxs(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:["Deposit"," ",w.jsx(Te,{as:"span",fontSize:"xs",color:"fg",children:t==null?void 0:t.symbol})]}),w.jsxs(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:["into"," ",w.jsx(Te,{as:"span",fontSize:"xs",color:"fg",children:r})]})]})]})},Mq=({tokenIn:t,tokenOut:e,chainIdIn:n,chainIdOut:r,isNontokenized:i=!1,size:o=24})=>w.jsxs(Rq,{children:[w.jsx($E,{token:t,chainId:n,title:"You send",subTitle:t==null?void 0:t.symbol,size:o}),w.jsx(W_,{color:"#707070",width:"16px",height:"16px"}),i&&(e!=null&&e.protocol)?w.jsx(Lq,{token:e,chainId:r,size:o}):w.jsx($E,{token:e,chainId:r,title:"You receive",subTitle:e==null?void 0:e.symbol,size:o})]}),Bq=({setStep:t})=>{const[e,n]=K.useState({tokenAmount:"",usdAmount:"10.10",mode:"usd"}),r=Me(B=>B.setAmountIn),i=Me(B=>B.amountIn),[o,s]=K.useState(!0),{tokenInData:a,effectiveTokenOutData:l,tokenIn:c,chainIdOut:u,chainIdIn:h,isNontokenized:p}=yr(),{data:g}=ll(h,c),b=a!=null&&a.decimals?Math.min(a.decimals,6):6,m=e.tokenAmount,x=qD(c,h),I=K.useCallback(B=>{if(!x||!g||!(a!=null&&a.decimals))return null;const G=(BigInt(x)*BigInt(B)/BigInt(100)).toString(),Z=ir(G,a.decimals),Y=Cu(Z,b);return{tokenAmount:Y,usdAmount:(+parseFloat(Y||"0")*g).toFixed(2)}},[x,g,a==null?void 0:a.decimals,b]);K.useEffect(()=>{if(o&&g&&a&&+x>0){s(!1);const B=I(100);if(!B)return;n(G=>({...G,...B}))}},[x,o,g,a,I]),K.useEffect(()=>{if(!(a!=null&&a.decimals))return;const B=m.endsWith(".")?m.slice(0,-1):m;if(!B||B==="."){r("0");return}try{r(r1(B,a.decimals))}catch(G){r("0")}},[m,a==null?void 0:a.decimals,r]);const N=fg(m)!==null,T=N?+x<+i:!1,$=!N||T;return w.jsxs(tn,{children:[w.jsx(g1,{value:e,onChange:n,tokenSymbol:a==null?void 0:a.symbol,tokenPriceUsd:g,roundingPrecision:b,onPercentSelect:I}),w.jsx(Mq,{tokenOut:l,tokenIn:a,chainIdIn:h,chainIdOut:u,isNontokenized:p}),w.jsx(nr,{onClick:()=>t("quote"),disabled:$,children:"Continue"})]})},Fq=({setStep:t})=>{const{chainIdIn:e}=yr(),{routeLoading:n,usdAmountIn:r,routeData:i}=Ms(),o=et.useChainId(),{switchChain:s}=et.useSwitchChain(),a=UD(e),l=o!==e;return w.jsxs(tn,{children:[w.jsxs(tr,{flexDirection:"column",gap:"16px",alignItems:"center",width:"100%",children:[w.jsx(jr,{loading:n,width:n?"156px":"auto",children:w.jsx(Yf,{readOnly:!0,marginY:"8px",variant:"text",placeholder:"$10.00",value:r})}),w.jsx(ud,{})]}),w.jsx(dd,{}),l?w.jsxs(nr,{onClick:()=>{s({chainId:e})},children:["Switch to ",a]}):w.jsx(nr,{disabled:!!(i!=null&&i.error),visual:n?"lightGray":"solid",onClick:n?()=>{}:()=>{t("confirmTransfer")},children:n?"Loading quote":"Continue"})]})},Dq="data:image/svg+xml,%3csvg%20width='20'%20height='20'%20viewBox='0%200%2020%2020'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20x='1'%20y='1'%20width='18'%20height='18'%20rx='9'%20stroke='white'%20stroke-width='2'/%3e%3cpath%20d='M17.7589%2011.9352C16.6904%2016.221%2012.3496%2018.8292%208.06336%2017.7605C3.77889%2016.692%201.17066%2012.351%202.23959%208.06558C3.30758%203.77935%207.64835%201.17093%2011.9333%202.23939C16.2192%203.30785%2018.8273%207.64936%2017.7587%2011.9353L17.7588%2011.9352H17.7589Z'%20fill='%2314AE5C'/%3e%3cpath%20d='M11.9997%204.66675C12.3679%204.66675%2012.6663%204.96522%2012.6663%205.33341C12.6663%205.7016%2012.3679%206.00008%2011.9997%206.00008H7.99967C7.63148%206.00008%207.33301%205.7016%207.33301%205.33341C7.33301%204.96522%207.63148%204.66675%207.99967%204.66675H11.9997Z'%20fill='white'/%3e%3cpath%20d='M12.0003%207.33325C12.3685%207.33325%2012.667%207.63173%2012.667%207.99992V9.33325H14.667C14.9366%209.33325%2015.1797%209.49564%2015.2829%209.74471C15.386%209.99383%2015.329%2010.2806%2015.1383%2010.4713L10.4717%2015.1379C10.2113%2015.3983%209.7893%2015.3983%209.52895%2015.1379L4.86229%2010.4713C4.67162%2010.2806%204.61457%209.99383%204.71775%209.74471C4.82096%209.49564%205.06403%209.33325%205.33364%209.33325H7.33364V7.99992C7.33364%207.63173%207.63212%207.33325%208.00031%207.33325H12.0003ZM8.66697%209.99992C8.66697%2010.3681%208.3685%2010.6666%208.00031%2010.6666H6.94301L10.0003%2013.7239L13.0576%2010.6666H12.0003C11.6321%2010.6666%2011.3336%2010.3681%2011.3336%209.99992V8.66659H8.66697V9.99992Z'%20fill='white'/%3e%3c/svg%3e",Vq=We(Rn,{base:{boxSize:"36px",borderRadius:"full",objectFit:"contain"}}),$q=We(Rn,{base:{boxSize:"16px",position:"absolute",bottom:"-2px",right:"-2px",borderRadius:"full",border:"1px solid",borderColor:"bg",objectFit:"contain"}}),zq=({onClose:t,currencyIcon:e})=>{const n=()=>{const r=new Date,i=r.toLocaleString("en-US",{month:"short"}),o=r.toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return`${i} - ${o}`};return w.jsxs(ue,{border:"1px solid",borderColor:"border.subtle",borderRadius:"12px",width:"100%",bg:"bg",children:[w.jsxs(ue,{display:"flex",alignItems:"center",gap:"12px",borderBottom:"1px solid",borderColor:"border.subtle",padding:"10px 16px",children:[w.jsxs(ue,{position:"relative",children:[w.jsx(Vq,{src:e,alt:"Currency icon"}),w.jsx($q,{src:Dq,alt:"deposit icon"})]}),w.jsxs(ue,{flex:"1",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"4px",children:"Deposit processing"}),w.jsx(Te,{fontSize:"sm",color:"fg.muted",lineHeight:"1.4",children:"Your deposit will be added to your account soon."})]}),t&&w.jsx(on,{as:Ss,width:"16px",height:"16px",color:"fg.subtle",cursor:"pointer",_hover:{color:"fg.muted"},onClick:t})]}),w.jsxs(ue,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 16px",children:[w.jsx(Te,{fontSize:"sm",color:"fg.muted",children:"Order started"}),w.jsx(Te,{fontSize:"sm",color:"fg",fontWeight:"medium",children:n()})]})]})},Uq=()=>{var h;const{chainIdIn:t,tokenIn:e,amountIn:n}=yr(),{address:r}=et.useAccount(),{approveData:i,approveFetched:o}=mD({address:r,token:e,chainId:t,amount:n}),{routeData:s,routeFetched:a}=Ms(),{approveNeeded:l,allowanceFetched:c}=KD(e,(h=i==null?void 0:i.tx)==null?void 0:h.to,n);return{calls:K.useMemo(()=>!Ro(e,Pt)&&!c||!a||!o?[]:l?[i==null?void 0:i.tx,s==null?void 0:s.tx]:[s==null?void 0:s.tx],[l,c,a,i,s,o]),approveNeeded:l}},Wq=({setStep:t})=>{const[e,n]=K.useState("idle"),[r,i]=K.useState(!1),{address:o}=et.useAccount(),[s,a]=K.useState(""),[l,c]=K.useState(!1),{chainIdIn:u,chainIdOut:h}=yr(),{calls:p}=Uq(),{sendTxns:g,ready:b}=eV({calls:p,address:o,chainId:u}),{track:m}=lq(),x=u!==h,I=K.useCallback(W=>{n("processing"),a(W),m({hash:W,isActive:!0,chainId:u,crosschain:x,status:x?"(0/4) Waiting for source transaction completion":"Transaction in progess",message:"Transaction confirmed",onConfirmed:()=>{n("success")}})},[u,h]),N=K.useCallback(W=>{console.error(W),n("failed")},[]);K.useEffect(()=>{console.log(l,b),!l&&b&&(g(I,N),c(!0))},[l,b,g,I]);const T=()=>{i(!0)},$=()=>{t("selectToken")},B=()=>{t("quote")},G=aq(s),Z=x?`https://layerzeroscan.com/tx/${s}`:Iu({hash:s,chainId:u}),Y=()=>{switch(e){case"success":return"#14AE5C";case"failed":return"#E84142";default:return"#1E171F"}},F=()=>{switch(e){case"success":return"Success";case"failed":return"Failed";case"idle":return"Awaiting wallet approval";default:return G==null?void 0:G.status}},V=()=>{switch(e){case"processing":case"idle":return w.jsx(NE,{start:e==="processing",onFinish:T});case"success":return w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:PE,boxShadow:"0px 0px 20px #14AE5C",borderRadius:"90%",width:"58px",height:"58px"})});case"failed":return w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:LE,boxShadow:"0px 0px 20px #E84142",borderRadius:"90%",width:"58px",height:"58px"})})}},U=()=>e==="processing"&&r?w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",marginTop:"16px",textAlign:"center",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"8px",children:"Deposit pending"}),w.jsx(Te,{fontSize:"sm",color:"fg.muted",maxWidth:"280px",children:"Your deposit is still in progress – no action is required from you."})]}):null;return w.jsxs(tn,{children:[w.jsxs(ue,{display:"flex",flexDirection:"column",paddingBottom:"16px",alignItems:"center",width:"100%",children:[V(),U()]}),w.jsx(hu,{size:"sm",variant:"outline",width:"100%",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Status"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{color:Y(),children:F()})})]}),["success","processing"].includes(e)&&w.jsxs(En,{children:[w.jsx(je,{children:"Transaction"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:Z?w.jsx("a",{href:Z,target:"_blank",rel:"noreferrer",children:w.jsxs(Te,{color:"blue.500",children:["View on"," ",x?"LayerZero":"Etherscan"]})}):w.jsx(Te,{children:"-"})})]})]})},"status"),w.jsx(ud,{}),e==="processing"?w.jsx(zq,{currencyIcon:dg(h)}):w.jsx(dd,{}),e==="success"&&w.jsx(nr,{visual:"solid",onClick:$,width:"100%",children:"New Deposit"}),e==="failed"&&w.jsx(nr,{visual:"solid",onClick:B,width:"100%",children:"Retry Deposit"})]})};var zE=(t=>(t.SelectToken="selectToken",t.SelectAmount="selectAmount",t.Quote="quote",t.ConfirmTransfer="confirmTransfer",t))(zE||{});const UE=["selectToken","selectAmount","quote","confirmTransfer"],Hq={exchange:kq,wallet:({initialStep:t="selectToken",setFlow:e})=>{const[n,r]=K.useState(t),{handleClose:i,enforceFlow:o}=K.useContext(ic),s=c=>{r(c)},a=()=>{const c=UE.findIndex(u=>u===n)-1;c>=0?r(UE[c]):e&&e("")},l=(()=>{switch(n){case"selectToken":return w.jsx(VE,{setStep:s});case"selectAmount":return w.jsx(Bq,{setStep:s});case"quote":return w.jsx(Fq,{setStep:s});case"confirmTransfer":return w.jsx(Wq,{setStep:s});default:return w.jsx(VE,{setStep:s})}})();return w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(nx,{children:[!(o&&n==="selectToken")&&w.jsx(gi,{minWidth:"16px",minHeight:"16px",maxWidth:"16px",onClick:a,children:w.jsx(on,{as:U_,color:"gray",width:"16px",height:"16px"})}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center",width:"100%",children:w.jsx(Ao,{children:"Wallet Deposit"})}),i&&w.jsx(gi,{onClick:i,minWidth:"16px",minHeight:"16px",maxWidth:"16px",marginLeft:"auto",children:w.jsx(on,{as:Ss,color:"gray",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:l})]})}},jq=()=>{const{handleClose:t,enableExchange:e,enforceFlow:n}=K.useContext(ic),[r,i]=K.useState(""),[o,s]=K.useState(""),[a,l]=K.useState(null),{total:c,isLoading:u}=i1(),{address:h}=et.useAccount(),{walletIcon:p,walletDisplayName:g}=f1(),{total:b,isLoading:m}=h1(1);K.useEffect(()=>{if(n)if(n==="exchange"){if(!Array.isArray(e)||e.length===0){l("No exchanges configured. Please enable at least one exchange in the widget configuration.");return}i("exchange"),s(fd.ChooseExchange)}else n==="wallet"&&h&&(i("wallet"),s(zE.SelectToken))},[n,e,h]);const x=K.useMemo(()=>u?w.jsx(jr,{display:"inline-block",height:"10px",width:"60px"}):typeof c=="number"?Tr(c):c||"$0.00",[c,u]),I=K.useMemo(()=>h?ug(h):"",[h]),N=K.useMemo(()=>{const $=[];return!m&&b>20&&$.push({id:"smart-balance",title:"Smart Account Balance",limit:Tr(b),delay:"2 min",icons:[],flow:"exchange",firstStep:fd.ChooseBalanceAsset}),Array.isArray(e)&&e.length>0&&$.unshift({id:"exchange",title:"Connect Exchange",limit:"No Limit",delay:"2 min",icons:e.map(B=>hd[ea[B]]).filter(Boolean),flow:"exchange",firstStep:fd.ChooseExchange}),$},[h,e,b,m]),T=r&&Hq[r];return T?w.jsx(T,{setFlow:i,initialStep:o}):a?w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Configuration Error"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsx(tn,{children:w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",gap:"4",p:"6",textAlign:"center",children:[w.jsx(on,{as:j4,color:"red.500",width:"48px",height:"48px"}),w.jsx(Te,{color:"fg.muted",children:a})]})})})]}):n==="wallet"&&!h?w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Connect Wallet"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsx(tn,{children:w.jsx(Oo,{children:w.jsx(s1,{icon:p,walletHash:"Not Connected",balance:"Connect your wallet to continue",delay:"",status:hg.NONE})})})})]}):w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Deposit"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsxs(tn,{children:[h&&w.jsx(Oo,{children:w.jsx(s1,{icon:p,walletHash:I,balance:x,delay:"Instant",status:hg.CONNECTED,badge:g,onClick:()=>{i("wallet")}},h)}),N.length>0&&w.jsxs(w.Fragment,{children:[w.jsx(vB,{}),w.jsx(Oo,{children:N.map($=>w.jsx(RD,{title:$.title,limit:$.limit,delay:$.delay,icons:$.icons,onClick:()=>{$.disabled||(i($.flow),s($.firstStep))}},$.id))})]})]})})]})};var oe=typeof window!="undefined"?window:void 0,bn=typeof globalThis!="undefined"?globalThis:oe;typeof self=="undefined"&&(bn.self=bn),typeof File=="undefined"&&(bn.File=function(){});var WE=Array.prototype,HE=WE.forEach,jE=WE.indexOf,ur=bn==null?void 0:bn.navigator,me=bn==null?void 0:bn.document,jn=bn==null?void 0:bn.location,Sp=bn==null?void 0:bn.fetch,Ip=bn!=null&&bn.XMLHttpRequest&&"withCredentials"in new bn.XMLHttpRequest?bn.XMLHttpRequest:void 0,qE=bn==null?void 0:bn.AbortController,qn=ur==null?void 0:ur.userAgent,ke=oe!=null?oe:{},Ci={DEBUG:!1,LIB_VERSION:"1.310.1"};function GE(t,e,n,r,i,o,s){try{var a=t[o](s),l=a.value}catch(c){return void n(c)}a.done?e(l):Promise.resolve(l).then(r,i)}function KE(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var o=t.apply(e,n);function s(l){GE(o,r,i,s,a,"next",l)}function a(l){GE(o,r,i,s,a,"throw",l)}s(void 0)}))}}function be(){return be=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},be.apply(null,arguments)}function YE(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var qq=["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"],XE=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return qq.concat(e).some((r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1}))},Gq=["$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 Ue(t,e){return t.indexOf(e)!==-1}var pd=function(t){return t.trim()},Cp=function(t){return t.replace(/^\$/,"")},Kq=Array.isArray,ZE=Object.prototype,JE=ZE.hasOwnProperty,md=ZE.toString,Ze=Kq||function(t){return md.call(t)==="[object Array]"},ro=t=>typeof t=="function",an=t=>t===Object(t)&&!Ze(t),ta=t=>{if(an(t)){for(var e in t)if(JE.call(t,e))return!1;return!0}return!1},fe=t=>t===void 0,nn=t=>md.call(t)=="[object String]",Ap=t=>nn(t)&&t.trim().length===0,Pr=t=>t===null,Je=t=>fe(t)||Pr(t),ei=t=>md.call(t)=="[object Number]",Ai=t=>md.call(t)==="[object Boolean]",Yq=t=>t instanceof FormData,Xq=t=>Ue(Gq,t);function Op(t){return t===null||typeof t!="object"}function vd(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function QE(t){return!fe(Event)&&(function(e,n){try{return e instanceof n}catch(r){return!1}})(t,Event)}var Zq=[!0,"true",1,"1","yes"],kp=t=>Ue(Zq,t),Jq=[!1,"false",0,"0","no"];function ti(t,e,n,r,i){return e>n&&(r.warn("min cannot be greater than max."),e=n),ei(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),ti(i||n,e,n,r))}class Qq{constructor(e){this.t={},this.i=e.i,this.o=ti(e.bucketSize,0,100,e.h),this.m=ti(e.refillRate,0,this.o,e.h),this.$=ti(e.refillInterval,0,864e5,e.h)}S(e,n){var r=n-e.lastAccess,i=Math.floor(r/this.$);if(i>0){var o=i*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+i*this.$}}consumeRateLimit(e){var n,r=Date.now(),i=String(e),o=this.t[i];return o?this.S(o,r):(o={tokens:this.o,lastAccess:r},this.t[i]=o),o.tokens===0||(o.tokens--,o.tokens===0&&((n=this.i)==null||n.call(this,e)),o.tokens===0)}stop(){this.t={}}}var br="Mobile",yd="iOS",Oi="Android",Rl="Tablet",eS=Oi+" "+Rl,tS="iPad",nS="Apple",rS=nS+" Watch",Nl="Safari",na="BlackBerry",iS="Samsung",oS=iS+"Browser",sS=iS+" Internet",qo="Chrome",eG=qo+" OS",aS=qo+" "+yd,Tp="Internet Explorer",lS=Tp+" "+br,Rp="Opera",tG=Rp+" Mini",Np="Edge",cS="Microsoft "+Np,ra="Firefox",uS=ra+" "+yd,Pl="Nintendo",Ll="PlayStation",ia="Xbox",dS=Oi+" "+br,hS=br+" "+Nl,Ml="Windows",Pp=Ml+" Phone",fS="Nokia",Lp="Ouya",gS="Generic",nG=gS+" "+br.toLowerCase(),pS=gS+" "+Rl.toLowerCase(),Mp="Konqueror",Pn="(\\d+(\\.\\d+)?)",Bp=new RegExp("Version/"+Pn),rG=new RegExp(ia,"i"),iG=new RegExp(Ll+" \\w+","i"),oG=new RegExp(Pl+" \\w+","i"),Fp=new RegExp(na+"|PlayBook|BB10","i"),sG={"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"},bd,mS,Dp,aG=(t,e)=>e&&Ue(e,nS)||(function(n){return Ue(n,Nl)&&!Ue(n,qo)&&!Ue(n,Oi)})(t),vS=function(t,e){return e=e||"",Ue(t," OPR/")&&Ue(t,"Mini")?tG:Ue(t," OPR/")?Rp:Fp.test(t)?na:Ue(t,"IE"+br)||Ue(t,"WPDesktop")?lS:Ue(t,oS)?sS:Ue(t,Np)||Ue(t,"Edg/")?cS:Ue(t,"FBIOS")?"Facebook "+br:Ue(t,"UCWEB")||Ue(t,"UCBrowser")?"UC Browser":Ue(t,"CriOS")?aS:Ue(t,"CrMo")||Ue(t,qo)?qo:Ue(t,Oi)&&Ue(t,Nl)?dS:Ue(t,"FxiOS")?uS:Ue(t.toLowerCase(),Mp.toLowerCase())?Mp:aG(t,e)?Ue(t,br)?hS:Nl:Ue(t,ra)?ra:Ue(t,"MSIE")||Ue(t,"Trident/")?Tp:Ue(t,"Gecko")?ra:""},lG={[lS]:[new RegExp("rv:"+Pn)],[cS]:[new RegExp(Np+"?\\/"+Pn)],[qo]:[new RegExp("("+qo+"|CrMo)\\/"+Pn)],[aS]:[new RegExp("CriOS\\/"+Pn)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Pn)],[Nl]:[Bp],[hS]:[Bp],[Rp]:[new RegExp("(Opera|OPR)\\/"+Pn)],[ra]:[new RegExp(ra+"\\/"+Pn)],[uS]:[new RegExp("FxiOS\\/"+Pn)],[Mp]:[new RegExp("Konqueror[:/]?"+Pn,"i")],[na]:[new RegExp(na+" "+Pn),Bp],[dS]:[new RegExp("android\\s"+Pn,"i")],[sS]:[new RegExp(oS+"\\/"+Pn)],[Tp]:[new RegExp("(rv:|MSIE )"+Pn)],Mozilla:[new RegExp("rv:"+Pn)]},cG=function(t,e){var n=vS(t,e),r=lG[n];if(fe(r))return null;for(var i=0;i<r.length;i++){var o=r[i],s=t.match(o);if(s)return parseFloat(s[s.length-2])}return null},yS=[[new RegExp(ia+"; "+ia+" (.*?)[);]","i"),t=>[ia,t&&t[1]||""]],[new RegExp(Pl,"i"),[Pl,""]],[new RegExp(Ll,"i"),[Ll,""]],[Fp,[na,""]],[new RegExp(Ml,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Pp,""];if(new RegExp(br).test(e)&&!/IEMobile\b/.test(e))return[Ml+" "+br,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var r=n[1],i=sG[r]||"";return/arm/i.test(e)&&(i="RT"),[Ml,i]}return[Ml,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[yd,e.join(".")]}return[yd,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=fe(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Oi+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Oi+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[Oi,e.join(".")]}return[Oi,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[eG,""]],[/Linux|debian/i,["Linux",""]]],bS=function(t){return oG.test(t)?Pl:iG.test(t)?Ll:rG.test(t)?ia:new RegExp(Lp,"i").test(t)?Lp:new RegExp("("+Pp+"|WPDesktop)","i").test(t)?Pp:/iPad/.test(t)?tS:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?rS:Fp.test(t)?na:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(fS,"i").test(t)?fS:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(br).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Oi:eS:new RegExp("(pda|"+br+")","i").test(t)?nG:new RegExp(Rl,"i").test(t)&&!new RegExp(Rl+" pc","i").test(t)?pS:""},uG=t=>t instanceof Error;function dG(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Dp&&n.length===mS||(mS=n.length,Dp=n.reduce(((r,i)=>{bd||(bd={});var o=bd[i];if(o)r[o[0]]=o[1];else for(var s=t(i),a=s.length-1;a>=0;a--){var l=s[a],c=l==null?void 0:l.filename,u=e[i];if(c&&u){r[c]=u,bd[i]=[c,u];break}}return r}),{})),Dp}}class hG{constructor(e,n,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=n,this.modifiers=r}buildFromUnknown(e,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(e),o=this.buildParsingContext(),s=this.parseStacktrace(i,o);return{$exception_list:this.convertToExceptionList(s,r),$exception_level:"error"}}modifyFrames(e){var n=this;return KE((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Ze(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),n.chunkIdMap)),be({},e,{cause:r,stack:i})}applyChunkIds(e,n){return e.map((r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r)))}applyCoercers(e,n){for(var r of this.coercers)if(r.match(e))return r.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return KE((function*(){var r=e;for(var i of n.modifiers)r=yield i(r);return r}))()}convertToExceptionList(e,n){var r,i,o,s={type:e.type,value:e.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(o=e.synthetic)!==null&&o!==void 0&&o}};e.stack&&(s.stacktrace={type:"raw",frames:e.stack});var a=[s];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,be({},n,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:dG(this.stackParser)}}buildCoercingContext(e,n,r){r===void 0&&(r=0);var i=(o,s)=>{if(s<=4){var a=this.buildCoercingContext(e,n,s);return this.applyCoercers(o,a)}};return be({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:e,apply:o=>i(o,r),next:o=>i(o,r+1)})}}var oa="?";function Vp(t,e,n,r,i){var o={platform:t,filename:e,function:n==="<anonymous>"?oa:n,in_app:!0};return fe(r)||(o.lineno=r),fe(i)||(o.colno=i),o}var _S=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:oa,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pG=/\((\S*)(?::(\d+))(?::(\d+))\)/,mG=(t,e)=>{var n=fG.exec(t);if(n){var[,r,i,o]=n;return Vp(e,r,oa,+i,+o)}var s=gG.exec(t);if(s){if(s[2]&&s[2].indexOf("eval")===0){var a=pG.exec(s[2]);a&&(s[2]=a[1],s[3]=a[2],s[4]=a[3])}var[l,c]=_S(s[1]||oa,s[2]);return Vp(e,c,l,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},vG=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,bG=(t,e)=>{var n=vG.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=yG.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],o=n[1]||oa;return[o,i]=_S(o,i),Vp(e,i,o,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},xS=/\(error: (.*)\)/,wS=50;function _G(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return function(i,o){o===void 0&&(o=0);for(var s=[],a=i.split(`
228
+ `,x=m+b.join(m);console.error(g.error.message,x)}throw new Qw({action:"simulate",signature:"",transactionMessage:g.error.message,logs:b})}return g.result}async sendTransaction(e,n,r){if("version"in e){if(n&&Array.isArray(n))throw new Error("Invalid arguments");const s=e.serialize();return await this.sendRawTransaction(s,n)}if(n===void 0||!Array.isArray(n))throw new Error("Invalid arguments");const i=n;if(e.nonceInfo)e.sign(...i);else{let s=this._disableBlockhashCaching;for(;;){const a=await this._blockhashWithExpiryBlockHeight(s);if(e.lastValidBlockHeight=a.lastValidBlockHeight,e.recentBlockhash=a.blockhash,e.sign(...i),!e.signature)throw new Error("!signature");const l=e.signature.toString("base64");if(this._blockhashInfo.transactionSignatures.includes(l))s=!0;else{this._blockhashInfo.transactionSignatures.push(l);break}}}const o=e.serialize();return await this.sendRawTransaction(o,r)}async sendRawTransaction(e,n){const r=Gs(e).toString("base64");return await this.sendEncodedTransaction(r,n)}async sendEncodedTransaction(e,n){const r={encoding:"base64"},i=n&&n.skipPreflight,o=i===!0?"processed":n&&n.preflightCommitment||this.commitment;n&&n.maxRetries!=null&&(r.maxRetries=n.maxRetries),n&&n.minContextSlot!=null&&(r.minContextSlot=n.minContextSlot),i&&(r.skipPreflight=i),o&&(r.preflightCommitment=o);const s=[e,r],a=await this._rpcRequest("sendTransaction",s),l=he(a,Pj);if("error"in l){let c;throw"data"in l.error&&(c=l.error.data.logs),new Qw({action:i?"send":"simulate",signature:"",transactionMessage:l.error.message,logs:c})}return l.result}_wsOnOpen(){this._rpcWebSocketConnected=!0,this._rpcWebSocketHeartbeat=setInterval(()=>{(async()=>{try{await this._rpcWebSocket.notify("ping")}catch(e){}})()},5e3),this._updateSubscriptions()}_wsOnError(e){this._rpcWebSocketConnected=!1,console.error("ws error:",e.message)}_wsOnClose(e){if(this._rpcWebSocketConnected=!1,this._rpcWebSocketGeneration=(this._rpcWebSocketGeneration+1)%Number.MAX_SAFE_INTEGER,this._rpcWebSocketIdleTimeout&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null),this._rpcWebSocketHeartbeat&&(clearInterval(this._rpcWebSocketHeartbeat),this._rpcWebSocketHeartbeat=null),e===1e3){this._updateSubscriptions();return}this._subscriptionCallbacksByServerSubscriptionId={},Object.entries(this._subscriptionsByHash).forEach(([n,r])=>{this._setSubscription(n,{...r,state:"pending"})})}_setSubscription(e,n){var i;const r=(i=this._subscriptionsByHash[e])==null?void 0:i.state;if(this._subscriptionsByHash[e]=n,r!==n.state){const o=this._subscriptionStateChangeCallbacksByHash[e];o&&o.forEach(s=>{try{s(n.state)}catch(a){}})}}_onSubscriptionStateChange(e,n){var o;const r=this._subscriptionHashByClientSubscriptionId[e];if(r==null)return()=>{};const i=(o=this._subscriptionStateChangeCallbacksByHash)[r]||(o[r]=new Set);return i.add(n),()=>{i.delete(n),i.size===0&&delete this._subscriptionStateChangeCallbacksByHash[r]}}async _updateSubscriptions(){if(Object.keys(this._subscriptionsByHash).length===0){this._rpcWebSocketConnected&&(this._rpcWebSocketConnected=!1,this._rpcWebSocketIdleTimeout=setTimeout(()=>{this._rpcWebSocketIdleTimeout=null;try{this._rpcWebSocket.close()}catch(r){r instanceof Error&&console.log(`Error when closing socket connection: ${r.message}`)}},500));return}if(this._rpcWebSocketIdleTimeout!==null&&(clearTimeout(this._rpcWebSocketIdleTimeout),this._rpcWebSocketIdleTimeout=null,this._rpcWebSocketConnected=!0),!this._rpcWebSocketConnected){this._rpcWebSocket.connect();return}const e=this._rpcWebSocketGeneration,n=()=>e===this._rpcWebSocketGeneration;await Promise.all(Object.keys(this._subscriptionsByHash).map(async r=>{const i=this._subscriptionsByHash[r];if(i!==void 0)switch(i.state){case"pending":case"unsubscribed":if(i.callbacks.size===0){delete this._subscriptionsByHash[r],i.state==="unsubscribed"&&delete this._subscriptionCallbacksByServerSubscriptionId[i.serverSubscriptionId],await this._updateSubscriptions();return}await(async()=>{const{args:o,method:s}=i;try{this._setSubscription(r,{...i,state:"subscribing"});const a=await this._rpcWebSocket.call(s,o);this._setSubscription(r,{...i,serverSubscriptionId:a,state:"subscribed"}),this._subscriptionCallbacksByServerSubscriptionId[a]=i.callbacks,await this._updateSubscriptions()}catch(a){if(console.error(`Received ${a instanceof Error?"":"JSON-RPC "}error calling \`${s}\``,{args:o,error:a}),!n())return;this._setSubscription(r,{...i,state:"pending"}),await this._updateSubscriptions()}})();break;case"subscribed":i.callbacks.size===0&&await(async()=>{const{serverSubscriptionId:o,unsubscribeMethod:s}=i;if(this._subscriptionsAutoDisposedByRpc.has(o))this._subscriptionsAutoDisposedByRpc.delete(o);else{this._setSubscription(r,{...i,state:"unsubscribing"}),this._setSubscription(r,{...i,state:"unsubscribing"});try{await this._rpcWebSocket.call(s,[o])}catch(a){if(a instanceof Error&&console.error(`${s} error:`,a.message),!n())return;this._setSubscription(r,{...i,state:"subscribed"}),await this._updateSubscriptions();return}}this._setSubscription(r,{...i,state:"unsubscribed"}),await this._updateSubscriptions()})();break}}))}_handleServerNotification(e,n){const r=this._subscriptionCallbacksByServerSubscriptionId[e];r!==void 0&&r.forEach(i=>{try{i(...n)}catch(o){console.error(o)}})}_wsOnAccountNotification(e){const{result:n,subscription:r}=he(e,rj);this._handleServerNotification(r,[n.value,n.context])}_makeSubscription(e,n){const r=this._nextClientSubscriptionId++,i=nE([e.method,n]),o=this._subscriptionsByHash[i];return o===void 0?this._subscriptionsByHash[i]={...e,args:n,callbacks:new Set([e.callback]),state:"pending"}:o.callbacks.add(e.callback),this._subscriptionHashByClientSubscriptionId[r]=i,this._subscriptionDisposeFunctionsByClientSubscriptionId[r]=async()=>{delete this._subscriptionDisposeFunctionsByClientSubscriptionId[r],delete this._subscriptionHashByClientSubscriptionId[r];const s=this._subscriptionsByHash[i];pt(s!==void 0,`Could not find a \`Subscription\` when tearing down client subscription #${r}`),s.callbacks.delete(e.callback),await this._updateSubscriptions()},this._updateSubscriptions(),r}onAccountChange(e,n,r){const{commitment:i,config:o}=ct(r),s=this._buildArgs([e.toBase58()],i||this._commitment||"finalized","base64",o);return this._makeSubscription({callback:n,method:"accountSubscribe",unsubscribeMethod:"accountUnsubscribe"},s)}async removeAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"account change")}_wsOnProgramAccountNotification(e){const{result:n,subscription:r}=he(e,oj);this._handleServerNotification(r,[{accountId:n.value.pubkey,accountInfo:n.value.account},n.context])}onProgramAccountChange(e,n,r,i){const{commitment:o,config:s}=ct(r),a=this._buildArgs([e.toBase58()],o||this._commitment||"finalized","base64",s||(i?{filters:sE(i)}:void 0));return this._makeSubscription({callback:n,method:"programSubscribe",unsubscribeMethod:"programUnsubscribe"},a)}async removeProgramAccountChangeListener(e){await this._unsubscribeClientSubscription(e,"program account change")}onLogs(e,n,r){const i=this._buildArgs([typeof e=="object"?{mentions:[e.toString()]}:e],r||this._commitment||"finalized");return this._makeSubscription({callback:n,method:"logsSubscribe",unsubscribeMethod:"logsUnsubscribe"},i)}async removeOnLogsListener(e){await this._unsubscribeClientSubscription(e,"logs")}_wsOnLogsNotification(e){const{result:n,subscription:r}=he(e,Mj);this._handleServerNotification(r,[n.value,n.context])}_wsOnSlotNotification(e){const{result:n,subscription:r}=he(e,aj);this._handleServerNotification(r,[n])}onSlotChange(e){return this._makeSubscription({callback:e,method:"slotSubscribe",unsubscribeMethod:"slotUnsubscribe"},[])}async removeSlotChangeListener(e){await this._unsubscribeClientSubscription(e,"slot change")}_wsOnSlotUpdatesNotification(e){const{result:n,subscription:r}=he(e,cj);this._handleServerNotification(r,[n])}onSlotUpdate(e){return this._makeSubscription({callback:e,method:"slotsUpdatesSubscribe",unsubscribeMethod:"slotsUpdatesUnsubscribe"},[])}async removeSlotUpdateListener(e){await this._unsubscribeClientSubscription(e,"slot update")}async _unsubscribeClientSubscription(e,n){const r=this._subscriptionDisposeFunctionsByClientSubscriptionId[e];r?await r():console.warn(`Ignored unsubscribe request because an active subscription with id \`${e}\` for '${n}' events could not be found.`)}_buildArgs(e,n,r,i){const o=n||this._commitment;if(o||r||i){let s={};r&&(s.encoding=r),o&&(s.commitment=o),i&&(s=Object.assign(s,i)),e.push(s)}return e}_buildArgsAtLeastConfirmed(e,n,r,i){const o=n||this._commitment;if(o&&!["confirmed","finalized"].includes(o))throw new Error("Using Connection with default commitment: `"+this._commitment+"`, but method requires at least `confirmed`");return this._buildArgs(e,n,r,i)}_wsOnSignatureNotification(e){const{result:n,subscription:r}=he(e,uj);n.value!=="receivedSignature"&&this._subscriptionsAutoDisposedByRpc.add(r),this._handleServerNotification(r,n.value==="receivedSignature"?[{type:"received"},n.context]:[{type:"status",result:n.value},n.context])}onSignature(e,n,r){const i=this._buildArgs([e],r||this._commitment||"finalized"),o=this._makeSubscription({callback:(s,a)=>{if(s.type==="status"){n(s.result,a);try{this.removeSignatureListener(o)}catch(l){}}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},i);return o}onSignatureWithOptions(e,n,r){const{commitment:i,...o}={...r,commitment:r&&r.commitment||this._commitment||"finalized"},s=this._buildArgs([e],i,void 0,o),a=this._makeSubscription({callback:(l,c)=>{n(l,c);try{this.removeSignatureListener(a)}catch(u){}},method:"signatureSubscribe",unsubscribeMethod:"signatureUnsubscribe"},s);return a}async removeSignatureListener(e){await this._unsubscribeClientSubscription(e,"signature result")}_wsOnRootNotification(e){const{result:n,subscription:r}=he(e,dj);this._handleServerNotification(r,[n])}onRootChange(e){return this._makeSubscription({callback:e,method:"rootSubscribe",unsubscribeMethod:"rootUnsubscribe"},[])}async removeRootChangeListener(e){await this._unsubscribeClientSubscription(e,"root change")}}Object.freeze({CreateLookupTable:{index:0,layout:q.struct([q.u32("instruction"),Zs("recentSlot"),q.u8("bumpSeed")])},FreezeLookupTable:{index:1,layout:q.struct([q.u32("instruction")])},ExtendLookupTable:{index:2,layout:q.struct([q.u32("instruction"),Zs(),q.seq(ze(),q.offset(q.u32(),-8),"addresses")])},DeactivateLookupTable:{index:3,layout:q.struct([q.u32("instruction")])},CloseLookupTable:{index:4,layout:q.struct([q.u32("instruction")])}}),new Re("AddressLookupTab1e1111111111111111111111111"),Object.freeze({RequestUnits:{index:0,layout:q.struct([q.u8("instruction"),q.u32("units"),q.u32("additionalFee")])},RequestHeapFrame:{index:1,layout:q.struct([q.u8("instruction"),q.u32("bytes")])},SetComputeUnitLimit:{index:2,layout:q.struct([q.u8("instruction"),q.u32("units")])},SetComputeUnitPrice:{index:3,layout:q.struct([q.u8("instruction"),Zs("microLamports")])}}),new Re("ComputeBudget111111111111111111111111111111"),q.struct([q.u8("numSignatures"),q.u8("padding"),q.u16("signatureOffset"),q.u16("signatureInstructionIndex"),q.u16("publicKeyOffset"),q.u16("publicKeyInstructionIndex"),q.u16("messageDataOffset"),q.u16("messageDataSize"),q.u16("messageInstructionIndex")]),new Re("Ed25519SigVerify111111111111111111111111111"),XH.utils.isValidPrivateKey,q.struct([q.u8("numSignatures"),q.u16("signatureOffset"),q.u8("signatureInstructionIndex"),q.u16("ethAddressOffset"),q.u8("ethAddressInstructionIndex"),q.u16("messageDataOffset"),q.u16("messageDataSize"),q.u8("messageInstructionIndex"),q.blob(20,"ethAddress"),q.blob(64,"signature"),q.u8("recoveryId")]),new Re("KeccakSecp256k11111111111111111111111111111");var bE;new Re("StakeConfig11111111111111111111111111111111");class _E{constructor(e,n,r){this.unixTimestamp=void 0,this.epoch=void 0,this.custodian=void 0,this.unixTimestamp=e,this.epoch=n,this.custodian=r}}bE=_E,_E.default=new bE(0,0,Re.default),Object.freeze({Initialize:{index:0,layout:q.struct([q.u32("instruction"),n9(),r9()])},Authorize:{index:1,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("stakeAuthorizationType")])},Delegate:{index:2,layout:q.struct([q.u32("instruction")])},Split:{index:3,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},Withdraw:{index:4,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},Deactivate:{index:5,layout:q.struct([q.u32("instruction")])},Merge:{index:7,layout:q.struct([q.u32("instruction")])},AuthorizeWithSeed:{index:8,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("stakeAuthorizationType"),Ys("authoritySeed"),ze("authorityOwner")])}}),new Re("Stake11111111111111111111111111111111111111"),Object.freeze({InitializeAccount:{index:0,layout:q.struct([q.u32("instruction"),i9()])},Authorize:{index:1,layout:q.struct([q.u32("instruction"),ze("newAuthorized"),q.u32("voteAuthorizationType")])},Withdraw:{index:3,layout:q.struct([q.u32("instruction"),q.ns64("lamports")])},UpdateValidatorIdentity:{index:4,layout:q.struct([q.u32("instruction")])},AuthorizeWithSeed:{index:10,layout:q.struct([q.u32("instruction"),o9()])}}),new Re("Vote111111111111111111111111111111111111111"),new Re("Va1idator1nfo111111111111111111111111111111"),ce({name:de(),website:Ce(de()),details:Ce(de()),iconUrl:Ce(de()),keybaseUsername:Ce(de())}),new Re("Vote111111111111111111111111111111111111111"),q.struct([ze("nodePubkey"),ze("authorizedWithdrawer"),q.u8("commission"),q.nu64(),q.seq(q.struct([q.nu64("slot"),q.u32("confirmationCount")]),q.offset(q.u32(),-8),"votes"),q.u8("rootSlotValid"),q.nu64("rootSlot"),q.nu64(),q.seq(q.struct([q.nu64("epoch"),ze("authorizedVoter")]),q.offset(q.u32(),-8),"authorizedVoters"),q.struct([q.seq(q.struct([ze("authorizedPubkey"),q.nu64("epochOfLastAuthorizedSwitch"),q.nu64("targetEpoch")]),32,"buf"),q.nu64("idx"),q.u8("isEmpty")],"priorVoters"),q.nu64(),q.seq(q.struct([q.nu64("epoch"),q.nu64("credits"),q.nu64("prevCredits")]),q.offset(q.u32(),-8),"epochCredits"),q.struct([q.nu64("slot"),q.nu64("timestamp")],"lastTimestamp")]);function gp(t){switch(t){case"processed":case"confirmed":case"finalized":case void 0:return t;case"recent":return"processed";case"single":case"singleGossip":return"confirmed";case"max":case"root":return"finalized";default:return}}const xE="solana:mainnet",Dj="solana:devnet",Vj="solana:testnet",$j="solana:localnet",zj="https://api.mainnet-beta.solana.com";function Uj(t){return t.includes(zj)?xE:/\bdevnet\b/i.test(t)?Dj:/\btestnet\b/i.test(t)?Vj:/\blocalhost\b/i.test(t)||/\b127\.0\.0\.1\b/.test(t)?$j:xE}function Wj(t,e){if(t===e)return!0;const n=t.length;if(n!==e.length)return!1;for(let r=0;r<n;r++)if(t[r]!==e[r])return!1;return!0}function Hj(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let c=0;c<e.length;c++)e[c]=255;for(let c=0;c<t.length;c++){const u=t.charAt(c),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=c}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),o=Math.log(256)/Math.log(n);function s(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let u=0,h=0,p=0;const g=c.length;for(;p!==g&&c[p]===0;)p++,u++;const b=(g-p)*o+1>>>0,m=new Uint8Array(b);for(;p!==g;){let N=c[p],T=0;for(let $=b-1;(N!==0||T<h)&&$!==-1;$--,T++)N+=256*m[$]>>>0,m[$]=N%n>>>0,N=N/n>>>0;if(N!==0)throw new Error("Non-zero carry");h=T,p++}let x=b-h;for(;x!==b&&m[x]===0;)x++;let I=r.repeat(u);for(;x<b;++x)I+=t.charAt(m[x]);return I}function a(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let u=0,h=0,p=0;for(;c[u]===r;)h++,u++;const g=(c.length-u)*i+1>>>0,b=new Uint8Array(g);for(;u<c.length;){const N=c.charCodeAt(u);if(N>255)return;let T=e[N];if(T===255)return;let $=0;for(let B=g-1;(T!==0||$<p)&&B!==-1;B--,$++)T+=n*b[B]>>>0,b[B]=T%256>>>0,T=T/256>>>0;if(T!==0)throw new Error("Non-zero carry");p=$,u++}let m=g-p;for(;m!==g&&b[m]===0;)m++;const x=new Uint8Array(h+(g-m));let I=h;for(;m!==g;)x[I++]=b[m++];return x}function l(c){const u=a(c);if(u)return u;throw new Error("Non-base"+n+" character")}return{encode:s,decodeUnsafe:a,decode:l}}var jj="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const qj=Hj(jj);var we=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},Mt=function(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n},yn,Hn,Uo,Wo,Ho,Ol,sd,qe,ad,pp,ld,mp,kl,vp,wE,EE,SE,IE;class Gj extends zV{get name(){return we(this,qe,"f").name}get url(){return"https://github.com/solana-labs/wallet-standard"}get icon(){return we(this,qe,"f").icon}get readyState(){return we(this,ad,"f")}get publicKey(){return we(this,Uo,"f")}get connecting(){return we(this,Wo,"f")}get supportedTransactionVersions(){return we(this,sd,"f")}get wallet(){return we(this,qe,"f")}get standard(){return!0}constructor({wallet:e}){super(),yn.add(this),Hn.set(this,void 0),Uo.set(this,void 0),Wo.set(this,void 0),Ho.set(this,void 0),Ol.set(this,void 0),sd.set(this,void 0),qe.set(this,void 0),ad.set(this,typeof window=="undefined"||typeof document=="undefined"?fl.Unsupported:fl.Installed),vp.set(this,n=>{if("accounts"in n){const r=we(this,qe,"f").accounts[0];we(this,Hn,"f")&&!we(this,Ho,"f")&&r!==we(this,Hn,"f")&&(r?we(this,yn,"m",ld).call(this,r):(this.emit("error",new FV),we(this,yn,"m",mp).call(this)))}"features"in n&&we(this,yn,"m",kl).call(this)}),Mt(this,qe,e,"f"),Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),Mt(this,Wo,!1,"f"),Mt(this,Ho,!1,"f"),Mt(this,Ol,we(this,qe,"f").features[P1].on("change",we(this,vp,"f")),"f"),we(this,yn,"m",kl).call(this)}destroy(){Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),Mt(this,Wo,!1,"f"),Mt(this,Ho,!1,"f");const e=we(this,Ol,"f");e&&(Mt(this,Ol,null,"f"),e())}async autoConnect(){return we(this,yn,"m",pp).call(this,{silent:!0})}async connect(){return we(this,yn,"m",pp).call(this)}async disconnect(){if(N1 in we(this,qe,"f").features)try{Mt(this,Ho,!0,"f"),await we(this,qe,"f").features[N1].disconnect()}catch(e){this.emit("error",new DV(e==null?void 0:e.message,e))}finally{Mt(this,Ho,!1,"f")}we(this,yn,"m",mp).call(this)}async sendTransaction(e,n,r={}){try{const i=we(this,Hn,"f");if(!i)throw new hl;let o;if(Ji in we(this,qe,"f").features)if(i.features.includes(Ji))o=Ji;else if(gn in we(this,qe,"f").features&&i.features.includes(gn))o=gn;else throw new Vs;else if(gn in we(this,qe,"f").features){if(!i.features.includes(gn))throw new Vs;o=gn}else throw new dl;const s=Uj(n.rpcEndpoint);if(!i.chains.includes(s))throw new O1;try{const{signers:a,...l}=r;let c;if(gl(e)?(a!=null&&a.length&&e.sign(a),c=e.serialize()):(e=await this.prepareTransaction(e,n,l),a!=null&&a.length&&e.partialSign(...a),c=new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))),o===Ji){const[u]=await we(this,qe,"f").features[Ji].signAndSendTransaction({account:i,chain:s,transaction:c,options:{preflightCommitment:gp(l.preflightCommitment||n.commitment),skipPreflight:l.skipPreflight,maxRetries:l.maxRetries,minContextSlot:l.minContextSlot}});return qj.encode(u.signature)}else{const[u]=await we(this,qe,"f").features[gn].signTransaction({account:i,chain:s,transaction:c,options:{preflightCommitment:gp(l.preflightCommitment||n.commitment),minContextSlot:l.minContextSlot}});return await n.sendRawTransaction(u.signedTransaction,{...l,preflightCommitment:gp(l.preflightCommitment||n.commitment)})}}catch(a){throw a instanceof Un?a:new O1(a==null?void 0:a.message,a)}}catch(i){throw this.emit("error",i),i}}}Hn=new WeakMap,Uo=new WeakMap,Wo=new WeakMap,Ho=new WeakMap,Ol=new WeakMap,sd=new WeakMap,qe=new WeakMap,ad=new WeakMap,vp=new WeakMap,yn=new WeakSet,pp=async function(e){try{if(this.connected||this.connecting)return;if(we(this,ad,"f")!==fl.Installed)throw new MV;if(Mt(this,Wo,!0,"f"),!we(this,qe,"f").accounts.length)try{await we(this,qe,"f").features[R1].connect(e)}catch(r){throw new BV(r==null?void 0:r.message,r)}const n=we(this,qe,"f").accounts[0];if(!n)throw new Vs;we(this,yn,"m",ld).call(this,n)}catch(n){throw this.emit("error",n),n}finally{Mt(this,Wo,!1,"f")}},ld=function(e){let n;try{n=new Re(e.address)}catch(r){throw new VV(r==null?void 0:r.message,r)}Mt(this,Hn,e,"f"),Mt(this,Uo,n,"f"),we(this,yn,"m",kl).call(this),this.emit("connect",n)},mp=function(){Mt(this,Hn,null,"f"),Mt(this,Uo,null,"f"),we(this,yn,"m",kl).call(this),this.emit("disconnect")},kl=function(){var n,r;const e=Ji in we(this,qe,"f").features?we(this,qe,"f").features[Ji].supportedTransactionVersions:we(this,qe,"f").features[gn].supportedTransactionVersions;Mt(this,sd,Wj(e,["legacy"])?null:new Set(e),"f"),gn in we(this,qe,"f").features&&((n=we(this,Hn,"f"))!=null&&n.features.includes(gn))?(this.signTransaction=we(this,yn,"m",wE),this.signAllTransactions=we(this,yn,"m",EE)):(delete this.signTransaction,delete this.signAllTransactions),pl in we(this,qe,"f").features&&((r=we(this,Hn,"f"))!=null&&r.features.includes(pl))?this.signMessage=we(this,yn,"m",SE):delete this.signMessage,Eg in we(this,qe,"f").features?this.signIn=we(this,yn,"m",IE):delete this.signIn},wE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(gn in we(this,qe,"f").features))throw new dl;if(!n.features.includes(gn))throw new Vs;try{const i=(await we(this,qe,"f").features[gn].signTransaction({account:n,transaction:gl(e)?e.serialize():new Uint8Array(e.serialize({requireAllSignatures:!1,verifySignatures:!1}))}))[0].signedTransaction;return gl(e)?Vo.deserialize(i):cr.from(i)}catch(r){throw r instanceof Un?r:new k1(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},EE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(gn in we(this,qe,"f").features))throw new dl;if(!n.features.includes(gn))throw new Vs;try{const r=await we(this,qe,"f").features[gn].signTransaction(...e.map(i=>({account:n,transaction:gl(i)?i.serialize():new Uint8Array(i.serialize({requireAllSignatures:!1,verifySignatures:!1}))})));return e.map((i,o)=>{const s=r[o].signedTransaction;return gl(i)?Vo.deserialize(s):cr.from(s)})}catch(r){throw new k1(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},SE=async function(e){try{const n=we(this,Hn,"f");if(!n)throw new hl;if(!(pl in we(this,qe,"f").features))throw new dl;if(!n.features.includes(pl))throw new Vs;try{return(await we(this,qe,"f").features[pl].signMessage({account:n,message:e}))[0].signature}catch(r){throw new $V(r==null?void 0:r.message,r)}}catch(n){throw this.emit("error",n),n}},IE=async function(e={}){try{if(!(Eg in we(this,qe,"f").features))throw new dl;let n;try{[n]=await we(this,qe,"f").features[Eg].signIn(e)}catch(r){throw new T1(r==null?void 0:r.message,r)}if(!n)throw new T1;return we(this,yn,"m",ld).call(this,n.account),n}catch(n){throw this.emit("error",n),n}};class Kj{constructor(e){mt(this,"iframe");mt(this,"handshakeComplete",!1);mt(this,"parentAPI",null);mt(this,"endpoint",null);if(!e)throw new Error("BridgeParent requires an iframe element");this.iframe=e,this.initializeConnection()}async initializeConnection(){if(!this.iframe||!this.iframe.contentWindow)return;const e=await this.discoverWallets(),n=this.getSolanaWallets();this.parentAPI={eip6963Wallets:e,eip6963WalletsReady:!0,walletStandardWallets:n,walletStandardWalletsReady:!0},this.endpoint=EV(this.iframe.contentWindow,window,"*"),bg(this.parentAPI,this.endpoint),this.handshakeComplete=!0}isConnected(){return this.handshakeComplete}async discoverWallets(){return new Promise(e=>{const n=[],i=o=>{const s=o,{info:a,provider:l}=s.detail;n.findIndex(u=>u.uuid===a.uuid)===-1&&n.push({uuid:a.uuid,name:a.name,icon:a.icon,rdns:a.rdns,provider:l})};window.addEventListener("eip6963:announceProvider",i),window.dispatchEvent(new Event("eip6963:requestProvider")),setTimeout(()=>{window.removeEventListener("eip6963:announceProvider",i),e(n)},1e3)})}getSolanaWallets(){const{get:e}=kV(),n=e(),r=[],i=new Set;for(const o of n)if(this.isSolanaWallet(o)){let s;UV(o)&&(s=new Gj({wallet:o})),r.push({uuid:this.generateWalletId(o),name:o.name,chains:o.chains||[],features:Object.keys(o.features),adapter:s?{name:s.name,url:s.url,icon:s.icon,readyState:s.readyState,publicKey:S1({get value(){return s.publicKey},toBase58:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBase58()},toJSON:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toJSON()},toBytes:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBytes()},toBuffer:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toBuffer()},toString:async()=>{var a;return(a=s.publicKey)==null?void 0:a.toString()}}),connecting:s.connecting,connected:s.connected,supportedTransactionVersions:s.supportedTransactionVersions,wallet:s.wallet,standard:s.standard,destroy:async()=>await s.destroy(),autoConnect:async()=>await s.autoConnect(),connect:async()=>await s.connect(),disconnect:async()=>await s.disconnect(),sendTransaction:async(a,l,c)=>await s.sendTransaction(a,l,c),signTransaction:async a=>s.signTransaction!==void 0?await s.signTransaction(a):new Error("Adapter does not support signTransaction"),signAllTransactions:async a=>s.signAllTransactions!==void 0?await s.signAllTransactions(a):new Error("Adapter does not support signAllTransactions"),signMessage:async a=>s.signMessage!==void 0?await s.signMessage(a):new Error("Adapter does not support signMessage"),signIn:async a=>s.signIn!==void 0?await s.signIn(a):new Error("Adapter does not support signIn"),customFunctions:["sendSerializedTransaction","signAllSerializedTransactions","signSerializedTransaction"],sendSerializedTransaction:async(a,l)=>{const c=new Fj(l),u=new Uint8Array(a);let h;try{h=Vo.deserialize(u)}catch(p){try{h=cr.from(u)}catch(g){throw new Error("Failed to deserialize transaction as either versioned or legacy format")}}return await s.sendTransaction(h,c)},signSerializedTransaction:async a=>{if(s.signTransaction===void 0)return new Error("Adapter does not support signTransaction");const l=new Uint8Array(a);let c;try{c=Vo.deserialize(l)}catch(u){try{c=cr.from(l)}catch(h){return new Error("Failed to deserialize transaction as either versioned or legacy format")}}return await s.signTransaction(c)},signAllSerializedTransactions:async a=>{if(s.signAllTransactions===void 0)return new Error("Adapter does not support signAllTransactions");const l=[];for(const c of a){const u=new Uint8Array(c);let h;try{h=Vo.deserialize(u)}catch(p){try{h=cr.from(u)}catch(g){return new Error("Failed to deserialize one or more transactions")}}l.push(h)}return await s.signAllTransactions(l)}}:void 0}),i.add(o.name)}return r}isSolanaWallet(e){return(e.chains||[]).some(i=>i.startsWith("solana:"))}generateWalletId(e){var r;const n=((r=e.chains)==null?void 0:r[0])||"unknown";return`${e.name}-${n}`.toLowerCase().replace(/\s+/g,"-")}destroy(){this.handshakeComplete=!1,this.parentAPI&&(this.parentAPI.eip6963Wallets=[],this.parentAPI.walletStandardWallets=[],this.parentAPI=null),this.endpoint=null,this.iframe=null}}var yp=function(){return yp=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++){e=arguments[n];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i])}return t},yp.apply(this,arguments)},CE=function(t,e,n,r){function i(o){return o instanceof n?o:new n(function(s){s(o)})}return new(n||(n=Promise))(function(o,s){function a(u){try{c(r.next(u))}catch(h){s(h)}}function l(u){try{c(r.throw(u))}catch(h){s(h)}}function c(u){u.done?o(u.value):i(u.value).then(a,l)}c((r=r.apply(t,e||[])).next())})},AE=function(t,e){var n={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},r,i,o,s=Object.create((typeof Iterator=="function"?Iterator:Object).prototype);return s.next=a(0),s.throw=a(1),s.return=a(2),typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(c){return function(u){return l([c,u])}}function l(c){if(r)throw new TypeError("Generator is already executing.");for(;s&&(s=0,c[0]&&(n=0)),n;)try{if(r=1,i&&(o=c[0]&2?i.return:c[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,c[1])).done)return o;switch(i=0,o&&(c=[c[0]&2,o.value]),c[0]){case 0:case 1:o=c;break;case 4:return n.label++,{value:c[1],done:!1};case 5:n.label++,i=c[1],c=[0];continue;case 7:c=n.ops.pop(),n.trys.pop();continue;default:if(o=n.trys,!(o=o.length>0&&o[o.length-1])&&(c[0]===6||c[0]===2)){n=0;continue}if(c[0]===3&&(!o||c[1]>o[0]&&c[1]<o[3])){n.label=c[1];break}if(c[0]===6&&n.label<o[1]){n.label=o[1],o=c;break}if(o&&n.label<o[2]){n.label=o[2],n.ops.push(c);break}o[2]&&n.ops.pop(),n.trys.pop();continue}c=e.call(t,n)}catch(u){c=[6,u],i=0}finally{r=o=0}if(c[0]&5)throw c[1];return{value:c[0]?c[1]:void 0,done:!0}}},Ae,OE,cd,bp=mg,jo=null,kE=function(){return document.getElementById(bp)};function _p(t){var e,n=kE();if(!n){console.warn("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe - no iframe element found"));return}if(!cd){console.warn("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe - no link token origin found"));return}try{(e=n.contentWindow)===null||e===void 0||e.postMessage(t,cd)}catch(r){console.error("Mesh SDK: Failed to deliver ".concat(t.type," message to the iframe")),console.error(r)}}function Yj(t){return CE(this,void 0,void 0,function(){var e,e,e,e,n,r,i,o,s,a,l,c,u,h;return AE(this,function(p){switch(t.data.type){case"brokerageAccountAccessToken":{e={accessToken:t.data.payload},(n=Ae==null?void 0:Ae.onEvent)===null||n===void 0||n.call(Ae,{type:"integrationConnected",payload:e}),(r=Ae==null?void 0:Ae.onIntegrationConnected)===null||r===void 0||r.call(Ae,e);break}case"delayedAuthentication":{e={delayedAuth:t.data.payload},(i=Ae==null?void 0:Ae.onEvent)===null||i===void 0||i.call(Ae,{type:"integrationConnected",payload:e}),(o=Ae==null?void 0:Ae.onIntegrationConnected)===null||o===void 0||o.call(Ae,e);break}case"transferFinished":{e=t.data.payload,(s=Ae==null?void 0:Ae.onEvent)===null||s===void 0||s.call(Ae,{type:"transferCompleted",payload:e}),(a=Ae==null?void 0:Ae.onTransferFinished)===null||a===void 0||a.call(Ae,e);break}case"close":case"done":{e=(l=t.data)===null||l===void 0?void 0:l.payload,(c=Ae==null?void 0:Ae.onExit)===null||c===void 0||c.call(Ae,e==null?void 0:e.errorMessage,e),jo==null||jo.destroy(),vg();break}case"loaded":{_p({type:"meshSDKSpecs",payload:yp({},dV)}),Ae!=null&&Ae.accessTokens&&_p({type:"frontAccessTokens",payload:Ae.accessTokens}),Ae!=null&&Ae.transferDestinationTokens&&_p({type:"frontTransferDestinationTokens",payload:Ae.transferDestinationTokens}),(u=Ae==null?void 0:Ae.onEvent)===null||u===void 0||u.call(Ae,{type:"pageLoaded"});break}default:{sV(t.data.type)&&((h=Ae==null?void 0:Ae.onEvent)===null||h===void 0||h.call(Ae,t.data));break}}return[2]})})}function xp(t){return CE(this,void 0,void 0,function(){return AE(this,function(e){switch(e.label){case 0:return t.origin!==OE&&t.origin!==cd?(console.warn("Received message from untrusted origin:",t.origin),[3,3]):[3,1];case 1:return[4,Yj(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})}var TE=function(t){var e=function(r,i){var o,s;if(!r){(o=t==null?void 0:t.onExit)===null||o===void 0||o.call(t,"Invalid link token!");return}Ae=t;var a=window.atob(r),l=a.startsWith("http://")||a.startsWith("https://");if(!l){(s=t==null?void 0:t.onExit)===null||s===void 0||s.call(t,"Invalid link token!");return}if(a=Xj(a,Ae==null?void 0:Ae.language),a=Zj(a,Ae==null?void 0:Ae.displayFiatCurrency),a=Jj(a,Ae==null?void 0:Ae.theme),cd=new URL(a).origin,window.removeEventListener("message",xp),i){var c=document.getElementById(i);c?(c.allow="clipboard-read *; clipboard-write *",c.src=a,bp=i):console.warn("Mesh SDK: No iframe found with id ".concat(i))}else bp=mg,cV(a);window.addEventListener("message",xp),OE=window.location.origin;var u=kE();u&&(jo=new Kj(u))},n=function(){var r;jo==null||jo.destroy(),vg(),window.removeEventListener("message",xp),(r=t.onExit)===null||r===void 0||r.call(t)};return{openLink:e,closeLink:n}};function Xj(t,e){return e==="system"&&(e=typeof navigator!="undefined"&&navigator.language?encodeURIComponent(navigator.language):void 0),"".concat(t).concat(t.includes("?")?"&":"?","lng=").concat(e||"en")}function Zj(t,e){return e?"".concat(t).concat(t.includes("?")?"&":"?","fiatCur=").concat(e):t}function Jj(t,e){return e?"".concat(t).concat(t.includes("?")?"&":"?","th=").concat(e):t}const Qj="Swap not found for a required underlying of defi route, please make sure your amount is within an acceptable range",eq="coingecko",tq=t=>t.includes(eq)?t.replace("/thumb/","/large/"):t,RE=({token:t,chainId:e,size:n=32})=>w.jsxs(ue,{position:"relative",borderRadius:"50%",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:t!=null&&t.logoURI?tq(t==null?void 0:t.logoURI):Is,title:t==null?void 0:t.symbol,alt:t==null?void 0:t.symbol,width:`${n}px`,height:`${n}px`})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid",borderColor:"bg",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),ud=()=>{const{address:t}=et.useAccount(),{walletIcon:e,walletDisplayName:n}=f1(),{chainIdOut:r,effectiveTokenOutData:i,tokenInData:o,amountIn:s,chainIdIn:a,selectedIntegration:l,isNontokenized:c}=yr(),{routeLoading:u,routeData:h,routeFetched:p,routerError:g}=Ms(),b=u||!p&&!g,m=h!=null&&h.error||(h==null?void 0:h.statusCode)===500?Qj:null,x=Iu({hash:t,chainId:a,type:"/address"}),I=Iu({hash:t,chainId:r,type:"/address"}),N=K.useMemo(()=>{if(l!=null&&l.type){const T=hd[l.type],$=l.name||l.type;return w.jsxs(w.Fragment,{children:[T&&w.jsx(Rn,{src:T,width:"16px",height:"16px",borderRadius:"full"}),w.jsx(Te,{children:$})]})}return w.jsxs(w.Fragment,{children:[typeof e=="string"?w.jsx(Rn,{src:e,width:"16px",height:"16px"}):e,w.jsx(Kf,{content:n,children:w.jsx(Te,{children:t&&n+" "+ug(t,!0)})}),x&&w.jsx(Vf,{href:x,target:"_blank",children:w.jsx(on,{as:H_,color:"fg.muted",width:"16px",height:"16px"})})]})},[l,e,n,t,x]);return w.jsxs(w.Fragment,{children:[w.jsx(hu,{size:"sm",variant:"outline",width:"100%",borderRadius:"sm",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Source"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(ue,{display:"flex",gap:"8px",alignItems:"center",children:N})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Destination"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(jr,{loading:b,width:b?"80px":"auto",children:w.jsxs(tr,{gap:"8px",alignItems:"center",children:[w.jsx(Rn,{src:dg(r),width:"16px",height:"16px"}),w.jsx(Te,{children:l1(r)})," - ",w.jsx(Kf,{content:n,children:w.jsx(Te,{children:t&&ug(t)})}),I&&w.jsx(Vf,{href:I,target:"_blank",children:w.jsx(on,{as:H_,color:"fg.muted",width:"16px",height:"16px"})})]})})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Estimated time"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(jr,{loading:b,width:b?"80px":"auto",children:w.jsx(Te,{children:l!=null&&l.type?"~2min":a!==r?"~1 min":"instant"})})})]})]})},"line"),m?w.jsx(Te,{fontSize:"xs",color:"error",children:m}):w.jsx(hu,{size:"sm",variant:"outline",bg:"bg.subtle",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"You send"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsxs(ue,{display:"flex",gap:"8px",alignItems:"center",children:[w.jsxs(Te,{children:[kr(ir(s,o==null?void 0:o.decimals))," ",o==null?void 0:o.symbol]}),w.jsx(RE,{token:o,chainId:a,size:24})]})})]}),w.jsxs(En,{children:[w.jsx(je,{children:c&&(i!=null&&i.protocol)?`Deposit into ${i.protocolName||i.protocol}`:"You receive"}),w.jsxs(je,{display:"flex",textAlign:"end",justifyContent:"end",children:[" ",w.jsx(jr,{loading:b,width:b?"156px":"auto",children:w.jsxs(ue,{display:"flex",gap:"8px",alignItems:"center",children:[w.jsxs(Te,{children:[kr(ir(h==null?void 0:h.amountOut,i==null?void 0:i.decimals))," ",i==null?void 0:i.symbol]}),c&&(i!=null&&i.protocol)?w.jsxs(ue,{position:"relative",minW:"24px",minH:"24px",children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:"24px",height:"24px",children:w.jsx("img",{src:i.protocolLogo||Is,title:i.protocol,alt:i.protocol,width:"24px",height:"24px",onError:T=>{T.currentTarget.src=Is}})}),r&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:"12px",height:"12px",borderRadius:"50%",overflow:"hidden",border:"1px solid",borderColor:"bg",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[r]}.svg`,alt:`Chain ${r}`,width:"100%",height:"100%"})})]}):w.jsx(RE,{token:i,chainId:r,size:24})]})})]})]})]})},"line")]})},nq=()=>{var l;const{routeData:t}=Ms(),{tokenIn:e,chainIdIn:n,amountIn:r}=yr(),{data:i}=ll(n,Pt),{data:[o]}=Ls(Pt,n),s=K.useMemo(()=>{var u,h;let c=+((h=(u=t==null?void 0:t.tx)==null?void 0:u.value)!=null?h:0);return Ro(e,Pt)&&(c-=+r),ir(Math.max(0,c).toString(),18)},[(l=t==null?void 0:t.tx)==null?void 0:l.value,e,r]),a=+s*+(i!=null?i:0);return w.jsxs(Te,{title:"Bridging fee",cursor:"default",display:"flex",alignItems:"center",gap:1,color:"fg.subtle",fontSize:"xs",children:[w.jsx(q4,{size:12}),w.jsx(Kf,{content:`${kr(s,!0)} ${o==null?void 0:o.symbol}`,children:w.jsx(Te,{fontSize:"xs",color:"fg.subtle",children:Tr(a)})})]})};We("div",{base:{display:"flex",justifyContent:"space-between",alignItems:"center",h:"36px",p:"8px 12px",borderRadius:"8px",bg:"bg",w:"100%"}});const dd=()=>{const{routeData:t}=Ms(),{chainIdIn:e,chainIdOut:n,selectedIntegration:r}=yr(),i=Me(c=>c.slippage),[o,s]=K.useState(!1),l=[{detail:`${t!=null&&t.priceImpact?(-(t==null?void 0:t.priceImpact)/100).toFixed(2):"0.00"}%`,label:"Est. price impact"},{detail:`${i/100}%`,label:"Max. slippage"},{detail:r!=null&&r.type?"~2min":e!==n?"~1 min":"instant",label:"Est. processing time"}];return w.jsx(x4,{open:o,onOpenChange:c=>s(c.open),w:"full",children:w.jsxs(ue,{width:"100%",bg:"bg.subtle",borderRadius:"md",padding:"12px",transition:"all 0.2s",children:[w.jsx(w4,{asChild:!0,children:w.jsxs(tr,{align:"center",justify:"space-between",width:"100%",cursor:"pointer",children:[w.jsxs(tr,{align:"center",gap:2,children:[w.jsx(Vi,{color:"fg.muted",fontSize:"sm",children:"Transaction details"}),w.jsx(on,{as:H4,width:"14px",height:"14px",color:"fg.muted",transform:o?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.2s ease-in-out"})]}),w.jsx(nq,{})]})}),w.jsx(E4,{children:w.jsx(ue,{marginTop:"12px",paddingTop:"12px",borderTop:"1px solid",borderColor:"border",children:l.map((c,u)=>w.jsxs(tr,{justify:"space-between",align:"center",paddingY:"6px",children:[w.jsx(Vi,{fontSize:"sm",color:"fg.muted",children:c.label}),w.jsx(Vi,{fontSize:"sm",color:"fg",fontWeight:"medium",children:c.detail})]},u))})})]})})},rq=We("div",{base:{w:"58px",h:"58px",borderRadius:"full",border:"1px solid",borderColor:"border",display:"flex",alignItems:"center",justifyContent:"center"}}),NE=({onFinish:t,start:e,duration:n=60})=>{const[r,i]=K.useState(n);K.useEffect(()=>{i(n)},[n]),K.useEffect(()=>{if(!e)return;const s=setInterval(()=>{i(a=>a<=1?(clearInterval(s),t==null||t(),0):a-1)},1e3);return()=>clearInterval(s)},[e,t]);const o=s=>{const a=Math.floor(s/60).toString().padStart(2,"0"),l=(s%60).toString().padStart(2,"0");return`${a}:${l}`};return w.jsx(Es,{children:w.jsx(rq,{children:w.jsx(Te,{fontSize:"xs",color:"fg.muted",fontWeight:"medium",children:o(r)})})})},iq="data:image/svg+xml,%3csvg%20width='17'%20height='16'%20viewBox='0%200%2017%2016'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_126_8587)'%3e%3cpath%20fill-rule='evenodd'%20clip-rule='evenodd'%20d='M16.3686%2010.6232C16.3715%2010.6146%2016.359%2010.6097%2016.355%2010.6179C14.975%2013.5085%2012.2144%2015.5112%208.66017%2015.5112C4.88611%2015.5112%201.35008%2012.688%201.35008%208.37011C1.35008%204.65011%204.30812%201.56104%207.74213%201.56104C10.6321%201.56104%2012.6382%203.28819%2012.6382%204.51714C12.6382%205.08189%2012.2642%205.48041%2011.6862%205.48041C10.3602%205.48041%209.85022%203.15536%207.33413%203.15536C4.78406%203.15536%202.6081%205.54683%202.6081%208.37011C2.6081%2012.0238%205.56614%2014.4153%208.52417%2014.4153C9.68043%2014.4153%2010.322%2014.1182%2010.5073%2014.0169C10.515%2014.0126%2010.51%2014.0012%2010.5017%2014.0037C10.3174%2014.0604%209.73839%2014.2159%208.93211%2014.2159C5.29405%2014.2159%203.83206%2011.4591%203.83206%209.66544C3.83206%208.30367%204.71606%207.73906%205.43016%207.73906C7.33413%207.73906%207.06219%2011.7248%2011.7542%2011.7248C14.2023%2011.7248%2016.4803%2010.0972%2016.4803%206.87544C16.4803%203.22178%2012.9442%200%208.66017%200C4.17214%200%200.5%203.554%200.5%207.97156C0.5%2012.4223%204.30812%2015.9763%208.66017%2015.9763C12.4804%2015.9763%2015.3429%2013.5242%2016.3686%2010.6232Z'%20fill='%231E171F'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_126_8587'%3e%3crect%20width='16'%20height='16'%20fill='white'%20transform='translate(0.5)'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",oq="data:image/svg+xml,%3csvg%20width='32'%20height='33'%20viewBox='0%200%2032%2033'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20y='0.5'%20width='32'%20height='32'%20rx='16'%20fill='%232F2B32'/%3e%3cpath%20d='M22.5582%2020.6133L16.0006%2027.1709L9.4469%2020.6172L9.44397%2020.6133L11.858%2018.2061L16.0006%2022.3496L20.1481%2018.2021L22.5582%2020.6133ZM18.4469%2016.502L16.0006%2018.9521L13.5543%2016.5059V16.498L13.984%2016.0693L14.194%2015.8633L16.0006%2014.0557L18.4469%2016.502ZM26.6666%2016.5029L24.2565%2018.9131L21.8473%2016.5029L24.2565%2014.0928L26.6666%2016.5029ZM10.153%2016.501L7.7428%2018.9111L5.33264%2016.501L7.7428%2014.0908L10.153%2016.501ZM22.5582%2012.3906L20.1481%2014.8018L16.0006%2010.6543L11.858%2014.7979L9.4469%2012.3867L16.0006%205.83301L22.5582%2012.3906Z'%20fill='%23F3BA2F'/%3e%3c/svg%3e",wp=({icon:t,title:e,description:n})=>w.jsxs(ue,{display:"flex",flexDirection:"row",gap:"16px",width:"100%",alignItems:"flex-start",children:[w.jsx(on,{as:t,color:"fg.muted",width:"20px",height:"20px",marginTop:"2px"}),w.jsxs(ue,{display:"flex",flexDirection:"column",gap:"4px",flex:"1",children:[w.jsx(ue,{fontWeight:"600",fontSize:"14px",lineHeight:"120%",color:"fg",children:e}),w.jsx(ue,{fontWeight:"400",fontSize:"12px",lineHeight:"140%",color:"fg.subtle",children:n})]})]}),sq=({onConfirm:t,exchangeName:e="your exchange",exchangeIcon:n})=>w.jsxs(tn,{children:[w.jsx(ue,{display:"flex",justifyContent:"center",width:"100%",children:w.jsx(Rn,{w:"48px",h:"48px",borderRadius:"full",src:n||oq})}),w.jsxs(ue,{fontWeight:"600",fontSize:"16px",lineHeight:"140%",color:"fg",textAlign:"center",children:["Enso Checkout uses a 3rd party to connect your ",e," account."]}),w.jsxs(ue,{display:"flex",flexDirection:"column",gap:"12px",width:"100%",children:[w.jsx(wp,{icon:G4,title:"Your sign-in credentials are never stored",description:"All data is encrypted between enso and Binance"}),w.jsx(wp,{icon:Y4,title:"2fa always required",description:"Transfers cannot be made without your approval."}),w.jsx(wp,{icon:K4,title:"Assets never touch 3rd parties",description:"Your funds are transferred directly to your wallet."}),w.jsxs(mB,{children:[w.jsx(Rn,{src:iq,color:"gray",w:"24px"}),"Enso securely encrypts all user data."]})]}),w.jsx(nr,{onClick:t,children:"Continue to 3rd Party"})]}),PE="data:image/svg+xml,%3csvg%20width='58'%20height='58'%20viewBox='0%200%2058%2058'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='29'%20cy='29'%20r='29'%20fill='%2314AE5C'/%3e%3cpath%20d='M36.2929%2022.2929C36.6834%2021.9024%2037.3164%2021.9024%2037.707%2022.2929C38.0975%2022.6834%2038.0975%2023.3164%2037.707%2023.707L26.707%2034.707C26.3164%2035.0975%2025.6834%2035.0975%2025.2929%2034.707L20.2929%2029.707C19.9024%2029.3164%2019.9024%2028.6834%2020.2929%2028.2929C20.659%2027.9268%2021.238%2027.9042%2021.6308%2028.2245L21.707%2028.2929L25.9999%2032.5859L36.2929%2022.2929Z'%20fill='white'/%3e%3c/svg%3e",LE="data:image/svg+xml,%3csvg%20width='58'%20height='58'%20viewBox='0%200%2058%2058'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3ccircle%20cx='29'%20cy='29'%20r='29'%20fill='%23E84142'/%3e%3cpath%20d='M34.2929%2022.2929C34.6834%2021.9024%2035.3164%2021.9024%2035.707%2022.2929C36.0975%2022.6834%2036.0975%2023.3164%2035.707%2023.707L23.707%2035.707C23.3164%2036.0975%2022.6834%2036.0975%2022.2929%2035.707C21.9024%2035.3164%2021.9024%2034.6834%2022.2929%2034.2929L34.2929%2022.2929Z'%20fill='white'/%3e%3cpath%20d='M22.2929%2022.2929C22.6834%2021.9024%2023.3164%2021.9024%2023.707%2022.2929L35.707%2034.2929L35.7753%2034.3691C36.0957%2034.7618%2036.0731%2035.3408%2035.707%2035.707C35.3408%2036.0731%2034.7618%2036.0957%2034.3691%2035.7753L34.2929%2035.707L22.2929%2023.707C21.9024%2023.3164%2021.9024%2022.6834%2022.2929%2022.2929Z'%20fill='white'/%3e%3c/svg%3e";var Qr=(t=>(t.Binance="binance",t.Kraken="kraken",t.Coinbase="coinbase",t.Bybit="bybit",t))(Qr||{});const Qs=ox(t=>({txs:[],addTx:e=>t(n=>({txs:[...n.txs,e]})),removeTx:e=>t(n=>({txs:n.txs.filter(r=>r.hash!==e)})),updateTx:(e,n)=>t(r=>({txs:r.txs.map(i=>i.hash===e?{...i,...n}:i)}))})),aq=t=>{const{txs:e}=Qs();return e.find(n=>n.hash===t)},lq=()=>{const{addTx:t}=Qs();return{track:K.useCallback(n=>{n.hash&&t(n)},[])}},cq=(t,e=!0)=>{var l,c;const{data:n,isLoading:r}=Kn.useQuery({queryKey:["layerZeroStatus",t||"none"],queryFn:async()=>t?fetch(`https://scan.layerzero-api.com/v1/messages/tx/${t}`).then(u=>u.json()).then(u=>{var h,p;return(p=(h=u.data)==null?void 0:h[0])!=null?p:null}):null,refetchInterval:2e3,enabled:e&&!!t}),i=(l=n==null?void 0:n.status)==null?void 0:l.name,o=(c=n==null?void 0:n.source)==null?void 0:c.status;let s=0,a="Waiting for bridge transaction...";return o&&o!=="SUCCEEDED"?(s=1,a="Waiting for funds to be sent on destination"):i==="INFLIGHT"?(s=2,a="Waiting for funds to be delivered on destination"):i==="CONFIRMING"?(s=3,a="Waiting for destination execution"):i==="DELIVERED"&&(s=4,a="Bridging is complete"),{data:n,isLoading:r,status:i,sourceStatus:o,step:s,message:a,isComplete:i==="DELIVERED",isFailed:i==="FAILED"}},uq=(t,e)=>{const n=Qs(i=>i.updateTx),{data:r}=Kn.useQuery({queryKey:["layerZeroUrl",t||"none",!!e],queryFn:async()=>t?fetch(`https://scan.layerzero-api.com/v1/messages/tx/${t}`).then(i=>i.json()).then(i=>i.data[0]):null,refetchInterval:2e3,enabled:!!(e&&t)});K.useEffect(()=>{var i,o,s,a;t&&((i=r==null?void 0:r.source)!=null&&i.status&&r.source.status!=="SUCCEEDED"?n(t,{status:"(1/4) Waiting for funds to be sent on destination"}):((o=r==null?void 0:r.status)==null?void 0:o.name)==="DELIVERED"?(e==null||e(),n(t,{status:"(4/4) Bridging is complete",isActive:!1})):((s=r==null?void 0:r.status)==null?void 0:s.name)==="CONFIRMING"?n(t,{status:"(3/4) Waiting for destination execution"}):((a=r==null?void 0:r.status)==null?void 0:a.name)==="INFLIGHT"&&n(t,{status:"(2/4) Waiting for funds to be delivered on destination"}))},[r,t])},dq=(t,e,n,r,i)=>{const o=Iu({hash:t,chainId:e}),s=Qs(a=>a.updateTx);K.useEffect(()=>{i&&(r.error?s(t,{status:"Transaction Failed",isActive:!1}):r.data&&(i==null||i(),s(t,{status:"Transaction Confirmed",isActive:!1})))},[r.data,r.error,r.isLoading,n,o,i])},hq=({hash:t,chainId:e,message:n="Transaction confirmed",onConfirmed:r})=>{const{removeTx:i}=Qs(),o=et.useWaitForTransactionReceipt({hash:t,chainId:e});return K.useEffect(()=>{o.data&&(r==null||r(o.data))},[o.data,r]),dq(t,e,n,o,()=>i(t)),null},fq=({hash:t,chainId:e,onConfirmed:n})=>{const r=et.useWaitForTransactionReceipt({hash:t,chainId:e});return uq(r.data?t:void 0,()=>n==null?void 0:n(r.data)),null},gq=t=>t.crosschain?w.jsx(fq,{...t}):w.jsx(hq,{...t}),pq=()=>{const{txs:t}=Qs();return w.jsx(w.Fragment,{children:t.filter(e=>e.isActive).map(e=>w.jsx(gq,{...e},e.hash))})},mq="0x0000000071727de22e5e9d8baf0edac6f37da032",ea={[Qr.Binance]:"binanceInternationalDirect",[Qr.Kraken]:"krakenDirect",[Qr.Coinbase]:"coinbase",[Qr.Bybit]:"bybitDirect"},hd={[ea[Qr.Binance]]:"https://assets.coingecko.com/markets/images/52/large/binance.jpg",[ea[Qr.Kraken]]:"https://assets.coingecko.com/markets/images/29/large/kraken.jpg",[ea[Qr.Coinbase]]:"https://assets.coingecko.com/markets/images/23/large/Coinbase_Coin_Primary.png",[ea[Qr.Bybit]]:"https://assets.coingecko.com/markets/images/698/large/bybit_spot.png"},ME=t=>t==="delayed",Tl="https://mesh-bff.enso-checkout.workers.dev";var fd=(t=>(t[t.CheckSessionKey=0]="CheckSessionKey",t[t.ChooseExchange=1]="ChooseExchange",t[t.ChooseExchangeAsset=2]="ChooseExchangeAsset",t[t.ChooseBalanceAsset=3]="ChooseBalanceAsset",t[t.ChooseAmount=4]="ChooseAmount",t[t.SignUserOp=5]="SignUserOp",t[t.InitiateWithdrawal=6]="InitiateWithdrawal",t[t.TrackUserOp=7]="TrackUserOp",t))(fd||{});const vq={0:1,2:1,4:2,5:4,6:5},yq={4:3,5:4},Ep={1:"e3c7fdd8-b1fc-4e51-85ae-bb276e075611",8453:"aa883b03-120d-477c-a588-37c2afd3ca71",42161:"a34f2431-0ddd-4de4-bc22-4a8143287aeb",137:"7436e9d0-ba42-4d2b-b4c0-8e4e606b2c12",10:"18fa36b0-88a8-43ca-83db-9a874e0a2288",43114:"bad16371-c22a-4bf4-a311-274d046cd760",56:"ed0ebeec-b166-4c8b-8574-cb078f7af8cf",146:"385f0b3a-8471-4b8f-884f-c4f4496f1603"},BE=Object.keys(Ep).map(Number),bq=t=>Ep[t]||Ep[8453],FE=()=>{const{setMeshAccessToken:t}=Me(),e=gd(),n=Me(r=>r.selectedIntegration);return K.useCallback((r,i)=>{t(r),sessionStorage.setItem(`${e}:${n==null?void 0:n.type}`,JSON.stringify({accessTokenPayload:r,sessionId:i,timestamp:Date.now()}))},[e,n==null?void 0:n.type])},_q=({setStep:t})=>{var b;const{chainIdOut:e,setChainIdIn:n}=Me(),[r,i]=K.useState([]),[o,s]=K.useState(!0),[a,l]=K.useState(null),c=Me(m=>m.setSelectedIntegration),{enableExchange:u,cexBridgeChainMapping:h}=K.useContext(ic),p=h!=null?h:Jf,g=(b=RB(e,p))!=null?b:e;return K.useEffect(()=>{g&&n(g)},[g,n]),K.useEffect(()=>{(async()=>{try{const I=await(await fetch(`${Tl}/integrations`)).json(),N=u.map($=>ea[$]).filter(Boolean),T=I==null?void 0:I.filter($=>$.networks.some(B=>+B.chainId===g)&&N.includes($.type));i(T)}catch(x){console.error("Failed to fetch integrations",x),l("Failed to load exchanges")}finally{s(!1)}})()},[g]),o?w.jsx(Es,{children:w.jsx(Co,{m:5})}):a?w.jsx(tn,{children:w.jsx(ue,{p:5,color:"red.500",children:a})}):w.jsx(tn,{children:(r==null?void 0:r.length)>0?w.jsx(Oo,{children:r.map(m=>w.jsx(Eu,{icon:hd[m.type],title:m.name,balance:"",usdBalance:"",tag:"",loading:!1,selected:!1,onClick:()=>{c({id:m.id,type:m.type,name:m.name}),t(0)}},m.id))}):w.jsx(ue,{textAlign:"center",fontSize:"sm",color:"fg.subtle",py:3,children:"No exchanges available for specified target chain"})})},xq=({setStep:t})=>{const{chainIdIn:e,chainIdOut:n,setMeshAccessToken:r,setSessionId:i}=Me(),{address:o}=et.useAccount(),s=gd(),[a,l]=K.useState(!1),c=Me(b=>b.selectedIntegration),u=e!==n,h=n&&!BE.includes(n)&&!u,p=FE();K.useEffect(()=>{if(!c){t(1);return}if(h)return;const b=sessionStorage.getItem(`${s}:${c.type}`);if(b)try{const m=JSON.parse(b);if(m!=null&&m.accessTokenPayload&&(m!=null&&m.sessionId)){r(m.accessTokenPayload),i(m.sessionId),t(2);return}}catch(m){console.error("Failed to parse saved Mesh connection",m)}l(!0)},[s,h,c]);const g=()=>{const b=c==null?void 0:c.type;fetch(`${Tl}/linktoken?brokerType=${encodeURIComponent(b)}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userId:s,integrationId:c==null?void 0:c.id,address:o})}).then(m=>m.json()).then(m=>{i(m.content.sessionId);const x=TE({clientId:o,onIntegrationConnected:I=>{console.log("onIntegrationConnected",I),x.closeLink(),t(2),p(I.accessToken,m.content.sessionId)},onExit:I=>{console.log("onExit",I)},onTransferFinished:I=>{console.log("onTransferFinished",I)},onEvent:I=>{console.log(I)}});x.openLink(m.content.linkToken)}).catch(m=>console.error(m))};return h?w.jsx(tn,{children:w.jsxs(ue,{textAlign:"center",py:8,children:[w.jsx(Te,{fontSize:"lg",fontWeight:"bold",color:"red.500",mb:4,children:"Unsupported Network"}),w.jsxs(Te,{color:"fg.muted",mb:6,children:["The selected network (Chain ID: ",n,") is not supported for exchange transactions. Please switch to a supported network such as: ",BE.join(", ")]})]})}):a?w.jsx(sq,{onConfirm:g,exchangeName:c==null?void 0:c.name,exchangeIcon:c!=null&&c.type?hd[c.type]:void 0}):w.jsx(Co,{m:5})},DE="meshDeviceId",gd=()=>K.useMemo(()=>{let t=localStorage.getItem(DE);return t||(t=`device_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,localStorage.setItem(DE,t)),t},[]),wq=({setStep:t,onTokenSelect:e})=>{const[n,r]=K.useState([]),[i,o]=K.useState(null),[s,a]=K.useState(!0),[l,c]=K.useState(null),{address:u}=et.useAccount(),{meshAccessToken:h,sessionId:p,setMeshAccessToken:g,setSessionId:b,setTokenIn:m,chainIdIn:x}=Me(),I=gd(),N=Me($=>$.selectedIntegration);K.useEffect(()=>{h&&p&&x&&N&&(async()=>{var B,G,Z,Y;try{const V=await(await fetch(`${Tl}/holdings`,{method:"POST",headers:{"Content-Type":"application/json","x-session-id":p},body:JSON.stringify({authToken:(G=(B=h==null?void 0:h.accountTokens)==null?void 0:B[0])==null?void 0:G.accessToken,brokerType:N==null?void 0:N.type})})).json();if(console.log("Holdings data:",V),V.status!=="ok"||!((Z=V.content)!=null&&Z.cryptocurrencyPositions))throw V.errorType==="invalidIntegrationToken"&&(console.log("Invalid integration token"),t(0),g(null),b(null),sessionStorage.removeItem(`${I}:${N==null?void 0:N.type}`)),new Error(V.message||"Failed to fetch holdings");const W=await(await fetch(`${Tl}/tokens?chainId=${x}&brokerType=${encodeURIComponent((N==null?void 0:N.type)||"")}`)).json();if(W.status==="success"&&((Y=W.content)!=null&&Y.tokens)){const A=W.content.tokens.map(d=>{const y=V.content.cryptocurrencyPositions.find(S=>S.symbol===d.symbol);return y?{...d,balance:y.amount,marketValue:y.marketValue,holding:y}:null}).filter(d=>d!==null&&d.marketValue>5).sort((d,y)=>y.marketValue-d.marketValue);console.log("Matched tokens with balances:",A),r(A)}else throw new Error(W.message||"Failed to fetch supported tokens")}catch(F){debugger;console.error("Error fetching data:",F),c(F instanceof Error?F.message:"Failed to fetch data")}finally{a(!1)}})()},[u,x,h,p,N]);const T=$D(n.map($=>$.symbol),x);return s?w.jsx(Es,{children:w.jsx(Co,{m:5})}):l?w.jsxs(ue,{p:5,color:"red.500",children:["Error: ",l]}):w.jsxs(tn,{children:[w.jsxs(ue,{mb:4,width:"100%",textAlign:"left",children:[w.jsx(Ao,{children:"Your Holdings"}),w.jsxs(Zf,{children:["Found ",n.length," token balances above $5"]})]}),w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:n.map(($,B)=>{var G,Z;return w.jsx(Eu,{chainId:x,icon:(Z=(G=T==null?void 0:T[B])==null?void 0:G.logoURI)==null?void 0:Z.replace("/thumb/","/large/"),title:$.name,balance:`${kr($.balance)} ${$.symbol}`,usdBalance:Tr($.marketValue||0),tag:"",loading:!1,selected:i===$.symbol,onClick:()=>{var Y;o($.symbol),e($),m((Y=T==null?void 0:T[B])==null?void 0:Y.address)}},`${$.symbol}-${B}`)})})}),n.length===0&&w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No tokens with balances found for this chain"}),w.jsx(nr,{disabled:!i,onClick:()=>{t(4)},children:"Continue"})]})},Eq=({setStep:t,onTokenSelect:e})=>{const{chainIdIn:n,setTokenIn:r,setChainIdIn:i}=Me(),[o,s]=K.useState(null),{holdingsList:a,total:l,isLoading:c}=h1(1),u=Me(h=>h.setSelectedIntegration);return K.useEffect(()=>{u({type:"delayed",name:"Smart account",id:""})},[]),c?w.jsx(Es,{children:w.jsx(Co,{m:5})}):w.jsxs(tn,{children:[w.jsx(ue,{mb:4,width:"100%",textAlign:"left",children:w.jsxs(Zf,{children:["Smart Account Balance: ",Tr(l)]})}),w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:a==null?void 0:a.map(h=>w.jsx(Eu,{chainId:h.chainId,icon:h.logoUri,title:h.name,balance:`${kr(ir(h.amount,h.decimals))} ${h.symbol}`,usdBalance:Tr(h.total),tag:"",loading:!1,selected:o===h.token&&n===h.chainId,onClick:()=>{s(h.token),r(h.token),i(h.chainId);const p={symbol:h.symbol,name:h.name,networkId:h.chainId.toString(),chainId:h.chainId,integrationNetworks:[],balance:Number(ir(h.amount,h.decimals)),marketValue:h.total};e(p)}},`${h.token}-${h.chainId}`))})}),(a==null?void 0:a.length)===0&&w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No tokens found in smart account"}),w.jsx(nr,{disabled:!o,onClick:()=>{t(4)},children:"Continue"})]})},Sq=({setStep:t,selectedToken:e})=>{var Y;const[n,r]=K.useState({tokenAmount:"",usdAmount:"",mode:"usd"}),i=Me(F=>F.setAmountIn),{tokenInData:o,selectedIntegration:s}=yr(),l=(e==null?void 0:e.symbol.toLowerCase().includes("USD"))?2:6,c=n.tokenAmount,u=n.usdAmount,h=!ME(s.type),p=e?h?(e.marketValue-ax).toFixed(2):e.marketValue.toFixed(2):0,g=K.useMemo(()=>{if(!(!e||!e.balance))return e.marketValue/e.balance},[e]),b=K.useCallback(F=>{if(!e)return;const V=e.marketValue*F/100;let U,W;if(h){const A=sx[e.symbol]||0;U=Math.max(A,Math.min(V,+p));const d=e.marketValue/e.balance;W=Math.min(U/d,e.balance)}else U=V,W=e.balance*F/100;return{tokenAmount:Cu(W,l),usdAmount:U.toFixed(2)}},[e,h,p,l]);K.useEffect(()=>{if(e){const F=b(100);if(!F)return;r(V=>({...V,...F}))}},[e,b]),K.useEffect(()=>{if(!(o!=null&&o.decimals))return;const F=c.endsWith(".")?c.slice(0,-1):c;if(!F||F==="."){i("0");return}try{i(r1(F,o.decimals))}catch(V){i("0")}},[c,o==null?void 0:o.decimals,i]);const m=fg(c),x=m!==null,I=!!u&&u!==".",N=e?x&&m!==null&&m>e.balance:!0,T=I&&(Y=fg(u))!=null?Y:0,$=h&&e?sx[e.symbol]:0,B=h&&e&&x&&T>0&&$&&m!==null&&m<$,G=h&&e&&x&&T>0&&T>+p,Z=!x||B||G||N;return e?w.jsxs(tn,{children:[w.jsxs(ue,{mb:4,width:"100%",textAlign:"left",children:[w.jsx(Ao,{children:"Enter Amount"}),w.jsxs(Zf,{children:["Available: ",kr(e.balance)," ",e.symbol," (",Tr(e.marketValue),")"]})]}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"8px",width:"100%",children:w.jsx(g1,{value:n,onChange:r,tokenSymbol:e.symbol,tokenPriceUsd:g,roundingPrecision:l,onPercentSelect:b})}),w.jsx(ue,{textAlign:"center",color:"fg.subtle",fontSize:"xs",h:3,m:-1,visibility:Z?"visible":"hidden",children:x?B?`Minimum amount is ${kr($)} ${e.symbol}`:G?`Maximum amount is ${Tr(p)} (balance - $${ax})`:N?"Amount exceeds available balance":"":"Please enter an amount"}),w.jsx(nr,{onClick:()=>Z?void 0:t(5),disabled:Z,children:"Continue"})]}):w.jsx(tn,{children:w.jsx(ue,{textAlign:"center",color:"fg.subtle",py:8,children:"No token selected"})})},Iq=({setStep:t,setUserOp:e,nextStep:n})=>{const{chainIdIn:r}=yr(),{routeLoading:i,usdAmountIn:o,routeData:s}=Ms(),{signMessageAsync:a}=et.useSignMessage(),{address:l}=et.useAccount(),[c,u]=K.useState(!1),h=async()=>{if(!s||s!=null&&s.error){console.error("No valid router data available");return}try{u(!0);const p=s==null?void 0:s.userOp;if(!p){console.error("No userOperation found in routeData");return}console.log("Signing userOperation:",p);const g=rV({userOperation:p,entryPointAddress:mq,entryPointVersion:"0.7",chainId:r}),b=await a({account:l,message:{raw:g}}),m={...p,signature:b};console.log("signedUserOp",JSON.stringify(m)),e(m),t(n)}catch(p){console.error("Failed to sign userOperation:",p)}finally{u(!1)}};return w.jsxs(tn,{children:[w.jsxs(tr,{flexDirection:"column",gap:"16px",alignItems:"center",width:"100%",children:[w.jsx(jr,{loading:i,width:i?"156px":"auto",children:w.jsx(Yf,{readOnly:!0,marginY:"8px",variant:"text",placeholder:"$10.00",value:o})}),w.jsx(ud,{})]}),w.jsx(dd,{}),w.jsx(nr,{disabled:!!(s!=null&&s.message)||i||c,loading:i||c,onClick:h,children:i?"Loading quote":c?"Signing...":"Sign Transaction"})]})},Cq=({selectedToken:t,userOp:e,setStep:n})=>{const{meshAccessToken:r,amountIn:i,chainIdIn:o}=Me(),{address:s}=et.useAccount(),{tokenInData:a}=yr(),l=Me(x=>x.sessionId),[c,u]=K.useState(!0),[h,p]=K.useState(null),g=Me(x=>x.selectedIntegration),b=FE(),m=gd();return K.useEffect(()=>{if(!t||!e||!r){console.error("Missing required data for withdrawal initiation");return}const x=a!=null&&a.decimals?ir(i,a.decimals):0;console.log("transferAmount",x),(async()=>{try{const N=[{networkId:bq(o),symbol:t.symbol,address:e.sender,amount:x}],T={restrictMultipleAccounts:!0,userId:m,integrationId:g==null?void 0:g.id,transferOptions:{toAddresses:N}};console.log("link request body",T);const B=await(await fetch(`${Tl}/linktoken?brokerType=${encodeURIComponent((g==null?void 0:g.type)||"")}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({restrictMultipleAccounts:!0,userId:m,integrationId:g==null?void 0:g.id,transferOptions:{toAddresses:N}})})).json();console.log("Link token response:",B);const G=r.accountTokens.map(F=>({...F,accountId:F.account.accountId,accountName:F.account.accountName,brokerName:g==null?void 0:g.name,brokerType:g==null?void 0:g.type}));console.log("accessTokens",G);let Z=!1;const Y=TE({clientId:s,accessTokens:G,onIntegrationConnected:F=>{b(F.accessToken,l),console.log("Integration connected",F)},onTransferFinished:F=>{console.log("Transfer finished:",F),u(!1)},onExit:F=>{console.log("Mesh link exited:",F),!Z&&(u(!1),n(2))},onEvent:F=>{var V;if(console.log("Mesh event:",F),F.type==="transferExecuted")console.log("Transfer executed, closing mesh link and moving to TrackUserOp step"),Z=!0,Y.closeLink(),n(7);else if(F.type==="transferExecutionError"){const U=((V=F.payload)==null?void 0:V.errorMessage)||"Transfer failed. Please try again.";console.error("Mesh transfer error:",U),Z=!0,Y.closeLink(),p(U),u(!1)}}});Y.openLink(B.content.linkToken)}catch(N){console.error("Failed to fetch link token:",N),u(!1)}})()},[t,e]),h?w.jsx(tn,{children:w.jsxs(tr,{direction:"column",align:"center",justify:"center",flex:1,p:6,gap:4,children:[w.jsx(tr,{align:"center",justify:"center",w:12,h:12,borderRadius:"full",bg:"orange.100",children:w.jsx(on,{as:X4,boxSize:6,color:"orange.500"})}),w.jsx(Te,{fontSize:"md",textAlign:"center",color:"gray.700",children:h})]})}):w.jsx(tn,{children:w.jsx(Es,{children:w.jsx(Te,{mt:4,children:c?w.jsxs(tr,{alignItems:"center",gap:2,children:[w.jsx(Co,{m:5}),w.jsx(Te,{children:"Intiating Mesh"})]}):"Transfer completed"})})})},Aq=({currentPhase:t,phases:e})=>w.jsx(ue,{display:"flex",gap:4,justifyContent:"center",mb:4,children:e.map((n,r)=>w.jsxs(ue,{display:"flex",alignItems:"center",gap:2,children:[w.jsx(ue,{w:6,h:6,borderRadius:"full",bg:r<t?"green.500":r===t?"blue.500":"gray.300",display:"flex",alignItems:"center",justifyContent:"center",color:"white",fontSize:"xs",fontWeight:"bold",children:r<t?"✓":r+1}),w.jsx(Te,{fontSize:"sm",color:r===t?"fg":"fg.muted",fontWeight:r===t?"semibold":"normal",children:n})]},n))}),Oq=({selectedToken:t,userOp:e,setStep:n})=>{const{chainIdIn:r,chainIdOut:i,tokenInData:o}=yr(),{amountIn:s}=Me(),a=r!==i,[l,c]=K.useState("cex"),[u,h]=K.useState(null),[p,g]=K.useState("sending"),[b,m]=K.useState("Sending operation to tracker..."),[x,I]=K.useState(null),[N,T]=K.useState(!1),[$,B]=K.useState(null),[G,Z]=K.useState(!1),[Y,F]=K.useState(null),[V,U]=K.useState(null),[W,A]=K.useState(null),d=cq(x!=null?x:void 0,a&&l==="bridge");K.useEffect(()=>{(async()=>{if(!t||!e||!o){console.error("Missing required data for tracking"),g("failed"),m("Missing required data"),c("failed");return}try{const M=await(await fetch("https://alpha-scanners-dev-054573dc8549.herokuapp.com/operations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({userOperationData:{sender:e.sender,nonce:e.nonce,factory:e.factory,factoryData:e.factoryData,callData:e.callData,callGasLimit:e.callGasLimit,verificationGasLimit:e.verificationGasLimit,preVerificationGas:e.preVerificationGas,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,paymaster:e.paymaster,paymasterData:e.paymasterData,paymasterVerificationGasLimit:e.paymasterVerificationGasLimit,paymasterPostOpGasLimit:e.paymasterPostOpGasLimit,signature:e.signature},chainId:r,expectedBalance:s,tokenAddress:o.address})})).json();if(console.log("Operation tracking response:",M),M.success&&M.operationId)h(M.operationId),g("tracking"),m(a?"Funds forwarding in progress...":"Tracking operation progress...");else throw new Error(M.message||"Failed to send operation to tracker")}catch(k){console.error("Failed to send operation to tracker:",k),g("failed"),m("Failed to send operation to tracker"),c("failed")}})()},[]),K.useEffect(()=>{if(!u||p!=="tracking")return;const k=setInterval(async()=>{var M,H,Q;try{const j=await(await fetch(`https://alpha-scanners-dev-054573dc8549.herokuapp.com/operations/${u}/status`)).json();console.log("Operation status:",j),((M=j.operation)==null?void 0:M.status)==="completed"?(g("completed"),a?(m("Funds forwarding completed!"),(H=j.operation)!=null&&H.bundleTxHash?(I(j.operation.bundleTxHash),c("bridge")):(console.warn("No bundleTxHash returned from indexer, cannot track bridge"),c("completed"))):(m("Operation completed successfully!"),c("completed")),$&&(clearInterval($),B(null))):["failed","failed_permanent"].includes((Q=j.operation)==null?void 0:Q.status)&&(g("failed"),m(a?"Bridging failed. Please select Smart-account balance as a source to use withdrawn funds":"Operation failed"),c("failed"),$&&(clearInterval($),B(null)))}catch(X){console.error("Failed to fetch operation status:",X)}},3e3);return B(k),()=>{k&&clearInterval(k)}},[u,p,a]),K.useEffect(()=>{if(!(!a||l!=="bridge")){if(d.isFailed){c("failed");return}d.isComplete&&!G&&x&&r&&(async()=>{var k;try{const M=await fetch(`https://api.enso.build/api/v1/layerzero/bridge/check?chainId=${r}&txHash=${x}`);if(!M.ok){Z(!0),F(!0),c("completed");return}const H=await M.json();Z(!0),A(H.destinationTxHash||null),H.status==="success"?(F(!0),c("completed")):H.status==="failed"?(F(!1),U(((k=H.ensoDestinationEvent)==null?void 0:k.refundDetails)||null),c("failed")):(F(!0),c("completed"))}catch(M){console.error("Failed to verify destination:",M),Z(!0),F(!0),c("completed")}})()}},[l,d.isComplete,d.isFailed,a,G,x,r]);const y=()=>{T(!0)},S=()=>l==="failed"?"failed":l==="completed"?"completed":"processing",C=()=>{switch(S()){case"completed":return"#14AE5C";case"failed":return"#E84142";default:return"#1E171F"}},R=()=>{switch(S()){case"completed":return"Success";case"failed":return"Failed";default:return"Processing"}},D=()=>a?l==="cex"?`(1/2) ${b}`:l==="bridge"?`(2/2) ${d.message}`:l==="completed"?"Transfer completed successfully!":V?"Destination execution failed. Funds refunded to smart account.":"Transfer failed":l==="completed"?"Operation completed successfully!":l==="failed"?"Operation failed":b,L=()=>l==="cex"||l==="bridge"?w.jsx(NE,{start:p==="tracking"||l==="bridge",onFinish:y,duration:a?180:120}):l==="completed"?w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:PE,boxShadow:"0px 0px 20px #14AE5C",borderRadius:"90%",width:"58px",height:"58px"})}):w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:LE,boxShadow:"0px 0px 20px #E84142",borderRadius:"90%",width:"58px",height:"58px"})}),O=r?ko[r]:"Unknown",f=i?ko[i]:"Unknown";return w.jsxs(tn,{children:[a&&w.jsx(Aq,{currentPhase:l==="cex"?0:l==="bridge"?1:2,phases:["Forward funds","Bridge"]}),w.jsxs(ue,{display:"flex",flexDirection:"column",paddingBottom:"16px",alignItems:"center",width:"100%",children:[L(),w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",marginTop:"16px",textAlign:"center",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"8px",children:D()}),(l==="cex"||l==="bridge")&&N&&w.jsx(Te,{fontSize:"sm",color:"fg.muted",maxWidth:"280px",children:"Your operation is being processed – no action is required from you."})]})]}),w.jsx(hu,{size:"sm",variant:"outline",width:"100%",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Status"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{color:C(),children:R()})})]}),a&&w.jsxs(w.Fragment,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Current Phase"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{children:l==="cex"?"Awaiting funds":l==="bridge"?"Bridging":l==="completed"?"Complete":"Failed"})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Intermediate Chain"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{textTransform:"capitalize",children:O})})]}),w.jsxs(En,{children:[w.jsx(je,{children:"Final Destination"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{textTransform:"capitalize",children:f})})]})]}),u&&w.jsxs(En,{children:[w.jsx(je,{children:"Operation ID"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"fg.muted",children:u})})]}),a&&x&&w.jsxs(En,{children:[w.jsx(je,{children:"Bridge TX"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"blue.500",cursor:"pointer",onClick:()=>window.open(`https://layerzeroscan.com/tx/${x}`,"_blank"),children:"View on LayerZero"})})]}),a&&W&&w.jsxs(En,{children:[w.jsx(je,{children:"Destination TX"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"blue.500",cursor:"pointer",onClick:()=>{const v=ux[i]||"https://etherscan.io";window.open(`${v}/tx/${W}`,"_blank")},children:"View on Explorer"})})]}),a&&l==="bridge"&&w.jsxs(En,{children:[w.jsx(je,{children:"Bridge Progress"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsxs(Te,{children:["(",d.step,"/4)"]})})]}),a&&V&&w.jsxs(En,{children:[w.jsx(je,{children:"Refund"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{fontSize:"sm",color:"orange.500",children:"Funds refunded to smart account"})})]})]})},"status"),w.jsx(ud,{}),w.jsx(dd,{}),(l==="completed"||l==="failed")&&w.jsx(nr,{onClick:()=>n(0),visual:"solid",children:l==="completed"?"New Deposit":"Retry Deposit"})]})},kq=({setFlow:t,initialStep:e=1})=>{const{handleClose:n,enforceFlow:r}=K.useContext(ic),[i,o]=K.useState(e),[s,a]=K.useState(null),[l,c]=K.useState(null),u=Me(g=>g.setSelectedIntegration),h=Me(g=>g.selectedIntegration);K.useEffect(()=>()=>u(null),[]);const p=(()=>{switch(i){case 1:return w.jsx(_q,{setStep:o});case 0:return w.jsx(xq,{setStep:o});case 2:return w.jsx(wq,{setStep:o,onTokenSelect:a});case 3:return w.jsx(Eq,{setStep:o,onTokenSelect:a});case 4:return w.jsx(Sq,{setStep:o,selectedToken:s});case 5:return w.jsx(Iq,{nextStep:s.holding?6:7,setStep:o,setUserOp:c});case 6:return w.jsx(Cq,{selectedToken:s,userOp:l,setStep:o});case 7:return w.jsx(Oq,{selectedToken:s,userOp:l,setStep:o});default:return null}})();return w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(nx,{children:[!(r&&(i===1||i===3))&&w.jsx(gi,{minWidth:"16px",minHeight:"16px",maxWidth:"16px",onClick:()=>{const g=(ME(h==null?void 0:h.type)?yq:vq)[i];g!==void 0?o(g):t("")},children:w.jsx(on,{as:U_,color:"gray",width:"16px",height:"16px"})}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center",width:"100%",children:w.jsxs(Ao,{children:["Deposit from ",h==null?void 0:h.name]})}),n&&w.jsx(gi,{onClick:n,minWidth:"16px",minHeight:"16px",maxWidth:"16px",marginLeft:"auto",children:w.jsx(on,{as:Ss,color:"gray",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:p})]})},VE=({setStep:t})=>{const e=Me(h=>h.setSelectedIntegration),n=Me(h=>h.setTokenIn),r=Me(h=>h.tokenIn),i=Me(h=>h.setChainIdIn),o=Me(h=>h.chainIdIn),s=Me(h=>h.tokenOut),a=Me(h=>h.chainIdOut),{holdingsList:l,isLoading:c}=i1(),u=l==null?void 0:l.filter(h=>!(h.token.toLowerCase()===s.toLowerCase()&&h.chainId===a));return K.useEffect(()=>{e(null)},[]),w.jsxs(tn,{children:[w.jsx(ue,{overflowY:"scroll",maxH:"400px",children:w.jsx(Oo,{children:c?Array.from({length:10}).map((h,p)=>w.jsx(jr,{height:"40px",width:"300px"},p)):u==null?void 0:u.map(h=>w.jsx(Eu,{chainId:h.chainId,icon:h.logoUri,title:h.name,balance:`${kr(ir(h.amount,h.decimals))} ${h.symbol}`,usdBalance:Tr(h.total),tag:"",loading:!1,selected:h.token===r&&h.chainId===o,onClick:()=>{n(h.token),i(h.chainId)}},`${h.token}-${h.chainId}`))})}),w.jsx(nr,{onClick:()=>{t("selectAmount")},disabled:!r,children:"Continue"})]})},Tq="coingecko",Rq=We("div",{base:{display:"flex",gap:"8px",alignItems:"center",justifyContent:"center",p:"8px 12px",borderRadius:"114px",bg:"bg.subtle",w:"fit-content"}}),Nq=t=>t.includes(Tq)?t.replace("/thumb/","/large/"):t,Pq=({token:t,chainId:e,size:n=32})=>w.jsxs(ue,{position:"relative",borderRadius:"50%",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:t!=null&&t.logoURI?Nq(t==null?void 0:t.logoURI):Is,title:t==null?void 0:t.symbol,alt:t==null?void 0:t.symbol,width:`${n}px`,height:`${n}px`})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid white",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),$E=({token:t,chainId:e,size:n=32,title:r,subTitle:i})=>w.jsxs(tr,{align:"center",gap:2,children:[w.jsx(Pq,{token:t,chainId:e,size:n}),w.jsxs(ue,{children:[w.jsx(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:r}),w.jsx(Te,{fontSize:"xs",color:"fg",children:i})]})]}),Lq=({token:t,chainId:e,size:n=32})=>{const r=(t==null?void 0:t.protocolName)||(t==null?void 0:t.protocol),i=t==null?void 0:t.protocolLogo;return w.jsxs(tr,{align:"center",gap:2,children:[w.jsxs(ue,{position:"relative",minW:`${n}px`,minH:`${n}px`,children:[w.jsx(ue,{borderRadius:"50%",overflow:"hidden",width:`${n}px`,height:`${n}px`,children:w.jsx("img",{src:i||Is,title:r,alt:r,width:`${n}px`,height:`${n}px`,onError:o=>{o.currentTarget.src=Is}})}),e&&w.jsx(ue,{position:"absolute",bottom:"0",right:"-2px",width:`${n/2}px`,height:`${n/2}px`,borderRadius:"50%",overflow:"hidden",border:"1px solid white",zIndex:"1",children:w.jsx("img",{src:`https://icons-ckg.pages.dev/stargate-light/networks/${ko[e]}.svg`,alt:`Chain ${e}`,width:"100%",height:"100%"})})]}),w.jsxs(ue,{children:[w.jsxs(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:["Deposit"," ",w.jsx(Te,{as:"span",fontSize:"xs",color:"fg",children:t==null?void 0:t.symbol})]}),w.jsxs(Te,{fontWeight:"medium",fontSize:"xs",color:"fg.muted",children:["into"," ",w.jsx(Te,{as:"span",fontSize:"xs",color:"fg",children:r})]})]})]})},Mq=({tokenIn:t,tokenOut:e,chainIdIn:n,chainIdOut:r,isNontokenized:i=!1,size:o=24})=>w.jsxs(Rq,{children:[w.jsx($E,{token:t,chainId:n,title:"You send",subTitle:t==null?void 0:t.symbol,size:o}),w.jsx(W_,{color:"#707070",width:"16px",height:"16px"}),i&&(e!=null&&e.protocol)?w.jsx(Lq,{token:e,chainId:r,size:o}):w.jsx($E,{token:e,chainId:r,title:"You receive",subTitle:e==null?void 0:e.symbol,size:o})]}),Bq=({setStep:t})=>{const[e,n]=K.useState({tokenAmount:"",usdAmount:"10.10",mode:"usd"}),r=Me(B=>B.setAmountIn),i=Me(B=>B.amountIn),[o,s]=K.useState(!0),{tokenInData:a,effectiveTokenOutData:l,tokenIn:c,chainIdOut:u,chainIdIn:h,isNontokenized:p}=yr(),{data:g}=ll(h,c),b=a!=null&&a.decimals?Math.min(a.decimals,6):6,m=e.tokenAmount,x=qD(c,h),I=K.useCallback(B=>{if(!x||!g||!(a!=null&&a.decimals))return null;const G=(BigInt(x)*BigInt(B)/BigInt(100)).toString(),Z=ir(G,a.decimals),Y=Cu(Z,b);return{tokenAmount:Y,usdAmount:(+parseFloat(Y||"0")*g).toFixed(2)}},[x,g,a==null?void 0:a.decimals,b]);K.useEffect(()=>{if(o&&g&&a&&+x>0){s(!1);const B=I(100);if(!B)return;n(G=>({...G,...B}))}},[x,o,g,a,I]),K.useEffect(()=>{if(!(a!=null&&a.decimals))return;const B=m.endsWith(".")?m.slice(0,-1):m;if(!B||B==="."){r("0");return}try{r(r1(B,a.decimals))}catch(G){r("0")}},[m,a==null?void 0:a.decimals,r]);const N=fg(m)!==null,T=N?+x<+i:!1,$=!N||T;return w.jsxs(tn,{children:[w.jsx(g1,{value:e,onChange:n,tokenSymbol:a==null?void 0:a.symbol,tokenPriceUsd:g,roundingPrecision:b,onPercentSelect:I}),w.jsx(Mq,{tokenOut:l,tokenIn:a,chainIdIn:h,chainIdOut:u,isNontokenized:p}),w.jsx(nr,{onClick:()=>t("quote"),disabled:$,children:"Continue"})]})},Fq=({setStep:t})=>{const{chainIdIn:e}=yr(),{routeLoading:n,usdAmountIn:r,routeData:i}=Ms(),o=et.useChainId(),{switchChain:s}=et.useSwitchChain(),a=UD(e),l=o!==e;return w.jsxs(tn,{children:[w.jsxs(tr,{flexDirection:"column",gap:"16px",alignItems:"center",width:"100%",children:[w.jsx(jr,{loading:n,width:n?"156px":"auto",children:w.jsx(Yf,{readOnly:!0,marginY:"8px",variant:"text",placeholder:"$10.00",value:r})}),w.jsx(ud,{})]}),w.jsx(dd,{}),l?w.jsxs(nr,{onClick:()=>{s({chainId:e})},children:["Switch to ",a]}):w.jsx(nr,{disabled:!!(i!=null&&i.error),visual:n?"lightGray":"solid",onClick:n?()=>{}:()=>{t("confirmTransfer")},children:n?"Loading quote":"Continue"})]})},Dq="data:image/svg+xml,%3csvg%20width='20'%20height='20'%20viewBox='0%200%2020%2020'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20x='1'%20y='1'%20width='18'%20height='18'%20rx='9'%20stroke='white'%20stroke-width='2'/%3e%3cpath%20d='M17.7589%2011.9352C16.6904%2016.221%2012.3496%2018.8292%208.06336%2017.7605C3.77889%2016.692%201.17066%2012.351%202.23959%208.06558C3.30758%203.77935%207.64835%201.17093%2011.9333%202.23939C16.2192%203.30785%2018.8273%207.64936%2017.7587%2011.9353L17.7588%2011.9352H17.7589Z'%20fill='%2314AE5C'/%3e%3cpath%20d='M11.9997%204.66675C12.3679%204.66675%2012.6663%204.96522%2012.6663%205.33341C12.6663%205.7016%2012.3679%206.00008%2011.9997%206.00008H7.99967C7.63148%206.00008%207.33301%205.7016%207.33301%205.33341C7.33301%204.96522%207.63148%204.66675%207.99967%204.66675H11.9997Z'%20fill='white'/%3e%3cpath%20d='M12.0003%207.33325C12.3685%207.33325%2012.667%207.63173%2012.667%207.99992V9.33325H14.667C14.9366%209.33325%2015.1797%209.49564%2015.2829%209.74471C15.386%209.99383%2015.329%2010.2806%2015.1383%2010.4713L10.4717%2015.1379C10.2113%2015.3983%209.7893%2015.3983%209.52895%2015.1379L4.86229%2010.4713C4.67162%2010.2806%204.61457%209.99383%204.71775%209.74471C4.82096%209.49564%205.06403%209.33325%205.33364%209.33325H7.33364V7.99992C7.33364%207.63173%207.63212%207.33325%208.00031%207.33325H12.0003ZM8.66697%209.99992C8.66697%2010.3681%208.3685%2010.6666%208.00031%2010.6666H6.94301L10.0003%2013.7239L13.0576%2010.6666H12.0003C11.6321%2010.6666%2011.3336%2010.3681%2011.3336%209.99992V8.66659H8.66697V9.99992Z'%20fill='white'/%3e%3c/svg%3e",Vq=We(Rn,{base:{boxSize:"36px",borderRadius:"full",objectFit:"contain"}}),$q=We(Rn,{base:{boxSize:"16px",position:"absolute",bottom:"-2px",right:"-2px",borderRadius:"full",border:"1px solid",borderColor:"bg",objectFit:"contain"}}),zq=({onClose:t,currencyIcon:e})=>{const n=()=>{const r=new Date,i=r.toLocaleString("en-US",{month:"short"}),o=r.toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"});return`${i} - ${o}`};return w.jsxs(ue,{border:"1px solid",borderColor:"border.subtle",borderRadius:"12px",width:"100%",bg:"bg",children:[w.jsxs(ue,{display:"flex",alignItems:"center",gap:"12px",borderBottom:"1px solid",borderColor:"border.subtle",padding:"10px 16px",children:[w.jsxs(ue,{position:"relative",children:[w.jsx(Vq,{src:e,alt:"Currency icon"}),w.jsx($q,{src:Dq,alt:"deposit icon"})]}),w.jsxs(ue,{flex:"1",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"4px",children:"Deposit processing"}),w.jsx(Te,{fontSize:"sm",color:"fg.muted",lineHeight:"1.4",children:"Your deposit will be added to your account soon."})]}),t&&w.jsx(on,{as:Ss,width:"16px",height:"16px",color:"fg.subtle",cursor:"pointer",_hover:{color:"fg.muted"},onClick:t})]}),w.jsxs(ue,{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"10px 16px",children:[w.jsx(Te,{fontSize:"sm",color:"fg.muted",children:"Order started"}),w.jsx(Te,{fontSize:"sm",color:"fg",fontWeight:"medium",children:n()})]})]})},Uq=()=>{var h;const{chainIdIn:t,tokenIn:e,amountIn:n}=yr(),{address:r}=et.useAccount(),{approveData:i,approveFetched:o}=mD({address:r,token:e,chainId:t,amount:n}),{routeData:s,routeFetched:a}=Ms(),{approveNeeded:l,allowanceFetched:c}=KD(e,(h=i==null?void 0:i.tx)==null?void 0:h.to,n);return{calls:K.useMemo(()=>!Ro(e,Pt)&&!c||!a||!o?[]:l?[i==null?void 0:i.tx,s==null?void 0:s.tx]:[s==null?void 0:s.tx],[l,c,a,i,s,o]),approveNeeded:l}},Wq=({setStep:t})=>{const[e,n]=K.useState("idle"),[r,i]=K.useState(!1),{address:o}=et.useAccount(),[s,a]=K.useState(""),[l,c]=K.useState(!1),{chainIdIn:u,chainIdOut:h}=yr(),{calls:p}=Uq(),{sendTxns:g,ready:b}=eV({calls:p,address:o,chainId:u}),{track:m}=lq(),x=u!==h,I=K.useCallback(W=>{n("processing"),a(W),m({hash:W,isActive:!0,chainId:u,crosschain:x,status:x?"(0/4) Waiting for source transaction completion":"Transaction in progess",message:"Transaction confirmed",onConfirmed:()=>{n("success")}})},[u,h]),N=K.useCallback(W=>{console.error(W),n("failed")},[]);K.useEffect(()=>{console.log(l,b),!l&&b&&(g(I,N),c(!0))},[l,b,g,I]);const T=()=>{i(!0)},$=()=>{t("selectToken")},B=()=>{t("quote")},G=aq(s),Z=x?`https://layerzeroscan.com/tx/${s}`:Iu({hash:s,chainId:u}),Y=()=>{switch(e){case"success":return"#14AE5C";case"failed":return"#E84142";default:return"#1E171F"}},F=()=>{switch(e){case"success":return"Success";case"failed":return"Failed";case"idle":return"Awaiting wallet approval";default:return G==null?void 0:G.status}},V=()=>{switch(e){case"processing":case"idle":return w.jsx(NE,{start:e==="processing",onFinish:T});case"success":return w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:PE,boxShadow:"0px 0px 20px #14AE5C",borderRadius:"90%",width:"58px",height:"58px"})});case"failed":return w.jsx(ue,{display:"flex",flexDirection:"column",alignItems:"center",children:w.jsx(Rn,{src:LE,boxShadow:"0px 0px 20px #E84142",borderRadius:"90%",width:"58px",height:"58px"})})}},U=()=>e==="processing"&&r?w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",marginTop:"16px",textAlign:"center",children:[w.jsx(Te,{fontSize:"lg",fontWeight:"semibold",color:"fg",marginBottom:"8px",children:"Deposit pending"}),w.jsx(Te,{fontSize:"sm",color:"fg.muted",maxWidth:"280px",children:"Your deposit is still in progress – no action is required from you."})]}):null;return w.jsxs(tn,{children:[w.jsxs(ue,{display:"flex",flexDirection:"column",paddingBottom:"16px",alignItems:"center",width:"100%",children:[V(),U()]}),w.jsx(hu,{size:"sm",variant:"outline",width:"100%",children:w.jsxs(fu,{children:[w.jsxs(En,{children:[w.jsx(je,{children:"Status"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:w.jsx(Te,{color:Y(),children:F()})})]}),["success","processing"].includes(e)&&w.jsxs(En,{children:[w.jsx(je,{children:"Transaction"}),w.jsx(je,{display:"flex",textAlign:"end",justifyContent:"end",children:Z?w.jsx("a",{href:Z,target:"_blank",rel:"noreferrer",children:w.jsxs(Te,{color:"blue.500",children:["View on"," ",x?"LayerZero":"Etherscan"]})}):w.jsx(Te,{children:"-"})})]})]})},"status"),w.jsx(ud,{}),e==="processing"?w.jsx(zq,{currencyIcon:dg(h)}):w.jsx(dd,{}),e==="success"&&w.jsx(nr,{visual:"solid",onClick:$,width:"100%",children:"New Deposit"}),e==="failed"&&w.jsx(nr,{visual:"solid",onClick:B,width:"100%",children:"Retry Deposit"})]})};var zE=(t=>(t.SelectToken="selectToken",t.SelectAmount="selectAmount",t.Quote="quote",t.ConfirmTransfer="confirmTransfer",t))(zE||{});const UE=["selectToken","selectAmount","quote","confirmTransfer"],Hq={exchange:kq,wallet:({initialStep:t="selectToken",setFlow:e})=>{const[n,r]=K.useState(t),{handleClose:i,enforceFlow:o}=K.useContext(ic),s=c=>{r(c)},a=()=>{const c=UE.findIndex(u=>u===n)-1;c>=0?r(UE[c]):e&&e("")},l=(()=>{switch(n){case"selectToken":return w.jsx(VE,{setStep:s});case"selectAmount":return w.jsx(Bq,{setStep:s});case"quote":return w.jsx(Fq,{setStep:s});case"confirmTransfer":return w.jsx(Wq,{setStep:s});default:return w.jsx(VE,{setStep:s})}})();return w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(nx,{children:[!(o&&n==="selectToken")&&w.jsx(gi,{minWidth:"16px",minHeight:"16px",maxWidth:"16px",onClick:a,children:w.jsx(on,{as:U_,color:"gray",width:"16px",height:"16px"})}),w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",alignItems:"center",width:"100%",children:w.jsx(Ao,{children:"Wallet Deposit"})}),i&&w.jsx(gi,{onClick:i,minWidth:"16px",minHeight:"16px",maxWidth:"16px",marginLeft:"auto",children:w.jsx(on,{as:Ss,color:"gray",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:l})]})}},jq=()=>{const{handleClose:t,enableExchange:e,enforceFlow:n}=K.useContext(ic),[r,i]=K.useState(""),[o,s]=K.useState(""),[a,l]=K.useState(null),{total:c,isLoading:u}=i1(),{address:h}=et.useAccount(),{walletIcon:p,walletDisplayName:g}=f1(),{total:b,isLoading:m}=h1(1);K.useEffect(()=>{if(n)if(n==="exchange"){if(!Array.isArray(e)||e.length===0){l("No exchanges configured. Please enable at least one exchange in the widget configuration.");return}i("exchange"),s(fd.ChooseExchange)}else n==="wallet"&&h&&(i("wallet"),s(zE.SelectToken))},[n,e,h]);const x=K.useMemo(()=>u?w.jsx(jr,{display:"inline-block",height:"10px",width:"60px"}):typeof c=="number"?Tr(c):c||"$0.00",[c,u]),I=K.useMemo(()=>h?ug(h):"",[h]),N=K.useMemo(()=>{const $=[];return!m&&b>20&&$.push({id:"smart-balance",title:"Smart Account Balance",limit:Tr(b),delay:"2 min",icons:[],flow:"exchange",firstStep:fd.ChooseBalanceAsset}),Array.isArray(e)&&e.length>0&&$.unshift({id:"exchange",title:"Connect Exchange",limit:"No Limit",delay:"2 min",icons:e.map(B=>hd[ea[B]]).filter(Boolean),flow:"exchange",firstStep:fd.ChooseExchange}),$},[h,e,b,m]),T=r&&Hq[r];return T?w.jsx(T,{setFlow:i,initialStep:o}):a?w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Configuration Error"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsx(tn,{children:w.jsxs(ue,{display:"flex",flexDirection:"column",alignItems:"center",gap:"4",p:"6",textAlign:"center",children:[w.jsx(on,{as:j4,color:"red.500",width:"48px",height:"48px"}),w.jsx(Te,{color:"fg.muted",children:a})]})})})]}):n==="wallet"&&!h?w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Connect Wallet"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsx(tn,{children:w.jsx(Oo,{children:w.jsx(s1,{icon:p,walletHash:"Not Connected",balance:"Connect your wallet to continue",delay:"",status:hg.NONE})})})})]}):w.jsxs(w.Fragment,{children:[w.jsx(or.Header,{children:w.jsxs(Xf,{children:[w.jsx(ue,{display:"flex",flexDirection:"column",gap:"4px",children:w.jsx(Ao,{children:"Deposit"})}),t&&w.jsx(gi,{onClick:t,width:"40px",children:w.jsx(on,{as:Ss,color:"fg.muted",width:"16px",height:"16px"})})]})}),w.jsx(or.Body,{children:w.jsxs(tn,{children:[h&&w.jsx(Oo,{children:w.jsx(s1,{icon:p,walletHash:I,balance:x,delay:"Instant",status:hg.CONNECTED,badge:g,onClick:()=>{i("wallet")}},h)}),N.length>0&&w.jsxs(w.Fragment,{children:[w.jsx(vB,{}),w.jsx(Oo,{children:N.map($=>w.jsx(RD,{title:$.title,limit:$.limit,delay:$.delay,icons:$.icons,onClick:()=>{$.disabled||(i($.flow),s($.firstStep))}},$.id))})]})]})})]})};var oe=typeof window!="undefined"?window:void 0,bn=typeof globalThis!="undefined"?globalThis:oe;typeof self=="undefined"&&(bn.self=bn),typeof File=="undefined"&&(bn.File=function(){});var WE=Array.prototype,HE=WE.forEach,jE=WE.indexOf,ur=bn==null?void 0:bn.navigator,me=bn==null?void 0:bn.document,jn=bn==null?void 0:bn.location,Sp=bn==null?void 0:bn.fetch,Ip=bn!=null&&bn.XMLHttpRequest&&"withCredentials"in new bn.XMLHttpRequest?bn.XMLHttpRequest:void 0,qE=bn==null?void 0:bn.AbortController,qn=ur==null?void 0:ur.userAgent,ke=oe!=null?oe:{},Ci={DEBUG:!1,LIB_VERSION:"1.310.1"};function GE(t,e,n,r,i,o,s){try{var a=t[o](s),l=a.value}catch(c){return void n(c)}a.done?e(l):Promise.resolve(l).then(r,i)}function KE(t){return function(){var e=this,n=arguments;return new Promise((function(r,i){var o=t.apply(e,n);function s(l){GE(o,r,i,s,a,"next",l)}function a(l){GE(o,r,i,s,a,"throw",l)}s(void 0)}))}}function be(){return be=Object.assign?Object.assign.bind():function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)({}).hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t},be.apply(null,arguments)}function YE(t,e){if(t==null)return{};var n={};for(var r in t)if({}.hasOwnProperty.call(t,r)){if(e.indexOf(r)!==-1)continue;n[r]=t[r]}return n}var qq=["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"],XE=function(t,e){if(e===void 0&&(e=[]),!t)return!1;var n=t.toLowerCase();return qq.concat(e).some((r=>{var i=r.toLowerCase();return n.indexOf(i)!==-1}))},Gq=["$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 Ue(t,e){return t.indexOf(e)!==-1}var pd=function(t){return t.trim()},Cp=function(t){return t.replace(/^\$/,"")},Kq=Array.isArray,ZE=Object.prototype,JE=ZE.hasOwnProperty,md=ZE.toString,Ze=Kq||function(t){return md.call(t)==="[object Array]"},ro=t=>typeof t=="function",an=t=>t===Object(t)&&!Ze(t),ta=t=>{if(an(t)){for(var e in t)if(JE.call(t,e))return!1;return!0}return!1},fe=t=>t===void 0,nn=t=>md.call(t)=="[object String]",Ap=t=>nn(t)&&t.trim().length===0,Pr=t=>t===null,Je=t=>fe(t)||Pr(t),ei=t=>md.call(t)=="[object Number]",Ai=t=>md.call(t)==="[object Boolean]",Yq=t=>t instanceof FormData,Xq=t=>Ue(Gq,t);function Op(t){return t===null||typeof t!="object"}function vd(t,e){return Object.prototype.toString.call(t)==="[object "+e+"]"}function QE(t){return!fe(Event)&&(function(e,n){try{return e instanceof n}catch(r){return!1}})(t,Event)}var Zq=[!0,"true",1,"1","yes"],kp=t=>Ue(Zq,t),Jq=[!1,"false",0,"0","no"];function ti(t,e,n,r,i){return e>n&&(r.warn("min cannot be greater than max."),e=n),ei(t)?t>n?(r.warn(" cannot be greater than max: "+n+". Using max value instead."),n):t<e?(r.warn(" cannot be less than min: "+e+". Using min value instead."),e):t:(r.warn(" must be a number. using max or fallback. max: "+n+", fallback: "+i),ti(i||n,e,n,r))}class Qq{constructor(e){this.t={},this.i=e.i,this.o=ti(e.bucketSize,0,100,e.h),this.m=ti(e.refillRate,0,this.o,e.h),this.$=ti(e.refillInterval,0,864e5,e.h)}S(e,n){var r=n-e.lastAccess,i=Math.floor(r/this.$);if(i>0){var o=i*this.m;e.tokens=Math.min(e.tokens+o,this.o),e.lastAccess=e.lastAccess+i*this.$}}consumeRateLimit(e){var n,r=Date.now(),i=String(e),o=this.t[i];return o?this.S(o,r):(o={tokens:this.o,lastAccess:r},this.t[i]=o),o.tokens===0||(o.tokens--,o.tokens===0&&((n=this.i)==null||n.call(this,e)),o.tokens===0)}stop(){this.t={}}}var br="Mobile",yd="iOS",Oi="Android",Rl="Tablet",eS=Oi+" "+Rl,tS="iPad",nS="Apple",rS=nS+" Watch",Nl="Safari",na="BlackBerry",iS="Samsung",oS=iS+"Browser",sS=iS+" Internet",qo="Chrome",eG=qo+" OS",aS=qo+" "+yd,Tp="Internet Explorer",lS=Tp+" "+br,Rp="Opera",tG=Rp+" Mini",Np="Edge",cS="Microsoft "+Np,ra="Firefox",uS=ra+" "+yd,Pl="Nintendo",Ll="PlayStation",ia="Xbox",dS=Oi+" "+br,hS=br+" "+Nl,Ml="Windows",Pp=Ml+" Phone",fS="Nokia",Lp="Ouya",gS="Generic",nG=gS+" "+br.toLowerCase(),pS=gS+" "+Rl.toLowerCase(),Mp="Konqueror",Pn="(\\d+(\\.\\d+)?)",Bp=new RegExp("Version/"+Pn),rG=new RegExp(ia,"i"),iG=new RegExp(Ll+" \\w+","i"),oG=new RegExp(Pl+" \\w+","i"),Fp=new RegExp(na+"|PlayBook|BB10","i"),sG={"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"},bd,mS,Dp,aG=(t,e)=>e&&Ue(e,nS)||(function(n){return Ue(n,Nl)&&!Ue(n,qo)&&!Ue(n,Oi)})(t),vS=function(t,e){return e=e||"",Ue(t," OPR/")&&Ue(t,"Mini")?tG:Ue(t," OPR/")?Rp:Fp.test(t)?na:Ue(t,"IE"+br)||Ue(t,"WPDesktop")?lS:Ue(t,oS)?sS:Ue(t,Np)||Ue(t,"Edg/")?cS:Ue(t,"FBIOS")?"Facebook "+br:Ue(t,"UCWEB")||Ue(t,"UCBrowser")?"UC Browser":Ue(t,"CriOS")?aS:Ue(t,"CrMo")||Ue(t,qo)?qo:Ue(t,Oi)&&Ue(t,Nl)?dS:Ue(t,"FxiOS")?uS:Ue(t.toLowerCase(),Mp.toLowerCase())?Mp:aG(t,e)?Ue(t,br)?hS:Nl:Ue(t,ra)?ra:Ue(t,"MSIE")||Ue(t,"Trident/")?Tp:Ue(t,"Gecko")?ra:""},lG={[lS]:[new RegExp("rv:"+Pn)],[cS]:[new RegExp(Np+"?\\/"+Pn)],[qo]:[new RegExp("("+qo+"|CrMo)\\/"+Pn)],[aS]:[new RegExp("CriOS\\/"+Pn)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+Pn)],[Nl]:[Bp],[hS]:[Bp],[Rp]:[new RegExp("(Opera|OPR)\\/"+Pn)],[ra]:[new RegExp(ra+"\\/"+Pn)],[uS]:[new RegExp("FxiOS\\/"+Pn)],[Mp]:[new RegExp("Konqueror[:/]?"+Pn,"i")],[na]:[new RegExp(na+" "+Pn),Bp],[dS]:[new RegExp("android\\s"+Pn,"i")],[sS]:[new RegExp(oS+"\\/"+Pn)],[Tp]:[new RegExp("(rv:|MSIE )"+Pn)],Mozilla:[new RegExp("rv:"+Pn)]},cG=function(t,e){var n=vS(t,e),r=lG[n];if(fe(r))return null;for(var i=0;i<r.length;i++){var o=r[i],s=t.match(o);if(s)return parseFloat(s[s.length-2])}return null},yS=[[new RegExp(ia+"; "+ia+" (.*?)[);]","i"),t=>[ia,t&&t[1]||""]],[new RegExp(Pl,"i"),[Pl,""]],[new RegExp(Ll,"i"),[Ll,""]],[Fp,[na,""]],[new RegExp(Ml,"i"),(t,e)=>{if(/Phone/.test(e)||/WPDesktop/.test(e))return[Pp,""];if(new RegExp(br).test(e)&&!/IEMobile\b/.test(e))return[Ml+" "+br,""];var n=/Windows NT ([0-9.]+)/i.exec(e);if(n&&n[1]){var r=n[1],i=sG[r]||"";return/arm/i.test(e)&&(i="RT"),[Ml,i]}return[Ml,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,t=>{if(t&&t[3]){var e=[t[3],t[4],t[5]||"0"];return[yd,e.join(".")]}return[yd,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,t=>{var e="";return t&&t.length>=3&&(e=fe(t[2])?t[3]:t[2]),["watchOS",e]}],[new RegExp("("+Oi+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Oi+")","i"),t=>{if(t&&t[2]){var e=[t[2],t[3],t[4]||"0"];return[Oi,e.join(".")]}return[Oi,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,t=>{var e=["Mac OS X",""];if(t&&t[1]){var n=[t[1],t[2],t[3]||"0"];e[1]=n.join(".")}return e}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[eG,""]],[/Linux|debian/i,["Linux",""]]],bS=function(t){return oG.test(t)?Pl:iG.test(t)?Ll:rG.test(t)?ia:new RegExp(Lp,"i").test(t)?Lp:new RegExp("("+Pp+"|WPDesktop)","i").test(t)?Pp:/iPad/.test(t)?tS:/iPod/.test(t)?"iPod Touch":/iPhone/.test(t)?"iPhone":/(watch)(?: ?os[,/]|\d,\d\/)[\d.]+/i.test(t)?rS:Fp.test(t)?na:/(kobo)\s(ereader|touch)/i.test(t)?"Kobo":new RegExp(fS,"i").test(t)?fS:/(kf[a-z]{2}wi|aeo[c-r]{2})( bui|\))/i.test(t)||/(kf[a-z]+)( bui|\)).+silk\//i.test(t)?"Kindle Fire":/(Android|ZTE)/i.test(t)?new RegExp(br).test(t)&&!/(9138B|TB782B|Nexus [97]|pixel c|HUAWEISHT|BTV|noble nook|smart ultra 6)/i.test(t)||/pixel[\daxl ]{1,6}/i.test(t)&&!/pixel c/i.test(t)||/(huaweimed-al00|tah-|APA|SM-G92|i980|zte|U304AA)/i.test(t)||/lmy47v/i.test(t)&&!/QTAQZ3/i.test(t)?Oi:eS:new RegExp("(pda|"+br+")","i").test(t)?nG:new RegExp(Rl,"i").test(t)&&!new RegExp(Rl+" pc","i").test(t)?pS:""},uG=t=>t instanceof Error;function dG(t){var e=globalThis._posthogChunkIds;if(e){var n=Object.keys(e);return Dp&&n.length===mS||(mS=n.length,Dp=n.reduce(((r,i)=>{bd||(bd={});var o=bd[i];if(o)r[o[0]]=o[1];else for(var s=t(i),a=s.length-1;a>=0;a--){var l=s[a],c=l==null?void 0:l.filename,u=e[i];if(c&&u){r[c]=u,bd[i]=[c,u];break}}return r}),{})),Dp}}class hG{constructor(e,n,r){r===void 0&&(r=[]),this.coercers=e,this.stackParser=n,this.modifiers=r}buildFromUnknown(e,n){n===void 0&&(n={});var r=n&&n.mechanism||{handled:!0,type:"generic"},i=this.buildCoercingContext(r,n,0).apply(e),o=this.buildParsingContext(),s=this.parseStacktrace(i,o);return{$exception_list:this.convertToExceptionList(s,r),$exception_level:"error"}}modifyFrames(e){var n=this;return KE((function*(){for(var r of e)r.stacktrace&&r.stacktrace.frames&&Ze(r.stacktrace.frames)&&(r.stacktrace.frames=yield n.applyModifiers(r.stacktrace.frames));return e}))()}coerceFallback(e){var n;return{type:"Error",value:"Unknown error",stack:(n=e.syntheticException)==null?void 0:n.stack,synthetic:!0}}parseStacktrace(e,n){var r,i;return e.cause!=null&&(r=this.parseStacktrace(e.cause,n)),e.stack!=""&&e.stack!=null&&(i=this.applyChunkIds(this.stackParser(e.stack,e.synthetic?1:0),n.chunkIdMap)),be({},e,{cause:r,stack:i})}applyChunkIds(e,n){return e.map((r=>(r.filename&&n&&(r.chunk_id=n[r.filename]),r)))}applyCoercers(e,n){for(var r of this.coercers)if(r.match(e))return r.coerce(e,n);return this.coerceFallback(n)}applyModifiers(e){var n=this;return KE((function*(){var r=e;for(var i of n.modifiers)r=yield i(r);return r}))()}convertToExceptionList(e,n){var r,i,o,s={type:e.type,value:e.value,mechanism:{type:(r=n.type)!==null&&r!==void 0?r:"generic",handled:(i=n.handled)===null||i===void 0||i,synthetic:(o=e.synthetic)!==null&&o!==void 0&&o}};e.stack&&(s.stacktrace={type:"raw",frames:e.stack});var a=[s];return e.cause!=null&&a.push(...this.convertToExceptionList(e.cause,be({},n,{handled:!0}))),a}buildParsingContext(){return{chunkIdMap:dG(this.stackParser)}}buildCoercingContext(e,n,r){r===void 0&&(r=0);var i=(o,s)=>{if(s<=4){var a=this.buildCoercingContext(e,n,s);return this.applyCoercers(o,a)}};return be({},n,{syntheticException:r==0?n.syntheticException:void 0,mechanism:e,apply:o=>i(o,r),next:o=>i(o,r+1)})}}var oa="?";function Vp(t,e,n,r,i){var o={platform:t,filename:e,function:n==="<anonymous>"?oa:n,in_app:!0};return fe(r)||(o.lineno=r),fe(i)||(o.colno=i),o}var _S=(t,e)=>{var n=t.indexOf("safari-extension")!==-1,r=t.indexOf("safari-web-extension")!==-1;return n||r?[t.indexOf("@")!==-1?t.split("@")[0]:oa,n?"safari-extension:"+e:"safari-web-extension:"+e]:[t,e]},fG=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,gG=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,pG=/\((\S*)(?::(\d+))(?::(\d+))\)/,mG=(t,e)=>{var n=fG.exec(t);if(n){var[,r,i,o]=n;return Vp(e,r,oa,+i,+o)}var s=gG.exec(t);if(s){if(s[2]&&s[2].indexOf("eval")===0){var a=pG.exec(s[2]);a&&(s[2]=a[1],s[3]=a[2],s[4]=a[3])}var[l,c]=_S(s[1]||oa,s[2]);return Vp(e,c,l,s[3]?+s[3]:void 0,s[4]?+s[4]:void 0)}},vG=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,yG=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i,bG=(t,e)=>{var n=vG.exec(t);if(n){if(n[3]&&n[3].indexOf(" > eval")>-1){var r=yG.exec(n[3]);r&&(n[1]=n[1]||"eval",n[3]=r[1],n[4]=r[2],n[5]="")}var i=n[3],o=n[1]||oa;return[o,i]=_S(o,i),Vp(e,i,o,n[4]?+n[4]:void 0,n[5]?+n[5]:void 0)}},xS=/\(error: (.*)\)/,wS=50;function _G(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return function(i,o){o===void 0&&(o=0);for(var s=[],a=i.split(`
229
229
  `),l=o;l<a.length;l++){var c=a[l];if(!(c.length>1024)){var u=xS.test(c)?c.replace(xS,"$1"):c;if(!u.match(/\S*Error: /)){for(var h of n){var p=h(u,t);if(p){s.push(p);break}}if(s.length>=wS)break}}}return(function(g){if(!g.length)return[];var b=Array.from(g);return b.reverse(),b.slice(0,wS).map((m=>{return be({},m,{filename:m.filename||(x=b,x[x.length-1]||{}).filename,function:m.function||oa});var x}))})(s)}}class xG{match(e){return this.isDOMException(e)||this.isDOMError(e)}coerce(e,n){var r=nn(e.stack);return{type:this.getType(e),value:this.getValue(e),stack:r?e.stack:void 0,cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return this.isDOMError(e)?"DOMError":"DOMException"}getValue(e){var n=e.name||(this.isDOMError(e)?"DOMError":"DOMException");return e.message?n+": "+e.message:n}isDOMException(e){return vd(e,"DOMException")}isDOMError(e){return vd(e,"DOMError")}}class wG{match(e){return(n=>n instanceof Error)(e)}coerce(e,n){return{type:this.getType(e),value:this.getMessage(e,n),stack:this.getStack(e),cause:e.cause?n.next(e.cause):void 0,synthetic:!1}}getType(e){return e.name||e.constructor.name}getMessage(e,n){var r=e.message;return r.error&&typeof r.error.message=="string"?String(r.error.message):String(r)}getStack(e){return e.stacktrace||e.stack||void 0}}class EG{constructor(){}match(e){return vd(e,"ErrorEvent")&&e.error!=null}coerce(e,n){var r,i=n.apply(e.error);return i||{type:"ErrorEvent",value:e.message,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}var SG=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i;class IG{match(e){return typeof e=="string"}coerce(e,n){var r,[i,o]=this.getInfos(e);return{type:i!=null?i:"Error",value:o!=null?o:e,stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}getInfos(e){var n="Error",r=e,i=e.match(SG);return i&&(n=i[1],r=i[2]),[n,r]}}var CG=["fatal","error","warning","log","info","debug"];function ES(t,e){e===void 0&&(e=40);var n=Object.keys(t);if(n.sort(),!n.length)return"[object has no keys]";for(var r=n.length;r>0;r--){var i=n.slice(0,r).join(", ");if(!(i.length>e))return r===n.length||i.length<=e?i:i.slice(0,e)+"..."}return""}class AG{match(e){return typeof e=="object"&&e!==null}coerce(e,n){var r,i=this.getErrorPropertyFromObject(e);return i?n.apply(i):{type:this.getType(e),value:this.getValue(e),stack:(r=n.syntheticException)==null?void 0:r.stack,level:this.isSeverityLevel(e.level)?e.level:"error",synthetic:!0}}getType(e){return QE(e)?e.constructor.name:"Error"}getValue(e){if("name"in e&&typeof e.name=="string"){var n="'"+e.name+"' captured as exception";return"message"in e&&typeof e.message=="string"&&(n+=" with message: '"+e.message+"'"),n}if("message"in e&&typeof e.message=="string")return e.message;var r=this.getObjectClassName(e);return(r&&r!=="Object"?"'"+r+"'":"Object")+" captured as exception with keys: "+ES(e)}isSeverityLevel(e){return nn(e)&&!Ap(e)&&CG.indexOf(e)>=0}getErrorPropertyFromObject(e){for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var r=e[n];if(uG(r))return r}}getObjectClassName(e){try{var n=Object.getPrototypeOf(e);return n?n.constructor.name:void 0}catch(r){return}}}class OG{match(e){return QE(e)}coerce(e,n){var r,i=e.constructor.name;return{type:i,value:i+" captured as exception with keys: "+ES(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class kG{match(e){return Op(e)}coerce(e,n){var r;return{type:"Error",value:"Primitive value captured as exception: "+String(e),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}}}class TG{match(e){return vd(e,"PromiseRejectionEvent")}coerce(e,n){var r,i=this.getUnhandledRejectionReason(e);return Op(i)?{type:"UnhandledRejection",value:"Non-Error promise rejection captured with value: "+String(i),stack:(r=n.syntheticException)==null?void 0:r.stack,synthetic:!0}:n.apply(i)}getUnhandledRejectionReason(e){if(Op(e))return e;try{if("reason"in e)return e.reason;if("detail"in e&&"reason"in e.detail)return e.detail.reason}catch(n){}return e}}var SS=function(t,e){var{debugEnabled:n}=e===void 0?{}:e,r={k:function(i){if(oe&&(Ci.DEBUG||ke.POSTHOG_DEBUG||n)&&!fe(oe.console)&&oe.console){for(var o=("__rrweb_original__"in oe.console[i])?oe.console[i].__rrweb_original__:oe.console[i],s=arguments.length,a=new Array(s>1?s-1:0),l=1;l<s;l++)a[l-1]=arguments[l];o(t,...a)}},info:function(){for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];r.k("log",...o)},warn:function(){for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];r.k("warn",...o)},error:function(){for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];r.k("error",...o)},critical:function(){for(var i=arguments.length,o=new Array(i),s=0;s<i;s++)o[s]=arguments[s];console.error(t,...o)},uninitializedWarning:i=>{r.error("You must initialize PostHog before calling "+i)},createLogger:(i,o)=>SS(t+" "+i,o)};return r},ye=SS("[PostHog.js]"),At=ye.createLogger,RG=At("[ExternalScriptsLoader]"),IS=(t,e,n)=>{if(t.config.disable_external_dependency_loading)return RG.warn(e+" was requested but loading of external scripts is disabled."),n("Loading of external scripts is disabled");var r=me==null?void 0:me.querySelectorAll("script");if(r){for(var i,o=function(){if(r[s].src===e){var l=r[s];return l.__posthog_loading_callback_fired?{v:n()}:(l.addEventListener("load",(c=>{l.__posthog_loading_callback_fired=!0,n(void 0,c)})),l.onerror=c=>n(c),{v:void 0})}},s=0;s<r.length;s++)if(i=o())return i.v}var a=()=>{if(!me)return n("document not found");var l=me.createElement("script");if(l.type="text/javascript",l.crossOrigin="anonymous",l.src=e,l.onload=h=>{l.__posthog_loading_callback_fired=!0,n(void 0,h)},l.onerror=h=>n(h),t.config.prepare_external_dependency_script&&(l=t.config.prepare_external_dependency_script(l)),!l)return n("prepare_external_dependency_script returned null");var c,u=me.querySelectorAll("body > script");u.length>0?(c=u[0].parentNode)==null||c.insertBefore(l,u[0]):me.body.appendChild(l)};me!=null&&me.body?a():me==null||me.addEventListener("DOMContentLoaded",a)};ke.__PosthogExtensions__=ke.__PosthogExtensions__||{},ke.__PosthogExtensions__.loadExternalDependency=(t,e,n)=>{var r="/static/"+e+".js?v="+t.version;if(e==="remote-config"&&(r="/array/"+t.config.token+"/config.js"),e==="toolbar"){var i=3e5;r=r+"&t="+Math.floor(Date.now()/i)*i}var o=t.requestRouter.endpointFor("assets",r);IS(t,o,n)},ke.__PosthogExtensions__.loadSiteApp=(t,e,n)=>{var r=t.requestRouter.endpointFor("api",e);IS(t,r,n)};var _d={};function io(t,e,n){if(Ze(t)){if(HE&&t.forEach===HE)t.forEach(e,n);else if("length"in t&&t.length===+t.length){for(var r=0,i=t.length;r<i;r++)if(r in t&&e.call(n,t[r],r)===_d)return}}}function ut(t,e,n){if(!Je(t)){if(Ze(t))return io(t,e,n);if(Yq(t)){for(var r of t.entries())if(e.call(n,r[1],r[0])===_d)return}else for(var i in t)if(JE.call(t,i)&&e.call(n,t[i],i)===_d)return}}var Ot=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return io(n,(function(i){for(var o in i)i[o]!==void 0&&(t[o]=i[o])})),t},sa=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),r=1;r<e;r++)n[r-1]=arguments[r];return io(n,(function(i){io(i,(function(o){t.push(o)}))})),t};function xd(t){for(var e=Object.keys(t),n=e.length,r=new Array(n);n--;)r[n]=[e[n],t[e[n]]];return r}var CS=function(t){try{return t()}catch(e){return}},NG=function(t){return function(){try{for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];return t.apply(this,n)}catch(i){ye.critical("Implementation error. Please turn on debug mode and open a ticket on https://app.posthog.com/home#panel=support%3Asupport%3A."),ye.critical(i)}}},$p=function(t){var e={};return ut(t,(function(n,r){(nn(n)&&n.length>0||ei(n))&&(e[r]=n)})),e};function PG(t,e){return n=t,r=o=>nn(o)&&!Pr(e)?o.slice(0,e):o,i=new Set,(function o(s,a){return s!==Object(s)?r?r(s,a):s:i.has(s)?void 0:(i.add(s),Ze(s)?(l=[],io(s,(c=>{l.push(o(c))}))):(l={},ut(s,((c,u)=>{i.has(c)||(l[u]=o(c,u))}))),l);var l})(n);var n,r,i}var LG=["herokuapp.com","vercel.app","netlify.app"];function MG(t){var e=t==null?void 0:t.hostname;if(!nn(e))return!1;var n=e.split(".").slice(-2).join(".");for(var r of LG)if(n===r)return!1;return!0}function AS(t,e){for(var n=0;n<t.length;n++)if(e(t[n]))return t[n]}function Bt(t,e,n,r){var{capture:i=!1,passive:o=!0}=r!=null?r:{};t==null||t.addEventListener(e,n,{capture:i,passive:o})}var OS="$people_distinct_id",Bl="__alias",Fl="__timers",kS="$autocapture_disabled_server_side",zp="$heatmaps_enabled_server_side",TS="$exception_capture_enabled_server_side",Up="$error_tracking_suppression_rules",RS="$error_tracking_capture_extension_exceptions",NS="$web_vitals_enabled_server_side",PS="$dead_clicks_enabled_server_side",LS="$product_tours_enabled_server_side",MS="$web_vitals_allowed_metrics",Wp="$session_recording_remote_config",wd="$sesid",BS="$session_is_sampled",aa="$enabled_feature_flags",Dl="$early_access_features",Hp="$feature_flag_details",Vl="$stored_person_properties",Go="$stored_group_properties",jp="$surveys",Ed="$flag_call_reported",ki="$user_state",qp="$client_session_props",Gp="$capture_rate_limit",Kp="$initial_campaign_params",Yp="$initial_referrer_info",Sd="$initial_person_info",Id="$epp",FS="__POSTHOG_TOOLBAR__",$l="$posthog_cookieless",BG=[OS,Bl,"__cmpns",Fl,"$session_recording_enabled_server_side",zp,wd,aa,Up,ki,Dl,Hp,Go,Vl,jp,Ed,qp,Gp,Kp,Yp,Id,Sd,"$conversations_widget_session_id","$conversations_ticket_id","$conversations_widget_state","$conversations_user_traits"];function DS(t){return t instanceof Element&&(t.id===FS||!(t.closest==null||!t.closest(".toolbar-global-fade-container")))}function Cd(t){return!!t&&t.nodeType===1}function oo(t,e){return!!t&&!!t.tagName&&t.tagName.toLowerCase()===e.toLowerCase()}function VS(t){return!!t&&t.nodeType===3}function $S(t){return!!t&&t.nodeType===11}function Xp(t){return t?pd(t).split(/\s+/):[]}function zS(t){var e=oe==null?void 0:oe.location.href;return!!(e&&t&&t.some((n=>e.match(n))))}function Ad(t){var e="";switch(typeof t.className){case"string":e=t.className;break;case"object":e=(t.className&&"baseVal"in t.className?t.className.baseVal:null)||t.getAttribute("class")||"";break;default:e=""}return Xp(e)}function US(t){return Je(t)?null:pd(t).split(/(\s+)/).filter((e=>Ul(e))).join("").replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)}function zl(t){var e="";return Qp(t)&&!YS(t)&&t.childNodes&&t.childNodes.length&&ut(t.childNodes,(function(n){var r;VS(n)&&n.textContent&&(e+=(r=US(n.textContent))!==null&&r!==void 0?r:"")})),pd(e)}function WS(t){return fe(t.target)?t.srcElement||null:(e=t.target)!=null&&e.shadowRoot?t.composedPath()[0]||null:t.target||null;var e}var Zp=["a","button","form","input","select","textarea","label"];function HS(t,e){if(fe(e))return!0;var n,r=function(o){if(e.some((s=>o.matches(s))))return{v:!0}};for(var i of t)if(n=r(i))return n.v;return!1}function jS(t){var e=t.parentNode;return!(!e||!Cd(e))&&e}var FG=["next","previous","prev",">","<"],qS=10,GS=[".ph-no-rageclick",".ph-no-capture"];function DG(t,e){if(!oe||Jp(t))return!1;var n,r,i;if(Ai(e)?(n=!!e&&GS,r=void 0):(n=(i=e==null?void 0:e.css_selector_ignorelist)!==null&&i!==void 0?i:GS,r=e==null?void 0:e.content_ignorelist),n===!1)return!1;var{targetElementList:o}=KS(t,!1);return!(function(s,a){if(s===!1||fe(s))return!1;var l;if(s===!0)l=FG;else{if(!Ze(s))return!1;if(s.length>qS)return ye.error("[PostHog] content_ignorelist array cannot exceed "+qS+" items. Use css_selector_ignorelist for more complex matching."),!1;l=s.map((c=>c.toLowerCase()))}return a.some((c=>{var{safeText:u,ariaLabel:h}=c;return l.some((p=>u.includes(p)||h.includes(p)))}))})(r,o.map((s=>{var a;return{safeText:zl(s).toLowerCase(),ariaLabel:((a=s.getAttribute("aria-label"))==null?void 0:a.toLowerCase().trim())||""}})))&&!HS(o,n)}var Jp=t=>!t||oo(t,"html")||!Cd(t),KS=(t,e)=>{if(!oe||Jp(t))return{parentIsUsefulElement:!1,targetElementList:[]};for(var n=!1,r=[t],i=t;i.parentNode&&!oo(i,"body");)if($S(i.parentNode))r.push(i.parentNode.host),i=i.parentNode.host;else{var o=jS(i);if(!o)break;if(e||Zp.indexOf(o.tagName.toLowerCase())>-1)n=!0;else{var s=oe.getComputedStyle(o);s&&s.getPropertyValue("cursor")==="pointer"&&(n=!0)}r.push(o),i=o}return{parentIsUsefulElement:n,targetElementList:r}};function VG(t,e,n,r,i){var o,s,a,l;if(n===void 0&&(n=void 0),!oe||Jp(t)||(o=n)!=null&&o.url_allowlist&&!zS(n.url_allowlist)||(s=n)!=null&&s.url_ignorelist&&zS(n.url_ignorelist))return!1;if((a=n)!=null&&a.dom_event_allowlist){var c=n.dom_event_allowlist;if(c&&!c.some((b=>e.type===b)))return!1}var{parentIsUsefulElement:u,targetElementList:h}=KS(t,r);if(!(function(b,m){var x=m==null?void 0:m.element_allowlist;if(fe(x))return!0;var I,N=function($){if(x.some((B=>$.tagName.toLowerCase()===B)))return{v:!0}};for(var T of b)if(I=N(T))return I.v;return!1})(h,n)||!HS(h,(l=n)==null?void 0:l.css_selector_allowlist))return!1;var p=oe.getComputedStyle(t);if(p&&p.getPropertyValue("cursor")==="pointer"&&e.type==="click")return!0;var g=t.tagName.toLowerCase();switch(g){case"html":return!1;case"form":return(i||["submit"]).indexOf(e.type)>=0;case"input":case"select":case"textarea":return(i||["change","click"]).indexOf(e.type)>=0;default:return u?(i||["click"]).indexOf(e.type)>=0:(i||["click"]).indexOf(e.type)>=0&&(Zp.indexOf(g)>-1||t.getAttribute("contenteditable")==="true")}}function Qp(t){for(var e=t;e.parentNode&&!oo(e,"body");e=e.parentNode){var n=Ad(e);if(Ue(n,"ph-sensitive")||Ue(n,"ph-no-capture"))return!1}if(Ue(Ad(t),"ph-include"))return!0;var r=t.type||"";if(nn(r))switch(r.toLowerCase()){case"hidden":case"password":return!1}var i=t.name||t.id||"";return!(nn(i)&&/^cc|cardnum|ccnum|creditcard|csc|cvc|cvv|exp|pass|pwd|routing|seccode|securitycode|securitynum|socialsec|socsec|ssn/i.test(i.replace(/[^a-zA-Z0-9]/g,"")))}function YS(t){return!!(oo(t,"input")&&!["button","checkbox","submit","reset"].includes(t.type)||oo(t,"select")||oo(t,"textarea")||t.getAttribute("contenteditable")==="true")}var XS="(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})",$G=new RegExp("^(?:"+XS+")$"),zG=new RegExp(XS),ZS="\\d{3}-?\\d{2}-?\\d{4}",UG=new RegExp("^("+ZS+")$"),WG=new RegExp("("+ZS+")");function Ul(t,e){return e===void 0&&(e=!0),!(Je(t)||nn(t)&&(t=pd(t),(e?$G:zG).test((t||"").replace(/[- ]/g,""))||(e?UG:WG).test(t)))}function JS(t){var e=zl(t);return Ul(e=(e+" "+QS(t)).trim())?e:""}function QS(t){var e="";return t&&t.childNodes&&t.childNodes.length&&ut(t.childNodes,(function(n){var r;if(n&&((r=n.tagName)==null?void 0:r.toLowerCase())==="span")try{var i=zl(n);e=(e+" "+i).trim(),n.childNodes&&n.childNodes.length&&(e=(e+" "+QS(n)).trim())}catch(o){ye.error("[AutoCapture]",o)}})),e}function HG(t){return(function(e){var n=e.map((r=>{var i,o,s="";if(r.tag_name&&(s+=r.tag_name),r.attr_class)for(var a of(r.attr_class.sort(),r.attr_class))s+="."+a.replace(/"/g,"");var l=be({},r.text?{text:r.text}:{},{"nth-child":(i=r.nth_child)!==null&&i!==void 0?i:0,"nth-of-type":(o=r.nth_of_type)!==null&&o!==void 0?o:0},r.href?{href:r.href}:{},r.attr_id?{attr_id:r.attr_id}:{},r.attributes),c={};return xd(l).sort(((u,h)=>{var[p]=u,[g]=h;return p.localeCompare(g)})).forEach((u=>{var[h,p]=u;return c[eI(h.toString())]=eI(p.toString())})),s+=":",s+=xd(c).map((u=>{var[h,p]=u;return h+'="'+p+'"'})).join("")}));return n.join(";")})((function(e){return e.map((n=>{var r,i,o={text:(r=n.$el_text)==null?void 0:r.slice(0,400),tag_name:n.tag_name,href:(i=n.attr__href)==null?void 0:i.slice(0,2048),attr_class:jG(n),attr_id:n.attr__id,nth_child:n.nth_child,nth_of_type:n.nth_of_type,attributes:{}};return xd(n).filter((s=>{var[a]=s;return a.indexOf("attr__")===0})).forEach((s=>{var[a,l]=s;return o.attributes[a]=l})),o}))})(t))}function eI(t){return t.replace(/"|\\"/g,'\\"')}function jG(t){var e=t.attr__class;return e?Ze(e)?e:Xp(e):void 0}class tI{constructor(e){this.disabled=e===!1;var n=an(e)?e:{};this.thresholdPx=n.threshold_px||30,this.timeoutMs=n.timeout_ms||1e3,this.clickCount=n.click_count||3,this.clicks=[]}isRageClick(e,n,r){if(this.disabled)return!1;var i=this.clicks[this.clicks.length-1];if(i&&Math.abs(e-i.x)+Math.abs(n-i.y)<this.thresholdPx&&r-i.timestamp<this.timeoutMs){if(this.clicks.push({x:e,y:n,timestamp:r}),this.clicks.length===this.clickCount)return!0}else this.clicks=[{x:e,y:n,timestamp:r}];return!1}}var em="$copy_autocapture",Ti=(function(t){return t.GZipJS="gzip-js",t.Base64="base64",t})({}),Od=t=>{var e=me==null?void 0:me.createElement("a");return fe(e)?null:(e.href=t,e)},qG=function(t,e){var n,r;e===void 0&&(e="&");var i=[];return ut(t,(function(o,s){fe(o)||fe(s)||s==="undefined"||(n=encodeURIComponent((a=>a instanceof File)(o)?o.name:o.toString()),r=encodeURIComponent(s),i[i.length]=r+"="+n)})),i.join(e)},kd=function(t,e){for(var n,r=((t.split("#")[0]||"").split(/\?(.*)/)[1]||"").replace(/^\?+/g,"").split("&"),i=0;i<r.length;i++){var o=r[i].split("=");if(o[0]===e){n=o;break}}if(!Ze(n)||n.length<2)return"";var s=n[1];try{s=decodeURIComponent(s)}catch(a){ye.error("Skipping decoding for malformed query param: "+s)}return s.replace(/\+/g," ")},Wl=function(t,e,n){if(!t||!e||!e.length)return t;for(var r=t.split("#"),i=r[0]||"",o=r[1],s=i.split("?"),a=s[1],l=s[0],c=(a||"").split("&"),u=[],h=0;h<c.length;h++){var p=c[h].split("=");Ze(p)&&(e.includes(p[0])?u.push(p[0]+"="+n):u.push(c[h]))}var g=l;return a!=null&&(g+="?"+u.join("&")),o!=null&&(g+="#"+o),g},Td=function(t,e){var n=t.match(new RegExp(e+"=([^&]*)"));return n?n[1]:null},nI=At("[AutoCapture]");function tm(t,e){return e.length>t?e.slice(0,t)+"...":e}function GG(t){if(t.previousElementSibling)return t.previousElementSibling;var e=t;do e=e.previousSibling;while(e&&!Cd(e));return e}function KG(t,e,n,r){var i=t.tagName.toLowerCase(),o={tag_name:i};Zp.indexOf(i)>-1&&!n&&(i.toLowerCase()==="a"||i.toLowerCase()==="button"?o.$el_text=tm(1024,JS(t)):o.$el_text=tm(1024,zl(t)));var s=Ad(t);s.length>0&&(o.classes=s.filter((function(u){return u!==""}))),ut(t.attributes,(function(u){var h;if((!YS(t)||["name","id","class","aria-label"].indexOf(u.name)!==-1)&&(r==null||!r.includes(u.name))&&!e&&Ul(u.value)&&(h=u.name,!nn(h)||h.substring(0,10)!=="_ngcontent"&&h.substring(0,7)!=="_nghost")){var p=u.value;u.name==="class"&&(p=Xp(p).join(" ")),o["attr__"+u.name]=tm(1024,p)}}));for(var a=1,l=1,c=t;c=GG(c);)a++,c.tagName===t.tagName&&l++;return o.nth_child=a,o.nth_of_type=l,o}function YG(t,e){for(var n,r,{e:i,maskAllElementAttributes:o,maskAllText:s,elementAttributeIgnoreList:a,elementsChainAsString:l}=e,c=[t],u=t;u.parentNode&&!oo(u,"body");)$S(u.parentNode)?(c.push(u.parentNode.host),u=u.parentNode.host):(c.push(u.parentNode),u=u.parentNode);var h,p=[],g={},b=!1,m=!1;if(ut(c,($=>{var B=Qp($);$.tagName.toLowerCase()==="a"&&(b=$.getAttribute("href"),b=B&&b&&Ul(b)&&b),Ue(Ad($),"ph-no-capture")&&(m=!0),p.push(KG($,o,s,a));var G=(function(Z){if(!Qp(Z))return{};var Y={};return ut(Z.attributes,(function(F){if(F.name&&F.name.indexOf("data-ph-capture-attribute")===0){var V=F.name.replace("data-ph-capture-attribute-",""),U=F.value;V&&U&&Ul(U)&&(Y[V]=U)}})),Y})($);Ot(g,G)})),m)return{props:{},explicitNoCapture:m};if(s||(t.tagName.toLowerCase()==="a"||t.tagName.toLowerCase()==="button"?p[0].$el_text=JS(t):p[0].$el_text=zl(t)),b){var x,I;p[0].attr__href=b;var N=(x=Od(b))==null?void 0:x.host,T=oe==null||(I=oe.location)==null?void 0:I.host;N&&T&&N!==T&&(h=b)}return{props:Ot({$event_type:i.type,$ce_version:1},l?{}:{$elements:p},{$elements_chain:HG(p)},(n=p[0])!=null&&n.$el_text?{$el_text:(r=p[0])==null?void 0:r.$el_text}:{},h&&i.type==="click"?{$external_click_url:h}:{},g)}}class XG{constructor(e){this.P=!1,this.T=null,this.I=!1,this.instance=e,this.rageclicks=new tI(e.config.rageclick),this.C=null}get R(){var e,n,r=an(this.instance.config.autocapture)?this.instance.config.autocapture:{};return r.url_allowlist=(e=r.url_allowlist)==null?void 0:e.map((i=>new RegExp(i))),r.url_ignorelist=(n=r.url_ignorelist)==null?void 0:n.map((i=>new RegExp(i))),r}F(){if(this.isBrowserSupported()){if(oe&&me){var e=r=>{r=r||(oe==null?void 0:oe.event);try{this.M(r)}catch(i){nI.error("Failed to capture event",i)}};if(Bt(me,"submit",e,{capture:!0}),Bt(me,"change",e,{capture:!0}),Bt(me,"click",e,{capture:!0}),this.R.capture_copied_text){var n=r=>{r=r||(oe==null?void 0:oe.event),this.M(r,em)};Bt(me,"copy",n,{capture:!0}),Bt(me,"cut",n,{capture:!0})}}}else nI.info("Disabling Automatic Event Collection because this browser is not supported")}startIfEnabled(){this.isEnabled&&!this.P&&(this.F(),this.P=!0)}onRemoteConfig(e){e.elementsChainAsString&&(this.I=e.elementsChainAsString),this.instance.persistence&&this.instance.persistence.register({[kS]:!!e.autocapture_opt_out}),this.T=!!e.autocapture_opt_out,this.startIfEnabled()}setElementSelectors(e){this.C=e}getElementSelectors(e){var n,r=[];return(n=this.C)==null||n.forEach((i=>{var o=me==null?void 0:me.querySelectorAll(i);o==null||o.forEach((s=>{e===s&&r.push(i)}))})),r}get isEnabled(){var e,n,r=(e=this.instance.persistence)==null?void 0:e.props[kS],i=this.T;if(Pr(i)&&!Ai(r)&&!this.instance.O())return!1;var o=(n=this.T)!==null&&n!==void 0?n:!!r;return!!this.instance.config.autocapture&&!o}M(e,n){if(n===void 0&&(n="$autocapture"),this.isEnabled){var r,i=WS(e);VS(i)&&(i=i.parentNode||null),n==="$autocapture"&&e.type==="click"&&e instanceof MouseEvent&&this.instance.config.rageclick&&(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,e.timeStamp||new Date().getTime())&&DG(i,this.instance.config.rageclick)&&this.M(e,"$rageclick");var o=n===em;if(i&&VG(i,e,this.R,o,o?["copy","cut"]:void 0)){var{props:s,explicitNoCapture:a}=YG(i,{e,maskAllElementAttributes:this.instance.config.mask_all_element_attributes,maskAllText:this.instance.config.mask_all_text,elementAttributeIgnoreList:this.R.element_attribute_ignorelist,elementsChainAsString:this.I});if(a)return!1;var l=this.getElementSelectors(i);if(l&&l.length>0&&(s.$element_selectors=l),n===em){var c,u=US(oe==null||(c=oe.getSelection())==null?void 0:c.toString()),h=e.type||"clipboard";if(!u)return!1;s.$selected_content=u,s.$copy_type=h}return this.instance.capture(n,s),!0}}}isBrowserSupported(){return ro(me==null?void 0:me.querySelectorAll)}}Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Number.isInteger||(Number.isInteger=function(t){return ei(t)&&isFinite(t)&&Math.floor(t)===t});var rI="0123456789abcdef";class Rd{constructor(e){if(this.bytes=e,e.length!==16)throw new TypeError("not 128-bit length")}static fromFieldsV7(e,n,r,i){if(!Number.isInteger(e)||!Number.isInteger(n)||!Number.isInteger(r)||!Number.isInteger(i)||e<0||n<0||r<0||i<0||e>0xffffffffffff||n>4095||r>1073741823||i>4294967295)throw new RangeError("invalid field value");var o=new Uint8Array(16);return o[0]=e/Math.pow(2,40),o[1]=e/Math.pow(2,32),o[2]=e/Math.pow(2,24),o[3]=e/Math.pow(2,16),o[4]=e/Math.pow(2,8),o[5]=e,o[6]=112|n>>>8,o[7]=n,o[8]=128|r>>>24,o[9]=r>>>16,o[10]=r>>>8,o[11]=r,o[12]=i>>>24,o[13]=i>>>16,o[14]=i>>>8,o[15]=i,new Rd(o)}toString(){for(var e="",n=0;n<this.bytes.length;n++)e=e+rI.charAt(this.bytes[n]>>>4)+rI.charAt(15&this.bytes[n]),n!==3&&n!==5&&n!==7&&n!==9||(e+="-");if(e.length!==36)throw new Error("Invalid UUIDv7 was generated");return e}clone(){return new Rd(this.bytes.slice(0))}equals(e){return this.compareTo(e)===0}compareTo(e){for(var n=0;n<16;n++){var r=this.bytes[n]-e.bytes[n];if(r!==0)return Math.sign(r)}return 0}}class ZG{constructor(){this.A=0,this.D=0,this.j=new JG}generate(){var e=this.generateOrAbort();if(fe(e)){this.A=0;var n=this.generateOrAbort();if(fe(n))throw new Error("Could not generate UUID after timestamp reset");return n}return e}generateOrAbort(){var e=Date.now();if(e>this.A)this.A=e,this.L();else{if(!(e+1e4>this.A))return;this.D++,this.D>4398046511103&&(this.A++,this.L())}return Rd.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 iI,oI=t=>{if(typeof UUIDV7_DENY_WEAK_RNG!="undefined"&&UUIDV7_DENY_WEAK_RNG)throw new Error("no cryptographically strong RNG available");for(var e=0;e<t.length;e++)t[e]=65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random());return t};oe&&!fe(oe.crypto)&&crypto.getRandomValues&&(oI=t=>crypto.getRandomValues(t));class JG{constructor(){this.N=new Uint32Array(8),this.U=1/0}nextUint32(){return this.U>=this.N.length&&(oI(this.N),this.U=0),this.N[this.U++]}}var so=()=>QG().toString(),QG=()=>(iI||(iI=new ZG)).generate(),Hl="",eK=/[a-z0-9][a-z0-9-]+\.[a-z]{2,}$/i;function tK(t,e){if(e){var n=(function(i,o){if(o===void 0&&(o=me),Hl)return Hl;if(!o||["localhost","127.0.0.1"].includes(i))return"";for(var s=i.split("."),a=Math.min(s.length,8),l="dmn_chk_"+so();!Hl&&a--;){var c=s.slice(a).join("."),u=l+"=1;domain=."+c+";path=/";o.cookie=u+";max-age=3",o.cookie.includes(l)&&(o.cookie=u+";max-age=0",Hl=c)}return Hl})(t);if(!n){var r=(i=>{var o=i.match(eK);return o?o[0]:""})(t);r!==n&&ye.info("Warning: cookie subdomain discovery mismatch",r,n),n=r}return n?"; domain=."+n:""}return""}var ni={H:()=>!!me,B:function(t){ye.error("cookieStore error: "+t)},q:function(t){if(me){try{for(var e=t+"=",n=me.cookie.split(";").filter((o=>o.length)),r=0;r<n.length;r++){for(var i=n[r];i.charAt(0)==" ";)i=i.substring(1,i.length);if(i.indexOf(e)===0)return decodeURIComponent(i.substring(e.length,i.length))}}catch(o){}return null}},W:function(t){var e;try{e=JSON.parse(ni.q(t))||{}}catch(n){}return e},G:function(t,e,n,r,i){if(me)try{var o="",s="",a=tK(me.location.hostname,r);if(n){var l=new Date;l.setTime(l.getTime()+24*n*60*60*1e3),o="; expires="+l.toUTCString()}i&&(s="; secure");var c=t+"="+encodeURIComponent(JSON.stringify(e))+o+"; SameSite=Lax; path=/"+a+s;return c.length>3686.4&&ye.warn("cookieStore warning: large cookie, len="+c.length),me.cookie=c,c}catch(u){return}},V:function(t,e){if(me!=null&&me.cookie)try{ni.G(t,"",-1,e)}catch(n){return}}},nm=null,bt={H:function(){if(!Pr(nm))return nm;var t=!0;if(fe(oe))t=!1;else try{var e="__mplssupport__";bt.G(e,"xyz"),bt.q(e)!=='"xyz"'&&(t=!1),bt.V(e)}catch(n){t=!1}return t||ye.error("localStorage unsupported; falling back to cookie store"),nm=t,t},B:function(t){ye.error("localStorage error: "+t)},q:function(t){try{return oe==null?void 0:oe.localStorage.getItem(t)}catch(e){bt.B(e)}return null},W:function(t){try{return JSON.parse(bt.q(t))||{}}catch(e){}return null},G:function(t,e){try{oe==null||oe.localStorage.setItem(t,JSON.stringify(e))}catch(n){bt.B(n)}},V:function(t){try{oe==null||oe.localStorage.removeItem(t)}catch(e){bt.B(e)}}},nK=["distinct_id",wd,BS,Id,Sd],Nd=be({},bt,{W:function(t){try{var e={};try{e=ni.W(t)||{}}catch(r){}var n=Ot(e,JSON.parse(bt.q(t)||"{}"));return bt.G(t,n),n}catch(r){}return null},G:function(t,e,n,r,i,o){try{bt.G(t,e,void 0,void 0,o);var s={};nK.forEach((a=>{e[a]&&(s[a]=e[a])})),Object.keys(s).length&&ni.G(t,s,n,r,i,o)}catch(a){bt.B(a)}},V:function(t,e){try{oe==null||oe.localStorage.removeItem(t),ni.V(t,e)}catch(n){bt.B(n)}}}),Pd={},rK={H:function(){return!0},B:function(t){ye.error("memoryStorage error: "+t)},q:function(t){return Pd[t]||null},W:function(t){return Pd[t]||null},G:function(t,e){Pd[t]=e},V:function(t){delete Pd[t]}},Ko=null,_n={H:function(){if(!Pr(Ko))return Ko;if(Ko=!0,fe(oe))Ko=!1;else try{var t="__support__";_n.G(t,"xyz"),_n.q(t)!=='"xyz"'&&(Ko=!1),_n.V(t)}catch(e){Ko=!1}return Ko},B:function(t){ye.error("sessionStorage error: ",t)},q:function(t){try{return oe==null?void 0:oe.sessionStorage.getItem(t)}catch(e){_n.B(e)}return null},W:function(t){try{return JSON.parse(_n.q(t))||null}catch(e){}return null},G:function(t,e){try{oe==null||oe.sessionStorage.setItem(t,JSON.stringify(e))}catch(n){_n.B(n)}},V:function(t){try{oe==null||oe.sessionStorage.removeItem(t)}catch(e){_n.B(e)}}},Ri=(function(t){return t[t.PENDING=-1]="PENDING",t[t.DENIED=0]="DENIED",t[t.GRANTED=1]="GRANTED",t})({});class iK{constructor(e){this._instance=e}get R(){return this._instance.config}get consent(){return this.J()?Ri.DENIED:this.K}isOptedOut(){return this.R.cookieless_mode==="always"||this.consent===Ri.DENIED||this.consent===Ri.PENDING&&(this.R.opt_out_capturing_by_default||this.R.cookieless_mode==="on_reject")}isOptedIn(){return!this.isOptedOut()}isExplicitlyOptedOut(){return this.consent===Ri.DENIED}optInOut(e){this.Y.G(this.X,e?1:0,this.R.cookie_expiration,this.R.cross_subdomain_cookie,this.R.secure_cookie)}reset(){this.Y.V(this.X,this.R.cross_subdomain_cookie)}get X(){var{token:e,opt_out_capturing_cookie_prefix:n,consent_persistence_name:r}=this._instance.config;return r||(n?n+e:"__ph_opt_in_out_"+e)}get K(){var e=this.Y.q(this.X);return kp(e)?Ri.GRANTED:Ue(Jq,e)?Ri.DENIED:Ri.PENDING}get Y(){if(!this.Z){var e=this.R.opt_out_capturing_persistence_type;this.Z=e==="localStorage"?bt:ni;var n=e==="localStorage"?ni:bt;n.q(this.X)&&(this.Z.q(this.X)||this.optInOut(kp(n.q(this.X))),n.V(this.X,this.R.cross_subdomain_cookie))}return this.Z}J(){return!!this.R.respect_dnt&&!!AS([ur==null?void 0:ur.doNotTrack,ur==null?void 0:ur.msDoNotTrack,ke.doNotTrack],(e=>kp(e)))}}var Ld=At("[Dead Clicks]"),oK=()=>!0,sK=t=>{var e,n=!((e=t.instance.persistence)==null||!e.get_property(PS)),r=t.instance.config.capture_dead_clicks;return Ai(r)?r:!!an(r)||n};class sI{get lazyLoadedDeadClicksAutocapture(){return this.tt}constructor(e,n,r){this.instance=e,this.isEnabled=n,this.onCapture=r,this.startIfEnabled()}onRemoteConfig(e){this.instance.persistence&&this.instance.persistence.register({[PS]:e==null?void 0:e.captureDeadClicks}),this.startIfEnabled()}startIfEnabled(){this.isEnabled(this)&&this.it((()=>{this.et()}))}it(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.initDeadClicksAutocapture&&e(),(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this.instance,"dead-clicks-autocapture",(i=>{i?Ld.error("failed to load script",i):e()}))}et(){var e;if(me){if(!this.tt&&(e=ke.__PosthogExtensions__)!=null&&e.initDeadClicksAutocapture){var n=an(this.instance.config.capture_dead_clicks)?this.instance.config.capture_dead_clicks:{};n.__onCapture=this.onCapture,this.tt=ke.__PosthogExtensions__.initDeadClicksAutocapture(this.instance,n),this.tt.start(me),Ld.info("starting...")}}else Ld.error("`document` not found. Cannot start.")}stop(){this.tt&&(this.tt.stop(),this.tt=void 0,Ld.info("stopping..."))}}var jl=At("[ExceptionAutocapture]");class aK{constructor(e){var n,r,i;this.rt=()=>{var o;if(oe&&this.isEnabled&&(o=ke.__PosthogExtensions__)!=null&&o.errorWrappingFunctions){var s=ke.__PosthogExtensions__.errorWrappingFunctions.wrapOnError,a=ke.__PosthogExtensions__.errorWrappingFunctions.wrapUnhandledRejection,l=ke.__PosthogExtensions__.errorWrappingFunctions.wrapConsoleError;try{!this.st&&this.R.capture_unhandled_errors&&(this.st=s(this.captureException.bind(this))),!this.nt&&this.R.capture_unhandled_rejections&&(this.nt=a(this.captureException.bind(this))),!this.ot&&this.R.capture_console_errors&&(this.ot=l(this.captureException.bind(this)))}catch(c){jl.error("failed to start",c),this.ut()}}},this._instance=e,this.ht=!((n=this._instance.persistence)==null||!n.props[TS]),this.dt=new Qq({refillRate:(r=this._instance.config.error_tracking.__exceptionRateLimiterRefillRate)!==null&&r!==void 0?r:1,bucketSize:(i=this._instance.config.error_tracking.__exceptionRateLimiterBucketSize)!==null&&i!==void 0?i:10,refillInterval:1e4,h:jl}),this.R=this.vt(),this.startIfEnabledOrStop()}vt(){var e=this._instance.config.capture_exceptions,n={capture_unhandled_errors:!1,capture_unhandled_rejections:!1,capture_console_errors:!1};return an(e)?n=be({},n,e):(fe(e)?this.ht:e)&&(n=be({},n,{capture_unhandled_errors:!0,capture_unhandled_rejections:!0})),n}get isEnabled(){return this.R.capture_console_errors||this.R.capture_unhandled_errors||this.R.capture_unhandled_rejections}startIfEnabledOrStop(){this.isEnabled?(jl.info("enabled"),this.ut(),this.it(this.rt)):this.ut()}it(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.errorWrappingFunctions&&e(),(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"exception-autocapture",(i=>{if(i)return jl.error("failed to load script",i);e()}))}ut(){var e,n,r;(e=this.st)==null||e.call(this),this.st=void 0,(n=this.nt)==null||n.call(this),this.nt=void 0,(r=this.ot)==null||r.call(this),this.ot=void 0}onRemoteConfig(e){var n=e.autocaptureExceptions;this.ht=!!n||!1,this._instance.persistence&&this._instance.persistence.register({[TS]:this.ht}),this.R=this.vt(),this.startIfEnabledOrStop()}onConfigChange(){this.R=this.vt()}captureException(e){var n,r,i=(n=e==null||(r=e.$exception_list)==null||(r=r[0])==null?void 0:r.type)!==null&&n!==void 0?n:"Exception";this.dt.consumeRateLimit(i)?jl.info("Skipping exception capture because of client rate limiting.",{exception:i}):this._instance.exceptions.sendExceptionEvent(e)}}function aI(t,e,n){try{if(!(e in t))return()=>{};var r=t[e],i=n(r);return ro(i)&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__posthog_wrapped__:{enumerable:!1,value:!0}})),t[e]=i,()=>{t[e]=r}}catch(o){return()=>{}}}class lK{constructor(e){var n;this._instance=e,this.ct=(oe==null||(n=oe.location)==null?void 0:n.pathname)||""}get isEnabled(){return this._instance.config.capture_pageview==="history_change"}startIfEnabled(){this.isEnabled&&(ye.info("History API monitoring enabled, starting..."),this.monitorHistoryChanges())}stop(){this.ft&&this.ft(),this.ft=void 0,ye.info("History API monitoring stopped")}monitorHistoryChanges(){var e,n;if(oe&&oe.history){var r=this;(e=oe.history.pushState)!=null&&e.__posthog_wrapped__||aI(oe.history,"pushState",(i=>function(o,s,a){i.call(this,o,s,a),r._t("pushState")})),(n=oe.history.replaceState)!=null&&n.__posthog_wrapped__||aI(oe.history,"replaceState",(i=>function(o,s,a){i.call(this,o,s,a),r._t("replaceState")})),this.bt()}}_t(e){try{var n,r=oe==null||(n=oe.location)==null?void 0:n.pathname;if(!r)return;r!==this.ct&&this.isEnabled&&this._instance.capture("$pageview",{navigation_type:e}),this.ct=r}catch(i){ye.error("Error capturing "+e+" pageview",i)}}bt(){if(!this.ft){var e=()=>{this._t("popstate")};Bt(oe,"popstate",e),this.ft=()=>{oe&&oe.removeEventListener("popstate",e)}}}}var rm=At("[SegmentIntegration]");function cK(t,e){var n=t.config.segment;if(!n)return e();(function(r,i){var o=r.config.segment;if(!o)return i();var s=l=>{var c=()=>l.anonymousId()||so();r.config.get_device_id=c,l.id()&&(r.register({distinct_id:l.id(),$device_id:c()}),r.persistence.set_property(ki,"identified")),i()},a=o.user();"then"in a&&ro(a.then)?a.then((l=>s(l))):s(a)})(t,(()=>{n.register((r=>{Promise&&Promise.resolve||rm.warn("This browser does not have Promise support, and can not use the segment integration");var i=(o,s)=>{if(!s)return o;o.event.userId||o.event.anonymousId===r.get_distinct_id()||(rm.info("No userId set, resetting PostHog"),r.reset()),o.event.userId&&o.event.userId!==r.get_distinct_id()&&(rm.info("UserId set, identifying with PostHog"),r.identify(o.event.userId));var a=r.calculateEventProperties(s,o.event.properties);return o.event.properties=Object.assign({},a,o.event.properties),o};return{name:"PostHog JS",type:"enrichment",version:"1.0.0",isLoaded:()=>!0,load:()=>Promise.resolve(),track:o=>i(o,o.event.event),page:o=>i(o,"$pageview"),identify:o=>i(o,"$identify"),screen:o=>i(o,"$screen")}})(t)).then((()=>{e()}))}))}var lI="posthog-js";function cI(t,e){var{organization:n,projectId:r,prefix:i,severityAllowList:o=["error"],sendExceptionsToPostHog:s=!0}=e===void 0?{}:e;return a=>{var l,c,u,h,p;if(!(o==="*"||o.includes(a.level))||!t.__loaded)return a;a.tags||(a.tags={});var g=t.requestRouter.endpointFor("ui","/project/"+t.config.token+"/person/"+t.get_distinct_id());a.tags["PostHog Person URL"]=g,t.sessionRecordingStarted()&&(a.tags["PostHog Recording URL"]=t.get_session_replay_url({withTimestamp:!0}));var b=((l=a.exception)==null?void 0:l.values)||[],m=b.map((I=>be({},I,{stacktrace:I.stacktrace?be({},I.stacktrace,{type:"raw",frames:(I.stacktrace.frames||[]).map((N=>be({},N,{platform:"web:javascript"})))}):void 0}))),x={$exception_message:((c=b[0])==null?void 0:c.value)||a.message,$exception_type:(u=b[0])==null?void 0:u.type,$exception_level:a.level,$exception_list:m,$sentry_event_id:a.event_id,$sentry_exception:a.exception,$sentry_exception_message:((h=b[0])==null?void 0:h.value)||a.message,$sentry_exception_type:(p=b[0])==null?void 0:p.type,$sentry_tags:a.tags};return n&&r&&(x.$sentry_url=(i||"https://sentry.io/organizations/")+n+"/issues/?project="+r+"&query="+a.event_id),s&&t.exceptions.sendExceptionEvent(x),a}}class uK{constructor(e,n,r,i,o,s){this.name=lI,this.setupOnce=function(a){a(cI(e,{organization:n,projectId:r,prefix:i,severityAllowList:o,sendExceptionsToPostHog:s==null||s}))}}}var dK=oe!=null&&oe.location?Td(oe.location.hash,"__posthog")||Td(location.hash,"state"):null,uI="_postHogToolbarParams",dI=At("[Toolbar]"),ao=(function(t){return t[t.UNINITIALIZED=0]="UNINITIALIZED",t[t.LOADING=1]="LOADING",t[t.LOADED=2]="LOADED",t})(ao||{});class hK{constructor(e){this.instance=e}yt(e){ke.ph_toolbar_state=e}wt(){var e;return(e=ke.ph_toolbar_state)!==null&&e!==void 0?e:ao.UNINITIALIZED}maybeLoadToolbar(e,n,r){if(e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),!oe||!me)return!1;e=e!=null?e:oe.location,r=r!=null?r:oe.history;try{if(!n){try{oe.localStorage.setItem("test","test"),oe.localStorage.removeItem("test")}catch(a){return!1}n=oe==null?void 0:oe.localStorage}var i,o=dK||Td(e.hash,"__posthog")||Td(e.hash,"state"),s=o?CS((()=>JSON.parse(atob(decodeURIComponent(o)))))||CS((()=>JSON.parse(decodeURIComponent(o)))):null;return s&&s.action==="ph_authorize"?((i=s).source="url",i&&Object.keys(i).length>0&&(s.desiredHash?e.hash=s.desiredHash:r?r.replaceState(r.state,"",e.pathname+e.search):e.hash="")):((i=JSON.parse(n.getItem(uI)||"{}")).source="localstorage",delete i.userIntent),!(!i.token||this.instance.config.token!==i.token)&&(this.loadToolbar(i),!0)}catch(a){return!1}}xt(e){var n=ke.ph_load_toolbar||ke.ph_load_editor;!Je(n)&&ro(n)?n(e,this.instance):dI.warn("No toolbar load function found")}loadToolbar(e){var n=!(me==null||!me.getElementById(FS));if(!oe||n)return!1;var r=this.instance.requestRouter.region==="custom"&&this.instance.config.advanced_disable_toolbar_metrics,i=be({token:this.instance.config.token},e,{apiURL:this.instance.requestRouter.endpointFor("ui")},r?{instrument:!1}:{});if(oe.localStorage.setItem(uI,JSON.stringify(be({},i,{source:void 0}))),this.wt()===ao.LOADED)this.xt(i);else if(this.wt()===ao.UNINITIALIZED){var o;this.yt(ao.LOADING),(o=ke.__PosthogExtensions__)==null||o.loadExternalDependency==null||o.loadExternalDependency(this.instance,"toolbar",(s=>{if(s)return dI.error("[Toolbar] Failed to load",s),void this.yt(ao.UNINITIALIZED);this.yt(ao.LOADED),this.xt(i)})),Bt(oe,"turbolinks:load",(()=>{this.yt(ao.UNINITIALIZED),this.loadToolbar(i)}))}return!0}Et(e){return this.loadToolbar(e)}maybeLoadEditor(e,n,r){return e===void 0&&(e=void 0),n===void 0&&(n=void 0),r===void 0&&(r=void 0),this.maybeLoadToolbar(e,n,r)}}var fK=At("[TracingHeaders]");class gK{constructor(e){this.$t=void 0,this.St=void 0,this.rt=()=>{var n,r;fe(this.$t)&&((n=ke.__PosthogExtensions__)==null||(n=n.tracingHeadersPatchFns)==null||n._patchXHR(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager)),fe(this.St)&&((r=ke.__PosthogExtensions__)==null||(r=r.tracingHeadersPatchFns)==null||r._patchFetch(this._instance.config.__add_tracing_headers||[],this._instance.get_distinct_id(),this._instance.sessionManager))},this._instance=e}it(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.tracingHeadersPatchFns&&e(),(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"tracing-headers",(i=>{if(i)return fK.error("failed to load script",i);e()}))}startIfEnabledOrStop(){var e,n;this._instance.config.__add_tracing_headers?this.it(this.rt):((e=this.$t)==null||e.call(this),(n=this.St)==null||n.call(this),this.$t=void 0,this.St=void 0)}}var Md="https?://(.*)",la=["gclid","gclsrc","dclid","gbraid","wbraid","fbclid","msclkid","twclid","li_fat_id","igshid","ttclid","rdt_cid","epik","qclid","sccid","irclid","_kx"],pK=sa(["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gad_source","mc_cid"],la),ql="<masked>",mK=["li_fat_id"];function hI(t,e,n){if(!me)return{};var r,i=e?sa([],la,n||[]):[],o=fI(Wl(me.URL,i,ql),t),s=(r={},ut(mK,(function(a){var l=ni.q(a);r[a]=l||null})),r);return Ot(s,o)}function fI(t,e){var n=pK.concat(e||[]),r={};return ut(n,(function(i){var o=kd(t,i);r[i]=o||null})),r}function gI(t){var e=(function(o){return o?o.search(Md+"google.([^/?]*)")===0?"google":o.search(Md+"bing.com")===0?"bing":o.search(Md+"yahoo.com")===0?"yahoo":o.search(Md+"duckduckgo.com")===0?"duckduckgo":null:null})(t),n=e!="yahoo"?"q":"p",r={};if(!Pr(e)){r.$search_engine=e;var i=me?kd(me.referrer,n):"";i.length&&(r.ph_keyword=i)}return r}function pI(){return navigator.language||navigator.userLanguage}function mI(){return(me==null?void 0:me.referrer)||"$direct"}function vI(t,e){var n=t?sa([],la,e||[]):[],r=jn==null?void 0:jn.href.substring(0,1e3);return{r:mI().substring(0,1e3),u:r?Wl(r,n,ql):void 0}}function yI(t){var e,{r:n,u:r}=t,i={$referrer:n,$referring_domain:n==null?void 0:n=="$direct"?"$direct":(e=Od(n))==null?void 0:e.host};if(r){i.$current_url=r;var o=Od(r);i.$host=o==null?void 0:o.host,i.$pathname=o==null?void 0:o.pathname;var s=fI(r);Ot(i,s)}if(n){var a=gI(n);Ot(i,a)}return i}function bI(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch(t){return}}function vK(){try{return new Date().getTimezoneOffset()}catch(t){return}}function yK(t,e){if(!qn)return{};var n,r,i,o=t?sa([],la,e||[]):[],[s,a]=(function(l){for(var c=0;c<yS.length;c++){var[u,h]=yS[c],p=u.exec(l),g=p&&(ro(h)?h(p,l):h);if(g)return g}return["",""]})(qn);return Ot($p({$os:s,$os_version:a,$browser:vS(qn,navigator.vendor),$device:bS(qn),$device_type:(r=qn,i=bS(r),i===tS||i===eS||i==="Kobo"||i==="Kindle Fire"||i===pS?Rl:i===Pl||i===ia||i===Ll||i===Lp?"Console":i===rS?"Wearable":i?br:"Desktop"),$timezone:bI(),$timezone_offset:vK()}),{$current_url:Wl(jn==null?void 0:jn.href,o,ql),$host:jn==null?void 0:jn.host,$pathname:jn==null?void 0:jn.pathname,$raw_user_agent:qn.length>1e3?qn.substring(0,997)+"...":qn,$browser_version:cG(qn,navigator.vendor),$browser_language:pI(),$browser_language_prefix:(n=pI(),typeof n=="string"?n.split("-")[0]:void 0),$screen_height:oe==null?void 0:oe.screen.height,$screen_width:oe==null?void 0:oe.screen.width,$viewport_height:oe==null?void 0:oe.innerHeight,$viewport_width:oe==null?void 0:oe.innerWidth,$lib:"web",$lib_version:Ci.LIB_VERSION,$insert_id:Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10),$time:Date.now()/1e3})}var lo=At("[Web Vitals]"),_I=9e5;class bK{constructor(e){var n;this.kt=!1,this.P=!1,this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0},this.Pt=()=>{clearTimeout(this.Tt),this.N.metrics.length!==0&&(this._instance.capture("$web_vitals",this.N.metrics.reduce(((r,i)=>be({},r,{["$web_vitals_"+i.name+"_event"]:be({},i),["$web_vitals_"+i.name+"_value"]:i.value})),{})),this.N={url:void 0,metrics:[],firstMetricTimestamp:void 0})},this.It=r=>{var i,o=(i=this._instance.sessionManager)==null?void 0:i.checkAndGetSessionAndWindowId(!0);if(fe(o))lo.error("Could not read session ID. Dropping metrics!");else{this.N=this.N||{url:void 0,metrics:[],firstMetricTimestamp:void 0};var s=this.Ct();fe(s)||(Je(r==null?void 0:r.name)||Je(r==null?void 0:r.value)?lo.error("Invalid metric received",r):this.Rt&&r.value>=this.Rt?lo.error("Ignoring metric with value >= "+this.Rt,r):(this.N.url!==s&&(this.Pt(),this.Tt=setTimeout(this.Pt,this.flushToCaptureTimeoutMs)),fe(this.N.url)&&(this.N.url=s),this.N.firstMetricTimestamp=fe(this.N.firstMetricTimestamp)?Date.now():this.N.firstMetricTimestamp,r.attribution&&r.attribution.interactionTargetElement&&(r.attribution.interactionTargetElement=void 0),this.N.metrics.push(be({},r,{$current_url:s,$session_id:o.sessionId,$window_id:o.windowId,timestamp:Date.now()})),this.N.metrics.length===this.allowedMetrics.length&&this.Pt()))}},this.rt=()=>{var r,i,o,s,a=ke.__PosthogExtensions__;fe(a)||fe(a.postHogWebVitalsCallbacks)||({onLCP:r,onCLS:i,onFCP:o,onINP:s}=a.postHogWebVitalsCallbacks),r&&i&&o&&s?(this.allowedMetrics.indexOf("LCP")>-1&&r(this.It.bind(this)),this.allowedMetrics.indexOf("CLS")>-1&&i(this.It.bind(this)),this.allowedMetrics.indexOf("FCP")>-1&&o(this.It.bind(this)),this.allowedMetrics.indexOf("INP")>-1&&s(this.It.bind(this)),this.P=!0):lo.error("web vitals callbacks not loaded - not starting")},this._instance=e,this.kt=!((n=this._instance.persistence)==null||!n.props[NS]),this.startIfEnabled()}get allowedMetrics(){var e,n,r=an(this._instance.config.capture_performance)?(e=this._instance.config.capture_performance)==null?void 0:e.web_vitals_allowed_metrics:void 0;return fe(r)?((n=this._instance.persistence)==null?void 0:n.props[MS])||["CLS","FCP","INP","LCP"]:r}get flushToCaptureTimeoutMs(){return(an(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals_delayed_flush_ms:void 0)||5e3}get Rt(){var e=an(this._instance.config.capture_performance)&&ei(this._instance.config.capture_performance.__web_vitals_max_value)?this._instance.config.capture_performance.__web_vitals_max_value:_I;return 0<e&&e<=6e4?_I:e}get isEnabled(){var e=jn==null?void 0:jn.protocol;if(e!=="http:"&&e!=="https:")return lo.info("Web Vitals are disabled on non-http/https protocols"),!1;var n=an(this._instance.config.capture_performance)?this._instance.config.capture_performance.web_vitals:Ai(this._instance.config.capture_performance)?this._instance.config.capture_performance:void 0;return Ai(n)?n:this.kt}startIfEnabled(){this.isEnabled&&!this.P&&(lo.info("enabled, starting..."),this.it(this.rt))}onRemoteConfig(e){var n=an(e.capturePerformance)&&!!e.capturePerformance.web_vitals,r=an(e.capturePerformance)?e.capturePerformance.web_vitals_allowed_metrics:void 0;this._instance.persistence&&(this._instance.persistence.register({[NS]:n}),this._instance.persistence.register({[MS]:r})),this.kt=n,this.startIfEnabled()}it(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.postHogWebVitalsCallbacks&&e(),(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"web-vitals",(i=>{i?lo.error("failed to load script",i):e()}))}Ct(){var e=oe?oe.location.href:void 0;if(e){var n=this._instance.config.mask_personal_data_properties,r=this._instance.config.custom_personal_data_properties,i=n?sa([],la,r||[]):[];return Wl(e,i,ql)}lo.error("Could not determine current URL")}}var _K=At("[Heatmaps]");function xI(t){return an(t)&&"clientX"in t&&"clientY"in t&&ei(t.clientX)&&ei(t.clientY)}class xK{constructor(e){var n;this.kt=!1,this.P=!1,this.Ft=null,this.instance=e,this.kt=!((n=this.instance.persistence)==null||!n.props[zp]),this.rageclicks=new tI(e.config.rageclick)}get flushIntervalMilliseconds(){var e=5e3;return an(this.instance.config.capture_heatmaps)&&this.instance.config.capture_heatmaps.flush_interval_milliseconds&&(e=this.instance.config.capture_heatmaps.flush_interval_milliseconds),e}get isEnabled(){return fe(this.instance.config.capture_heatmaps)?fe(this.instance.config.enable_heatmaps)?this.kt:this.instance.config.enable_heatmaps:this.instance.config.capture_heatmaps!==!1}startIfEnabled(){if(this.isEnabled){if(this.P)return;_K.info("starting..."),this.Mt(),this.Ot()}else{var e;clearInterval((e=this.Ft)!==null&&e!==void 0?e:void 0),this.At(),this.getAndClearBuffer()}}onRemoteConfig(e){var n=!!e.heatmaps;this.instance.persistence&&this.instance.persistence.register({[zp]:n}),this.kt=n,this.startIfEnabled()}getAndClearBuffer(){var e=this.N;return this.N=void 0,e}Dt(e){this.jt(e.originalEvent,"deadclick")}Ot(){this.Ft&&clearInterval(this.Ft),this.Ft=(function(e){return(e==null?void 0:e.visibilityState)==="visible"})(me)?setInterval(this.Lt.bind(this),this.flushIntervalMilliseconds):null}Mt(){oe&&me&&(this.Nt=this.Lt.bind(this),Bt(oe,"beforeunload",this.Nt),this.Ut=e=>this.jt(e||(oe==null?void 0:oe.event)),Bt(me,"click",this.Ut,{capture:!0}),this.zt=e=>this.Ht(e||(oe==null?void 0:oe.event)),Bt(me,"mousemove",this.zt,{capture:!0}),this.Bt=new sI(this.instance,oK,this.Dt.bind(this)),this.Bt.startIfEnabled(),this.qt=this.Ot.bind(this),Bt(me,"visibilitychange",this.qt),this.P=!0)}At(){var e;oe&&me&&(this.Nt&&oe.removeEventListener("beforeunload",this.Nt),this.Ut&&me.removeEventListener("click",this.Ut,{capture:!0}),this.zt&&me.removeEventListener("mousemove",this.zt,{capture:!0}),this.qt&&me.removeEventListener("visibilitychange",this.qt),clearTimeout(this.Wt),(e=this.Bt)==null||e.stop(),this.P=!1)}Gt(e,n){var r=this.instance.scrollManager.scrollY(),i=this.instance.scrollManager.scrollX(),o=this.instance.scrollManager.scrollElement(),s=(function(a,l,c){for(var u=a;u&&Cd(u)&&!oo(u,"body");){if(u===c)return!1;if(Ue(l,oe==null?void 0:oe.getComputedStyle(u).position))return!0;u=jS(u)}return!1})(WS(e),["fixed","sticky"],o);return{x:e.clientX+(s?0:i),y:e.clientY+(s?0:r),target_fixed:s,type:n}}jt(e,n){var r;if(n===void 0&&(n="click"),!DS(e.target)&&xI(e)){var i=this.Gt(e,n);(r=this.rageclicks)!=null&&r.isRageClick(e.clientX,e.clientY,new Date().getTime())&&this.Vt(be({},i,{type:"rageclick"})),this.Vt(i)}}Ht(e){!DS(e.target)&&xI(e)&&(clearTimeout(this.Wt),this.Wt=setTimeout((()=>{this.Vt(this.Gt(e,"mousemove"))}),500))}Vt(e){if(oe){var n=oe.location.href,r=this.instance.config.mask_personal_data_properties,i=this.instance.config.custom_personal_data_properties,o=r?sa([],la,i||[]):[],s=Wl(n,o,ql);this.N=this.N||{},this.N[s]||(this.N[s]=[]),this.N[s].push(e)}}Lt(){this.N&&!ta(this.N)&&this.instance.capture("$$heatmap",{$heatmap_data:this.getAndClearBuffer()})}}class wK{constructor(e){this._instance=e}doPageView(e,n){var r,i=this.Jt(e,n);return this.Kt={pathname:(r=oe==null?void 0:oe.location.pathname)!==null&&r!==void 0?r:"",pageViewId:n,timestamp:e},this._instance.scrollManager.resetContext(),i}doPageLeave(e){var n;return this.Jt(e,(n=this.Kt)==null?void 0:n.pageViewId)}doEvent(){var e;return{$pageview_id:(e=this.Kt)==null?void 0:e.pageViewId}}Jt(e,n){var r=this.Kt;if(!r)return{$pageview_id:n};var i={$pageview_id:n,$prev_pageview_id:r.pageViewId},o=this._instance.scrollManager.getContext();if(o&&!this._instance.config.disable_scroll_properties){var{maxScrollHeight:s,lastScrollY:a,maxScrollY:l,maxContentHeight:c,lastContentY:u,maxContentY:h}=o;if(!(fe(s)||fe(a)||fe(l)||fe(c)||fe(u)||fe(h))){s=Math.ceil(s),a=Math.ceil(a),l=Math.ceil(l),c=Math.ceil(c),u=Math.ceil(u),h=Math.ceil(h);var p=s<=1?1:ti(a/s,0,1,ye),g=s<=1?1:ti(l/s,0,1,ye),b=c<=1?1:ti(u/c,0,1,ye),m=c<=1?1:ti(h/c,0,1,ye);i=Ot(i,{$prev_pageview_last_scroll:a,$prev_pageview_last_scroll_percentage:p,$prev_pageview_max_scroll:l,$prev_pageview_max_scroll_percentage:g,$prev_pageview_last_content:u,$prev_pageview_last_content_percentage:b,$prev_pageview_max_content:h,$prev_pageview_max_content_percentage:m})}}return r.pathname&&(i.$prev_pageview_pathname=r.pathname),r.timestamp&&(i.$prev_pageview_duration=(e.getTime()-r.timestamp.getTime())/1e3),i}}var _r=Uint8Array,Gn=Uint16Array,ca=Uint32Array,im=new _r([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]),om=new _r([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]),wI=new _r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),EI=function(t,e){for(var n=new Gn(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];var i=new ca(n[30]);for(r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)i[o]=o-n[r]<<5|r;return[n,i]},SI=EI(im,2),EK=SI[0],sm=SI[1];EK[28]=258,sm[258]=28;for(var II=EI(om,0)[1],CI=new Gn(32768),ft=0;ft<32768;++ft){var Yo=(43690&ft)>>>1|(21845&ft)<<1;Yo=(61680&(Yo=(52428&Yo)>>>2|(13107&Yo)<<2))>>>4|(3855&Yo)<<4,CI[ft]=((65280&Yo)>>>8|(255&Yo)<<8)>>>1}var Gl=function(t,e,n){for(var r=t.length,i=0,o=new Gn(e);i<r;++i)++o[t[i]-1];var s,a=new Gn(e);for(i=0;i<e;++i)a[i]=a[i-1]+o[i-1]<<1;for(s=new Gn(r),i=0;i<r;++i)s[i]=CI[a[t[i]-1]++]>>>15-t[i];return s},Xo=new _r(288);for(ft=0;ft<144;++ft)Xo[ft]=8;for(ft=144;ft<256;++ft)Xo[ft]=9;for(ft=256;ft<280;++ft)Xo[ft]=7;for(ft=280;ft<288;++ft)Xo[ft]=8;var Bd=new _r(32);for(ft=0;ft<32;++ft)Bd[ft]=5;var SK=Gl(Xo,9),IK=Gl(Bd,5),AI=function(t){return(t/8>>0)+(7&t&&1)},OI=function(t,e,n){(n==null||n>t.length)&&(n=t.length);var r=new(t instanceof Gn?Gn:t instanceof ca?ca:_r)(n-e);return r.set(t.subarray(e,n)),r},Ni=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8},Kl=function(t,e,n){n<<=7&e;var r=e/8>>0;t[r]|=n,t[r+1]|=n>>>8,t[r+2]|=n>>>16},am=function(t,e){for(var n=[],r=0;r<t.length;++r)t[r]&&n.push({s:r,f:t[r]});var i=n.length,o=n.slice();if(!i)return[new _r(0),0];if(i==1){var s=new _r(n[0].s+1);return s[n[0].s]=1,[s,1]}n.sort((function(B,G){return B.f-G.f})),n.push({s:-1,f:25001});var a=n[0],l=n[1],c=0,u=1,h=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};u!=i-1;)a=n[n[c].f<n[h].f?c++:h++],l=n[c!=u&&n[c].f<n[h].f?c++:h++],n[u++]={s:-1,f:a.f+l.f,l:a,r:l};var p=o[0].s;for(r=1;r<i;++r)o[r].s>p&&(p=o[r].s);var g=new Gn(p+1),b=lm(n[u-1],g,0);if(b>e){r=0;var m=0,x=b-e,I=1<<x;for(o.sort((function(B,G){return g[G.s]-g[B.s]||B.f-G.f}));r<i;++r){var N=o[r].s;if(!(g[N]>e))break;m+=I-(1<<b-g[N]),g[N]=e}for(m>>>=x;m>0;){var T=o[r].s;g[T]<e?m-=1<<e-g[T]++-1:++r}for(;r>=0&&m;--r){var $=o[r].s;g[$]==e&&(--g[$],++m)}b=e}return[new _r(g),b]},lm=function(t,e,n){return t.s==-1?Math.max(lm(t.l,e,n+1),lm(t.r,e,n+1)):e[t.s]=n},kI=function(t){for(var e=t.length;e&&!t[--e];);for(var n=new Gn(++e),r=0,i=t[0],o=1,s=function(l){n[r++]=l},a=1;a<=e;++a)if(t[a]==i&&a!=e)++o;else{if(!i&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0)}else if(o>3){for(s(i),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0)}for(;o--;)s(i);o=1,i=t[a]}return[n.subarray(0,r),e]},Yl=function(t,e){for(var n=0,r=0;r<e.length;++r)n+=t[r]*e[r];return n},cm=function(t,e,n){var r=n.length,i=AI(e+2);t[i]=255&r,t[i+1]=r>>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var o=0;o<r;++o)t[i+o+4]=n[o];return 8*(i+4+r)},TI=function(t,e,n,r,i,o,s,a,l,c,u){Ni(e,u++,n),++i[256];for(var h=am(i,15),p=h[0],g=h[1],b=am(o,15),m=b[0],x=b[1],I=kI(p),N=I[0],T=I[1],$=kI(m),B=$[0],G=$[1],Z=new Gn(19),Y=0;Y<N.length;++Y)Z[31&N[Y]]++;for(Y=0;Y<B.length;++Y)Z[31&B[Y]]++;for(var F=am(Z,7),V=F[0],U=F[1],W=19;W>4&&!V[wI[W-1]];--W);var A,d,y,S,C=c+5<<3,R=Yl(i,Xo)+Yl(o,Bd)+s,D=Yl(i,p)+Yl(o,m)+s+14+3*W+Yl(Z,V)+(2*Z[16]+3*Z[17]+7*Z[18]);if(C<=R&&C<=D)return cm(e,u,t.subarray(l,l+c));if(Ni(e,u,1+(D<R)),u+=2,D<R){A=Gl(p,g),d=p,y=Gl(m,x),S=m;var L=Gl(V,U);for(Ni(e,u,T-257),Ni(e,u+5,G-1),Ni(e,u+10,W-4),u+=14,Y=0;Y<W;++Y)Ni(e,u+3*Y,V[wI[Y]]);u+=3*W;for(var O=[N,B],f=0;f<2;++f){var v=O[f];for(Y=0;Y<v.length;++Y){var k=31&v[Y];Ni(e,u,L[k]),u+=V[k],k>15&&(Ni(e,u,v[Y]>>>5&127),u+=v[Y]>>>12)}}}else A=SK,d=Xo,y=IK,S=Bd;for(Y=0;Y<a;++Y)if(r[Y]>255){k=r[Y]>>>18&31,Kl(e,u,A[k+257]),u+=d[k+257],k>7&&(Ni(e,u,r[Y]>>>23&31),u+=im[k]);var M=31&r[Y];Kl(e,u,y[M]),u+=S[M],M>3&&(Kl(e,u,r[Y]>>>5&8191),u+=om[M])}else Kl(e,u,A[r[Y]]),u+=d[r[Y]];return Kl(e,u,A[256]),u+d[256]},CK=new ca([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),AK=(function(){for(var t=new ca(256),e=0;e<256;++e){for(var n=e,r=9;--r;)n=(1&n&&3988292384)^n>>>1;t[e]=n}return t})(),OK=function(t,e,n,r,i){return(function(o,s,a,l,c,u){var h=o.length,p=new _r(l+h+5*(1+Math.floor(h/7e3))+c),g=p.subarray(l,p.length-c),b=0;if(!s||h<8)for(var m=0;m<=h;m+=65535){var x=m+65535;x<h?b=cm(g,b,o.subarray(m,x)):(g[m]=u,b=cm(g,b,o.subarray(m,h)))}else{for(var I=CK[s-1],N=I>>>13,T=8191&I,$=(1<<a)-1,B=new Gn(32768),G=new Gn($+1),Z=Math.ceil(a/3),Y=2*Z,F=function(He){return(o[He]^o[He+1]<<Z^o[He+2]<<Y)&$},V=new ca(25e3),U=new Gn(288),W=new Gn(32),A=0,d=0,y=(m=0,0),S=0,C=0;m<h;++m){var R=F(m),D=32767&m,L=G[R];if(B[D]=L,G[R]=D,S<=m){var O=h-m;if((A>7e3||y>24576)&&O>423){b=TI(o,g,0,V,U,W,d,y,C,m-C,b),y=A=d=0,C=m;for(var f=0;f<286;++f)U[f]=0;for(f=0;f<30;++f)W[f]=0}var v=2,k=0,M=T,H=D-L&32767;if(O>2&&R==F(m-H))for(var Q=Math.min(N,O)-1,X=Math.min(32767,m),j=Math.min(258,O);H<=X&&--M&&D!=L;){if(o[m+v]==o[m+v-H]){for(var ee=0;ee<j&&o[m+ee]==o[m+ee-H];++ee);if(ee>v){if(v=ee,k=H,ee>Q)break;var se=Math.min(H,ee-2),re=0;for(f=0;f<se;++f){var ve=m-H+f+32768&32767,xe=ve-B[ve]+32768&32767;xe>re&&(re=xe,L=ve)}}}H+=(D=L)-(L=B[D])+32768&32767}if(k){V[y++]=268435456|sm[v]<<18|II[k];var Pe=31&sm[v],Et=31&II[k];d+=im[Pe]+om[Et],++U[257+Pe],++W[Et],S=m+v,++A}else V[y++]=o[m],++U[o[m]]}}b=TI(o,g,u,V,U,W,d,y,C,m-C,b)}return OI(p,0,l+AI(b)+c)})(t,e.level==null?6:e.level,e.mem==null?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(t.length)))):12+e.mem,n,r,!0)},um=function(t,e,n){for(;n;++e)t[e]=n,n>>>=8};function kK(t,e){e===void 0&&(e={});var n=(function(){var a=4294967295;return{p:function(l){for(var c=a,u=0;u<l.length;++u)c=AK[255&c^l[u]]^c>>>8;a=c},d:function(){return 4294967295^a}}})(),r=t.length;n.p(t);var i,o=OK(t,e,10+((i=e).filename&&i.filename.length+1||0),8),s=o.length;return(function(a,l){var c=l.filename;if(a[0]=31,a[1]=139,a[2]=8,a[8]=l.level<2?4:l.level==9?2:0,a[9]=3,l.mtime!=0&&um(a,4,Math.floor(new Date(l.mtime||Date.now())/1e3)),c){a[3]=8;for(var u=0;u<=c.length;++u)a[u+10]=c.charCodeAt(u)}})(o,e),um(o,s-8,n.d()),um(o,s-4,r),o}var TK=function(t){var e,n,r,i,o="";for(e=n=0,r=(t=(t+"").replace(/\r\n/g,`
230
230
  `).replace(/\r/g,`
231
231
  `)).length,i=0;i<r;i++){var s=t.charCodeAt(i),a=null;s<128?n++:a=s>127&&s<2048?String.fromCharCode(s>>6|192,63&s|128):String.fromCharCode(s>>12|224,s>>6&63|128,63&s|128),Pr(a)||(n>e&&(o+=t.substring(e,n)),o+=a,e=n=i+1)}return n>e&&(o+=t.substring(e,t.length)),o},RK=!!Ip||!!Sp,RI="text/plain",Fd=function(t,e,n){var r;n===void 0&&(n=!0);var[i,o]=t.split("?"),s=be({},e),a=(r=o==null?void 0:o.split("&").map((c=>{var u,[h,p]=c.split("="),g=n&&(u=s[h])!==null&&u!==void 0?u:p;return delete s[h],h+"="+g})))!==null&&r!==void 0?r:[],l=qG(s);return l&&a.push(l),i+"?"+a.join("&")},Xl=(t,e)=>JSON.stringify(t,((n,r)=>typeof r=="bigint"?r.toString():r),e),dm=t=>{var{data:e,compression:n}=t;if(e){if(n===Ti.GZipJS){var r=kK((function(l,c){var u=l.length;if(typeof TextEncoder!="undefined")return new TextEncoder().encode(l);for(var h=new _r(l.length+(l.length>>>1)),p=0,g=function(I){h[p++]=I},b=0;b<u;++b){if(p+5>h.length){var m=new _r(p+8+(u-b<<1));m.set(h),h=m}var x=l.charCodeAt(b);x<128||c?g(x):x<2048?(g(192|x>>>6),g(128|63&x)):x>55295&&x<57344?(g(240|(x=65536+(1047552&x)|1023&l.charCodeAt(++b))>>>18),g(128|x>>>12&63),g(128|x>>>6&63),g(128|63&x)):(g(224|x>>>12),g(128|x>>>6&63),g(128|63&x))}return OI(h,0,p)})(Xl(e)),{mtime:0}),i=new Blob([r],{type:RI});return{contentType:RI,body:i,estimatedSize:i.size}}if(n===Ti.Base64){var o=(function(l){var c,u,h,p,g,b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",m=0,x=0,I="",N=[];if(!l)return l;l=TK(l);do c=(g=l.charCodeAt(m++)<<16|l.charCodeAt(m++)<<8|l.charCodeAt(m++))>>18&63,u=g>>12&63,h=g>>6&63,p=63&g,N[x++]=b.charAt(c)+b.charAt(u)+b.charAt(h)+b.charAt(p);while(m<l.length);switch(I=N.join(""),l.length%3){case 1:I=I.slice(0,-2)+"==";break;case 2:I=I.slice(0,-1)+"="}return I})(Xl(e)),s=(l=>"data="+encodeURIComponent(typeof l=="string"?l:Xl(l)))(o);return{contentType:"application/x-www-form-urlencoded",body:s,estimatedSize:new Blob([s]).size}}var a=Xl(e);return{contentType:"application/json",body:a,estimatedSize:new Blob([a]).size}}},Dd=[];Sp&&Dd.push({transport:"fetch",method:t=>{var e,n,{contentType:r,body:i,estimatedSize:o}=(e=dm(t))!==null&&e!==void 0?e:{},s=new Headers;ut(t.headers,(function(u,h){s.append(h,u)})),r&&s.append("Content-Type",r);var a=t.url,l=null;if(qE){var c=new qE;l={signal:c.signal,timeout:setTimeout((()=>c.abort()),t.timeout)}}Sp(a,be({method:(t==null?void 0:t.method)||"GET",headers:s,keepalive:t.method==="POST"&&(o||0)<52428.8,body:i,signal:(n=l)==null?void 0:n.signal},t.fetchOptions)).then((u=>u.text().then((h=>{var p={statusCode:u.status,text:h};if(u.status===200)try{p.json=JSON.parse(h)}catch(g){ye.error(g)}t.callback==null||t.callback(p)})))).catch((u=>{ye.error(u),t.callback==null||t.callback({statusCode:0,text:u})})).finally((()=>l?clearTimeout(l.timeout):null))}}),Ip&&Dd.push({transport:"XHR",method:t=>{var e,n=new Ip;n.open(t.method||"GET",t.url,!0);var{contentType:r,body:i}=(e=dm(t))!==null&&e!==void 0?e:{};ut(t.headers,(function(o,s){n.setRequestHeader(s,o)})),r&&n.setRequestHeader("Content-Type",r),t.timeout&&(n.timeout=t.timeout),t.disableXHRCredentials||(n.withCredentials=!0),n.onreadystatechange=()=>{if(n.readyState===4){var o={statusCode:n.status,text:n.responseText};if(n.status===200)try{o.json=JSON.parse(n.responseText)}catch(s){}t.callback==null||t.callback(o)}},n.send(i)}}),ur!=null&&ur.sendBeacon&&Dd.push({transport:"sendBeacon",method:t=>{var e=Fd(t.url,{beacon:"1"});try{var n,{contentType:r,body:i}=(n=dm(t))!==null&&n!==void 0?n:{},o=typeof i=="string"?new Blob([i],{type:r}):i;ur.sendBeacon(e,o)}catch(s){}}});var Vd=function(t,e){if(!(function(n){try{new RegExp(n)}catch(r){return!1}return!0})(e))return!1;try{return new RegExp(e).test(t)}catch(n){return!1}};function NI(t,e,n){return Xl({distinct_id:t,userPropertiesToSet:e,userPropertiesToSetOnce:n})}var PI={exact:(t,e)=>e.some((n=>t.some((r=>n===r)))),is_not:(t,e)=>e.every((n=>t.every((r=>n!==r)))),regex:(t,e)=>e.some((n=>t.some((r=>Vd(n,r))))),not_regex:(t,e)=>e.every((n=>t.every((r=>!Vd(n,r))))),icontains:(t,e)=>e.map($d).some((n=>t.map($d).some((r=>n.includes(r))))),not_icontains:(t,e)=>e.map($d).every((n=>t.map($d).every((r=>!n.includes(r))))),gt:(t,e)=>e.some((n=>{var r=parseFloat(n);return!isNaN(r)&&t.some((i=>r>parseFloat(i)))})),lt:(t,e)=>e.some((n=>{var r=parseFloat(n);return!isNaN(r)&&t.some((i=>r<parseFloat(i)))}))},$d=t=>t.toLowerCase();function LI(t,e){return!t||Object.entries(t).every((n=>{var[r,i]=n,o=e==null?void 0:e[r];if(fe(o)||Pr(o))return!1;var s=[String(o)],a=PI[i.operator];return!!a&&a(i.values,s)}))}var hm=At("[Error tracking]");class NK{constructor(e){var n,r;this.Yt=[],this.Xt=new hG([new xG,new TG,new EG,new wG,new OG,new AG,new IG,new kG],_G("web:javascript",mG,bG)),this._instance=e,this.Yt=(n=(r=this._instance.persistence)==null?void 0:r.get_property(Up))!==null&&n!==void 0?n:[]}onRemoteConfig(e){var n,r,i,o=(n=(r=e.errorTracking)==null?void 0:r.suppressionRules)!==null&&n!==void 0?n:[],s=(i=e.errorTracking)==null?void 0:i.captureExtensionExceptions;this.Yt=o,this._instance.persistence&&this._instance.persistence.register({[Up]:this.Yt,[RS]:s})}get Qt(){var e,n=!!this._instance.get_property(RS),r=this._instance.config.error_tracking.captureExtensionExceptions;return(e=r!=null?r:n)!==null&&e!==void 0&&e}buildProperties(e,n){return this.Xt.buildFromUnknown(e,{syntheticException:n==null?void 0:n.syntheticException,mechanism:{handled:n==null?void 0:n.handled}})}sendExceptionEvent(e){var n=e.$exception_list;if(this.Zt(n)){if(this.ti(n))return void hm.info("Skipping exception capture because a suppression rule matched");if(!this.Qt&&this.ii(n))return void hm.info("Skipping exception capture because it was thrown by an extension");if(!this._instance.config.error_tracking.__capturePostHogExceptions&&this.ei(n))return void hm.info("Skipping exception capture because it was thrown by the PostHog SDK")}return this._instance.capture("$exception",e,{_noTruncate:!0,_batchKey:"exceptionEvent"})}ti(e){if(e.length===0)return!1;var n=e.reduce(((r,i)=>{var{type:o,value:s}=i;return nn(o)&&o.length>0&&r.$exception_types.push(o),nn(s)&&s.length>0&&r.$exception_values.push(s),r}),{$exception_types:[],$exception_values:[]});return this.Yt.some((r=>{var i=r.values.map((o=>{var s,a=PI[o.operator],l=Ze(o.value)?o.value:[o.value],c=(s=n[o.key])!==null&&s!==void 0?s:[];return l.length>0&&a(l,c)}));return r.type==="OR"?i.some(Boolean):i.every(Boolean)}))}ii(e){return e.flatMap((n=>{var r,i;return(r=(i=n.stacktrace)==null?void 0:i.frames)!==null&&r!==void 0?r:[]})).some((n=>n.filename&&n.filename.startsWith("chrome-extension://")))}ei(e){if(e.length>0){var n,r,i,o,s=(n=(r=e[0].stacktrace)==null?void 0:r.frames)!==null&&n!==void 0?n:[],a=s[s.length-1];return(i=a==null||(o=a.filename)==null?void 0:o.includes("posthog.com/static"))!==null&&i!==void 0&&i}return!1}Zt(e){return!Je(e)&&Ze(e)}}var Lr=At("[FeatureFlags]"),Zl=At("[FeatureFlags]",{debugEnabled:!0}),fm="$active_feature_flags",ua="$override_feature_flags",MI="$feature_flag_payloads",Jl="$override_feature_flag_payloads",BI="$feature_flag_request_id",FI="$feature_flag_evaluated_at",DI=t=>{var e={};for(var[n,r]of xd(t||{}))r&&(e[n]=r);return e},PK=t=>{var e=t.flags;return e?(t.featureFlags=Object.fromEntries(Object.keys(e).map((n=>{var r;return[n,(r=e[n].variant)!==null&&r!==void 0?r:e[n].enabled]}))),t.featureFlagPayloads=Object.fromEntries(Object.keys(e).filter((n=>e[n].enabled)).filter((n=>{var r;return(r=e[n].metadata)==null?void 0:r.payload})).map((n=>{var r;return[n,(r=e[n].metadata)==null?void 0:r.payload]})))):Lr.warn("Using an older version of the feature flags endpoint. Please upgrade your PostHog server to the latest version"),t},LK=(function(t){return t.FeatureFlags="feature_flags",t.Recordings="recordings",t})({});class MK{constructor(e){this.ri=!1,this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this._instance=e,this.featureFlagEventHandlers=[]}hi(){var e=this._instance.config.evaluation_environments;return e!=null&&e.length?e.filter((n=>{var r=n&&typeof n=="string"&&n.trim().length>0;return r||Lr.error("Invalid evaluation environment found:",n,"Expected non-empty string"),r})):[]}di(){return this.hi().length>0}flags(){if(this._instance.config.__preview_remote_config)this.li=!0;else{var e=!this.vi&&(this._instance.config.advanced_disable_feature_flags||this._instance.config.advanced_disable_feature_flags_on_first_load);this.ci({disableFlags:e})}}get hasLoadedFlags(){return this.si}getFlags(){return Object.keys(this.getFlagVariants())}getFlagsWithDetails(){var e=this._instance.get_property(Hp),n=this._instance.get_property(ua),r=this._instance.get_property(Jl);if(!r&&!n)return e||{};var i=Ot({},e||{}),o=[...new Set([...Object.keys(r||{}),...Object.keys(n||{})])];for(var s of o){var a,l,c=i[s],u=n==null?void 0:n[s],h=fe(u)?(a=c==null?void 0:c.enabled)!==null&&a!==void 0&&a:!!u,p=fe(u)?c.variant:typeof u=="string"?u:void 0,g=r==null?void 0:r[s],b=be({},c,{enabled:h,variant:h?p!=null?p:c==null?void 0:c.variant:void 0});h!==(c==null?void 0:c.enabled)&&(b.original_enabled=c==null?void 0:c.enabled),p!==(c==null?void 0:c.variant)&&(b.original_variant=c==null?void 0:c.variant),g&&(b.metadata=be({},c==null?void 0:c.metadata,{payload:g,original_payload:c==null||(l=c.metadata)==null?void 0:l.payload})),i[s]=b}return this.ri||(Lr.warn(" Overriding feature flag details!",{flagDetails:e,overriddenPayloads:r,finalDetails:i}),this.ri=!0),i}getFlagVariants(){var e=this._instance.get_property(aa),n=this._instance.get_property(ua);if(!n)return e||{};for(var r=Ot({},e),i=Object.keys(n),o=0;o<i.length;o++)r[i[o]]=n[i[o]];return this.ri||(Lr.warn(" Overriding feature flags!",{enabledFlags:e,overriddenFlags:n,finalFlags:r}),this.ri=!0),r}getFlagPayloads(){var e=this._instance.get_property(MI),n=this._instance.get_property(Jl);if(!n)return e||{};for(var r=Ot({},e||{}),i=Object.keys(n),o=0;o<i.length;o++)r[i[o]]=n[i[o]];return this.ri||(Lr.warn(" Overriding feature flag payloads!",{flagPayloads:e,overriddenPayloads:n,finalPayloads:r}),this.ri=!0),r}reloadFeatureFlags(){this.oi||this._instance.config.advanced_disable_feature_flags||this.vi||(this.vi=setTimeout((()=>{this.ci()}),5))}fi(){clearTimeout(this.vi),this.vi=void 0}ensureFlagsLoaded(){this.si||this.ni||this.vi||this.reloadFeatureFlags()}setAnonymousDistinctId(e){this.$anon_distinct_id=e}setReloadingPaused(e){this.oi=e}ci(e){var n;if(this.fi(),!this._instance.O())if(this.ni)this.ai=!0;else{var r=this._instance.config.token,i=this._instance.get_property("$device_id"),o={token:r,distinct_id:this._instance.get_distinct_id(),groups:this._instance.getGroups(),$anon_distinct_id:this.$anon_distinct_id,person_properties:be({},((n=this._instance.persistence)==null?void 0:n.get_initial_props())||{},this._instance.get_property(Vl)||{}),group_properties:this._instance.get_property(Go)};Pr(i)||fe(i)||(o.$device_id=i),(e!=null&&e.disableFlags||this._instance.config.advanced_disable_feature_flags)&&(o.disable_flags=!0),this.di()&&(o.evaluation_environments=this.hi());var s=this._instance.config.__preview_remote_config,a=s?"/flags/?v=2":"/flags/?v=2&config=true",l=this._instance.config.advanced_only_evaluate_survey_feature_flags?"&only_evaluate_survey_feature_flags=true":"",c=this._instance.requestRouter.endpointFor("flags",a+l);s&&(o.timezone=bI()),this.ni=!0,this._instance._send_request({method:"POST",url:c,data:o,compression:this._instance.config.disable_compression?void 0:Ti.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:u=>{var h,p,g=!0;if(u.statusCode===200&&(this.ai||(this.$anon_distinct_id=void 0),g=!1),this.ni=!1,this.li||(this.li=!0,this._instance.pi((p=u.json)!==null&&p!==void 0?p:{})),!o.disable_flags||this.ai)if(this.ui=!g,u.json&&(h=u.json.quotaLimited)!=null&&h.includes(LK.FeatureFlags))Lr.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 b;o.disable_flags||this.receivedFeatureFlags((b=u.json)!==null&&b!==void 0?b:{},g),this.ai&&(this.ai=!1,this.ci())}}})}}getFeatureFlag(e,n){if(n===void 0&&(n={}),this.si||this.getFlags()&&this.getFlags().length>0){var r=this.getFlagVariants()[e],i=""+r,o=this._instance.get_property(BI)||void 0,s=this._instance.get_property(FI)||void 0,a=this._instance.get_property(Ed)||{};if((n.send_event||!("send_event"in n))&&(!(e in a)||!a[e].includes(i))){var l,c,u,h,p,g,b,m,x;Ze(a[e])?a[e].push(i):a[e]=[i],(l=this._instance.persistence)==null||l.register({[Ed]:a});var I=this.getFeatureFlagDetails(e),N={$feature_flag:e,$feature_flag_response:r,$feature_flag_payload:this.getFeatureFlagPayload(e)||null,$feature_flag_request_id:o,$feature_flag_evaluated_at:s,$feature_flag_bootstrapped_response:((c=this._instance.config.bootstrap)==null||(c=c.featureFlags)==null?void 0:c[e])||null,$feature_flag_bootstrapped_payload:((u=this._instance.config.bootstrap)==null||(u=u.featureFlagPayloads)==null?void 0:u[e])||null,$used_bootstrap_value:!this.ui};fe(I==null||(h=I.metadata)==null?void 0:h.version)||(N.$feature_flag_version=I.metadata.version);var T,$=(p=I==null||(g=I.reason)==null?void 0:g.description)!==null&&p!==void 0?p:I==null||(b=I.reason)==null?void 0:b.code;$&&(N.$feature_flag_reason=$),I!=null&&(m=I.metadata)!=null&&m.id&&(N.$feature_flag_id=I.metadata.id),fe(I==null?void 0:I.original_variant)&&fe(I==null?void 0:I.original_enabled)||(N.$feature_flag_original_response=fe(I.original_variant)?I.original_enabled:I.original_variant),I!=null&&(x=I.metadata)!=null&&x.original_payload&&(N.$feature_flag_original_payload=I==null||(T=I.metadata)==null?void 0:T.original_payload),this._instance.capture("$feature_flag_called",N)}return r}Lr.warn('getFeatureFlag for key "'+e+`" failed. Feature flags didn't load in time.`)}getFeatureFlagDetails(e){return this.getFlagsWithDetails()[e]}getFeatureFlagPayload(e){return this.getFlagPayloads()[e]}getRemoteConfigPayload(e,n){var r=this._instance.config.token,i={distinct_id:this._instance.get_distinct_id(),token:r};this.di()&&(i.evaluation_environments=this.hi()),this._instance._send_request({method:"POST",url:this._instance.requestRouter.endpointFor("flags","/flags/?v=2&config=true"),data:i,compression:this._instance.config.disable_compression?void 0:Ti.Base64,timeout:this._instance.config.feature_flag_request_timeout_ms,callback:o=>{var s,a=(s=o.json)==null?void 0:s.featureFlagPayloads;n((a==null?void 0:a[e])||void 0)}})}isFeatureEnabled(e,n){if(n===void 0&&(n={}),this.si||this.getFlags()&&this.getFlags().length>0){var r=this.getFeatureFlag(e,n);return fe(r)?void 0:!!r}Lr.warn('isFeatureEnabled for key "'+e+`" failed. Feature flags didn't load in time.`)}addFeatureFlagsHandler(e){this.featureFlagEventHandlers.push(e)}removeFeatureFlagsHandler(e){this.featureFlagEventHandlers=this.featureFlagEventHandlers.filter((n=>n!==e))}receivedFeatureFlags(e,n){if(this._instance.persistence){this.si=!0;var r=this.getFlagVariants(),i=this.getFlagPayloads(),o=this.getFlagsWithDetails();(function(s,a,l,c,u){l===void 0&&(l={}),c===void 0&&(c={}),u===void 0&&(u={});var h=PK(s),p=h.flags,g=h.featureFlags,b=h.featureFlagPayloads;if(g){var m=s.requestId,x=s.evaluatedAt;if(Ze(g)){Lr.warn("v1 of the feature flags endpoint is deprecated. Please use the latest version.");var I={};if(g)for(var N=0;N<g.length;N++)I[g[N]]=!0;a&&a.register({[fm]:g,[aa]:I})}else{var T=g,$=b,B=p;s.errorsWhileComputingFlags&&(T=be({},l,T),$=be({},c,$),B=be({},u,B)),a&&a.register(be({[fm]:Object.keys(DI(T)),[aa]:T||{},[MI]:$||{},[Hp]:B||{}},m?{[BI]:m}:{},x?{[FI]:x}:{}))}}})(e,this._instance.persistence,r,i,o),this.gi(n)}}override(e,n){n===void 0&&(n=!1),Lr.warn("override is deprecated. Please use overrideFeatureFlags instead."),this.overrideFeatureFlags({flags:e,suppressWarning:n})}overrideFeatureFlags(e){if(!this._instance.__loaded||!this._instance.persistence)return Lr.uninitializedWarning("posthog.featureFlags.overrideFeatureFlags");if(e===!1)return this._instance.persistence.unregister(ua),this._instance.persistence.unregister(Jl),this.gi(),Zl.info("All overrides cleared");if(e&&typeof e=="object"&&("flags"in e||"payloads"in e)){var n,r=e;if(this.ri=!!((n=r.suppressWarning)!==null&&n!==void 0&&n),"flags"in r){if(r.flags===!1)this._instance.persistence.unregister(ua),Zl.info("Flag overrides cleared");else if(r.flags){if(Ze(r.flags)){for(var i={},o=0;o<r.flags.length;o++)i[r.flags[o]]=!0;this._instance.persistence.register({[ua]:i})}else this._instance.persistence.register({[ua]:r.flags});Zl.info("Flag overrides set",{flags:r.flags})}}return"payloads"in r&&(r.payloads===!1?(this._instance.persistence.unregister(Jl),Zl.info("Payload overrides cleared")):r.payloads&&(this._instance.persistence.register({[Jl]:r.payloads}),Zl.info("Payload overrides set",{payloads:r.payloads}))),void this.gi()}this.gi()}onFeatureFlags(e){if(this.addFeatureFlagsHandler(e),this.si){var{flags:n,flagVariants:r}=this.mi();e(n,r)}return()=>this.removeFeatureFlagsHandler(e)}updateEarlyAccessFeatureEnrollment(e,n,r){var i,o=(this._instance.get_property(Dl)||[]).find((c=>c.flagKey===e)),s={["$feature_enrollment/"+e]:n},a={$feature_flag:e,$feature_enrollment:n,$set:s};o&&(a.$early_access_feature_name=o.name),r&&(a.$feature_enrollment_stage=r),this._instance.capture("$feature_enrollment_update",a),this.setPersonPropertiesForFlags(s,!1);var l=be({},this.getFlagVariants(),{[e]:n});(i=this._instance.persistence)==null||i.register({[fm]:Object.keys(DI(l)),[aa]:l}),this.gi()}getEarlyAccessFeatures(e,n,r){n===void 0&&(n=!1);var i=this._instance.get_property(Dl),o=r?"&"+r.map((s=>"stage="+s)).join("&"):"";if(i&&!n)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/early_access_features/?token="+this._instance.config.token+o),method:"GET",callback:s=>{var a,l;if(s.json){var c=s.json.earlyAccessFeatures;return(a=this._instance.persistence)==null||a.unregister(Dl),(l=this._instance.persistence)==null||l.register({[Dl]:c}),e(c)}}})}mi(){var e=this.getFlags(),n=this.getFlagVariants();return{flags:e.filter((r=>n[r])),flagVariants:Object.keys(n).filter((r=>n[r])).reduce(((r,i)=>(r[i]=n[i],r)),{})}}gi(e){var{flags:n,flagVariants:r}=this.mi();this.featureFlagEventHandlers.forEach((i=>i(n,r,{errorsLoading:e})))}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Vl)||{};this._instance.register({[Vl]:be({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetPersonPropertiesForFlags(){this._instance.unregister(Vl)}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0);var r=this._instance.get_property(Go)||{};Object.keys(r).length!==0&&Object.keys(r).forEach((i=>{r[i]=be({},r[i],e[i]),delete e[i]})),this._instance.register({[Go]:be({},r,e)}),n&&this._instance.reloadFeatureFlags()}resetGroupPropertiesForFlags(e){if(e){var n=this._instance.get_property(Go)||{};this._instance.register({[Go]:be({},n,{[e]:{}})})}else this._instance.unregister(Go)}reset(){this.si=!1,this.ni=!1,this.oi=!1,this.ai=!1,this.li=!1,this.ui=!1,this.$anon_distinct_id=void 0,this.fi(),this.ri=!1}}var BK=["cookie","localstorage","localstorage+cookie","sessionstorage","memory"];class gm{constructor(e,n){this.R=e,this.props={},this.bi=!1,this.yi=(r=>{var i="";return r.token&&(i=r.token.replace(/\+/g,"PL").replace(/\//g,"SL").replace(/=/g,"EQ")),r.persistence_name?"ph_"+r.persistence_name:"ph_"+i+"_posthog"})(e),this.Y=this.wi(e),this.load(),e.debug&&ye.info("Persistence loaded",e.persistence,be({},this.props)),this.update_config(e,e,n),this.save()}isDisabled(){return!!this.xi}wi(e){BK.indexOf(e.persistence.toLowerCase())===-1&&(ye.critical("Unknown persistence type "+e.persistence+"; falling back to localStorage+cookie"),e.persistence="localStorage+cookie");var n=e.persistence.toLowerCase();return n==="localstorage"&&bt.H()?bt:n==="localstorage+cookie"&&Nd.H()?Nd:n==="sessionstorage"&&_n.H()?_n:n==="memory"?rK:n==="cookie"?ni:Nd.H()?Nd:ni}properties(){var e={};return ut(this.props,(function(n,r){if(r===aa&&an(n))for(var i=Object.keys(n),o=0;o<i.length;o++)e["$feature/"+i[o]]=n[i[o]];else a=r,l=!1,(Pr(s=BG)?l:jE&&s.indexOf===jE?s.indexOf(a)!=-1:(ut(s,(function(c){if(l||(l=c===a))return _d})),l))||(e[r]=n);var s,a,l})),e}load(){if(!this.xi){var e=this.Y.W(this.yi);e&&(this.props=Ot({},e))}}save(){this.xi||this.Y.G(this.yi,this.props,this.Ei,this.$i,this.Si,this.R.debug)}remove(){this.Y.V(this.yi,!1),this.Y.V(this.yi,!0)}clear(){this.remove(),this.props={}}register_once(e,n,r){if(an(e)){fe(n)&&(n="None"),this.Ei=fe(r)?this.ki:r;var i=!1;if(ut(e,((o,s)=>{this.props.hasOwnProperty(s)&&this.props[s]!==n||(this.props[s]=o,i=!0)})),i)return this.save(),!0}return!1}register(e,n){if(an(e)){this.Ei=fe(n)?this.ki:n;var r=!1;if(ut(e,((i,o)=>{e.hasOwnProperty(o)&&this.props[o]!==i&&(this.props[o]=i,r=!0)})),r)return this.save(),!0}return!1}unregister(e){e in this.props&&(delete this.props[e],this.save())}update_campaign_params(){if(!this.bi){var e=hI(this.R.custom_campaign_params,this.R.mask_personal_data_properties,this.R.custom_personal_data_properties);ta($p(e))||this.register(e),this.bi=!0}}update_search_keyword(){var e;this.register((e=me==null?void 0:me.referrer)?gI(e):{})}update_referrer_info(){var e;this.register_once({$referrer:mI(),$referring_domain:me!=null&&me.referrer&&((e=Od(me.referrer))==null?void 0:e.host)||"$direct"},void 0)}set_initial_person_info(){this.props[Kp]||this.props[Yp]||this.register_once({[Sd]:vI(this.R.mask_personal_data_properties,this.R.custom_personal_data_properties)},void 0)}get_initial_props(){var e={};ut([Yp,Kp],(s=>{var a=this.props[s];a&&ut(a,(function(l,c){e["$initial_"+Cp(c)]=l}))}));var n,r,i=this.props[Sd];if(i){var o=(n=yI(i),r={},ut(n,(function(s,a){r["$initial_"+Cp(a)]=s})),r);Ot(e,o)}return e}safe_merge(e){return ut(this.props,(function(n,r){r in e||(e[r]=n)})),e}update_config(e,n,r){if(this.ki=this.Ei=e.cookie_expiration,this.set_disabled(e.disable_persistence||!!r),this.set_cross_subdomain(e.cross_subdomain_cookie),this.set_secure(e.secure_cookie),e.persistence!==n.persistence){var i=this.wi(e),o=this.props;this.clear(),this.Y=i,this.props=o,this.save()}}set_disabled(e){this.xi=e,this.xi?this.remove():this.save()}set_cross_subdomain(e){e!==this.$i&&(this.$i=e,this.remove(),this.save())}set_secure(e){e!==this.Si&&(this.Si=e,this.remove(),this.save())}set_event_timer(e,n){var r=this.props[Fl]||{};r[e]=n,this.props[Fl]=r,this.save()}remove_event_timer(e){var n=(this.props[Fl]||{})[e];return fe(n)||(delete this.props[Fl][e],this.save()),n}get_property(e){return this.props[e]}set_property(e,n){this.props[e]=n,this.save()}}var VI=At("[Product Tours]"),pm="ph_product_tours";class FK{constructor(e){this.Pi=null,this.Ti=null,this._instance=e}onRemoteConfig(e){this._instance.persistence&&this._instance.persistence.register({[LS]:!(e==null||!e.productTours)}),this.loadIfEnabled()}loadIfEnabled(){var e,n;this.Pi||(e=this._instance).config.disable_product_tours||(n=e.persistence)==null||!n.get_property(LS)||this.it((()=>this.Ii()))}it(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.generateProductTours?e():(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"product-tours",(i=>{i?VI.error("Could not load product tours script",i):e()}))}Ii(){var e;!this.Pi&&(e=ke.__PosthogExtensions__)!=null&&e.generateProductTours&&(this.Pi=ke.__PosthogExtensions__.generateProductTours(this._instance,!0))}getProductTours(e,n){if(n===void 0&&(n=!1),!Ze(this.Ti)||n){var r=this._instance.persistence;if(r){var i=r.props[pm];if(Ze(i)&&!n)return this.Ti=i,void e(i,{isLoaded:!0})}this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/product_tours/?token="+this._instance.config.token),method:"GET",callback:o=>{var s=o.statusCode;if(s!==200||!o.json){var a="Product Tours API could not be loaded, status: "+s;return VI.error(a),void e([],{isLoaded:!1,error:a})}var l=Ze(o.json.product_tours)?o.json.product_tours:[];this.Ti=l,r&&r.register({[pm]:l}),e(l,{isLoaded:!0})}})}else e(this.Ti,{isLoaded:!0})}getActiveProductTours(e){Je(this.Pi)?e([],{isLoaded:!1,error:"Product tours not loaded"}):this.Pi.getActiveProductTours(e)}showProductTour(e){var n;(n=this.Pi)==null||n.showTourById(e)}previewTour(e){this.Pi?this.Pi.previewTour(e):this.it((()=>{var n;this.Ii(),(n=this.Pi)==null||n.previewTour(e)}))}dismissProductTour(){var e;(e=this.Pi)==null||e.dismissTour("user_clicked_skip")}nextStep(){var e;(e=this.Pi)==null||e.nextStep()}previousStep(){var e;(e=this.Pi)==null||e.previousStep()}clearCache(){var e;this.Ti=null,(e=this._instance.persistence)==null||e.unregister(pm)}resetTour(e){var n;(n=this.Pi)==null||n.resetTour(e)}resetAllTours(){var e;(e=this.Pi)==null||e.resetAllTours()}cancelPendingTour(e){var n;(n=this.Pi)==null||n.cancelPendingTour(e)}}var Ql=(function(t){return t.Activation="events",t.Cancellation="cancelEvents",t})({});(function(t){return t.Button="button",t.Tab="tab",t.Selector="selector",t})({}),(function(t){return t.TopLeft="top_left",t.TopRight="top_right",t.TopCenter="top_center",t.MiddleLeft="middle_left",t.MiddleRight="middle_right",t.MiddleCenter="middle_center",t.Left="left",t.Center="center",t.Right="right",t.NextToTrigger="next_to_trigger",t})({}),(function(t){return t.Top="top",t.Left="left",t.Right="right",t.Bottom="bottom",t})({});var mm=(function(t){return t.Popover="popover",t.API="api",t.Widget="widget",t.ExternalSurvey="external_survey",t})({});(function(t){return t.Open="open",t.MultipleChoice="multiple_choice",t.SingleChoice="single_choice",t.Rating="rating",t.Link="link",t})({}),(function(t){return t.NextQuestion="next_question",t.End="end",t.ResponseBased="response_based",t.SpecificQuestion="specific_question",t})({}),(function(t){return t.Once="once",t.Recurring="recurring",t.Always="always",t})({});var zd=(function(t){return t.SHOWN="survey shown",t.DISMISSED="survey dismissed",t.SENT="survey sent",t.ABANDONED="survey abandoned",t})({}),$I=(function(t){return t.SURVEY_ID="$survey_id",t.SURVEY_NAME="$survey_name",t.SURVEY_RESPONSE="$survey_response",t.SURVEY_ITERATION="$survey_iteration",t.SURVEY_ITERATION_START_DATE="$survey_iteration_start_date",t.SURVEY_PARTIALLY_COMPLETED="$survey_partially_completed",t.SURVEY_SUBMISSION_ID="$survey_submission_id",t.SURVEY_QUESTIONS="$survey_questions",t.SURVEY_COMPLETED="$survey_completed",t.PRODUCT_TOUR_ID="$product_tour_id",t})({}),zI=(function(t){return t.Popover="popover",t.Inline="inline",t})({}),dt=At("[Surveys]"),UI="seenSurvey_",DK=(t,e)=>{var n="$survey_"+e+"/"+t.id;return t.current_iteration&&t.current_iteration>0&&(n="$survey_"+e+"/"+t.id+"/"+t.current_iteration),n},WI=t=>((e,n)=>{var r=""+e+n.id;return n.current_iteration&&n.current_iteration>0&&(r=""+e+n.id+"_"+n.current_iteration),r})(UI,t),VK=[mm.Popover,mm.Widget,mm.API],$K={ignoreConditions:!1,ignoreDelay:!1,displayType:zI.Popover};class vm{constructor(){this.Ci={},this.Ci={}}on(e,n){return this.Ci[e]||(this.Ci[e]=[]),this.Ci[e].push(n),()=>{this.Ci[e]=this.Ci[e].filter((r=>r!==n))}}emit(e,n){for(var r of this.Ci[e]||[])r(n);for(var i of this.Ci["*"]||[])i(e,n)}}function da(t,e,n){if(Je(t))return!1;switch(n){case"exact":return t===e;case"contains":var r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/_/g,".").replace(/%/g,".*");return new RegExp(r,"i").test(t);case"regex":try{return new RegExp(e).test(t)}catch(i){return!1}default:return!1}}class zK{constructor(e){this.Ri=new vm,this.Fi=(n,r)=>this.Mi(n,r)&&this.Oi(n,r)&&this.Ai(n,r)&&this.Di(n,r),this.Mi=(n,r)=>r==null||!r.event||(n==null?void 0:n.event)===(r==null?void 0:r.event),this._instance=e,this.ji=new Set,this.Li=new Set}init(){var e;if(!fe((e=this._instance)==null?void 0:e.Ni)){var n;(n=this._instance)==null||n.Ni(((r,i)=>{this.on(r,i)}))}}register(e){var n,r;if(!fe((n=this._instance)==null?void 0:n.Ni)&&(e.forEach((s=>{var a,l;(a=this.Li)==null||a.add(s),(l=s.steps)==null||l.forEach((c=>{var u;(u=this.ji)==null||u.add((c==null?void 0:c.event)||"")}))})),(r=this._instance)!=null&&r.autocapture)){var i,o=new Set;e.forEach((s=>{var a;(a=s.steps)==null||a.forEach((l=>{l!=null&&l.selector&&o.add(l==null?void 0:l.selector)}))})),(i=this._instance)==null||i.autocapture.setElementSelectors(o)}}on(e,n){var r;n!=null&&e.length!=0&&(this.ji.has(e)||this.ji.has(n==null?void 0:n.event))&&this.Li&&((r=this.Li)==null?void 0:r.size)>0&&this.Li.forEach((i=>{this.Ui(n,i)&&this.Ri.emit("actionCaptured",i.name)}))}zi(e){this.onAction("actionCaptured",(n=>e(n)))}Ui(e,n){if((n==null?void 0:n.steps)==null)return!1;for(var r of n.steps)if(this.Fi(e,r))return!0;return!1}onAction(e,n){return this.Ri.on(e,n)}Oi(e,n){if(n!=null&&n.url){var r,i=e==null||(r=e.properties)==null?void 0:r.$current_url;if(!i||typeof i!="string"||!da(i,n.url,n.url_matching||"contains"))return!1}return!0}Ai(e,n){return!!this.Hi(e,n)&&!!this.Bi(e,n)&&!!this.qi(e,n)}Hi(e,n){var r;if(n==null||!n.href)return!0;var i=this.Wi(e);if(i.length>0)return i.some((a=>da(a.href,n.href,n.href_matching||"exact")));var o,s=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!s&&da((o=s.match(/(?::|")href="(.*?)"/))?o[1]:"",n.href,n.href_matching||"exact")}Bi(e,n){var r;if(n==null||!n.text)return!0;var i=this.Wi(e);if(i.length>0)return i.some((c=>da(c.text,n.text,n.text_matching||"exact")||da(c.$el_text,n.text,n.text_matching||"exact")));var o,s,a,l=(e==null||(r=e.properties)==null?void 0:r.$elements_chain)||"";return!!l&&(o=(function(c){for(var u,h=[],p=/(?::|")text="(.*?)"/g;!Je(u=p.exec(c));)h.includes(u[1])||h.push(u[1]);return h})(l),s=n.text,a=n.text_matching||"exact",o.some((c=>da(c,s,a))))}qi(e,n){var r,i;if(n==null||!n.selector)return!0;var o=e==null||(r=e.properties)==null?void 0:r.$element_selectors;if(o!=null&&o.includes(n.selector))return!0;var s=(e==null||(i=e.properties)==null?void 0:i.$elements_chain)||"";if(n.selector_regex&&s)try{return new RegExp(n.selector_regex).test(s)}catch(a){return!1}return!1}Wi(e){var n;return(e==null||(n=e.properties)==null?void 0:n.$elements)==null?[]:e==null?void 0:e.properties.$elements}Di(e,n){return n==null||!n.properties||n.properties.length===0||LI(n.properties.reduce(((r,i)=>{var o=Ze(i.value)?i.value.map(String):i.value!=null?[String(i.value)]:[];return r[i.key]={values:o,operator:i.operator||"exact"},r}),{}),e==null?void 0:e.properties)}}class UK{constructor(e){this._instance=e,this.Gi=new Map,this.Vi=new Map,this.Ji=new Map}Ki(e,n){return!!e&&LI(e.propertyFilters,n==null?void 0:n.properties)}Yi(e,n){var r=new Map;return e.forEach((i=>{var o;(o=i.conditions)==null||(o=o[n])==null||(o=o.values)==null||o.forEach((s=>{if(s!=null&&s.name){var a=r.get(s.name)||[];a.push(i.id),r.set(s.name,a)}}))})),r}Xi(e,n,r){var i=(r===Ql.Activation?this.Gi:this.Vi).get(e),o=[];return this.Qi((s=>{o=s.filter((a=>i==null?void 0:i.includes(a.id)))})),o.filter((s=>{var a,l=(a=s.conditions)==null||(a=a[r])==null||(a=a.values)==null?void 0:a.find((c=>c.name===e));return this.Ki(l,n)}))}register(e){var n;fe((n=this._instance)==null?void 0:n.Ni)||(this.Zi(e),this.te(e))}te(e){var n=e.filter((r=>{var i,o;return((i=r.conditions)==null?void 0:i.actions)&&((o=r.conditions)==null||(o=o.actions)==null||(o=o.values)==null?void 0:o.length)>0}));n.length!==0&&(this.ie==null&&(this.ie=new zK(this._instance),this.ie.init(),this.ie.zi((r=>{this.onAction(r)}))),n.forEach((r=>{var i,o,s,a,l;r.conditions&&(i=r.conditions)!=null&&i.actions&&(o=r.conditions)!=null&&(o=o.actions)!=null&&o.values&&((s=r.conditions)==null||(s=s.actions)==null||(s=s.values)==null?void 0:s.length)>0&&((a=this.ie)==null||a.register(r.conditions.actions.values),(l=r.conditions)==null||(l=l.actions)==null||(l=l.values)==null||l.forEach((c=>{if(c&&c.name){var u=this.Ji.get(c.name);u&&u.push(r.id),this.Ji.set(c.name,u||[r.id])}})))})))}Zi(e){var n,r=e.filter((o=>{var s,a;return((s=o.conditions)==null?void 0:s.events)&&((a=o.conditions)==null||(a=a.events)==null||(a=a.values)==null?void 0:a.length)>0})),i=e.filter((o=>{var s,a;return((s=o.conditions)==null?void 0:s.cancelEvents)&&((a=o.conditions)==null||(a=a.cancelEvents)==null||(a=a.values)==null?void 0:a.length)>0}));(r.length!==0||i.length!==0)&&((n=this._instance)==null||n.Ni(((o,s)=>{this.onEvent(o,s)})),this.Gi=this.Yi(e,Ql.Activation),this.Vi=this.Yi(e,Ql.Cancellation))}onEvent(e,n){var r,i=this.ee(),o=this.re(),s=this.se(),a=((r=this._instance)==null||(r=r.persistence)==null?void 0:r.props[o])||[];if(s===e&&n&&a.length>0){var l,c;i.info("event matched, removing item from activated items",{event:e,eventPayload:n,existingActivatedItems:a});var u=(n==null||(l=n.properties)==null?void 0:l.$survey_id)||(n==null||(c=n.properties)==null?void 0:c.$product_tour_id);if(u){var h=a.indexOf(u);h>=0&&(a.splice(h,1),this.ne(a))}}else{if(this.Vi.has(e)){var p=this.Xi(e,n,Ql.Cancellation);p.length>0&&(i.info("cancel event matched, cancelling items",{event:e,itemsToCancel:p.map((b=>b.id))}),p.forEach((b=>{var m=a.indexOf(b.id);m>=0&&a.splice(m,1),this.oe(b.id)})),this.ne(a))}if(this.Gi.has(e)){i.info("event name matched",{event:e,eventPayload:n,items:this.Gi.get(e)});var g=this.Xi(e,n,Ql.Activation);this.ne(a.concat(g.map((b=>b.id))||[]))}}}onAction(e){var n,r=this.re(),i=((n=this._instance)==null||(n=n.persistence)==null?void 0:n.props[r])||[];this.Ji.has(e)&&this.ne(i.concat(this.Ji.get(e)||[]))}ne(e){var n,r=this.ee(),i=this.re(),o=[...new Set(e)].filter((s=>!this.ae(s)));r.info("updating activated items",{activatedItems:o}),(n=this._instance)==null||(n=n.persistence)==null||n.register({[i]:o})}getActivatedIds(){var e,n=this.re(),r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.props[n];return r||[]}getEventToItemsMap(){return this.Gi}le(){return this.ie}}class WK extends UK{constructor(e){super(e)}re(){return"$surveys_activated"}se(){return zd.SHOWN}Qi(e){var n;(n=this._instance)==null||n.getSurveys(e)}oe(e){var n;(n=this._instance)==null||n.cancelPendingSurvey(e)}ee(){return dt}ae(){return!1}getSurveys(){return this.getActivatedIds()}getEventToSurveys(){return this.getEventToItemsMap()}}class HK{constructor(e){this.ue=void 0,this._surveyManager=null,this.he=!1,this.de=!1,this.ve=[],this._instance=e,this._surveyEventReceiver=null}onRemoteConfig(e){if(!this._instance.config.disable_surveys){var n=e.surveys;if(Je(n))return dt.warn("Flags not loaded yet. Not loading surveys.");var r=Ze(n);this.ue=r?n.length>0:n,dt.info("flags response received, isSurveysEnabled: "+this.ue),this.loadIfEnabled()}}reset(){localStorage.removeItem("lastSeenSurveyDate");for(var e=[],n=0;n<localStorage.length;n++){var r=localStorage.key(n);(r!=null&&r.startsWith(UI)||r!=null&&r.startsWith("inProgressSurvey_"))&&e.push(r)}e.forEach((i=>localStorage.removeItem(i)))}loadIfEnabled(){if(!this._surveyManager)if(this.de)dt.info("Already initializing surveys, skipping...");else if(this._instance.config.disable_surveys)dt.info("Disabled. Not loading surveys.");else if(this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())dt.info("Not loading surveys in cookieless mode without consent.");else{var e=ke==null?void 0:ke.__PosthogExtensions__;if(e){if(!fe(this.ue)||this._instance.config.advanced_enable_surveys){var n=this.ue||this._instance.config.advanced_enable_surveys;this.de=!0;try{var r=e.generateSurveys;if(r)return void this.ce(r,n);var i=e.loadExternalDependency;if(!i)return void this.fe("PostHog loadExternalDependency extension not found.");i(this._instance,"surveys",(o=>{o||!e.generateSurveys?this.fe("Could not load surveys script",o):this.ce(e.generateSurveys,n)}))}catch(o){throw this.fe("Error initializing surveys",o),o}finally{this.de=!1}}}else dt.error("PostHog Extensions not found.")}}ce(e,n){this._surveyManager=e(this._instance,n),this._surveyEventReceiver=new WK(this._instance),dt.info("Surveys loaded successfully"),this.pe({isLoaded:!0})}fe(e,n){dt.error(e,n),this.pe({isLoaded:!1,error:e})}onSurveysLoaded(e){return this.ve.push(e),this._surveyManager&&this.pe({isLoaded:!0}),()=>{this.ve=this.ve.filter((n=>n!==e))}}getSurveys(e,n){if(n===void 0&&(n=!1),this._instance.config.disable_surveys)return dt.info("Disabled. Not loading surveys."),e([]);var r=this._instance.get_property(jp);if(r&&!n)return e(r,{isLoaded:!0});if(this.he)return e([],{isLoaded:!1,error:"Surveys are already being loaded"});try{this.he=!0,this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/surveys/?token="+this._instance.config.token),method:"GET",timeout:this._instance.config.surveys_request_timeout_ms,callback:i=>{var o;this.he=!1;var s=i.statusCode;if(s!==200||!i.json){var a="Surveys API could not be loaded, status: "+s;return dt.error(a),e([],{isLoaded:!1,error:a})}var l,c=i.json.surveys||[],u=c.filter((h=>(function(p){return!(!p.start_date||p.end_date)})(h)&&((function(p){var g;return!((g=p.conditions)==null||(g=g.events)==null||(g=g.values)==null||!g.length)})(h)||(function(p){var g;return!((g=p.conditions)==null||(g=g.actions)==null||(g=g.values)==null||!g.length)})(h))));return u.length>0&&((l=this._surveyEventReceiver)==null||l.register(u)),(o=this._instance.persistence)==null||o.register({[jp]:c}),e(c,{isLoaded:!0})}})}catch(i){throw this.he=!1,i}}pe(e){for(var n of this.ve)try{if(!e.isLoaded)return n([],e);this.getSurveys(n)}catch(r){dt.error("Error in survey callback",r)}}getActiveMatchingSurveys(e,n){if(n===void 0&&(n=!1),!Je(this._surveyManager))return this._surveyManager.getActiveMatchingSurveys(e,n);dt.warn("init was not called")}ge(e){var n=null;return this.getSurveys((r=>{var i;n=(i=r.find((o=>o.id===e)))!==null&&i!==void 0?i:null})),n}_e(e){if(Je(this._surveyManager))return{eligible:!1,reason:"SDK is not enabled or survey functionality is not yet loaded"};var n=typeof e=="string"?this.ge(e):e;return n?this._surveyManager.checkSurveyEligibility(n):{eligible:!1,reason:"Survey not found"}}canRenderSurvey(e){if(Je(this._surveyManager))return dt.warn("init was not called"),{visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"};var n=this._e(e);return{visible:n.eligible,disabledReason:n.reason}}canRenderSurveyAsync(e,n){return Je(this._surveyManager)?(dt.warn("init was not called"),Promise.resolve({visible:!1,disabledReason:"SDK is not enabled or survey functionality is not yet loaded"})):new Promise((r=>{this.getSurveys((i=>{var o,s=(o=i.find((l=>l.id===e)))!==null&&o!==void 0?o:null;if(s){var a=this._e(s);r({visible:a.eligible,disabledReason:a.reason})}else r({visible:!1,disabledReason:"Survey not found"})}),n)}))}renderSurvey(e,n){var r;if(Je(this._surveyManager))dt.warn("init was not called");else{var i=typeof e=="string"?this.ge(e):e;if(i!=null&&i.id)if(VK.includes(i.type)){var o=me==null?void 0:me.querySelector(n);if(o)return(r=i.appearance)!=null&&r.surveyPopupDelaySeconds?(dt.info("Rendering survey "+i.id+" with delay of "+i.appearance.surveyPopupDelaySeconds+" seconds"),void setTimeout((()=>{var s,a;dt.info("Rendering survey "+i.id+" with delay of "+((s=i.appearance)==null?void 0:s.surveyPopupDelaySeconds)+" seconds"),(a=this._surveyManager)==null||a.renderSurvey(i,o),dt.info("Survey "+i.id+" rendered")}),1e3*i.appearance.surveyPopupDelaySeconds)):void this._surveyManager.renderSurvey(i,o);dt.warn("Survey element not found")}else dt.warn("Surveys of type "+i.type+" cannot be rendered in the app");else dt.warn("Survey not found")}}displaySurvey(e,n){var r;if(Je(this._surveyManager))dt.warn("init was not called");else{var i=this.ge(e);if(i){var o=i;if((r=i.appearance)!=null&&r.surveyPopupDelaySeconds&&n.ignoreDelay&&(o=be({},i,{appearance:be({},i.appearance,{surveyPopupDelaySeconds:0})})),n.ignoreConditions===!1){var s=this.canRenderSurvey(i);if(!s.visible)return void dt.warn("Survey is not eligible to be displayed: ",s.disabledReason)}n.displayType!==zI.Inline?this._surveyManager.handlePopoverSurvey(o):this.renderSurvey(o,n.selector)}else dt.warn("Survey not found")}}cancelPendingSurvey(e){Je(this._surveyManager)?dt.warn("init was not called"):this._surveyManager.cancelSurvey(e)}handlePageUnload(){var e;(e=this._surveyManager)==null||e.handlePageUnload()}}var ec=At("[Conversations]");class jK{constructor(e){this.me=void 0,this._conversationsManager=null,this.be=!1,this.ye=null,this._instance=e}onRemoteConfig(e){if(!this._instance.config.disable_conversations){var n=e.conversations;Je(n)||(Ai(n)?this.me=n:(this.me=n.enabled,this.ye=n),this.loadIfEnabled())}}reset(){var e;(e=this._conversationsManager)==null||e.reset(),this._conversationsManager=null,this.me=void 0,this.ye=null}loadIfEnabled(){if(!this._conversationsManager&&!this.be&&!(this._instance.config.disable_conversations||this._instance.config.cookieless_mode&&this._instance.consent.isOptedOut())){var e=ke==null?void 0:ke.__PosthogExtensions__;if(e&&!fe(this.me)&&this.me)if(this.ye&&this.ye.token){if((function(i){var o;if(!i||i.length===0)return!0;var s=oe==null||(o=oe.location)==null?void 0:o.hostname;return!s||i.some((a=>{var l=(function(u){var h=u.replace(/^https?:\/\//,"");return(h=h.split("/")[0].split("?")[0].split(":")[0])||null})(a);if(!l)return!1;if(l.startsWith("*.")){var c=l.slice(2);return s.endsWith("."+c)||s===c}return s===l}))})(this.ye.domains)){this.be=!0;try{var n=e.initConversations;if(n)return this.we(n),void(this.be=!1);var r=e.loadExternalDependency;if(!r)return void this.xe("PostHog loadExternalDependency extension not found.");r(this._instance,"conversations",(i=>{i||!e.initConversations?this.xe("Could not load conversations script",i):this.we(e.initConversations),this.be=!1}))}catch(i){this.xe("Error initializing conversations",i),this.be=!1}}}else ec.error("Conversations enabled but missing token in remote config.")}}we(e){if(this.ye)try{this._conversationsManager=e(this.ye,this._instance),ec.info("Conversations loaded successfully")}catch(n){this.xe("Error completing conversations initialization",n)}else ec.error("Cannot complete initialization: remote config is null")}xe(e,n){ec.error(e,n),this._conversationsManager=null,this.be=!1}enable(){this._conversationsManager?this._conversationsManager.enable():ec.warn("Conversations not loaded yet.")}disable(){this._conversationsManager&&this._conversationsManager.disable()}isLoaded(){return!Pr(this._conversationsManager)}isEnabled(){return this.me===!0}}var HI=At("[RateLimiter]");class qK{constructor(e){var n,r;this.serverLimits={},this.lastEventRateLimited=!1,this.checkForLimiting=i=>{var o=i.text;if(o&&o.length)try{(JSON.parse(o).quota_limited||[]).forEach((s=>{HI.info((s||"events")+" is quota limited."),this.serverLimits[s]=new Date().getTime()+6e4}))}catch(s){return void HI.warn('could not rate limit - continuing. Error: "'+(s==null?void 0:s.message)+'"',{text:o})}},this.instance=e,this.captureEventsPerSecond=((n=e.config.rate_limiting)==null?void 0:n.events_per_second)||10,this.captureEventsBurstLimit=Math.max(((r=e.config.rate_limiting)==null?void 0:r.events_burst_limit)||10*this.captureEventsPerSecond,this.captureEventsPerSecond),this.lastEventRateLimited=this.clientRateLimitContext(!0).isRateLimited}clientRateLimitContext(e){var n,r,i;e===void 0&&(e=!1);var o=new Date().getTime(),s=(n=(r=this.instance.persistence)==null?void 0:r.get_property(Gp))!==null&&n!==void 0?n:{tokens:this.captureEventsBurstLimit,last:o};s.tokens+=(o-s.last)/1e3*this.captureEventsPerSecond,s.last=o,s.tokens>this.captureEventsBurstLimit&&(s.tokens=this.captureEventsBurstLimit);var a=s.tokens<1;return a||e||(s.tokens=Math.max(0,s.tokens-1)),!a||this.lastEventRateLimited||e||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=a,(i=this.instance.persistence)==null||i.set_property(Gp,s),{isRateLimited:a,remainingTokens:s.tokens}}isServerRateLimited(e){var n=this.serverLimits[e||"events"]||!1;return n!==!1&&new Date().getTime()<n}}var Zo=At("[RemoteConfig]");class GK{constructor(e){this._instance=e}get remoteConfig(){var e;return(e=ke._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.config}Ee(e){var n,r;(n=ke.__PosthogExtensions__)!=null&&n.loadExternalDependency?(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,"remote-config",(()=>e(this.remoteConfig))):(Zo.error("PostHog Extensions not found. Cannot load remote config."),e())}$e(e){this._instance._send_request({method:"GET",url:this._instance.requestRouter.endpointFor("assets","/array/"+this._instance.config.token+"/config"),callback:n=>{e(n.json)}})}load(){try{if(this.remoteConfig)return Zo.info("Using preloaded remote config",this.remoteConfig),void this.pi(this.remoteConfig);if(this._instance.O())return void Zo.warn("Remote config is disabled. Falling back to local config.");this.Ee((e=>{if(!e)return Zo.info("No config found after loading remote JS config. Falling back to JSON."),void this.$e((n=>{this.pi(n)}));this.pi(e)}))}catch(e){Zo.error("Error loading remote config",e)}}pi(e){e?this._instance.config.__preview_remote_config?(this._instance.pi(e),e.hasFeatureFlags!==!1&&this._instance.featureFlags.ensureFlagsLoaded()):Zo.info("__preview_remote_config is disabled. Logging config instead",e):Zo.error("Failed to fetch remote config from PostHog.")}}var ym=3e3;class KK{constructor(e,n){this.Se=!0,this.ke=[],this.Pe=ti((n==null?void 0:n.flush_interval_ms)||ym,250,5e3,ye.createLogger("flush interval"),ym),this.Te=e}enqueue(e){this.ke.push(e),this.Ie||this.Ce()}unload(){this.Re();var e=this.ke.length>0?this.Fe():{},n=Object.values(e);[...n.filter((r=>r.url.indexOf("/e")===0)),...n.filter((r=>r.url.indexOf("/e")!==0))].map((r=>{this.Te(be({},r,{transport:"sendBeacon"}))}))}enable(){this.Se=!1,this.Ce()}Ce(){var e=this;this.Se||(this.Ie=setTimeout((()=>{if(this.Re(),this.ke.length>0){var n=this.Fe(),r=function(){var o=n[i],s=new Date().getTime();o.data&&Ze(o.data)&&ut(o.data,(a=>{a.offset=Math.abs(a.timestamp-s),delete a.timestamp})),e.Te(o)};for(var i in n)r()}}),this.Pe))}Re(){clearTimeout(this.Ie),this.Ie=void 0}Fe(){var e={};return ut(this.ke,(n=>{var r,i=n,o=(i?i.batchKey:null)||i.url;fe(e[o])&&(e[o]=be({},i,{data:[]})),(r=e[o].data)==null||r.push(i.data)})),this.ke=[],e}}var YK=["retriesPerformedSoFar"];class XK{constructor(e){this.Me=!1,this.Oe=3e3,this.ke=[],this._instance=e,this.ke=[],this.Ae=!0,!fe(oe)&&"onLine"in oe.navigator&&(this.Ae=oe.navigator.onLine,this.De=()=>{this.Ae=!0,this.Lt()},this.je=()=>{this.Ae=!1},Bt(oe,"online",this.De),Bt(oe,"offline",this.je))}get length(){return this.ke.length}retriableRequest(e){var{retriesPerformedSoFar:n}=e,r=YE(e,YK);ei(n)&&n>0&&(r.url=Fd(r.url,{retry_count:n})),this._instance._send_request(be({},r,{callback:i=>{i.statusCode!==200&&(i.statusCode<400||i.statusCode>=500)&&(n!=null?n:0)<10?this.Le(be({retriesPerformedSoFar:n},r)):r.callback==null||r.callback(i)}}))}Le(e){var n=e.retriesPerformedSoFar||0;e.retriesPerformedSoFar=n+1;var r=(function(s){var a=3e3*Math.pow(2,s),l=a/2,c=Math.min(18e5,a),u=(Math.random()-.5)*(c-l);return Math.ceil(c+u)})(n),i=Date.now()+r;this.ke.push({retryAt:i,requestOptions:e});var o="Enqueued failed request for retry in "+r;navigator.onLine||(o+=" (Browser is offline)"),ye.warn(o),this.Me||(this.Me=!0,this.Ne())}Ne(){if(this.Ue&&clearTimeout(this.Ue),this.ke.length===0)return this.Me=!1,void(this.Ue=void 0);this.Ue=setTimeout((()=>{this.Ae&&this.ke.length>0&&this.Lt(),this.Ne()}),this.Oe)}Lt(){var e=Date.now(),n=[],r=this.ke.filter((o=>o.retryAt<e||(n.push(o),!1)));if(this.ke=n,r.length>0)for(var{requestOptions:i}of r)this.retriableRequest(i)}unload(){for(var{requestOptions:e}of(this.Ue&&(clearTimeout(this.Ue),this.Ue=void 0),this.Me=!1,fe(oe)||(this.De&&(oe.removeEventListener("online",this.De),this.De=void 0),this.je&&(oe.removeEventListener("offline",this.je),this.je=void 0)),this.ke))try{this._instance._send_request(be({},e,{transport:"sendBeacon"}))}catch(n){ye.error(n)}this.ke=[]}}class ZK{constructor(e){this.ze=()=>{var n,r,i,o;this.He||(this.He={});var s=this.scrollElement(),a=this.scrollY(),l=s?Math.max(0,s.scrollHeight-s.clientHeight):0,c=a+((s==null?void 0:s.clientHeight)||0),u=(s==null?void 0:s.scrollHeight)||0;this.He.lastScrollY=Math.ceil(a),this.He.maxScrollY=Math.max(a,(n=this.He.maxScrollY)!==null&&n!==void 0?n:0),this.He.maxScrollHeight=Math.max(l,(r=this.He.maxScrollHeight)!==null&&r!==void 0?r:0),this.He.lastContentY=c,this.He.maxContentY=Math.max(c,(i=this.He.maxContentY)!==null&&i!==void 0?i:0),this.He.maxContentHeight=Math.max(u,(o=this.He.maxContentHeight)!==null&&o!==void 0?o:0)},this._instance=e}getContext(){return this.He}resetContext(){var e=this.He;return setTimeout(this.ze,0),e}startMeasuringScrollPosition(){Bt(oe,"scroll",this.ze,{capture:!0}),Bt(oe,"scrollend",this.ze,{capture:!0}),Bt(oe,"resize",this.ze)}scrollElement(){if(!this._instance.config.scroll_root_selector)return oe==null?void 0:oe.document.documentElement;var e=Ze(this._instance.config.scroll_root_selector)?this._instance.config.scroll_root_selector:[this._instance.config.scroll_root_selector];for(var n of e){var r=oe==null?void 0:oe.document.querySelector(n);if(r)return r}}scrollY(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollTop||0}return oe&&(oe.scrollY||oe.pageYOffset||oe.document.documentElement.scrollTop)||0}scrollX(){if(this._instance.config.scroll_root_selector){var e=this.scrollElement();return e&&e.scrollLeft||0}return oe&&(oe.scrollX||oe.pageXOffset||oe.document.documentElement.scrollLeft)||0}}var JK=t=>vI(t==null?void 0:t.config.mask_personal_data_properties,t==null?void 0:t.config.custom_personal_data_properties);class jI{constructor(e,n,r,i){this.Be=o=>{var s=this.qe();if(!s||s.sessionId!==o){var a={sessionId:o,props:this.We(this._instance)};this.Ge.register({[qp]:a})}},this._instance=e,this.Ve=n,this.Ge=r,this.We=i||JK,this.Ve.onSessionId(this.Be)}qe(){return this.Ge.props[qp]}getSetOnceProps(){var e,n=(e=this.qe())==null?void 0:e.props;return n?"r"in n?yI(n):{$referring_domain:n.referringDomain,$pathname:n.initialPathName,utm_source:n.utm_source,utm_campaign:n.utm_campaign,utm_medium:n.utm_medium,utm_content:n.utm_content,utm_term:n.utm_term}:{}}getSessionProps(){var e={};return ut($p(this.getSetOnceProps()),((n,r)=>{r==="$current_url"&&(r="url"),e["$session_entry_"+Cp(r)]=n})),e}}var bm=At("[SessionId]");class qI{on(e,n){return this.Je.on(e,n)}constructor(e,n,r){var i;if(this.Ke=[],this.Ye=void 0,this.Je=new vm,this.Xe=(u,h)=>Math.abs(u-h)>this.sessionTimeoutMs,!e.persistence)throw new Error("SessionIdManager requires a PostHogPersistence instance");if(e.config.cookieless_mode==="always")throw new Error('SessionIdManager cannot be used with cookieless_mode="always"');this.R=e.config,this.Ge=e.persistence,this.Qe=void 0,this.Ze=void 0,this._sessionStartTimestamp=null,this._sessionActivityTimestamp=null,this.tr=n||so,this.ir=r||so;var o=this.R.persistence_name||this.R.token,s=this.R.session_idle_timeout_seconds||1800;if(this._sessionTimeoutMs=1e3*ti(s,60,36e3,bm.createLogger("session_idle_timeout_seconds"),1800),e.register({$configured_session_timeout_ms:this._sessionTimeoutMs}),this.er(),this.rr="ph_"+o+"_window_id",this.sr="ph_"+o+"_primary_window_exists",this.nr()){var a=_n.W(this.rr),l=_n.W(this.sr);a&&!l?this.Qe=a:_n.V(this.rr),_n.G(this.sr,!0)}if((i=this.R.bootstrap)!=null&&i.sessionID)try{var c=(u=>{var h=u.replace(/-/g,"");if(h.length!==32)throw new Error("Not a valid UUID");if(h[12]!=="7")throw new Error("Not a UUIDv7");return parseInt(h.substring(0,12),16)})(this.R.bootstrap.sessionID);this.ar(this.R.bootstrap.sessionID,new Date().getTime(),c)}catch(u){bm.error("Invalid sessionID in bootstrap",u)}this.lr()}get sessionTimeoutMs(){return this._sessionTimeoutMs}onSessionId(e){return fe(this.Ke)&&(this.Ke=[]),this.Ke.push(e),this.Ze&&e(this.Ze,this.Qe),()=>{this.Ke=this.Ke.filter((n=>n!==e))}}nr(){return this.R.persistence!=="memory"&&!this.Ge.xi&&_n.H()}ur(e){e!==this.Qe&&(this.Qe=e,this.nr()&&_n.G(this.rr,e))}hr(){return this.Qe?this.Qe:this.nr()?_n.W(this.rr):null}ar(e,n,r){e===this.Ze&&n===this._sessionActivityTimestamp&&r===this._sessionStartTimestamp||(this._sessionStartTimestamp=r,this._sessionActivityTimestamp=n,this.Ze=e,this.Ge.register({[wd]:[n,e,r]}))}dr(){var e=this.Ge.props[wd];return Ze(e)&&e.length===2&&e.push(e[0]),e||[0,null,0]}resetSessionId(){this.ar(null,null,null)}destroy(){clearTimeout(this.vr),this.vr=void 0,this.Ye&&oe&&(oe.removeEventListener("beforeunload",this.Ye,{capture:!1}),this.Ye=void 0),this.Ke=[]}lr(){this.Ye=()=>{this.nr()&&_n.V(this.sr)},Bt(oe,"beforeunload",this.Ye,{capture:!1})}checkAndGetSessionAndWindowId(e,n){if(e===void 0&&(e=!1),n===void 0&&(n=null),this.R.cookieless_mode==="always")throw new Error('checkAndGetSessionAndWindowId should not be called with cookieless_mode="always"');var r=n||new Date().getTime(),[i,o,s]=this.dr(),a=this.hr(),l=ei(s)&&s>0&&Math.abs(r-s)>864e5,c=!1,u=!o,h=!u&&!e&&this.Xe(r,i);u||h||l?(o=this.tr(),a=this.ir(),bm.info("new session ID generated",{sessionId:o,windowId:a,changeReason:{noSessionId:u,activityTimeout:h,sessionPastMaximumLength:l}}),s=r,c=!0):a||(a=this.ir(),c=!0);var p=i===0||!e||l?r:i,g=s===0?new Date().getTime():s;return this.ur(a),this.ar(o,p,g),e||this.er(),c&&this.Ke.forEach((b=>b(o,a,c?{noSessionId:u,activityTimeout:h,sessionPastMaximumLength:l}:void 0))),{sessionId:o,windowId:a,sessionStartTimestamp:g,changeReason:c?{noSessionId:u,activityTimeout:h,sessionPastMaximumLength:l}:void 0,lastActivityTimestamp:i}}er(){clearTimeout(this.vr),this.vr=setTimeout((()=>{var[e]=this.dr();if(this.Xe(new Date().getTime(),e)){var n=this.Ze;this.resetSessionId(),this.Je.emit("forcedIdleReset",{idleSessionId:n})}}),1.1*this.sessionTimeoutMs)}}var QK=["$set_once","$set"],co=At("[SiteApps]");class eY{constructor(e){this._instance=e,this.cr=[],this.apps={}}get isEnabled(){return!!this._instance.config.opt_in_site_apps}pr(e,n){if(n){var r=this.globalsForEvent(n);this.cr.push(r),this.cr.length>1e3&&(this.cr=this.cr.slice(10))}}get siteAppLoaders(){var e;return(e=ke._POSTHOG_REMOTE_CONFIG)==null||(e=e[this._instance.config.token])==null?void 0:e.siteApps}init(){if(this.isEnabled){var e=this._instance.Ni(this.pr.bind(this));this.gr=()=>{e(),this.cr=[],this.gr=void 0}}}globalsForEvent(e){var n,r,i,o,s,a,l;if(!e)throw new Error("Event payload is required");var c={},u=this._instance.get_property("$groups")||[],h=this._instance.get_property("$stored_group_properties")||{};for(var[p,g]of Object.entries(h))c[p]={id:u[p],type:p,properties:g};var{$set_once:b,$set:m}=e;return{event:be({},YE(e,QK),{properties:be({},e.properties,m?{$set:be({},(n=(r=e.properties)==null?void 0:r.$set)!==null&&n!==void 0?n:{},m)}:{},b?{$set_once:be({},(i=(o=e.properties)==null?void 0:o.$set_once)!==null&&i!==void 0?i:{},b)}:{}),elements_chain:(s=(a=e.properties)==null?void 0:a.$elements_chain)!==null&&s!==void 0?s:"",distinct_id:(l=e.properties)==null?void 0:l.distinct_id}),person:{properties:this._instance.get_property("$stored_person_properties")},groups:c}}setupSiteApp(e){var n=this.apps[e.id],r=()=>{var a;!n.errored&&this.cr.length&&(co.info("Processing "+this.cr.length+" events for site app with id "+e.id),this.cr.forEach((l=>n.processEvent==null?void 0:n.processEvent(l))),n.processedBuffer=!0),Object.values(this.apps).every((l=>l.processedBuffer||l.errored))&&((a=this.gr)==null||a.call(this))},i=!1,o=a=>{n.errored=!a,n.loaded=!0,co.info("Site app with id "+e.id+" "+(a?"loaded":"errored")),i&&r()};try{var{processEvent:s}=e.init({posthog:this._instance,callback:a=>{o(a)}});s&&(n.processEvent=s),i=!0}catch(a){co.error("Error while initializing PostHog app with config id "+e.id,a),o(!1)}if(i&&n.loaded)try{r()}catch(a){co.error("Error while processing buffered events PostHog app with config id "+e.id,a),n.errored=!0}}_r(){var e=this.siteAppLoaders||[];for(var n of e)this.apps[n.id]={id:n.id,loaded:!1,errored:!1,processedBuffer:!1};for(var r of e)this.setupSiteApp(r)}mr(e){if(Object.keys(this.apps).length!==0){var n=this.globalsForEvent(e);for(var r of Object.values(this.apps))try{r.processEvent==null||r.processEvent(n)}catch(i){co.error("Error while processing event "+e.event+" for site app "+r.id,i)}}}onRemoteConfig(e){var n,r,i,o=this;if((n=this.siteAppLoaders)!=null&&n.length)return this.isEnabled?(this._r(),void this._instance.on("eventCaptured",(c=>this.mr(c)))):void co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.');if((r=this.gr)==null||r.call(this),(i=e.siteApps)!=null&&i.length)if(this.isEnabled){var s=function(c){var u;ke["__$$ph_site_app_"+c]=o._instance,(u=ke.__PosthogExtensions__)==null||u.loadSiteApp==null||u.loadSiteApp(o._instance,l,(h=>{if(h)return co.error("Error while initializing PostHog app with config id "+c,h)}))};for(var{id:a,url:l}of e.siteApps)s(a)}else co.error('PostHog site apps are disabled. Enable the "opt_in_site_apps" config to proceed.')}}var GI=function(t,e){if(!t)return!1;var n=t.userAgent;if(n&&XE(n,e))return!0;try{var r=t==null?void 0:t.userAgentData;if(r!=null&&r.brands&&r.brands.some((i=>XE(i==null?void 0:i.brand,e))))return!0}catch(i){}return!!t.webdriver},tc=(function(t){return t.US="us",t.EU="eu",t.CUSTOM="custom",t})({}),KI="i.posthog.com";class tY{constructor(e){this.br={},this.instance=e}get apiHost(){var e=this.instance.config.api_host.trim().replace(/\/$/,"");return e==="https://app.posthog.com"?"https://us.i.posthog.com":e}get flagsApiHost(){var e=this.instance.config.flags_api_host;return e?e.trim().replace(/\/$/,""):this.apiHost}get uiHost(){var e,n=(e=this.instance.config.ui_host)==null?void 0:e.replace(/\/$/,"");return n||(n=this.apiHost.replace("."+KI,".posthog.com")),n==="https://app.posthog.com"?"https://us.posthog.com":n}get region(){return this.br[this.apiHost]||(/https:\/\/(app|us|us-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.br[this.apiHost]=tc.US:/https:\/\/(eu|eu-assets)(\.i)?\.posthog\.com/i.test(this.apiHost)?this.br[this.apiHost]=tc.EU:this.br[this.apiHost]=tc.CUSTOM),this.br[this.apiHost]}endpointFor(e,n){if(n===void 0&&(n=""),n&&(n=n[0]==="/"?n:"/"+n),e==="ui")return this.uiHost+n;if(e==="flags")return this.flagsApiHost+n;if(this.region===tc.CUSTOM)return this.apiHost+n;var r=KI+n;switch(e){case"assets":return"https://"+this.region+"-assets."+r;case"api":return"https://"+this.region+"."+r}}}var nY={icontains:(t,e)=>!!oe&&e.href.toLowerCase().indexOf(t.toLowerCase())>-1,not_icontains:(t,e)=>!!oe&&e.href.toLowerCase().indexOf(t.toLowerCase())===-1,regex:(t,e)=>!!oe&&Vd(e.href,t),not_regex:(t,e)=>!!oe&&!Vd(e.href,t),exact:(t,e)=>e.href===t,is_not:(t,e)=>e.href!==t};class Tn{constructor(e){var n=this;this.getWebExperimentsAndEvaluateDisplayLogic=function(r){r===void 0&&(r=!1),n.getWebExperiments((i=>{Tn.yr("retrieved web experiments from the server"),n.wr=new Map,i.forEach((o=>{if(o.feature_flag_key){var s;n.wr&&(Tn.yr("setting flag key ",o.feature_flag_key," to web experiment ",o),(s=n.wr)==null||s.set(o.feature_flag_key,o));var a=n._instance.getFeatureFlag(o.feature_flag_key);nn(a)&&o.variants[a]&&n.Er(o.name,a,o.variants[a].transforms)}else if(o.variants)for(var l in o.variants){var c=o.variants[l];Tn.$r(c)&&n.Er(o.name,l,c.transforms)}}))}),r)},this._instance=e,this._instance.onFeatureFlags((r=>{this.onFeatureFlags(r)}))}onFeatureFlags(e){if(this._is_bot())Tn.yr("Refusing to render web experiment since the viewer is a likely bot");else if(!this._instance.config.disable_web_experiments){if(Je(this.wr))return this.wr=new Map,this.loadIfEnabled(),void this.previewWebExperiment();Tn.yr("applying feature flags",e),e.forEach((n=>{var r;if(this.wr&&(r=this.wr)!=null&&r.has(n)){var i,o=this._instance.getFeatureFlag(n),s=(i=this.wr)==null?void 0:i.get(n);o&&s!=null&&s.variants[o]&&this.Er(s.name,o,s.variants[o].transforms)}}))}}previewWebExperiment(){var e=Tn.getWindowLocation();if(e!=null&&e.search){var n=kd(e==null?void 0:e.search,"__experiment_id"),r=kd(e==null?void 0:e.search,"__experiment_variant");n&&r&&(Tn.yr("previewing web experiments "+n+" && "+r),this.getWebExperiments((i=>{this.Sr(parseInt(n),r,i)}),!1,!0))}}loadIfEnabled(){this._instance.config.disable_web_experiments||this.getWebExperimentsAndEvaluateDisplayLogic()}getWebExperiments(e,n,r){if(this._instance.config.disable_web_experiments&&!r)return e([]);var i=this._instance.get_property("$web_experiments");if(i&&!n)return e(i);this._instance._send_request({url:this._instance.requestRouter.endpointFor("api","/api/web_experiments/?token="+this._instance.config.token),method:"GET",callback:o=>{if(o.statusCode!==200||!o.json)return e([]);var s=o.json.experiments||[];return e(s)}})}Sr(e,n,r){var i=r.filter((o=>o.id===e));i&&i.length>0&&(Tn.yr("Previewing web experiment ["+i[0].name+"] with variant ["+n+"]"),this.Er(i[0].name,n,i[0].variants[n].transforms))}static $r(e){return!Je(e.conditions)&&Tn.kr(e)&&Tn.Pr(e)}static kr(e){var n;if(Je(e.conditions)||Je((n=e.conditions)==null?void 0:n.url))return!0;var r,i,o,s=Tn.getWindowLocation();return!!s&&((r=e.conditions)==null||!r.url||nY[(i=(o=e.conditions)==null?void 0:o.urlMatchType)!==null&&i!==void 0?i:"icontains"](e.conditions.url,s))}static getWindowLocation(){return oe==null?void 0:oe.location}static Pr(e){var n;if(Je(e.conditions)||Je((n=e.conditions)==null?void 0:n.utm))return!0;var r=hI();if(r.utm_source){var i,o,s,a,l,c,u,h,p=(i=e.conditions)==null||(i=i.utm)==null||!i.utm_campaign||((o=e.conditions)==null||(o=o.utm)==null?void 0:o.utm_campaign)==r.utm_campaign,g=(s=e.conditions)==null||(s=s.utm)==null||!s.utm_source||((a=e.conditions)==null||(a=a.utm)==null?void 0:a.utm_source)==r.utm_source,b=(l=e.conditions)==null||(l=l.utm)==null||!l.utm_medium||((c=e.conditions)==null||(c=c.utm)==null?void 0:c.utm_medium)==r.utm_medium,m=(u=e.conditions)==null||(u=u.utm)==null||!u.utm_term||((h=e.conditions)==null||(h=h.utm)==null?void 0:h.utm_term)==r.utm_term;return p&&b&&m&&g}return!1}static yr(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];ye.info("[WebExperiments] "+e,r)}Er(e,n,r){this._is_bot()?Tn.yr("Refusing to render web experiment since the viewer is a likely bot"):n!=="control"?r.forEach((i=>{if(i.selector){var o;Tn.yr("applying transform of variant "+n+" for experiment "+e+" ",i);var s=(o=document)==null?void 0:o.querySelectorAll(i.selector);s==null||s.forEach((a=>{var l=a;i.html&&(l.innerHTML=i.html),i.css&&l.setAttribute("style",i.css)}))}})):Tn.yr("Control variants leave the page unmodified.")}_is_bot(){return ur&&this._instance?GI(ur,this._instance.config.custom_blocked_useragents):void 0}}var rY=At("[PostHog ExternalIntegrations]"),iY={intercom:"intercom-integration",crispChat:"crisp-chat-integration"};class oY{constructor(e){this._instance=e}it(e,n){var r;(r=ke.__PosthogExtensions__)==null||r.loadExternalDependency==null||r.loadExternalDependency(this._instance,e,(i=>{if(i)return rY.error("failed to load script",i);n()}))}startIfEnabledOrStop(){var e=this,n=function(s){var a,l,c;!i||(a=ke.__PosthogExtensions__)!=null&&(a=a.integrations)!=null&&a[s]||e.it(iY[s],(()=>{var u;(u=ke.__PosthogExtensions__)==null||(u=u.integrations)==null||(u=u[s])==null||u.start(e._instance)})),!i&&(l=ke.__PosthogExtensions__)!=null&&(l=l.integrations)!=null&&l[s]&&((c=ke.__PosthogExtensions__)==null||(c=c.integrations)==null||(c=c[s])==null||c.stop())};for(var[r,i]of Object.entries((o=this._instance.config.integrations)!==null&&o!==void 0?o:{})){var o;n(r)}}}var _m="[SessionRecording]",nc=At(_m);class YI{get started(){var e;return!((e=this.Tr)==null||!e.isStarted)}get status(){return this.Tr?this.Tr.status:this.Ir&&!this.Cr?"disabled":"lazy_loading"}constructor(e){if(this._forceAllowLocalhostNetworkCapture=!1,this.Ir=!1,this.Rr=void 0,this._instance=e,!this._instance.sessionManager)throw nc.error("started without valid sessionManager"),new Error(_m+" started without valid sessionManager. This is a bug.");if(this._instance.config.cookieless_mode==="always")throw new Error(_m+' cannot be used with cookieless_mode="always"')}get Cr(){var e,n=!((e=this._instance.get_property(Wp))==null||!e.enabled),r=!this._instance.config.disable_session_recording,i=this._instance.config.disable_session_recording||this._instance.consent.isOptedOut();return oe&&n&&r&&!i}startIfEnabledOrStop(e){var n;if(!this.Cr||(n=this.Tr)==null||!n.isStarted){var r=!fe(Object.assign)&&!fe(Array.from);this.Cr&&r?(this.Fr(e),nc.info("starting")):this.stopRecording()}}Fr(e){var n,r,i;this.Cr&&(ke!=null&&(n=ke.__PosthogExtensions__)!=null&&(n=n.rrweb)!=null&&n.record&&(r=ke.__PosthogExtensions__)!=null&&r.initSessionRecording?this.Mr(e):(i=ke.__PosthogExtensions__)==null||i.loadExternalDependency==null||i.loadExternalDependency(this._instance,this.Or,(o=>{if(o)return nc.error("could not load recorder",o);this.Mr(e)})))}stopRecording(){var e,n;(e=this.Rr)==null||e.call(this),this.Rr=void 0,(n=this.Tr)==null||n.stop()}Ar(){var e;(e=this._instance.persistence)==null||e.unregister(BS)}Dr(e){if(this._instance.persistence){var n,r,i=this._instance.persistence,o=()=>{var s=e.sessionRecording===!1?void 0:e.sessionRecording,a=s==null?void 0:s.sampleRate,l=Je(a)?null:parseFloat(a);Je(l)&&this.Ar();var c=s==null?void 0:s.minimumDurationMilliseconds;i.register({[Wp]:be({enabled:!!s},s,{networkPayloadCapture:be({capturePerformance:e.capturePerformance},s==null?void 0:s.networkPayloadCapture),canvasRecording:{enabled:s==null?void 0:s.recordCanvas,fps:s==null?void 0:s.canvasFps,quality:s==null?void 0:s.canvasQuality},sampleRate:l,minimumDurationMilliseconds:fe(c)?null:c,endpoint:s==null?void 0:s.endpoint,triggerMatchType:s==null?void 0:s.triggerMatchType,masking:s==null?void 0:s.masking,urlTriggers:s==null?void 0:s.urlTriggers})})};o(),(n=this.Rr)==null||n.call(this),this.Rr=(r=this._instance.sessionManager)==null?void 0:r.onSessionId(o)}}onRemoteConfig(e){"sessionRecording"in e?e.sessionRecording!==!1?(this.Dr(e),this.Ir=!0,this.startIfEnabledOrStop()):this.Ir=!0:nc.info("skipping remote config with no sessionRecording",e)}log(e,n){var r;n===void 0&&(n="log"),(r=this.Tr)!=null&&r.log?this.Tr.log(e,n):nc.warn("log called before recorder was ready")}get Or(){var e,n,r=(e=this._instance)==null||(e=e.persistence)==null?void 0:e.get_property(Wp);return(r==null||(n=r.scriptConfig)==null?void 0:n.script)||"lazy-recorder"}Mr(e){var n,r;if((n=ke.__PosthogExtensions__)==null||!n.initSessionRecording)throw Error("Called on script loaded before session recording is available");this.Tr||(this.Tr=(r=ke.__PosthogExtensions__)==null?void 0:r.initSessionRecording(this._instance),this.Tr._forceAllowLocalhostNetworkCapture=this._forceAllowLocalhostNetworkCapture),this.Tr.start(e)}onRRwebEmit(e){var n;(n=this.Tr)==null||n.onRRwebEmit==null||n.onRRwebEmit(e)}overrideLinkedFlag(){var e,n;this.Tr||(n=this._instance.persistence)==null||n.register({$replay_override_linked_flag:!0}),(e=this.Tr)==null||e.overrideLinkedFlag()}overrideSampling(){var e,n;this.Tr||(n=this._instance.persistence)==null||n.register({$replay_override_sampling:!0}),(e=this.Tr)==null||e.overrideSampling()}overrideTrigger(e){var n,r;this.Tr||(r=this._instance.persistence)==null||r.register({[e==="url"?"$replay_override_url_trigger":"$replay_override_event_trigger"]:!0}),(n=this.Tr)==null||n.overrideTrigger(e)}get sdkDebugProperties(){var e;return((e=this.Tr)==null?void 0:e.sdkDebugProperties)||{$recording_status:this.status}}tryAddCustomEvent(e,n){var r;return!((r=this.Tr)==null||!r.tryAddCustomEvent(e,n))}}var rc={},xm=()=>{},ha="posthog",XI=!RK&&(qn==null?void 0:qn.indexOf("MSIE"))===-1&&(qn==null?void 0:qn.indexOf("Mozilla"))===-1,ZI=t=>{var e;return be({api_host:"https://us.i.posthog.com",flags_api_host:null,ui_host:null,token:"",autocapture:!0,cross_subdomain_cookie:MG(me==null?void 0:me.location),persistence:"localStorage+cookie",persistence_name:"",loaded:xm,save_campaign_params:!0,custom_campaign_params:[],custom_blocked_useragents:[],save_referrer:!0,capture_pageleave:"if_capture_pageview",defaults:t!=null?t:"unset",__preview_deferred_init_extensions:!1,debug:jn&&nn(jn==null?void 0:jn.search)&&jn.search.indexOf("__posthog_debug=true")!==-1||!1,cookie_expiration:365,upgrade:!1,disable_session_recording:!1,disable_persistence:!1,disable_web_experiments:!0,disable_surveys:!1,disable_surveys_automatic_display:!1,disable_conversations:!1,disable_product_tours:!0,disable_external_dependency_loading:!1,enable_recording_console_log:void 0,secure_cookie:(oe==null||(e=oe.location)==null?void 0:e.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:n=>{var r="Bad HTTP status: "+n.statusCode+" "+n.text;ye.error(r)},get_device_id:n=>n,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:ym},error_tracking:{},_onCapture:xm,__preview_eager_load_replay:!1},(n=>({rageclick:!(n&&n>="2025-11-30")||{content_ignorelist:!0},capture_pageview:!(n&&n>="2025-05-24")||"history_change",session_recording:n&&n>="2025-11-30"?{strictMinimumDuration:!0}:{}}))(t))},JI=t=>{var e={};fe(t.process_person)||(e.person_profiles=t.process_person),fe(t.xhr_headers)||(e.request_headers=t.xhr_headers),fe(t.cookie_name)||(e.persistence_name=t.cookie_name),fe(t.disable_cookie)||(e.disable_persistence=t.disable_cookie),fe(t.store_google)||(e.save_campaign_params=t.store_google),fe(t.verbose)||(e.debug=t.verbose);var n=Ot({},e,t);return Ze(t.property_blacklist)&&(fe(t.property_denylist)?n.property_denylist=t.property_blacklist:Ze(t.property_denylist)?n.property_denylist=[...t.property_blacklist,...t.property_denylist]:ye.error("Invalid value for property_denylist config: "+t.property_denylist)),n};class sY{constructor(){this.__forceAllowLocalhost=!1}get jr(){return this.__forceAllowLocalhost}set jr(e){ye.error("WebPerformanceObserver is deprecated and has no impact on network capture. Use `_forceAllowLocalhostNetworkCapture` on `posthog.sessionRecording`"),this.__forceAllowLocalhost=e}}class Ud{get decideEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}get flagsEndpointWasHit(){var e,n;return(e=(n=this.featureFlags)==null?void 0:n.hasLoadedFlags)!==null&&e!==void 0&&e}constructor(){this.webPerformance=new sY,this.Lr=!1,this.version=Ci.LIB_VERSION,this.Nr=new vm,this._calculate_event_properties=this.calculateEventProperties.bind(this),this.config=ZI(),this.SentryIntegration=uK,this.sentryIntegration=e=>(function(n,r){var i=cI(n,r);return{name:lI,processEvent:o=>i(o)}})(this,e),this.__request_queue=[],this.__loaded=!1,this.analyticsDefaultEndpoint="/e/",this.Ur=!1,this.zr=null,this.Hr=null,this.Br=null,this.featureFlags=new MK(this),this.toolbar=new hK(this),this.scrollManager=new ZK(this),this.pageViewManager=new wK(this),this.surveys=new HK(this),this.conversations=new jK(this),this.experiments=new Tn(this),this.exceptions=new NK(this),this.rateLimiter=new qK(this),this.requestRouter=new tY(this),this.consent=new iK(this),this.externalIntegrations=new oY(this),this.people={set:(e,n,r)=>{var i=nn(e)?{[e]:n}:e;this.setPersonProperties(i),r==null||r({})},set_once:(e,n,r)=>{var i=nn(e)?{[e]:n}:e;this.setPersonProperties(void 0,i),r==null||r({})}},this.on("eventCaptured",(e=>ye.info('send "'+(e==null?void 0:e.event)+'"',e)))}init(e,n,r){if(r&&r!==ha){var i,o=(i=rc[r])!==null&&i!==void 0?i:new Ud;return o._init(e,n,r),rc[r]=o,rc[ha][r]=o,o}return this._init(e,n,r)}_init(e,n,r){var i;if(n===void 0&&(n={}),fe(e)||Ap(e))return ye.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={},n.debug=this.qr(n.debug),this.Wr=n,this.Gr=[],n.person_profiles&&(this.Hr=n.person_profiles),this.set_config(Ot({},ZI(n.defaults),JI(n),{name:r,token:e})),this.config.on_xhr_error&&ye.error("on_xhr_error is deprecated. Use on_request_error instead"),this.compression=n.disable_compression?void 0:Ti.GZipJS;var o=this.Vr();this.persistence=new gm(this.config,o),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new gm(be({},this.config,{persistence:"sessionStorage"}),o);var s=be({},this.persistence.props),a=be({},this.sessionPersistence.props);this.register({$initialization_time:new Date().toISOString()}),this.Jr=new KK((N=>this.Kr(N)),this.config.request_queue_config),this.Yr=new XK(this),this.__request_queue=[];var l=this.config.cookieless_mode==="always"||this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut();if(l||(this.sessionManager=new qI(this),this.sessionPropsManager=new jI(this,this.sessionManager,this.persistence)),this.config.__preview_deferred_init_extensions?(ye.info("Deferring extension initialization to improve startup performance"),setTimeout((()=>{this.Xr(l)}),0)):(ye.info("Initializing extensions synchronously"),this.Xr(l)),Ci.DEBUG=Ci.DEBUG||this.config.debug,Ci.DEBUG&&ye.info("Starting in debug mode",{this:this,config:n,thisC:be({},this.config),p:s,s:a}),((i=n.bootstrap)==null?void 0:i.distinctID)!==void 0){var c,u,h=this.config.get_device_id(so()),p=(c=n.bootstrap)!=null&&c.isIdentifiedID?h:n.bootstrap.distinctID;this.persistence.set_property(ki,(u=n.bootstrap)!=null&&u.isIdentifiedID?"identified":"anonymous"),this.register({distinct_id:n.bootstrap.distinctID,$device_id:p})}if(this.Qr()){var g,b,m=Object.keys(((g=n.bootstrap)==null?void 0:g.featureFlags)||{}).filter((N=>{var T;return!((T=n.bootstrap)==null||(T=T.featureFlags)==null||!T[N])})).reduce(((N,T)=>{var $;return N[T]=(($=n.bootstrap)==null||($=$.featureFlags)==null?void 0:$[T])||!1,N}),{}),x=Object.keys(((b=n.bootstrap)==null?void 0:b.featureFlagPayloads)||{}).filter((N=>m[N])).reduce(((N,T)=>{var $,B;return($=n.bootstrap)!=null&&($=$.featureFlagPayloads)!=null&&$[T]&&(N[T]=(B=n.bootstrap)==null||(B=B.featureFlagPayloads)==null?void 0:B[T]),N}),{});this.featureFlags.receivedFeatureFlags({featureFlags:m,featureFlagPayloads:x})}if(l)this.register_once({distinct_id:$l,$device_id:null},"");else if(!this.get_distinct_id()){var I=this.config.get_device_id(so());this.register_once({distinct_id:I,$device_id:I},""),this.persistence.set_property(ki,"anonymous")}return Bt(oe,"onpagehide"in self?"pagehide":"unload",this._handle_unload.bind(this),{passive:!1}),this.toolbar.maybeLoadToolbar(),n.segment?cK(this,(()=>this.Zr())):this.Zr(),ro(this.config._onCapture)&&this.config._onCapture!==xm&&(ye.warn("onCapture is deprecated. Please use `before_send` instead"),this.on("eventCaptured",(N=>this.config._onCapture(N.event,N)))),this.config.ip&&ye.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}Xr(e){var n=performance.now();this.historyAutocapture=new lK(this),this.historyAutocapture.startIfEnabled();var r=[];r.push((()=>{new gK(this).startIfEnabledOrStop()})),r.push((()=>{var i;this.siteApps=new eY(this),(i=this.siteApps)==null||i.init()})),e||r.push((()=>{this.sessionRecording=new YI(this),this.sessionRecording.startIfEnabledOrStop()})),this.config.disable_scroll_properties||r.push((()=>{this.scrollManager.startMeasuringScrollPosition()})),r.push((()=>{this.autocapture=new XG(this),this.autocapture.startIfEnabled()})),r.push((()=>{this.surveys.loadIfEnabled()})),r.push((()=>{this.conversations.loadIfEnabled()})),r.push((()=>{this.productTours=new FK(this),this.productTours.loadIfEnabled()})),r.push((()=>{this.heatmaps=new xK(this),this.heatmaps.startIfEnabled()})),r.push((()=>{this.webVitalsAutocapture=new bK(this)})),r.push((()=>{this.exceptionObserver=new aK(this),this.exceptionObserver.startIfEnabledOrStop()})),r.push((()=>{this.deadClicksAutocapture=new sI(this,sK),this.deadClicksAutocapture.startIfEnabled()})),r.push((()=>{if(this.ts){var i=this.ts;this.ts=void 0,this.pi(i)}})),this.es(r,n)}es(e,n){for(;e.length>0;){if(this.config.__preview_deferred_init_extensions&&performance.now()-n>=30&&e.length>0)return void setTimeout((()=>{this.es(e,n)}),0);var r=e.shift();if(r)try{r()}catch(o){ye.error("Error initializing extension:",o)}}var i=Math.round(performance.now()-n);this.register_for_session({$sdk_debug_extensions_init_method:this.config.__preview_deferred_init_extensions?"deferred":"synchronous",$sdk_debug_extensions_init_time_ms:i}),this.config.__preview_deferred_init_extensions&&ye.info("PostHog extensions initialized ("+i+"ms)")}pi(e){var n,r,i,o,s,a,l,c,u;if(!me||!me.body)return ye.info("document not ready yet, trying again in 500 milliseconds..."),void setTimeout((()=>{this.pi(e)}),500);this.config.__preview_deferred_init_extensions&&(this.ts=e),this.compression=void 0,e.supportedCompression&&!this.config.disable_compression&&(this.compression=Ue(e.supportedCompression,Ti.GZipJS)?Ti.GZipJS:Ue(e.supportedCompression,Ti.Base64)?Ti.Base64:void 0),(n=e.analytics)!=null&&n.endpoint&&(this.analyticsDefaultEndpoint=e.analytics.endpoint),this.set_config({person_profiles:this.Hr?this.Hr:"identified_only"}),(r=this.siteApps)==null||r.onRemoteConfig(e),(i=this.sessionRecording)==null||i.onRemoteConfig(e),(o=this.autocapture)==null||o.onRemoteConfig(e),(s=this.heatmaps)==null||s.onRemoteConfig(e),this.surveys.onRemoteConfig(e),this.conversations.onRemoteConfig(e),(a=this.productTours)==null||a.onRemoteConfig(e),(l=this.webVitalsAutocapture)==null||l.onRemoteConfig(e),(c=this.exceptionObserver)==null||c.onRemoteConfig(e),this.exceptions.onRemoteConfig(e),(u=this.deadClicksAutocapture)==null||u.onRemoteConfig(e)}Zr(){try{this.config.loaded(this)}catch(e){ye.critical("`loaded` function failed",e)}this.rs(),this.config.capture_pageview&&setTimeout((()=>{(this.consent.isOptedIn()||this.config.cookieless_mode==="always")&&this.ss()}),1),new GK(this).load(),this.featureFlags.flags()}rs(){var e;this.is_capturing()&&this.config.request_batching&&((e=this.Jr)==null||e.enable())}_dom_loaded(){this.is_capturing()&&io(this.__request_queue,(e=>this.Kr(e))),this.__request_queue=[],this.rs()}_handle_unload(){var e,n;this.surveys.handlePageUnload(),this.config.request_batching?(this.ns()&&this.capture("$pageleave"),(e=this.Jr)==null||e.unload(),(n=this.Yr)==null||n.unload()):this.ns()&&this.capture("$pageleave",null,{transport:"sendBeacon"})}_send_request(e){this.__loaded&&(XI?this.__request_queue.push(e):this.rateLimiter.isServerRateLimited(e.batchKey)||(e.transport=e.transport||this.config.api_transport,e.url=Fd(e.url,{ip:this.config.ip?1:0}),e.headers=be({},this.config.request_headers,e.headers),e.compression=e.compression==="best-available"?this.compression:e.compression,e.disableXHRCredentials=this.config.__preview_disable_xhr_credentials,this.config.__preview_disable_beacon&&(e.disableTransport=["sendBeacon"]),e.fetchOptions=e.fetchOptions||this.config.fetch_options,(n=>{var r,i,o,s=be({},n);s.timeout=s.timeout||6e4,s.url=Fd(s.url,{_:new Date().getTime().toString(),ver:Ci.LIB_VERSION,compression:s.compression});var a=(r=s.transport)!==null&&r!==void 0?r:"fetch",l=Dd.filter((u=>!s.disableTransport||!u.transport||!s.disableTransport.includes(u.transport))),c=(i=(o=AS(l,(u=>u.transport===a)))==null?void 0:o.method)!==null&&i!==void 0?i:l[0].method;if(!c)throw new Error("No available transport method");c(s)})(be({},e,{callback:n=>{var r,i;this.rateLimiter.checkForLimiting(n),n.statusCode>=400&&((r=(i=this.config).on_request_error)==null||r.call(i,n)),e.callback==null||e.callback(n)}}))))}Kr(e){this.Yr?this.Yr.retriableRequest(e):this._send_request(e)}_execute_array(e){var n,r=[],i=[],o=[];io(e,(a=>{a&&(n=a[0],Ze(n)?o.push(a):ro(a)?a.call(this):Ze(a)&&n==="alias"?r.push(a):Ze(a)&&n.indexOf("capture")!==-1&&ro(this[n])?o.push(a):i.push(a))}));var s=function(a,l){io(a,(function(c){if(Ze(c[0])){var u=l;ut(c,(function(h){u=u[h[0]].apply(u,h.slice(1))}))}else this[c[0]].apply(this,c.slice(1))}),l)};s(r,this),s(i,this),s(o,this)}Qr(){var e,n;return((e=this.config.bootstrap)==null?void 0:e.featureFlags)&&Object.keys((n=this.config.bootstrap)==null?void 0:n.featureFlags).length>0||!1}push(e){this._execute_array([e])}capture(e,n,r){var i;if(this.__loaded&&this.persistence&&this.sessionPersistence&&this.Jr){if(this.is_capturing())if(!fe(e)&&nn(e)){var o=!this.config.opt_out_useragent_filter&&this._is_bot();if(!(o&&!this.config.__preview_capture_bot_pageviews)){var s=r!=null&&r.skip_client_rate_limiting?void 0:this.rateLimiter.clientRateLimitContext();if(s==null||!s.isRateLimited){n!=null&&n.$current_url&&!nn(n==null?void 0:n.$current_url)&&(ye.error("Invalid `$current_url` property provided to `posthog.capture`. Input must be a string. Ignoring provided value."),n==null||delete n.$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 a=new Date,l=(r==null?void 0:r.timestamp)||a,c=so(),u={uuid:c,event:e,properties:this.calculateEventProperties(e,n||{},l,c)};e==="$pageview"&&this.config.__preview_capture_bot_pageviews&&o&&(u.event="$bot_pageview",u.properties.$browser_type="bot"),s&&(u.properties.$lib_rate_limit_remaining_tokens=s.remainingTokens),r!=null&&r.$set&&(u.$set=r==null?void 0:r.$set);var h,p=e!=="$groupidentify",g=this.os(r==null?void 0:r.$set_once,p);if(g&&(u.$set_once=g),(u=PG(u,r!=null&&r._noTruncate?null:this.config.properties_string_max_length)).timestamp=l,fe(r==null?void 0:r.timestamp)||(u.properties.$event_time_override_provided=!0,u.properties.$event_time_override_system_time=a),e===zd.DISMISSED||e===zd.SENT){var b=n==null?void 0:n[$I.SURVEY_ID],m=n==null?void 0:n[$I.SURVEY_ITERATION];h={id:b,current_iteration:m},localStorage.getItem(WI(h))||localStorage.setItem(WI(h),"true"),u.$set=be({},u.$set,{[DK({id:b,current_iteration:m},e===zd.SENT?"responded":"dismissed")]:!0})}var x=be({},u.properties.$set,u.$set);if(ta(x)||this.setPersonPropertiesForFlags(x),!Je(this.config.before_send)){var I=this.ls(u);if(!I)return;u=I}this.Nr.emit("eventCaptured",u);var N={method:"POST",url:(i=r==null?void 0:r._url)!==null&&i!==void 0?i:this.requestRouter.endpointFor("api",this.analyticsDefaultEndpoint),data:u,compression:"best-available",batchKey:r==null?void 0:r._batchKey};return!this.config.request_batching||r&&(r==null||!r._batchKey)||r!=null&&r.send_instantly?this.Kr(N):this.Jr.enqueue(N),u}ye.critical("This capture call is ignored due to client rate limiting.")}}else ye.error("No event name provided to posthog.capture")}else ye.uninitializedWarning("posthog.capture")}Ni(e){return this.on("eventCaptured",(n=>e(n.event,n)))}calculateEventProperties(e,n,r,i,o){if(r=r||new Date,!this.persistence||!this.sessionPersistence)return n;var s=o?void 0:this.persistence.remove_event_timer(e),a=be({},n);if(a.token=this.config.token,a.$config_defaults=this.config.defaults,(this.config.cookieless_mode=="always"||this.config.cookieless_mode=="on_reject"&&this.consent.isExplicitlyOptedOut())&&(a.$cookieless_mode=!0),e==="$snapshot"){var l=be({},this.persistence.properties(),this.sessionPersistence.properties());return a.distinct_id=l.distinct_id,(!nn(a.distinct_id)&&!ei(a.distinct_id)||Ap(a.distinct_id))&&ye.error("Invalid distinct_id for replay event. This indicates a bug in your implementation"),a}var c,u=yK(this.config.mask_personal_data_properties,this.config.custom_personal_data_properties);if(this.sessionManager){var{sessionId:h,windowId:p}=this.sessionManager.checkAndGetSessionAndWindowId(o,r.getTime());a.$session_id=h,a.$window_id=p}this.sessionPropsManager&&Ot(a,this.sessionPropsManager.getSessionProps());try{var g;this.sessionRecording&&Ot(a,this.sessionRecording.sdkDebugProperties),a.$sdk_debug_retry_queue_size=(g=this.Yr)==null?void 0:g.length}catch(I){a.$sdk_debug_error_capturing_properties=String(I)}if(this.requestRouter.region===tc.CUSTOM&&(a.$lib_custom_api_host=this.config.api_host),c=e!=="$pageview"||o?e!=="$pageleave"||o?this.pageViewManager.doEvent():this.pageViewManager.doPageLeave(r):this.pageViewManager.doPageView(r,i),a=Ot(a,c),e==="$pageview"&&me&&(a.title=me.title),!fe(s)){var b=r.getTime()-s;a.$duration=parseFloat((b/1e3).toFixed(3))}qn&&this.config.opt_out_useragent_filter&&(a.$browser_type=this._is_bot()?"bot":"browser"),(a=Ot({},u,this.persistence.properties(),this.sessionPersistence.properties(),a)).$is_identified=this._isIdentified(),Ze(this.config.property_denylist)?ut(this.config.property_denylist,(function(I){delete a[I]})):ye.error("Invalid value for property_denylist config: "+this.config.property_denylist+" or property_blacklist config: "+this.config.property_blacklist);var m=this.config.sanitize_properties;m&&(ye.error("sanitize_properties is deprecated. Use before_send instead"),a=m(a,e));var x=this.us();return a.$process_person_profile=x,x&&!o&&this.hs("_calculate_event_properties"),a}os(e,n){var r;if(n===void 0&&(n=!0),!this.persistence||!this.us()||this.Lr)return e;var i=this.persistence.get_initial_props(),o=(r=this.sessionPropsManager)==null?void 0:r.getSetOnceProps(),s=Ot({},i,o||{},e||{}),a=this.config.sanitize_properties;return a&&(ye.error("sanitize_properties is deprecated. Use before_send instead"),s=a(s,"$set_once")),n&&(this.Lr=!0),ta(s)?void 0:s}register(e,n){var r;(r=this.persistence)==null||r.register(e,n)}register_once(e,n,r){var i;(i=this.persistence)==null||i.register_once(e,n,r)}register_for_session(e){var n;(n=this.sessionPersistence)==null||n.register(e)}unregister(e){var n;(n=this.persistence)==null||n.unregister(e)}unregister_for_session(e){var n;(n=this.sessionPersistence)==null||n.unregister(e)}ds(e,n){this.register({[e]:n})}getFeatureFlag(e,n){return this.featureFlags.getFeatureFlag(e,n)}getFeatureFlagPayload(e){var n=this.featureFlags.getFeatureFlagPayload(e);try{return JSON.parse(n)}catch(r){return n}}isFeatureEnabled(e,n){return this.featureFlags.isFeatureEnabled(e,n)}reloadFeatureFlags(){this.featureFlags.reloadFeatureFlags()}updateEarlyAccessFeatureEnrollment(e,n,r){this.featureFlags.updateEarlyAccessFeatureEnrollment(e,n,r)}getEarlyAccessFeatures(e,n,r){return n===void 0&&(n=!1),this.featureFlags.getEarlyAccessFeatures(e,n,r)}on(e,n){return this.Nr.on(e,n)}onFeatureFlags(e){return this.featureFlags.onFeatureFlags(e)}onSurveysLoaded(e){return this.surveys.onSurveysLoaded(e)}onSessionId(e){var n,r;return(n=(r=this.sessionManager)==null?void 0:r.onSessionId(e))!==null&&n!==void 0?n:()=>{}}getSurveys(e,n){n===void 0&&(n=!1),this.surveys.getSurveys(e,n)}getActiveMatchingSurveys(e,n){n===void 0&&(n=!1),this.surveys.getActiveMatchingSurveys(e,n)}renderSurvey(e,n){this.surveys.renderSurvey(e,n)}displaySurvey(e,n){n===void 0&&(n=$K),this.surveys.displaySurvey(e,n)}cancelPendingSurvey(e){this.surveys.cancelPendingSurvey(e)}canRenderSurvey(e){return this.surveys.canRenderSurvey(e)}canRenderSurveyAsync(e,n){return n===void 0&&(n=!1),this.surveys.canRenderSurveyAsync(e,n)}identify(e,n,r){if(!this.__loaded||!this.persistence)return ye.uninitializedWarning("posthog.identify");if(ei(e)&&(e=e.toString(),ye.warn("The first argument to posthog.identify was a number, but it should be a string. It has been converted to a string.")),e)if(["distinct_id","distinctid"].includes(e.toLowerCase()))ye.critical('The string "'+e+'" was set in posthog.identify which indicates an error. This ID should be unique to the user and not a hardcoded string.');else if(e!==$l){if(this.hs("posthog.identify")){var i=this.get_distinct_id();if(this.register({$user_id:e}),!this.get_property("$device_id")){var o=i;this.register_once({$had_persisted_distinct_id:!0,$device_id:o},"")}e!==i&&e!==this.get_property(Bl)&&(this.unregister(Bl),this.register({distinct_id:e}));var s=(this.persistence.get_property(ki)||"anonymous")==="anonymous";e!==i&&s?(this.persistence.set_property(ki,"identified"),this.setPersonPropertiesForFlags(be({},r||{},n||{}),!1),this.capture("$identify",{distinct_id:e,$anon_distinct_id:i},{$set:n||{},$set_once:r||{}}),this.Br=NI(e,n,r),this.featureFlags.setAnonymousDistinctId(i)):(n||r)&&this.setPersonProperties(n,r),e!==i&&(this.reloadFeatureFlags(),this.unregister(Ed))}}else ye.critical('The string "'+$l+'" was set in posthog.identify which indicates an error. This ID is only used as a sentinel value.');else ye.error("Unique user id has not been set in posthog.identify")}setPersonProperties(e,n){if((e||n)&&this.hs("posthog.setPersonProperties")){var r=NI(this.get_distinct_id(),e,n);this.Br!==r?(this.setPersonPropertiesForFlags(be({},n||{},e||{})),this.capture("$set",{$set:e||{},$set_once:n||{}}),this.Br=r):ye.info("A duplicate setPersonProperties call was made with the same properties. It has been ignored.")}}group(e,n,r){if(e&&n){var i=this.getGroups();i[e]!==n&&this.resetGroupPropertiesForFlags(e),this.register({$groups:be({},i,{[e]:n})}),r&&(this.capture("$groupidentify",{$group_type:e,$group_key:n,$group_set:r}),this.setGroupPropertiesForFlags({[e]:r})),i[e]===n||r||this.reloadFeatureFlags()}else ye.error("posthog.group requires a group type and group key")}resetGroups(){this.register({$groups:{}}),this.resetGroupPropertiesForFlags(),this.reloadFeatureFlags()}setPersonPropertiesForFlags(e,n){n===void 0&&(n=!0),this.featureFlags.setPersonPropertiesForFlags(e,n)}resetPersonPropertiesForFlags(){this.featureFlags.resetPersonPropertiesForFlags()}setGroupPropertiesForFlags(e,n){n===void 0&&(n=!0),this.hs("posthog.setGroupPropertiesForFlags")&&this.featureFlags.setGroupPropertiesForFlags(e,n)}resetGroupPropertiesForFlags(e){this.featureFlags.resetGroupPropertiesForFlags(e)}reset(e){var n,r,i,o;if(ye.info("reset"),!this.__loaded)return ye.uninitializedWarning("posthog.reset");var s=this.get_property("$device_id");if(this.consent.reset(),(n=this.persistence)==null||n.clear(),(r=this.sessionPersistence)==null||r.clear(),this.surveys.reset(),this.featureFlags.reset(),(i=this.persistence)==null||i.set_property(ki,"anonymous"),(o=this.sessionManager)==null||o.resetSessionId(),this.Br=null,this.config.cookieless_mode==="always")this.register_once({distinct_id:$l,$device_id:null},"");else{var a=this.config.get_device_id(so());this.register_once({distinct_id:a,$device_id:e?a:s},"")}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 e,n;return(e=(n=this.sessionManager)==null?void 0:n.checkAndGetSessionAndWindowId(!0).sessionId)!==null&&e!==void 0?e:""}get_session_replay_url(e){if(!this.sessionManager)return"";var{sessionId:n,sessionStartTimestamp:r}=this.sessionManager.checkAndGetSessionAndWindowId(!0),i=this.requestRouter.endpointFor("ui","/project/"+this.config.token+"/replay/"+n);if(e!=null&&e.withTimestamp&&r){var o,s=(o=e.timestampLookBack)!==null&&o!==void 0?o:10;if(!r)return i;i+="?t="+Math.max(Math.floor((new Date().getTime()-r)/1e3)-s,0)}return i}alias(e,n){return e===this.get_property(OS)?(ye.critical("Attempting to create alias for existing People user - aborting."),-2):this.hs("posthog.alias")?(fe(n)&&(n=this.get_distinct_id()),e!==n?(this.ds(Bl,e),this.capture("$create_alias",{alias:e,distinct_id:n})):(ye.warn("alias matches current distinct_id - skipping api call."),this.identify(e),-1)):void 0}set_config(e){var n=be({},this.config);if(an(e)){var r,i,o,s,a,l,c;Ot(this.config,JI(e));var u=this.Vr();(r=this.persistence)==null||r.update_config(this.config,n,u),this.sessionPersistence=this.config.persistence==="sessionStorage"||this.config.persistence==="memory"?this.persistence:new gm(be({},this.config,{persistence:"sessionStorage"}),u);var h=this.qr(this.config.debug);Ai(h)&&(this.config.debug=h),Ai(this.config.debug)&&(this.config.debug?(Ci.DEBUG=!0,bt.H()&&bt.G("ph_debug","true"),ye.info("set_config",{config:e,oldConfig:n,newConfig:be({},this.config)})):(Ci.DEBUG=!1,bt.H()&&bt.V("ph_debug"))),(i=this.exceptionObserver)==null||i.onConfigChange(),(o=this.sessionRecording)==null||o.startIfEnabledOrStop(),(s=this.autocapture)==null||s.startIfEnabled(),(a=this.heatmaps)==null||a.startIfEnabled(),(l=this.exceptionObserver)==null||l.startIfEnabledOrStop(),this.surveys.loadIfEnabled(),this.vs(),(c=this.externalIntegrations)==null||c.startIfEnabledOrStop()}}startSessionRecording(e){var n=e===!0,r={sampling:n||!(e==null||!e.sampling),linked_flag:n||!(e==null||!e.linked_flag),url_trigger:n||!(e==null||!e.url_trigger),event_trigger:n||!(e==null||!e.event_trigger)};if(Object.values(r).some(Boolean)){var i,o,s,a,l;(i=this.sessionManager)==null||i.checkAndGetSessionAndWindowId(),r.sampling&&((o=this.sessionRecording)==null||o.overrideSampling()),r.linked_flag&&((s=this.sessionRecording)==null||s.overrideLinkedFlag()),r.url_trigger&&((a=this.sessionRecording)==null||a.overrideTrigger("url")),r.event_trigger&&((l=this.sessionRecording)==null||l.overrideTrigger("event"))}this.set_config({disable_session_recording:!1})}stopSessionRecording(){this.set_config({disable_session_recording:!0})}sessionRecordingStarted(){var e;return!((e=this.sessionRecording)==null||!e.started)}captureException(e,n){var r=new Error("PostHog syntheticException"),i=this.exceptions.buildProperties(e,{handled:!0,syntheticException:r});return this.exceptions.sendExceptionEvent(be({},i,n))}startExceptionAutocapture(e){this.set_config({capture_exceptions:e==null||e})}stopExceptionAutocapture(){this.set_config({capture_exceptions:!1})}loadToolbar(e){return this.toolbar.loadToolbar(e)}get_property(e){var n;return(n=this.persistence)==null?void 0:n.props[e]}getSessionProperty(e){var n;return(n=this.sessionPersistence)==null?void 0:n.props[e]}toString(){var e,n=(e=this.config.name)!==null&&e!==void 0?e:ha;return n!==ha&&(n=ha+"."+n),n}_isIdentified(){var e,n;return((e=this.persistence)==null?void 0:e.get_property(ki))==="identified"||((n=this.sessionPersistence)==null?void 0:n.get_property(ki))==="identified"}us(){var e,n;return!(this.config.person_profiles==="never"||this.config.person_profiles==="identified_only"&&!this._isIdentified()&&ta(this.getGroups())&&((e=this.persistence)==null||(e=e.props)==null||!e[Bl])&&((n=this.persistence)==null||(n=n.props)==null||!n[Id]))}ns(){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.us()||this.hs("posthog.createPersonProfile")&&this.setPersonProperties({},{})}hs(e){return this.config.person_profiles==="never"?(ye.error(e+' was called, but process_person is set to "never". This call will be ignored.'),!1):(this.ds(Id,!0),!0)}Vr(){if(this.config.cookieless_mode==="always")return!0;var e=this.consent.isOptedOut(),n=this.config.opt_out_persistence_by_default||this.config.cookieless_mode==="on_reject";return this.config.disable_persistence||e&&!!n}vs(){var e,n,r,i,o=this.Vr();return((e=this.persistence)==null?void 0:e.xi)!==o&&((r=this.persistence)==null||r.set_disabled(o)),((n=this.sessionPersistence)==null?void 0:n.xi)!==o&&((i=this.sessionPersistence)==null||i.set_disabled(o)),o}opt_in_capturing(e){var n;if(this.config.cookieless_mode!=="always"){var r,i;this.config.cookieless_mode==="on_reject"&&this.consent.isExplicitlyOptedOut()&&(this.reset(!0),(r=this.sessionManager)==null||r.destroy(),this.sessionManager=new qI(this),this.persistence&&(this.sessionPropsManager=new jI(this,this.sessionManager,this.persistence)),this.sessionRecording=new YI(this),this.sessionRecording.startIfEnabledOrStop()),this.consent.optInOut(!0),this.vs(),this.rs(),(n=this.sessionRecording)==null||n.startIfEnabledOrStop(),this.config.cookieless_mode=="on_reject"&&this.surveys.loadIfEnabled(),(fe(e==null?void 0:e.captureEventName)||e!=null&&e.captureEventName)&&this.capture((i=e==null?void 0:e.captureEventName)!==null&&i!==void 0?i:"$opt_in",e==null?void 0:e.captureProperties,{send_instantly:!0}),this.config.capture_pageview&&this.ss()}else ye.warn('Consent opt in/out is not valid with cookieless_mode="always" and will be ignored')}opt_out_capturing(){var e,n;this.config.cookieless_mode!=="always"?(this.config.cookieless_mode==="on_reject"&&this.consent.isOptedIn()&&this.reset(!0),this.consent.optInOut(!1),this.vs(),this.config.cookieless_mode==="on_reject"&&(this.register({distinct_id:$l,$device_id:null}),(e=this.sessionManager)==null||e.destroy(),this.sessionManager=void 0,this.sessionPropsManager=void 0,(n=this.sessionRecording)==null||n.stopRecording(),this.sessionRecording=void 0,this.ss())):ye.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 e=this.consent.consent;return e===Ri.GRANTED?"granted":e===Ri.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.vs()}_is_bot(){return ur?GI(ur,this.config.custom_blocked_useragents):void 0}ss(){me&&(me.visibilityState==="visible"?this.Ur||(this.Ur=!0,this.capture("$pageview",{title:me.title},{send_instantly:!0}),this.zr&&(me.removeEventListener("visibilitychange",this.zr),this.zr=null)):this.zr||(this.zr=this.ss.bind(this),Bt(me,"visibilitychange",this.zr)))}debug(e){e===!1?(oe==null||oe.console.log("You've disabled debug mode."),this.set_config({debug:!1})):(oe==null||oe.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}))}O(){var e,n,r,i,o,s,a,l=this.Wr||{};return"advanced_disable_flags"in l?!!l.advanced_disable_flags:this.config.advanced_disable_flags!==!1?!!this.config.advanced_disable_flags:this.config.advanced_disable_decide===!0?(ye.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):(r="advanced_disable_decide",i=!1,o=ye,s=(n="advanced_disable_flags")in(e=l)&&!fe(e[n]),a=r in e&&!fe(e[r]),s?e[n]:a?(o&&o.warn("Config field '"+r+"' is deprecated. Please use '"+n+"' instead. The old field will be removed in a future major version."),e[r]):i)}ls(e){if(Je(this.config.before_send))return e;var n=Ze(this.config.before_send)?this.config.before_send:[this.config.before_send],r=e;for(var i of n){if(r=i(r),Je(r)){var o="Event '"+e.event+"' was rejected in beforeSend function";return Xq(e.event)?ye.warn(o+". This can cause unexpected behavior."):ye.info(o),null}r.properties&&!ta(r.properties)||ye.warn("Event '"+e.event+"' has no properties after beforeSend function, this is likely an error.")}return r}getPageViewId(){var e;return(e=this.pageViewManager.Kt)==null?void 0:e.pageViewId}captureTraceFeedback(e,n){this.capture("$ai_feedback",{$ai_trace_id:String(e),$ai_feedback_text:n})}captureTraceMetric(e,n,r){this.capture("$ai_metric",{$ai_trace_id:String(e),$ai_metric_name:n,$ai_metric_value:String(r)})}qr(e){var n=Ai(e)&&!e,r=bt.H()&&bt.q("ph_debug")==="true";return!n&&(!!r||e)}}(function(t,e){for(var n=0;n<e.length;n++)t.prototype[e[n]]=NG(t.prototype[e[n]])})(Ud,["identify"]);var QI,aY=(QI=rc[ha]=new Ud,(function(){function t(){t.done||(t.done=!0,XI=!1,ut(rc,(function(e){e._dom_loaded()})))}me!=null&&me.addEventListener?me.readyState==="complete"?t():Bt(me,"DOMContentLoaded",t,{capture:!1}):oe&&ye.error("Browser doesn't support `document.addEventListener` so PostHog couldn't be initialized")})(),QI);const ic=K.createContext({}),eC=({config:{apiKey:t,tokenOut:e,chainIdOut:n,theme:r,enableExchange:i,cexBridgeChainMapping:o,recipient:s,enforceFlow:a},onClose:l,wrapper:c})=>{const u=Me(x=>x.setEnsoApiToken),h=Me(x=>x.setTokenOut),p=Me(x=>x.setChainIdOut),g=Me(x=>x.setRecipient),b=K.useMemo(()=>l?()=>{l&&l()}:void 0,[l]);K.useEffect(()=>{h(e),p(n),g(s)},[e,n,s]),K.useEffect(()=>{aY.init("phc_capPDVae4W7y6QIqVTugTtx5geVthX4YVswtXa6DrjM",{api_host:"https://eu.i.posthog.com",person_profiles:"always"}),t||alert("Please provide an API key"),u(t)},[t]);const m=K.useMemo(()=>c!=null?c:(({children:x,...I})=>w.jsx(ue,{p:4,w:"374px",...I,children:x})),[c]);return w.jsx(ic.Provider,{value:{handleClose:b,enableExchange:i,cexBridgeChainMapping:o,enforceFlow:a},children:w.jsx(hB,{themeConfig:r,children:w.jsxs(m,{children:[w.jsx(pq,{}),w.jsx(jq,{})]})})})},lY=({config:t,setIsActive:e,isActive:n,onClose:r})=>{const i=K.useCallback(()=>{e(!1),r==null||r()},[e,r]);return n?w.jsx(eC,{wrapper:or,config:t,onClose:i}):null};_t.Checkout=eC,_t.CheckoutModal=lY,_t.DEFAULT_CEX_BRIDGE_CHAIN_MAPPING=Jf,_t.SupportedExchanges=Qr,Object.defineProperty(_t,Symbol.toStringTag,{value:"Module"})}));