@nexus-cross/crossx-sdk-core 2.1.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/adapters/BrowserConfirmationAdapter.test.d.ts +2 -0
- package/dist/__tests__/adapters/BrowserConfirmationAdapter.test.d.ts.map +1 -0
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +14 -0
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/core/i18n/messages.en.d.ts.map +1 -1
- package/dist/core/i18n/messages.ko.d.ts.map +1 -1
- package/dist/core/i18n/types.d.ts +11 -0
- package/dist/core/i18n/types.d.ts.map +1 -1
- package/dist/crossx.global +77 -64
- package/dist/index.cjs +81 -68
- package/dist/index.js +867 -822
- package/package.json +1 -1
package/dist/crossx.global
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
var CROSSx=function(z){"use strict";var La=Object.defineProperty;var Da=(z,h,x)=>h in z?La(z,h,{enumerable:!0,configurable:!0,writable:!0,value:x}):z[h]=x;var
|
|
1
|
+
var CROSSx=function(z){"use strict";var La=Object.defineProperty;var Da=(z,h,x)=>h in z?La(z,h,{enumerable:!0,configurable:!0,writable:!0,value:x}):z[h]=x;var C=(z,h,x)=>Da(z,typeof h!="symbol"?h+"":h,x);var vt,Jr;var h=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",r.SESSION_EXPIRED="SESSION_EXPIRED",r.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.USER_NOT_FOUND="USER_NOT_FOUND",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(h||{});class x extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}var We=(r=>(r.MetaMask="io.metamask",r.Binance="com.binance.wallet",r.CROSSx="crossx",r))(We||{});const Xr={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},is=["crossx","io.metamask","com.binance.wallet"];function os(r){return Xr[r]??r}function Zr(r){return Array.isArray(r.connectOtherWallets)&&r.connectOtherWallets.length>0?[...r.connectOtherWallets]:r.showConnectOtherWallets===!0?[...is]:[]}const rt={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Qr=Object.fromEntries(Object.entries(rt).map(([r,e])=>[r,e.caipId])),en=new Map(Object.values(rt).map(r=>[r.caipId,r]));new Map(Object.values(rt).map(r=>[r.chainId,r]));const tn={symbol:"",decimals:18};function Et(r){var e;return((e=en.get(r))==null?void 0:e.nativeCurrency)??tn}class as{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new x(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let ye=null;function Ma(r){}function cs(r){ye=r}const u={info(...r){if(ye){ye.log(...r);return}console.log(...r)},log(...r){if(ye){ye.log(...r);return}},warn(...r){if(ye){ye.warn(...r);return}},error(...r){if(ye){ye.error(...r);return}}},sn={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",walletSelector_addError_limitExceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",walletSelector_addError_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
2
2
|
|
|
3
|
-
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},ls={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
3
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},ls={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",walletSelector_addError_limitExceeded:"Account limit reached. Maximum {limit} accounts allowed.",walletSelector_addError_generic:"Failed to add a new account. Please try again.",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
4
4
|
|
|
5
|
-
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},rn={ko:sn,en:ls};function be(r="en",e){return rn[r]??ls}const ds="crossx_access_token",us="crossx_refresh_token",hs="crossx_user_info",bt=class bt{constructor(e,s,t,n,i,o,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new x(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new x(h.OAUTH_POPUP_BLOCKED,i):new x(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:d}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,d);let _,f,b;try{const I=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),f=(i=I.firebase)==null?void 0:i.sign_in_provider;const R=((o=I.firebase)==null?void 0:o.identities)??{};b=I.email??((a=R.email)==null?void 0:a[0]),f==="google.com"?_=(c=R["google.com"])==null?void 0:c[0]:f==="apple.com"&&(_=(l=R["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",f,"hasProviderSub:",!!_,"email:",b??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const I=this.crypto.decodeJWT(p);u.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const R=await this.crypto.verifyJWT(p);if(n=R.signatureVerified??!1,!R.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const W=R.payload,D=W.email??b??s;u.log("[CROSSx] email 소스 — CROSSx JWT:",W.email??"(없음)","/ Firebase JWT:",b??"(없음)","/ OAuth 콜백:",s??"(없음)","→",D??"(없음)"),t={id:W.sub,email:D,signInProvider:f,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??s,signInProvider:f,providerSub:_},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const v=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,v),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof x&&e.code===h.SESSION_EXPIRED;return u.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const d=this.tokenStore.get()??"";d&&(i.access_token=d),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=bt.REFRESH_RELOGIN_CODES.has(c.code);throw new x(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new x(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof x&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(hs);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(ds);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(us);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(hs),await this.storage.remove(ds),await this.storage.remove(us),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof x&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof x&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};bt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Et=bt;class nn{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class on{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class At{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class an{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new x(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class cn{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}var nt={environment:"production"};const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function ln(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}function ps(){try{if(typeof nt<"u"){const r=typeof nt=="string"?JSON.parse(nt):nt,e=ln(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Ue)return Ue[r]}catch{}return Ue.production}const dn=2e3,fs=6e4,un=1e3,hn=1e4,pn="0x77359400",_s="0x3B9ACA00",gs=130,xs=6,ms=18,ws=3e4,fn=5*60*1e3,_n=30*1e3,It=100;function ys(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===48;)e--;return r.slice(0,e)}function gn(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(ms),t=e/s,i=(e%s).toString().padStart(ms,"0"),o=ys(i).slice(0,xs);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function it(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),i=t/n,a=(t%n).toString().padStart(s,"0"),c=ys(a.slice(0,xs));return`${c?`${i}.${c}`:`${i}`} ${e}`}catch{return}}function xn(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==gs)throw new x(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${gs} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function mn(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function wn(r,e){const s=yn(e);if(r==="0"){if(s!==void 0&&s!==0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${s}`);return}const t=r.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(s===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function yn(r){if(r==null||typeof r!="object")return;const e=r.domain;if(e==null||typeof e!="object")return;const s=e.chainId;if(s==null)return;const t=Number(s);return Number.isFinite(t)?t:void 0}class He{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new x(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const s=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(d){if(this.deps.pinStore.clear(),d instanceof x){if(d.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(d.code===h.PIN_INVALID)return{ok:!1,error:d.message};if(d.code===h.PIN_LOCKED)return He.buildPinLockedResult(d,a)}throw d}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof x&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=be(this.deps.getLocale()??"en"),d=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:d?this.deps.maskEmail(d,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const s=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof x){if(t=He.parsePinError(n,s),!t)throw n}else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof x&&(t=He.parsePinError(n,s),t))continue;throw n}}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,s){const t=He.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class bn{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new x(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let t;return this.deps.walletProvider.prepare&&(t=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(t)})}}function Sn(r){return r==="google"||r==="apple"}class vn{constructor(e){this.deps=e}async signInAgain(){var s,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Sn(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((s=i.user)==null?void 0:s.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.sessionAlert_title,message:l.alert_differentAccount,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(s){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof x&&s.code===h.WITHDRAW_FAILED){if(u.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof x&&s.code===h.WALLET_NOT_FOUND){if(u.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof x)||s.code!==h.SESSION_EXPIRED)throw s;if(u.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:i})==="signout")throw this.deps.clearAuthState(),new x(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new x(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class En{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,s){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){const a=s?i.find(d=>d.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?i.find(d=>d.index===e):void 0,l=a??c??i[0];u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address),this.deps.setActiveWallet(l.address,l.index);return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class An{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:s});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const d=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(d===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,d,e));if(!p){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=d;break}if(p.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=d;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const _=g.lockExpiresAt*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),b=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${f}초, 메시지: ${b}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,b),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof x))throw p;if(p.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.sessionAlert_title,message:g.alert_sessionExpired,email:_?this.deps.maskEmail(_,g.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((g==null?void 0:g.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),b=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${f}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,b),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const d=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",d.address),d}catch(d){if(d instanceof x&&d.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(d instanceof x&&d.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:g?this.deps.maskEmail(g,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const b=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",b.address),b}catch(b){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",b),b}}throw this.deps.clearAuthState(),d}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",d),d}}}class In{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,i?this.deps.estimateGas(e,s):null,o?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=g;if(_){const f=_s;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(f)).toString(16)}`,c.maxPriorityFeePerGas=f,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=pn,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=_s,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Tn{constructor(e){this.crypto=e}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Rn(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class kn{constructor(e){this.deps=e}setActiveWallet(e,s){this.deps.setState({address:e,activeWalletIndex:s}),this.deps.emitAddressChanged({address:e,index:s}),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const s={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Rn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(s),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class On{constructor(e){this.deps=e}async resolveAddress(e){const s=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===s){if(!t)throw new x(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:s}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Pn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new x(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new x(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Cn{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const s=await this.deps.walletLifecycleService.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",s),s==="migration_required"){const t=this.deps.getProviderSub()??e;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return s==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const s=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(s.address,0),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function Tt(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const $e=class $e extends cn{constructor(e,s,t,n,i,o,a,c,l,d,p){var g,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&cs(e.logger),this.confirmation=l,this.pinStore=p??new At,this.stateManager=new kn({setState:f=>{f.authenticated!==void 0&&(this.authenticated=f.authenticated),f.userId!==void 0&&(this.userId=f.userId),f.address!==void 0&&(this.address=f.address),f.activeWalletIndex!==void 0&&(this.activeWalletIndex=f.activeWalletIndex),f.userEmail!==void 0&&(this.userEmail=f.userEmail),f.providerSub!==void 0&&(this.providerSub=f.providerSub),f.loginType!==void 0&&(this.loginType=f.loginType),f.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=f.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:f,index:b})=>{this.emit("addressChanged",{address:f,index:b})},emitAuthChanged:({isAuthenticated:f,address:b,userId:v})=>{this.emit("authChanged",{isAuthenticated:f,address:b,userId:v})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:$e.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new He({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Tt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new bn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator}),this.walletLifecycleService=new En({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(f,b)=>this.setActiveWallet(f,b)}),this.migrationOrchestrator=new An({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(f,b)=>this.migrateWalletUseCase.execute(f,b),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Tt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var f;return((f=this._config.migration)==null?void 0:f.allowSkip)??!0}}),this.transactionLifecycleService=new In({getActiveAddress:()=>this.address,estimateGas:(f,b)=>this.estimateGas(f,b),getBaseFeePerGas:f=>this.getBaseFeePerGas(f),jsonRpcCall:(f,b,v)=>this.jsonRpc.call(f,b,v)}),this.signatureVerifier=new Tn(this.crypto),this.addressResolverService=new On({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Pn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Cn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(f,b)=>this.setActiveWallet(f,b)}),this.sessionOrchestrator=new vn({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:f=>{this._isRecoveringSession=f},setAuthenticated:f=>{this.authenticated=f},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:f=>this.signInUseCase.execute(f),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:f=>this.confirmation.showSessionAlert(f),clearAuthState:()=>this.clearAuthState(),applyAuthResult:f=>this.applyAuthResult(f),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Tt}),this.chainRegistry=d,this.jsonRpc=new an(d,i),this.signInUseCase=new Et(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new nn(this.internalConfig,t,c),this.migrateWalletUseCase=new on(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var s,t;u.log("[CROSSx SDK] v2.0.2 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=ps();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get($e.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index),a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.signInUseCase.restoreSession();if(c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(d){if(!(d instanceof x&&d.code===h.PIN_CANCELLED))throw d;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,u.info("[CROSSx SDK] v2.0.2 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new x(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:Zr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new x(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:s,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,s);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,s);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof x&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof x?s:new x(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof x&&s.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(s.address,0),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=s.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,s){if(e.length<2)return null;if(s){const t=e.find(n=>n.address.toLowerCase()===s.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:s,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");wn(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:s,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return xn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData($e.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=vt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return mn(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof x)throw o;const a=o instanceof Error?o.message:String(o);throw new x(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=vt(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async a=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,a)).txHash;const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a);return c.txHash??c.signature}});return{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof x)throw o;const a=o instanceof Error?o.message:String(o);throw new x(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??un,i=hn,o=t.timeoutMs??fs,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,v;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??dn,l=i??((v=this._config.receiptPolling)==null?void 0:v.timeoutMs)??fs,d=vt(e),p=s.from??"";let g,_;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{g=I;const R=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),W=s.value?BigInt(s.value):0n,D=it(s.value,d.symbol,d.decimals),V=it("0x"+R.toString(16),d.symbol,d.decimals),G=it("0x"+(W+R).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:D,fees:V,total:G,nativeSymbol:d.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(_=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:p,to:s.to,amount:it(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},f),_)throw _;return{chainId:e,txHash:a,receipt:g}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new x(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof x?n:new x(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:gn(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){return this.ensureAuthenticated(),new as(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const i=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,s){this.stateManager.setActiveWallet(e,s)}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState()}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,s){return this.walletLifecycleService.loadWalletAfterAuth(e,s)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),cs(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};$e.WALLET_PREF_KEY="wallet_preference",$e.OFFCHAIN_CHAIN_ID="0";let ot=$e;class Nn{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const Rt="crossx-sdk",Ln=1,_e="data",Ce="keys",at="aes-primary",Dn=12;class bs{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,Ln);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Ce)||i.createObjectStore(Ce)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ce,at);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ce,at,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Rt)return null;try{const e=await this.openDB(Rt),s=e.transaction([Ce,_e],"readonly"),t=s.objectStore(Ce).get(at),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=s.objectStore(_e).getAll(),o=s.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ce,at,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Rt),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(Dn);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(_e,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const kt=crypto,Ss=r=>r instanceof CryptoKey,ct=new TextEncoder,Xe=new TextDecoder;function Mn(...r){const e=r.reduce((n,{length:i})=>n+i,0),s=new Uint8Array(e);let t=0;for(const n of r)s.set(n,t),t+=n.length;return s}const $n=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},Te=r=>{let e=r;e instanceof Uint8Array&&(e=Xe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return $n(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Q extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Q.code="ERR_JOSE_GENERIC";class ue extends Q{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}ue.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ot extends Q{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}Ot.code="ERR_JWT_EXPIRED";class vs extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}vs.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class Wn extends Q{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}Wn.code="ERR_JWE_DECRYPTION_FAILED";class Un extends Q{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Un.code="ERR_JWE_INVALID";class Z extends Q{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Z.code="ERR_JWS_INVALID";class xe extends Q{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class Hn extends Q{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Hn.code="ERR_JWK_INVALID";class Pt extends Q{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Pt.code="ERR_JWKS_INVALID";class Ct extends Q{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ct.code="ERR_JWKS_NO_MATCHING_KEY";class Es extends Q{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Es.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class As extends Q{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}As.code="ERR_JWKS_TIMEOUT";class Is extends Q{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Is.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function me(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Ze(r,e){return r.name===e}function Nt(r){return parseInt(r.name.slice(4),10)}function Bn(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Fn(r,e){if(e.length&&!e.some(s=>r.usages.includes(s))){let s="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();s+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?s+=`one of ${e[0]} or ${e[1]}.`:s+=`${e[0]}.`;throw new TypeError(s)}}function Kn(r,e,...s){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ze(r.algorithm,"HMAC"))throw me("HMAC");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ze(r.algorithm,"RSASSA-PKCS1-v1_5"))throw me("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ze(r.algorithm,"RSA-PSS"))throw me("RSA-PSS");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw me("Ed25519 or Ed448");break}case"Ed25519":{if(!Ze(r.algorithm,"Ed25519"))throw me("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ze(r.algorithm,"ECDSA"))throw me("ECDSA");const t=Bn(e);if(r.algorithm.namedCurve!==t)throw me(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Fn(r,s)}function Ts(r,e,...s){var t;if(s=s.filter(Boolean),s.length>2){const n=s.pop();r+=`one of type ${s.join(", ")}, or ${n}.`}else s.length===2?r+=`one of type ${s[0]} or ${s[1]}.`:r+=`of type ${s[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const Rs=(r,...e)=>Ts("Key must be ",r,...e);function ks(r,e,...s){return Ts(`Key for the ${r} algorithm must be `,e,...s)}const Os=r=>Ss(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",lt=["CryptoKey"],Gn=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let s;for(const t of e){const n=Object.keys(t);if(!s||s.size===0){s=new Set(n);continue}for(const i of n){if(s.has(i))return!1;s.add(i)}}return!0};function qn(r){return typeof r=="object"&&r!==null}function Se(r){if(!qn(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const Vn=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:s}=e.algorithm;if(typeof s!="number"||s<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function Be(r){return Se(r)&&typeof r.kty=="string"}function zn(r){return r.kty!=="oct"&&typeof r.d=="string"}function Jn(r){return r.kty!=="oct"&&typeof r.d>"u"}function Yn(r){return Be(r)&&r.kty==="oct"&&typeof r.k=="string"}function jn(r){let e,s;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},s=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},s=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},s=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},s=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:s}}const Ps=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:s}=jn(r),t=[e,r.ext??!1,r.key_ops??s],n={...r};return delete n.alg,delete n.use,kt.subtle.importKey("jwk",n,...t)},Cs=r=>Te(r);let Fe,Ke;const Ns=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",dt=async(r,e,s,t,n=!1)=>{let i=r.get(e);if(i!=null&&i[t])return i[t];const o=await Ps({...s,alg:t});return n&&Object.freeze(e),i?i[t]=o:r.set(e,{[t]:o}),o},Xn={normalizePublicKey:(r,e)=>{if(Ns(r)){let s=r.export({format:"jwk"});return delete s.d,delete s.dp,delete s.dq,delete s.p,delete s.q,delete s.qi,s.k?Cs(s.k):(Ke||(Ke=new WeakMap),dt(Ke,r,s,e))}return Be(r)?r.k?Te(r.k):(Ke||(Ke=new WeakMap),dt(Ke,r,r,e,!0)):r},normalizePrivateKey:(r,e)=>{if(Ns(r)){let s=r.export({format:"jwk"});return s.k?Cs(s.k):(Fe||(Fe=new WeakMap),dt(Fe,r,s,e))}return Be(r)?r.k?Te(r.k):(Fe||(Fe=new WeakMap),dt(Fe,r,r,e,!0)):r}};async function Ls(r,e){if(!Se(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Te(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ps({...r,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const Ge=r=>r==null?void 0:r[Symbol.toStringTag],Lt=(r,e,s)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,s))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},Zn=(r,e,s,t)=>{if(!(e instanceof Uint8Array)){if(t&&Be(e)){if(Yn(e)&&Lt(r,e,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Os(e))throw new TypeError(ks(r,e,...lt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Ge(e)} instances for symmetric algorithms must be of type "secret"`)}},Qn=(r,e,s,t)=>{if(t&&Be(e))switch(s){case"sign":if(zn(e)&&Lt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Jn(e)&&Lt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Os(e))throw new TypeError(ks(r,e,...lt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Ge(e)} instances for asymmetric algorithms must not be of type "secret"`);if(s==="sign"&&e.type==="public")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm signing must be of type "private"`);if(s==="decrypt"&&e.type==="public")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&s==="verify"&&e.type==="private")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&s==="encrypt"&&e.type==="private")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ds(r,e,s,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Zn(e,s,t,r):Qn(e,s,t,r)}Ds.bind(void 0,!1);const Ms=Ds.bind(void 0,!0);function ei(r,e,s,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;s!==void 0?i=new Map([...Object.entries(s),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new r(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new r(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const ti=(r,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(s=>typeof s!="string")))throw new TypeError(`"${r}" option must be an array of strings`);if(e)return new Set(e)};function si(r,e){const s=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function ri(r,e,s){if(e=await Xn.normalizePublicKey(e,r),Ss(e))return Kn(e,r,s),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(Rs(e,...lt));return kt.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(Rs(e,...lt,"Uint8Array","JSON Web Key"))}const ni=async(r,e,s,t)=>{const n=await ri(r,e,"verify");Vn(r,n);const i=si(r,n.algorithm);try{return await kt.subtle.verify(i,n,s,t)}catch{return!1}};async function ii(r,e,s){if(!Se(r))throw new Z("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new Z("JWS Protected Header incorrect type");if(r.payload===void 0)throw new Z("JWS Payload missing");if(typeof r.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(r.header!==void 0&&!Se(r.header))throw new Z("JWS Unprotected Header incorrect type");let t={};if(r.protected)try{const b=Te(r.protected);t=JSON.parse(Xe.decode(b))}catch{throw new Z("JWS Protected Header is invalid")}if(!Gn(t,r.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...r.header},i=ei(Z,new Map([["b64",!0]]),s==null?void 0:s.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&ti("algorithms",s.algorithms);if(c&&!c.has(a))throw new vs('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof r.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,r),l=!0,Ms(a,e,"verify"),Be(e)&&(e=await Ls(e,a))):Ms(a,e,"verify");const d=Mn(ct.encode(r.protected??""),ct.encode("."),typeof r.payload=="string"?ct.encode(r.payload):r.payload);let p;try{p=Te(r.signature)}catch{throw new Z("Failed to base64url decode the signature")}if(!await ni(a,e,p,d))throw new Is;let _;if(o)try{_=Te(r.payload)}catch{throw new Z("Failed to base64url decode the payload")}else typeof r.payload=="string"?_=ct.encode(r.payload):_=r.payload;const f={payload:_};return r.protected!==void 0&&(f.protectedHeader=t),r.header!==void 0&&(f.unprotectedHeader=r.header),l?{...f,key:e}:f}async function oi(r,e,s){if(r instanceof Uint8Array&&(r=Xe.decode(r)),typeof r!="string")throw new Z("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=r.split(".");if(o!==3)throw new Z("Invalid Compact JWS");const a=await ii({payload:n,protected:t,signature:i},e,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const ai=r=>Math.floor(r.getTime()/1e3),$s=60,Ws=$s*60,Dt=Ws*24,ci=Dt*7,li=Dt*365.25,di=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Us=r=>{const e=di.exec(r);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const s=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(s*$s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(s*Ws);break;case"day":case"days":case"d":n=Math.round(s*Dt);break;case"week":case"weeks":case"w":n=Math.round(s*ci);break;default:n=Math.round(s*li);break}return e[1]==="-"||e[4]==="ago"?-n:n},Hs=r=>r.toLowerCase().replace(/^application\//,""),ui=(r,e)=>typeof r=="string"?e.includes(r):Array.isArray(r)?e.some(Set.prototype.has.bind(new Set(r))):!1,hi=(r,e,s={})=>{let t;try{t=JSON.parse(Xe.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=s;if(n&&(typeof r.typ!="string"||Hs(r.typ)!==Hs(n)))throw new ue('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=s,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const f of new Set(d.reverse()))if(!(f in t))throw new ue(`missing required "${f}" claim`,t,f,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new ue('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new ue('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!ui(t.aud,typeof c=="string"?[c]:c))throw new ue('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof s.clockTolerance){case"string":p=Us(s.clockTolerance);break;case"number":p=s.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=s,_=ai(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new ue('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new ue('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>_+p)throw new ue('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new ue('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=_-p)throw new Ot('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const f=_-t.iat,b=typeof l=="number"?l:Us(l);if(f-p>b)throw new Ot('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(f<0-p)throw new ue('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function pi(r,e,s){var o;const t=await oi(r,e,s);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:hi(t.protectedHeader,t.payload,s),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function fi(r){switch(typeof r=="string"&&r.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function _i(r){return r&&typeof r=="object"&&Array.isArray(r.keys)&&r.keys.every(gi)}function gi(r){return Se(r)}function Bs(r){return typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}class xi{constructor(e){if(this._cached=new WeakMap,!_i(e))throw new Pt("JSON Web Key Set malformed");this._jwks=Bs(e)}async getKey(e,s){const{alg:t,kid:n}={...e,...s==null?void 0:s.header},i=fi(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new Ct;if(c!==1){const l=new Es,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Fs(d,p,t)}catch{}},l}return Fs(this._cached,a,t)}}async function Fs(r,e,s){const t=r.get(e)||r.set(e,{}).get(e);if(t[s]===void 0){const n=await Ls({...e,ext:!0},s);if(n instanceof Uint8Array||n.type!=="public")throw new Pt("JSON Web Key Set members must be public keys");t[s]=n}return t[s]}function Ks(r){const e=new xi(r),s=async(t,n)=>e.getKey(t,n);return Object.defineProperties(s,{jwks:{value:()=>Bs(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),s}const mi=async(r,e,s)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(r.href,{signal:t?t.signal:void 0,redirect:"manual",headers:s.headers}).catch(a=>{throw i?new As:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new Q("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Q("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function wi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Mt;(typeof navigator>"u"||!((Jr=(St=navigator.userAgent)==null?void 0:St.startsWith)!=null&&Jr.call(St,"Mozilla/5.0 ")))&&(Mt="jose/v5.10.0");const $t=Symbol();function yi(r,e){return!(typeof r!="object"||r===null||!("uat"in r)||typeof r.uat!="number"||Date.now()-r.uat>=e||!("jwks"in r)||!Se(r.jwks)||!Array.isArray(r.jwks.keys)||!Array.prototype.every.call(r.jwks.keys,Se))}class bi{constructor(e,s){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:s==null?void 0:s.agent,headers:s==null?void 0:s.headers},this._timeoutDuration=typeof(s==null?void 0:s.timeoutDuration)=="number"?s==null?void 0:s.timeoutDuration:5e3,this._cooldownDuration=typeof(s==null?void 0:s.cooldownDuration)=="number"?s==null?void 0:s.cooldownDuration:3e4,this._cacheMaxAge=typeof(s==null?void 0:s.cacheMaxAge)=="number"?s==null?void 0:s.cacheMaxAge:6e5,(s==null?void 0:s[$t])!==void 0&&(this._cache=s==null?void 0:s[$t],yi(s==null?void 0:s[$t],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ks(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,s){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,s)}catch(t){if(t instanceof Ct&&this.coolingDown()===!1)return await this.reload(),this._local(e,s);throw t}}async reload(){this._pendingFetch&&wi()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Mt&&!e.has("User-Agent")&&(e.set("User-Agent",Mt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=mi(this._url,this._timeoutDuration,this._options).then(s=>{this._local=Ks(s),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=s),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(s=>{throw this._pendingFetch=void 0,s})),await this._pendingFetch}}function Si(r,e){const s=new bi(r,e),t=async(n,i)=>s.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!s._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=s._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const vi=Te;function Ei(r){if(typeof r!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=vi(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Xe.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Wt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ve(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function q(r,e,s=""){const t=Wt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function Gs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(r.outputLen),ve(r.blockLen)}function qe(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function qs(r,e){q(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Ai(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ve(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ut(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function we(r,e){return r<<32-e|r>>>e}const Ii=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ti(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Ri(r){for(let e=0;e<r.length;e++)r[e]=Ti(r[e]);return r}const Vs=Ii?r=>r:Ri,zs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ki=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Qe(r){if(q(r),zs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ki[r[s]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Js(r){if(r>=Ee._0&&r<=Ee._9)return r-Ee._0;if(r>=Ee.A&&r<=Ee.F)return r-(Ee.A-10);if(r>=Ee.a&&r<=Ee.f)return r-(Ee.a-10)}function ut(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(zs)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=Js(r.charCodeAt(i)),a=Js(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Re(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];q(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Ys(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function js(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const Oi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Pi(r,e,s){return r&e^~r&s}function Ci(r,e,s){return r&e^r&s^e&s}class Ni{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ut(this.buffer)}update(e){qe(this),q(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Ut(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qe(this),qs(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ve(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Ut(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ht=BigInt(2**32-1),Xs=BigInt(32);function Li(r,e=!1){return e?{h:Number(r&ht),l:Number(r>>Xs&ht)}:{h:Number(r>>Xs&ht)|0,l:Number(r&ht)|0}}function Di(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Li(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const Mi=(r,e,s)=>r<<s|e>>>32-s,$i=(r,e,s)=>e<<s|r>>>32-s,Wi=(r,e,s)=>e<<s-32|r>>>64-s,Ui=(r,e,s)=>r<<s-32|e>>>64-s,Hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oe=new Uint32Array(64);class Bi extends Ni{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let p=0;p<16;p++,s+=4)Oe[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const g=Oe[p-15],_=Oe[p-2],f=we(g,7)^we(g,18)^g>>>3,b=we(_,17)^we(_,19)^_>>>10;Oe[p]=b+Oe[p-7]+f+Oe[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const g=we(a,6)^we(a,11)^we(a,25),_=d+g+Pi(a,c,l)+Hi[p]+Oe[p]|0,b=(we(t,2)^we(t,13)^we(t,22))+Ci(t,n,i)|0;d=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+b|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){Ve(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}}class Fi extends Bi{constructor(){super(32);P(this,"A",ke[0]|0);P(this,"B",ke[1]|0);P(this,"C",ke[2]|0);P(this,"D",ke[3]|0);P(this,"E",ke[4]|0);P(this,"F",ke[5]|0);P(this,"G",ke[6]|0);P(this,"H",ke[7]|0)}}const Ki=Ys(()=>new Fi,Oi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ht=BigInt(0),Bt=BigInt(1);function pt(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Zs(r){if(typeof r=="bigint"){if(!gt(r))throw new Error("positive bigint expected, got "+r)}else ve(r);return r}function ft(r){const e=Zs(r).toString(16);return e.length&1?"0"+e:e}function Qs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ht:BigInt("0x"+r)}function _t(r){return Qs(Qe(r))}function er(r){return Qs(Qe(Gi(q(r)).reverse()))}function Ft(r,e){ve(e),r=Zs(r);const s=ut(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function tr(r,e){return Ft(r,e).reverse()}function Gi(r){return Uint8Array.from(r)}const gt=r=>typeof r=="bigint"&&Ht<=r;function qi(r,e,s){return gt(r)&>(e)&>(s)&&e<=r&&r<s}function Vi(r,e,s,t){if(!qi(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function zi(r){let e;for(e=0;r>Ht;r>>=Bt,e+=1);return e}const Kt=r=>(Bt<<BigInt(r))-Bt;function Ji(r,e,s){if(ve(r,"hashLen"),ve(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=v=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},g=(...v)=>s(l,Re(c,...v)),_=(v=n)=>{l=g(i,v),c=g(),v.length!==0&&(l=g(o,v),c=g())},f=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let v=0;const I=[];for(;v<e;){c=g();const R=c.slice();I.push(R),v+=c.length}return Re(...I)};return(v,I)=>{p(),_(v);let R;for(;!(R=I(f()));)_();return p(),R}}function Gt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function sr(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oe=BigInt(0),re=BigInt(1),Ne=BigInt(2),rr=BigInt(3),nr=BigInt(4),ir=BigInt(5),Yi=BigInt(7),or=BigInt(8),ji=BigInt(9),ar=BigInt(16);function he(r,e){const s=r%e;return s>=oe?s:e+s}function de(r,e,s){let t=r;for(;e-- >oe;)t*=t,t%=s;return t}function cr(r,e){if(r===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let s=he(r,e),t=e,n=oe,i=re;for(;s!==oe;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==re)throw new Error("invert: does not exist");return he(n,e)}function qt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function lr(r,e){const s=(r.ORDER+re)/nr,t=r.pow(e,s);return qt(r,t,e),t}function Xi(r,e){const s=(r.ORDER-ir)/or,t=r.mul(e,Ne),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,Ne),n),a=r.mul(i,r.sub(o,r.ONE));return qt(r,a,e),a}function Zi(r){const e=xt(r),s=dr(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+Yi)/ar;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),_=a.eql(a.sqr(d),c),f=a.eql(a.sqr(p),c);l=a.cmov(l,d,_),d=a.cmov(g,p,f);const b=a.eql(a.sqr(d),c),v=a.cmov(l,d,b);return qt(a,v,c),v}}function dr(r){if(r<rr)throw new Error("sqrt is not defined for small field");let e=r-re,s=0;for(;e%Ne===oe;)e/=Ne,s++;let t=Ne;const n=xt(r);for(;hr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return lr;let i=n.pow(t,e);const o=(e+re)/Ne;return function(c,l){if(c.is0(l))return l;if(hr(c,l)!==1)throw new Error("Cannot find square root");let d=s,p=c.mul(c.ONE,i),g=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let f=1,b=c.sqr(g);for(;!c.eql(b,c.ONE);)if(f++,b=c.sqr(b),f===d)throw new Error("Cannot find square root");const v=re<<BigInt(d-f-1),I=c.pow(p,v);d=f,p=c.sqr(I),g=c.mul(g,p),_=c.mul(_,I)}return _}}function Qi(r){return r%nr===rr?lr:r%or===ir?Xi:r%ar===ji?Zi(r):dr(r)}const eo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function to(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=eo.reduce((t,n)=>(t[n]="function",t),e);return Gt(r,s),r}function so(r,e,s){if(s<oe)throw new Error("invalid exponent, negatives unsupported");if(s===oe)return r.ONE;if(s===re)return e;let t=r.ONE,n=e;for(;s>oe;)s&re&&(t=r.mul(t,n)),n=r.sqr(n),s>>=re;return t}function ur(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function hr(r,e){const s=(r.ORDER-re)/Ne,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function ro(r,e){e!==void 0&&ve(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class no{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",oe);P(this,"ONE",re);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=oe)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=ro(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return he(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return he(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return he(e*e,this.ORDER)}add(e,s){return he(e+s,this.ORDER)}sub(e,s){return he(e-s,this.ORDER)}mul(e,s){return he(e*s,this.ORDER)}pow(e,s){return so(this,e,s)}div(e,s){return he(e*cr(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return cr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Qi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?tr(e,this.BYTES):Ft(e,this.BYTES)}fromBytes(e,s=!1){q(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?er(e):_t(e);if(a&&(c=he(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ur(this,e)}cmov(e,s,t){return t?s:e}}function xt(r,e={}){return new no(r,e)}function pr(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function fr(r){const e=pr(r);return e+Math.ceil(e/2)}function io(r,e,s=!1){q(r);const t=r.length,n=pr(e),i=fr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?er(r):_t(r),a=he(o,e-re)+re;return s?tr(a,n):Ft(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ze=BigInt(0),Le=BigInt(1);function mt(r,e){const s=e.negate();return r?s:e}function _r(r,e){const s=ur(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function gr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Vt(r,e){gr(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Kt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function xr(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Le);const l=e*t,d=l+Math.abs(a)-1,p=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:g,isNegF:_,offsetF:l}}const zt=new WeakMap,mr=new WeakMap;function Jt(r){return mr.get(r)||1}function wr(r){if(r!==ze)throw new Error("invalid wNAF")}class oo{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>ze;)s&Le&&(t=t.add(n)),n=n.double(),s>>=Le;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Vt(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Vt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:g,offsetF:_}=xr(t,a,o);t=c,d?i=i.add(mt(g,s[_])):n=n.add(mt(p,s[l]))}return wr(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=Vt(e,this.bits);for(let o=0;o<i.windows&&t!==ze;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=xr(t,o,i);if(t=a,!l){const p=s[c];n=n.add(d?p.negate():p)}}return wr(t),n}getPrecomputes(e,s,t){let n=zt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),zt.set(s,n))),n}cached(e,s,t){const n=Jt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=Jt(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){gr(s,this.bits),mr.set(e,s),zt.delete(e)}hasCache(e){return Jt(e)!==1}}function ao(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>ze||t>ze;)s&Le&&(i=i.add(n)),t&Le&&(o=o.add(n)),n=n.double(),s>>=Le,t>>=Le;return{p1:i,p2:o}}function yr(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return to(e),e}else return xt(r,{isLE:s})}function co(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>ze))throw new Error(`CURVE.${c} must be positive bigint`)}const n=yr(e.p,s.Fp,t),i=yr(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function lo(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class br{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(Gs(e),q(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ve(n)}update(e){return qe(this),this.iHash.update(e),this}digestInto(e){qe(this),q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sr=(r,e,s)=>new br(r,e).update(s).digest();Sr.create=(r,e)=>new br(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const vr=(r,e)=>(r+(r>=0?e:-e)/Er)/e;function uo(r,e,s){const[[t,n],[i,o]]=e,a=vr(o*r,s),c=vr(-n*r,s);let l=r-a*t-c*i,d=-a*n-c*o;const p=l<Ae,g=d<Ae;p&&(l=-l),g&&(d=-d);const _=Kt(Math.ceil(zi(s)/2))+Je;if(l<Ae||l>=_||d<Ae||d>=_)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,k1:l,k2neg:g,k2:d}}function Yt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function jt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return pt(s.lowS,"lowS"),pt(s.prehash,"prehash"),s.format!==void 0&&Yt(s.format),s}class ho extends Error{constructor(e=""){super(e)}}const Pe={Err:ho,_tlv:{encode:(r,e)=>{const{Err:s}=Pe;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=ft(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?ft(n.length/2|128):"";return ft(r)+i+n+e},decode(r,e){const{Err:s}=Pe;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Pe;if(r<Ae)throw new e("integer: negative integers are not allowed");let s=ft(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Pe;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return _t(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Pe,n=q(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Pe,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Je=BigInt(1),Er=BigInt(2),wt=BigInt(3),po=BigInt(4);function fo(r,e={}){const s=co("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;Gt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ir(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p($,m,w){const{x:T,y:O}=m.toAffine(),M=t.toBytes(T);if(pt(w,"isCompressed"),w){d();const y=!t.isOdd(O);return Re(Ar(y),M)}else return Re(Uint8Array.of(4),M,t.toBytes(O))}function g($){q($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=$.length,O=$[0],M=$.subarray(1);if(T===m&&(O===2||O===3)){const y=t.fromBytes(M);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const S=b(y);let E;try{E=t.sqrt(S)}catch(B){const U=B instanceof Error?": "+B.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}d();const A=t.isOdd(E);return(O&1)===1!==A&&(E=t.neg(E)),{x:y,y:E}}else if(T===w&&O===4){const y=t.BYTES,S=t.fromBytes(M.subarray(0,y)),E=t.fromBytes(M.subarray(y,y*2));if(!v(S,E))throw new Error("bad point: is not on curve");return{x:S,y:E}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const _=e.toBytes||p,f=e.fromBytes||g;function b($){const m=t.sqr($),w=t.mul(m,$);return t.add(t.add(w,t.mul($,i.a)),i.b)}function v($,m){const w=t.sqr(m),T=b($);return t.eql(w,T)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,wt),po),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,R)))throw new Error("bad curve params: a or b");function W($,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function D($){if(!($ instanceof X))throw new Error("Weierstrass Point expected")}function V($){if(!c||!c.basises)throw new Error("no endo");return uo($,c.basises,n.ORDER)}const G=sr(($,m)=>{const{X:w,Y:T,Z:O}=$;if(t.eql(O,t.ONE))return{x:w,y:T};const M=$.is0();m==null&&(m=M?t.ONE:t.inv(O));const y=t.mul(w,m),S=t.mul(T,m),E=t.mul(O,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:y,y:S}}),te=sr($=>{if($.is0()){if(e.allowInfinityPoint&&!t.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=$.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!v(m,w))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F($,m,w,T,O){return w=new X(t.mul(w.X,$),w.Y,w.Z),m=mt(T,m),w=mt(O,w),m.add(w)}const N=class N{constructor(m,w,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=W("x",m),this.Y=W("y",w,!0),this.Z=W("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof N)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?N.ZERO:new N(w,T,t.ONE)}static fromBytes(m){const w=N.fromAffine(f(q(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return N.fromBytes(ut(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return H.createCache(this,m),w||this.multiply(wt),this}assertValidity(){te(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){D(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:S}=m,E=t.eql(t.mul(w,S),t.mul(M,O)),A=t.eql(t.mul(T,S),t.mul(y,O));return E&&A}negate(){return new N(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,wt),{X:O,Y:M,Z:y}=this;let S=t.ZERO,E=t.ZERO,A=t.ZERO,k=t.mul(O,O),B=t.mul(M,M),U=t.mul(y,y),L=t.mul(O,M);return L=t.add(L,L),A=t.mul(O,y),A=t.add(A,A),S=t.mul(m,A),E=t.mul(T,U),E=t.add(S,E),S=t.sub(B,E),E=t.add(B,E),E=t.mul(S,E),S=t.mul(L,S),A=t.mul(T,A),U=t.mul(m,U),L=t.sub(k,U),L=t.mul(m,L),L=t.add(L,A),A=t.add(k,k),k=t.add(A,k),k=t.add(k,U),k=t.mul(k,L),E=t.add(E,k),U=t.mul(M,y),U=t.add(U,U),k=t.mul(U,L),S=t.sub(S,k),A=t.mul(U,B),A=t.add(A,A),A=t.add(A,A),new N(S,E,A)}add(m){D(m);const{X:w,Y:T,Z:O}=this,{X:M,Y:y,Z:S}=m;let E=t.ZERO,A=t.ZERO,k=t.ZERO;const B=i.a,U=t.mul(i.b,wt);let L=t.mul(w,M),K=t.mul(T,y),j=t.mul(O,S),le=t.add(w,T),Y=t.add(M,y);le=t.mul(le,Y),Y=t.add(L,K),le=t.sub(le,Y),Y=t.add(w,O);let ie=t.add(M,S);return Y=t.mul(Y,ie),ie=t.add(L,j),Y=t.sub(Y,ie),ie=t.add(T,O),E=t.add(y,S),ie=t.mul(ie,E),E=t.add(K,j),ie=t.sub(ie,E),k=t.mul(B,Y),E=t.mul(U,j),k=t.add(E,k),E=t.sub(K,k),k=t.add(K,k),A=t.mul(E,k),K=t.add(L,L),K=t.add(K,L),j=t.mul(B,j),Y=t.mul(U,Y),K=t.add(K,j),j=t.sub(L,j),j=t.mul(B,j),Y=t.add(Y,j),L=t.mul(K,Y),A=t.add(A,L),L=t.mul(ie,Y),E=t.mul(le,E),E=t.sub(E,L),L=t.mul(le,K),k=t.mul(ie,k),k=t.add(k,L),new N(E,A,k)}subtract(m){return this.add(m.negate())}is0(){return this.equals(N.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const M=y=>H.cached(this,y,S=>_r(N,S));if(w){const{k1neg:y,k1:S,k2neg:E,k2:A}=V(m),{p:k,f:B}=M(S),{p:U,f:L}=M(A);O=B.add(L),T=F(w.beta,k,U,y,E)}else{const{p:y,f:S}=M(m);T=y,O=S}return _r(N,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ae||T.is0())return N.ZERO;if(m===Je)return T;if(H.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:M,k2neg:y,k2:S}=V(m),{p1:E,p2:A}=ao(N,T,M,S);return F(w.beta,E,A,O,y)}else return H.unsafe(T,m)}toAffine(m){return G(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Je?!0:m?m(N,this):H.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Je?this:m?m(N,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return pt(m,"isCompressed"),this.assertValidity(),_(N,this,m)}toHex(m=!0){return Qe(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(N,"BASE",new N(i.Gx,i.Gy,t.ONE)),P(N,"ZERO",new N(t.ZERO,t.ONE,t.ZERO)),P(N,"Fp",t),P(N,"Fn",n);let X=N;const se=n.BITS,H=new oo(X,e.endo?Math.ceil(se/2):se);return X.BASE.precompute(8),X}function Ar(r){return Uint8Array.of(r?2:3)}function Ir(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function _o(r,e={}){const{Fn:s}=r,t=e.randomBytes||js,n=Object.assign(Ir(r.Fp,s),{seed:fr(s.ORDER)});function i(_){try{const f=s.fromBytes(_);return s.isValidNot0(f)}catch{return!1}}function o(_,f){const{publicKey:b,publicKeyUncompressed:v}=n;try{const I=_.length;return f===!0&&I!==b||f===!1&&I!==v?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return io(q(_,n.seed,"seed"),s.ORDER)}function c(_,f=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(f)}function l(_){const{secretKey:f,publicKey:b,publicKeyUncompressed:v}=n;if(!Wt(_)||"_lengths"in s&&s._lengths||f===b)return;const I=q(_,void 0,"key").length;return I===b||I===v}function d(_,f,b=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");const v=s.fromBytes(_);return r.fromBytes(f).multiply(v).toBytes(b)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=lo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:g,Point:r,utils:p,lengths:n})}function go(r,e,s={}){Gs(e),Gt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||js,n=s.hmac||((m,w)=>Sr(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:g,lengths:_}=_o(r,s),f={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*Er<i.ORDER;function v(m){const w=a>>Je;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function R(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function W(m,w){Yt(w);const T=_.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return q(m,O)}class D{constructor(w,T,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=I("r",w),this.s=I("s",T),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=f.format){W(w,T);let O;if(T==="der"){const{r:E,s:A}=Pe.toSig(q(w));return new D(E,A)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const M=_.signature/2,y=w.subarray(0,M),S=w.subarray(M,M*2);return new D(o.fromBytes(y),o.fromBytes(S),O)}static fromHex(w,T){return this.fromBytes(ut(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new D(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,M=this.assertRecovery(),y=M===2||M===3?T+a:T;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const S=i.toBytes(y),E=r.fromBytes(Re(Ar((M&1)===0),S)),A=o.inv(y),k=G(q(w,void 0,"msgHash")),B=o.create(-k*A),U=o.create(O*A),L=r.BASE.multiplyUnsafe(B).add(E.multiplyUnsafe(U));if(L.is0())throw new Error("invalid recovery: point at infinify");return L.assertValidity(),L}hasHighS(){return v(this.s)}toBytes(w=f.format){if(Yt(w),w==="der")return ut(Pe.hexFromSig(this));const{r:T,s:O}=this,M=o.toBytes(T),y=o.toBytes(O);return w==="recovered"?(R(),Re(Uint8Array.of(this.assertRecovery()),M,y)):Re(M,y)}toHex(w){return Qe(this.toBytes(w))}}const V=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=_t(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},G=s.bits2int_modN||function(w){return o.create(V(w))},te=Kt(c);function F(m){return Vi("num < 2^"+c,m,Ae,te),o.toBytes(m)}function X(m,w){return q(m,void 0,"message"),w?q(e(m),void 0,"prehashed message"):m}function se(m,w,T){const{lowS:O,prehash:M,extraEntropy:y}=jt(T,f);m=X(m,M);const S=G(m),E=o.fromBytes(w);if(!o.isValidNot0(E))throw new Error("invalid private key");const A=[F(E),F(S)];if(y!=null&&y!==!1){const L=y===!0?t(_.secretKey):y;A.push(q(L,void 0,"extraEntropy"))}const k=Re(...A),B=S;function U(L){const K=V(L);if(!o.isValidNot0(K))return;const j=o.inv(K),le=r.BASE.multiply(K).toAffine(),Y=o.create(le.x);if(Y===Ae)return;const ie=o.create(j*o.create(B+Y*E));if(ie===Ae)return;let Yr=(le.x===Y?0:2)|Number(le.y&Je),jr=ie;return O&&v(ie)&&(jr=o.neg(ie),Yr^=1),new D(Y,jr,b?void 0:Yr)}return{seed:k,k2sig:U}}function H(m,w,T={}){const{seed:O,k2sig:M}=se(m,w,T);return Ji(e.outputLen,o.BYTES,n)(O,M).toBytes(T.format)}function N(m,w,T,O={}){const{lowS:M,prehash:y,format:S}=jt(O,f);if(T=q(T,void 0,"publicKey"),w=X(w,y),!Wt(m)){const E=m instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}W(m,S);try{const E=D.fromBytes(m,S),A=r.fromBytes(T);if(M&&E.hasHighS())return!1;const{r:k,s:B}=E,U=G(w),L=o.inv(B),K=o.create(U*L),j=o.create(k*L),le=r.BASE.multiplyUnsafe(K).add(A.multiplyUnsafe(j));return le.is0()?!1:o.create(le.x)===k}catch{return!1}}function $(m,w,T={}){const{prehash:O}=jt(T,f);return w=X(w,O),D.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:g,lengths:_,Point:r,sign:H,verify:N,recoverPublicKey:$,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tr=BigInt(2);function mo(r){const e=Xt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,p=de(d,s,e)*d%e,g=de(p,s,e)*d%e,_=de(g,Tr,e)*l%e,f=de(_,n,e)*_%e,b=de(f,i,e)*f%e,v=de(b,a,e)*b%e,I=de(v,c,e)*v%e,R=de(I,a,e)*b%e,W=de(R,s,e)*d%e,D=de(W,o,e)*f%e,V=de(D,t,e)*l%e,G=de(V,Tr,e);if(!Zt.eql(Zt.sqr(G),r))throw new Error("Cannot find square root");return G}const Zt=xt(Xt.p,{sqrt:mo}),wo=go(fo(Xt,{Fp:Zt,endo:xo}),Ki),yo=BigInt(0),et=BigInt(1),bo=BigInt(2),So=BigInt(7),vo=BigInt(256),Eo=BigInt(113),Rr=[],kr=[],Or=[];for(let r=0,e=et,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Rr.push(2*(5*t+s)),kr.push((r+1)*(r+2)/2%64);let n=yo;for(let i=0;i<7;i++)e=(e<<et^(e>>So)*Eo)%vo,e&bo&&(n^=et<<(et<<BigInt(i))-et);Or.push(n)}const Pr=Di(Or,!0),Ao=Pr[0],Io=Pr[1],Cr=(r,e,s)=>s>32?Wi(r,e,s):Mi(r,e,s),Nr=(r,e,s)=>s>32?Ui(r,e,s):$i(r,e,s);function To(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],p=Cr(l,d,1)^s[a],g=Nr(l,d,1)^s[a+1];for(let _=0;_<50;_+=10)r[o+_]^=p,r[o+_+1]^=g}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=kr[o],c=Cr(n,i,a),l=Nr(n,i,a),d=Rr[o];n=r[d],i=r[d+1],r[d]=c,r[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Ao[t],r[1]^=Io[t]}Ve(s)}class Qt{constructor(e,s,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ai(this.state)}clone(){return this._cloneInto()}keccak(){Vs(this.state32),To(this.state32,this.rounds),Vs(this.state32),this.posOut=0,this.pos=0}update(e){qe(this),q(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){qe(this,!1),q(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qs(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ve(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Qt(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Lr=((r,e,s,t={})=>Ys(()=>new Qt(e,r,s),t))(1,136,32),Ro=60;class ko{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Si(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Ro<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await pi(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ei(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
-
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Lr(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Oo(a),l=c.slice(0,32),d=c.slice(32,64),p=c[64],g=p>=27?p-27:p,b=new wo.Signature(Dr(l),Dr(d)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),v=Lr(b);return"0x"+Qe(v.slice(12))}}function Oo(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function Dr(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const Po=3e4,Co=1e3;class No{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,Co*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??Po);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Lo=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class De{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=De.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await De.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=De.generateRandom16Hex(),l=De.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),D(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,b=30;let v=0,I=null;const R=()=>{clearInterval(W),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+b+"초간 대기합니다"),I=setTimeout(()=>{D(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},b*1e3)},W=setInterval(()=>{v++;try{g.closed&&(v<=f?R():(D(),t(new Error("로그인이 취소되었습니다"))))}catch{R()}},1e3),D=()=>{clearTimeout(_),clearInterval(W),I&&clearTimeout(I),window.removeEventListener("message",V)},V=G=>{if(G.origin!==e.expectedOrigin)return;if(!Lo.has(G.origin)){u.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),D(),t(new Error("Unauthorized OAuth origin"));return}D();const te=typeof G.data.status=="string",F=te?G.data.data??{}:G.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:te?"wrapped":"flat",status:te?G.data.status:"(flat)"});const X=(F==null?void 0:F.state)??G.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(te&&G.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",F==null?void 0:F.error),t(new Error((F==null?void 0:F.error)||"Authentication failed"));return}if(!te&&(F!=null&&F.error)){u.error("[CROSSx] OAuth 실패:",F.error),t(new Error(F.error||"Authentication failed"));return}const se=F==null?void 0:F.idToken,H=F==null?void 0:F.accessToken,N=H??se,$=(F==null?void 0:F.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!H,hasIdToken:!!se,hasEmail:!!$}),!N){u.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const m={token:N,email:$},w=T=>{De.verifyIdTokenNonce(T,l).then(()=>s(m)).catch(O=>{u.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};H?H.split(".").length===3?w(H):se?w(se):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):se?w(se):t(new Error("Token not found in response"))};window.addEventListener("message",V)})}}const tt="crossx_wallet_data",Ye="crossx_mock_pin_hash";class Do{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(tt)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(tt);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(tt,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(Ye,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(tt);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,i,o){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Ye);return s&&s!==e?!1:(s||await this.storage.set(Ye,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ye);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ye,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new x(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(tt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ye,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Me{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(ws))return e;const s=!e||this.tokenStore.isExpiringSoon(ws);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,d,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const f=_.message||_.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:f,url:o,method:e});const b=Me.mapGatewayError(_.code,_.data);if(b===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(b===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(h.USER_NOT_FOUND,Me.getGatewayErrorMessage(_.code,f));const v=b===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:b,I=v===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(_.code,f),R=_.data;let W;throw b===h.PIN_LOCKED?W=Me.extractLockDetails(R):b===h.ADDRESS_LIMIT_EXCEEDED?W={limit:It,raw:R}:W=R??void 0,new x(v,I,W)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(g){if(g instanceof x)throw g;const _=((l=g.response)==null?void 0:l.status)??g.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((d=g.response)!=null&&d.data){const f=g.response.data,b=f.message||f.data||"API 요청에 실패했습니다",v=f.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:v,message:b,url:o,method:e,status:(p=g.response)==null?void 0:p.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${v}): ${b}`)}throw g}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new x(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new x(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new x(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new x(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return Me.hasLockInfo(s)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${s}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${It} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class st{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=st.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?_n:fn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new x(st.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=st.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(rt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Mr="__crossx-confirm-style",ee="__crossx-confirm-overlay",Mo={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function $r(r,e){const s=Mo[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const $o=`
|
|
5
|
+
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},rn={ko:sn,en:ls};function be(r="en",e){return rn[r]??ls}const ds="crossx_access_token",us="crossx_refresh_token",hs="crossx_user_info",St=class St{constructor(e,s,t,n,i,o,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new x(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new x(h.OAUTH_POPUP_BLOCKED,i):new x(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:d}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,d);let _,f,y;try{const T=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(T).join(", ")),f=(i=T.firebase)==null?void 0:i.sign_in_provider;const P=((o=T.firebase)==null?void 0:o.identities)??{};y=T.email??((a=P.email)==null?void 0:a[0]),f==="google.com"?_=(c=P["google.com"])==null?void 0:c[0]:f==="apple.com"&&(_=(l=P["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",f,"hasProviderSub:",!!_,"email:",y??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const T=this.crypto.decodeJWT(p);u.log("[CROSSx] access_token 디코딩 — sub:",T.sub,"exp:",T.exp,"필드:",Object.keys(T).join(", "));const P=await this.crypto.verifyJWT(p);if(n=P.signatureVerified??!1,!P.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const k=P.payload,N=k.email??y??s;u.log("[CROSSx] email 소스 — CROSSx JWT:",k.email??"(없음)","/ Firebase JWT:",y??"(없음)","/ OAuth 콜백:",s??"(없음)","→",N??"(없음)"),t={id:k.sub,email:N,signInProvider:f,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const T=this.crypto.decodeJWT(e);t={id:T.sub,email:T.email??s,signInProvider:f,providerSub:_},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const E=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,E),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof x&&e.code===h.SESSION_EXPIRED;return u.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const d=this.tokenStore.get()??"";d&&(i.access_token=d),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=St.REFRESH_RELOGIN_CODES.has(c.code);throw new x(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new x(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof x&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(hs);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(ds);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(us);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(hs),await this.storage.remove(ds),await this.storage.remove(us),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof x&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof x&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};St.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let At=St;class nn{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class on{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class It{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class an{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new x(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class cn{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}var nt={environment:"production"};const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function ln(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}function ps(){try{if(typeof nt<"u"){const r=typeof nt=="string"?JSON.parse(nt):nt,e=ln(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Ue)return Ue[r]}catch{}return Ue.production}const dn=2e3,fs=6e4,un=1e3,hn=1e4,pn="0x77359400",_s="0x3B9ACA00",gs=130,xs=6,ms=18,ws=3e4,fn=5*60*1e3,_n=30*1e3,it=100;function ys(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===48;)e--;return r.slice(0,e)}function gn(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(ms),t=e/s,i=(e%s).toString().padStart(ms,"0"),o=ys(i).slice(0,xs);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function ot(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),i=t/n,a=(t%n).toString().padStart(s,"0"),c=ys(a.slice(0,xs));return`${c?`${i}.${c}`:`${i}`} ${e}`}catch{return}}function xn(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==gs)throw new x(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${gs} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function mn(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function wn(r,e){const s=yn(e);if(r==="0"){if(s!==void 0&&s!==0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${s}`);return}const t=r.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(s===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function yn(r){if(r==null||typeof r!="object")return;const e=r.domain;if(e==null||typeof e!="object")return;const s=e.chainId;if(s==null)return;const t=Number(s);return Number.isFinite(t)?t:void 0}class He{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new x(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const s=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(d){if(this.deps.pinStore.clear(),d instanceof x){if(d.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(d.code===h.PIN_INVALID)return{ok:!1,error:d.message};if(d.code===h.PIN_LOCKED)return He.buildPinLockedResult(d,a)}throw d}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof x&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=be(this.deps.getLocale()??"en"),d=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:d?this.deps.maskEmail(d,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const s=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof x){if(t=He.parsePinError(n,s),!t)throw n}else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof x&&(t=He.parsePinError(n,s),t))continue;throw n}}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,s){const t=He.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class bn{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new x(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let t;return this.deps.walletProvider.prepare&&(t=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(t)})}}function Sn(r){return r==="google"||r==="apple"}class vn{constructor(e){this.deps=e}async signInAgain(){var s,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Sn(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((s=i.user)==null?void 0:s.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.sessionAlert_title,message:l.alert_differentAccount,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(s){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof x&&s.code===h.WITHDRAW_FAILED){if(u.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof x&&s.code===h.WALLET_NOT_FOUND){if(u.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof x)||s.code!==h.SESSION_EXPIRED)throw s;if(u.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:i})==="signout")throw this.deps.clearAuthState(),new x(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new x(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class En{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,s){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){const a=s?i.find(d=>d.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?i.find(d=>d.index===e):void 0,l=a??c??i[0];u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address),this.deps.setActiveWallet(l.address,l.index);return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class An{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:s});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const d=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(d===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,d,e));if(!p){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=d;break}if(p.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=d;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const _=g.lockExpiresAt*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),y=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${f}초, 메시지: ${y}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,y),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof x))throw p;if(p.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.sessionAlert_title,message:g.alert_sessionExpired,email:_?this.deps.maskEmail(_,g.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((g==null?void 0:g.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),y=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${f}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,y),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const d=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",d.address),d}catch(d){if(d instanceof x&&d.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(d instanceof x&&d.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:g?this.deps.maskEmail(g,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const y=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",y.address),y}catch(y){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",y),y}}throw this.deps.clearAuthState(),d}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",d),d}}}class In{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,i?this.deps.estimateGas(e,s):null,o?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=g;if(_){const f=_s;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(f)).toString(16)}`,c.maxPriorityFeePerGas=f,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=pn,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=_s,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Tn{constructor(e){this.crypto=e}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Rn(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class kn{constructor(e){this.deps=e}setActiveWallet(e,s){this.deps.setState({address:e,activeWalletIndex:s}),this.deps.emitAddressChanged({address:e,index:s}),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const s={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Rn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(s),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class On{constructor(e){this.deps=e}async resolveAddress(e){const s=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===s){if(!t)throw new x(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:s}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Pn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new x(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new x(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Cn{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const s=await this.deps.walletLifecycleService.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",s),s==="migration_required"){const t=this.deps.getProviderSub()??e;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return s==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const s=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(s.address,0),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function Tt(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const $e=class $e extends cn{constructor(e,s,t,n,i,o,a,c,l,d,p){var g,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&cs(e.logger),this.confirmation=l,this.pinStore=p??new It,this.stateManager=new kn({setState:f=>{f.authenticated!==void 0&&(this.authenticated=f.authenticated),f.userId!==void 0&&(this.userId=f.userId),f.address!==void 0&&(this.address=f.address),f.activeWalletIndex!==void 0&&(this.activeWalletIndex=f.activeWalletIndex),f.userEmail!==void 0&&(this.userEmail=f.userEmail),f.providerSub!==void 0&&(this.providerSub=f.providerSub),f.loginType!==void 0&&(this.loginType=f.loginType),f.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=f.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:f,index:y})=>{this.emit("addressChanged",{address:f,index:y})},emitAuthChanged:({isAuthenticated:f,address:y,userId:E})=>{this.emit("authChanged",{isAuthenticated:f,address:y,userId:E})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:$e.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new He({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Tt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new bn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator}),this.walletLifecycleService=new En({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(f,y)=>this.setActiveWallet(f,y)}),this.migrationOrchestrator=new An({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(f,y)=>this.migrateWalletUseCase.execute(f,y),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Tt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var f;return((f=this._config.migration)==null?void 0:f.allowSkip)??!0}}),this.transactionLifecycleService=new In({getActiveAddress:()=>this.address,estimateGas:(f,y)=>this.estimateGas(f,y),getBaseFeePerGas:f=>this.getBaseFeePerGas(f),jsonRpcCall:(f,y,E)=>this.jsonRpc.call(f,y,E)}),this.signatureVerifier=new Tn(this.crypto),this.addressResolverService=new On({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Pn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Cn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(f,y)=>this.setActiveWallet(f,y)}),this.sessionOrchestrator=new vn({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:f=>{this._isRecoveringSession=f},setAuthenticated:f=>{this.authenticated=f},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:f=>this.signInUseCase.execute(f),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:f=>this.confirmation.showSessionAlert(f),clearAuthState:()=>this.clearAuthState(),applyAuthResult:f=>this.applyAuthResult(f),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Tt}),this.chainRegistry=d,this.jsonRpc=new an(d,i),this.signInUseCase=new At(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new nn(this.internalConfig,t,c),this.migrateWalletUseCase=new on(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var s,t;u.log("[CROSSx SDK] v2.1.1 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=ps();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get($e.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index),a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.signInUseCase.restoreSession();if(c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(d){if(!(d instanceof x&&d.code===h.PIN_CANCELLED))throw d;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,u.info("[CROSSx SDK] v2.1.1 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new x(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:Zr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new x(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:s,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,s);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,s);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof x&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof x?s:new x(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof x&&s.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(s.address,0),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=s.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,s){if(e.length<2)return null;if(s){const t=e.find(n=>n.address.toLowerCase()===s.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:s,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");wn(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:s,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return xn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData($e.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Et(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return mn(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof x)throw o;const a=o instanceof Error?o.message:String(o);throw new x(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Et(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async a=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,a)).txHash;const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a);return c.txHash??c.signature}});return{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof x)throw o;const a=o instanceof Error?o.message:String(o);throw new x(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??un,i=hn,o=t.timeoutMs??fs,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var y,E;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((y=this._config.receiptPolling)==null?void 0:y.intervalMs)??dn,l=i??((E=this._config.receiptPolling)==null?void 0:E.timeoutMs)??fs,d=Et(e),p=s.from??"";let g,_;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(T=>{g=T;const P=BigInt(T.gasUsed)*BigInt(T.effectiveGasPrice),k=s.value?BigInt(s.value):0n,N=ot(s.value,d.symbol,d.decimals),F=ot("0x"+P.toString(16),d.symbol,d.decimals),G=ot("0x"+(k+P).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:T.from,to:T.to??s.to,amount:N,fees:F,total:G,nativeSymbol:d.symbol,status:T.status==="0x1"?"success":"reverted"}}).catch(T=>(_=T instanceof Error?T:new Error(String(T)),{chainId:e,txHash:a,from:p,to:s.to,amount:ot(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},f),_)throw _;return{chainId:e,txHash:a,receipt:g}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new x(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof x?n:new x(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new x(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:gn(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){return this.ensureAuthenticated(),new as(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const i=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,s){this.stateManager.setActiveWallet(e,s)}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState()}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,s){return this.walletLifecycleService.loadWalletAfterAuth(e,s)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),cs(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};$e.WALLET_PREF_KEY="wallet_preference",$e.OFFCHAIN_CHAIN_ID="0";let at=$e;class Nn{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const Rt="crossx-sdk",Ln=1,_e="data",Ce="keys",ct="aes-primary",Dn=12;class bs{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,Ln);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Ce)||i.createObjectStore(Ce)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ce,ct);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ce,ct,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Rt)return null;try{const e=await this.openDB(Rt),s=e.transaction([Ce,_e],"readonly"),t=s.objectStore(Ce).get(ct),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=s.objectStore(_e).getAll(),o=s.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ce,ct,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Rt),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(Dn);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(_e,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const kt=crypto,Ss=r=>r instanceof CryptoKey,lt=new TextEncoder,Xe=new TextDecoder;function Mn(...r){const e=r.reduce((n,{length:i})=>n+i,0),s=new Uint8Array(e);let t=0;for(const n of r)s.set(n,t),t+=n.length;return s}const $n=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},Te=r=>{let e=r;e instanceof Uint8Array&&(e=Xe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return $n(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class ee extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}ee.code="ERR_JOSE_GENERIC";class ue extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}ue.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ot extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}Ot.code="ERR_JWT_EXPIRED";class vs extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}vs.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class Wn extends ee{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}Wn.code="ERR_JWE_DECRYPTION_FAILED";class Un extends ee{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Un.code="ERR_JWE_INVALID";class Z extends ee{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Z.code="ERR_JWS_INVALID";class xe extends ee{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class Hn extends ee{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Hn.code="ERR_JWK_INVALID";class Pt extends ee{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Pt.code="ERR_JWKS_INVALID";class Ct extends ee{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ct.code="ERR_JWKS_NO_MATCHING_KEY";class Es extends ee{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Es.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class As extends ee{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}As.code="ERR_JWKS_TIMEOUT";class Is extends ee{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Is.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function me(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Ze(r,e){return r.name===e}function Nt(r){return parseInt(r.name.slice(4),10)}function Bn(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Fn(r,e){if(e.length&&!e.some(s=>r.usages.includes(s))){let s="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();s+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?s+=`one of ${e[0]} or ${e[1]}.`:s+=`${e[0]}.`;throw new TypeError(s)}}function Kn(r,e,...s){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ze(r.algorithm,"HMAC"))throw me("HMAC");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ze(r.algorithm,"RSASSA-PKCS1-v1_5"))throw me("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ze(r.algorithm,"RSA-PSS"))throw me("RSA-PSS");const t=parseInt(e.slice(2),10);if(Nt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw me("Ed25519 or Ed448");break}case"Ed25519":{if(!Ze(r.algorithm,"Ed25519"))throw me("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ze(r.algorithm,"ECDSA"))throw me("ECDSA");const t=Bn(e);if(r.algorithm.namedCurve!==t)throw me(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Fn(r,s)}function Ts(r,e,...s){var t;if(s=s.filter(Boolean),s.length>2){const n=s.pop();r+=`one of type ${s.join(", ")}, or ${n}.`}else s.length===2?r+=`one of type ${s[0]} or ${s[1]}.`:r+=`of type ${s[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const Rs=(r,...e)=>Ts("Key must be ",r,...e);function ks(r,e,...s){return Ts(`Key for the ${r} algorithm must be `,e,...s)}const Os=r=>Ss(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",dt=["CryptoKey"],Gn=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let s;for(const t of e){const n=Object.keys(t);if(!s||s.size===0){s=new Set(n);continue}for(const i of n){if(s.has(i))return!1;s.add(i)}}return!0};function qn(r){return typeof r=="object"&&r!==null}function Se(r){if(!qn(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const Vn=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:s}=e.algorithm;if(typeof s!="number"||s<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function Be(r){return Se(r)&&typeof r.kty=="string"}function zn(r){return r.kty!=="oct"&&typeof r.d=="string"}function Jn(r){return r.kty!=="oct"&&typeof r.d>"u"}function Yn(r){return Be(r)&&r.kty==="oct"&&typeof r.k=="string"}function jn(r){let e,s;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},s=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},s=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},s=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},s=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:s}}const Ps=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:s}=jn(r),t=[e,r.ext??!1,r.key_ops??s],n={...r};return delete n.alg,delete n.use,kt.subtle.importKey("jwk",n,...t)},Cs=r=>Te(r);let Fe,Ke;const Ns=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ut=async(r,e,s,t,n=!1)=>{let i=r.get(e);if(i!=null&&i[t])return i[t];const o=await Ps({...s,alg:t});return n&&Object.freeze(e),i?i[t]=o:r.set(e,{[t]:o}),o},Xn={normalizePublicKey:(r,e)=>{if(Ns(r)){let s=r.export({format:"jwk"});return delete s.d,delete s.dp,delete s.dq,delete s.p,delete s.q,delete s.qi,s.k?Cs(s.k):(Ke||(Ke=new WeakMap),ut(Ke,r,s,e))}return Be(r)?r.k?Te(r.k):(Ke||(Ke=new WeakMap),ut(Ke,r,r,e,!0)):r},normalizePrivateKey:(r,e)=>{if(Ns(r)){let s=r.export({format:"jwk"});return s.k?Cs(s.k):(Fe||(Fe=new WeakMap),ut(Fe,r,s,e))}return Be(r)?r.k?Te(r.k):(Fe||(Fe=new WeakMap),ut(Fe,r,r,e,!0)):r}};async function Ls(r,e){if(!Se(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Te(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ps({...r,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const Ge=r=>r==null?void 0:r[Symbol.toStringTag],Lt=(r,e,s)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,s))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},Zn=(r,e,s,t)=>{if(!(e instanceof Uint8Array)){if(t&&Be(e)){if(Yn(e)&&Lt(r,e,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Os(e))throw new TypeError(ks(r,e,...dt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Ge(e)} instances for symmetric algorithms must be of type "secret"`)}},Qn=(r,e,s,t)=>{if(t&&Be(e))switch(s){case"sign":if(zn(e)&&Lt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Jn(e)&&Lt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Os(e))throw new TypeError(ks(r,e,...dt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Ge(e)} instances for asymmetric algorithms must not be of type "secret"`);if(s==="sign"&&e.type==="public")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm signing must be of type "private"`);if(s==="decrypt"&&e.type==="public")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&s==="verify"&&e.type==="private")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&s==="encrypt"&&e.type==="private")throw new TypeError(`${Ge(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ds(r,e,s,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Zn(e,s,t,r):Qn(e,s,t,r)}Ds.bind(void 0,!1);const Ms=Ds.bind(void 0,!0);function ei(r,e,s,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;s!==void 0?i=new Map([...Object.entries(s),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new r(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new r(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const ti=(r,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(s=>typeof s!="string")))throw new TypeError(`"${r}" option must be an array of strings`);if(e)return new Set(e)};function si(r,e){const s=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function ri(r,e,s){if(e=await Xn.normalizePublicKey(e,r),Ss(e))return Kn(e,r,s),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(Rs(e,...dt));return kt.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(Rs(e,...dt,"Uint8Array","JSON Web Key"))}const ni=async(r,e,s,t)=>{const n=await ri(r,e,"verify");Vn(r,n);const i=si(r,n.algorithm);try{return await kt.subtle.verify(i,n,s,t)}catch{return!1}};async function ii(r,e,s){if(!Se(r))throw new Z("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new Z("JWS Protected Header incorrect type");if(r.payload===void 0)throw new Z("JWS Payload missing");if(typeof r.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(r.header!==void 0&&!Se(r.header))throw new Z("JWS Unprotected Header incorrect type");let t={};if(r.protected)try{const y=Te(r.protected);t=JSON.parse(Xe.decode(y))}catch{throw new Z("JWS Protected Header is invalid")}if(!Gn(t,r.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...r.header},i=ei(Z,new Map([["b64",!0]]),s==null?void 0:s.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&ti("algorithms",s.algorithms);if(c&&!c.has(a))throw new vs('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof r.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,r),l=!0,Ms(a,e,"verify"),Be(e)&&(e=await Ls(e,a))):Ms(a,e,"verify");const d=Mn(lt.encode(r.protected??""),lt.encode("."),typeof r.payload=="string"?lt.encode(r.payload):r.payload);let p;try{p=Te(r.signature)}catch{throw new Z("Failed to base64url decode the signature")}if(!await ni(a,e,p,d))throw new Is;let _;if(o)try{_=Te(r.payload)}catch{throw new Z("Failed to base64url decode the payload")}else typeof r.payload=="string"?_=lt.encode(r.payload):_=r.payload;const f={payload:_};return r.protected!==void 0&&(f.protectedHeader=t),r.header!==void 0&&(f.unprotectedHeader=r.header),l?{...f,key:e}:f}async function oi(r,e,s){if(r instanceof Uint8Array&&(r=Xe.decode(r)),typeof r!="string")throw new Z("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=r.split(".");if(o!==3)throw new Z("Invalid Compact JWS");const a=await ii({payload:n,protected:t,signature:i},e,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const ai=r=>Math.floor(r.getTime()/1e3),$s=60,Ws=$s*60,Dt=Ws*24,ci=Dt*7,li=Dt*365.25,di=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Us=r=>{const e=di.exec(r);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const s=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(s*$s);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(s*Ws);break;case"day":case"days":case"d":n=Math.round(s*Dt);break;case"week":case"weeks":case"w":n=Math.round(s*ci);break;default:n=Math.round(s*li);break}return e[1]==="-"||e[4]==="ago"?-n:n},Hs=r=>r.toLowerCase().replace(/^application\//,""),ui=(r,e)=>typeof r=="string"?e.includes(r):Array.isArray(r)?e.some(Set.prototype.has.bind(new Set(r))):!1,hi=(r,e,s={})=>{let t;try{t=JSON.parse(Xe.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=s;if(n&&(typeof r.typ!="string"||Hs(r.typ)!==Hs(n)))throw new ue('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=s,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const f of new Set(d.reverse()))if(!(f in t))throw new ue(`missing required "${f}" claim`,t,f,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new ue('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new ue('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!ui(t.aud,typeof c=="string"?[c]:c))throw new ue('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof s.clockTolerance){case"string":p=Us(s.clockTolerance);break;case"number":p=s.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=s,_=ai(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new ue('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new ue('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>_+p)throw new ue('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new ue('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=_-p)throw new Ot('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const f=_-t.iat,y=typeof l=="number"?l:Us(l);if(f-p>y)throw new Ot('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(f<0-p)throw new ue('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function pi(r,e,s){var o;const t=await oi(r,e,s);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:hi(t.protectedHeader,t.payload,s),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function fi(r){switch(typeof r=="string"&&r.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function _i(r){return r&&typeof r=="object"&&Array.isArray(r.keys)&&r.keys.every(gi)}function gi(r){return Se(r)}function Bs(r){return typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}class xi{constructor(e){if(this._cached=new WeakMap,!_i(e))throw new Pt("JSON Web Key Set malformed");this._jwks=Bs(e)}async getKey(e,s){const{alg:t,kid:n}={...e,...s==null?void 0:s.header},i=fi(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new Ct;if(c!==1){const l=new Es,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Fs(d,p,t)}catch{}},l}return Fs(this._cached,a,t)}}async function Fs(r,e,s){const t=r.get(e)||r.set(e,{}).get(e);if(t[s]===void 0){const n=await Ls({...e,ext:!0},s);if(n instanceof Uint8Array||n.type!=="public")throw new Pt("JSON Web Key Set members must be public keys");t[s]=n}return t[s]}function Ks(r){const e=new xi(r),s=async(t,n)=>e.getKey(t,n);return Object.defineProperties(s,{jwks:{value:()=>Bs(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),s}const mi=async(r,e,s)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(r.href,{signal:t?t.signal:void 0,redirect:"manual",headers:s.headers}).catch(a=>{throw i?new As:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new ee("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new ee("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function wi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Mt;(typeof navigator>"u"||!((Jr=(vt=navigator.userAgent)==null?void 0:vt.startsWith)!=null&&Jr.call(vt,"Mozilla/5.0 ")))&&(Mt="jose/v5.10.0");const $t=Symbol();function yi(r,e){return!(typeof r!="object"||r===null||!("uat"in r)||typeof r.uat!="number"||Date.now()-r.uat>=e||!("jwks"in r)||!Se(r.jwks)||!Array.isArray(r.jwks.keys)||!Array.prototype.every.call(r.jwks.keys,Se))}class bi{constructor(e,s){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:s==null?void 0:s.agent,headers:s==null?void 0:s.headers},this._timeoutDuration=typeof(s==null?void 0:s.timeoutDuration)=="number"?s==null?void 0:s.timeoutDuration:5e3,this._cooldownDuration=typeof(s==null?void 0:s.cooldownDuration)=="number"?s==null?void 0:s.cooldownDuration:3e4,this._cacheMaxAge=typeof(s==null?void 0:s.cacheMaxAge)=="number"?s==null?void 0:s.cacheMaxAge:6e5,(s==null?void 0:s[$t])!==void 0&&(this._cache=s==null?void 0:s[$t],yi(s==null?void 0:s[$t],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ks(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,s){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,s)}catch(t){if(t instanceof Ct&&this.coolingDown()===!1)return await this.reload(),this._local(e,s);throw t}}async reload(){this._pendingFetch&&wi()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Mt&&!e.has("User-Agent")&&(e.set("User-Agent",Mt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=mi(this._url,this._timeoutDuration,this._options).then(s=>{this._local=Ks(s),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=s),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(s=>{throw this._pendingFetch=void 0,s})),await this._pendingFetch}}function Si(r,e){const s=new bi(r,e),t=async(n,i)=>s.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!s._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=s._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const vi=Te;function Ei(r){if(typeof r!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=vi(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Xe.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Wt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ve(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function V(r,e,s=""){const t=Wt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function Gs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(r.outputLen),ve(r.blockLen)}function qe(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function qs(r,e){V(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Ai(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ve(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ut(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function we(r,e){return r<<32-e|r>>>e}const Ii=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ti(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Ri(r){for(let e=0;e<r.length;e++)r[e]=Ti(r[e]);return r}const Vs=Ii?r=>r:Ri,zs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ki=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Qe(r){if(V(r),zs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ki[r[s]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Js(r){if(r>=Ee._0&&r<=Ee._9)return r-Ee._0;if(r>=Ee.A&&r<=Ee.F)return r-(Ee.A-10);if(r>=Ee.a&&r<=Ee.f)return r-(Ee.a-10)}function ht(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(zs)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=Js(r.charCodeAt(i)),a=Js(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Re(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];V(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Ys(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function js(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const Oi=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Pi(r,e,s){return r&e^~r&s}function Ci(r,e,s){return r&e^r&s^e&s}class Ni{constructor(e,s,t,n){C(this,"blockLen");C(this,"outputLen");C(this,"padOffset");C(this,"isLE");C(this,"buffer");C(this,"view");C(this,"finished",!1);C(this,"length",0);C(this,"pos",0);C(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ut(this.buffer)}update(e){qe(this),V(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Ut(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){qe(this),qs(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ve(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Ut(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pt=BigInt(2**32-1),Xs=BigInt(32);function Li(r,e=!1){return e?{h:Number(r&pt),l:Number(r>>Xs&pt)}:{h:Number(r>>Xs&pt)|0,l:Number(r&pt)|0}}function Di(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Li(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const Mi=(r,e,s)=>r<<s|e>>>32-s,$i=(r,e,s)=>e<<s|r>>>32-s,Wi=(r,e,s)=>e<<s-32|r>>>64-s,Ui=(r,e,s)=>r<<s-32|e>>>64-s,Hi=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oe=new Uint32Array(64);class Bi extends Ni{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let p=0;p<16;p++,s+=4)Oe[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const g=Oe[p-15],_=Oe[p-2],f=we(g,7)^we(g,18)^g>>>3,y=we(_,17)^we(_,19)^_>>>10;Oe[p]=y+Oe[p-7]+f+Oe[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const g=we(a,6)^we(a,11)^we(a,25),_=d+g+Pi(a,c,l)+Hi[p]+Oe[p]|0,y=(we(t,2)^we(t,13)^we(t,22))+Ci(t,n,i)|0;d=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+y|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){Ve(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),Ve(this.buffer)}}class Fi extends Bi{constructor(){super(32);C(this,"A",ke[0]|0);C(this,"B",ke[1]|0);C(this,"C",ke[2]|0);C(this,"D",ke[3]|0);C(this,"E",ke[4]|0);C(this,"F",ke[5]|0);C(this,"G",ke[6]|0);C(this,"H",ke[7]|0)}}const Ki=Ys(()=>new Fi,Oi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ht=BigInt(0),Bt=BigInt(1);function ft(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Zs(r){if(typeof r=="bigint"){if(!xt(r))throw new Error("positive bigint expected, got "+r)}else ve(r);return r}function _t(r){const e=Zs(r).toString(16);return e.length&1?"0"+e:e}function Qs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ht:BigInt("0x"+r)}function gt(r){return Qs(Qe(r))}function er(r){return Qs(Qe(Gi(V(r)).reverse()))}function Ft(r,e){ve(e),r=Zs(r);const s=ht(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function tr(r,e){return Ft(r,e).reverse()}function Gi(r){return Uint8Array.from(r)}const xt=r=>typeof r=="bigint"&&Ht<=r;function qi(r,e,s){return xt(r)&&xt(e)&&xt(s)&&e<=r&&r<s}function Vi(r,e,s,t){if(!qi(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function zi(r){let e;for(e=0;r>Ht;r>>=Bt,e+=1);return e}const Kt=r=>(Bt<<BigInt(r))-Bt;function Ji(r,e,s){if(ve(r,"hashLen"),ve(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},g=(...E)=>s(l,Re(c,...E)),_=(E=n)=>{l=g(i,E),c=g(),E.length!==0&&(l=g(o,E),c=g())},f=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const T=[];for(;E<e;){c=g();const P=c.slice();T.push(P),E+=c.length}return Re(...T)};return(E,T)=>{p(),_(E);let P;for(;!(P=T(f()));)_();return p(),P}}function Gt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function sr(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oe=BigInt(0),re=BigInt(1),Ne=BigInt(2),rr=BigInt(3),nr=BigInt(4),ir=BigInt(5),Yi=BigInt(7),or=BigInt(8),ji=BigInt(9),ar=BigInt(16);function he(r,e){const s=r%e;return s>=oe?s:e+s}function de(r,e,s){let t=r;for(;e-- >oe;)t*=t,t%=s;return t}function cr(r,e){if(r===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let s=he(r,e),t=e,n=oe,i=re;for(;s!==oe;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==re)throw new Error("invert: does not exist");return he(n,e)}function qt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function lr(r,e){const s=(r.ORDER+re)/nr,t=r.pow(e,s);return qt(r,t,e),t}function Xi(r,e){const s=(r.ORDER-ir)/or,t=r.mul(e,Ne),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,Ne),n),a=r.mul(i,r.sub(o,r.ONE));return qt(r,a,e),a}function Zi(r){const e=mt(r),s=dr(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+Yi)/ar;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),_=a.eql(a.sqr(d),c),f=a.eql(a.sqr(p),c);l=a.cmov(l,d,_),d=a.cmov(g,p,f);const y=a.eql(a.sqr(d),c),E=a.cmov(l,d,y);return qt(a,E,c),E}}function dr(r){if(r<rr)throw new Error("sqrt is not defined for small field");let e=r-re,s=0;for(;e%Ne===oe;)e/=Ne,s++;let t=Ne;const n=mt(r);for(;hr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return lr;let i=n.pow(t,e);const o=(e+re)/Ne;return function(c,l){if(c.is0(l))return l;if(hr(c,l)!==1)throw new Error("Cannot find square root");let d=s,p=c.mul(c.ONE,i),g=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let f=1,y=c.sqr(g);for(;!c.eql(y,c.ONE);)if(f++,y=c.sqr(y),f===d)throw new Error("Cannot find square root");const E=re<<BigInt(d-f-1),T=c.pow(p,E);d=f,p=c.sqr(T),g=c.mul(g,p),_=c.mul(_,T)}return _}}function Qi(r){return r%nr===rr?lr:r%or===ir?Xi:r%ar===ji?Zi(r):dr(r)}const eo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function to(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=eo.reduce((t,n)=>(t[n]="function",t),e);return Gt(r,s),r}function so(r,e,s){if(s<oe)throw new Error("invalid exponent, negatives unsupported");if(s===oe)return r.ONE;if(s===re)return e;let t=r.ONE,n=e;for(;s>oe;)s&re&&(t=r.mul(t,n)),n=r.sqr(n),s>>=re;return t}function ur(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function hr(r,e){const s=(r.ORDER-re)/Ne,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function ro(r,e){e!==void 0&&ve(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class no{constructor(e,s={}){C(this,"ORDER");C(this,"BITS");C(this,"BYTES");C(this,"isLE");C(this,"ZERO",oe);C(this,"ONE",re);C(this,"_lengths");C(this,"_sqrt");C(this,"_mod");var o;if(e<=oe)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=ro(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return he(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return he(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return he(e*e,this.ORDER)}add(e,s){return he(e+s,this.ORDER)}sub(e,s){return he(e-s,this.ORDER)}mul(e,s){return he(e*s,this.ORDER)}pow(e,s){return so(this,e,s)}div(e,s){return he(e*cr(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return cr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Qi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?tr(e,this.BYTES):Ft(e,this.BYTES)}fromBytes(e,s=!1){V(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?er(e):gt(e);if(a&&(c=he(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ur(this,e)}cmov(e,s,t){return t?s:e}}function mt(r,e={}){return new no(r,e)}function pr(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function fr(r){const e=pr(r);return e+Math.ceil(e/2)}function io(r,e,s=!1){V(r);const t=r.length,n=pr(e),i=fr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?er(r):gt(r),a=he(o,e-re)+re;return s?tr(a,n):Ft(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ze=BigInt(0),Le=BigInt(1);function wt(r,e){const s=e.negate();return r?s:e}function _r(r,e){const s=ur(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function gr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Vt(r,e){gr(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Kt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function xr(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=Le);const l=e*t,d=l+Math.abs(a)-1,p=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:g,isNegF:_,offsetF:l}}const zt=new WeakMap,mr=new WeakMap;function Jt(r){return mr.get(r)||1}function wr(r){if(r!==ze)throw new Error("invalid wNAF")}class oo{constructor(e,s){C(this,"BASE");C(this,"ZERO");C(this,"Fn");C(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>ze;)s&Le&&(t=t.add(n)),n=n.double(),s>>=Le;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Vt(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Vt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:g,offsetF:_}=xr(t,a,o);t=c,d?i=i.add(wt(g,s[_])):n=n.add(wt(p,s[l]))}return wr(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=Vt(e,this.bits);for(let o=0;o<i.windows&&t!==ze;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=xr(t,o,i);if(t=a,!l){const p=s[c];n=n.add(d?p.negate():p)}}return wr(t),n}getPrecomputes(e,s,t){let n=zt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),zt.set(s,n))),n}cached(e,s,t){const n=Jt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=Jt(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){gr(s,this.bits),mr.set(e,s),zt.delete(e)}hasCache(e){return Jt(e)!==1}}function ao(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>ze||t>ze;)s&Le&&(i=i.add(n)),t&Le&&(o=o.add(n)),n=n.double(),s>>=Le,t>>=Le;return{p1:i,p2:o}}function yr(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return to(e),e}else return mt(r,{isLE:s})}function co(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>ze))throw new Error(`CURVE.${c} must be positive bigint`)}const n=yr(e.p,s.Fp,t),i=yr(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function lo(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class br{constructor(e,s){C(this,"oHash");C(this,"iHash");C(this,"blockLen");C(this,"outputLen");C(this,"finished",!1);C(this,"destroyed",!1);if(Gs(e),V(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ve(n)}update(e){return qe(this),this.iHash.update(e),this}digestInto(e){qe(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Sr=(r,e,s)=>new br(r,e).update(s).digest();Sr.create=(r,e)=>new br(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const vr=(r,e)=>(r+(r>=0?e:-e)/Er)/e;function uo(r,e,s){const[[t,n],[i,o]]=e,a=vr(o*r,s),c=vr(-n*r,s);let l=r-a*t-c*i,d=-a*n-c*o;const p=l<Ae,g=d<Ae;p&&(l=-l),g&&(d=-d);const _=Kt(Math.ceil(zi(s)/2))+Je;if(l<Ae||l>=_||d<Ae||d>=_)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,k1:l,k2neg:g,k2:d}}function Yt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function jt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ft(s.lowS,"lowS"),ft(s.prehash,"prehash"),s.format!==void 0&&Yt(s.format),s}class ho extends Error{constructor(e=""){super(e)}}const Pe={Err:ho,_tlv:{encode:(r,e)=>{const{Err:s}=Pe;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=_t(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?_t(n.length/2|128):"";return _t(r)+i+n+e},decode(r,e){const{Err:s}=Pe;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Pe;if(r<Ae)throw new e("integer: negative integers are not allowed");let s=_t(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Pe;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return gt(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Pe,n=V(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Pe,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Je=BigInt(1),Er=BigInt(2),yt=BigInt(3),po=BigInt(4);function fo(r,e={}){const s=co("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;Gt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Ir(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(W,m,w){const{x:I,y:O}=m.toAffine(),$=t.toBytes(I);if(ft(w,"isCompressed"),w){d();const b=!t.isOdd(O);return Re(Ar(b),$)}else return Re(Uint8Array.of(4),$,t.toBytes(O))}function g(W){V(W,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,I=W.length,O=W[0],$=W.subarray(1);if(I===m&&(O===2||O===3)){const b=t.fromBytes($);if(!t.isValid(b))throw new Error("bad point: is not on curve, wrong x");const S=y(b);let v;try{v=t.sqrt(S)}catch(B){const U=B instanceof Error?": "+B.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}d();const A=t.isOdd(v);return(O&1)===1!==A&&(v=t.neg(v)),{x:b,y:v}}else if(I===w&&O===4){const b=t.BYTES,S=t.fromBytes($.subarray(0,b)),v=t.fromBytes($.subarray(b,b*2));if(!E(S,v))throw new Error("bad point: is not on curve");return{x:S,y:v}}else throw new Error(`bad point: got length ${I}, expected compressed=${m} or uncompressed=${w}`)}const _=e.toBytes||p,f=e.fromBytes||g;function y(W){const m=t.sqr(W),w=t.mul(m,W);return t.add(t.add(w,t.mul(W,i.a)),i.b)}function E(W,m){const w=t.sqr(m),I=y(W);return t.eql(w,I)}if(!E(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const T=t.mul(t.pow(i.a,yt),po),P=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(T,P)))throw new Error("bad curve params: a or b");function k(W,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${W}`);return m}function N(W){if(!(W instanceof X))throw new Error("Weierstrass Point expected")}function F(W){if(!c||!c.basises)throw new Error("no endo");return uo(W,c.basises,n.ORDER)}const G=sr((W,m)=>{const{X:w,Y:I,Z:O}=W;if(t.eql(O,t.ONE))return{x:w,y:I};const $=W.is0();m==null&&(m=$?t.ONE:t.inv(O));const b=t.mul(w,m),S=t.mul(I,m),v=t.mul(O,m);if($)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:b,y:S}}),Q=sr(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=W.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!E(m,w))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function K(W,m,w,I,O){return w=new X(t.mul(w.X,W),w.Y,w.Z),m=wt(I,m),w=wt(O,w),m.add(w)}const D=class D{constructor(m,w,I){C(this,"X");C(this,"Y");C(this,"Z");this.X=k("x",m),this.Y=k("y",w,!0),this.Z=k("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:I}=m||{};if(!m||!t.isValid(w)||!t.isValid(I))throw new Error("invalid affine point");if(m instanceof D)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(I)?D.ZERO:new D(w,I,t.ONE)}static fromBytes(m){const w=D.fromAffine(f(V(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return D.fromBytes(ht(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return H.createCache(this,m),w||this.multiply(yt),this}assertValidity(){Q(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){N(m);const{X:w,Y:I,Z:O}=this,{X:$,Y:b,Z:S}=m,v=t.eql(t.mul(w,S),t.mul($,O)),A=t.eql(t.mul(I,S),t.mul(b,O));return v&&A}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,I=t.mul(w,yt),{X:O,Y:$,Z:b}=this;let S=t.ZERO,v=t.ZERO,A=t.ZERO,R=t.mul(O,O),B=t.mul($,$),U=t.mul(b,b),M=t.mul(O,$);return M=t.add(M,M),A=t.mul(O,b),A=t.add(A,A),S=t.mul(m,A),v=t.mul(I,U),v=t.add(S,v),S=t.sub(B,v),v=t.add(B,v),v=t.mul(S,v),S=t.mul(M,S),A=t.mul(I,A),U=t.mul(m,U),M=t.sub(R,U),M=t.mul(m,M),M=t.add(M,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,U),R=t.mul(R,M),v=t.add(v,R),U=t.mul($,b),U=t.add(U,U),R=t.mul(U,M),S=t.sub(S,R),A=t.mul(U,B),A=t.add(A,A),A=t.add(A,A),new D(S,v,A)}add(m){N(m);const{X:w,Y:I,Z:O}=this,{X:$,Y:b,Z:S}=m;let v=t.ZERO,A=t.ZERO,R=t.ZERO;const B=i.a,U=t.mul(i.b,yt);let M=t.mul(w,$),q=t.mul(I,b),j=t.mul(O,S),le=t.add(w,I),Y=t.add($,b);le=t.mul(le,Y),Y=t.add(M,q),le=t.sub(le,Y),Y=t.add(w,O);let ie=t.add($,S);return Y=t.mul(Y,ie),ie=t.add(M,j),Y=t.sub(Y,ie),ie=t.add(I,O),v=t.add(b,S),ie=t.mul(ie,v),v=t.add(q,j),ie=t.sub(ie,v),R=t.mul(B,Y),v=t.mul(U,j),R=t.add(v,R),v=t.sub(q,R),R=t.add(q,R),A=t.mul(v,R),q=t.add(M,M),q=t.add(q,M),j=t.mul(B,j),Y=t.mul(U,Y),q=t.add(q,j),j=t.sub(M,j),j=t.mul(B,j),Y=t.add(Y,j),M=t.mul(q,Y),A=t.add(A,M),M=t.mul(ie,Y),v=t.mul(le,v),v=t.sub(v,M),M=t.mul(le,q),R=t.mul(ie,R),R=t.add(R,M),new D(v,A,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(D.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let I,O;const $=b=>H.cached(this,b,S=>_r(D,S));if(w){const{k1neg:b,k1:S,k2neg:v,k2:A}=F(m),{p:R,f:B}=$(S),{p:U,f:M}=$(A);O=B.add(M),I=K(w.beta,R,U,b,v)}else{const{p:b,f:S}=$(m);I=b,O=S}return _r(D,[I,O])[0]}multiplyUnsafe(m){const{endo:w}=e,I=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ae||I.is0())return D.ZERO;if(m===Je)return I;if(H.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:$,k2neg:b,k2:S}=F(m),{p1:v,p2:A}=ao(D,I,$,S);return K(w.beta,v,A,O,b)}else return H.unsafe(I,m)}toAffine(m){return G(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Je?!0:m?m(D,this):H.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Je?this:m?m(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return ft(m,"isCompressed"),this.assertValidity(),_(D,this,m)}toHex(m=!0){return Qe(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};C(D,"BASE",new D(i.Gx,i.Gy,t.ONE)),C(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),C(D,"Fp",t),C(D,"Fn",n);let X=D;const se=n.BITS,H=new oo(X,e.endo?Math.ceil(se/2):se);return X.BASE.precompute(8),X}function Ar(r){return Uint8Array.of(r?2:3)}function Ir(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function _o(r,e={}){const{Fn:s}=r,t=e.randomBytes||js,n=Object.assign(Ir(r.Fp,s),{seed:fr(s.ORDER)});function i(_){try{const f=s.fromBytes(_);return s.isValidNot0(f)}catch{return!1}}function o(_,f){const{publicKey:y,publicKeyUncompressed:E}=n;try{const T=_.length;return f===!0&&T!==y||f===!1&&T!==E?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return io(V(_,n.seed,"seed"),s.ORDER)}function c(_,f=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(f)}function l(_){const{secretKey:f,publicKey:y,publicKeyUncompressed:E}=n;if(!Wt(_)||"_lengths"in s&&s._lengths||f===y)return;const T=V(_,void 0,"key").length;return T===y||T===E}function d(_,f,y=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");const E=s.fromBytes(_);return r.fromBytes(f).multiply(E).toBytes(y)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=lo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:g,Point:r,utils:p,lengths:n})}function go(r,e,s={}){Gs(e),Gt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||js,n=s.hmac||((m,w)=>Sr(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:g,lengths:_}=_o(r,s),f={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},y=a*Er<i.ORDER;function E(m){const w=a>>Je;return m>w}function T(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function P(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(m,w){Yt(w);const I=_.signature,O=w==="compact"?I:w==="recovered"?I+1:void 0;return V(m,O)}class N{constructor(w,I,O){C(this,"r");C(this,"s");C(this,"recovery");if(this.r=T("r",w),this.s=T("s",I),O!=null){if(P(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,I=f.format){k(w,I);let O;if(I==="der"){const{r:v,s:A}=Pe.toSig(V(w));return new N(v,A)}I==="recovered"&&(O=w[0],I="compact",w=w.subarray(1));const $=_.signature/2,b=w.subarray(0,$),S=w.subarray($,$*2);return new N(o.fromBytes(b),o.fromBytes(S),O)}static fromHex(w,I){return this.fromBytes(ht(w),I)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new N(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:O}=this,$=this.assertRecovery(),b=$===2||$===3?I+a:I;if(!i.isValid(b))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const S=i.toBytes(b),v=r.fromBytes(Re(Ar(($&1)===0),S)),A=o.inv(b),R=G(V(w,void 0,"msgHash")),B=o.create(-R*A),U=o.create(O*A),M=r.BASE.multiplyUnsafe(B).add(v.multiplyUnsafe(U));if(M.is0())throw new Error("invalid recovery: point at infinify");return M.assertValidity(),M}hasHighS(){return E(this.s)}toBytes(w=f.format){if(Yt(w),w==="der")return ht(Pe.hexFromSig(this));const{r:I,s:O}=this,$=o.toBytes(I),b=o.toBytes(O);return w==="recovered"?(P(),Re(Uint8Array.of(this.assertRecovery()),$,b)):Re($,b)}toHex(w){return Qe(this.toBytes(w))}}const F=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const I=gt(w),O=w.length*8-c;return O>0?I>>BigInt(O):I},G=s.bits2int_modN||function(w){return o.create(F(w))},Q=Kt(c);function K(m){return Vi("num < 2^"+c,m,Ae,Q),o.toBytes(m)}function X(m,w){return V(m,void 0,"message"),w?V(e(m),void 0,"prehashed message"):m}function se(m,w,I){const{lowS:O,prehash:$,extraEntropy:b}=jt(I,f);m=X(m,$);const S=G(m),v=o.fromBytes(w);if(!o.isValidNot0(v))throw new Error("invalid private key");const A=[K(v),K(S)];if(b!=null&&b!==!1){const M=b===!0?t(_.secretKey):b;A.push(V(M,void 0,"extraEntropy"))}const R=Re(...A),B=S;function U(M){const q=F(M);if(!o.isValidNot0(q))return;const j=o.inv(q),le=r.BASE.multiply(q).toAffine(),Y=o.create(le.x);if(Y===Ae)return;const ie=o.create(j*o.create(B+Y*v));if(ie===Ae)return;let Yr=(le.x===Y?0:2)|Number(le.y&Je),jr=ie;return O&&E(ie)&&(jr=o.neg(ie),Yr^=1),new N(Y,jr,y?void 0:Yr)}return{seed:R,k2sig:U}}function H(m,w,I={}){const{seed:O,k2sig:$}=se(m,w,I);return Ji(e.outputLen,o.BYTES,n)(O,$).toBytes(I.format)}function D(m,w,I,O={}){const{lowS:$,prehash:b,format:S}=jt(O,f);if(I=V(I,void 0,"publicKey"),w=X(w,b),!Wt(m)){const v=m instanceof N?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+v)}k(m,S);try{const v=N.fromBytes(m,S),A=r.fromBytes(I);if($&&v.hasHighS())return!1;const{r:R,s:B}=v,U=G(w),M=o.inv(B),q=o.create(U*M),j=o.create(R*M),le=r.BASE.multiplyUnsafe(q).add(A.multiplyUnsafe(j));return le.is0()?!1:o.create(le.x)===R}catch{return!1}}function W(m,w,I={}){const{prehash:O}=jt(I,f);return w=X(w,O),N.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:g,lengths:_,Point:r,sign:H,verify:D,recoverPublicKey:W,Signature:N,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},xo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Tr=BigInt(2);function mo(r){const e=Xt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,p=de(d,s,e)*d%e,g=de(p,s,e)*d%e,_=de(g,Tr,e)*l%e,f=de(_,n,e)*_%e,y=de(f,i,e)*f%e,E=de(y,a,e)*y%e,T=de(E,c,e)*E%e,P=de(T,a,e)*y%e,k=de(P,s,e)*d%e,N=de(k,o,e)*f%e,F=de(N,t,e)*l%e,G=de(F,Tr,e);if(!Zt.eql(Zt.sqr(G),r))throw new Error("Cannot find square root");return G}const Zt=mt(Xt.p,{sqrt:mo}),wo=go(fo(Xt,{Fp:Zt,endo:xo}),Ki),yo=BigInt(0),et=BigInt(1),bo=BigInt(2),So=BigInt(7),vo=BigInt(256),Eo=BigInt(113),Rr=[],kr=[],Or=[];for(let r=0,e=et,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Rr.push(2*(5*t+s)),kr.push((r+1)*(r+2)/2%64);let n=yo;for(let i=0;i<7;i++)e=(e<<et^(e>>So)*Eo)%vo,e&bo&&(n^=et<<(et<<BigInt(i))-et);Or.push(n)}const Pr=Di(Or,!0),Ao=Pr[0],Io=Pr[1],Cr=(r,e,s)=>s>32?Wi(r,e,s):Mi(r,e,s),Nr=(r,e,s)=>s>32?Ui(r,e,s):$i(r,e,s);function To(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],p=Cr(l,d,1)^s[a],g=Nr(l,d,1)^s[a+1];for(let _=0;_<50;_+=10)r[o+_]^=p,r[o+_+1]^=g}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=kr[o],c=Cr(n,i,a),l=Nr(n,i,a),d=Rr[o];n=r[d],i=r[d+1],r[d]=c,r[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Ao[t],r[1]^=Io[t]}Ve(s)}class Qt{constructor(e,s,t,n=!1,i=24){C(this,"state");C(this,"pos",0);C(this,"posOut",0);C(this,"finished",!1);C(this,"state32");C(this,"destroyed",!1);C(this,"blockLen");C(this,"suffix");C(this,"outputLen");C(this,"enableXOF",!1);C(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ai(this.state)}clone(){return this._cloneInto()}keccak(){Vs(this.state32),To(this.state32,this.rounds),Vs(this.state32),this.posOut=0,this.pos=0}update(e){qe(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){qe(this,!1),V(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qs(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ve(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Qt(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Lr=((r,e,s,t={})=>Ys(()=>new Qt(e,r,s),t))(1,136,32),Ro=60;class ko{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Si(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Ro<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await pi(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ei(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Lr(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Oo(a),l=c.slice(0,32),d=c.slice(32,64),p=c[64],g=p>=27?p-27:p,y=new wo.Signature(Dr(l),Dr(d)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),E=Lr(y);return"0x"+Qe(E.slice(12))}}function Oo(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function Dr(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const Po=3e4,Co=1e3;class No{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,Co*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??Po);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Lo=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class De{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=De.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await De.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=De.generateRandom16Hex(),l=De.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),N(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,y=30;let E=0,T=null;const P=()=>{clearInterval(k),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+y+"초간 대기합니다"),T=setTimeout(()=>{N(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},y*1e3)},k=setInterval(()=>{E++;try{g.closed&&(E<=f?P():(N(),t(new Error("로그인이 취소되었습니다"))))}catch{P()}},1e3),N=()=>{clearTimeout(_),clearInterval(k),T&&clearTimeout(T),window.removeEventListener("message",F)},F=G=>{if(G.origin!==e.expectedOrigin)return;if(!Lo.has(G.origin)){u.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),N(),t(new Error("Unauthorized OAuth origin"));return}N();const Q=typeof G.data.status=="string",K=Q?G.data.data??{}:G.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:Q?"wrapped":"flat",status:Q?G.data.status:"(flat)"});const X=(K==null?void 0:K.state)??G.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Q&&G.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",K==null?void 0:K.error),t(new Error((K==null?void 0:K.error)||"Authentication failed"));return}if(!Q&&(K!=null&&K.error)){u.error("[CROSSx] OAuth 실패:",K.error),t(new Error(K.error||"Authentication failed"));return}const se=K==null?void 0:K.idToken,H=K==null?void 0:K.accessToken,D=H??se,W=(K==null?void 0:K.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!H,hasIdToken:!!se,hasEmail:!!W}),!D){u.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const m={token:D,email:W},w=I=>{De.verifyIdTokenNonce(I,l).then(()=>s(m)).catch(O=>{u.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};H?H.split(".").length===3?w(H):se?w(se):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):se?w(se):t(new Error("Token not found in response"))};window.addEventListener("message",F)})}}const tt="crossx_wallet_data",Ye="crossx_mock_pin_hash";class Do{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(tt)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(tt);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(tt,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(Ye,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(tt);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,i,o){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Ye);return s&&s!==e?!1:(s||await this.storage.set(Ye,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ye);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ye,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new x(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(tt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ye,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Me{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(ws))return e;const s=!e||this.tokenStore.isExpiringSoon(ws);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,d,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const f=_.message||_.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:f,url:o,method:e});const y=Me.mapGatewayError(_.code,_.data);if(y===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(y===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(h.USER_NOT_FOUND,Me.getGatewayErrorMessage(_.code,f));const E=y===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:y,T=E===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(_.code,f),P=_.data;let k;throw y===h.PIN_LOCKED?k=Me.extractLockDetails(P):y===h.ADDRESS_LIMIT_EXCEEDED?k={limit:it,raw:P}:k=P??void 0,new x(E,T,k)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(g){if(g instanceof x)throw g;const _=((l=g.response)==null?void 0:l.status)??g.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((d=g.response)!=null&&d.data){const f=g.response.data,y=f.message||f.data||"API 요청에 실패했습니다",E=f.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:y,url:o,method:e,status:(p=g.response)==null?void 0:p.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${y}`)}throw g}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new x(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new x(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new x(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new x(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return Me.hasLockInfo(s)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${s}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${it} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class st{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=st.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?_n:fn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new x(st.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=st.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(rt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Mr="__crossx-confirm-style",te="__crossx-confirm-overlay",Mo={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function $r(r,e){const s=Mo[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const $o=`
|
|
7
7
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
8
8
|
|
|
9
|
-
#${
|
|
9
|
+
#${te} {
|
|
10
10
|
position: fixed;
|
|
11
11
|
inset: 0;
|
|
12
12
|
z-index: 2147483647;
|
|
@@ -1365,6 +1365,18 @@ button.__crossx-connect-other-block:active {
|
|
|
1365
1365
|
line-height: 1.3;
|
|
1366
1366
|
color: var(--cx-subtitle);
|
|
1367
1367
|
}
|
|
1368
|
+
.__crossx-wallet-add-error {
|
|
1369
|
+
margin: 8px 0 0;
|
|
1370
|
+
padding: 8px 10px;
|
|
1371
|
+
font-size: 13px;
|
|
1372
|
+
line-height: 1.45;
|
|
1373
|
+
color: var(--cx-error);
|
|
1374
|
+
background: color-mix(in srgb, var(--cx-error) 10%, transparent);
|
|
1375
|
+
border: 1px solid color-mix(in srgb, var(--cx-error) 35%, transparent);
|
|
1376
|
+
border-radius: 8px;
|
|
1377
|
+
word-break: break-word;
|
|
1378
|
+
}
|
|
1379
|
+
.__crossx-wallet-add-error[hidden] { display: none; }
|
|
1368
1380
|
|
|
1369
1381
|
/* ── Safe area fill (mobile only, created by JS in mountOverlay) ── */
|
|
1370
1382
|
.__crossx-safe-area-fill {
|
|
@@ -1372,7 +1384,7 @@ button.__crossx-connect-other-block:active {
|
|
|
1372
1384
|
}
|
|
1373
1385
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1374
1386
|
@media (max-width: 480px) {
|
|
1375
|
-
#${
|
|
1387
|
+
#${te} { align-items: flex-end; }
|
|
1376
1388
|
.__crossx-safe-area-fill {
|
|
1377
1389
|
display: block;
|
|
1378
1390
|
position: fixed;
|
|
@@ -1582,7 +1594,7 @@ button.__crossx-connect-other-block:active {
|
|
|
1582
1594
|
|
|
1583
1595
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1584
1596
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1585
|
-
#${
|
|
1597
|
+
#${te} { align-items: center !important; overflow: hidden; }
|
|
1586
1598
|
.__crossx-card--send-tx,
|
|
1587
1599
|
.__crossx-card--sign-tx,
|
|
1588
1600
|
.__crossx-card--sign-msg,
|
|
@@ -2077,7 +2089,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2077
2089
|
color: var(--cx-title);
|
|
2078
2090
|
margin: 0;
|
|
2079
2091
|
}
|
|
2080
|
-
`;function pe(){let r=document.getElementById(Mr);r||(r=document.createElement("style"),r.id=Mr,document.head.appendChild(r)),r.textContent=$o}function Wo(){const r=`#${
|
|
2092
|
+
`;function pe(){let r=document.getElementById(Mr);r||(r=document.createElement("style"),r.id=Mr,document.head.appendChild(r)),r.textContent=$o}function Wo(){const r=`#${te}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,r)&&t.stopImmediatePropagation()},s=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,r)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",s,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",s,!0)}}function fe(r){const e=r.querySelector(".__crossx-card");if(e){const o=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(o){const a=o[1].trim();r.style.setProperty("--cx-bg",a);const c=document.createElement("div");c.className="__crossx-safe-area-fill",c.style.background=a,r.appendChild(c)}}const s=i=>i.stopPropagation();for(const i of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(i,s);r.setAttribute("data-vaul-no-drag","");for(const i of["touchstart","touchend"])r.addEventListener(i,s);r.addEventListener("touchmove",i=>{i.stopPropagation();let o=i.target;for(;o&&o!==r;){const a=window.getComputedStyle(o);if((a.overflowY==="auto"||a.overflowY==="scroll")&&o.scrollHeight>o.clientHeight)return;o=o.parentElement}i.preventDefault()},{passive:!1});const t=Wo(),n=r.remove.bind(r);r.remove=()=>{t(),n()},document.body.appendChild(r)}const Uo=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function je(){if(Uo()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}}function ne(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function Wr(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=es(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Ur={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Hr(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Ur[e]?Ur[e]:r}function es(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,o=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function ts(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function Ho(r){try{return BigInt(r).toLocaleString()}catch{return r}}function Bo(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=r;if(!e)return null;try{const a=BigInt(e),c=Ho(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${es(l,o)} ${i}`,maxFeeGwei:ts(t),maxPriorityFeeGwei:n?ts(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${es(l,o)} ${i}`,gasPriceGwei:ts(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Br(r){const e=Bo(r);if(!e)return J("Estimated fee","<span>—</span>");let s=J("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=J("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=J("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=J("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=J("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const Ie=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2081
2093
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
2082
2094
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
2083
2095
|
</svg>`,ae=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
@@ -2096,8 +2108,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2096
2108
|
<div class="__crossx-row">
|
|
2097
2109
|
<span class="__crossx-row-label">${r}</span>
|
|
2098
2110
|
<div class="__crossx-row-value">${e}</div>
|
|
2099
|
-
</div>`}function Yo(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=
|
|
2100
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2111
|
+
</div>`}function Yo(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=bt(r.dappName),o=r.to?`<span class="__crossx-addr-text">${ne(r.to)}</span>
|
|
2112
|
+
<button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${Ie}</button>`:"<span>—</span>",a=Br(r),c=Wr(r.value,t,n),l=c?J("Value",`<span>${c}</span>`):"",d=r.data??"0x",p=document.createElement("div");return p.id=te,p.innerHTML=`
|
|
2101
2113
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2102
2114
|
<div class="__crossx-header">
|
|
2103
2115
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2108,7 +2120,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2108
2120
|
<div class="__crossx-body-cols">
|
|
2109
2121
|
<div class="__crossx-col-left">
|
|
2110
2122
|
<p class="__crossx-sig-subtitle">
|
|
2111
|
-
<span class="__crossx-sig-origin">${
|
|
2123
|
+
<span class="__crossx-sig-origin">${L(i)} </span>is requesting a Signature
|
|
2112
2124
|
</p>
|
|
2113
2125
|
<div class="__crossx-addr-pill">
|
|
2114
2126
|
${ss}
|
|
@@ -2124,7 +2136,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2124
2136
|
${l}
|
|
2125
2137
|
${a}
|
|
2126
2138
|
</div>
|
|
2127
|
-
<pre class="__crossx-raw-tx">${
|
|
2139
|
+
<pre class="__crossx-raw-tx">${L(d)}</pre>
|
|
2128
2140
|
</div>
|
|
2129
2141
|
</div>
|
|
2130
2142
|
<div class="__crossx-btn-row">
|
|
@@ -2133,8 +2145,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2133
2145
|
</div>
|
|
2134
2146
|
</div>
|
|
2135
2147
|
</div>
|
|
2136
|
-
`,p}function jo(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=
|
|
2137
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2148
|
+
`,p}function jo(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=bt(r.dappName),o=r.to?`<span class="__crossx-addr-text">${ne(r.to)}</span>
|
|
2149
|
+
<button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${Ie}</button>`:"<span>—</span>",a=Br(r),l=Wr(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
|
|
2138
2150
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2139
2151
|
<div class="__crossx-header">
|
|
2140
2152
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -2143,7 +2155,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2143
2155
|
<hr class="__crossx-divider">
|
|
2144
2156
|
<div class="__crossx-body">
|
|
2145
2157
|
<p class="__crossx-tx-subtitle">
|
|
2146
|
-
<span class="__crossx-sig-origin">${
|
|
2158
|
+
<span class="__crossx-sig-origin">${L(i)}</span> wants your permission to approve the following transaction.
|
|
2147
2159
|
</p>
|
|
2148
2160
|
<div class="__crossx-body-cols">
|
|
2149
2161
|
<div class="__crossx-rows">
|
|
@@ -2159,13 +2171,13 @@ button.__crossx-connect-other-block:active {
|
|
|
2159
2171
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
2160
2172
|
</div>
|
|
2161
2173
|
</div>
|
|
2162
|
-
`,d}function
|
|
2163
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2164
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2165
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2174
|
+
`,d}function bt(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function L(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Xo(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Zo(r){if(typeof r=="string")return L(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return L(JSON.stringify(r))}catch{return String(r)}}function Qo(r,e){const s=J("From",`<span class="__crossx-addr-text">${ne(r.from)}</span>
|
|
2175
|
+
<button class="__crossx-copy-btn" data-copy="${L(r.from)}" title="Copy address">${Ie}</button>`),t=r.to?J("To",`<span class="__crossx-addr-text">${ne(r.to)}</span>
|
|
2176
|
+
<button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${Ie}</button>`):"",n=r.amount?J("Transfer",`<span>${L(r.amount)}</span>`):"",i=r.fees?J("Tx Fee",`<span>${L(r.fees)}</span>`):"",o=r.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${ne(r.txHash)}</span>
|
|
2177
|
+
<button class="__crossx-copy-btn" data-copy="${L(r.txHash)}" title="Copy hash">${Ie}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
2166
2178
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2167
|
-
<span class="__crossx-total-amount">${
|
|
2168
|
-
</div>`:"",c=document.createElement("div");return c.id=
|
|
2179
|
+
<span class="__crossx-total-amount">${L(r.total)}</span>
|
|
2180
|
+
</div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
2169
2181
|
<div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2170
2182
|
<div class="__crossx-header">
|
|
2171
2183
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
@@ -2184,7 +2196,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2184
2196
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
2185
2197
|
</div>
|
|
2186
2198
|
</div>
|
|
2187
|
-
`,c}function ea(r,e){const s=document.createElement("div");return s.id=
|
|
2199
|
+
`,c}function ea(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
2188
2200
|
<div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2189
2201
|
<div class="__crossx-header">
|
|
2190
2202
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -2197,12 +2209,12 @@ button.__crossx-connect-other-block:active {
|
|
|
2197
2209
|
</div>
|
|
2198
2210
|
</div>
|
|
2199
2211
|
</div>
|
|
2200
|
-
`,s}function ta(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const f=n?Jo:t?"":zo,
|
|
2201
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2202
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2203
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2212
|
+
`,s}function ta(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const f=n?Jo:t?"":zo,y=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";f?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${f}<span>${y}</span>`):i.textContent=y}if(o&&!r.querySelector("#__crossx-close-btn")){const f=document.createElement("button");f.className="__crossx-close",f.id="__crossx-close-btn",f.setAttribute("aria-label","Close"),f.innerHTML=ae,o.appendChild(f)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?J("From",`<span class="__crossx-addr-text">${ne(e.from)}</span>
|
|
2213
|
+
<button class="__crossx-copy-btn" data-copy="${L(e.from)}" title="Copy address">${Ie}</button>`):"",l=e.to?J("To",`<span class="__crossx-addr-text">${ne(e.to)}</span>
|
|
2214
|
+
<button class="__crossx-copy-btn" data-copy="${L(e.to)}" title="Copy address">${Ie}</button>`):"",d=e.amount?J("Transfer",`<span>${L(e.amount)}</span>`):"",p=e.fees?J("Tx Fee",`<span>${L(e.fees)}</span>`):"",g=e.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${ne(e.txHash)}</span>
|
|
2215
|
+
<button class="__crossx-copy-btn" data-copy="${L(e.txHash)}" title="Copy hash">${Ie}</button>`):"",_=e.total?`<div class="__crossx-total-pill">
|
|
2204
2216
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2205
|
-
<span class="__crossx-total-amount">${
|
|
2217
|
+
<span class="__crossx-total-amount">${L(e.total)}</span>
|
|
2206
2218
|
</div>`:"";a.innerHTML=`
|
|
2207
2219
|
<div class="__crossx-rows">
|
|
2208
2220
|
${c}
|
|
@@ -2213,7 +2225,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2213
2225
|
</div>
|
|
2214
2226
|
${_}
|
|
2215
2227
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
2216
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",
|
|
2228
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",y=>{var T;y.stopPropagation();const E=f.dataset.copy;E&&((T=navigator.clipboard)==null||T.writeText(E).catch(()=>{}))})})}function sa(r,e){const s=e,t=bt(r.dappName),n=L(r.message),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2217
2229
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2218
2230
|
<div class="__crossx-header">
|
|
2219
2231
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2224,7 +2236,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2224
2236
|
<div class="__crossx-body-cols">
|
|
2225
2237
|
<div class="__crossx-col-left">
|
|
2226
2238
|
<p class="__crossx-sig-subtitle">
|
|
2227
|
-
<span class="__crossx-sig-origin">${
|
|
2239
|
+
<span class="__crossx-sig-origin">${L(t)} </span>is requesting a Signature
|
|
2228
2240
|
</p>
|
|
2229
2241
|
<div class="__crossx-addr-pill">
|
|
2230
2242
|
${ss}
|
|
@@ -2241,16 +2253,16 @@ button.__crossx-connect-other-block:active {
|
|
|
2241
2253
|
</div>
|
|
2242
2254
|
</div>
|
|
2243
2255
|
</div>
|
|
2244
|
-
`,i}function ra(r,e){const s=e,t=
|
|
2256
|
+
`,i}function ra(r,e){const s=e,t=bt(r.dappName);let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
|
|
2245
2257
|
<div class="__crossx-td-row">
|
|
2246
2258
|
<span class="__crossx-td-label">Primary Type</span>
|
|
2247
|
-
<span class="__crossx-td-value">${
|
|
2259
|
+
<span class="__crossx-td-value">${L(i)}</span>
|
|
2248
2260
|
</div>`;for(const[l,d]of Object.entries(o)){const p=Zo(d),_=Xo(d)?`<span class="__crossx-addr-text">${ne(d)}</span>
|
|
2249
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2261
|
+
<button class="__crossx-copy-btn" data-copy="${L(String(d))}" title="Copy">${Ie}</button>`:`<span>${p}</span>`;a+=`
|
|
2250
2262
|
<div class="__crossx-td-row">
|
|
2251
|
-
<span class="__crossx-td-label">${
|
|
2263
|
+
<span class="__crossx-td-label">${L(l)}</span>
|
|
2252
2264
|
<div class="__crossx-td-value">${_}</div>
|
|
2253
|
-
</div>`}const c=document.createElement("div");return c.id=
|
|
2265
|
+
</div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
2254
2266
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2255
2267
|
<div class="__crossx-header">
|
|
2256
2268
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2261,7 +2273,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2261
2273
|
<div class="__crossx-body-cols">
|
|
2262
2274
|
<div class="__crossx-col-left">
|
|
2263
2275
|
<p class="__crossx-sig-subtitle">
|
|
2264
|
-
<span class="__crossx-sig-origin">${
|
|
2276
|
+
<span class="__crossx-sig-origin">${L(t)} </span>is requesting a Signature
|
|
2265
2277
|
</p>
|
|
2266
2278
|
<div class="__crossx-addr-pill">
|
|
2267
2279
|
${ss}
|
|
@@ -2281,9 +2293,9 @@ button.__crossx-connect-other-block:active {
|
|
|
2281
2293
|
`,c}const na=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2282
2294
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2283
2295
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2284
|
-
</svg>`,ia='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="var(--cx-primary, #019d92)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Kr(r){return r.name||`Account ${r.index+1}`}function oa(){return`<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect width="32" height="32" rx="16" fill="#121212" fill-opacity="0.1"/><g fill="#121212" fill-opacity="0.5">${Fr}</g></svg>`}const aa=ps().portraitBaseUrl;function ca(r,e){return e.replace("#",""),`${aa}/portrait/evm/${r}.png?size=56`}function Gr(r,e,s){const t=ca(r,s),i=oa().replace(/"/g,""");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function la(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t,c=a?" __crossx-wallet-item--selected":"",l=a?`<span class="__crossx-wallet-selected">Selected</span><span class="__crossx-wallet-check">${ia}</span>`:"";return`<button class="__crossx-wallet-item${c}" data-wallet-index="${o.index}" data-wallet-address="${
|
|
2285
|
-
${Gr(o.address,o.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${
|
|
2286
|
-
</button>`}).join(""),i=document.createElement("div");return i.id=
|
|
2296
|
+
</svg>`,ia='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="var(--cx-primary, #019d92)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Kr(r){return r.name||`Account ${r.index+1}`}function oa(){return`<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect width="32" height="32" rx="16" fill="#121212" fill-opacity="0.1"/><g fill="#121212" fill-opacity="0.5">${Fr}</g></svg>`}const aa=ps().portraitBaseUrl;function ca(r,e){return e.replace("#",""),`${aa}/portrait/evm/${r}.png?size=56`}function Gr(r,e,s){const t=ca(r,s),i=oa().replace(/"/g,""");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function la(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t,c=a?" __crossx-wallet-item--selected":"",l=a?`<span class="__crossx-wallet-selected">Selected</span><span class="__crossx-wallet-check">${ia}</span>`:"";return`<button class="__crossx-wallet-item${c}" data-wallet-index="${o.index}" data-wallet-address="${L(o.address)}">
|
|
2297
|
+
${Gr(o.address,o.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${L(Kr(o))}</span><span class="__crossx-wallet-addr">${ne(o.address)}</span></span>${l}
|
|
2298
|
+
</button>`}).join(""),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2287
2299
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2288
2300
|
<div class="__crossx-header">
|
|
2289
2301
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2310,6 +2322,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2310
2322
|
<span class="__crossx-wallet-add-icon">${na}</span>
|
|
2311
2323
|
<span class="__crossx-wallet-add-label">add a wallet</span>
|
|
2312
2324
|
</button>
|
|
2325
|
+
<p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
|
|
2313
2326
|
</div>
|
|
2314
2327
|
</div>
|
|
2315
2328
|
</div>
|
|
@@ -2322,7 +2335,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2322
2335
|
<path d="M20.5 38.5c4.94 0 9.09-1.64 12.12-4.44l-5.91-4.57c-1.64 1.1-3.73 1.75-6.21 1.75-4.77 0-8.82-3.22-10.26-7.55H4.16v4.72A18.49 18.49 0 0 0 20.5 38.5z" fill="#34A853"/>
|
|
2323
2336
|
<path d="M10.24 23.69A11.16 11.16 0 0 1 9.66 20c0-1.28.22-2.52.58-3.69v-4.72H4.16A18.49 18.49 0 0 0 2 20c0 2.97.71 5.78 1.97 8.28l6.27-4.59z" fill="#FBBC05"/>
|
|
2324
2337
|
<path d="M20.5 8.76c2.69 0 5.1.92 7 2.73l5.24-5.24C29.58 3.36 25.43 1.5 20.5 1.5A18.49 18.49 0 0 0 4.16 11.59l6.08 4.72C11.68 11.98 15.73 8.76 20.5 8.76z" fill="#EA4335"/>
|
|
2325
|
-
</svg>`;function ha(r){const e=os(r);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Vo[r]??""}</span><span class="__crossx-connect-other-wallet-name">${
|
|
2338
|
+
</svg>`;function ha(r){const e=os(r);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Vo[r]??""}</span><span class="__crossx-connect-other-wallet-name">${L(e)}</span></span>`}function pa(r){if(r.length===0)return"";const e=n=>ha(r[n]),s="Supported wallets include ";if(r.length===1)return`${s}${e(0)}.`;if(r.length===2)return`${s}${e(0)} and ${e(1)}.`;if(r.length===3)return`${s}${e(0)}, ${e(1)} and ${e(2)}.`;const t=r.length-3;return`${s}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function fa(r,e=[]){const s=r,t=L(String(e[0])),n=e.length>0?`
|
|
2326
2339
|
<div class="__crossx-login-or-divider">
|
|
2327
2340
|
<hr><span>or</span><hr>
|
|
2328
2341
|
</div>
|
|
@@ -2331,7 +2344,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2331
2344
|
<span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">Connect with Other Wallets</span>
|
|
2332
2345
|
<span class="__crossx-connect-other-desc __crossx-connect-other-summary">${pa(e)}</span>
|
|
2333
2346
|
</span>
|
|
2334
|
-
</button>`:"",i=document.createElement("div");return i.id=
|
|
2347
|
+
</button>`:"",i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2335
2348
|
<div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2336
2349
|
<div class="__crossx-header">
|
|
2337
2350
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2357,29 +2370,29 @@ button.__crossx-connect-other-block:active {
|
|
|
2357
2370
|
</p>
|
|
2358
2371
|
</div>
|
|
2359
2372
|
</div>
|
|
2360
|
-
`,i}function _a(r,e){const s=r,t=document.createElement("div");t.id=
|
|
2361
|
-
<p class="__crossx-session-account-label">${
|
|
2362
|
-
<p class="__crossx-session-account-email">${
|
|
2373
|
+
`,i}function _a(r,e){const s=r,t=document.createElement("div");t.id=te;const n=L(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
|
|
2374
|
+
<p class="__crossx-session-account-label">${L(e.accountLabel)}</p>
|
|
2375
|
+
<p class="__crossx-session-account-email">${L(e.email)}</p>
|
|
2363
2376
|
</div>`:"";return t.innerHTML=`
|
|
2364
2377
|
<div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
|
|
2365
2378
|
<div class="__crossx-header">
|
|
2366
|
-
<p class="__crossx-title" id="__crossx-session-header-title">${
|
|
2379
|
+
<p class="__crossx-title" id="__crossx-session-header-title">${L(e.title)}</p>
|
|
2367
2380
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2368
2381
|
</div>
|
|
2369
2382
|
<hr class="__crossx-divider">
|
|
2370
2383
|
<div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
|
|
2371
2384
|
<div class="__crossx-session-hero">
|
|
2372
|
-
<p class="__crossx-session-hero-title">${
|
|
2385
|
+
<p class="__crossx-session-hero-title">${L(e.title)}</p>
|
|
2373
2386
|
<p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
|
|
2374
2387
|
</div>
|
|
2375
2388
|
${i}
|
|
2376
2389
|
<div class="__crossx-btn-row">
|
|
2377
|
-
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${
|
|
2378
|
-
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${
|
|
2390
|
+
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${L(e.signOutLabel)}</button>
|
|
2391
|
+
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${L(e.signInAgainLabel)}</button>
|
|
2379
2392
|
</div>
|
|
2380
2393
|
</div>
|
|
2381
2394
|
</div>
|
|
2382
|
-
`,t}function ga(r,e=!0){const s=r,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=
|
|
2395
|
+
`,t}function ga(r,e=!0){const s=r,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2383
2396
|
<div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2384
2397
|
<div class="__crossx-header">
|
|
2385
2398
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2399,7 +2412,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2399
2412
|
${n}
|
|
2400
2413
|
</div>
|
|
2401
2414
|
</div>
|
|
2402
|
-
`,i}function xa(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=
|
|
2415
|
+
`,i}function xa(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=te,p.innerHTML=`
|
|
2403
2416
|
<div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2404
2417
|
<div class="__crossx-header">
|
|
2405
2418
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2419,7 +2432,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2419
2432
|
${d}
|
|
2420
2433
|
</div>
|
|
2421
2434
|
</div>
|
|
2422
|
-
`,p}function ma(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function wa(r,e,s){const t=r,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?ma(i):null,a=document.createElement("div");return a.id=
|
|
2435
|
+
`,p}function ma(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function wa(r,e,s){const t=r,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?ma(i):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
2423
2436
|
<div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2424
2437
|
<div class="__crossx-header">
|
|
2425
2438
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2442,12 +2455,12 @@ button.__crossx-connect-other-block:active {
|
|
|
2442
2455
|
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function ya(r){const s=[r.check1,r.check2].map((t,n)=>`
|
|
2443
2456
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2444
2457
|
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Ea}</div>
|
|
2445
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2458
|
+
<span class="__crossx-pw-notice-item-text">${L(t)}</span>
|
|
2446
2459
|
</div>
|
|
2447
2460
|
`).join("");return`
|
|
2448
2461
|
<div class="__crossx-header">
|
|
2449
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2450
|
-
<p class="__crossx-pw-subtitle">${
|
|
2462
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${L(r.title)}</p>
|
|
2463
|
+
<p class="__crossx-pw-subtitle">${L(r.headerSubtitle)}</p>
|
|
2451
2464
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2452
2465
|
</div>
|
|
2453
2466
|
<hr class="__crossx-divider">
|
|
@@ -2456,25 +2469,25 @@ button.__crossx-connect-other-block:active {
|
|
|
2456
2469
|
<div class="__crossx-pw-notice-header">
|
|
2457
2470
|
<div class="__crossx-pw-notice-title-row">
|
|
2458
2471
|
<span class="__crossx-pw-notice-icon">${Aa}</span>
|
|
2459
|
-
<p class="__crossx-pw-notice-title">${
|
|
2472
|
+
<p class="__crossx-pw-notice-title">${L(r.noticeTitle)}</p>
|
|
2460
2473
|
</div>
|
|
2461
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2474
|
+
<p class="__crossx-pw-notice-desc">${L(r.noticeDesc)}</p>
|
|
2462
2475
|
</div>
|
|
2463
2476
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2464
2477
|
${s}
|
|
2465
2478
|
</div>
|
|
2466
2479
|
</div>
|
|
2467
2480
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2468
|
-
data-next-label="${
|
|
2469
|
-
data-submit-label="${
|
|
2470
|
-
${
|
|
2481
|
+
data-next-label="${L(r.nextButton)}"
|
|
2482
|
+
data-submit-label="${L(r.submitButton)}">
|
|
2483
|
+
${L(r.nextButton)}
|
|
2471
2484
|
</button>
|
|
2472
2485
|
</div>
|
|
2473
2486
|
<div class="__crossx-home-indicator"></div>
|
|
2474
|
-
`}function rs(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${
|
|
2487
|
+
`}function rs(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${L(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${L(r.subtitle)}</p>`:"",i=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${L(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2475
2488
|
${Vr}
|
|
2476
2489
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2477
|
-
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${
|
|
2490
|
+
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${L(r.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${r.attemptCount}/${r.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",d=Array.from({length:6},(y,E)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${E+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",g=Array.from({length:6},(y,E)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${E}" aria-label="PIN digit ${E+1}"></div>`).join(""),_=e?" --disabled":"",f=`
|
|
2478
2491
|
<div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
|
|
2479
2492
|
<div class="__crossx-pin6-numpad-row">
|
|
2480
2493
|
<button type="button" class="__crossx-pin6-numpad-key${_}" data-key="1">1</button>
|
|
@@ -2498,7 +2511,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2498
2511
|
</div>
|
|
2499
2512
|
</div>`;return`
|
|
2500
2513
|
<div class="__crossx-header">
|
|
2501
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2514
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${L(r.title)}</p>
|
|
2502
2515
|
${t}
|
|
2503
2516
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2504
2517
|
</div>
|
|
@@ -2517,11 +2530,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2517
2530
|
${o}
|
|
2518
2531
|
</div>
|
|
2519
2532
|
${f}
|
|
2520
|
-
`}function qr(r,e){const s=document.createElement("div");return s.id=
|
|
2533
|
+
`}function qr(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
2521
2534
|
<div class="__crossx-card __crossx-card--pin6" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2522
2535
|
${e}
|
|
2523
2536
|
</div>
|
|
2524
|
-
`,s}function ba(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Sa(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ns(r,e,s,t,n,i,o){var O
|
|
2537
|
+
`,s}function ba(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Sa(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ns(r,e,s,t,n,i,o){var O,$;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),d=()=>r.querySelector("#__crossx-pin6-boxes"),p=()=>r.querySelector("#__crossx-pin6-error"),g=()=>r.querySelector("#__crossx-pin6-lock-msg"),_=()=>r.querySelector("#__crossx-pin6-lock-countdown"),f=()=>r.querySelector(".__crossx-pin6-body"),y=()=>l().map(b=>b.value).join(""),E=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),T=()=>{var v;const b=l(),S=E();if(S.length&&(S.forEach((A,R)=>{const B=!!(b[R]&&b[R].value);A.classList.toggle("--filled",B),A.classList.toggle("--active",!1)}),!a&&!c)){const A=b.findIndex(B=>!B.value);(v=S[A===-1?5:A])==null||v.classList.add("--active")}},P=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(S=>S.classList.toggle("--disabled",a)),E().forEach(S=>S.classList.toggle("--locked",a)),T()},k=b=>{a=b,l().forEach(S=>{S.disabled=b,S.classList.toggle("--locked",b)})},N=()=>r.querySelector("#__crossx-pin6-attempt"),F=()=>{const b=p();b&&(b.textContent="")},G=()=>o??"Your account will be locked after further failures.",Q=()=>r.querySelector("#__crossx-pin6-warning"),K=b=>{var v;let S=Q();if(!S){S=document.createElement("p"),S.className="__crossx-pin6-warning",S.id="__crossx-pin6-warning";const A=p();A?A.insertAdjacentElement("afterend",S):(v=f())==null||v.appendChild(S)}S.textContent=b},X=()=>{const b=Q();b&&(b.textContent="")},se=(b,S)=>{var A;let v=N();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-attempt",v.id="__crossx-pin6-attempt";const R=Q()??p();R?R.insertAdjacentElement("afterend",v):(A=f())==null||A.appendChild(v)}v.textContent=`${b}/${S}`},H=()=>{const b=N();b&&(b.textContent="")},D=b=>{const S=p();S&&(S.textContent=b);const v=d();v==null||v.classList.add("--shake"),setTimeout(()=>v==null?void 0:v.classList.remove("--shake"),500),l().forEach(A=>{A.value=""}),setTimeout(()=>{var A;(A=l()[0])==null||A.focus(),T()},50)},W=b=>{var B;k(!0),l().forEach(U=>{U.value=""}),P();const S=p();if(S&&(S.textContent="Too many failed attempts. Please wait."),!g()){const U=document.createElement("p");U.className="__crossx-pin6-lock-msg",U.id="__crossx-pin6-lock-msg",U.innerHTML=`${Vr}<span id="__crossx-pin6-lock-countdown"></span>`;const M=p();M?M.insertAdjacentElement("afterend",U):(B=f())==null||B.appendChild(U)}const v=()=>{var q;const U=b-Date.now(),M=_();U<=0?(clearInterval(A),k(!1),(q=g())==null||q.remove(),S&&(S.textContent=""),P(),setTimeout(()=>{var j;return(j=l()[0])==null?void 0:j.focus()},50)):M&&(M.textContent=` ${Sa(U)}`)},A=setInterval(v,1e3);v();const R=new MutationObserver(()=>{document.contains(r)||(clearInterval(A),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},m=async()=>{if(a||c)return;const b=y();if(b.length===6){c=!0,l().forEach(S=>{S.disabled=!0});try{if(n){const S=await n(b);S.ok?e(b):S.lockExpiresAt?(H(),W(S.lockExpiresAt)):(D(S.error??"Incorrect PIN. Please try again."),S.attemptCount!=null&&S.maxAttempts!=null?(K(G()),se(S.attemptCount,S.maxAttempts)):(X(),H()))}else e(b)}catch(S){t&&t(S)}finally{c=!1,a||l().forEach(S=>{S.disabled=!1}),T()}}};i&&i>Date.now()?W(i):setTimeout(()=>{var b;return(b=l()[0])==null?void 0:b.focus()},100);const w=()=>{if(a||c)return;const b=l(),S=b.find(v=>!v.value)??b[b.length-1];S==null||S.focus()};(O=d())==null||O.addEventListener("click",b=>{b.target.classList.contains("__crossx-pin6-box")||w()}),($=f())==null||$.addEventListener("click",b=>{const S=b.target;S.classList.contains("__crossx-pin6-box")||S.closest("button")||w()}),l().forEach((b,S)=>{b.addEventListener("input",()=>{var A;const v=b.value.replace(/\D/g,"").slice(-1);b.value=v,F(),v&&S<5&&((A=l()[S+1])==null||A.focus()),T(),y().length===6&&setTimeout(m,80)}),b.addEventListener("keydown",v=>{var A,R;if(v.key==="Backspace"){if(v.preventDefault(),b.value)b.value="";else if(S>0){const B=l()[S-1];B.value="",B.focus()}T()}else v.key==="ArrowLeft"&&S>0?(v.preventDefault(),(A=l()[S-1])==null||A.focus()):v.key==="ArrowRight"&&S<5?(v.preventDefault(),(R=l()[S+1])==null||R.focus()):v.key==="Escape"&&s()}),b.addEventListener("paste",v=>{var B,U;v.preventDefault();const A=(((B=v.clipboardData)==null?void 0:B.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!A)return;const R=l();A.split("").forEach((M,q)=>{R[q]&&(R[q].value=M)}),(U=R[Math.min(A.length-1,5)])==null||U.focus(),F(),T(),y().length===6&&setTimeout(m,80)}),b.addEventListener("focus",()=>b.select())});const I=r.querySelector("#__crossx-pin6-numpad");if(I){let b=null;const S=()=>{b&&(b.classList.remove("--pressed"),b=null)};I.addEventListener("pointerdown",A=>{const R=A.target.closest(".__crossx-pin6-numpad-key");!R||a||c||(S(),b=R,R.classList.add("--pressed"),R.setPointerCapture(A.pointerId))});const v=A=>{const R=A.dataset.key;if(!R)return;if(R==="backspace"){const q=[...l()].reverse().find(j=>j.value);q&&(q.value="",F()),T();return}if(!/^\d$/.test(R))return;const U=l().find(M=>!M.value);U&&(U.value=R,F(),T(),y().length===6&&setTimeout(m,80))};I.addEventListener("pointerup",A=>{if(!b)return;const R=b;S();const B=R.getBoundingClientRect();A.clientX>=B.left&&A.clientX<=B.right&&A.clientY>=B.top&&A.clientY<=B.bottom&&!a&&!c&&v(R)}),I.addEventListener("pointercancel",S),I.addEventListener("pointerleave",S,!0),T(),i&&i>Date.now()&&P()}}const va=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2525
2538
|
<path d="M7.36 0.5H19.5C20.6046 0.5 21.5 1.39543 21.5 2.5V14.5C21.5 15.6046 20.6046 16.5 19.5 16.5H7.36C6.76 16.5 6.19 16.24 5.8 15.79L0.94 10.02C0.35 9.32 0.35 8.3 0.94 7.6L5.8 1.71C6.19 1.26 6.76 0.5 7.36 0.5Z" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
|
2526
2539
|
<line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2527
2540
|
<line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
@@ -2531,4 +2544,4 @@ button.__crossx-connect-other-block:active {
|
|
|
2531
2544
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2532
2545
|
</svg>`,Aa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2533
2546
|
<path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
|
|
2534
|
-
</svg>`;function Ia(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(d=>d.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,_)=>{t[_]&&(t[_].value=g)});const d=Math.min(l.length,3);t[d].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Ta{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=$r(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=$r(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var b;pe();const i=[...e],o=la(i,this.tokens,t),a=je();fe(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},d=v=>{l(),n(v)},p=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(v=>{v.addEventListener("click",()=>{const I=v.dataset.walletAddress??"",R=parseInt(v.dataset.walletIndex??"0",10),W=i.find(D=>D.index===R);d({address:I,index:R,name:W==null?void 0:W.name})})})})();const _=o.querySelector("#__crossx-add-wallet-btn");_&&_.addEventListener("click",async()=>{_.disabled=!0;try{const v=await s();i.push(v);const I=o.querySelector("#__crossx-wallet-list");if(I){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(v.index),R.dataset.walletAddress=v.address,R.innerHTML=`${Gr(v.address,v.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${C(Kr(v))}</span><span class="__crossx-wallet-addr">${ne(v.address)}</span></span>`,R.addEventListener("click",()=>d(v)),I.appendChild(R),R.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{_.disabled=!1}}),(b=o.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",p),o.addEventListener("click",v=>{v.target===o&&p()});const f=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",f),p())};document.addEventListener("keydown",f)})}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var g,_,f,b;pe();const i=fa(this.tokens,s),o=je();fe(i);const a=()=>{i.remove(),o()},c=v=>{a(),n({type:"oauth",provider:v})},l=v=>{a(),n({type:"external",walletId:v})},d=()=>{a(),n(null)};(g=i.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>c("apple")),(_=i.querySelector("#__crossx-google-btn"))==null||_.addEventListener("click",()=>c("google")),(f=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||f.addEventListener("click",v=>{const R=v.currentTarget.dataset.walletId??"";R&&l(R)}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",d),i.addEventListener("click",v=>{v.target===i&&d()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(v=>{v.addEventListener("click",I=>I.stopPropagation())});const p=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(s=>{var d,p,g;pe();const t=this.messages,n=_a(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=je();fe(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;pe();const n=ga(this.tokens,s);fe(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",g=>{g.target===n&&d()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(s=>{pe();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=qr(this.tokens,ya(n)),c=je();fe(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},p=R=>{d(),s(R)},g=()=>{d(),s(null)},_=a.querySelector(".__crossx-card"),f={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},b=R=>{var W;_.innerHTML=rs({title:o.title,headerSubtitle:o.headerSubtitle}),(W=_.querySelector("#__crossx-close-btn"))==null||W.addEventListener("click",g),ns(_,D=>{D===R?p(R):v(i.mismatchError)},g)},v=R=>{var W;_.innerHTML=rs({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:R}),(W=_.querySelector("#__crossx-close-btn"))==null||W.addEventListener("click",g),ns(_,D=>{const V=ba(D,f);V?v(V):b(D)},g)};(()=>{var se;const R=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),W=_.querySelector("#__crossx-pin-notice-next"),D=new Set;W.removeAttribute("disabled");const V=W.dataset.nextLabel??"Next",G=W.dataset.submitLabel??"I Understand",te=()=>{const H=D.size===R.length;W.classList.toggle("--disabled",!H),W.textContent=H?G:V},F=(H,N)=>{if(D.has(N))return;const $=H.querySelector(`#__crossx-notice-check-${N}`);D.add(N),$.classList.add("--checked"),H.setAttribute("aria-checked","true"),te()},X=(H,N)=>{if(!D.has(N))return;const $=H.querySelector(`#__crossx-notice-check-${N}`);D.delete(N),$.classList.remove("--checked"),H.setAttribute("aria-checked","false"),te()};R.forEach(H=>{const N=parseInt(H.dataset.checkIndex??"0",10);H.addEventListener("click",()=>{D.has(N)?X(H,N):F(H,N)}),H.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),D.has(N)?X(H,N):F(H,N))})}),W.addEventListener("click",()=>{if(D.size===R.length){v(e==null?void 0:e.errorMessage);return}const H=R.find($=>{const m=parseInt($.dataset.checkIndex??"0",10);return!D.has(m)});if(!H)return;const N=parseInt(H.dataset.checkIndex??"0",10);H.scrollIntoView({behavior:"smooth",block:"nearest"}),H.classList.add("--highlight"),setTimeout(()=>{H.classList.remove("--highlight"),F(H,N)},400)}),(se=_.querySelector("#__crossx-close-btn"))==null||se.addEventListener("click",g)})(),a.addEventListener("click",R=>{R.target===a&&g()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var I;pe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=qr(this.tokens,rs({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),d=je();fe(l);let p=!1;const g=()=>{p||(p=!0,l.remove(),d())},_=R=>{g(),s(R)},f=()=>{g(),s(null)},b=R=>{g(),t(R)},v=l.querySelector(".__crossx-card");(I=v.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",f),ns(v,_,f,b,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;pe();const t=xa(this.tokens,e);fe(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};Ia(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;pe();const{overlay:n,startCountdown:i}=wa(this.tokens,e,s);fe(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;pe();const t=Qo(e,this.tokens);fe(t);const n=()=>t.remove(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var g;d.stopPropagation();const p=l.dataset.copy;p&&((g=navigator.clipboard)==null||g.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{pe();const n=ea(e,this.tokens);fe(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,p;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(ta(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,d,p;pe();let t;e.type==="sign-message"?t=sa(e,this.tokens):e.type==="sign-typed-data"?t=ra(e,this.tokens):e.type==="sign"?t=Yo(e,this.tokens):t=jo(e,this.tokens);const n=je();fe(t);const i=()=>{t.remove(),n()},o=()=>{i(),s(!0)},a=()=>{i(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(d=t.querySelector("#__crossx-cancel-btn"))==null||d.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",_=>{var b;_.stopPropagation();const f=g.dataset.copy;f&&((b=navigator.clipboard)==null||b.writeText(f).catch(()=>{}))})}),t.addEventListener("click",g=>{g.target===t&&a()});const c=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class zr{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Ra(r,e){r.debug;const s=Ue.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},i=t.authMode!=="cookie"&&bs.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new bs(r.projectId):new Nn,a=new ko,c=new No,l=new De,d=new zr,p=new At;let g;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),g=new Do(o,p)):(u.log("[CROSSx] Remote Wallet Provider 사용"),g=new Me(n,o,c,d,p));const _=new st(n,c),f=new Ta(r.theme??"light",r.themeTokens),b=e!=null&&e.wrapConfirmation?e.wrapConfirmation(f):f,v=new ot(t,n,o,a,c,l,g,d,b,_,p);return typeof window<"u"&&(window.__crossxSDK=v),v}function ka(r){const e=Oa(r),s=Pa(e),t=JSON.parse(s);Na(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Oa(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function Pa(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=Ca(r);return decodeURIComponent(e)}function Ca(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Na(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return z.CONNECT_OTHER_WALLET_DISPLAY_ORDER=is,z.CROSSxError=x,z.CROSSxEthereumProvider=as,z.CROSSxSDK=ot,z.ChainId=Qr,z.ConnectOtherWalletItem=We,z.ErrorCode=h,z.MNEMONIC_ADDRESS_LIMIT=It,z.PinMemoryStore=At,z.TokenMemoryStore=zr,z.createCROSSxSDK=Ra,z.getConnectOtherWalletLabel=os,z.parseOAuthDeeplink=ka,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"}),z}({});
|
|
2547
|
+
</svg>`;function Ia(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(d=>d.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,_)=>{t[_]&&(t[_].value=g)});const d=Math.min(l.length,3);t[d].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Ta{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=$r(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=$r(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise((n,i)=>{var P;pe();const o=[...e],a=la(o,this.tokens,t),c=je();fe(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())};let p=null;const g=k=>{d(),n(k)},_=()=>{d(),p?i(p):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(k=>{k.addEventListener("click",()=>{const N=k.dataset.walletAddress??"",F=parseInt(k.dataset.walletIndex??"0",10),G=o.find(Q=>Q.index===F);g({address:N,index:F,name:G==null?void 0:G.name})})})})();const y=a.querySelector("#__crossx-add-wallet-error"),E=a.querySelector("#__crossx-add-wallet-btn");E&&E.addEventListener("click",async()=>{E.disabled=!0,y&&(y.hidden=!0,y.textContent="");try{const k=await s();o.push(k);const N=a.querySelector("#__crossx-wallet-list");if(N){const F=document.createElement("button");F.className="__crossx-wallet-item",F.dataset.walletIndex=String(k.index),F.dataset.walletAddress=k.address,F.innerHTML=`${Gr(k.address,k.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${L(Kr(k))}</span><span class="__crossx-wallet-addr">${ne(k.address)}</span></span>`,F.addEventListener("click",()=>g(k)),N.appendChild(F);try{F.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}E.disabled=!1}catch(k){const N=k instanceof x&&k.code===h.ADDRESS_LIMIT_EXCEEDED,F=this.resolveAddWalletErrorMessage(k);y&&(y.textContent=F,y.hidden=!1),N?(E.disabled=!0,E.setAttribute("aria-disabled","true")):E.disabled=!1,p=k}}),(P=a.querySelector("#__crossx-close-btn"))==null||P.addEventListener("click",_),a.addEventListener("click",k=>{k.target===a&&_()});const T=k=>{k.key==="Escape"&&(document.removeEventListener("keydown",T),_())};document.addEventListener("keydown",T)})}resolveAddWalletErrorMessage(e){const s=this.messages;if(e instanceof x&&e.code===h.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:it;return((s==null?void 0:s.walletSelector_addError_limitExceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}return(s==null?void 0:s.walletSelector_addError_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var g,_,f,y;pe();const i=fa(this.tokens,s),o=je();fe(i);const a=()=>{i.remove(),o()},c=E=>{a(),n({type:"oauth",provider:E})},l=E=>{a(),n({type:"external",walletId:E})},d=()=>{a(),n(null)};(g=i.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>c("apple")),(_=i.querySelector("#__crossx-google-btn"))==null||_.addEventListener("click",()=>c("google")),(f=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||f.addEventListener("click",E=>{const P=E.currentTarget.dataset.walletId??"";P&&l(P)}),(y=i.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",d),i.addEventListener("click",E=>{E.target===i&&d()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(E=>{E.addEventListener("click",T=>T.stopPropagation())});const p=E=>{E.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(s=>{var d,p,g;pe();const t=this.messages,n=_a(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=je();fe(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;pe();const n=ga(this.tokens,s);fe(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",g=>{g.target===n&&d()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(s=>{pe();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=qr(this.tokens,ya(n)),c=je();fe(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},p=P=>{d(),s(P)},g=()=>{d(),s(null)},_=a.querySelector(".__crossx-card"),f={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},y=P=>{var k;_.innerHTML=rs({title:o.title,headerSubtitle:o.headerSubtitle}),(k=_.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),ns(_,N=>{N===P?p(P):E(i.mismatchError)},g)},E=P=>{var k;_.innerHTML=rs({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:P}),(k=_.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),ns(_,N=>{const F=ba(N,f);F?E(F):y(N)},g)};(()=>{var se;const P=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),k=_.querySelector("#__crossx-pin-notice-next"),N=new Set;k.removeAttribute("disabled");const F=k.dataset.nextLabel??"Next",G=k.dataset.submitLabel??"I Understand",Q=()=>{const H=N.size===P.length;k.classList.toggle("--disabled",!H),k.textContent=H?G:F},K=(H,D)=>{if(N.has(D))return;const W=H.querySelector(`#__crossx-notice-check-${D}`);N.add(D),W.classList.add("--checked"),H.setAttribute("aria-checked","true"),Q()},X=(H,D)=>{if(!N.has(D))return;const W=H.querySelector(`#__crossx-notice-check-${D}`);N.delete(D),W.classList.remove("--checked"),H.setAttribute("aria-checked","false"),Q()};P.forEach(H=>{const D=parseInt(H.dataset.checkIndex??"0",10);H.addEventListener("click",()=>{N.has(D)?X(H,D):K(H,D)}),H.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),N.has(D)?X(H,D):K(H,D))})}),k.addEventListener("click",()=>{if(N.size===P.length){E(e==null?void 0:e.errorMessage);return}const H=P.find(W=>{const m=parseInt(W.dataset.checkIndex??"0",10);return!N.has(m)});if(!H)return;const D=parseInt(H.dataset.checkIndex??"0",10);H.scrollIntoView({behavior:"smooth",block:"nearest"}),H.classList.add("--highlight"),setTimeout(()=>{H.classList.remove("--highlight"),K(H,D)},400)}),(se=_.querySelector("#__crossx-close-btn"))==null||se.addEventListener("click",g)})(),a.addEventListener("click",P=>{P.target===a&&g()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var T;pe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=qr(this.tokens,rs({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),d=je();fe(l);let p=!1;const g=()=>{p||(p=!0,l.remove(),d())},_=P=>{g(),s(P)},f=()=>{g(),s(null)},y=P=>{g(),t(P)},E=l.querySelector(".__crossx-card");(T=E.querySelector("#__crossx-close-btn"))==null||T.addEventListener("click",f),ns(E,_,f,y,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",P=>{P.target===l&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;pe();const t=xa(this.tokens,e);fe(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};Ia(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;pe();const{overlay:n,startCountdown:i}=wa(this.tokens,e,s);fe(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;pe();const t=Qo(e,this.tokens);fe(t);const n=()=>t.remove(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var g;d.stopPropagation();const p=l.dataset.copy;p&&((g=navigator.clipboard)==null||g.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{pe();const n=ea(e,this.tokens);fe(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,p;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(ta(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,d,p;pe();let t;e.type==="sign-message"?t=sa(e,this.tokens):e.type==="sign-typed-data"?t=ra(e,this.tokens):e.type==="sign"?t=Yo(e,this.tokens):t=jo(e,this.tokens);const n=je();fe(t);const i=()=>{t.remove(),n()},o=()=>{i(),s(!0)},a=()=>{i(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(d=t.querySelector("#__crossx-cancel-btn"))==null||d.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",_=>{var y;_.stopPropagation();const f=g.dataset.copy;f&&((y=navigator.clipboard)==null||y.writeText(f).catch(()=>{}))})}),t.addEventListener("click",g=>{g.target===t&&a()});const c=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class zr{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Ra(r,e){r.debug;const s=Ue.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},i=t.authMode!=="cookie"&&bs.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new bs(r.projectId):new Nn,a=new ko,c=new No,l=new De,d=new zr,p=new It;let g;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),g=new Do(o,p)):(u.log("[CROSSx] Remote Wallet Provider 사용"),g=new Me(n,o,c,d,p));const _=new st(n,c),f=new Ta(r.theme??"light",r.themeTokens),y=e!=null&&e.wrapConfirmation?e.wrapConfirmation(f):f,E=new at(t,n,o,a,c,l,g,d,y,_,p);return typeof window<"u"&&(window.__crossxSDK=E),E}function ka(r){const e=Oa(r),s=Pa(e),t=JSON.parse(s);Na(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Oa(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function Pa(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=Ca(r);return decodeURIComponent(e)}function Ca(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Na(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return z.CONNECT_OTHER_WALLET_DISPLAY_ORDER=is,z.CROSSxError=x,z.CROSSxEthereumProvider=as,z.CROSSxSDK=at,z.ChainId=Qr,z.ConnectOtherWalletItem=We,z.ErrorCode=h,z.MNEMONIC_ADDRESS_LIMIT=it,z.PinMemoryStore=It,z.TokenMemoryStore=zr,z.createCROSSxSDK=Ra,z.getConnectOtherWalletLabel=os,z.parseOAuthDeeplink=ka,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"}),z}({});
|