@nexus-cross/crossx-sdk-core 3.0.0-beta.1 → 3.0.0-beta.2
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/core/constants.d.ts +1 -1
- package/dist/crossx.global +2 -2
- package/dist/{factory--q6B2KiB.js → factory-CB7q7IqU.js} +6 -6
- package/dist/{factory-DKz-M7y8.cjs → factory-CzX-ZcrQ.cjs} +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/internal.cjs +1 -1
- package/dist/internal.js +1 -1
- package/package.json +1 -1
package/dist/crossx.global
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var CROSSx=(function(W){"use strict";var ll=Object.defineProperty;var dl=(W,l,h)=>l in W?ll(W,l,{enumerable:!0,configurable:!0,writable:!0,value:h}):W[l]=h;var T=(W,l,h)=>dl(W,typeof l!="symbol"?l+"":l,h);var Ct,xn;var l=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.ONEID_TERMS_NOT_AGREED="ONEID_TERMS_NOT_AGREED",s.ONEID_ACCOUNT_NOT_FOUND="ONEID_ACCOUNT_NOT_FOUND",s.ONEID_SERVICE_NOT_LINKED="ONEID_SERVICE_NOT_LINKED",s.ONEID_AUTHORIZATION_FAILED="ONEID_AUTHORIZATION_FAILED",s.ONEID_STATE_MISMATCH="ONEID_STATE_MISMATCH",s.ONEID_ISSUER_MISMATCH="ONEID_ISSUER_MISMATCH",s.ONEID_TIMEOUT="ONEID_TIMEOUT",s.ONEID_SESSION_EVICTED="ONEID_SESSION_EVICTED",s.ONEID_SESSION_REVOKED="ONEID_SESSION_REVOKED",s.ONEID_SESSION_EXPIRED="ONEID_SESSION_EXPIRED",s.ONEID_SESSION_INVALID="ONEID_SESSION_INVALID",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SDK_VERSION_UNSUPPORTED="SDK_VERSION_UNSUPPORTED",s.UI_NOT_PROVIDED="UI_NOT_PROVIDED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.EXECUTION_REVERTED="EXECUTION_REVERTED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(l||{});class h extends Error{constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="CROSSxError",Object.setPrototypeOf(this,h.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Dn=2e3,Ir=6e4,kn=1e3,Ln=1e4,Un="0x77359400",Tr="0x3B9ACA00",Rr=130,Dt=6,Or=18,Nr=3e4,Wn=300*1e3,Bn=30*1e3,kt=100,Mn=300*1e3,Pr=60*1e3,ot="crossx-sdk-js/3.0.0-beta.
|
|
1
|
+
var CROSSx=(function(W){"use strict";var ll=Object.defineProperty;var dl=(W,l,h)=>l in W?ll(W,l,{enumerable:!0,configurable:!0,writable:!0,value:h}):W[l]=h;var T=(W,l,h)=>dl(W,typeof l!="symbol"?l+"":l,h);var Ct,xn;var l=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.ONEID_TERMS_NOT_AGREED="ONEID_TERMS_NOT_AGREED",s.ONEID_ACCOUNT_NOT_FOUND="ONEID_ACCOUNT_NOT_FOUND",s.ONEID_SERVICE_NOT_LINKED="ONEID_SERVICE_NOT_LINKED",s.ONEID_AUTHORIZATION_FAILED="ONEID_AUTHORIZATION_FAILED",s.ONEID_STATE_MISMATCH="ONEID_STATE_MISMATCH",s.ONEID_ISSUER_MISMATCH="ONEID_ISSUER_MISMATCH",s.ONEID_TIMEOUT="ONEID_TIMEOUT",s.ONEID_SESSION_EVICTED="ONEID_SESSION_EVICTED",s.ONEID_SESSION_REVOKED="ONEID_SESSION_REVOKED",s.ONEID_SESSION_EXPIRED="ONEID_SESSION_EXPIRED",s.ONEID_SESSION_INVALID="ONEID_SESSION_INVALID",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SDK_VERSION_UNSUPPORTED="SDK_VERSION_UNSUPPORTED",s.UI_NOT_PROVIDED="UI_NOT_PROVIDED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.EXECUTION_REVERTED="EXECUTION_REVERTED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(l||{});class h extends Error{constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="CROSSxError",Object.setPrototypeOf(this,h.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Dn=2e3,Ir=6e4,kn=1e3,Ln=1e4,Un="0x77359400",Tr="0x3B9ACA00",Rr=130,Dt=6,Or=18,Nr=3e4,Wn=300*1e3,Bn=30*1e3,kt=100,Mn=300*1e3,Pr=60*1e3,ot="crossx-sdk-js/3.0.0-beta.2",Fn="X-SDK-Version",Kn=!1,Hn="x-sdk-deprecation",ct=-10050,Lt="ONEpocket";var br=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(br||{});const Gn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:Lt},xr=["crossx","io.metamask","com.binance.wallet"];function $n(s){return Gn[s]??s}function Vn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...xr]:[]}function vr(s){const e=s instanceof Error?s.message:String(s);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const Jn=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),qn=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function Cr(s){if(!s||typeof s!="object")return;const e=s.code;return typeof e=="string"&&e.length>0?e:void 0}function Yn(s){const e=Cr(s);if(e)return Jn.has(e);const t=s instanceof Error?s.message:String(s);return qn.test(t)}function Ue(s,e){if(s instanceof h)return s;const t=Cr(s),r=s instanceof Error?s.message:String(s),n={nativeCode:t,cause:s};if(Yn(s))return new h(l.USER_REJECTED,r,n);const i=t&&!r.includes(t)?`${r} (${t})`:r;return new h(e,i,n)}const lt={ONE_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"ONEchain Mainnet",nativeCurrency:{symbol:"ONE",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},ONE_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",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}},zn=Object.fromEntries(Object.entries(lt).map(([s,e])=>[s,e.caipId])),Xn=new Map(Object.values(lt).map(s=>[s.caipId,s]));new Map(Object.values(lt).map(s=>[s.chainId,s]));const jn={symbol:"",decimals:18};function Zn(s,e){var t;return(e==null?void 0:e[s])??((t=Xn.get(s))==null?void 0:t.nativeCurrency)}class Ut{constructor(e,t){this.sdk=e,this.chainId=t,this._listeners=new Map}async request({method:e,params:t=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const r=await this.sdk.getAddress();return r?[r.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const r=this._normalizeEIP1193Tx(t[0]);return(await this.sdk.signTransaction(this.chainId,r)).signedTx}case"eth_sendTransaction":{const r=this._normalizeEIP1193Tx(t[0]);return(await this.sdk.sendTransaction(this.chainId,r)).txHash}case"personal_sign":case"eth_sign":throw new h(l.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new h(l.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,t,this.chainId)}}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),this}removeListener(e,t){var r;return(r=this._listeners.get(e))==null||r.delete(t),this}emit(e,...t){var r;(r=this._listeners.get(e))==null||r.forEach(n=>n(...t))}_caip2ToHex(e){const t=e.split(":");return`0x${parseInt(t[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 pe=null;function hl(s){}function Dr(s){pe=s}const d={info(...s){if(pe){pe.log(...s);return}console.log(...s)},log(...s){if(pe){pe.log(...s);return}},warn(...s){if(pe){pe.warn(...s);return}},error(...s){if(pe){pe.error(...s);return}}},kr={confirm:"확인",cancel:"취소",close:"닫기",signature_requesting:"이(가) 서명을 요청합니다",signature_warning:"서명 후에는 변경하거나 취소할 수 없습니다.",signature_sign_button:"서명",sign_message_title:"서명 요청",sign_typed_data_title:"서명 요청",sign_transaction_title:"서명 요청",send_transaction_title:"트랜잭션 승인",send_tx_permission_text:"이(가) 다음 트랜잭션 승인을 요청합니다.",send_tx_approve_button:"승인",send_tx_confirm_button:"확인",tx_pending:"트랜잭션을 처리하고 있습니다...",tx_success:"트랜잭션 완료",tx_failed:"트랜잭션 실패",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",tx_progress_waiting_title:"확인 대기 중",tx_progress_waiting_text:"트랜잭션 영수증을 기다리는 중...",tx_complete_done_button:"모두 완료",label_to:"받는 주소",label_from:"보내는 주소",label_network:"네트워크",label_value:"금액",label_estimated_fee:"예상 수수료",label_est_tx_fee:"예상 수수료",label_max_priority_fee:"최대 우선 수수료",label_max_gas_fee:"최대 가스 수수료",label_gas_price:"가스 가격",label_gas_limit:"가스 한도",label_transfer:"전송량",label_tx_fee:"수수료",label_tx_hash:"Tx 해시",label_total:"합계",label_including_fees:"(수수료 포함)",label_primary_type:"Primary Type",login_selector_title:"로그인 방법 선택",login_selector_subtitle:"소셜 계정으로 간편하게 로그인하세요",login_selector_google:"Google로 로그인",login_selector_apple:"Apple로 로그인",login_selector_or:"또는",login_selector_terms_template:"계속 진행하면 NEXUS {tos}에 동의하고 {pp}에 동의하게 됩니다.",login_selector_terms_tos:"이용약관",login_selector_terms_pp:"개인정보 처리방침",login_selector_connect_other_wallets:"다른 지갑으로 연결",login_selector_connect_other_wallets_desc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_found_title:"소셜 계정에서 지갑 발견",migration_found_description:`소셜 계정에 연결된 지갑을 발견했습니다.
|
|
2
2
|
4자리 PIN을 입력하여 자산을 복원하세요.`,migration_recover_button:"내 지갑 복구",migration_skip_button:"나중에 하기",recovery_pin_input_title:"내 지갑 복구",recovery_pin_input_placeholder:"지갑 복구를 위해 4자리 PIN을 입력하세요.",recovery_pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",wallet_selector_title:"연결된 지갑 선택",wallet_selector_description:"이전에 이 게임에서 사용한 지갑을 선택해야 계속 진행할 수 있습니다.",wallet_selector_info_title:"왜 지갑을 선택해야 하나요?",wallet_selector_info_desc:"이전에 연결된 지갑을 확인하면 게임 진행 상황과 자산이 올바르게 동기화됩니다.",wallet_selector_add_button:"지갑 추가",wallet_selector_selected:"선택됨",wallet_selector_empty:"아직 지갑이 없습니다. 지갑을 추가해 주세요.",wallet_selector_add_error_limit_exceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",wallet_selector_add_error_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",wallet_created_title:"지갑이 생성되었습니다!",wallet_created_button:"확인",pin_notice_header_subtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pin_notice_title:"PIN 설정 주의사항",pin_notice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pin_notice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pin_notice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pin_notice_next_button:"확인했습니다",pin_notice_submit_button:"확인했습니다",pin_setup_title:"PIN 만들기",pin_setup_header_subtitle:"이 PIN은 거래 승인에 사용됩니다.",pin_setup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pin_setup_confirm_title:"PIN 확인",pin_setup_confirm_subtitle:"6자리 PIN을 다시 입력하세요.",pin_setup_mismatch_error:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pin_validation_too_short:"6자리 PIN을 입력해 주세요.",pin_validation_numbers_only:"숫자(0-9)만 입력할 수 있습니다.",pin_validation_repeating_digit:"동일한 숫자를 3회 이상 연속으로 사용할 수 없습니다.",pin_validation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pin_validation_alternating_pattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pin_input_title:"PIN 입력",pin_input_subtitle:"거래 승인을 위해 PIN을 입력해 주세요.",pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verify_pin_title:"PIN 확인",verify_pin_subtitle:"계속하려면 PIN을 확인해 주세요.",pin_locked_message:"잠금이 해제된 후 다시 시도해 주세요.",pin_locked_available_from:"(%@ 이후 이용 가능)",pin_locked_failure_warning:"추가 실패 시 계정이 잠금됩니다.",pin_locked_permanent:"계정이 영구 잠금되었습니다. 고객센터에 문의해 주세요.",alert_session_expired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_account_withdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_wallet_not_found:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_different_account:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
3
3
|
|
|
4
4
|
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,update_required_title:"업데이트 필요",update_required_message:"이 서비스가 더 이상 지원하지 않는 지갑 버전을 사용하고 있어 지금은 로그인하거나 전송할 수 없습니다. 서비스가 업데이트된 뒤 다시 시도해 주세요.",update_required_confirm_button:"확인",session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},Wt={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",send_tx_confirm_button:"Confirm",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:Lt,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_empty:"No wallet yet. Add a wallet to continue.",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
|
|
5
5
|
|
|
6
|
-
For security, you must continue with the same account.`,update_required_title:"Update required",update_required_message:"This service is using a wallet version that is no longer supported, so you cannot sign in or send transactions right now. Please try again after the service is updated.",update_required_confirm_button:"OK",session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Qn={ko:kr,en:Wt};function we(s="en",e){return Qn[s]??Wt}function ei(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Lr="crossx_access_token",Ur="crossx_refresh_token",Wr="crossx_user_info",vt=class vt{constructor(e,t,r,n,i,a,o,c,u=()=>{}){this.config=e,this.storage=t,this.crypto=r,this.oauth=n,this.transport=i,this.walletProvider=a,this.tokenStore=o,this.requestFreshTokenFromBridge=c,this.getLocale=u,this._refreshPromise=null,this._migrated=!1;const f=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${f}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${f}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${f}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${f}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const t=this.crypto.decodeJWT(e);return t!=null&&t.exp?t.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const r=t;if(r.code&&r.code!==200&&r.code>0)return{code:r.code,message:r.message??""}}return null}checkResponseError(e,t){const r=this.extractResponseErrorCode(e);if(r)throw new h(l.AUTH_FAILED,`${t} 실패 (코드 ${r.code}): ${r.message}`)}async execute(e){let t,r;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:a,legacyOauthServiceUrl:o}=this.config,c=ei(this.getLocale()),u=E=>{const m=`${E}${i}`,y=m.includes("?")?"&":"?";return`${m}${y}locale=${c}`},f=u(a),g=o?u(o):void 0;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${f}`);const S=await this.oauth.openAuth({authUrl:f,...g?{legacyAuthUrl:g}:{},expectedOrigin:new URL(a).origin});t=S.token,r=S.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",t.length,")"),r&&d.log("[CROSSx] OAuth 콜백 email:",r)}catch(n){if(d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof h)throw n;const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new h(l.OAUTH_POPUP_BLOCKED,i):new h(l.AUTH_FAILED,i)}return this.processFirebaseToken(t,r)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var r,n,i;let t;try{const{authApiUrl:a}=this.config,{accessToken:o}=await this.exchangeNativeFirebaseToken(e.idToken,a);let c,u;try{const f=this.crypto.decodeJWT(e.idToken);u=e.provider??((r=f.firebase)==null?void 0:r.sign_in_provider);const g=((n=f.firebase)==null?void 0:n.identities)??{};c=f.email??((i=g.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",u,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(o){const f=await this.crypto.verifyJWT(o);if(!f.valid)throw new h(l.AUTH_FAILED,"Access token 검증 실패");const g=f.payload;t={id:g.sub,email:g.email??c,signInProvider:u,providerSub:e.providerSub},this.tokenStore.set(o),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,o),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,t)}else throw new h(l.AUTH_FAILED,"Access token 교환 실패")}catch(a){const o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0,u=a instanceof Error?a.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",u,"message:",o,"stack:",c),{success:!1,error:o||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,!1)}async processFirebaseToken(e,t){var i,a,o,c,u;let r,n=!1;try{const{authApiUrl:f}=this.config,{accessToken:g,refreshToken:S}=await this.exchangeFirebaseToken(e,f);let E,m,y;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),m=(i=A.firebase)==null?void 0:i.sign_in_provider;const P=((a=A.firebase)==null?void 0:a.identities)??{};y=A.email??((o=P.email)==null?void 0:o[0]),m==="google.com"?E=(c=P["google.com"])==null?void 0:c[0]:m==="apple.com"&&(E=(u=P["apple.com"])==null?void 0:u[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",m,"hasProviderSub:",!!E,"email:",y??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(g){const A=this.crypto.decodeJWT(g);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const P=await this.crypto.verifyJWT(g);if(n=P.signatureVerified??!1,!P.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const F=P.payload,M=F.email??y??t;d.log("[CROSSx] email 소스 — CROSSx JWT:",F.email??"(없음)","/ Firebase JWT:",y??"(없음)","/ OAuth 콜백:",t??"(없음)","→",M??"(없음)"),r={id:F.sub,email:M,signInProvider:m,providerSub:E},this.tokenStore.set(g),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,g),S&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,S):S&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);r={id:A.sub,email:A.email??t,signInProvider:m,providerSub:E},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)");const w=this.useCookieAuth?{id:r.id,email:r.email,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,w),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(f){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",f),{success:!1,error:f instanceof Error?f.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,n)}async exchangeNativeFirebaseToken(e,t){const r=`${t}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",r,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:r,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(o){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",r,"error:",o);const c=o instanceof Error?o.message:String(o);throw new h(l.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,o)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const a=this.extractAccessToken(i);if(!a)throw new h(l.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:a}}async exchangeFirebaseToken(e,t){const r=this.useCookieAuth,n=r?`${t}/cross-auth/social/login/cookie`:`${t}/cross-auth/social/login`;d.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"},...r?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Token exchange");const o=this.extractAccessToken(a);if(r&&!o)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!o)throw new h(l.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return r||(c=this.extractRefreshToken(a)),{accessToken:o,refreshToken:c}}extractAccessToken(e){const t=(e==null?void 0:e.data)??e;if(this.isJwtString(t))return t;if(typeof t=="object"&&t!==null){const r=t;if(this.isJwtString(r.data))return r.data;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.access_token??i.token;if(typeof a=="string")return a}const n=r.access_token??r.token;if(typeof n=="string")return n}}extractRefreshToken(e){const t=(e==null?void 0:e.data)??e;if(typeof t!="object"||t===null)return;const r=t;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.refresh_token??i.refresh;if(typeof a=="string")return a}const n=r.refresh_token??r.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 r=await this.crypto.verifyJWT(e);if(r.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,r.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const r=await this.silentRefresh();r&&this.tokenStore.set(r)}else{const r=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",r?"있음":"없음","refresh_token:",n?"있음":"없음"),n){r&&this.tokenStore.set(r);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!r)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(r)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(r)}}const t=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",t?`있음 (id: ${t.id})`:"없음"),!t)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",t.id);try{return await this.loadWallet(t,!1)}catch(r){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",r),{success:!0,user:t,tokenSignatureVerified:!1}}}catch(e){const t=e instanceof h&&e.code===l.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",t?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),t&&(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:t}=this.config,r=this.useCookieAuth,n=`${t}/cross-auth/social/refresh/simple`,i={};if(!r){const f=this.tokenStore.get()??"";f&&(i.access_token=f),e&&(i.refresh_token=e)}const a=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...r?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",a.status);const o=a.data,c=this.extractResponseErrorCode(o);if(c){const f=vt.REFRESH_RELOGIN_CODES.has(c.code);throw new h(f?l.SESSION_EXPIRED:l.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const u=this.extractAccessToken(o);if(r&&!u){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!u)throw new h(l.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(u),!r){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,u);const f=this.extractRefreshToken(o);f&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,f)}return d.log("[CROSSx] silentRefresh 성공"),u}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const r=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(r.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(r){throw r instanceof h&&r.code===l.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),r}}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):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof h&&e.code===l.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,t){let r,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!t)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const o=await this.silentRefresh(t);if(!o)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=o,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const a=i.payload;d.log("[CROSSx] signInWithJWT — sub:",a.sub,"signatureVerified:",n),r={id:a.sub,email:a.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),t&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,t),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,r),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(r,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Wr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const r=await this.storage.get(Lr);r&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,r);const n=await this.storage.get(Ur);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Wr),await this.storage.remove(Lr),await this.storage.remove(Ur),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,t){let r,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const a=await this.walletProvider.getAddresses(e.id);a.length>0?(r=a[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",r)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(a){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",a)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),r=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",r)}catch(i){if(i instanceof h&&i.code===l.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof h&&(i.code===l.PROJECT_NOT_REGISTERED||i.code===l.PROJECT_ID_MISSING||i.code===l.ORIGIN_NOT_ALLOWED||i.code===l.SDK_VERSION_UNSUPPORTED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",r,"needsMigration:",n),{success:!0,address:r,user:e,needsMigration:n,tokenSignatureVerified:t}}};vt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Bt=vt;class ti{constructor(e,t,r,n=[]){this.config=e,this.storage=t,this.tokenStore=r,this.preservedKeys=n;const i=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${i}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${i}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${i}_user_info`}async hasStoredSession(){const e=[this.STORAGE_KEY_ACCESS_TOKEN,this.STORAGE_KEY_REFRESH_TOKEN,this.STORAGE_KEY_USER];for(const t of e){const r=await this.storage.get(t).catch(()=>null);if(r!=null)return!0}return!1}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);const e=[];for(const t of this.preservedKeys){const r=await this.storage.get(t).catch(()=>null);r!=null&&e.push([t,r])}await this.storage.clear();for(const[t,r]of e)await this.storage.set(t,r).catch(()=>{})}}class ri{constructor(e,t){this.storage=e,this.walletProvider=t}async execute(e,t){if(!this.walletProvider.migrateWallet)throw new h(l.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",t);const r=await this.walletProvider.migrateWallet(e,t);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",r.address),{address:r.address}}}class Mt{constructor(){this.encryptedBytes=null,this.xorKey=null,this.setAt=null}set(e){this.clear();const t=new TextEncoder().encode(e),r=new Uint8Array(t.length);crypto.getRandomValues(r);const n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t[i]^r[i];t.fill(0),this.xorKey=r,this.encryptedBytes=n,this.setAt=Date.now()}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let r=0;r<this.encryptedBytes.length;r++)e[r]=this.encryptedBytes[r]^this.xorKey[r];const t=new TextDecoder().decode(e);return e.fill(0),t}clear(){var e,t;(e=this.encryptedBytes)==null||e.fill(0),(t=this.xorKey)==null||t.fill(0),this.encryptedBytes=null,this.xorKey=null,this.setAt=null}getSetAt(){return this.setAt}has(){return this.encryptedBytes!==null}}const si="/authorize/result",ni="one-oauth:authorization_response",Br="one-oauth:authorization_error",ii="one-oauth:authorization_ack",ai="openid profile offline_access";function Ft(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mr(s=32){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}async function Fr(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Ft(new Uint8Array(e))}function dt(s=16){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}const oi=300*1e3,ci=600*1e3,Kt="crossx.oneid.pending",li=1e3,di=10;function Kr(s){switch(s){case"access_denied":return l.USER_REJECTED;case"required_items_not_agreed":return l.ONEID_TERMS_NOT_AGREED;case"account_not_found":return l.ONEID_ACCOUNT_NOT_FOUND;case"service_not_linked":return l.ONEID_SERVICE_NOT_LINKED;default:return l.ONEID_AUTHORIZATION_FAILED}}function hi(s){switch(s){case"session_evicted":return l.ONEID_SESSION_EVICTED;case"session_revoked":return l.ONEID_SESSION_REVOKED;case"session_expired":return l.ONEID_SESSION_EXPIRED;default:return l.ONEID_SESSION_INVALID}}function Ht(s){if(!(typeof s!="string"||!s.startsWith("/"))&&!(s.startsWith("//")||s.startsWith("/\\")))return s}function We(s){let e;try{e=new URL(s)}catch{throw new h(l.INVALID_CONFIG,"ONE ID issuer가 올바른 URL이 아닙니다")}return e.toString().replace(/\/+$/,"")}function Hr(s){const e=s.split(".")[1];if(!e)return null;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=new TextDecoder().decode(Uint8Array.from(atob(r),a=>a.charCodeAt(0))),i=JSON.parse(n);return typeof i=="object"&&i!==null?i:null}catch{return null}}function ui(s){if(typeof s!="object"||s===null)return!1;const e=s.type;return e===ni||e===Br}function Gr(s,e){if(typeof s.access_token!="string"||s.access_token==="")throw new h(l.ONEID_AUTHORIZATION_FAILED,"토큰 응답에 access_token이 없습니다");const t=typeof s.expires_in=="number"?s.expires_in:0;return{accessToken:s.access_token,tokenType:typeof s.token_type=="string"?s.token_type:"Bearer",expiresAt:e+t*1e3,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:void 0,idToken:typeof s.id_token=="string"?s.id_token:void 0,scope:typeof s.scope=="string"?s.scope:void 0}}class fi{constructor(){this.reason=null,this.onAbort=null}abort(e){var t;this.reason??(this.reason=e),(t=this.onAbort)==null||t.call(this,e)}throwIfAborted(){if(this.reason!==null)throw new h(l.USER_REJECTED,this.reason)}}class gi{constructor(e={}){this.abortPending=null,this.popupSeq=0,this.options=e}get fetchImpl(){return this.options.fetch??((e,t)=>fetch(e,t))}now(){var e,t;return((t=(e=this.options).now)==null?void 0:t.call(e))??Date.now()}get pendingStorage(){return this.options.pendingStorage??window.sessionStorage}cancelPending(e="ONE ID 로그인 대기를 중단했습니다"){var t;(t=this.abortPending)==null||t.call(this,e)}async authorize(e){let t=null;if(e.mode!=="redirect"&&(t=this.openBlankPopup(e.width,e.height),!t&&e.mode==="popup"))throw new h(l.OAUTH_POPUP_BLOCKED,"팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요.");try{const r=We(e.issuer);if(!e.clientId)throw new h(l.INVALID_CONFIG,"ONE ID clientId가 비어 있습니다");this.cancelPending("새 ONE ID 로그인 요청으로 이전 대기를 중단했습니다");const n=new fi,i=a=>n.abort(a);this.abortPending=i;try{return t?await this.authorizeWithPopup(t,{...e,issuer:r},n):await this.authorizeWithRedirect({...e,issuer:r},n)}finally{this.abortPending===i&&(this.abortPending=null)}}catch(r){try{t==null||t.close()}catch{}throw r}}async completeRedirect(e,t){const r=We(e.issuer),n=this.takePending(),i=new URL(t).searchParams;if(!n||n.issuer!==r||n.clientId!==e.clientId)throw new h(l.ONEID_STATE_MISMATCH,"진행 중인 ONE ID 로그인이 없습니다. 다시 로그인해 주세요.");if(this.now()-n.createdAt>ci)throw new h(l.ONEID_TIMEOUT,"ONE ID 로그인 시간이 지났습니다");const a=i.get("state");if(!a||a!==n.state)throw new h(l.ONEID_STATE_MISMATCH,"ONE ID 로그인 결과의 state가 다릅니다");if(i.get("iss")!==r)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다");const o=i.get("error");if(o){const f=i.get("error_description")??void 0;throw new h(Kr(o),f||`ONE ID 인가 오류: ${o}`,{error:o,error_description:f})}const c=i.get("code");if(!c)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다");return{tokens:await this.exchangeCode({...e,issuer:r},c,n.codeVerifier,n.redirectUri,n.nonce),returnTo:Ht(n.returnTo)}}async refresh(e,t){const r=We(e.issuer),n=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:t});let i;try{i=await this.fetchImpl(`${r}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(c){throw new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",c)}const a=await Gt(i);if(!i.ok){if(i.status===400&&a.error==="invalid_grant"){const c=typeof a.error_reason=="string"?a.error_reason:void 0;throw new h(hi(c),"ONE ID 세션이 끝났습니다. 다시 로그인해 주세요.",{error:"invalid_grant",error_reason:c})}throw i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?new h(l.ONEID_SESSION_INVALID,"ONE ID 세션을 갱신할 수 없습니다. 다시 로그인해 주세요.",{status:i.status,error:a.error}):new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",{status:i.status,error:a.error})}const o=Gr(a,this.now());return{...o,refreshToken:o.refreshToken??t}}async logout(e,t){const r=We(e.issuer);let n;try{n=await this.fetchImpl(`${r}/logout`,{method:"POST",headers:{Authorization:`Bearer ${t}`}})}catch(i){throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청을 보내지 못했습니다",i)}if(!n.ok&&n.status!==401)throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청이 실패했습니다",{status:n.status})}openBlankPopup(e=500,t=700){const r=Math.max(e,500),n=Math.max(t,700),i=window.screenX+(window.outerWidth-r)/2,a=window.screenY+(window.outerHeight-n)/2;try{return this.popupSeq+=1,window.open("about:blank",`ONEidLogin${this.popupSeq}`,`width=${r},height=${n},left=${i},top=${a}`)}catch{return null}}async pushAuthorizationRequest(e,t,r,n,i){const a=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:t,scope:e.scope??ai,state:r,nonce:n,code_challenge:i,code_challenge_method:"S256"});let o;try{o=await this.fetchImpl(`${e.issuer}/par`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(u){throw new h(l.NETWORK_ERROR,"ONE ID 로그인 요청을 보내지 못했습니다",u)}const c=await Gt(o);if(!o.ok||typeof c.request_uri!="string")throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 요청이 거부되었습니다",{status:o.status,error:c.error});return c.request_uri}authorizeUrl(e,t){const r=new URL(`${e.issuer}/authorize`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("request_uri",t),r.toString()}async exchangeCode(e,t,r,n,i){const a=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t,redirect_uri:n,code_verifier:r});let o;try{o=await this.fetchImpl(`${e.issuer}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(f){throw new h(l.NETWORK_ERROR,"ONE ID 토큰을 받지 못했습니다",f)}const c=await Gt(o);if(!o.ok)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 토큰 교환이 거부되었습니다",{status:o.status,error:c.error});const u=Gr(c,this.now());if(u.idToken){const f=Hr(u.idToken);if(!f||f.iss!==e.issuer||f.nonce!==i)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID id_token의 발급자나 nonce가 요청과 다릅니다")}return u}async authorizeWithPopup(e,t,r){const n=new URL(t.issuer).origin,i=`${t.issuer}${si}`,a=dt(),o=dt(),c=Mr(),u=await Fr(c),f=await this.pushAuthorizationRequest(t,i,a,o,u);r.throwIfAborted(),d.log("[CROSSx] ONE ID 로그인 팝업 이동",{issuer:t.issuer,clientId:t.clientId}),e.location.href=this.authorizeUrl(t,f);const g=await new Promise((E,m)=>{let y=0,w=!0;const A=()=>{r.onAbort=null,clearTimeout(F),clearInterval(M),window.removeEventListener("message",V)},P=U=>{A(),m(U)},F=setTimeout(()=>{P(new h(l.ONEID_TIMEOUT,"ONE ID 로그인 응답 시간이 지났습니다"))},oi),M=setInterval(()=>{if(!w)return;y++;let U;try{U=e.closed}catch{w=!1;return}if(!U)return;const H=typeof document<"u"&&document.hasFocus();if(y<=di&&!H){d.warn("[CROSSx] ONE ID 팝업 closed 오탐 가능성(COOP) — 결과 대기 유지"),w=!1;return}P(new h(l.USER_REJECTED,"ONE ID 로그인이 취소되었습니다"))},li),V=U=>{if(U.origin!==n||U.source!==e||!ui(U.data))return;const H=U.data;if(H.state!==a){d.warn("[CROSSx] ONE ID 결과 state가 현재 요청과 달라 무시합니다");return}try{e.postMessage({type:ii,state:a},n)}catch{}if(H.iss!==t.issuer){P(new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다"));return}if(H.type===Br||H.error){const Z=H.error??"unknown_error";d.warn("[CROSSx] ONE ID 인가 오류:",Z),P(new h(Kr(Z),H.error_description||`ONE ID 인가 오류: ${Z}`,{error:Z,error_description:H.error_description}));return}if(!H.code){P(new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다"));return}A(),E(H.code)};r.onAbort=U=>{P(new h(l.USER_REJECTED,U))},window.addEventListener("message",V)}),S=await this.exchangeCode(t,g,c,i,o);return d.log("[CROSSx] ONE ID 로그인 완료 (팝업)"),{status:"completed",tokens:S,returnTo:Ht(t.returnTo)}}async authorizeWithRedirect(e,t){const r=e.redirectUri??`${window.location.origin}/auth/callback`;if(new URL(r).origin!==window.location.origin)throw new h(l.INVALID_CONFIG,"ONE ID redirectUri는 지금 페이지와 같은 origin이어야 합니다");const n=dt(),i=dt(),a=Mr(),o=await Fr(a),c=await this.pushAuthorizationRequest(e,r,n,i,o);t.throwIfAborted();const u={issuer:e.issuer,clientId:e.clientId,state:n,nonce:i,codeVerifier:a,redirectUri:r,returnTo:Ht(e.returnTo),createdAt:this.now()};this.pendingStorage.setItem(Kt,JSON.stringify(u)),d.log("[CROSSx] ONE ID 로그인 같은 창 이동",{issuer:e.issuer,clientId:e.clientId});const f=this.authorizeUrl(e,c);return(this.options.navigate??(g=>window.location.assign(g)))(f),{status:"redirecting"}}takePending(){const e=this.pendingStorage.getItem(Kt);if(this.pendingStorage.removeItem(Kt),!e)return null;try{const t=JSON.parse(e);return typeof(t==null?void 0:t.state)=="string"&&typeof t.codeVerifier=="string"?t:null}catch{return null}}}async function Gt(s){try{const e=await s.json();return typeof e=="object"&&e!==null?e:{}}catch{return{}}}const ht="crossx.oneid.session",$r=60*1e3,$t=new Set([l.ONEID_SESSION_EVICTED,l.ONEID_SESSION_REVOKED,l.ONEID_SESSION_EXPIRED,l.ONEID_SESSION_INVALID]);function Vr(s){return s instanceof h&&$t.has(s.code)}class _i{constructor(e,t,r,n=()=>Date.now()){this.port=e,this.config=t,this.storage=r,this.now=n,this.refreshing=null,this.generation=0}save(e){this.generation+=1;const t={issuer:We(this.config.issuer),clientId:this.config.clientId,tokens:e};return this.storage.setItem(ht,JSON.stringify(t)),Jr(t)}async get(){const e=await this.ensureFresh();return e?Jr(e):null}async getAccessToken(){const e=await this.ensureFresh();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID로 로그인하지 않았습니다");return e.tokens.accessToken}async signOut(){const e=this.read();if(this.clear(),!e)return;let t=e.tokens.accessToken;if(e.tokens.refreshToken&&e.tokens.expiresAt-$r<=this.now())try{t=(await this.port.refresh(this.config,e.tokens.refreshToken)).accessToken}catch(r){if(r instanceof h&&$t.has(r.code))return}await this.port.logout(this.config,t)}clear(){this.generation+=1,this.storage.removeItem(ht)}read(){var t;const e=this.storage.getItem(ht);if(!e)return null;try{const r=JSON.parse(e);return typeof((t=r==null?void 0:r.tokens)==null?void 0:t.accessToken)=="string"&&typeof r.tokens.expiresAt=="number"&&r.issuer===We(this.config.issuer)&&r.clientId===this.config.clientId?r:(this.clear(),null)}catch{return this.clear(),null}}async ensureFresh(){const e=this.read();if(!e)return null;if(e.tokens.expiresAt-$r>this.now())return e;if(!e.tokens.refreshToken){if(e.tokens.expiresAt>this.now())return e;throw this.clear(),new h(l.ONEID_SESSION_EXPIRED,"ONE ID 로그인이 만료되었습니다. 다시 로그인해 주세요.")}return this.refreshing??(this.refreshing=this.refresh(e).finally(()=>{this.refreshing=null})),this.refreshing}async refresh(e){const t=this.generation;try{const r=await this.port.refresh(this.config,e.tokens.refreshToken),n={...e,tokens:r};if(t!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID 세션이 바뀌었습니다");return this.storage.setItem(ht,JSON.stringify(n)),n}catch(r){if(t!==this.generation)throw r;if(r instanceof h&&$t.has(r.code))throw this.clear(),r;if(e.tokens.expiresAt>this.now())return e;throw r}}}function Jr(s){const e=s.tokens.idToken?Hr(s.tokens.idToken):null;return{subject:typeof(e==null?void 0:e.sub)=="string"?e.sub:"",clientId:s.clientId,issuer:s.issuer,scope:s.tokens.scope,expiresAt:s.tokens.expiresAt}}function pi(s){return s==="local"?window.localStorage:window.sessionStorage}const wi=new TextEncoder;function j(s){return wi.encode(s)}function Se(...s){const e=new Uint8Array(s.reduce((r,n)=>r+n.length,0));let t=0;for(const r of s)e.set(r,t),t+=r.length;return e}function Si(s){return new Uint8Array([s>>>24&255,s>>>16&255,s>>>8&255,s&255])}function oe(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e)}function Be(s){const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Vt(s){return oe(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ei(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return Be(e)}function mi(s){return globalThis.crypto.getRandomValues(new Uint8Array(s))}async function qr(s){return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",s))}const ie=globalThis.crypto.subtle,Jt={name:"ECDH",namedCurve:"P-256"},yi=32,Ai=12,Ii=32;function Xe(s){return new Uint8Array([s>>>8&255,s&255])}const je=Se(j("HPKE"),Xe(16),Xe(1),Xe(2)),Yr=Se(j("KEM"),Xe(16)),xe=new Uint8Array(0);async function zr(s,e){const t=s.length===0?new Uint8Array(32):s,r=await ie.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await ie.sign("HMAC",r,e))}async function Ti(s,e,t){const r=new Uint8Array(t);let n=xe;for(let i=1,a=0;a<t;i++)n=await zr(s,Se(n,e,new Uint8Array([i]))),r.set(n.subarray(0,Math.min(32,t-a)),a),a+=32;return r}function ut(s,e,t,r){return zr(s,Se(j("HPKE-v1"),r,j(e),t))}function qt(s,e,t,r,n){return Ti(s,Se(Xe(r),j("HPKE-v1"),n,j(e),t),r)}async function Xr(s,e){const t=await ie.importKey("raw",e,Jt,!1,[]);return new Uint8Array(await ie.deriveBits({name:"ECDH",public:t},s,256))}async function jr(s,e,t){const r=await ut(xe,"eae_prk",s,Yr);return qt(r,"shared_secret",Se(e,t),Ii,Yr)}async function Zr(s){const e=await ut(xe,"psk_id_hash",xe,je),t=await ut(xe,"info_hash",xe,je),r=Se(new Uint8Array([0]),e,t),n=await ut(s,"secret",xe,je),i=await qt(n,"key",r,yi,je),a=await qt(n,"base_nonce",r,Ai,je);return{key:i,baseNonce:a}}function ft(s,e){if(s.length!==65||s[0]!==4)throw new Error(`${e} must be SEC1 uncompressed P-256 (65B)`)}async function Qr(){const s=await ie.generateKey(Jt,!1,["deriveBits"]),e=new Uint8Array(await ie.exportKey("raw",s.publicKey));return{privateKey:s.privateKey,publicKey:e}}async function Ri(s,e,t){ft(s,"recipient public key");const r=await ie.generateKey(Jt,!0,["deriveBits"]),n=new Uint8Array(await ie.exportKey("raw",r.publicKey)),i=await jr(await Xr(r.privateKey,s),n,s),{key:a,baseNonce:o}=await Zr(i),c=await ie.importKey("raw",a,"AES-GCM",!1,["encrypt"]),u=new Uint8Array(await ie.encrypt({name:"AES-GCM",iv:o,additionalData:t},c,e));return{enc:n,ciphertext:u}}async function Oi(s,e,t,r){ft(e,"enc");const n=await jr(await Xr(s.privateKey,e),e,s.publicKey),{key:i,baseNonce:a}=await Zr(n),o=await ie.importKey("raw",i,"AES-GCM",!1,["decrypt"]);return new Uint8Array(await ie.decrypt({name:"AES-GCM",iv:a,additionalData:r},o,t))}const es=globalThis.crypto.subtle,Ni={name:"ECDSA",namedCurve:"P-256"},Pi="one-wallet/authz-sig/v1",bi="one-wallet/seal-aad/v1",xi=60,vi=32,Ci={generate:1,recover:3,verify_pin:4,change_pin:5,get_address:10,get_mnemonic:11,get_private_key:12,get_share_c:13,activate:14,sign:20,sign_typed_data:21,sign_message:22};function Di(s){return Se(Si(s.length),s)}function ts(s,e,t){return Se(j(s),...e.map(Di),new Uint8Array([t]))}function ki(s,e,t){return ts(bi,[s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Li(s,e,t){return ts(Pi,[s.enc,s.ciphertext,s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Ui(s,e,t){return qr(ki(s,e,t))}function Wi(s){return s.toISOString().replace(/\.\d+Z$/,"Z")}async function Bi(s,e){if(s.length!==32)throw new Error("authz private key must be a 32B P-256 scalar");return ft(e,"authz public key"),es.importKey("jwk",{kty:"EC",crv:"P-256",x:Vt(e.subarray(1,33)),y:Vt(e.subarray(33,65)),d:Vt(s),ext:!1},Ni,!1,["sign"])}async function Mi(s){if(s.intent.command!==s.command)throw new Error("intent.command must match command");const e=Ci[s.command],t=j(JSON.stringify(s.intent)),r={nonce:mi(vi),expiresAt:Wi(new Date((s.now??new Date).getTime()+(s.ttlSec??xi)*1e3)),intentHash:await qr(t),authzKeyId:s.authz.keyId},n=await Ui(r,s.bindingId,e),i={pin:s.plaintext.pin};s.plaintext.new_pin!=null&&(i.new_pin=s.plaintext.new_pin),s.plaintext.share_c&&(i.share_c=oe(s.plaintext.share_c)),s.plaintext.response_key&&(i.response_key=oe(s.plaintext.response_key));const{enc:a,ciphertext:o}=await Ri(s.recipientPub,j(JSON.stringify(i)),n),c=new Uint8Array(await es.sign({name:"ECDSA",hash:"SHA-256"},s.authz.signingKey,Li({...r,enc:a,ciphertext:o},s.bindingId,e)));return{envelope:{enc:oe(a),ciphertext:oe(o),nonce:oe(r.nonce),expires_at:r.expiresAt,intent_hash:oe(r.intentHash),authz_key_id:r.authzKeyId,authz_sig:oe(c),authz_key_cert:s.authz.cert},intent:oe(t),aad:n}}function rs(s,e,t){return Oi(s,Be(e.enc),Be(e.ciphertext),t)}const Fi=90*1e3;class Ki{constructor(e){this.opts=e,this.current=null,this.pending=null,this.generation=0,this.now=e.now??Date.now}async get(){const e=this.current;return e&&e.expiresAtMs-this.now()>Fi?e:(this.pending??(this.pending=this.issue().finally(()=>{this.pending=null})),this.pending)}invalidate(){this.current=null}async revoke(){const e=this.current;if(this.generation++,this.current=null,this.pending=null,!!e)try{await this.opts.client.call("DELETE",`/authz-keys/${encodeURIComponent(e.keyId)}`)}catch{}}async issue(){var u;const e=this.generation,t=await Qr(),r=await this.opts.getIssuanceJwt(),n=await this.opts.client.call("POST","/authz-keys",{jwt:r,response_key:oe(t.publicKey)});if(!((u=n==null?void 0:n.key_cert)!=null&&u.key_id)||!n.cert_sig||!n.sealed_private_key)throw new h(l.AUTH_FAILED,"authz-keys response is incomplete");let i;try{i=await rs(t,n.sealed_private_key,Be(n.cert_sig))}catch(f){throw new h(l.AUTH_FAILED,"failed to open sealed authz key",{cause:f})}const a=await Bi(i,Be(n.key_cert.pubkey));i.fill(0);const o=Date.parse(n.key_cert.expires_at);if(Number.isNaN(o))throw new h(l.AUTH_FAILED,"authz key_cert has no valid expires_at");const c={signingKey:a,keyId:n.key_cert.key_id,cert:{...n.key_cert,sig:n.cert_sig},expiresAtMs:o};if(e!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"authz key issuance was cancelled by sign-out");return this.current=c,c}}const Hi=600*1e3,Gi={UNAUTHORIZED:l.AUTH_TOKEN_INVALID,AUTHZ_TOKEN_INVALID:l.AUTH_TOKEN_INVALID,FORBIDDEN:l.AUTH_FAILED,AUTHZ_INVALID:l.AUTH_FAILED,OWNER_MISMATCH:l.AUTH_FAILED,USER_NOT_FOUND:l.USER_NOT_FOUND,INVALID_PIN:l.PIN_WRONG,PIN_LOCKED:l.PIN_LOCKED,PIN_THROTTLED:l.PIN_LOCKED,WALLET_ALREADY_EXISTS:l.WALLET_ALREADY_EXISTS,WALLET_NOT_FOUND:l.WALLET_NOT_FOUND,ADDRESS_NOT_FOUND:l.WALLET_NOT_FOUND,WALLET_DELETED:l.WALLET_NOT_FOUND,WALLET_NOT_ACTIVATED:l.WALLET_INCONSISTENT_STATE,WALLET_LOAD_FAILED:l.WALLET_INCONSISTENT_STATE,ADDRESS_LIMIT_EXCEEDED:l.ADDRESS_LIMIT_EXCEEDED,BROADCAST_FAILED:l.BROADCAST_FAILED,CHAIN_NOT_FOUND:l.CHAIN_NOT_SUPPORTED,INVALID_CHAIN_ID:l.INVALID_CHAIN,CHAIN_ID_MISMATCH:l.TYPED_DATA_CHAIN_ID_MISMATCH,INVALID_TYPED_DATA:l.TX_INVALID_PARAMS,INVALID_PARAMS:l.TX_INVALID_PARAMS,INVALID_REQUEST:l.TX_INVALID_PARAMS,BAD_REQUEST:l.TX_INVALID_PARAMS,INDEX_MISMATCH:l.TX_INVALID_PARAMS,OPERATION_IN_PROGRESS:l.GATEWAY_LOCK_CONFLICT,SIGNER_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,ATTESTATION_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,SERVICE_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,AUTH_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,BAD_GATEWAY:l.GATEWAY_INTERNAL_ERROR,INTERNAL_ERROR:l.GATEWAY_INTERNAL_ERROR,ENVELOPE_INVALID:l.SIGNATURE_FAILED,REPLAY:l.SIGNATURE_FAILED};function $i(s,e){const t=(e==null?void 0:e.code)??"",r=Gi[t]??(s===401?l.AUTH_TOKEN_INVALID:s>=500?l.GATEWAY_INTERNAL_ERROR:l.UNKNOWN_ERROR),n={status:s,serverCode:t};return(e==null?void 0:e.remaining_attempts)!=null&&(n.remainingAttempts=e.remaining_attempts),(e==null?void 0:e.lock_expires_at)!=null&&(n.lockExpiresAt=e.lock_expires_at>1e10?e.lock_expires_at:e.lock_expires_at*1e3),(e==null?void 0:e.permanent)!=null&&(n.permanent=e.permanent),e!=null&&e.tx_hash&&(n.txHash=e.tx_hash),new h(r,(e==null?void 0:e.message)||`one-wallet-api ${s}${t?` ${t}`:""}`,n)}class Vi{constructor(e){this.opts=e,this.recipient=null,this.now=e.now??Date.now}async call(e,t,r){const n=await this.opts.getAccessToken();return this.send(e,t,r,{Authorization:`Bearer ${n}`})}async callPublic(e,t){return this.send(e,t,void 0,{})}async getRecipientKey(){if(this.recipient&&this.now()-this.recipient.fetchedAt<Hi)return this.recipient.key;const e=await this.callPublic("GET","/attestation");if(!(e!=null&&e.recipient_public_key))throw new h(l.GATEWAY_INTERNAL_ERROR,"attestation has no recipient_public_key");const t=Be(e.recipient_public_key);return ft(t,"recipient_public_key"),this.recipient={key:t,fetchedAt:this.now()},t}forgetRecipientKey(){this.recipient=null}async send(e,t,r,n){const i=typeof this.opts.baseUrl=="function"?this.opts.baseUrl():this.opts.baseUrl;if(!i)throw new h(l.INVALID_CONFIG,"one-wallet-api URL is not configured for this environment");let a;try{a=await this.opts.transport.request({url:`${i.replace(/\/+$/,"")}${t}`,method:e,headers:r===void 0?n:{...n,"Content-Type":"application/json"},body:r})}catch(o){throw new h(l.NETWORK_ERROR,"one-wallet-api request failed",{cause:o})}if(a.status<200||a.status>=300)throw $i(a.status,a.data);return a.data}}const Yt=s=>`m/44'/60'/0'/0/${s}`,Ji=/^0x(?:[0-9a-fA-F]{2})*$/;function qi(s){try{const e=JSON.parse(new TextDecoder().decode(Ei(s.split(".")[1]??"")));if(typeof(e==null?void 0:e.sub)=="string"&&e.sub)return e.sub}catch{}throw new h(l.AUTH_TOKEN_INVALID,"access token has no sub")}function Yi(s){if(Ji.test(s)){const e=s.slice(2);return Uint8Array.from({length:e.length/2},(t,r)=>parseInt(e.slice(r*2,r*2+2),16))}return j(s)}const ss=s=>`0x${s.toString(16)}`;function ns(s,e){const t=s.chainId??Number(e.split(":")[1]);if(!Number.isSafeInteger(t))throw new h(l.TX_INVALID_PARAMS,`invalid chain id: ${e}`);if(s.nonce===void 0)throw new h(l.TX_INVALID_PARAMS,"transaction nonce is required");const r={to:s.to,value:s.value??"0x0",data:s.data??"0x",gas_limit:s.gasLimit,gas_price:s.gasPrice,max_fee_per_gas:s.maxFeePerGas,max_priority_fee_per_gas:s.maxPriorityFeePerGas,nonce:ss(s.nonce),chain_id:ss(t)};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}class is{constructor(e){this.opts=e,this.walletAddress=null,this.client=new Vi({baseUrl:e.baseUrl,transport:e.transport,getAccessToken:e.getAccessToken,now:e.now}),this.authzKeys=new Ki({client:this.client,getIssuanceJwt:e.getAccessToken,now:e.now})}async checkWallet(){return await this.findWallet()?"exists":"not_found"}async getOrCreateWallet(e){if(this.walletAddress)return this.walletData(this.walletAddress);const t=await this.findWallet();if(t)return this.walletData(t.address);const r=this.requirePin(),n=qi(await this.opts.getAccessToken()),i=await Qr(),{result:a,aad:o}=await this.withEnvelope("generate",n,{command:"generate"},{pin:r,response_key:i.publicKey},(c,u)=>this.client.call("POST","/wallets",{envelope:c,intent:u,ignore_backup:!1}));if(this.walletAddress=a.address,a.sealed_share_c&&this.opts.onShareC){const c=await rs(i,a.sealed_share_c,o);await this.opts.onShareC(c,a.address)}return this.walletData(a.address)}async getAddresses(e){const t=await this.requireWalletAddress(),r=await this.client.call("GET",`/wallets/${t}/addresses`);return((r==null?void 0:r.addresses)??[]).map(n=>({address:n.address,index:n.index,name:n.name||void 0}))}async getAddress(e,t){const r=await this.requireWalletAddress(),n=(await this.getAddresses(e)).find(a=>a.index===t);if(n)return{address:n.address,derivationPath:Yt(t)};const{result:i}=await this.withEnvelope("get_address",r,{command:"get_address",index:t},{pin:this.requirePin()},(a,o)=>this.client.call("PUT",`/wallets/${r}/addresses/${t}`,{envelope:a,intent:o}));return{address:i.address,derivationPath:Yt(t)}}async signMessage(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),{result:c}=await this.withEnvelope("sign_message",o.address,{command:"sign_message",index:o.index,message:oe(Yi(r))},{pin:this.requirePin()},(u,f)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"message",envelope:u,intent:f}));return{chainId:t,signature:c.signature,format:"hex"}}async signTypedData(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),c=typeof r=="string"?JSON.parse(r):r,{result:u}=await this.withEnvelope("sign_typed_data",o.address,{command:"sign_typed_data",index:o.index,typed_data:c},{pin:this.requirePin()},(f,g)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"typed_data",chain_id:t,envelope:f,intent:g}));return{chainId:t,signature:u.signature,format:"hex"}}async signTransaction(e,t,r,n){const i=await this.resolveTarget(n,r.from),{result:a}=await this.withEnvelope("sign",i.address,{command:"sign",index:i.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(o,c)=>this.client.call("POST",`/wallets/${i.address}/signatures`,{type:"transaction",chain_id:t,envelope:o,intent:c}));return{chainId:t,signature:a.signed_tx,txHash:a.tx_hash,format:"hex"}}async sendTransaction(e,t,r){const n=await this.resolveTarget(void 0,r.from),{result:i}=await this.withEnvelope("sign",n.address,{command:"sign",index:n.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(a,o)=>this.client.call("POST",`/wallets/${n.address}/transactions`,{chain_id:t,envelope:a,intent:o}));return{txHash:i.tx_hash}}async signOut(){this.walletAddress=null,await this.authzKeys.revoke()}walletData(e){return{id:e,address:e,derivationPath:Yt(0),createdAt:Date.now()}}async findWallet(){const e=await this.client.call("GET","/wallets"),t=Array.isArray(e)?e[0]??null:null;return this.walletAddress=(t==null?void 0:t.address)??null,t}async requireWalletAddress(){if(this.walletAddress)return this.walletAddress;const e=await this.findWallet();if(!e)throw new h(l.WALLET_NOT_FOUND,"no wallet for this account");return e.address}async resolveTarget(e,t){const r=await this.requireWalletAddress();if(!t&&!e)return{address:r,index:0};if(t&&t.toLowerCase()===r.toLowerCase()&&!e)return{address:r,index:0};const n=await this.getAddresses(""),i=t?n.find(a=>a.address.toLowerCase()===t.toLowerCase()):n.find(a=>a.index===e);if(!i)throw new h(l.TX_INVALID_PARAMS,t?`from is not an address of this wallet: ${t}`:`no derived address at index ${e}`);if(e!==void 0&&e!==i.index)throw new h(l.TX_INVALID_PARAMS,`from (index ${i.index}) does not match index ${e}`);return{address:i.address,index:i.index}}requirePin(){const e=this.opts.pinStore.get();if(!e)throw new h(l.PIN_NOT_SET,"PIN is required");return e}async withEnvelope(e,t,r,n,i){var a;for(let o=0;;o++){const c=await Mi({recipientPub:await this.client.getRecipientKey(),bindingId:t,command:e,intent:r,plaintext:n,authz:await this.authzKeys.get(),now:this.opts.now?new Date(this.opts.now()):void 0});try{return{result:await i(c.envelope,c.intent),aad:c.aad}}catch(u){if(o>0||!(u instanceof h))throw u;const f=(a=u.details)==null?void 0:a.serverCode;if(f==="AUTHZ_INVALID")this.authzKeys.invalidate();else if(f==="ENVELOPE_INVALID")this.client.forgetRecipientKey();else throw u}}}}const zi=3,Xi=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function ji(s){return s.code===zi||/execution reverted/i.test(s.message??"")}class Zi{constructor(e,t){this.chainRegistry=e,this.transport=t,this._nextId=1}async call(e,t,r){const n=await this.chainRegistry.getChain(r),i={jsonrpc:"2.0",method:e,params:t,id:this._nextId++},o=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(o!=null&&o.error){const{code:c,message:u}=o.error,f={method:e,chainId:r,code:c,message:u,data:o.error.data},g=ji(o.error);throw g&&typeof f.data=="string"&&Xi.test(f.data)&&(f.revertData=f.data,f.selector=f.data.slice(0,10).toLowerCase()),new h(g?l.EXECUTION_REVERTED:l.UNKNOWN_ERROR,`RPC 오류 [${e}] (${r}): ${u} (코드: ${c})`,f)}return o==null?void 0:o.result}}class Qi{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(n=>n(t))}removeAllListeners(){this.listeners.clear()}}function ea(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const t=new Uint8Array(16);return globalThis.crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class he{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const t=Date.now();for(;Date.now()-t<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await he.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=he.getBridge(),!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new h(l.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const t=await this.handshake();return this.context=t,d.log("[RNBridge] Bootstrap initialization complete",{activated:t.isActivated,ttl:`${t.absoluteTtlMs/1e3/60}min`}),t}async handshake(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=ea(),t=Date.now(),r={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:t,hmac:""};try{const n=await this.bridge.handshake(r);if(!n.activated)throw new h(l.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0,o=n.provider==="google"||n.provider==="apple"?n.provider:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:a,walletProvider:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new h(l.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),t=(e.expiresAt-Date.now())/1e3;if(t<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return this.touchActivity(),e}catch(e){if(e instanceof h)throw e;const t=e instanceof Error?e.message:String(e);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new h(l.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new h(l.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof h?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new h(l.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new h(l.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const t=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((t.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return t}catch(t){throw t instanceof h?t:(d.warn("[RNBridge] Session restore Firebase token request failed",t),new h(l.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",t))}}getContext(){return this.context}isActive(){var t;if(!((t=this.context)!=null&&t.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new h(l.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var gt={environment:"production"};const Me={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"",oneWalletApiUrl:""},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"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",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://stg-oauth2.onechain.nexus",oneWalletApiUrl:""},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"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",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://dev-oauth2.onechain.nexus",oneWalletApiUrl:"https://dev-one-pocket-api.onechain.nexus/embed/v1"}};function ta(s){const e=s.environment,t=e&&e in Me?Me[e]:null;if(!t)return null;const r=s.overrides;if(!r)return t;const n={...t};for(const[i,a]of Object.entries(r))typeof a=="string"&&a.trim()!==""&&(n[i]=a);return n}function _t(){try{if(typeof gt<"u"){const s=typeof gt=="string"?JSON.parse(gt):gt,e=ta(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Me)return Me[s]}catch{}return Me.production}function as(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function ra(s,e=Dt){if(!s||s==="0x0"||s==="0x")return"0";try{const t=BigInt(s);if(t===0n)return"0";const r=10n**BigInt(Or),n=t/r,a=(t%r).toString().padStart(Or,"0"),o=as(a).slice(0,e);return o?`${n}.${o}`:`${n}`}catch{return"?"}}function pt(s,e,t,r=Dt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(t),a=n/i,c=(n%i).toString().padStart(t,"0"),u=as(c.slice(0,r)),f=u?`${a}.${u}`:`${a}`;return e?`${f} ${e}`:f}catch{return}}function sa(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Rr)throw new h(l.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Rr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function na(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function ia(s,e){const t=aa(e);if(s==="0"){if(t!==void 0&&t!==0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const r=s.match(/^eip155:(\d+)$/);if(r){const n=Number(r[1]);if(t===void 0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function aa(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const t=e.chainId;if(t==null)return;const r=Number(t);return Number.isFinite(r)?r:void 0}const oa=new Set(["095ea7b3","a22cb465","39509351","d73dd623","87517c45"]),ca=new Set(["Permit","PermitSingle","PermitBatch","PermitTransferFrom","PermitBatchTransferFrom","PermitWitnessTransferFrom","PermitBatchWitnessTransferFrom"]);function la(s){var r;const{action:e,context:t}=s;if(e==="sign"||e==="send"){const n=(r=t.tx)==null?void 0:r.data;if(typeof n!="string")return!1;const i=n.trim().toLowerCase().replace(/^0x/,"");return i.length>=8&&oa.has(i.slice(0,8))}if(e==="sign-typed-data"){const n=da(t.typedData);return n===null||ca.has(n)}return!1}function da(s){let e=s;if(typeof e=="string")try{e=JSON.parse(e)}catch{return null}if(e&&typeof e=="object"&&"primaryType"in e){const t=e.primaryType;return typeof t=="string"?t:null}return null}function ha(s,e,t,r){if(!s)return!0;if(s.mode==="off"||e===null)return!1;const n=t-e;return n<0||n>=s.ttlMs?!1:!la(r)}function ua(s){return(s==null?void 0:s.mode)==="off"}class Fe{constructor(e){this.deps=e,this.verifyPinMutex=null}prepareForSigning(e){var r,n;if(!this.deps.pinStore.has())return;const t=(n=(r=this.deps).getPinReusePolicy)==null?void 0:n.call(r);ha(t,this.deps.pinStore.getSetAt(),Date.now(),e)||this.deps.pinStore.clear()}finishSigning(){var e,t;ua((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))&&this.deps.pinStore.clear()}hasReusePolicy(){var e,t;return((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))!==void 0}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new h(l.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const t=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!t)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(t),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,t,r,n){var c,u;if((u=(c=this.deps).isRNBridgeMode)!=null&&u.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,a;this.verifyPinMutex=new Promise((f,g)=>{i=f,a=g});const o=we(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const g=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n});if(!g)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(g),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const f=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n,onSubmit:async g=>{this.deps.pinStore.set(g);try{return await this.deps.walletProvider.verifyPin(g)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:o.pin_input_error})}catch(S){if(this.deps.pinStore.clear(),S instanceof h){if(S.code===l.PIN_WRONG)return{ok:!1,error:o.pin_input_error};if(S.code===l.PIN_INVALID)return{ok:!1,error:S.message};if(S.code===l.PIN_LOCKED)return Fe.buildPinLockedResult(S,o)}throw S}}});if(!f)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(f),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(f){if(f instanceof h&&(f.code===l.AUTH_NOT_AUTHENTICATED||f.code===l.AUTH_TOKEN_EXPIRED||f.code===l.SESSION_EXPIRED)&&f.code!==l.SESSION_EXPIRED){const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw a(f),f}throw a(f),f}finally{this.verifyPinMutex=null}}async withPinRetry(e){const t=we(this.deps.getLocale()??"en");let r=null;try{return await e()}catch(n){if(n instanceof h){if(r=Fe.parsePinError(n,t),!r)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",r.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(r.errorMessage,r.lockExpiresAt,r.attemptCount,r.maxAttempts);try{return await e()}catch(n){if(n instanceof h&&(r=Fe.parsePinError(n,t),r))continue;throw n}}}static parsePinError(e,t){if(e.code===l.PIN_WRONG)return{errorMessage:t.pin_input_error};if(e.code===l.PIN_INVALID)return{errorMessage:e.message};if(e.code===l.PIN_LOCKED){const r=e.details;return r!=null&&r.permanent?{errorMessage:t.pin_locked_permanent}:(r==null?void 0:r.remainingAttempts)!=null&&r.remainingAttempts>0&&r.maxAttempts?{errorMessage:t.pin_input_error,attemptCount:r.maxAttempts-r.remainingAttempts,maxAttempts:r.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:r==null?void 0:r.lockExpiresAt}}return null}static buildPinLockedResult(e,t){const r=Fe.parsePinError(e,t);if(!r)return{ok:!1,error:e.message};const{errorMessage:n,...i}=r;return{ok:!1,error:n,...i}}}class fa{constructor(e){this.deps=e,this.signingQueue=Promise.resolve()}async confirmAndExecuteWithPreparedPin(e){if(!this.deps.pinOrchestrator.hasReusePolicy())return this.confirmAndExecute(e);const t=this.signingQueue.then(()=>this.confirmAndExecute(e));return this.signingQueue=t.then(()=>{},()=>{}),t}async confirmAndExecute(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new h(l.USER_REJECTED,e.rejectedMessage);this.deps.pinOrchestrator.prepareForSigning({action:e.prepareAction,context:e.prepareContext});try{return await this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}finally{this.deps.pinOrchestrator.finishSigning()}}}function ga(s){return s==="google"||s==="apple"}class _a{constructor(e){this.deps=e}async signInAgain(){var t,r;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=ga(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(u){throw this.deps.clearAuthState(),u}if(!i.success)return this.deps.clearAuthState(),i;const a=((t=i.user)==null?void 0:t.providerSub)??null,o=((r=i.user)==null?void 0:r.id)??null;if(!(e.providerSub?!!a&&a===e.providerSub:e.userId?!!o&&e.userId===o:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const u=we(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:u.session_alert_title,message:u.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,u.session_alert_apple_account):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{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(t){const r=we(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,r.session_alert_apple_account):void 0;if(t instanceof h&&t.code===l.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(t instanceof h&&t.code===l.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(!(t instanceof h)||t.code!==l.SESSION_EXPIRED)throw t;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new h(l.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new h(l.SESSION_EXPIRED,o.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class pa{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,t,r){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const a=await this.deps.walletProvider.getAddresses(n);if(a.length>0){let c,u=!1;if(t){const g=a.find(S=>S.address.toLowerCase()===t.toLowerCase());g?c=g:(c={address:t,index:0},u=!0)}else e!==void 0?c=a.find(g=>g.index===e)??a[0]:c=a[0];u?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const f=!!t&&!!r&&c.address.toLowerCase()===t.toLowerCase();this.deps.setActiveWallet(c.address,c.index,f?{walletName:r}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class wa{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const t=this.deps.getAllowSkip(),r=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:t});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",r),r==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,a=5,o=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${a})`,n?`— 이전 메시지: ${n}`:"");const f=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:a});if(f===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const g=await((u=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:u.call(c,f,e));if(!g){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),o=f;break}if(g.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),o=f;break}const S=g.pinStatus;if(a=S.maxAttempts,i=a-S.remainingAttempts,S.remainingAttempts===0&&S.lockExpiresAt){const E=S.lockExpiresAt*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${m}초, 메시지: ${y}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${a})`),n="Incorrect PIN."}catch(g){if(!(g instanceof h))throw g;if(g.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const S=we(this.deps.getLocale()??"en"),E=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:S.session_alert_title,message:S.alert_session_expired,email:E?this.deps.maskEmail(E,S.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),g}if(g.code===l.MIGRATION_PIN_LOCKED){const S=g.details;if(a=(S==null?void 0:S.maxAttempts)??5,(S==null?void 0:S.permanent)===!0)return d.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 E=((S==null?void 0:S.lockExpiresAt)??0)*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${m}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const f=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof h&&f.code===l.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof h&&f.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const y=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",y.address),y}catch(y){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",y),y}}throw this.deps.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}}class Sa{constructor(e){this.deps=e}async withResolvedGasAndFee(e,t){const r=E=>!(E!=null&&E.trim()),n=e.nonce===void 0||e.nonce===null,i=r(e.gasLimit),a=r(e.gasPrice)&&r(e.maxFeePerGas),o=!r(e.maxFeePerGas)&&r(e.maxPriorityFeePerGas);if(!n&&!i&&!a&&!o)return e;const c={...e},u=n?c.from??this.deps.getActiveAddress()??void 0:void 0;u&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",u,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),a&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[f,g,S]=await Promise.all([u?this.deps.jsonRpcCall("eth_getTransactionCount",[u,"pending"],t):null,i?this.deps.estimateGas(e,t):null,a?this.deps.getBaseFeePerGas(t):null]);if(u&&(c.nonce=parseInt(f??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=g,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),a){const E=S;if(E){const m=Tr;c.maxFeePerGas=`0x${(BigInt(E)+BigInt(m)).toString(16)}`,c.maxPriorityFeePerGas=m,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",E,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Un,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!a&&o&&(c.maxPriorityFeePerGas=Tr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ea{constructor(e){this.crypto=e}verifySignatureSigner(e,t,r){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,t);if(n.toLowerCase()!==r.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:r,recovered:n}),new h(l.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${r}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof h)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function ma(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class ya{constructor(e){this.deps=e}setActiveWallet(e,t,r){this.deps.setState({address:e,activeWalletIndex:t});const n={address:e,index:t};(r==null?void 0:r.walletName)!==void 0&&(n.walletName=r.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:t,address:e}).catch(()=>{})}applyAuthResult(e,t){var n,i,a,o,c;const r={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((a=e.user)==null?void 0:a.providerSub)??null,loginType:ma((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...t?{source:t}:{}})}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.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Aa{constructor(e){this.deps=e}async resolveAddress(e){const t=this.deps.getActiveWalletIndex(),r=this.deps.getActiveAddress();if(e===void 0||e===t){if(!r&&this.deps.ensureWallet)return{address:await this.deps.ensureWallet(),index:t};if(!r)throw new h(l.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:r,index:t}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ia{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new h(l.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new h(l.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Ta{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const t=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",t),t==="migration_required"){const a=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",a);const o=await this.deps.migrationOrchestrator.handleMigrationFlow(a);if(o)return this.deps.setActiveWallet(o.address,0),{address:o.address};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(t==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const r=await this.tryGetOrCreateWalletWithMigrationFallback(e);return r.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:r.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const t=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(t.address,0),d.log("[CROSSx] 지갑 준비 완료:",t.address),{address:t.address,migrated:!1}}catch(t){if(t instanceof h&&t.code===l.MIGRATION_BACKUP_EXISTS){const r=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(r);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw t}}}function os(s,e){const t=s.replace(/\/$/,""),r=e.startsWith("/")?e:`/${e}`;return`${t}/cross-auth${r}`}class Ra{constructor(e){this.deps=e}async registerTokenHistory(e,t,r){if(!(e!=null&&e.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param chain_id");if(!(t!=null&&t.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(r!=null&&r.trim())||r.length>64)throw new h(l.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),a=os(i,`/v2/token-historical/${e}/${n}`),o={clientVersion:r};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:a,method:"POST",headers:{"Content-Type":"application/json"},body:o,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof h?c:new h(l.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const t=this.deps.getApiBaseUrl(),r=new URL(os(t,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&r.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&r.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:r.toString(),method:"GET",retries:0});if(i.status===404)throw new h(l.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof h?i:new h(l.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,t,r,n){const i=(n==null?void 0:n.maxRetries)??3,a=(n==null?void 0:n.retryDelayMs)??2e3;for(let o=0;o<i;o++)try{await this.registerTokenHistory(e,t,r);return}catch(c){if(c instanceof h&&c.message.includes("404")&&o<i-1){d.log(`[TokenHistory] Retry ${o+1}/${i} (404 - tx not yet indexed)`),await new Promise(f=>setTimeout(f,a));continue}throw c}}handleError(e,t){const n={400:{code:l.TX_INVALID_PARAMS,message:`Bad request (400): ${t==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:l.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:l.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:l.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new h(n.code,n.message)}}function zt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const t=s.indexOf("@");if(t<0)return"*".repeat(s.length||3);const r=s.substring(0,t),n=s.substring(t);return r.length<=1?`${r}${"*".repeat(Math.max(r.length,1))}${n}`:`${r[0]}${"*".repeat(r.length-1)}${n}`}const Ie=class Ie extends Qi{constructor(e,t,r,n,i,a,o,c,u,f,g,S,E){var m,y;super(),this.storage=r,this.crypto=n,this.transport=i,this.oauth=a,this.walletProvider=o,this.tokenStore=c,this.pinEncryptor=S,this.oneIdAuth=E,this._warnedUnknownNativeCurrency=new Set,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._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._sdkDeprecationNotified=!1,this._sdkUnsupportedNotified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=t,e.logger&&Dr(e.logger),this.confirmation=u,this.pinStore=g??new Mt,this.stateManager=new ya({setState:w=>{w.authenticated!==void 0&&(this.authenticated=w.authenticated),w.userId!==void 0&&(this.userId=w.userId),w.address!==void 0&&(this.address=w.address),w.activeWalletIndex!==void 0&&(this.activeWalletIndex=w.activeWalletIndex),w.userEmail!==void 0&&(this.userEmail=w.userEmail),w.providerSub!==void 0&&(this.providerSub=w.providerSub),w.loginType!==void 0&&(this.loginType=w.loginType),w.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=w.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:w,index:A,walletName:P})=>{const F={address:w,index:A};P!==void 0&&(F.walletName=P),this.emit("addressChanged",F)},emitAuthChanged:({isAuthenticated:w,address:A,userId:P,source:F})=>{this.emit("authChanged",{isAuthenticated:w,address:A,userId:P,...F?{source:F}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Ie.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Fe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge,getPinReusePolicy:()=>this.internalConfig.pinReuse}),this.signingOrchestrator=new fa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new pa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(w,A,P)=>this.setActiveWallet(w,A,P)}),this.migrationOrchestrator=new wa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(w,A)=>this.migrateWalletUseCase.execute(w,A),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var w;return((w=this._config.migration)==null?void 0:w.allowSkip)??!0}}),this.transactionLifecycleService=new Sa({getActiveAddress:()=>this.address,estimateGas:(w,A)=>this.estimateGas(w,A),getBaseFeePerGas:w=>this.getBaseFeePerGas(w),jsonRpcCall:(w,A,P)=>this.jsonRpc.call(w,A,P)}),this.signatureVerifier=new Ea(this.crypto),this.addressResolverService=new Aa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId,ensureWallet:this.usesOneWallet?()=>this.walletCreationService.createWallet().then(w=>w.address):void 0}),this.authGuardService=new Ia({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Ta({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(w,A)=>this.setActiveWallet(w,A),showWalletCreated:()=>{var w,A;return((A=(w=this.confirmation).showWalletCreatedPrompt)==null?void 0:A.call(w))??Promise.resolve()}}),this.tokenHistoryService=new Ra({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new _a({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:w=>{this._isRecoveringSession=w},setAuthenticated:w=>{this.authenticated=w},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:w=>this.signInUseCase.execute(w),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:w=>this.confirmation.showSessionAlert(w),clearAuthState:()=>this.clearAuthState(),applyAuthResult:w=>this.applyAuthResult(w),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:zt}),this.chainRegistry=f,this.jsonRpc=new Zi(f,i),this.signInUseCase=new Bt(this.internalConfig,r,n,a,i,o,c,void 0,()=>this._config.locale),this.signOutUseCase=new ti(this.internalConfig,r,c,this._config.persistWalletPreference!==!1?[Ie.WALLET_PREF_KEY]:[]),this.migrateWalletUseCase=new ri(r,o),(m=o.setOnUnauthorized)==null||m.call(o,()=>this.forceLogout()),(y=o.setTokenRefresher)==null||y.call(o,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}handleSdkVersionDeprecation(e){if(this._sdkDeprecationNotified)return;this._sdkDeprecationNotified=!0;const t=ot;console.warn(`[CROSSx] ${t} is deprecated`+(e.sunset?` and will stop working on ${e.sunset}`:"")+". Update @nexus-cross/crossx-sdk-core."+(e.infoUrl?` See ${e.infoUrl}`:"")),this.emit("versionDeprecated",{version:t,sunset:e.sunset,infoUrl:e.infoUrl})}handleSdkVersionUnsupported(e){this._sdkUnsupportedNotified||(this._sdkUnsupportedNotified=!0,console.error(`[CROSSx] ${ot} is no longer supported by the wallet gateway. Update @nexus-cross/crossx-sdk-core.`+(e.message?` (${e.message})`:"")),this.confirmation.showUpdateRequired().catch(t=>{d.warn("[CROSSx] 업데이트 필요 모달 표시 실패:",t)}))}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,d.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(t){d.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",t)}}}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}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 t,r;d.log("[CROSSx SDK] v3.0.0-beta.1 초기화 중..."),this.confirmation.setMessages(we(this._config.locale));try{const n=_t();if(this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(r=(t=this.crypto).setJWKSEndpoint)==null||r.call(t,`${n.authApiUrl}/.well-known/jwks.json`),this.usesOneWallet){const u=await this.restoreOneWalletSession();return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.1 초기화 완료 (one-wallet)"),this.emit("initialized",{restored:!!(u!=null&&u.success)}),u}const i=this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,a=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let o=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((o==null?void 0:o.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),o=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const u=this.address&&(!o||this.address.toLowerCase()===o.toLowerCase()),f=this._rnBridgeWalletName&&o&&this._rnBridgeWalletAddress&&o.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(u)this.address&&this.setActiveWallet(this.address,a??this.activeWalletIndex,f?{walletName:f}:void 0);else try{await this.loadWalletAfterAuth(a,o,f)}catch(g){if(g instanceof h&&g.code===l.PIN_CANCELLED)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(g instanceof h&&(g.code===l.SESSION_EXPIRED||g.code===l.AUTH_NOT_AUTHENTICATED||g.code===l.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",g.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw g}}return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.1 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new h(l.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!he.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),d.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"3.0.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new he({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"3.0.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),t=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=t.walletAddress,this._rnBridgeWalletName=t.walletName,this._rnBridgeWalletProvider=t.walletProvider,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:t.walletAddress??"(없음)",walletName:t.walletName??"(없음)"});const r=await this.signInUseCase.hasStoredRNBridgeSession();if(r&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(r){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const t=this._rnBridgeService.getContext(),r=Date.now();d.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:t?r-t.activatedAt:"(context 없음)",idleMs:t?r-t.lastActivityAt:"(context 없음)",absoluteTtlMs:(t==null?void 0:t.absoluteTtlMs)??"(context 없음)",idleTtlMs:(t==null?void 0:t.idleTtlMs)??"(context 없음)",absoluteExpired:t?r-t.activatedAt>t.absoluteTtlMs:"(context 없음)",idleExpired:t?r-t.lastActivityAt>t.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,d.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return d.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,null}}try{const t=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(r),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=r.user)==null?void 0:e.id}),r):null}catch(t){return t instanceof h&&t.code===l.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):t instanceof h&&t.code===l.SESSION_EXPIRED?(d.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",t),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const t=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=r.user)==null?void 0:e.id}),r):(this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 실패:",r.error),null)}catch(t){return this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",t),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new h(l.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new h(l.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return he.getBridge()}async signIn(e){if(this.ensureInitialized(),this.ensureNotOneWallet("signIn"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const t=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(t&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!t){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let r=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:Vn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new h(l.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(r);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof h?n:new h(l.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:t,...r}=e??{},n=await this.signIn(r);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c,t);return{...n,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i,t);return{...n,address:(a==null?void 0:a.address)??n.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",a))),i}}async signInWithOAuthToken(e){var r,n;if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithOAuthToken"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let t;try{t=await this.signInUseCase.executeWithOAuthToken(e),t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t,"external"),(n=(r=this.oauth).cancelPending)==null||n.call(r,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof h?i:new h(l.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!t.success)return{...t,addresses:[]};try{if(t.needsMigration||!t.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c);return{...t,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...t,address:(a==null?void 0:a.address)??t.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",a))),i}}async signInWithJWT(e,t){if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithJWT"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithJWT(e,t);return r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r)),r}catch(r){throw r instanceof h?r:new h(l.AUTH_FAILED,"JWT 로그인에 실패했습니다",r)}}signInWithOneId(e){var a,o;let t;try{t=this.oneIdContext()}catch(c){return Promise.reject(c)}const{port:r,config:n,sessions:i}=t;return r.authorize({...n,mode:(e==null?void 0:e.mode)??((a=this._config.oneId)==null?void 0:a.mode)??"auto",redirectUri:(o=this._config.oneId)==null?void 0:o.redirectUri,returnTo:e==null?void 0:e.returnTo}).then(async c=>{if(c.status==="redirecting")return c;const u=i.save(c.tokens);return this.usesOneWallet&&await this.applyOneIdSession(u),{status:"signed-in",session:u,returnTo:c.returnTo}})}async completeOneIdSignIn(e=window.location.href){const{port:t,config:r,sessions:n}=this.oneIdContext(),{tokens:i,returnTo:a}=await t.completeRedirect(r,e),o=n.save(i);return this.usesOneWallet&&await this.applyOneIdSession(o),{session:o,returnTo:a}}async getOneIdSession(){return this.oneIdContext().sessions.get()}async getOneIdAccessToken(){const e=this.usesOneWallet&&this._initPromise?this.oneIdContextUnchecked():this.oneIdContext();try{return await e.sessions.getAccessToken()}catch(t){throw this.usesOneWallet&&Vr(t)&&this.clearAuthState(),t}}async signOutOneId(){const{sessions:e}=this.oneIdContext();this.walletProvider instanceof is&&await this.walletProvider.signOut().catch(t=>d.warn("[CROSSx] B 키 폐기 실패 (로그아웃은 진행)",t));try{await e.signOut()}finally{this.usesOneWallet&&this.clearAuthState()}}ensureNotOneWallet(e){if(this.usesOneWallet)throw new h(l.NOT_IMPLEMENTED,`walletServer 'one-wallet' 에서는 ${e}() 를 쓸 수 없습니다. signInWithOneId() 로 로그인하세요`)}get usesOneWallet(){return this._config.walletServer==="one-wallet"}async restoreOneWalletSession(){await this.signOutUseCase.hasStoredSession().catch(()=>!1)&&(d.log("[CROSSx] one-wallet: 저장된 2.x 로그인 토큰을 무시하고 지운다"),await this.signOutUseCase.execute().catch(t=>d.warn("[CROSSx] 2.x 토큰 정리 실패",t)));let e;try{e=await this.oneIdContextUnchecked().sessions.get()}catch(t){return d.warn("[CROSSx] one-wallet: ONE ID 세션 복원 실패 — 로그아웃 상태로 시작",t),null}return e?this.applyOneIdSession(e):null}async applyOneIdSession(e){var n,i;let t;try{await((i=(n=this.walletProvider).checkWallet)==null?void 0:i.call(n))==="exists"&&(t=(await this.walletProvider.getOrCreateWallet(e.subject)).address)}catch(a){if(Vr(a))throw a;d.warn("[CROSSx] one-wallet: 지갑 조회 실패 — 주소 없이 로그인 상태로 둔다",a)}const r={success:!0,address:t,user:{id:e.subject}};return this.applyAuthResult(r),t&&this.setActiveWallet(t,0),r}oneIdContext(){return this.ensureInitialized(),this.oneIdContextUnchecked()}oneIdContextUnchecked(){const e=this._config.oneId;if(!this.oneIdAuth||!(e!=null&&e.clientId))throw new h(l.NOT_IMPLEMENTED,"이 환경에서는 ONE ID 로그인을 사용할 수 없습니다 (SDKConfig.oneId 필요)");const t=e.issuer||_t().oneIdIssuer;if(!t)throw new h(l.NOT_IMPLEMENTED,"ONE ID issuer가 정해지지 않았습니다. SDKConfig.oneId.issuer를 지정하세요");const r={issuer:t,clientId:e.clientId,scope:e.scope};return this._oneIdSessions??(this._oneIdSessions=new _i(this.oneIdAuth,r,pi(e.storage))),{port:this.oneIdAuth,config:r,sessions:this._oneIdSessions}}async signOut(){if(this.ensureInitialized(),this.usesOneWallet){await this.signOutOneId();return}try{await this.signOutUseCase.execute(),this.clearAuthState();const e=he.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(t){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",t)}}catch(e){throw new h(l.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}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",r)}return!0}const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(t);try{await this.loadWalletAfterAuth()}catch(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}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,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const t=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(t.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",t.address),t}catch(t){throw t instanceof h?t:new h(l.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",t)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new h(l.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,t){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const n=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const i=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,i)))).address,index:i};return r.push(o),o},e,t);return n&&this.setActiveWallet(n.address,n.index),n}async selectWalletIfMultiple(e,t){if(e.length<2)return null;const r=this._isAuthenticatedViaRNBridge?this._rnBridgeWalletAddress??this.address??void 0:void 0,n=!r&&this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,i=r?[r,t]:[t,n==null?void 0:n.address];for(const a of i){if(typeof a!="string"||!a)continue;const o=e.find(c=>c.address.toLowerCase()===a.toLowerCase());if(o)return this.setActiveWallet(o.address,o.index),o}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof h?e:new h(l.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(t){throw t instanceof h?t:new h(l.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,t)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),t=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};t(e.matches);const r=n=>t(n.matches);e.addEventListener("change",r),this._themeMediaCleanup=()=>e.removeEventListener("change",r)}applyTheme(e=this._config.theme??"light",t=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:t}),this.confirmation.setTheme(e,t)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(we(e))}setPinKeyboard(e){var t,r;this._config=Object.freeze({...this._config,pinKeyboard:e}),(r=(t=this.confirmation).setPinKeyboard)==null||r.call(t,e)}resolveNativeCurrency(e){const t=Zn(e,this._config.nativeCurrencies);return t||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),jn)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,t,r){return this.withSessionRecovery(()=>this._signMessage(e,t,r))}async _signMessage(e,t,r){const n=he.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const o=await n.signMessage({chainId:e,message:t,from:this.address??"",index:(r==null?void 0:r.index)??0,dappName:(r==null?void 0:r.dappName)??this._config.appName});return{chainId:e,signature:o.signature,message:t,address:this.address??""}}catch(o){if(!vr(o))throw Ue(o,l.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),d.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const a=await this.resolveAddress(r==null?void 0:r.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:a.address,message:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:t,from:a.address},execute:c=>this.walletProvider.signMessage(this.userId,e,t,r==null?void 0:r.index,c,a.address)});return this.signatureVerifier.verifySignatureSigner(t,o.signature,a.address),{chainId:e,signature:o.signature,message:t,address:a.address}}catch(o){throw o instanceof h?o:new h(l.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,t,r){return this.withSessionRecovery(()=>this._signTypedData(e,t,r))}async _signTypedData(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new h(l.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ia(e,t);const n=await this.resolveAddress(r==null?void 0:r.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:t,from:n.address},execute:a=>this.walletProvider.signTypedData(this.userId,e,t,r==null?void 0:r.index,a,n.address)});return sa(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof h?i:new h(l.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,t){return this.signTypedData(Ie.OFFCHAIN_CHAIN_ID,e,t)}async signTransaction(e,t,r){return this.withSessionRecovery(()=>this._signTransaction(e,t,r))}async _signTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:o=>this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,o)});return na(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${o}`,a)}}async sendTransaction(e,t,r){return this.withSessionRecovery(()=>this._sendTransaction(e,t,r))}async _sendTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async f=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,f)).txHash;const g=await this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,f);return g.txHash??g.signature}}),o=(t.data??"").toLowerCase().replace(/^0x/,""),c=o===""||o==="00000000",u=o.startsWith("a9059cbb");return(c||u)&&this.tokenHistoryService.registerHistoryFireAndForget(e,a,ot).catch(f=>d.log("[TokenHistory] register failed (non-critical):",f)),{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${o}`,a)}}async getTransactionReceipt(e,t){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],t)??null}catch{return null}}async waitForTxAndGetReceipt(e,t,r={}){const n=r.intervalMs??kn,i=Ln,a=r.timeoutMs??Ir,o=Date.now()+a;let c=n;for(;Date.now()<o;){const u=await this.getTransactionReceipt(e,t);if(u)return u;await new Promise(f=>setTimeout(f,c)),c=Math.min(c*2,i)}throw new h(l.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,t,r={}){var y,w;if(this._isAuthenticatedViaRNBridge){const A=he.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,t,r)}const{intervalMs:n,timeoutMs:i,...a}=r,{txHash:o}=await this.sendTransaction(e,t,a),c=n??((y=this._config.receiptPolling)==null?void 0:y.intervalMs)??Dn,u=i??((w=this._config.receiptPolling)==null?void 0:w.timeoutMs)??Ir,f=this.resolveNativeCurrency(e),g=t.from??"";let S,E;const m=this.waitForTxAndGetReceipt(o,e,{intervalMs:c,timeoutMs:u}).then(A=>{S=A;const P=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),F=t.value?BigInt(t.value):0n,M=pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),V=pt("0x"+P.toString(16),f.symbol,f.decimals,this._config.displayDecimals),U=pt("0x"+(F+P).toString(16),f.symbol,f.decimals,this._config.displayDecimals);return{chainId:e,txHash:o,from:A.from,to:A.to??t.to,amount:M,fees:V,total:U,nativeSymbol:f.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(E=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:o,from:g,to:t.to,amount:pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),nativeSymbol:f.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:o,from:g,to:t.to},m),E)throw E;return{chainId:e,txHash:o,receipt:S}}async bridgeSendTransactionWithWaitForReceipt(e,t,r,n){let i;try{i=await e.sendTransactionWithWaitForReceipt({chainId:t,tx:{to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce},from:r.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(a){throw Ue(a,l.TRANSACTION_FAILED)}return{chainId:t,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??r.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,t){this.ensureAuthenticated();const r=this.walletProvider;if(typeof r.changePin!="function")throw new h(l.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await r.changePin(e,t),this.pinStore.set(t),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof h?n:new h(l.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${r}`,t)}}async estimateGas(e,t){this.ensureAuthenticated();const r={};e.from&&(r.from=e.from),e.to&&(r.to=e.to),e.value&&(r.value=e.value),e.data&&(r.data=e.data),e.gasPrice&&(r.gasPrice=e.gasPrice),e.maxFeePerGas&&(r.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(r.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[r],t)}catch(n){if(n instanceof h&&n.code===l.EXECUTION_REVERTED)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${t}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const t=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(t==null?void 0:t.baseFeePerGas)??null}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getNonce(e){this.ensureAuthenticated();const t=this.address;if(!t)return 0;try{const r=await this.jsonRpc.call("eth_getTransactionCount",[t,"pending"],e);return parseInt(r??"0x0",16)}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,r)}}async getBalance(e){this.ensureAuthenticated();const t=this.address;if(!t)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[t,"latest"],e)??"0x0";return{wei:n,formatted:ra(n,this._config.displayDecimals),chainId:e}}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,r)}}getProvider(e){this.ensureAuthenticated();let t=this._providers.get(e);return t||(t=new Ut(this,e),this._providers.set(e,t)),t}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(t=>{try{t.emit("accountsChanged",[e])}catch(r){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",r)}})}async walletRpc(e,t,r){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,t,r)}catch(n){if(n instanceof h)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${r}): ${i}`,n)}}setActiveWallet(e,t,r){const n=this.address;this.stateManager.setActiveWallet(e,t,r),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=he.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",t=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!t||typeof t!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",t);return}const r=t,n=typeof r.address=="string"?r.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",r);return}if(r.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",r);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){d.warn("[walletChanged] not authenticated — 이벤트 무시",r);return}const i=typeof r.walletName=="string"?r.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:r.walletId,source:r.source,walletName:a}),this.setActiveWallet(n,0,{walletName:a}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=a)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,t){this.stateManager.applyAuthResult(e,t)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.ensureNotOneWallet("signInAgain"),this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.usesOneWallet?e():this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,t,r){return this.walletLifecycleService.loadWalletAfterAuth(e,t,r)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,t,r){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,t,r))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}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(),Dr(null)}};Ie.WALLET_PREF_KEY="wallet_preference",Ie.OFFCHAIN_CHAIN_ID="0";let Ze=Ie;class Oa{constructor(){this.prefix="crossx_"}async set(e,t){try{const r=JSON.stringify(t);localStorage.setItem(this.prefix+e,r)}catch(r){throw d.error("Storage set error:",r),r}}async get(e){try{const t=localStorage.getItem(this.prefix+e);return t?JSON.parse(t):null}catch(t){return d.error("Storage get error:",t),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(t){throw d.error("Storage remove error:",t),t}}async clear(){try{Object.keys(localStorage).forEach(t=>{t.startsWith(this.prefix)&&localStorage.removeItem(t)})}catch(e){throw d.error("Storage clear error:",e),e}}}const wt="crossx-sdk",cs=1,ce="data",Te="keys",St="aes-primary",Na=12;class ls{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(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,cs);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(ce)||n.createObjectStore(ce),n.objectStoreNames.contains(Te)||n.createObjectStore(Te)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}openLegacyIfExists(){return new Promise((e,t)=>{let r=!1;const n=indexedDB.open(wt,cs);n.onupgradeneeded=()=>{r=!0},n.onsuccess=()=>{const i=n.result;if(r){i.close(),this.deleteDB(wt).then(()=>e(null));return}if(!i.objectStoreNames.contains(Te)||!i.objectStoreNames.contains(ce)){i.close(),e(null);return}e(i)},n.onerror=()=>t(n.error)})}deleteDB(e){return new Promise(t=>{const r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>{d.warn("[CROSSx] IndexedDB 삭제 실패:",e,r.error),t()},r.onblocked=()=>{d.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),t()}})}idbGet(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readonly").objectStore(e).get(t);a.onsuccess=()=>r(a.result),a.onerror=()=>n(a.error)})}idbPut(e,t,r){return new Promise((n,i)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).put(r,t);o.onsuccess=()=>n(),o.onerror=()=>i(o.error)})}idbDelete(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).delete(t);a.onsuccess=()=>r(),a.onerror=()=>n(a.error)})}idbClear(e){return new Promise((t,r)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Te,St);if(e){this.cryptoKey=e;return}const t=await this.migrateFromLegacyDB();if(t){this.cryptoKey=t;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Te,St,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===wt)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const t=e.transaction([Te,ce],"readonly"),r=t.objectStore(Te).get(St),n=await new Promise((u,f)=>{r.onsuccess=()=>u(r.result),r.onerror=()=>f(r.error)});if(!n)return e.close(),null;const i=t.objectStore(ce).getAll(),a=t.objectStore(ce).getAllKeys(),[o,c]=await Promise.all([new Promise((u,f)=>{i.onsuccess=()=>u(i.result),i.onerror=()=>f(i.error)}),new Promise((u,f)=>{a.onsuccess=()=>u(a.result),a.onerror=()=>f(a.error)})]);e.close(),await this.idbPut(Te,St,n);for(let u=0;u<c.length;u++)await this.idbPut(ce,String(c[u]),o[u]);return await this.deleteDB(wt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const t=new Uint8Array(Na);crypto.getRandomValues(t);const r=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},this.cryptoKey,r);return{iv:t,ciphertext:n}}async decrypt(e){const t=new Uint8Array(e.iv),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(r)}async set(e,t){try{await this.ensureReady();const r=JSON.stringify(t),n=await this.encrypt(r);await this.idbPut(ce,e,n)}catch(r){throw d.error("[CROSSx] IndexedDB set error:",r),r}}async get(e){try{await this.ensureReady();const t=await this.idbGet(ce,e);if(!t)return null;const r=await this.decrypt(t);return JSON.parse(r)}catch(t){return d.error("[CROSSx] IndexedDB get error:",t),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ce,e)}catch(t){throw d.error("[CROSSx] IndexedDB remove error:",t),t}}async clear(){try{await this.ensureReady(),await this.idbClear(ce)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Xt=crypto,ds=s=>s instanceof CryptoKey,Et=new TextEncoder,Qe=new TextDecoder;function Pa(...s){const e=s.reduce((n,{length:i})=>n+i,0),t=new Uint8Array(e);let r=0;for(const n of s)t.set(n,r),r+=n.length;return t}const ba=s=>{const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ba(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class z extends Error{constructor(e,t){var r;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}z.code="ERR_JOSE_GENERIC";class le extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}le.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class jt extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}jt.code="ERR_JWT_EXPIRED";class hs extends z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}hs.code="ERR_JOSE_ALG_NOT_ALLOWED";class ue extends z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ue.code="ERR_JOSE_NOT_SUPPORTED";class xa extends z{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}xa.code="ERR_JWE_DECRYPTION_FAILED";class va extends z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}va.code="ERR_JWE_INVALID";class q extends z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}q.code="ERR_JWS_INVALID";class fe extends z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}fe.code="ERR_JWT_INVALID";class Ca extends z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ca.code="ERR_JWK_INVALID";class Zt extends z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Zt.code="ERR_JWKS_INVALID";class Qt extends z{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Qt.code="ERR_JWKS_NO_MATCHING_KEY";class us extends z{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}us.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class fs extends z{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}fs.code="ERR_JWKS_TIMEOUT";class gs extends z{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}gs.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function ge(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function er(s){return parseInt(s.name.slice(4),10)}function Da(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ka(s,e){if(e.length&&!e.some(t=>s.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const r=e.pop();t+=`one of ${e.join(", ")}, or ${r}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function La(s,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw ge("HMAC");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw ge("RSASSA-PKCS1-v1_5");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw ge("RSA-PSS");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw ge("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw ge("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw ge("ECDSA");const r=Da(e);if(s.algorithm.namedCurve!==r)throw ge(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ka(s,t)}function _s(s,e,...t){var r;if(t=t.filter(Boolean),t.length>2){const n=t.pop();s+=`one of type ${t.join(", ")}, or ${n}.`}else t.length===2?s+=`one of type ${t[0]} or ${t[1]}.`:s+=`of type ${t[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(r=e.constructor)!=null&&r.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const ps=(s,...e)=>_s("Key must be ",s,...e);function ws(s,e,...t){return _s(`Key for the ${s} algorithm must be `,e,...t)}const Ss=s=>ds(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",mt=["CryptoKey"],Ua=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const r of e){const n=Object.keys(r);if(!t||t.size===0){t=new Set(n);continue}for(const i of n){if(t.has(i))return!1;t.add(i)}}return!0};function Wa(s){return typeof s=="object"&&s!==null}function Ee(s){if(!Wa(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const Ba=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ke(s){return Ee(s)&&typeof s.kty=="string"}function Ma(s){return s.kty!=="oct"&&typeof s.d=="string"}function Fa(s){return s.kty!=="oct"&&typeof s.d>"u"}function Ka(s){return Ke(s)&&s.kty==="oct"&&typeof s.k=="string"}function Ha(s){let e,t;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},t=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},t=s.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(s.alg.slice(-3),10)||1}`},t=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},t=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},t=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ue('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Es=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Ha(s),r=[e,s.ext??!1,s.key_ops??t],n={...s};return delete n.alg,delete n.use,Xt.subtle.importKey("jwk",n,...r)},ms=s=>Re(s);let He,Ge;const ys=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",yt=async(s,e,t,r,n=!1)=>{let i=s.get(e);if(i!=null&&i[r])return i[r];const a=await Es({...t,alg:r});return n&&Object.freeze(e),i?i[r]=a:s.set(e,{[r]:a}),a},Ga={normalizePublicKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?ms(t.k):(Ge||(Ge=new WeakMap),yt(Ge,s,t,e))}return Ke(s)?s.k?Re(s.k):(Ge||(Ge=new WeakMap),yt(Ge,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return t.k?ms(t.k):(He||(He=new WeakMap),yt(He,s,t,e))}return Ke(s)?s.k?Re(s.k):(He||(He=new WeakMap),yt(He,s,s,e,!0)):s}};async function As(s,e){if(!Ee(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ue('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Es({...s,alg:e});default:throw new ue('Unsupported "kty" (Key Type) Parameter value')}}const $e=s=>s==null?void 0:s[Symbol.toStringTag],tr=(s,e,t)=>{var r,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=(r=e.key_ops).includes)==null?void 0:n.call(r,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},$a=(s,e,t,r)=>{if(!(e instanceof Uint8Array)){if(r&&Ke(e)){if(Ka(e)&&tr(s,e,t))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(!Ss(e))throw new TypeError(ws(s,e,...mt,"Uint8Array",r?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${$e(e)} instances for symmetric algorithms must be of type "secret"`)}},Va=(s,e,t,r)=>{if(r&&Ke(e))switch(t){case"sign":if(Ma(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Fa(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ss(e))throw new TypeError(ws(s,e,...mt,r?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${$e(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Is(s,e,t,r){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?$a(e,t,r,s):Va(e,t,r,s)}Is.bind(void 0,!1);const Ts=Is.bind(void 0,!0);function Ja(s,e,t,r,n){if(n.crit!==void 0&&(r==null?void 0:r.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(a=>typeof a!="string"||a.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;t!==void 0?i=new Map([...Object.entries(t),...e.entries()]):i=e;for(const a of r.crit){if(!i.has(a))throw new ue(`Extension Header Parameter "${a}" is not recognized`);if(n[a]===void 0)throw new s(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&r[a]===void 0)throw new s(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}const qa=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function Ya(s,e){const t=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ue(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function za(s,e,t){if(e=await Ga.normalizePublicKey(e,s),ds(e))return La(e,s,t),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(ps(e,...mt));return Xt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(ps(e,...mt,"Uint8Array","JSON Web Key"))}const Xa=async(s,e,t,r)=>{const n=await za(s,e,"verify");Ba(s,n);const i=Ya(s,n.algorithm);try{return await Xt.subtle.verify(i,n,t,r)}catch{return!1}};async function ja(s,e,t){if(!Ee(s))throw new q("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new q('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new q("JWS Protected Header incorrect type");if(s.payload===void 0)throw new q("JWS Payload missing");if(typeof s.signature!="string")throw new q("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Ee(s.header))throw new q("JWS Unprotected Header incorrect type");let r={};if(s.protected)try{const y=Re(s.protected);r=JSON.parse(Qe.decode(y))}catch{throw new q("JWS Protected Header is invalid")}if(!Ua(r,s.header))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...r,...s.header},i=Ja(q,new Map([["b64",!0]]),t==null?void 0:t.crit,r,n);let a=!0;if(i.has("b64")&&(a=r.b64,typeof a!="boolean"))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=n;if(typeof o!="string"||!o)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=t&&qa("algorithms",t.algorithms);if(c&&!c.has(o))throw new hs('"alg" (Algorithm) Header Parameter value not allowed');if(a){if(typeof s.payload!="string")throw new q("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new q("JWS Payload must be a string or an Uint8Array instance");let u=!1;typeof e=="function"?(e=await e(r,s),u=!0,Ts(o,e,"verify"),Ke(e)&&(e=await As(e,o))):Ts(o,e,"verify");const f=Pa(Et.encode(s.protected??""),Et.encode("."),typeof s.payload=="string"?Et.encode(s.payload):s.payload);let g;try{g=Re(s.signature)}catch{throw new q("Failed to base64url decode the signature")}if(!await Xa(o,e,g,f))throw new gs;let E;if(a)try{E=Re(s.payload)}catch{throw new q("Failed to base64url decode the payload")}else typeof s.payload=="string"?E=Et.encode(s.payload):E=s.payload;const m={payload:E};return s.protected!==void 0&&(m.protectedHeader=r),s.header!==void 0&&(m.unprotectedHeader=s.header),u?{...m,key:e}:m}async function Za(s,e,t){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new q("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:i,length:a}=s.split(".");if(a!==3)throw new q("Invalid Compact JWS");const o=await ja({payload:n,protected:r,signature:i},e,t),c={payload:o.payload,protectedHeader:o.protectedHeader};return typeof e=="function"?{...c,key:o.key}:c}const Qa=s=>Math.floor(s.getTime()/1e3),Rs=60,Os=Rs*60,rr=Os*24,eo=rr*7,to=rr*365.25,ro=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ns=s=>{const e=ro.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const t=parseFloat(e[2]),r=e[3].toLowerCase();let n;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(t);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(t*Rs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(t*Os);break;case"day":case"days":case"d":n=Math.round(t*rr);break;case"week":case"weeks":case"w":n=Math.round(t*eo);break;default:n=Math.round(t*to);break}return e[1]==="-"||e[4]==="ago"?-n:n},Ps=s=>s.toLowerCase().replace(/^application\//,""),so=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,no=(s,e,t={})=>{let r;try{r=JSON.parse(Qe.decode(e))}catch{}if(!Ee(r))throw new fe("JWT Claims Set must be a top-level JSON object");const{typ:n}=t;if(n&&(typeof s.typ!="string"||Ps(s.typ)!==Ps(n)))throw new le('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:o,audience:c,maxTokenAge:u}=t,f=[...i];u!==void 0&&f.push("iat"),c!==void 0&&f.push("aud"),o!==void 0&&f.push("sub"),a!==void 0&&f.push("iss");for(const m of new Set(f.reverse()))if(!(m in r))throw new le(`missing required "${m}" claim`,r,m,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(r.iss))throw new le('unexpected "iss" claim value',r,"iss","check_failed");if(o&&r.sub!==o)throw new le('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!so(r.aud,typeof c=="string"?[c]:c))throw new le('unexpected "aud" claim value',r,"aud","check_failed");let g;switch(typeof t.clockTolerance){case"string":g=Ns(t.clockTolerance);break;case"number":g=t.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:S}=t,E=Qa(S||new Date);if((r.iat!==void 0||u)&&typeof r.iat!="number")throw new le('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new le('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>E+g)throw new le('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new le('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=E-g)throw new jt('"exp" claim timestamp check failed',r,"exp","check_failed")}if(u){const m=E-r.iat,y=typeof u=="number"?u:Ns(u);if(m-g>y)throw new jt('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(m<0-g)throw new le('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r};async function io(s,e,t){var a;const r=await Za(s,e,t);if((a=r.protectedHeader.crit)!=null&&a.includes("b64")&&r.protectedHeader.b64===!1)throw new fe("JWTs MUST NOT use unencoded payload");const i={payload:no(r.protectedHeader,r.payload,t),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}function ao(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ue('Unsupported "alg" value for a JSON Web Key Set')}}function oo(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(co)}function co(s){return Ee(s)}function bs(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class lo{constructor(e){if(this._cached=new WeakMap,!oo(e))throw new Zt("JSON Web Key Set malformed");this._jwks=bs(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t==null?void 0:t.header},i=ao(r),a=this._jwks.keys.filter(u=>{let f=i===u.kty;if(f&&typeof n=="string"&&(f=n===u.kid),f&&typeof u.alg=="string"&&(f=r===u.alg),f&&typeof u.use=="string"&&(f=u.use==="sig"),f&&Array.isArray(u.key_ops)&&(f=u.key_ops.includes("verify")),f)switch(r){case"ES256":f=u.crv==="P-256";break;case"ES256K":f=u.crv==="secp256k1";break;case"ES384":f=u.crv==="P-384";break;case"ES512":f=u.crv==="P-521";break;case"Ed25519":f=u.crv==="Ed25519";break;case"EdDSA":f=u.crv==="Ed25519"||u.crv==="Ed448";break}return f}),{0:o,length:c}=a;if(c===0)throw new Qt;if(c!==1){const u=new us,{_cached:f}=this;throw u[Symbol.asyncIterator]=async function*(){for(const g of a)try{yield await xs(f,g,r)}catch{}},u}return xs(this._cached,o,r)}}async function xs(s,e,t){const r=s.get(e)||s.set(e,{}).get(e);if(r[t]===void 0){const n=await As({...e,ext:!0},t);if(n instanceof Uint8Array||n.type!=="public")throw new Zt("JSON Web Key Set members must be public keys");r[t]=n}return r[t]}function vs(s){const e=new lo(s),t=async(r,n)=>e.getKey(r,n);return Object.defineProperties(t,{jwks:{value:()=>bs(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),t}const ho=async(s,e,t)=>{let r,n,i=!1;typeof AbortController=="function"&&(r=new AbortController,n=setTimeout(()=>{i=!0,r.abort()},e));const a=await fetch(s.href,{signal:r?r.signal:void 0,redirect:"manual",headers:t.headers}).catch(o=>{throw i?new fs:o});if(n!==void 0&&clearTimeout(n),a.status!==200)throw new z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new z("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function uo(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let sr;(typeof navigator>"u"||!((xn=(Ct=navigator.userAgent)==null?void 0:Ct.startsWith)!=null&&xn.call(Ct,"Mozilla/5.0 ")))&&(sr="jose/v5.10.0");const nr=Symbol();function fo(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Ee(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Ee))}class go{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:t==null?void 0:t.agent,headers:t==null?void 0:t.headers},this._timeoutDuration=typeof(t==null?void 0:t.timeoutDuration)=="number"?t==null?void 0:t.timeoutDuration:5e3,this._cooldownDuration=typeof(t==null?void 0:t.cooldownDuration)=="number"?t==null?void 0:t.cooldownDuration:3e4,this._cacheMaxAge=typeof(t==null?void 0:t.cacheMaxAge)=="number"?t==null?void 0:t.cacheMaxAge:6e5,(t==null?void 0:t[nr])!==void 0&&(this._cache=t==null?void 0:t[nr],fo(t==null?void 0:t[nr],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=vs(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,t){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof Qt&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&uo()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);sr&&!e.has("User-Agent")&&(e.set("User-Agent",sr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ho(this._url,this._timeoutDuration,this._options).then(t=>{this._local=vs(t),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=t),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}}function _o(s,e){const t=new go(s,e),r=async(n,i)=>t.getKey(n,i);return Object.defineProperties(r,{coolingDown:{get:()=>t.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>t.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>t.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!t._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=t._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),r}const po=Re;function wo(s){if(typeof s!="string")throw new fe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=s.split(".");if(t===5)throw new fe("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new fe("Invalid JWT");if(!e)throw new fe("JWTs must contain a payload");let r;try{r=po(e)}catch{throw new fe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(r))}catch{throw new fe("Failed to parse the decoded payload as JSON")}if(!Ee(n))throw new fe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ir(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function me(s,e=""){if(!Number.isSafeInteger(s)||s<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${s}`)}}function $(s,e,t=""){const r=ir(s),n=s==null?void 0:s.length,i=e!==void 0;if(!r||i&&n!==e){const a=t&&`"${t}" `,o=i?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(a+"expected Uint8Array"+o+", got "+c)}return s}function Cs(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");me(s.outputLen),me(s.blockLen)}function Ve(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ds(s,e){$(s,void 0,"digestInto() output");const t=e.outputLen;if(s.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function So(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function ar(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function _e(s,e){return s<<32-e|s>>>e}const Eo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function mo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function yo(s){for(let e=0;e<s.length;e++)s[e]=mo(s[e]);return s}const ks=Eo?s=>s:yo,Ls=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ao=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if($(s),Ls)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Ao[s[t]];return e}const ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function Us(s){if(s>=ye._0&&s<=ye._9)return s-ye._0;if(s>=ye.A&&s<=ye.F)return s-(ye.A-10);if(s>=ye.a&&s<=ye.f)return s-(ye.a-10)}function At(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ls)return Uint8Array.fromHex(s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){const a=Us(s.charCodeAt(i)),o=Us(s.charCodeAt(i+1));if(a===void 0||o===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=a*16+o}return r}function Oe(...s){let e=0;for(let r=0;r<s.length;r++){const n=s[r];$(n),e+=n.length}const t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){const i=s[r];t.set(i,n),n+=i.length}return t}function Ws(s,e={}){const t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Bs(s=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(s))}const Io=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function To(s,e,t){return s&e^~s&t}function Ro(s,e,t){return s&e^s&t^e&t}class Oo{constructor(e,t,r,n){T(this,"blockLen");T(this,"outputLen");T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ar(this.buffer)}update(e){Ve(this),$(e);const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(n-this.pos,i-a);if(o===n){const c=ar(e);for(;n<=i-a;a+=n)this.process(c,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ve(this),Ds(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:a}=this;t[a++]=128,Je(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let g=a;g<n;g++)t[g]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);const o=ar(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<u;g++)o.setUint32(4*g,f[g],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),It=BigInt(2**32-1),Ms=BigInt(32);function No(s,e=!1){return e?{h:Number(s&It),l:Number(s>>Ms&It)}:{h:Number(s>>Ms&It)|0,l:Number(s&It)|0}}function Po(s,e=!1){const t=s.length;let r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){const{h:a,l:o}=No(s[i],e);[r[i],n[i]]=[a,o]}return[r,n]}const bo=(s,e,t)=>s<<t|e>>>32-t,xo=(s,e,t)=>e<<t|s>>>32-t,vo=(s,e,t)=>e<<t-32|s>>>64-t,Co=(s,e,t)=>s<<t-32|e>>>64-t,Do=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]),Pe=new Uint32Array(64);class ko extends Oo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:c}=this;return[e,t,r,n,i,a,o,c]}set(e,t,r,n,i,a,o,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,t){for(let g=0;g<16;g++,t+=4)Pe[g]=e.getUint32(t,!1);for(let g=16;g<64;g++){const S=Pe[g-15],E=Pe[g-2],m=_e(S,7)^_e(S,18)^S>>>3,y=_e(E,17)^_e(E,19)^E>>>10;Pe[g]=y+Pe[g-7]+m+Pe[g-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:c,G:u,H:f}=this;for(let g=0;g<64;g++){const S=_e(o,6)^_e(o,11)^_e(o,25),E=f+S+To(o,c,u)+Do[g]+Pe[g]|0,y=(_e(r,2)^_e(r,13)^_e(r,22))+Ro(r,n,i)|0;f=u,u=c,c=o,o=a+E|0,a=i,i=n,n=r,r=E+y|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,n,i,a,o,c,u,f)}roundClean(){Je(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Je(this.buffer)}}class Lo extends ko{constructor(){super(32);T(this,"A",Ne[0]|0);T(this,"B",Ne[1]|0);T(this,"C",Ne[2]|0);T(this,"D",Ne[3]|0);T(this,"E",Ne[4]|0);T(this,"F",Ne[5]|0);T(this,"G",Ne[6]|0);T(this,"H",Ne[7]|0)}}const Uo=Ws(()=>new Lo,Io(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const or=BigInt(0),cr=BigInt(1);function Tt(s,e=""){if(typeof s!="boolean"){const t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function Fs(s){if(typeof s=="bigint"){if(!Nt(s))throw new Error("positive bigint expected, got "+s)}else me(s);return s}function Rt(s){const e=Fs(s).toString(16);return e.length&1?"0"+e:e}function Ks(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?or:BigInt("0x"+s)}function Ot(s){return Ks(tt(s))}function Hs(s){return Ks(tt(Wo($(s)).reverse()))}function lr(s,e){me(e),s=Fs(s);const t=At(s.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Gs(s,e){return lr(s,e).reverse()}function Wo(s){return Uint8Array.from(s)}const Nt=s=>typeof s=="bigint"&&or<=s;function Bo(s,e,t){return Nt(s)&&Nt(e)&&Nt(t)&&e<=s&&s<t}function Mo(s,e,t,r){if(!Bo(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Fo(s){let e;for(e=0;s>or;s>>=cr,e+=1);return e}const dr=s=>(cr<<BigInt(s))-cr;function Ko(s,e,t){if(me(s,"hashLen"),me(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");const r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),a=Uint8Array.of(1),o=1e3;let c=r(s),u=r(s),f=0;const g=()=>{c.fill(1),u.fill(0),f=0},S=(...w)=>t(u,Oe(c,...w)),E=(w=n)=>{u=S(i,w),c=S(),w.length!==0&&(u=S(a,w),c=S())},m=()=>{if(f++>=o)throw new Error("drbg: tried max amount of iterations");let w=0;const A=[];for(;w<e;){c=S();const P=c.slice();A.push(P),w+=c.length}return Oe(...A)};return(w,A)=>{g(),E(w);let P;for(;!(P=A(m()));)E();return g(),P}}function hr(s,e={},t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(i,a,o){const c=s[i];if(o&&c===void 0)return;const u=typeof c;if(u!==a||c===null)throw new Error(`param "${i}" is invalid: expected ${a}, got ${u}`)}const n=(i,a)=>Object.entries(i).forEach(([o,c])=>r(o,c,a));n(e,!1),n(t,!0)}function $s(s){const e=new WeakMap;return(t,...r)=>{const n=e.get(t);if(n!==void 0)return n;const i=s(t,...r);return e.set(t,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),Q=BigInt(1),ve=BigInt(2),Vs=BigInt(3),Js=BigInt(4),qs=BigInt(5),Ho=BigInt(7),Ys=BigInt(8),Go=BigInt(9),zs=BigInt(16);function de(s,e){const t=s%e;return t>=se?t:e+t}function ae(s,e,t){let r=s;for(;e-- >se;)r*=r,r%=t;return r}function Xs(s,e){if(s===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let t=de(s,e),r=e,n=se,i=Q;for(;t!==se;){const o=r/t,c=r%t,u=n-i*o;r=t,t=c,n=i,i=u}if(r!==Q)throw new Error("invert: does not exist");return de(n,e)}function ur(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function js(s,e){const t=(s.ORDER+Q)/Js,r=s.pow(e,t);return ur(s,r,e),r}function $o(s,e){const t=(s.ORDER-qs)/Ys,r=s.mul(e,ve),n=s.pow(r,t),i=s.mul(e,n),a=s.mul(s.mul(i,ve),n),o=s.mul(i,s.sub(a,s.ONE));return ur(s,o,e),o}function Vo(s){const e=Pt(s),t=Zs(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),a=(s+Ho)/zs;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,r);const g=o.mul(u,n),S=o.mul(u,i),E=o.eql(o.sqr(f),c),m=o.eql(o.sqr(g),c);u=o.cmov(u,f,E),f=o.cmov(S,g,m);const y=o.eql(o.sqr(f),c),w=o.cmov(u,f,y);return ur(o,w,c),w}}function Zs(s){if(s<Vs)throw new Error("sqrt is not defined for small field");let e=s-Q,t=0;for(;e%ve===se;)e/=ve,t++;let r=ve;const n=Pt(s);for(;en(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return js;let i=n.pow(r,e);const a=(e+Q)/ve;return function(c,u){if(c.is0(u))return u;if(en(c,u)!==1)throw new Error("Cannot find square root");let f=t,g=c.mul(c.ONE,i),S=c.pow(u,e),E=c.pow(u,a);for(;!c.eql(S,c.ONE);){if(c.is0(S))return c.ZERO;let m=1,y=c.sqr(S);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===f)throw new Error("Cannot find square root");const w=Q<<BigInt(f-m-1),A=c.pow(g,w);f=m,g=c.sqr(A),S=c.mul(S,g),E=c.mul(E,A)}return E}}function Jo(s){return s%Js===Vs?js:s%Ys===qs?$o:s%zs===Go?Vo(s):Zs(s)}const qo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=qo.reduce((r,n)=>(r[n]="function",r),e);return hr(s,t),s}function zo(s,e,t){if(t<se)throw new Error("invalid exponent, negatives unsupported");if(t===se)return s.ONE;if(t===Q)return e;let r=s.ONE,n=e;for(;t>se;)t&Q&&(r=s.mul(r,n)),n=s.sqr(n),t>>=Q;return r}function Qs(s,e,t=!1){const r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((a,o,c)=>s.is0(o)?a:(r[c]=a,s.mul(a,o)),s.ONE),i=s.inv(n);return e.reduceRight((a,o,c)=>s.is0(o)?a:(r[c]=s.mul(a,r[c]),s.mul(a,o)),i),r}function en(s,e){const t=(s.ORDER-Q)/ve,r=s.pow(e,t),n=s.eql(r,s.ONE),i=s.eql(r,s.ZERO),a=s.eql(r,s.neg(s.ONE));if(!n&&!i&&!a)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Xo(s,e){e!==void 0&&me(e);const t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}class jo{constructor(e,t={}){T(this,"ORDER");T(this,"BITS");T(this,"BYTES");T(this,"isLE");T(this,"ZERO",se);T(this,"ONE",Q);T(this,"_lengths");T(this,"_sqrt");T(this,"_mod");var a;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=(a=t.allowedLengths)==null?void 0:a.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));const{nBitLength:n,nByteLength:i}=Xo(e,r);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 de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return de(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return de(e*e,this.ORDER)}add(e,t){return de(e+t,this.ORDER)}sub(e,t){return de(e-t,this.ORDER)}mul(e,t){return de(e*t,this.ORDER)}pow(e,t){return zo(this,e,t)}div(e,t){return de(e*Xs(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Xs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Jo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Gs(e,this.BYTES):lr(e,this.BYTES)}fromBytes(e,t=!1){$(e);const{_lengths:r,BYTES:n,isLE:i,ORDER:a,_mod:o}=this;if(r){if(!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Hs(e):Ot(e);if(o&&(c=de(c,a)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Qs(this,e)}cmov(e,t,r){return r?t:e}}function Pt(s,e={}){return new jo(s,e)}function tn(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function rn(s){const e=tn(s);return e+Math.ceil(e/2)}function Zo(s,e,t=!1){$(s);const r=s.length,n=tn(e),i=rn(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=t?Hs(s):Ot(s),o=de(a,e-Q)+Q;return t?Gs(o,n):lr(o,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),Ce=BigInt(1);function bt(s,e){const t=e.negate();return s?t:e}function sn(s,e){const t=Qs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function nn(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function fr(s,e){nn(s,e);const t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=dr(s),a=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:a}}function an(s,e,t){const{windowSize:r,mask:n,maxNumber:i,shiftBy:a}=t;let o=Number(s&n),c=s>>a;o>r&&(o-=i,c+=Ce);const u=e*r,f=u+Math.abs(o)-1,g=o===0,S=o<0,E=e%2!==0;return{nextN:c,offset:f,isZero:g,isNeg:S,isNegF:E,offsetF:u}}const gr=new WeakMap,on=new WeakMap;function _r(s){return on.get(s)||1}function cn(s){if(s!==qe)throw new Error("invalid wNAF")}class Qo{constructor(e,t){T(this,"BASE");T(this,"ZERO");T(this,"Fn");T(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>qe;)t&Ce&&(r=r.add(n)),n=n.double(),t>>=Ce;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=fr(t,this.bits),i=[];let a=e,o=a;for(let c=0;c<r;c++){o=a,i.push(o);for(let u=1;u<n;u++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const a=fr(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:g,isNegF:S,offsetF:E}=an(r,o,a);r=c,f?i=i.add(bt(S,t[E])):n=n.add(bt(g,t[u]))}return cn(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=fr(e,this.bits);for(let a=0;a<i.windows&&r!==qe;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=an(r,a,i);if(r=o,!u){const g=t[c];n=n.add(f?g.negate():g)}}return cn(r),n}getPrecomputes(e,t,r){let n=gr.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),gr.set(t,n))),n}cached(e,t,r){const n=_r(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=_r(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){nn(t,this.bits),on.set(e,t),gr.delete(e)}hasCache(e){return _r(e)!==1}}function ec(s,e,t,r){let n=e,i=s.ZERO,a=s.ZERO;for(;t>qe||r>qe;)t&Ce&&(i=i.add(n)),r&Ce&&(a=a.add(n)),n=n.double(),t>>=Ce,r>>=Ce;return{p1:i,p2:a}}function ln(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yo(e),e}else return Pt(s,{isLE:t})}function tc(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ln(e.p,t.Fp,r),i=ln(e.n,t.Fn,r),o=["Gx","Gy","a","b"];for(const c of o)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 rc(s,e){return function(r){const n=s(r);return{secretKey:n,publicKey:e(n)}}}class dn{constructor(e,t){T(this,"oHash");T(this,"iHash");T(this,"blockLen");T(this,"outputLen");T(this,"finished",!1);T(this,"destroyed",!1);if(Cs(e),$(t,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 r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);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),Je(n)}update(e){return Ve(this),this.iHash.update(e),this}digestInto(e){Ve(this),$(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:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hn=(s,e,t)=>new dn(s,e).update(t).digest();hn.create=(s,e)=>new dn(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=(s,e)=>(s+(s>=0?e:-e)/fn)/e;function sc(s,e,t){const[[r,n],[i,a]]=e,o=un(a*s,t),c=un(-n*s,t);let u=s-o*r-c*i,f=-o*n-c*a;const g=u<Ae,S=f<Ae;g&&(u=-u),S&&(f=-f);const E=dr(Math.ceil(Fo(t)/2))+Ye;if(u<Ae||u>=E||f<Ae||f>=E)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:g,k1:u,k2neg:S,k2:f}}function pr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function wr(s,e){const t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Tt(t.lowS,"lowS"),Tt(t.prehash,"prehash"),t.format!==void 0&&pr(t.format),t}class nc extends Error{constructor(e=""){super(e)}}const be={Err:nc,_tlv:{encode:(s,e)=>{const{Err:t}=be;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,n=Rt(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");const i=r>127?Rt(n.length/2|128):"";return Rt(s)+i+n+e},decode(s,e){const{Err:t}=be;let r=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");const n=e[r++],i=!!(n&128);let a=0;if(!i)a=n;else{const c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const f of u)a=a<<8|f;if(r+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}const o=e.subarray(r,r+a);if(o.length!==a)throw new t("tlv.decode: wrong value length");return{v:o,l:e.subarray(r+a)}}},_int:{encode(s){const{Err:e}=be;if(s<Ae)throw new e("integer: negative integers are not allowed");let t=Rt(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){const{Err:e}=be;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ot(s)}},toSig(s){const{Err:e,_int:t,_tlv:r}=be,n=$(s,void 0,"signature"),{v:i,l:a}=r.decode(48,n);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=r.decode(2,i),{v:u,l:f}=r.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(o),s:t.decode(u)}},hexFromSig(s){const{_tlv:e,_int:t}=be,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Ae=BigInt(0),Ye=BigInt(1),fn=BigInt(2),xt=BigInt(3),ic=BigInt(4);function ac(s,e={}){const t=tc("weierstrass",s,e),{Fp:r,Fn:n}=t;let i=t.CURVE;const{h:a,n:o}=i;hr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=_n(r,n);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(k,_,p){const{x:I,y:R}=_.toAffine(),b=r.toBytes(I);if(Tt(p,"isCompressed"),p){f();const N=!r.isOdd(R);return Oe(gn(N),b)}else return Oe(Uint8Array.of(4),b,r.toBytes(R))}function S(k){$(k,void 0,"Point");const{publicKey:_,publicKeyUncompressed:p}=u,I=k.length,R=k[0],b=k.subarray(1);if(I===_&&(R===2||R===3)){const N=r.fromBytes(b);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const x=y(N);let O;try{O=r.sqrt(x)}catch(Y){const G=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();const C=r.isOdd(O);return(R&1)===1!==C&&(O=r.neg(O)),{x:N,y:O}}else if(I===p&&R===4){const N=r.BYTES,x=r.fromBytes(b.subarray(0,N)),O=r.fromBytes(b.subarray(N,N*2));if(!w(x,O))throw new Error("bad point: is not on curve");return{x,y:O}}else throw new Error(`bad point: got length ${I}, expected compressed=${_} or uncompressed=${p}`)}const E=e.toBytes||g,m=e.fromBytes||S;function y(k){const _=r.sqr(k),p=r.mul(_,k);return r.add(r.add(p,r.mul(k,i.a)),i.b)}function w(k,_){const p=r.sqr(_),I=y(k);return r.eql(p,I)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(i.a,xt),ic),P=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(A,P)))throw new Error("bad curve params: a or b");function F(k,_,p=!1){if(!r.isValid(_)||p&&r.is0(_))throw new Error(`bad point coordinate ${k}`);return _}function M(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function V(k){if(!c||!c.basises)throw new Error("no endo");return sc(k,c.basises,n.ORDER)}const U=$s((k,_)=>{const{X:p,Y:I,Z:R}=k;if(r.eql(R,r.ONE))return{x:p,y:I};const b=k.is0();_==null&&(_=b?r.ONE:r.inv(R));const N=r.mul(p,_),x=r.mul(I,_),O=r.mul(R,_);if(b)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:N,y:x}}),H=$s(k=>{if(k.is0()){if(e.allowInfinityPoint&&!r.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:p}=k.toAffine();if(!r.isValid(_)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!w(_,p))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(k,_,p,I,R){return p=new v(r.mul(p.X,k),p.Y,p.Z),_=bt(I,_),p=bt(R,p),_.add(p)}const K=class K{constructor(_,p,I){T(this,"X");T(this,"Y");T(this,"Z");this.X=F("x",_),this.Y=F("y",p,!0),this.Z=F("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){const{x:p,y:I}=_||{};if(!_||!r.isValid(p)||!r.isValid(I))throw new Error("invalid affine point");if(_ instanceof K)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(I)?K.ZERO:new K(p,I,r.ONE)}static fromBytes(_){const p=K.fromAffine(m($(_,void 0,"point")));return p.assertValidity(),p}static fromHex(_){return K.fromBytes(At(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,p=!0){return B.createCache(this,_),p||this.multiply(xt),this}assertValidity(){H(this)}hasEvenY(){const{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_,O=r.eql(r.mul(p,x),r.mul(b,R)),C=r.eql(r.mul(I,x),r.mul(N,R));return O&&C}negate(){return new K(this.X,r.neg(this.Y),this.Z)}double(){const{a:_,b:p}=i,I=r.mul(p,xt),{X:R,Y:b,Z:N}=this;let x=r.ZERO,O=r.ZERO,C=r.ZERO,L=r.mul(R,R),Y=r.mul(b,b),G=r.mul(N,N),D=r.mul(R,b);return D=r.add(D,D),C=r.mul(R,N),C=r.add(C,C),x=r.mul(_,C),O=r.mul(I,G),O=r.add(x,O),x=r.sub(Y,O),O=r.add(Y,O),O=r.mul(x,O),x=r.mul(D,x),C=r.mul(I,C),G=r.mul(_,G),D=r.sub(L,G),D=r.mul(_,D),D=r.add(D,C),C=r.add(L,L),L=r.add(C,L),L=r.add(L,G),L=r.mul(L,D),O=r.add(O,L),G=r.mul(b,N),G=r.add(G,G),L=r.mul(G,D),x=r.sub(x,L),C=r.mul(G,Y),C=r.add(C,C),C=r.add(C,C),new K(x,O,C)}add(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_;let O=r.ZERO,C=r.ZERO,L=r.ZERO;const Y=i.a,G=r.mul(i.b,xt);let D=r.mul(p,b),X=r.mul(I,N),te=r.mul(R,x),ne=r.add(p,I),J=r.add(b,N);ne=r.mul(ne,J),J=r.add(D,X),ne=r.sub(ne,J),J=r.add(p,R);let re=r.add(b,x);return J=r.mul(J,re),re=r.add(D,te),J=r.sub(J,re),re=r.add(I,R),O=r.add(N,x),re=r.mul(re,O),O=r.add(X,te),re=r.sub(re,O),L=r.mul(Y,J),O=r.mul(G,te),L=r.add(O,L),O=r.sub(X,L),L=r.add(X,L),C=r.mul(O,L),X=r.add(D,D),X=r.add(X,D),te=r.mul(Y,te),J=r.mul(G,J),X=r.add(X,te),te=r.sub(D,te),te=r.mul(Y,te),J=r.add(J,te),D=r.mul(X,J),C=r.add(C,D),D=r.mul(re,J),O=r.mul(ne,O),O=r.sub(O,D),D=r.mul(ne,X),L=r.mul(re,L),L=r.add(L,D),new K(O,C,L)}subtract(_){return this.add(_.negate())}is0(){return this.equals(K.ZERO)}multiply(_){const{endo:p}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let I,R;const b=N=>B.cached(this,N,x=>sn(K,x));if(p){const{k1neg:N,k1:x,k2neg:O,k2:C}=V(_),{p:L,f:Y}=b(x),{p:G,f:D}=b(C);R=Y.add(D),I=Z(p.beta,L,G,N,O)}else{const{p:N,f:x}=b(_);I=N,R=x}return sn(K,[I,R])[0]}multiplyUnsafe(_){const{endo:p}=e,I=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ae||I.is0())return K.ZERO;if(_===Ye)return I;if(B.hasCache(this))return this.multiply(_);if(p){const{k1neg:R,k1:b,k2neg:N,k2:x}=V(_),{p1:O,p2:C}=ec(K,I,b,x);return Z(p.beta,O,C,R,N)}else return B.unsafe(I,_)}toAffine(_){return U(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return a===Ye?!0:_?_(K,this):B.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:_}=e;return a===Ye?this:_?_(K,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(_=!0){return Tt(_,"isCompressed"),this.assertValidity(),E(K,this,_)}toHex(_=!0){return tt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};T(K,"BASE",new K(i.Gx,i.Gy,r.ONE)),T(K,"ZERO",new K(r.ZERO,r.ONE,r.ZERO)),T(K,"Fp",r),T(K,"Fn",n);let v=K;const ee=n.BITS,B=new Qo(v,e.endo?Math.ceil(ee/2):ee);return v.BASE.precompute(8),v}function gn(s){return Uint8Array.of(s?2:3)}function _n(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function oc(s,e={}){const{Fn:t}=s,r=e.randomBytes||Bs,n=Object.assign(_n(s.Fp,t),{seed:rn(t.ORDER)});function i(E){try{const m=t.fromBytes(E);return t.isValidNot0(m)}catch{return!1}}function a(E,m){const{publicKey:y,publicKeyUncompressed:w}=n;try{const A=E.length;return m===!0&&A!==y||m===!1&&A!==w?!1:!!s.fromBytes(E)}catch{return!1}}function o(E=r(n.seed)){return Zo($(E,n.seed,"seed"),t.ORDER)}function c(E,m=!0){return s.BASE.multiply(t.fromBytes(E)).toBytes(m)}function u(E){const{secretKey:m,publicKey:y,publicKeyUncompressed:w}=n;if(!ir(E)||"_lengths"in t&&t._lengths||m===y)return;const A=$(E,void 0,"key").length;return A===y||A===w}function f(E,m,y=!0){if(u(E)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");const w=t.fromBytes(E);return s.fromBytes(m).multiply(w).toBytes(y)}const g={isValidSecretKey:i,isValidPublicKey:a,randomSecretKey:o},S=rc(o,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:S,Point:s,utils:g,lengths:n})}function cc(s,e,t={}){Cs(e),hr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);const r=t.randomBytes||Bs,n=t.hmac||((_,p)=>hn(e,_,p)),{Fp:i,Fn:a}=s,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E}=oc(s,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},y=o*fn<i.ORDER;function w(_){const p=o>>Ye;return _>p}function A(_,p){if(!a.isValidNot0(p))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return p}function P(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(_,p){pr(p);const I=E.signature,R=p==="compact"?I:p==="recovered"?I+1:void 0;return $(_,R)}class M{constructor(p,I,R){T(this,"r");T(this,"s");T(this,"recovery");if(this.r=A("r",p),this.s=A("s",I),R!=null){if(P(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(p,I=m.format){F(p,I);let R;if(I==="der"){const{r:O,s:C}=be.toSig($(p));return new M(O,C)}I==="recovered"&&(R=p[0],I="compact",p=p.subarray(1));const b=E.signature/2,N=p.subarray(0,b),x=p.subarray(b,b*2);return new M(a.fromBytes(N),a.fromBytes(x),R)}static fromHex(p,I){return this.fromBytes(At(p),I)}assertRecovery(){const{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new M(this.r,this.s,p)}recoverPublicKey(p){const{r:I,s:R}=this,b=this.assertRecovery(),N=b===2||b===3?I+o:I;if(!i.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const x=i.toBytes(N),O=s.fromBytes(Oe(gn((b&1)===0),x)),C=a.inv(N),L=U($(p,void 0,"msgHash")),Y=a.create(-L*C),G=a.create(R*C),D=s.BASE.multiplyUnsafe(Y).add(O.multiplyUnsafe(G));if(D.is0())throw new Error("invalid recovery: point at infinify");return D.assertValidity(),D}hasHighS(){return w(this.s)}toBytes(p=m.format){if(pr(p),p==="der")return At(be.hexFromSig(this));const{r:I,s:R}=this,b=a.toBytes(I),N=a.toBytes(R);return p==="recovered"?(P(),Oe(Uint8Array.of(this.assertRecovery()),b,N)):Oe(b,N)}toHex(p){return tt(this.toBytes(p))}}const V=t.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const I=Ot(p),R=p.length*8-c;return R>0?I>>BigInt(R):I},U=t.bits2int_modN||function(p){return a.create(V(p))},H=dr(c);function Z(_){return Mo("num < 2^"+c,_,Ae,H),a.toBytes(_)}function v(_,p){return $(_,void 0,"message"),p?$(e(_),void 0,"prehashed message"):_}function ee(_,p,I){const{lowS:R,prehash:b,extraEntropy:N}=wr(I,m);_=v(_,b);const x=U(_),O=a.fromBytes(p);if(!a.isValidNot0(O))throw new Error("invalid private key");const C=[Z(O),Z(x)];if(N!=null&&N!==!1){const D=N===!0?r(E.secretKey):N;C.push($(D,void 0,"extraEntropy"))}const L=Oe(...C),Y=x;function G(D){const X=V(D);if(!a.isValidNot0(X))return;const te=a.inv(X),ne=s.BASE.multiply(X).toAffine(),J=a.create(ne.x);if(J===Ae)return;const re=a.create(te*a.create(Y+J*O));if(re===Ae)return;let vn=(ne.x===J?0:2)|Number(ne.y&Ye),Cn=re;return R&&w(re)&&(Cn=a.neg(re),vn^=1),new M(J,Cn,y?void 0:vn)}return{seed:L,k2sig:G}}function B(_,p,I={}){const{seed:R,k2sig:b}=ee(_,p,I);return Ko(e.outputLen,a.BYTES,n)(R,b).toBytes(I.format)}function K(_,p,I,R={}){const{lowS:b,prehash:N,format:x}=wr(R,m);if(I=$(I,void 0,"publicKey"),p=v(p,N),!ir(_)){const O=_ instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}F(_,x);try{const O=M.fromBytes(_,x),C=s.fromBytes(I);if(b&&O.hasHighS())return!1;const{r:L,s:Y}=O,G=U(p),D=a.inv(Y),X=a.create(G*D),te=a.create(L*D),ne=s.BASE.multiplyUnsafe(X).add(C.multiplyUnsafe(te));return ne.is0()?!1:a.create(ne.x)===L}catch{return!1}}function k(_,p,I={}){const{prehash:R}=wr(I,m);return p=v(p,R),M.fromBytes(_,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E,Point:s,sign:B,verify:K,recoverPublicKey:k,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},lc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},pn=BigInt(2);function dc(s){const e=Sr.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=s*s*s%e,f=u*u*s%e,g=ae(f,t,e)*f%e,S=ae(g,t,e)*f%e,E=ae(S,pn,e)*u%e,m=ae(E,n,e)*E%e,y=ae(m,i,e)*m%e,w=ae(y,o,e)*y%e,A=ae(w,c,e)*w%e,P=ae(A,o,e)*y%e,F=ae(P,t,e)*f%e,M=ae(F,a,e)*m%e,V=ae(M,r,e)*u%e,U=ae(V,pn,e);if(!Er.eql(Er.sqr(U),s))throw new Error("Cannot find square root");return U}const Er=Pt(Sr.p,{sqrt:dc}),hc=cc(ac(Sr,{Fp:Er,endo:lc}),Uo),uc=BigInt(0),rt=BigInt(1),fc=BigInt(2),gc=BigInt(7),_c=BigInt(256),pc=BigInt(113),wn=[],Sn=[],En=[];for(let s=0,e=rt,t=1,r=0;s<24;s++){[t,r]=[r,(2*t+3*r)%5],wn.push(2*(5*r+t)),Sn.push((s+1)*(s+2)/2%64);let n=uc;for(let i=0;i<7;i++)e=(e<<rt^(e>>gc)*pc)%_c,e&fc&&(n^=rt<<(rt<<BigInt(i))-rt);En.push(n)}const mn=Po(En,!0),wc=mn[0],Sc=mn[1],yn=(s,e,t)=>t>32?vo(s,e,t):bo(s,e,t),An=(s,e,t)=>t>32?Co(s,e,t):xo(s,e,t);function Ec(s,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let a=0;a<10;a++)t[a]=s[a]^s[a+10]^s[a+20]^s[a+30]^s[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=t[c],f=t[c+1],g=yn(u,f,1)^t[o],S=An(u,f,1)^t[o+1];for(let E=0;E<50;E+=10)s[a+E]^=g,s[a+E+1]^=S}let n=s[2],i=s[3];for(let a=0;a<24;a++){const o=Sn[a],c=yn(n,i,o),u=An(n,i,o),f=wn[a];n=s[f],i=s[f+1],s[f]=c,s[f+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=s[a+o];for(let o=0;o<10;o++)s[a+o]^=~t[(o+2)%10]&t[(o+4)%10]}s[0]^=wc[r],s[1]^=Sc[r]}Je(t)}class mr{constructor(e,t,r,n=!1,i=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,me(r,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=So(this.state)}clone(){return this._cloneInto()}keccak(){ks(this.state32),Ec(this.state32,this.rounds),ks(this.state32),this.posOut=0,this.pos=0}update(e){Ve(this),$(e);const{blockLen:t,state:r}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(t-this.pos,n-i);for(let o=0;o<a;o++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,(t&128)!==0&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ve(this,!1),$(e),this.finish();const t=this.state,{blockLen:r}=this;for(let n=0,i=e.length;n<i;){this.posOut>=r&&this.keccak();const a=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+a),n),this.posOut+=a,n+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return me(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ds(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,Je(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:a}=this;return e||(e=new mr(t,r,n,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=a,e.destroyed=this.destroyed,e}}const In=((s,e,t,r={})=>Ws(()=>new mr(e,s,t),r))(1,136,32),mc=60;class yc{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=_o(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(t){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",t)}}async verifyJWT(e,t){try{const r=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:r.sub,exp:r.exp,iat:r.iat});const n=Math.floor(Date.now()/1e3);if(r.exp&&r.exp+mc<n)return d.warn("[CROSSx] 토큰 만료:",{exp:r.exp,now:n,만료시간:new Date(r.exp*1e3).toISOString()}),{payload:r,valid:!1,signatureVerified:!1};if(!r.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:r,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await io(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:r,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:r,valid:!0,signatureVerified:!1}}catch(r){throw d.error("[CROSSx] JWT 검증 중 에러:",r),r}}decodeJWT(e){return wo(e)}recoverPersonalSignSigner(e,t){const r=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
For security, you must continue with the same account.`,update_required_title:"Update required",update_required_message:"This service is using a wallet version that is no longer supported, so you cannot sign in or send transactions right now. Please try again after the service is updated.",update_required_confirm_button:"OK",session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Qn={ko:kr,en:Wt};function we(s="en",e){return Qn[s]??Wt}function ei(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Lr="crossx_access_token",Ur="crossx_refresh_token",Wr="crossx_user_info",vt=class vt{constructor(e,t,r,n,i,a,o,c,u=()=>{}){this.config=e,this.storage=t,this.crypto=r,this.oauth=n,this.transport=i,this.walletProvider=a,this.tokenStore=o,this.requestFreshTokenFromBridge=c,this.getLocale=u,this._refreshPromise=null,this._migrated=!1;const f=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${f}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${f}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${f}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${f}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const t=this.crypto.decodeJWT(e);return t!=null&&t.exp?t.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const r=t;if(r.code&&r.code!==200&&r.code>0)return{code:r.code,message:r.message??""}}return null}checkResponseError(e,t){const r=this.extractResponseErrorCode(e);if(r)throw new h(l.AUTH_FAILED,`${t} 실패 (코드 ${r.code}): ${r.message}`)}async execute(e){let t,r;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:a,legacyOauthServiceUrl:o}=this.config,c=ei(this.getLocale()),u=E=>{const m=`${E}${i}`,y=m.includes("?")?"&":"?";return`${m}${y}locale=${c}`},f=u(a),g=o?u(o):void 0;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${f}`);const S=await this.oauth.openAuth({authUrl:f,...g?{legacyAuthUrl:g}:{},expectedOrigin:new URL(a).origin});t=S.token,r=S.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",t.length,")"),r&&d.log("[CROSSx] OAuth 콜백 email:",r)}catch(n){if(d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof h)throw n;const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new h(l.OAUTH_POPUP_BLOCKED,i):new h(l.AUTH_FAILED,i)}return this.processFirebaseToken(t,r)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var r,n,i;let t;try{const{authApiUrl:a}=this.config,{accessToken:o}=await this.exchangeNativeFirebaseToken(e.idToken,a);let c,u;try{const f=this.crypto.decodeJWT(e.idToken);u=e.provider??((r=f.firebase)==null?void 0:r.sign_in_provider);const g=((n=f.firebase)==null?void 0:n.identities)??{};c=f.email??((i=g.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",u,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(o){const f=await this.crypto.verifyJWT(o);if(!f.valid)throw new h(l.AUTH_FAILED,"Access token 검증 실패");const g=f.payload;t={id:g.sub,email:g.email??c,signInProvider:u,providerSub:e.providerSub},this.tokenStore.set(o),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,o),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,t)}else throw new h(l.AUTH_FAILED,"Access token 교환 실패")}catch(a){const o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0,u=a instanceof Error?a.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",u,"message:",o,"stack:",c),{success:!1,error:o||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,!1)}async processFirebaseToken(e,t){var i,a,o,c,u;let r,n=!1;try{const{authApiUrl:f}=this.config,{accessToken:g,refreshToken:S}=await this.exchangeFirebaseToken(e,f);let E,m,y;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),m=(i=A.firebase)==null?void 0:i.sign_in_provider;const P=((a=A.firebase)==null?void 0:a.identities)??{};y=A.email??((o=P.email)==null?void 0:o[0]),m==="google.com"?E=(c=P["google.com"])==null?void 0:c[0]:m==="apple.com"&&(E=(u=P["apple.com"])==null?void 0:u[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",m,"hasProviderSub:",!!E,"email:",y??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(g){const A=this.crypto.decodeJWT(g);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const P=await this.crypto.verifyJWT(g);if(n=P.signatureVerified??!1,!P.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const F=P.payload,M=F.email??y??t;d.log("[CROSSx] email 소스 — CROSSx JWT:",F.email??"(없음)","/ Firebase JWT:",y??"(없음)","/ OAuth 콜백:",t??"(없음)","→",M??"(없음)"),r={id:F.sub,email:M,signInProvider:m,providerSub:E},this.tokenStore.set(g),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,g),S&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,S):S&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);r={id:A.sub,email:A.email??t,signInProvider:m,providerSub:E},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)");const w=this.useCookieAuth?{id:r.id,email:r.email,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,w),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(f){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",f),{success:!1,error:f instanceof Error?f.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,n)}async exchangeNativeFirebaseToken(e,t){const r=`${t}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",r,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:r,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(o){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",r,"error:",o);const c=o instanceof Error?o.message:String(o);throw new h(l.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,o)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const a=this.extractAccessToken(i);if(!a)throw new h(l.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:a}}async exchangeFirebaseToken(e,t){const r=this.useCookieAuth,n=r?`${t}/cross-auth/social/login/cookie`:`${t}/cross-auth/social/login`;d.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"},...r?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Token exchange");const o=this.extractAccessToken(a);if(r&&!o)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!o)throw new h(l.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return r||(c=this.extractRefreshToken(a)),{accessToken:o,refreshToken:c}}extractAccessToken(e){const t=(e==null?void 0:e.data)??e;if(this.isJwtString(t))return t;if(typeof t=="object"&&t!==null){const r=t;if(this.isJwtString(r.data))return r.data;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.access_token??i.token;if(typeof a=="string")return a}const n=r.access_token??r.token;if(typeof n=="string")return n}}extractRefreshToken(e){const t=(e==null?void 0:e.data)??e;if(typeof t!="object"||t===null)return;const r=t;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.refresh_token??i.refresh;if(typeof a=="string")return a}const n=r.refresh_token??r.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 r=await this.crypto.verifyJWT(e);if(r.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,r.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const r=await this.silentRefresh();r&&this.tokenStore.set(r)}else{const r=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",r?"있음":"없음","refresh_token:",n?"있음":"없음"),n){r&&this.tokenStore.set(r);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!r)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(r)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(r)}}const t=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",t?`있음 (id: ${t.id})`:"없음"),!t)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",t.id);try{return await this.loadWallet(t,!1)}catch(r){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",r),{success:!0,user:t,tokenSignatureVerified:!1}}}catch(e){const t=e instanceof h&&e.code===l.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",t?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),t&&(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:t}=this.config,r=this.useCookieAuth,n=`${t}/cross-auth/social/refresh/simple`,i={};if(!r){const f=this.tokenStore.get()??"";f&&(i.access_token=f),e&&(i.refresh_token=e)}const a=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...r?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",a.status);const o=a.data,c=this.extractResponseErrorCode(o);if(c){const f=vt.REFRESH_RELOGIN_CODES.has(c.code);throw new h(f?l.SESSION_EXPIRED:l.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const u=this.extractAccessToken(o);if(r&&!u){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!u)throw new h(l.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(u),!r){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,u);const f=this.extractRefreshToken(o);f&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,f)}return d.log("[CROSSx] silentRefresh 성공"),u}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const r=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(r.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(r){throw r instanceof h&&r.code===l.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),r}}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):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof h&&e.code===l.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,t){let r,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!t)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const o=await this.silentRefresh(t);if(!o)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=o,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const a=i.payload;d.log("[CROSSx] signInWithJWT — sub:",a.sub,"signatureVerified:",n),r={id:a.sub,email:a.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),t&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,t),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,r),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(r,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Wr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const r=await this.storage.get(Lr);r&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,r);const n=await this.storage.get(Ur);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Wr),await this.storage.remove(Lr),await this.storage.remove(Ur),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,t){let r,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const a=await this.walletProvider.getAddresses(e.id);a.length>0?(r=a[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",r)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(a){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",a)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),r=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",r)}catch(i){if(i instanceof h&&i.code===l.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof h&&(i.code===l.PROJECT_NOT_REGISTERED||i.code===l.PROJECT_ID_MISSING||i.code===l.ORIGIN_NOT_ALLOWED||i.code===l.SDK_VERSION_UNSUPPORTED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",r,"needsMigration:",n),{success:!0,address:r,user:e,needsMigration:n,tokenSignatureVerified:t}}};vt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Bt=vt;class ti{constructor(e,t,r,n=[]){this.config=e,this.storage=t,this.tokenStore=r,this.preservedKeys=n;const i=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${i}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${i}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${i}_user_info`}async hasStoredSession(){const e=[this.STORAGE_KEY_ACCESS_TOKEN,this.STORAGE_KEY_REFRESH_TOKEN,this.STORAGE_KEY_USER];for(const t of e){const r=await this.storage.get(t).catch(()=>null);if(r!=null)return!0}return!1}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);const e=[];for(const t of this.preservedKeys){const r=await this.storage.get(t).catch(()=>null);r!=null&&e.push([t,r])}await this.storage.clear();for(const[t,r]of e)await this.storage.set(t,r).catch(()=>{})}}class ri{constructor(e,t){this.storage=e,this.walletProvider=t}async execute(e,t){if(!this.walletProvider.migrateWallet)throw new h(l.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",t);const r=await this.walletProvider.migrateWallet(e,t);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",r.address),{address:r.address}}}class Mt{constructor(){this.encryptedBytes=null,this.xorKey=null,this.setAt=null}set(e){this.clear();const t=new TextEncoder().encode(e),r=new Uint8Array(t.length);crypto.getRandomValues(r);const n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t[i]^r[i];t.fill(0),this.xorKey=r,this.encryptedBytes=n,this.setAt=Date.now()}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let r=0;r<this.encryptedBytes.length;r++)e[r]=this.encryptedBytes[r]^this.xorKey[r];const t=new TextDecoder().decode(e);return e.fill(0),t}clear(){var e,t;(e=this.encryptedBytes)==null||e.fill(0),(t=this.xorKey)==null||t.fill(0),this.encryptedBytes=null,this.xorKey=null,this.setAt=null}getSetAt(){return this.setAt}has(){return this.encryptedBytes!==null}}const si="/authorize/result",ni="one-oauth:authorization_response",Br="one-oauth:authorization_error",ii="one-oauth:authorization_ack",ai="openid profile offline_access";function Ft(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mr(s=32){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}async function Fr(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Ft(new Uint8Array(e))}function dt(s=16){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}const oi=300*1e3,ci=600*1e3,Kt="crossx.oneid.pending",li=1e3,di=10;function Kr(s){switch(s){case"access_denied":return l.USER_REJECTED;case"required_items_not_agreed":return l.ONEID_TERMS_NOT_AGREED;case"account_not_found":return l.ONEID_ACCOUNT_NOT_FOUND;case"service_not_linked":return l.ONEID_SERVICE_NOT_LINKED;default:return l.ONEID_AUTHORIZATION_FAILED}}function hi(s){switch(s){case"session_evicted":return l.ONEID_SESSION_EVICTED;case"session_revoked":return l.ONEID_SESSION_REVOKED;case"session_expired":return l.ONEID_SESSION_EXPIRED;default:return l.ONEID_SESSION_INVALID}}function Ht(s){if(!(typeof s!="string"||!s.startsWith("/"))&&!(s.startsWith("//")||s.startsWith("/\\")))return s}function We(s){let e;try{e=new URL(s)}catch{throw new h(l.INVALID_CONFIG,"ONE ID issuer가 올바른 URL이 아닙니다")}return e.toString().replace(/\/+$/,"")}function Hr(s){const e=s.split(".")[1];if(!e)return null;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=new TextDecoder().decode(Uint8Array.from(atob(r),a=>a.charCodeAt(0))),i=JSON.parse(n);return typeof i=="object"&&i!==null?i:null}catch{return null}}function ui(s){if(typeof s!="object"||s===null)return!1;const e=s.type;return e===ni||e===Br}function Gr(s,e){if(typeof s.access_token!="string"||s.access_token==="")throw new h(l.ONEID_AUTHORIZATION_FAILED,"토큰 응답에 access_token이 없습니다");const t=typeof s.expires_in=="number"?s.expires_in:0;return{accessToken:s.access_token,tokenType:typeof s.token_type=="string"?s.token_type:"Bearer",expiresAt:e+t*1e3,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:void 0,idToken:typeof s.id_token=="string"?s.id_token:void 0,scope:typeof s.scope=="string"?s.scope:void 0}}class fi{constructor(){this.reason=null,this.onAbort=null}abort(e){var t;this.reason??(this.reason=e),(t=this.onAbort)==null||t.call(this,e)}throwIfAborted(){if(this.reason!==null)throw new h(l.USER_REJECTED,this.reason)}}class gi{constructor(e={}){this.abortPending=null,this.popupSeq=0,this.options=e}get fetchImpl(){return this.options.fetch??((e,t)=>fetch(e,t))}now(){var e,t;return((t=(e=this.options).now)==null?void 0:t.call(e))??Date.now()}get pendingStorage(){return this.options.pendingStorage??window.sessionStorage}cancelPending(e="ONE ID 로그인 대기를 중단했습니다"){var t;(t=this.abortPending)==null||t.call(this,e)}async authorize(e){let t=null;if(e.mode!=="redirect"&&(t=this.openBlankPopup(e.width,e.height),!t&&e.mode==="popup"))throw new h(l.OAUTH_POPUP_BLOCKED,"팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요.");try{const r=We(e.issuer);if(!e.clientId)throw new h(l.INVALID_CONFIG,"ONE ID clientId가 비어 있습니다");this.cancelPending("새 ONE ID 로그인 요청으로 이전 대기를 중단했습니다");const n=new fi,i=a=>n.abort(a);this.abortPending=i;try{return t?await this.authorizeWithPopup(t,{...e,issuer:r},n):await this.authorizeWithRedirect({...e,issuer:r},n)}finally{this.abortPending===i&&(this.abortPending=null)}}catch(r){try{t==null||t.close()}catch{}throw r}}async completeRedirect(e,t){const r=We(e.issuer),n=this.takePending(),i=new URL(t).searchParams;if(!n||n.issuer!==r||n.clientId!==e.clientId)throw new h(l.ONEID_STATE_MISMATCH,"진행 중인 ONE ID 로그인이 없습니다. 다시 로그인해 주세요.");if(this.now()-n.createdAt>ci)throw new h(l.ONEID_TIMEOUT,"ONE ID 로그인 시간이 지났습니다");const a=i.get("state");if(!a||a!==n.state)throw new h(l.ONEID_STATE_MISMATCH,"ONE ID 로그인 결과의 state가 다릅니다");if(i.get("iss")!==r)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다");const o=i.get("error");if(o){const f=i.get("error_description")??void 0;throw new h(Kr(o),f||`ONE ID 인가 오류: ${o}`,{error:o,error_description:f})}const c=i.get("code");if(!c)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다");return{tokens:await this.exchangeCode({...e,issuer:r},c,n.codeVerifier,n.redirectUri,n.nonce),returnTo:Ht(n.returnTo)}}async refresh(e,t){const r=We(e.issuer),n=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:t});let i;try{i=await this.fetchImpl(`${r}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(c){throw new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",c)}const a=await Gt(i);if(!i.ok){if(i.status===400&&a.error==="invalid_grant"){const c=typeof a.error_reason=="string"?a.error_reason:void 0;throw new h(hi(c),"ONE ID 세션이 끝났습니다. 다시 로그인해 주세요.",{error:"invalid_grant",error_reason:c})}throw i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?new h(l.ONEID_SESSION_INVALID,"ONE ID 세션을 갱신할 수 없습니다. 다시 로그인해 주세요.",{status:i.status,error:a.error}):new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",{status:i.status,error:a.error})}const o=Gr(a,this.now());return{...o,refreshToken:o.refreshToken??t}}async logout(e,t){const r=We(e.issuer);let n;try{n=await this.fetchImpl(`${r}/logout`,{method:"POST",headers:{Authorization:`Bearer ${t}`}})}catch(i){throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청을 보내지 못했습니다",i)}if(!n.ok&&n.status!==401)throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청이 실패했습니다",{status:n.status})}openBlankPopup(e=500,t=700){const r=Math.max(e,500),n=Math.max(t,700),i=window.screenX+(window.outerWidth-r)/2,a=window.screenY+(window.outerHeight-n)/2;try{return this.popupSeq+=1,window.open("about:blank",`ONEidLogin${this.popupSeq}`,`width=${r},height=${n},left=${i},top=${a}`)}catch{return null}}async pushAuthorizationRequest(e,t,r,n,i){const a=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:t,scope:e.scope??ai,state:r,nonce:n,code_challenge:i,code_challenge_method:"S256"});let o;try{o=await this.fetchImpl(`${e.issuer}/par`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(u){throw new h(l.NETWORK_ERROR,"ONE ID 로그인 요청을 보내지 못했습니다",u)}const c=await Gt(o);if(!o.ok||typeof c.request_uri!="string")throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 요청이 거부되었습니다",{status:o.status,error:c.error});return c.request_uri}authorizeUrl(e,t){const r=new URL(`${e.issuer}/authorize`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("request_uri",t),r.toString()}async exchangeCode(e,t,r,n,i){const a=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t,redirect_uri:n,code_verifier:r});let o;try{o=await this.fetchImpl(`${e.issuer}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(f){throw new h(l.NETWORK_ERROR,"ONE ID 토큰을 받지 못했습니다",f)}const c=await Gt(o);if(!o.ok)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 토큰 교환이 거부되었습니다",{status:o.status,error:c.error});const u=Gr(c,this.now());if(u.idToken){const f=Hr(u.idToken);if(!f||f.iss!==e.issuer||f.nonce!==i)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID id_token의 발급자나 nonce가 요청과 다릅니다")}return u}async authorizeWithPopup(e,t,r){const n=new URL(t.issuer).origin,i=`${t.issuer}${si}`,a=dt(),o=dt(),c=Mr(),u=await Fr(c),f=await this.pushAuthorizationRequest(t,i,a,o,u);r.throwIfAborted(),d.log("[CROSSx] ONE ID 로그인 팝업 이동",{issuer:t.issuer,clientId:t.clientId}),e.location.href=this.authorizeUrl(t,f);const g=await new Promise((E,m)=>{let y=0,w=!0;const A=()=>{r.onAbort=null,clearTimeout(F),clearInterval(M),window.removeEventListener("message",V)},P=U=>{A(),m(U)},F=setTimeout(()=>{P(new h(l.ONEID_TIMEOUT,"ONE ID 로그인 응답 시간이 지났습니다"))},oi),M=setInterval(()=>{if(!w)return;y++;let U;try{U=e.closed}catch{w=!1;return}if(!U)return;const H=typeof document<"u"&&document.hasFocus();if(y<=di&&!H){d.warn("[CROSSx] ONE ID 팝업 closed 오탐 가능성(COOP) — 결과 대기 유지"),w=!1;return}P(new h(l.USER_REJECTED,"ONE ID 로그인이 취소되었습니다"))},li),V=U=>{if(U.origin!==n||U.source!==e||!ui(U.data))return;const H=U.data;if(H.state!==a){d.warn("[CROSSx] ONE ID 결과 state가 현재 요청과 달라 무시합니다");return}try{e.postMessage({type:ii,state:a},n)}catch{}if(H.iss!==t.issuer){P(new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다"));return}if(H.type===Br||H.error){const Z=H.error??"unknown_error";d.warn("[CROSSx] ONE ID 인가 오류:",Z),P(new h(Kr(Z),H.error_description||`ONE ID 인가 오류: ${Z}`,{error:Z,error_description:H.error_description}));return}if(!H.code){P(new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다"));return}A(),E(H.code)};r.onAbort=U=>{P(new h(l.USER_REJECTED,U))},window.addEventListener("message",V)}),S=await this.exchangeCode(t,g,c,i,o);return d.log("[CROSSx] ONE ID 로그인 완료 (팝업)"),{status:"completed",tokens:S,returnTo:Ht(t.returnTo)}}async authorizeWithRedirect(e,t){const r=e.redirectUri??`${window.location.origin}/auth/callback`;if(new URL(r).origin!==window.location.origin)throw new h(l.INVALID_CONFIG,"ONE ID redirectUri는 지금 페이지와 같은 origin이어야 합니다");const n=dt(),i=dt(),a=Mr(),o=await Fr(a),c=await this.pushAuthorizationRequest(e,r,n,i,o);t.throwIfAborted();const u={issuer:e.issuer,clientId:e.clientId,state:n,nonce:i,codeVerifier:a,redirectUri:r,returnTo:Ht(e.returnTo),createdAt:this.now()};this.pendingStorage.setItem(Kt,JSON.stringify(u)),d.log("[CROSSx] ONE ID 로그인 같은 창 이동",{issuer:e.issuer,clientId:e.clientId});const f=this.authorizeUrl(e,c);return(this.options.navigate??(g=>window.location.assign(g)))(f),{status:"redirecting"}}takePending(){const e=this.pendingStorage.getItem(Kt);if(this.pendingStorage.removeItem(Kt),!e)return null;try{const t=JSON.parse(e);return typeof(t==null?void 0:t.state)=="string"&&typeof t.codeVerifier=="string"?t:null}catch{return null}}}async function Gt(s){try{const e=await s.json();return typeof e=="object"&&e!==null?e:{}}catch{return{}}}const ht="crossx.oneid.session",$r=60*1e3,$t=new Set([l.ONEID_SESSION_EVICTED,l.ONEID_SESSION_REVOKED,l.ONEID_SESSION_EXPIRED,l.ONEID_SESSION_INVALID]);function Vr(s){return s instanceof h&&$t.has(s.code)}class _i{constructor(e,t,r,n=()=>Date.now()){this.port=e,this.config=t,this.storage=r,this.now=n,this.refreshing=null,this.generation=0}save(e){this.generation+=1;const t={issuer:We(this.config.issuer),clientId:this.config.clientId,tokens:e};return this.storage.setItem(ht,JSON.stringify(t)),Jr(t)}async get(){const e=await this.ensureFresh();return e?Jr(e):null}async getAccessToken(){const e=await this.ensureFresh();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID로 로그인하지 않았습니다");return e.tokens.accessToken}async signOut(){const e=this.read();if(this.clear(),!e)return;let t=e.tokens.accessToken;if(e.tokens.refreshToken&&e.tokens.expiresAt-$r<=this.now())try{t=(await this.port.refresh(this.config,e.tokens.refreshToken)).accessToken}catch(r){if(r instanceof h&&$t.has(r.code))return}await this.port.logout(this.config,t)}clear(){this.generation+=1,this.storage.removeItem(ht)}read(){var t;const e=this.storage.getItem(ht);if(!e)return null;try{const r=JSON.parse(e);return typeof((t=r==null?void 0:r.tokens)==null?void 0:t.accessToken)=="string"&&typeof r.tokens.expiresAt=="number"&&r.issuer===We(this.config.issuer)&&r.clientId===this.config.clientId?r:(this.clear(),null)}catch{return this.clear(),null}}async ensureFresh(){const e=this.read();if(!e)return null;if(e.tokens.expiresAt-$r>this.now())return e;if(!e.tokens.refreshToken){if(e.tokens.expiresAt>this.now())return e;throw this.clear(),new h(l.ONEID_SESSION_EXPIRED,"ONE ID 로그인이 만료되었습니다. 다시 로그인해 주세요.")}return this.refreshing??(this.refreshing=this.refresh(e).finally(()=>{this.refreshing=null})),this.refreshing}async refresh(e){const t=this.generation;try{const r=await this.port.refresh(this.config,e.tokens.refreshToken),n={...e,tokens:r};if(t!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID 세션이 바뀌었습니다");return this.storage.setItem(ht,JSON.stringify(n)),n}catch(r){if(t!==this.generation)throw r;if(r instanceof h&&$t.has(r.code))throw this.clear(),r;if(e.tokens.expiresAt>this.now())return e;throw r}}}function Jr(s){const e=s.tokens.idToken?Hr(s.tokens.idToken):null;return{subject:typeof(e==null?void 0:e.sub)=="string"?e.sub:"",clientId:s.clientId,issuer:s.issuer,scope:s.tokens.scope,expiresAt:s.tokens.expiresAt}}function pi(s){return s==="local"?window.localStorage:window.sessionStorage}const wi=new TextEncoder;function j(s){return wi.encode(s)}function Se(...s){const e=new Uint8Array(s.reduce((r,n)=>r+n.length,0));let t=0;for(const r of s)e.set(r,t),t+=r.length;return e}function Si(s){return new Uint8Array([s>>>24&255,s>>>16&255,s>>>8&255,s&255])}function oe(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e)}function Be(s){const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Vt(s){return oe(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ei(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return Be(e)}function mi(s){return globalThis.crypto.getRandomValues(new Uint8Array(s))}async function qr(s){return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",s))}const ie=globalThis.crypto.subtle,Jt={name:"ECDH",namedCurve:"P-256"},yi=32,Ai=12,Ii=32;function Xe(s){return new Uint8Array([s>>>8&255,s&255])}const je=Se(j("HPKE"),Xe(16),Xe(1),Xe(2)),Yr=Se(j("KEM"),Xe(16)),xe=new Uint8Array(0);async function zr(s,e){const t=s.length===0?new Uint8Array(32):s,r=await ie.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await ie.sign("HMAC",r,e))}async function Ti(s,e,t){const r=new Uint8Array(t);let n=xe;for(let i=1,a=0;a<t;i++)n=await zr(s,Se(n,e,new Uint8Array([i]))),r.set(n.subarray(0,Math.min(32,t-a)),a),a+=32;return r}function ut(s,e,t,r){return zr(s,Se(j("HPKE-v1"),r,j(e),t))}function qt(s,e,t,r,n){return Ti(s,Se(Xe(r),j("HPKE-v1"),n,j(e),t),r)}async function Xr(s,e){const t=await ie.importKey("raw",e,Jt,!1,[]);return new Uint8Array(await ie.deriveBits({name:"ECDH",public:t},s,256))}async function jr(s,e,t){const r=await ut(xe,"eae_prk",s,Yr);return qt(r,"shared_secret",Se(e,t),Ii,Yr)}async function Zr(s){const e=await ut(xe,"psk_id_hash",xe,je),t=await ut(xe,"info_hash",xe,je),r=Se(new Uint8Array([0]),e,t),n=await ut(s,"secret",xe,je),i=await qt(n,"key",r,yi,je),a=await qt(n,"base_nonce",r,Ai,je);return{key:i,baseNonce:a}}function ft(s,e){if(s.length!==65||s[0]!==4)throw new Error(`${e} must be SEC1 uncompressed P-256 (65B)`)}async function Qr(){const s=await ie.generateKey(Jt,!1,["deriveBits"]),e=new Uint8Array(await ie.exportKey("raw",s.publicKey));return{privateKey:s.privateKey,publicKey:e}}async function Ri(s,e,t){ft(s,"recipient public key");const r=await ie.generateKey(Jt,!0,["deriveBits"]),n=new Uint8Array(await ie.exportKey("raw",r.publicKey)),i=await jr(await Xr(r.privateKey,s),n,s),{key:a,baseNonce:o}=await Zr(i),c=await ie.importKey("raw",a,"AES-GCM",!1,["encrypt"]),u=new Uint8Array(await ie.encrypt({name:"AES-GCM",iv:o,additionalData:t},c,e));return{enc:n,ciphertext:u}}async function Oi(s,e,t,r){ft(e,"enc");const n=await jr(await Xr(s.privateKey,e),e,s.publicKey),{key:i,baseNonce:a}=await Zr(n),o=await ie.importKey("raw",i,"AES-GCM",!1,["decrypt"]);return new Uint8Array(await ie.decrypt({name:"AES-GCM",iv:a,additionalData:r},o,t))}const es=globalThis.crypto.subtle,Ni={name:"ECDSA",namedCurve:"P-256"},Pi="one-wallet/authz-sig/v1",bi="one-wallet/seal-aad/v1",xi=60,vi=32,Ci={generate:1,recover:3,verify_pin:4,change_pin:5,get_address:10,get_mnemonic:11,get_private_key:12,get_share_c:13,activate:14,sign:20,sign_typed_data:21,sign_message:22};function Di(s){return Se(Si(s.length),s)}function ts(s,e,t){return Se(j(s),...e.map(Di),new Uint8Array([t]))}function ki(s,e,t){return ts(bi,[s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Li(s,e,t){return ts(Pi,[s.enc,s.ciphertext,s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Ui(s,e,t){return qr(ki(s,e,t))}function Wi(s){return s.toISOString().replace(/\.\d+Z$/,"Z")}async function Bi(s,e){if(s.length!==32)throw new Error("authz private key must be a 32B P-256 scalar");return ft(e,"authz public key"),es.importKey("jwk",{kty:"EC",crv:"P-256",x:Vt(e.subarray(1,33)),y:Vt(e.subarray(33,65)),d:Vt(s),ext:!1},Ni,!1,["sign"])}async function Mi(s){if(s.intent.command!==s.command)throw new Error("intent.command must match command");const e=Ci[s.command],t=j(JSON.stringify(s.intent)),r={nonce:mi(vi),expiresAt:Wi(new Date((s.now??new Date).getTime()+(s.ttlSec??xi)*1e3)),intentHash:await qr(t),authzKeyId:s.authz.keyId},n=await Ui(r,s.bindingId,e),i={pin:s.plaintext.pin};s.plaintext.new_pin!=null&&(i.new_pin=s.plaintext.new_pin),s.plaintext.share_c&&(i.share_c=oe(s.plaintext.share_c)),s.plaintext.response_key&&(i.response_key=oe(s.plaintext.response_key));const{enc:a,ciphertext:o}=await Ri(s.recipientPub,j(JSON.stringify(i)),n),c=new Uint8Array(await es.sign({name:"ECDSA",hash:"SHA-256"},s.authz.signingKey,Li({...r,enc:a,ciphertext:o},s.bindingId,e)));return{envelope:{enc:oe(a),ciphertext:oe(o),nonce:oe(r.nonce),expires_at:r.expiresAt,intent_hash:oe(r.intentHash),authz_key_id:r.authzKeyId,authz_sig:oe(c),authz_key_cert:s.authz.cert},intent:oe(t),aad:n}}function rs(s,e,t){return Oi(s,Be(e.enc),Be(e.ciphertext),t)}const Fi=90*1e3;class Ki{constructor(e){this.opts=e,this.current=null,this.pending=null,this.generation=0,this.now=e.now??Date.now}async get(){const e=this.current;return e&&e.expiresAtMs-this.now()>Fi?e:(this.pending??(this.pending=this.issue().finally(()=>{this.pending=null})),this.pending)}invalidate(){this.current=null}async revoke(){const e=this.current;if(this.generation++,this.current=null,this.pending=null,!!e)try{await this.opts.client.call("DELETE",`/authz-keys/${encodeURIComponent(e.keyId)}`)}catch{}}async issue(){var u;const e=this.generation,t=await Qr(),r=await this.opts.getIssuanceJwt(),n=await this.opts.client.call("POST","/authz-keys",{jwt:r,response_key:oe(t.publicKey)});if(!((u=n==null?void 0:n.key_cert)!=null&&u.key_id)||!n.cert_sig||!n.sealed_private_key)throw new h(l.AUTH_FAILED,"authz-keys response is incomplete");let i;try{i=await rs(t,n.sealed_private_key,Be(n.cert_sig))}catch(f){throw new h(l.AUTH_FAILED,"failed to open sealed authz key",{cause:f})}const a=await Bi(i,Be(n.key_cert.pubkey));i.fill(0);const o=Date.parse(n.key_cert.expires_at);if(Number.isNaN(o))throw new h(l.AUTH_FAILED,"authz key_cert has no valid expires_at");const c={signingKey:a,keyId:n.key_cert.key_id,cert:{...n.key_cert,sig:n.cert_sig},expiresAtMs:o};if(e!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"authz key issuance was cancelled by sign-out");return this.current=c,c}}const Hi=600*1e3,Gi={UNAUTHORIZED:l.AUTH_TOKEN_INVALID,AUTHZ_TOKEN_INVALID:l.AUTH_TOKEN_INVALID,FORBIDDEN:l.AUTH_FAILED,AUTHZ_INVALID:l.AUTH_FAILED,OWNER_MISMATCH:l.AUTH_FAILED,USER_NOT_FOUND:l.USER_NOT_FOUND,INVALID_PIN:l.PIN_WRONG,PIN_LOCKED:l.PIN_LOCKED,PIN_THROTTLED:l.PIN_LOCKED,WALLET_ALREADY_EXISTS:l.WALLET_ALREADY_EXISTS,WALLET_NOT_FOUND:l.WALLET_NOT_FOUND,ADDRESS_NOT_FOUND:l.WALLET_NOT_FOUND,WALLET_DELETED:l.WALLET_NOT_FOUND,WALLET_NOT_ACTIVATED:l.WALLET_INCONSISTENT_STATE,WALLET_LOAD_FAILED:l.WALLET_INCONSISTENT_STATE,ADDRESS_LIMIT_EXCEEDED:l.ADDRESS_LIMIT_EXCEEDED,BROADCAST_FAILED:l.BROADCAST_FAILED,CHAIN_NOT_FOUND:l.CHAIN_NOT_SUPPORTED,INVALID_CHAIN_ID:l.INVALID_CHAIN,CHAIN_ID_MISMATCH:l.TYPED_DATA_CHAIN_ID_MISMATCH,INVALID_TYPED_DATA:l.TX_INVALID_PARAMS,INVALID_PARAMS:l.TX_INVALID_PARAMS,INVALID_REQUEST:l.TX_INVALID_PARAMS,BAD_REQUEST:l.TX_INVALID_PARAMS,INDEX_MISMATCH:l.TX_INVALID_PARAMS,OPERATION_IN_PROGRESS:l.GATEWAY_LOCK_CONFLICT,SIGNER_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,ATTESTATION_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,SERVICE_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,AUTH_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,BAD_GATEWAY:l.GATEWAY_INTERNAL_ERROR,INTERNAL_ERROR:l.GATEWAY_INTERNAL_ERROR,ENVELOPE_INVALID:l.SIGNATURE_FAILED,REPLAY:l.SIGNATURE_FAILED};function $i(s,e){const t=(e==null?void 0:e.code)??"",r=Gi[t]??(s===401?l.AUTH_TOKEN_INVALID:s>=500?l.GATEWAY_INTERNAL_ERROR:l.UNKNOWN_ERROR),n={status:s,serverCode:t};return(e==null?void 0:e.remaining_attempts)!=null&&(n.remainingAttempts=e.remaining_attempts),(e==null?void 0:e.lock_expires_at)!=null&&(n.lockExpiresAt=e.lock_expires_at>1e10?e.lock_expires_at:e.lock_expires_at*1e3),(e==null?void 0:e.permanent)!=null&&(n.permanent=e.permanent),e!=null&&e.tx_hash&&(n.txHash=e.tx_hash),new h(r,(e==null?void 0:e.message)||`one-wallet-api ${s}${t?` ${t}`:""}`,n)}class Vi{constructor(e){this.opts=e,this.recipient=null,this.now=e.now??Date.now}async call(e,t,r){const n=await this.opts.getAccessToken();return this.send(e,t,r,{Authorization:`Bearer ${n}`})}async callPublic(e,t){return this.send(e,t,void 0,{})}async getRecipientKey(){if(this.recipient&&this.now()-this.recipient.fetchedAt<Hi)return this.recipient.key;const e=await this.callPublic("GET","/attestation");if(!(e!=null&&e.recipient_public_key))throw new h(l.GATEWAY_INTERNAL_ERROR,"attestation has no recipient_public_key");const t=Be(e.recipient_public_key);return ft(t,"recipient_public_key"),this.recipient={key:t,fetchedAt:this.now()},t}forgetRecipientKey(){this.recipient=null}async send(e,t,r,n){const i=typeof this.opts.baseUrl=="function"?this.opts.baseUrl():this.opts.baseUrl;if(!i)throw new h(l.INVALID_CONFIG,"one-wallet-api URL is not configured for this environment");let a;try{a=await this.opts.transport.request({url:`${i.replace(/\/+$/,"")}${t}`,method:e,headers:r===void 0?n:{...n,"Content-Type":"application/json"},body:r})}catch(o){throw new h(l.NETWORK_ERROR,"one-wallet-api request failed",{cause:o})}if(a.status<200||a.status>=300)throw $i(a.status,a.data);return a.data}}const Yt=s=>`m/44'/60'/0'/0/${s}`,Ji=/^0x(?:[0-9a-fA-F]{2})*$/;function qi(s){try{const e=JSON.parse(new TextDecoder().decode(Ei(s.split(".")[1]??"")));if(typeof(e==null?void 0:e.sub)=="string"&&e.sub)return e.sub}catch{}throw new h(l.AUTH_TOKEN_INVALID,"access token has no sub")}function Yi(s){if(Ji.test(s)){const e=s.slice(2);return Uint8Array.from({length:e.length/2},(t,r)=>parseInt(e.slice(r*2,r*2+2),16))}return j(s)}const ss=s=>`0x${s.toString(16)}`;function ns(s,e){const t=s.chainId??Number(e.split(":")[1]);if(!Number.isSafeInteger(t))throw new h(l.TX_INVALID_PARAMS,`invalid chain id: ${e}`);if(s.nonce===void 0)throw new h(l.TX_INVALID_PARAMS,"transaction nonce is required");const r={to:s.to,value:s.value??"0x0",data:s.data??"0x",gas_limit:s.gasLimit,gas_price:s.gasPrice,max_fee_per_gas:s.maxFeePerGas,max_priority_fee_per_gas:s.maxPriorityFeePerGas,nonce:ss(s.nonce),chain_id:ss(t)};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}class is{constructor(e){this.opts=e,this.walletAddress=null,this.client=new Vi({baseUrl:e.baseUrl,transport:e.transport,getAccessToken:e.getAccessToken,now:e.now}),this.authzKeys=new Ki({client:this.client,getIssuanceJwt:e.getAccessToken,now:e.now})}async checkWallet(){return await this.findWallet()?"exists":"not_found"}async getOrCreateWallet(e){if(this.walletAddress)return this.walletData(this.walletAddress);const t=await this.findWallet();if(t)return this.walletData(t.address);const r=this.requirePin(),n=qi(await this.opts.getAccessToken()),i=await Qr(),{result:a,aad:o}=await this.withEnvelope("generate",n,{command:"generate"},{pin:r,response_key:i.publicKey},(c,u)=>this.client.call("POST","/wallets",{envelope:c,intent:u,ignore_backup:!1}));if(this.walletAddress=a.address,a.sealed_share_c&&this.opts.onShareC){const c=await rs(i,a.sealed_share_c,o);await this.opts.onShareC(c,a.address)}return this.walletData(a.address)}async getAddresses(e){const t=await this.requireWalletAddress(),r=await this.client.call("GET",`/wallets/${t}/addresses`);return((r==null?void 0:r.addresses)??[]).map(n=>({address:n.address,index:n.index,name:n.name||void 0}))}async getAddress(e,t){const r=await this.requireWalletAddress(),n=(await this.getAddresses(e)).find(a=>a.index===t);if(n)return{address:n.address,derivationPath:Yt(t)};const{result:i}=await this.withEnvelope("get_address",r,{command:"get_address",index:t},{pin:this.requirePin()},(a,o)=>this.client.call("PUT",`/wallets/${r}/addresses/${t}`,{envelope:a,intent:o}));return{address:i.address,derivationPath:Yt(t)}}async signMessage(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),{result:c}=await this.withEnvelope("sign_message",o.address,{command:"sign_message",index:o.index,message:oe(Yi(r))},{pin:this.requirePin()},(u,f)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"message",envelope:u,intent:f}));return{chainId:t,signature:c.signature,format:"hex"}}async signTypedData(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),c=typeof r=="string"?JSON.parse(r):r,{result:u}=await this.withEnvelope("sign_typed_data",o.address,{command:"sign_typed_data",index:o.index,typed_data:c},{pin:this.requirePin()},(f,g)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"typed_data",chain_id:t,envelope:f,intent:g}));return{chainId:t,signature:u.signature,format:"hex"}}async signTransaction(e,t,r,n){const i=await this.resolveTarget(n,r.from),{result:a}=await this.withEnvelope("sign",i.address,{command:"sign",index:i.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(o,c)=>this.client.call("POST",`/wallets/${i.address}/signatures`,{type:"transaction",chain_id:t,envelope:o,intent:c}));return{chainId:t,signature:a.signed_tx,txHash:a.tx_hash,format:"hex"}}async sendTransaction(e,t,r){const n=await this.resolveTarget(void 0,r.from),{result:i}=await this.withEnvelope("sign",n.address,{command:"sign",index:n.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(a,o)=>this.client.call("POST",`/wallets/${n.address}/transactions`,{chain_id:t,envelope:a,intent:o}));return{txHash:i.tx_hash}}async signOut(){this.walletAddress=null,await this.authzKeys.revoke()}walletData(e){return{id:e,address:e,derivationPath:Yt(0),createdAt:Date.now()}}async findWallet(){const e=await this.client.call("GET","/wallets"),t=Array.isArray(e)?e[0]??null:null;return this.walletAddress=(t==null?void 0:t.address)??null,t}async requireWalletAddress(){if(this.walletAddress)return this.walletAddress;const e=await this.findWallet();if(!e)throw new h(l.WALLET_NOT_FOUND,"no wallet for this account");return e.address}async resolveTarget(e,t){const r=await this.requireWalletAddress();if(!t&&!e)return{address:r,index:0};if(t&&t.toLowerCase()===r.toLowerCase()&&!e)return{address:r,index:0};const n=await this.getAddresses(""),i=t?n.find(a=>a.address.toLowerCase()===t.toLowerCase()):n.find(a=>a.index===e);if(!i)throw new h(l.TX_INVALID_PARAMS,t?`from is not an address of this wallet: ${t}`:`no derived address at index ${e}`);if(e!==void 0&&e!==i.index)throw new h(l.TX_INVALID_PARAMS,`from (index ${i.index}) does not match index ${e}`);return{address:i.address,index:i.index}}requirePin(){const e=this.opts.pinStore.get();if(!e)throw new h(l.PIN_NOT_SET,"PIN is required");return e}async withEnvelope(e,t,r,n,i){var a;for(let o=0;;o++){const c=await Mi({recipientPub:await this.client.getRecipientKey(),bindingId:t,command:e,intent:r,plaintext:n,authz:await this.authzKeys.get(),now:this.opts.now?new Date(this.opts.now()):void 0});try{return{result:await i(c.envelope,c.intent),aad:c.aad}}catch(u){if(o>0||!(u instanceof h))throw u;const f=(a=u.details)==null?void 0:a.serverCode;if(f==="AUTHZ_INVALID")this.authzKeys.invalidate();else if(f==="ENVELOPE_INVALID")this.client.forgetRecipientKey();else throw u}}}}const zi=3,Xi=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function ji(s){return s.code===zi||/execution reverted/i.test(s.message??"")}class Zi{constructor(e,t){this.chainRegistry=e,this.transport=t,this._nextId=1}async call(e,t,r){const n=await this.chainRegistry.getChain(r),i={jsonrpc:"2.0",method:e,params:t,id:this._nextId++},o=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(o!=null&&o.error){const{code:c,message:u}=o.error,f={method:e,chainId:r,code:c,message:u,data:o.error.data},g=ji(o.error);throw g&&typeof f.data=="string"&&Xi.test(f.data)&&(f.revertData=f.data,f.selector=f.data.slice(0,10).toLowerCase()),new h(g?l.EXECUTION_REVERTED:l.UNKNOWN_ERROR,`RPC 오류 [${e}] (${r}): ${u} (코드: ${c})`,f)}return o==null?void 0:o.result}}class Qi{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(n=>n(t))}removeAllListeners(){this.listeners.clear()}}function ea(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const t=new Uint8Array(16);return globalThis.crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class he{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const t=Date.now();for(;Date.now()-t<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await he.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=he.getBridge(),!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new h(l.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const t=await this.handshake();return this.context=t,d.log("[RNBridge] Bootstrap initialization complete",{activated:t.isActivated,ttl:`${t.absoluteTtlMs/1e3/60}min`}),t}async handshake(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=ea(),t=Date.now(),r={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:t,hmac:""};try{const n=await this.bridge.handshake(r);if(!n.activated)throw new h(l.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0,o=n.provider==="google"||n.provider==="apple"?n.provider:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:a,walletProvider:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new h(l.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),t=(e.expiresAt-Date.now())/1e3;if(t<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return this.touchActivity(),e}catch(e){if(e instanceof h)throw e;const t=e instanceof Error?e.message:String(e);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new h(l.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new h(l.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof h?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new h(l.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new h(l.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const t=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((t.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return t}catch(t){throw t instanceof h?t:(d.warn("[RNBridge] Session restore Firebase token request failed",t),new h(l.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",t))}}getContext(){return this.context}isActive(){var t;if(!((t=this.context)!=null&&t.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new h(l.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var gt={environment:"production"};const Me={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"",oneWalletApiUrl:""},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"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",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://stg-oauth2.onechain.nexus",oneWalletApiUrl:""},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"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",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://dev-oauth2.onechain.nexus",oneWalletApiUrl:"https://dev-one-pocket-api.onechain.nexus/embed/v1"}};function ta(s){const e=s.environment,t=e&&e in Me?Me[e]:null;if(!t)return null;const r=s.overrides;if(!r)return t;const n={...t};for(const[i,a]of Object.entries(r))typeof a=="string"&&a.trim()!==""&&(n[i]=a);return n}function _t(){try{if(typeof gt<"u"){const s=typeof gt=="string"?JSON.parse(gt):gt,e=ta(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Me)return Me[s]}catch{}return Me.production}function as(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function ra(s,e=Dt){if(!s||s==="0x0"||s==="0x")return"0";try{const t=BigInt(s);if(t===0n)return"0";const r=10n**BigInt(Or),n=t/r,a=(t%r).toString().padStart(Or,"0"),o=as(a).slice(0,e);return o?`${n}.${o}`:`${n}`}catch{return"?"}}function pt(s,e,t,r=Dt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(t),a=n/i,c=(n%i).toString().padStart(t,"0"),u=as(c.slice(0,r)),f=u?`${a}.${u}`:`${a}`;return e?`${f} ${e}`:f}catch{return}}function sa(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Rr)throw new h(l.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Rr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function na(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function ia(s,e){const t=aa(e);if(s==="0"){if(t!==void 0&&t!==0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const r=s.match(/^eip155:(\d+)$/);if(r){const n=Number(r[1]);if(t===void 0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function aa(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const t=e.chainId;if(t==null)return;const r=Number(t);return Number.isFinite(r)?r:void 0}const oa=new Set(["095ea7b3","a22cb465","39509351","d73dd623","87517c45"]),ca=new Set(["Permit","PermitSingle","PermitBatch","PermitTransferFrom","PermitBatchTransferFrom","PermitWitnessTransferFrom","PermitBatchWitnessTransferFrom"]);function la(s){var r;const{action:e,context:t}=s;if(e==="sign"||e==="send"){const n=(r=t.tx)==null?void 0:r.data;if(typeof n!="string")return!1;const i=n.trim().toLowerCase().replace(/^0x/,"");return i.length>=8&&oa.has(i.slice(0,8))}if(e==="sign-typed-data"){const n=da(t.typedData);return n===null||ca.has(n)}return!1}function da(s){let e=s;if(typeof e=="string")try{e=JSON.parse(e)}catch{return null}if(e&&typeof e=="object"&&"primaryType"in e){const t=e.primaryType;return typeof t=="string"?t:null}return null}function ha(s,e,t,r){if(!s)return!0;if(s.mode==="off"||e===null)return!1;const n=t-e;return n<0||n>=s.ttlMs?!1:!la(r)}function ua(s){return(s==null?void 0:s.mode)==="off"}class Fe{constructor(e){this.deps=e,this.verifyPinMutex=null}prepareForSigning(e){var r,n;if(!this.deps.pinStore.has())return;const t=(n=(r=this.deps).getPinReusePolicy)==null?void 0:n.call(r);ha(t,this.deps.pinStore.getSetAt(),Date.now(),e)||this.deps.pinStore.clear()}finishSigning(){var e,t;ua((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))&&this.deps.pinStore.clear()}hasReusePolicy(){var e,t;return((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))!==void 0}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new h(l.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const t=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!t)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(t),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,t,r,n){var c,u;if((u=(c=this.deps).isRNBridgeMode)!=null&&u.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,a;this.verifyPinMutex=new Promise((f,g)=>{i=f,a=g});const o=we(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const g=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n});if(!g)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(g),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const f=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n,onSubmit:async g=>{this.deps.pinStore.set(g);try{return await this.deps.walletProvider.verifyPin(g)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:o.pin_input_error})}catch(S){if(this.deps.pinStore.clear(),S instanceof h){if(S.code===l.PIN_WRONG)return{ok:!1,error:o.pin_input_error};if(S.code===l.PIN_INVALID)return{ok:!1,error:S.message};if(S.code===l.PIN_LOCKED)return Fe.buildPinLockedResult(S,o)}throw S}}});if(!f)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(f),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(f){if(f instanceof h&&(f.code===l.AUTH_NOT_AUTHENTICATED||f.code===l.AUTH_TOKEN_EXPIRED||f.code===l.SESSION_EXPIRED)&&f.code!==l.SESSION_EXPIRED){const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw a(f),f}throw a(f),f}finally{this.verifyPinMutex=null}}async withPinRetry(e){const t=we(this.deps.getLocale()??"en");let r=null;try{return await e()}catch(n){if(n instanceof h){if(r=Fe.parsePinError(n,t),!r)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",r.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(r.errorMessage,r.lockExpiresAt,r.attemptCount,r.maxAttempts);try{return await e()}catch(n){if(n instanceof h&&(r=Fe.parsePinError(n,t),r))continue;throw n}}}static parsePinError(e,t){if(e.code===l.PIN_WRONG)return{errorMessage:t.pin_input_error};if(e.code===l.PIN_INVALID)return{errorMessage:e.message};if(e.code===l.PIN_LOCKED){const r=e.details;return r!=null&&r.permanent?{errorMessage:t.pin_locked_permanent}:(r==null?void 0:r.remainingAttempts)!=null&&r.remainingAttempts>0&&r.maxAttempts?{errorMessage:t.pin_input_error,attemptCount:r.maxAttempts-r.remainingAttempts,maxAttempts:r.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:r==null?void 0:r.lockExpiresAt}}return null}static buildPinLockedResult(e,t){const r=Fe.parsePinError(e,t);if(!r)return{ok:!1,error:e.message};const{errorMessage:n,...i}=r;return{ok:!1,error:n,...i}}}class fa{constructor(e){this.deps=e,this.signingQueue=Promise.resolve()}async confirmAndExecuteWithPreparedPin(e){if(!this.deps.pinOrchestrator.hasReusePolicy())return this.confirmAndExecute(e);const t=this.signingQueue.then(()=>this.confirmAndExecute(e));return this.signingQueue=t.then(()=>{},()=>{}),t}async confirmAndExecute(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new h(l.USER_REJECTED,e.rejectedMessage);this.deps.pinOrchestrator.prepareForSigning({action:e.prepareAction,context:e.prepareContext});try{return await this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}finally{this.deps.pinOrchestrator.finishSigning()}}}function ga(s){return s==="google"||s==="apple"}class _a{constructor(e){this.deps=e}async signInAgain(){var t,r;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=ga(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(u){throw this.deps.clearAuthState(),u}if(!i.success)return this.deps.clearAuthState(),i;const a=((t=i.user)==null?void 0:t.providerSub)??null,o=((r=i.user)==null?void 0:r.id)??null;if(!(e.providerSub?!!a&&a===e.providerSub:e.userId?!!o&&e.userId===o:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const u=we(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:u.session_alert_title,message:u.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,u.session_alert_apple_account):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{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(t){const r=we(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,r.session_alert_apple_account):void 0;if(t instanceof h&&t.code===l.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(t instanceof h&&t.code===l.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(!(t instanceof h)||t.code!==l.SESSION_EXPIRED)throw t;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new h(l.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new h(l.SESSION_EXPIRED,o.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class pa{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,t,r){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const a=await this.deps.walletProvider.getAddresses(n);if(a.length>0){let c,u=!1;if(t){const g=a.find(S=>S.address.toLowerCase()===t.toLowerCase());g?c=g:(c={address:t,index:0},u=!0)}else e!==void 0?c=a.find(g=>g.index===e)??a[0]:c=a[0];u?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const f=!!t&&!!r&&c.address.toLowerCase()===t.toLowerCase();this.deps.setActiveWallet(c.address,c.index,f?{walletName:r}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class wa{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const t=this.deps.getAllowSkip(),r=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:t});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",r),r==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,a=5,o=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${a})`,n?`— 이전 메시지: ${n}`:"");const f=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:a});if(f===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const g=await((u=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:u.call(c,f,e));if(!g){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),o=f;break}if(g.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),o=f;break}const S=g.pinStatus;if(a=S.maxAttempts,i=a-S.remainingAttempts,S.remainingAttempts===0&&S.lockExpiresAt){const E=S.lockExpiresAt*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${m}초, 메시지: ${y}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${a})`),n="Incorrect PIN."}catch(g){if(!(g instanceof h))throw g;if(g.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const S=we(this.deps.getLocale()??"en"),E=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:S.session_alert_title,message:S.alert_session_expired,email:E?this.deps.maskEmail(E,S.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),g}if(g.code===l.MIGRATION_PIN_LOCKED){const S=g.details;if(a=(S==null?void 0:S.maxAttempts)??5,(S==null?void 0:S.permanent)===!0)return d.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 E=((S==null?void 0:S.lockExpiresAt)??0)*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${m}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const f=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof h&&f.code===l.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof h&&f.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const y=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",y.address),y}catch(y){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",y),y}}throw this.deps.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}}class Sa{constructor(e){this.deps=e}async withResolvedGasAndFee(e,t){const r=E=>!(E!=null&&E.trim()),n=e.nonce===void 0||e.nonce===null,i=r(e.gasLimit),a=r(e.gasPrice)&&r(e.maxFeePerGas),o=!r(e.maxFeePerGas)&&r(e.maxPriorityFeePerGas);if(!n&&!i&&!a&&!o)return e;const c={...e},u=n?c.from??this.deps.getActiveAddress()??void 0:void 0;u&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",u,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),a&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[f,g,S]=await Promise.all([u?this.deps.jsonRpcCall("eth_getTransactionCount",[u,"pending"],t):null,i?this.deps.estimateGas(e,t):null,a?this.deps.getBaseFeePerGas(t):null]);if(u&&(c.nonce=parseInt(f??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=g,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),a){const E=S;if(E){const m=Tr;c.maxFeePerGas=`0x${(BigInt(E)+BigInt(m)).toString(16)}`,c.maxPriorityFeePerGas=m,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",E,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Un,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!a&&o&&(c.maxPriorityFeePerGas=Tr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ea{constructor(e){this.crypto=e}verifySignatureSigner(e,t,r){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,t);if(n.toLowerCase()!==r.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:r,recovered:n}),new h(l.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${r}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof h)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function ma(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class ya{constructor(e){this.deps=e}setActiveWallet(e,t,r){this.deps.setState({address:e,activeWalletIndex:t});const n={address:e,index:t};(r==null?void 0:r.walletName)!==void 0&&(n.walletName=r.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:t,address:e}).catch(()=>{})}applyAuthResult(e,t){var n,i,a,o,c;const r={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((a=e.user)==null?void 0:a.providerSub)??null,loginType:ma((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...t?{source:t}:{}})}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.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Aa{constructor(e){this.deps=e}async resolveAddress(e){const t=this.deps.getActiveWalletIndex(),r=this.deps.getActiveAddress();if(e===void 0||e===t){if(!r&&this.deps.ensureWallet)return{address:await this.deps.ensureWallet(),index:t};if(!r)throw new h(l.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:r,index:t}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ia{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new h(l.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new h(l.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Ta{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const t=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",t),t==="migration_required"){const a=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",a);const o=await this.deps.migrationOrchestrator.handleMigrationFlow(a);if(o)return this.deps.setActiveWallet(o.address,0),{address:o.address};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(t==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const r=await this.tryGetOrCreateWalletWithMigrationFallback(e);return r.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:r.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const t=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(t.address,0),d.log("[CROSSx] 지갑 준비 완료:",t.address),{address:t.address,migrated:!1}}catch(t){if(t instanceof h&&t.code===l.MIGRATION_BACKUP_EXISTS){const r=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(r);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw t}}}function os(s,e){const t=s.replace(/\/$/,""),r=e.startsWith("/")?e:`/${e}`;return`${t}/cross-auth${r}`}class Ra{constructor(e){this.deps=e}async registerTokenHistory(e,t,r){if(!(e!=null&&e.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param chain_id");if(!(t!=null&&t.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(r!=null&&r.trim())||r.length>64)throw new h(l.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),a=os(i,`/v2/token-historical/${e}/${n}`),o={clientVersion:r};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:a,method:"POST",headers:{"Content-Type":"application/json"},body:o,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof h?c:new h(l.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const t=this.deps.getApiBaseUrl(),r=new URL(os(t,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&r.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&r.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:r.toString(),method:"GET",retries:0});if(i.status===404)throw new h(l.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof h?i:new h(l.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,t,r,n){const i=(n==null?void 0:n.maxRetries)??3,a=(n==null?void 0:n.retryDelayMs)??2e3;for(let o=0;o<i;o++)try{await this.registerTokenHistory(e,t,r);return}catch(c){if(c instanceof h&&c.message.includes("404")&&o<i-1){d.log(`[TokenHistory] Retry ${o+1}/${i} (404 - tx not yet indexed)`),await new Promise(f=>setTimeout(f,a));continue}throw c}}handleError(e,t){const n={400:{code:l.TX_INVALID_PARAMS,message:`Bad request (400): ${t==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:l.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:l.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:l.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new h(n.code,n.message)}}function zt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const t=s.indexOf("@");if(t<0)return"*".repeat(s.length||3);const r=s.substring(0,t),n=s.substring(t);return r.length<=1?`${r}${"*".repeat(Math.max(r.length,1))}${n}`:`${r[0]}${"*".repeat(r.length-1)}${n}`}const Ie=class Ie extends Qi{constructor(e,t,r,n,i,a,o,c,u,f,g,S,E){var m,y;super(),this.storage=r,this.crypto=n,this.transport=i,this.oauth=a,this.walletProvider=o,this.tokenStore=c,this.pinEncryptor=S,this.oneIdAuth=E,this._warnedUnknownNativeCurrency=new Set,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._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._sdkDeprecationNotified=!1,this._sdkUnsupportedNotified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=t,e.logger&&Dr(e.logger),this.confirmation=u,this.pinStore=g??new Mt,this.stateManager=new ya({setState:w=>{w.authenticated!==void 0&&(this.authenticated=w.authenticated),w.userId!==void 0&&(this.userId=w.userId),w.address!==void 0&&(this.address=w.address),w.activeWalletIndex!==void 0&&(this.activeWalletIndex=w.activeWalletIndex),w.userEmail!==void 0&&(this.userEmail=w.userEmail),w.providerSub!==void 0&&(this.providerSub=w.providerSub),w.loginType!==void 0&&(this.loginType=w.loginType),w.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=w.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:w,index:A,walletName:P})=>{const F={address:w,index:A};P!==void 0&&(F.walletName=P),this.emit("addressChanged",F)},emitAuthChanged:({isAuthenticated:w,address:A,userId:P,source:F})=>{this.emit("authChanged",{isAuthenticated:w,address:A,userId:P,...F?{source:F}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Ie.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Fe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge,getPinReusePolicy:()=>this.internalConfig.pinReuse}),this.signingOrchestrator=new fa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new pa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(w,A,P)=>this.setActiveWallet(w,A,P)}),this.migrationOrchestrator=new wa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(w,A)=>this.migrateWalletUseCase.execute(w,A),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var w;return((w=this._config.migration)==null?void 0:w.allowSkip)??!0}}),this.transactionLifecycleService=new Sa({getActiveAddress:()=>this.address,estimateGas:(w,A)=>this.estimateGas(w,A),getBaseFeePerGas:w=>this.getBaseFeePerGas(w),jsonRpcCall:(w,A,P)=>this.jsonRpc.call(w,A,P)}),this.signatureVerifier=new Ea(this.crypto),this.addressResolverService=new Aa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId,ensureWallet:this.usesOneWallet?()=>this.walletCreationService.createWallet().then(w=>w.address):void 0}),this.authGuardService=new Ia({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Ta({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(w,A)=>this.setActiveWallet(w,A),showWalletCreated:()=>{var w,A;return((A=(w=this.confirmation).showWalletCreatedPrompt)==null?void 0:A.call(w))??Promise.resolve()}}),this.tokenHistoryService=new Ra({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new _a({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:w=>{this._isRecoveringSession=w},setAuthenticated:w=>{this.authenticated=w},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:w=>this.signInUseCase.execute(w),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:w=>this.confirmation.showSessionAlert(w),clearAuthState:()=>this.clearAuthState(),applyAuthResult:w=>this.applyAuthResult(w),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:zt}),this.chainRegistry=f,this.jsonRpc=new Zi(f,i),this.signInUseCase=new Bt(this.internalConfig,r,n,a,i,o,c,void 0,()=>this._config.locale),this.signOutUseCase=new ti(this.internalConfig,r,c,this._config.persistWalletPreference!==!1?[Ie.WALLET_PREF_KEY]:[]),this.migrateWalletUseCase=new ri(r,o),(m=o.setOnUnauthorized)==null||m.call(o,()=>this.forceLogout()),(y=o.setTokenRefresher)==null||y.call(o,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}handleSdkVersionDeprecation(e){if(this._sdkDeprecationNotified)return;this._sdkDeprecationNotified=!0;const t=ot;console.warn(`[CROSSx] ${t} is deprecated`+(e.sunset?` and will stop working on ${e.sunset}`:"")+". Update @nexus-cross/crossx-sdk-core."+(e.infoUrl?` See ${e.infoUrl}`:"")),this.emit("versionDeprecated",{version:t,sunset:e.sunset,infoUrl:e.infoUrl})}handleSdkVersionUnsupported(e){this._sdkUnsupportedNotified||(this._sdkUnsupportedNotified=!0,console.error(`[CROSSx] ${ot} is no longer supported by the wallet gateway. Update @nexus-cross/crossx-sdk-core.`+(e.message?` (${e.message})`:"")),this.confirmation.showUpdateRequired().catch(t=>{d.warn("[CROSSx] 업데이트 필요 모달 표시 실패:",t)}))}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,d.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(t){d.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",t)}}}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}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 t,r;d.log("[CROSSx SDK] v3.0.0-beta.2 초기화 중..."),this.confirmation.setMessages(we(this._config.locale));try{const n=_t();if(this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(r=(t=this.crypto).setJWKSEndpoint)==null||r.call(t,`${n.authApiUrl}/.well-known/jwks.json`),this.usesOneWallet){const u=await this.restoreOneWalletSession();return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.2 초기화 완료 (one-wallet)"),this.emit("initialized",{restored:!!(u!=null&&u.success)}),u}const i=this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,a=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let o=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((o==null?void 0:o.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),o=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const u=this.address&&(!o||this.address.toLowerCase()===o.toLowerCase()),f=this._rnBridgeWalletName&&o&&this._rnBridgeWalletAddress&&o.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(u)this.address&&this.setActiveWallet(this.address,a??this.activeWalletIndex,f?{walletName:f}:void 0);else try{await this.loadWalletAfterAuth(a,o,f)}catch(g){if(g instanceof h&&g.code===l.PIN_CANCELLED)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(g instanceof h&&(g.code===l.SESSION_EXPIRED||g.code===l.AUTH_NOT_AUTHENTICATED||g.code===l.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",g.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw g}}return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.2 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new h(l.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!he.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),d.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"3.0.0-beta.2",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new he({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"3.0.0-beta.2",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),t=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=t.walletAddress,this._rnBridgeWalletName=t.walletName,this._rnBridgeWalletProvider=t.walletProvider,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:t.walletAddress??"(없음)",walletName:t.walletName??"(없음)"});const r=await this.signInUseCase.hasStoredRNBridgeSession();if(r&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(r){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const t=this._rnBridgeService.getContext(),r=Date.now();d.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:t?r-t.activatedAt:"(context 없음)",idleMs:t?r-t.lastActivityAt:"(context 없음)",absoluteTtlMs:(t==null?void 0:t.absoluteTtlMs)??"(context 없음)",idleTtlMs:(t==null?void 0:t.idleTtlMs)??"(context 없음)",absoluteExpired:t?r-t.activatedAt>t.absoluteTtlMs:"(context 없음)",idleExpired:t?r-t.lastActivityAt>t.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,d.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return d.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,null}}try{const t=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(r),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=r.user)==null?void 0:e.id}),r):null}catch(t){return t instanceof h&&t.code===l.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):t instanceof h&&t.code===l.SESSION_EXPIRED?(d.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",t),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const t=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=r.user)==null?void 0:e.id}),r):(this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 실패:",r.error),null)}catch(t){return this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",t),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new h(l.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new h(l.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return he.getBridge()}async signIn(e){if(this.ensureInitialized(),this.ensureNotOneWallet("signIn"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const t=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(t&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!t){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let r=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:Vn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new h(l.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(r);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof h?n:new h(l.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:t,...r}=e??{},n=await this.signIn(r);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c,t);return{...n,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i,t);return{...n,address:(a==null?void 0:a.address)??n.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",a))),i}}async signInWithOAuthToken(e){var r,n;if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithOAuthToken"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let t;try{t=await this.signInUseCase.executeWithOAuthToken(e),t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t,"external"),(n=(r=this.oauth).cancelPending)==null||n.call(r,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof h?i:new h(l.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!t.success)return{...t,addresses:[]};try{if(t.needsMigration||!t.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c);return{...t,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...t,address:(a==null?void 0:a.address)??t.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",a))),i}}async signInWithJWT(e,t){if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithJWT"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithJWT(e,t);return r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r)),r}catch(r){throw r instanceof h?r:new h(l.AUTH_FAILED,"JWT 로그인에 실패했습니다",r)}}signInWithOneId(e){var a,o;let t;try{t=this.oneIdContext()}catch(c){return Promise.reject(c)}const{port:r,config:n,sessions:i}=t;return r.authorize({...n,mode:(e==null?void 0:e.mode)??((a=this._config.oneId)==null?void 0:a.mode)??"auto",redirectUri:(o=this._config.oneId)==null?void 0:o.redirectUri,returnTo:e==null?void 0:e.returnTo}).then(async c=>{if(c.status==="redirecting")return c;const u=i.save(c.tokens);return this.usesOneWallet&&await this.applyOneIdSession(u),{status:"signed-in",session:u,returnTo:c.returnTo}})}async completeOneIdSignIn(e=window.location.href){const{port:t,config:r,sessions:n}=this.oneIdContext(),{tokens:i,returnTo:a}=await t.completeRedirect(r,e),o=n.save(i);return this.usesOneWallet&&await this.applyOneIdSession(o),{session:o,returnTo:a}}async getOneIdSession(){return this.oneIdContext().sessions.get()}async getOneIdAccessToken(){const e=this.usesOneWallet&&this._initPromise?this.oneIdContextUnchecked():this.oneIdContext();try{return await e.sessions.getAccessToken()}catch(t){throw this.usesOneWallet&&Vr(t)&&this.clearAuthState(),t}}async signOutOneId(){const{sessions:e}=this.oneIdContext();this.walletProvider instanceof is&&await this.walletProvider.signOut().catch(t=>d.warn("[CROSSx] B 키 폐기 실패 (로그아웃은 진행)",t));try{await e.signOut()}finally{this.usesOneWallet&&this.clearAuthState()}}ensureNotOneWallet(e){if(this.usesOneWallet)throw new h(l.NOT_IMPLEMENTED,`walletServer 'one-wallet' 에서는 ${e}() 를 쓸 수 없습니다. signInWithOneId() 로 로그인하세요`)}get usesOneWallet(){return this._config.walletServer==="one-wallet"}async restoreOneWalletSession(){await this.signOutUseCase.hasStoredSession().catch(()=>!1)&&(d.log("[CROSSx] one-wallet: 저장된 2.x 로그인 토큰을 무시하고 지운다"),await this.signOutUseCase.execute().catch(t=>d.warn("[CROSSx] 2.x 토큰 정리 실패",t)));let e;try{e=await this.oneIdContextUnchecked().sessions.get()}catch(t){return d.warn("[CROSSx] one-wallet: ONE ID 세션 복원 실패 — 로그아웃 상태로 시작",t),null}return e?this.applyOneIdSession(e):null}async applyOneIdSession(e){var n,i;let t;try{await((i=(n=this.walletProvider).checkWallet)==null?void 0:i.call(n))==="exists"&&(t=(await this.walletProvider.getOrCreateWallet(e.subject)).address)}catch(a){if(Vr(a))throw a;d.warn("[CROSSx] one-wallet: 지갑 조회 실패 — 주소 없이 로그인 상태로 둔다",a)}const r={success:!0,address:t,user:{id:e.subject}};return this.applyAuthResult(r),t&&this.setActiveWallet(t,0),r}oneIdContext(){return this.ensureInitialized(),this.oneIdContextUnchecked()}oneIdContextUnchecked(){const e=this._config.oneId;if(!this.oneIdAuth||!(e!=null&&e.clientId))throw new h(l.NOT_IMPLEMENTED,"이 환경에서는 ONE ID 로그인을 사용할 수 없습니다 (SDKConfig.oneId 필요)");const t=e.issuer||_t().oneIdIssuer;if(!t)throw new h(l.NOT_IMPLEMENTED,"ONE ID issuer가 정해지지 않았습니다. SDKConfig.oneId.issuer를 지정하세요");const r={issuer:t,clientId:e.clientId,scope:e.scope};return this._oneIdSessions??(this._oneIdSessions=new _i(this.oneIdAuth,r,pi(e.storage))),{port:this.oneIdAuth,config:r,sessions:this._oneIdSessions}}async signOut(){if(this.ensureInitialized(),this.usesOneWallet){await this.signOutOneId();return}try{await this.signOutUseCase.execute(),this.clearAuthState();const e=he.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(t){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",t)}}catch(e){throw new h(l.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}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",r)}return!0}const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(t);try{await this.loadWalletAfterAuth()}catch(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}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,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const t=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(t.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",t.address),t}catch(t){throw t instanceof h?t:new h(l.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",t)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new h(l.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,t){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const n=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const i=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,i)))).address,index:i};return r.push(o),o},e,t);return n&&this.setActiveWallet(n.address,n.index),n}async selectWalletIfMultiple(e,t){if(e.length<2)return null;const r=this._isAuthenticatedViaRNBridge?this._rnBridgeWalletAddress??this.address??void 0:void 0,n=!r&&this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,i=r?[r,t]:[t,n==null?void 0:n.address];for(const a of i){if(typeof a!="string"||!a)continue;const o=e.find(c=>c.address.toLowerCase()===a.toLowerCase());if(o)return this.setActiveWallet(o.address,o.index),o}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof h?e:new h(l.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(t){throw t instanceof h?t:new h(l.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,t)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),t=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};t(e.matches);const r=n=>t(n.matches);e.addEventListener("change",r),this._themeMediaCleanup=()=>e.removeEventListener("change",r)}applyTheme(e=this._config.theme??"light",t=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:t}),this.confirmation.setTheme(e,t)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(we(e))}setPinKeyboard(e){var t,r;this._config=Object.freeze({...this._config,pinKeyboard:e}),(r=(t=this.confirmation).setPinKeyboard)==null||r.call(t,e)}resolveNativeCurrency(e){const t=Zn(e,this._config.nativeCurrencies);return t||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),jn)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,t,r){return this.withSessionRecovery(()=>this._signMessage(e,t,r))}async _signMessage(e,t,r){const n=he.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const o=await n.signMessage({chainId:e,message:t,from:this.address??"",index:(r==null?void 0:r.index)??0,dappName:(r==null?void 0:r.dappName)??this._config.appName});return{chainId:e,signature:o.signature,message:t,address:this.address??""}}catch(o){if(!vr(o))throw Ue(o,l.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),d.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const a=await this.resolveAddress(r==null?void 0:r.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:a.address,message:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:t,from:a.address},execute:c=>this.walletProvider.signMessage(this.userId,e,t,r==null?void 0:r.index,c,a.address)});return this.signatureVerifier.verifySignatureSigner(t,o.signature,a.address),{chainId:e,signature:o.signature,message:t,address:a.address}}catch(o){throw o instanceof h?o:new h(l.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,t,r){return this.withSessionRecovery(()=>this._signTypedData(e,t,r))}async _signTypedData(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new h(l.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ia(e,t);const n=await this.resolveAddress(r==null?void 0:r.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:t,from:n.address},execute:a=>this.walletProvider.signTypedData(this.userId,e,t,r==null?void 0:r.index,a,n.address)});return sa(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof h?i:new h(l.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,t){return this.signTypedData(Ie.OFFCHAIN_CHAIN_ID,e,t)}async signTransaction(e,t,r){return this.withSessionRecovery(()=>this._signTransaction(e,t,r))}async _signTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:o=>this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,o)});return na(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${o}`,a)}}async sendTransaction(e,t,r){return this.withSessionRecovery(()=>this._sendTransaction(e,t,r))}async _sendTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async f=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,f)).txHash;const g=await this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,f);return g.txHash??g.signature}}),o=(t.data??"").toLowerCase().replace(/^0x/,""),c=o===""||o==="00000000",u=o.startsWith("a9059cbb");return(c||u)&&this.tokenHistoryService.registerHistoryFireAndForget(e,a,ot).catch(f=>d.log("[TokenHistory] register failed (non-critical):",f)),{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${o}`,a)}}async getTransactionReceipt(e,t){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],t)??null}catch{return null}}async waitForTxAndGetReceipt(e,t,r={}){const n=r.intervalMs??kn,i=Ln,a=r.timeoutMs??Ir,o=Date.now()+a;let c=n;for(;Date.now()<o;){const u=await this.getTransactionReceipt(e,t);if(u)return u;await new Promise(f=>setTimeout(f,c)),c=Math.min(c*2,i)}throw new h(l.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,t,r={}){var y,w;if(this._isAuthenticatedViaRNBridge){const A=he.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,t,r)}const{intervalMs:n,timeoutMs:i,...a}=r,{txHash:o}=await this.sendTransaction(e,t,a),c=n??((y=this._config.receiptPolling)==null?void 0:y.intervalMs)??Dn,u=i??((w=this._config.receiptPolling)==null?void 0:w.timeoutMs)??Ir,f=this.resolveNativeCurrency(e),g=t.from??"";let S,E;const m=this.waitForTxAndGetReceipt(o,e,{intervalMs:c,timeoutMs:u}).then(A=>{S=A;const P=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),F=t.value?BigInt(t.value):0n,M=pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),V=pt("0x"+P.toString(16),f.symbol,f.decimals,this._config.displayDecimals),U=pt("0x"+(F+P).toString(16),f.symbol,f.decimals,this._config.displayDecimals);return{chainId:e,txHash:o,from:A.from,to:A.to??t.to,amount:M,fees:V,total:U,nativeSymbol:f.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(E=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:o,from:g,to:t.to,amount:pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),nativeSymbol:f.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:o,from:g,to:t.to},m),E)throw E;return{chainId:e,txHash:o,receipt:S}}async bridgeSendTransactionWithWaitForReceipt(e,t,r,n){let i;try{i=await e.sendTransactionWithWaitForReceipt({chainId:t,tx:{to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce},from:r.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(a){throw Ue(a,l.TRANSACTION_FAILED)}return{chainId:t,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??r.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,t){this.ensureAuthenticated();const r=this.walletProvider;if(typeof r.changePin!="function")throw new h(l.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await r.changePin(e,t),this.pinStore.set(t),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof h?n:new h(l.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${r}`,t)}}async estimateGas(e,t){this.ensureAuthenticated();const r={};e.from&&(r.from=e.from),e.to&&(r.to=e.to),e.value&&(r.value=e.value),e.data&&(r.data=e.data),e.gasPrice&&(r.gasPrice=e.gasPrice),e.maxFeePerGas&&(r.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(r.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[r],t)}catch(n){if(n instanceof h&&n.code===l.EXECUTION_REVERTED)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${t}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const t=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(t==null?void 0:t.baseFeePerGas)??null}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getNonce(e){this.ensureAuthenticated();const t=this.address;if(!t)return 0;try{const r=await this.jsonRpc.call("eth_getTransactionCount",[t,"pending"],e);return parseInt(r??"0x0",16)}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,r)}}async getBalance(e){this.ensureAuthenticated();const t=this.address;if(!t)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[t,"latest"],e)??"0x0";return{wei:n,formatted:ra(n,this._config.displayDecimals),chainId:e}}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,r)}}getProvider(e){this.ensureAuthenticated();let t=this._providers.get(e);return t||(t=new Ut(this,e),this._providers.set(e,t)),t}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(t=>{try{t.emit("accountsChanged",[e])}catch(r){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",r)}})}async walletRpc(e,t,r){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,t,r)}catch(n){if(n instanceof h)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${r}): ${i}`,n)}}setActiveWallet(e,t,r){const n=this.address;this.stateManager.setActiveWallet(e,t,r),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=he.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",t=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!t||typeof t!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",t);return}const r=t,n=typeof r.address=="string"?r.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",r);return}if(r.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",r);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){d.warn("[walletChanged] not authenticated — 이벤트 무시",r);return}const i=typeof r.walletName=="string"?r.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:r.walletId,source:r.source,walletName:a}),this.setActiveWallet(n,0,{walletName:a}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=a)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,t){this.stateManager.applyAuthResult(e,t)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.ensureNotOneWallet("signInAgain"),this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.usesOneWallet?e():this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,t,r){return this.walletLifecycleService.loadWalletAfterAuth(e,t,r)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,t,r){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,t,r))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}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(),Dr(null)}};Ie.WALLET_PREF_KEY="wallet_preference",Ie.OFFCHAIN_CHAIN_ID="0";let Ze=Ie;class Oa{constructor(){this.prefix="crossx_"}async set(e,t){try{const r=JSON.stringify(t);localStorage.setItem(this.prefix+e,r)}catch(r){throw d.error("Storage set error:",r),r}}async get(e){try{const t=localStorage.getItem(this.prefix+e);return t?JSON.parse(t):null}catch(t){return d.error("Storage get error:",t),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(t){throw d.error("Storage remove error:",t),t}}async clear(){try{Object.keys(localStorage).forEach(t=>{t.startsWith(this.prefix)&&localStorage.removeItem(t)})}catch(e){throw d.error("Storage clear error:",e),e}}}const wt="crossx-sdk",cs=1,ce="data",Te="keys",St="aes-primary",Na=12;class ls{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(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,cs);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(ce)||n.createObjectStore(ce),n.objectStoreNames.contains(Te)||n.createObjectStore(Te)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}openLegacyIfExists(){return new Promise((e,t)=>{let r=!1;const n=indexedDB.open(wt,cs);n.onupgradeneeded=()=>{r=!0},n.onsuccess=()=>{const i=n.result;if(r){i.close(),this.deleteDB(wt).then(()=>e(null));return}if(!i.objectStoreNames.contains(Te)||!i.objectStoreNames.contains(ce)){i.close(),e(null);return}e(i)},n.onerror=()=>t(n.error)})}deleteDB(e){return new Promise(t=>{const r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>{d.warn("[CROSSx] IndexedDB 삭제 실패:",e,r.error),t()},r.onblocked=()=>{d.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),t()}})}idbGet(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readonly").objectStore(e).get(t);a.onsuccess=()=>r(a.result),a.onerror=()=>n(a.error)})}idbPut(e,t,r){return new Promise((n,i)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).put(r,t);o.onsuccess=()=>n(),o.onerror=()=>i(o.error)})}idbDelete(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).delete(t);a.onsuccess=()=>r(),a.onerror=()=>n(a.error)})}idbClear(e){return new Promise((t,r)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Te,St);if(e){this.cryptoKey=e;return}const t=await this.migrateFromLegacyDB();if(t){this.cryptoKey=t;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Te,St,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===wt)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const t=e.transaction([Te,ce],"readonly"),r=t.objectStore(Te).get(St),n=await new Promise((u,f)=>{r.onsuccess=()=>u(r.result),r.onerror=()=>f(r.error)});if(!n)return e.close(),null;const i=t.objectStore(ce).getAll(),a=t.objectStore(ce).getAllKeys(),[o,c]=await Promise.all([new Promise((u,f)=>{i.onsuccess=()=>u(i.result),i.onerror=()=>f(i.error)}),new Promise((u,f)=>{a.onsuccess=()=>u(a.result),a.onerror=()=>f(a.error)})]);e.close(),await this.idbPut(Te,St,n);for(let u=0;u<c.length;u++)await this.idbPut(ce,String(c[u]),o[u]);return await this.deleteDB(wt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const t=new Uint8Array(Na);crypto.getRandomValues(t);const r=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},this.cryptoKey,r);return{iv:t,ciphertext:n}}async decrypt(e){const t=new Uint8Array(e.iv),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(r)}async set(e,t){try{await this.ensureReady();const r=JSON.stringify(t),n=await this.encrypt(r);await this.idbPut(ce,e,n)}catch(r){throw d.error("[CROSSx] IndexedDB set error:",r),r}}async get(e){try{await this.ensureReady();const t=await this.idbGet(ce,e);if(!t)return null;const r=await this.decrypt(t);return JSON.parse(r)}catch(t){return d.error("[CROSSx] IndexedDB get error:",t),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ce,e)}catch(t){throw d.error("[CROSSx] IndexedDB remove error:",t),t}}async clear(){try{await this.ensureReady(),await this.idbClear(ce)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Xt=crypto,ds=s=>s instanceof CryptoKey,Et=new TextEncoder,Qe=new TextDecoder;function Pa(...s){const e=s.reduce((n,{length:i})=>n+i,0),t=new Uint8Array(e);let r=0;for(const n of s)t.set(n,r),r+=n.length;return t}const ba=s=>{const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ba(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class z extends Error{constructor(e,t){var r;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}z.code="ERR_JOSE_GENERIC";class le extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}le.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class jt extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}jt.code="ERR_JWT_EXPIRED";class hs extends z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}hs.code="ERR_JOSE_ALG_NOT_ALLOWED";class ue extends z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ue.code="ERR_JOSE_NOT_SUPPORTED";class xa extends z{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}xa.code="ERR_JWE_DECRYPTION_FAILED";class va extends z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}va.code="ERR_JWE_INVALID";class q extends z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}q.code="ERR_JWS_INVALID";class fe extends z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}fe.code="ERR_JWT_INVALID";class Ca extends z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ca.code="ERR_JWK_INVALID";class Zt extends z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Zt.code="ERR_JWKS_INVALID";class Qt extends z{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Qt.code="ERR_JWKS_NO_MATCHING_KEY";class us extends z{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}us.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class fs extends z{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}fs.code="ERR_JWKS_TIMEOUT";class gs extends z{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}gs.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function ge(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function er(s){return parseInt(s.name.slice(4),10)}function Da(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ka(s,e){if(e.length&&!e.some(t=>s.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const r=e.pop();t+=`one of ${e.join(", ")}, or ${r}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function La(s,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw ge("HMAC");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw ge("RSASSA-PKCS1-v1_5");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw ge("RSA-PSS");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw ge("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw ge("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw ge("ECDSA");const r=Da(e);if(s.algorithm.namedCurve!==r)throw ge(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ka(s,t)}function _s(s,e,...t){var r;if(t=t.filter(Boolean),t.length>2){const n=t.pop();s+=`one of type ${t.join(", ")}, or ${n}.`}else t.length===2?s+=`one of type ${t[0]} or ${t[1]}.`:s+=`of type ${t[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(r=e.constructor)!=null&&r.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const ps=(s,...e)=>_s("Key must be ",s,...e);function ws(s,e,...t){return _s(`Key for the ${s} algorithm must be `,e,...t)}const Ss=s=>ds(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",mt=["CryptoKey"],Ua=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const r of e){const n=Object.keys(r);if(!t||t.size===0){t=new Set(n);continue}for(const i of n){if(t.has(i))return!1;t.add(i)}}return!0};function Wa(s){return typeof s=="object"&&s!==null}function Ee(s){if(!Wa(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const Ba=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ke(s){return Ee(s)&&typeof s.kty=="string"}function Ma(s){return s.kty!=="oct"&&typeof s.d=="string"}function Fa(s){return s.kty!=="oct"&&typeof s.d>"u"}function Ka(s){return Ke(s)&&s.kty==="oct"&&typeof s.k=="string"}function Ha(s){let e,t;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},t=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},t=s.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(s.alg.slice(-3),10)||1}`},t=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},t=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},t=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ue('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Es=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Ha(s),r=[e,s.ext??!1,s.key_ops??t],n={...s};return delete n.alg,delete n.use,Xt.subtle.importKey("jwk",n,...r)},ms=s=>Re(s);let He,Ge;const ys=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",yt=async(s,e,t,r,n=!1)=>{let i=s.get(e);if(i!=null&&i[r])return i[r];const a=await Es({...t,alg:r});return n&&Object.freeze(e),i?i[r]=a:s.set(e,{[r]:a}),a},Ga={normalizePublicKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?ms(t.k):(Ge||(Ge=new WeakMap),yt(Ge,s,t,e))}return Ke(s)?s.k?Re(s.k):(Ge||(Ge=new WeakMap),yt(Ge,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return t.k?ms(t.k):(He||(He=new WeakMap),yt(He,s,t,e))}return Ke(s)?s.k?Re(s.k):(He||(He=new WeakMap),yt(He,s,s,e,!0)):s}};async function As(s,e){if(!Ee(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ue('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Es({...s,alg:e});default:throw new ue('Unsupported "kty" (Key Type) Parameter value')}}const $e=s=>s==null?void 0:s[Symbol.toStringTag],tr=(s,e,t)=>{var r,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=(r=e.key_ops).includes)==null?void 0:n.call(r,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},$a=(s,e,t,r)=>{if(!(e instanceof Uint8Array)){if(r&&Ke(e)){if(Ka(e)&&tr(s,e,t))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(!Ss(e))throw new TypeError(ws(s,e,...mt,"Uint8Array",r?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${$e(e)} instances for symmetric algorithms must be of type "secret"`)}},Va=(s,e,t,r)=>{if(r&&Ke(e))switch(t){case"sign":if(Ma(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Fa(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ss(e))throw new TypeError(ws(s,e,...mt,r?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${$e(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Is(s,e,t,r){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?$a(e,t,r,s):Va(e,t,r,s)}Is.bind(void 0,!1);const Ts=Is.bind(void 0,!0);function Ja(s,e,t,r,n){if(n.crit!==void 0&&(r==null?void 0:r.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(a=>typeof a!="string"||a.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;t!==void 0?i=new Map([...Object.entries(t),...e.entries()]):i=e;for(const a of r.crit){if(!i.has(a))throw new ue(`Extension Header Parameter "${a}" is not recognized`);if(n[a]===void 0)throw new s(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&r[a]===void 0)throw new s(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}const qa=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function Ya(s,e){const t=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ue(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function za(s,e,t){if(e=await Ga.normalizePublicKey(e,s),ds(e))return La(e,s,t),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(ps(e,...mt));return Xt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(ps(e,...mt,"Uint8Array","JSON Web Key"))}const Xa=async(s,e,t,r)=>{const n=await za(s,e,"verify");Ba(s,n);const i=Ya(s,n.algorithm);try{return await Xt.subtle.verify(i,n,t,r)}catch{return!1}};async function ja(s,e,t){if(!Ee(s))throw new q("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new q('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new q("JWS Protected Header incorrect type");if(s.payload===void 0)throw new q("JWS Payload missing");if(typeof s.signature!="string")throw new q("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Ee(s.header))throw new q("JWS Unprotected Header incorrect type");let r={};if(s.protected)try{const y=Re(s.protected);r=JSON.parse(Qe.decode(y))}catch{throw new q("JWS Protected Header is invalid")}if(!Ua(r,s.header))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...r,...s.header},i=Ja(q,new Map([["b64",!0]]),t==null?void 0:t.crit,r,n);let a=!0;if(i.has("b64")&&(a=r.b64,typeof a!="boolean"))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=n;if(typeof o!="string"||!o)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=t&&qa("algorithms",t.algorithms);if(c&&!c.has(o))throw new hs('"alg" (Algorithm) Header Parameter value not allowed');if(a){if(typeof s.payload!="string")throw new q("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new q("JWS Payload must be a string or an Uint8Array instance");let u=!1;typeof e=="function"?(e=await e(r,s),u=!0,Ts(o,e,"verify"),Ke(e)&&(e=await As(e,o))):Ts(o,e,"verify");const f=Pa(Et.encode(s.protected??""),Et.encode("."),typeof s.payload=="string"?Et.encode(s.payload):s.payload);let g;try{g=Re(s.signature)}catch{throw new q("Failed to base64url decode the signature")}if(!await Xa(o,e,g,f))throw new gs;let E;if(a)try{E=Re(s.payload)}catch{throw new q("Failed to base64url decode the payload")}else typeof s.payload=="string"?E=Et.encode(s.payload):E=s.payload;const m={payload:E};return s.protected!==void 0&&(m.protectedHeader=r),s.header!==void 0&&(m.unprotectedHeader=s.header),u?{...m,key:e}:m}async function Za(s,e,t){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new q("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:i,length:a}=s.split(".");if(a!==3)throw new q("Invalid Compact JWS");const o=await ja({payload:n,protected:r,signature:i},e,t),c={payload:o.payload,protectedHeader:o.protectedHeader};return typeof e=="function"?{...c,key:o.key}:c}const Qa=s=>Math.floor(s.getTime()/1e3),Rs=60,Os=Rs*60,rr=Os*24,eo=rr*7,to=rr*365.25,ro=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ns=s=>{const e=ro.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const t=parseFloat(e[2]),r=e[3].toLowerCase();let n;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(t);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(t*Rs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(t*Os);break;case"day":case"days":case"d":n=Math.round(t*rr);break;case"week":case"weeks":case"w":n=Math.round(t*eo);break;default:n=Math.round(t*to);break}return e[1]==="-"||e[4]==="ago"?-n:n},Ps=s=>s.toLowerCase().replace(/^application\//,""),so=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,no=(s,e,t={})=>{let r;try{r=JSON.parse(Qe.decode(e))}catch{}if(!Ee(r))throw new fe("JWT Claims Set must be a top-level JSON object");const{typ:n}=t;if(n&&(typeof s.typ!="string"||Ps(s.typ)!==Ps(n)))throw new le('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:o,audience:c,maxTokenAge:u}=t,f=[...i];u!==void 0&&f.push("iat"),c!==void 0&&f.push("aud"),o!==void 0&&f.push("sub"),a!==void 0&&f.push("iss");for(const m of new Set(f.reverse()))if(!(m in r))throw new le(`missing required "${m}" claim`,r,m,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(r.iss))throw new le('unexpected "iss" claim value',r,"iss","check_failed");if(o&&r.sub!==o)throw new le('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!so(r.aud,typeof c=="string"?[c]:c))throw new le('unexpected "aud" claim value',r,"aud","check_failed");let g;switch(typeof t.clockTolerance){case"string":g=Ns(t.clockTolerance);break;case"number":g=t.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:S}=t,E=Qa(S||new Date);if((r.iat!==void 0||u)&&typeof r.iat!="number")throw new le('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new le('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>E+g)throw new le('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new le('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=E-g)throw new jt('"exp" claim timestamp check failed',r,"exp","check_failed")}if(u){const m=E-r.iat,y=typeof u=="number"?u:Ns(u);if(m-g>y)throw new jt('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(m<0-g)throw new le('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r};async function io(s,e,t){var a;const r=await Za(s,e,t);if((a=r.protectedHeader.crit)!=null&&a.includes("b64")&&r.protectedHeader.b64===!1)throw new fe("JWTs MUST NOT use unencoded payload");const i={payload:no(r.protectedHeader,r.payload,t),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}function ao(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ue('Unsupported "alg" value for a JSON Web Key Set')}}function oo(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(co)}function co(s){return Ee(s)}function bs(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class lo{constructor(e){if(this._cached=new WeakMap,!oo(e))throw new Zt("JSON Web Key Set malformed");this._jwks=bs(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t==null?void 0:t.header},i=ao(r),a=this._jwks.keys.filter(u=>{let f=i===u.kty;if(f&&typeof n=="string"&&(f=n===u.kid),f&&typeof u.alg=="string"&&(f=r===u.alg),f&&typeof u.use=="string"&&(f=u.use==="sig"),f&&Array.isArray(u.key_ops)&&(f=u.key_ops.includes("verify")),f)switch(r){case"ES256":f=u.crv==="P-256";break;case"ES256K":f=u.crv==="secp256k1";break;case"ES384":f=u.crv==="P-384";break;case"ES512":f=u.crv==="P-521";break;case"Ed25519":f=u.crv==="Ed25519";break;case"EdDSA":f=u.crv==="Ed25519"||u.crv==="Ed448";break}return f}),{0:o,length:c}=a;if(c===0)throw new Qt;if(c!==1){const u=new us,{_cached:f}=this;throw u[Symbol.asyncIterator]=async function*(){for(const g of a)try{yield await xs(f,g,r)}catch{}},u}return xs(this._cached,o,r)}}async function xs(s,e,t){const r=s.get(e)||s.set(e,{}).get(e);if(r[t]===void 0){const n=await As({...e,ext:!0},t);if(n instanceof Uint8Array||n.type!=="public")throw new Zt("JSON Web Key Set members must be public keys");r[t]=n}return r[t]}function vs(s){const e=new lo(s),t=async(r,n)=>e.getKey(r,n);return Object.defineProperties(t,{jwks:{value:()=>bs(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),t}const ho=async(s,e,t)=>{let r,n,i=!1;typeof AbortController=="function"&&(r=new AbortController,n=setTimeout(()=>{i=!0,r.abort()},e));const a=await fetch(s.href,{signal:r?r.signal:void 0,redirect:"manual",headers:t.headers}).catch(o=>{throw i?new fs:o});if(n!==void 0&&clearTimeout(n),a.status!==200)throw new z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new z("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function uo(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let sr;(typeof navigator>"u"||!((xn=(Ct=navigator.userAgent)==null?void 0:Ct.startsWith)!=null&&xn.call(Ct,"Mozilla/5.0 ")))&&(sr="jose/v5.10.0");const nr=Symbol();function fo(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Ee(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Ee))}class go{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:t==null?void 0:t.agent,headers:t==null?void 0:t.headers},this._timeoutDuration=typeof(t==null?void 0:t.timeoutDuration)=="number"?t==null?void 0:t.timeoutDuration:5e3,this._cooldownDuration=typeof(t==null?void 0:t.cooldownDuration)=="number"?t==null?void 0:t.cooldownDuration:3e4,this._cacheMaxAge=typeof(t==null?void 0:t.cacheMaxAge)=="number"?t==null?void 0:t.cacheMaxAge:6e5,(t==null?void 0:t[nr])!==void 0&&(this._cache=t==null?void 0:t[nr],fo(t==null?void 0:t[nr],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=vs(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,t){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof Qt&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&uo()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);sr&&!e.has("User-Agent")&&(e.set("User-Agent",sr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ho(this._url,this._timeoutDuration,this._options).then(t=>{this._local=vs(t),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=t),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}}function _o(s,e){const t=new go(s,e),r=async(n,i)=>t.getKey(n,i);return Object.defineProperties(r,{coolingDown:{get:()=>t.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>t.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>t.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!t._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=t._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),r}const po=Re;function wo(s){if(typeof s!="string")throw new fe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=s.split(".");if(t===5)throw new fe("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new fe("Invalid JWT");if(!e)throw new fe("JWTs must contain a payload");let r;try{r=po(e)}catch{throw new fe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(r))}catch{throw new fe("Failed to parse the decoded payload as JSON")}if(!Ee(n))throw new fe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ir(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function me(s,e=""){if(!Number.isSafeInteger(s)||s<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${s}`)}}function $(s,e,t=""){const r=ir(s),n=s==null?void 0:s.length,i=e!==void 0;if(!r||i&&n!==e){const a=t&&`"${t}" `,o=i?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(a+"expected Uint8Array"+o+", got "+c)}return s}function Cs(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");me(s.outputLen),me(s.blockLen)}function Ve(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Ds(s,e){$(s,void 0,"digestInto() output");const t=e.outputLen;if(s.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function So(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function ar(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function _e(s,e){return s<<32-e|s>>>e}const Eo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function mo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function yo(s){for(let e=0;e<s.length;e++)s[e]=mo(s[e]);return s}const ks=Eo?s=>s:yo,Ls=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ao=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if($(s),Ls)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Ao[s[t]];return e}const ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function Us(s){if(s>=ye._0&&s<=ye._9)return s-ye._0;if(s>=ye.A&&s<=ye.F)return s-(ye.A-10);if(s>=ye.a&&s<=ye.f)return s-(ye.a-10)}function At(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ls)return Uint8Array.fromHex(s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){const a=Us(s.charCodeAt(i)),o=Us(s.charCodeAt(i+1));if(a===void 0||o===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=a*16+o}return r}function Oe(...s){let e=0;for(let r=0;r<s.length;r++){const n=s[r];$(n),e+=n.length}const t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){const i=s[r];t.set(i,n),n+=i.length}return t}function Ws(s,e={}){const t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Bs(s=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(s))}const Io=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function To(s,e,t){return s&e^~s&t}function Ro(s,e,t){return s&e^s&t^e&t}class Oo{constructor(e,t,r,n){T(this,"blockLen");T(this,"outputLen");T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ar(this.buffer)}update(e){Ve(this),$(e);const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(n-this.pos,i-a);if(o===n){const c=ar(e);for(;n<=i-a;a+=n)this.process(c,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ve(this),Ds(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:a}=this;t[a++]=128,Je(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let g=a;g<n;g++)t[g]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);const o=ar(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<u;g++)o.setUint32(4*g,f[g],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),It=BigInt(2**32-1),Ms=BigInt(32);function No(s,e=!1){return e?{h:Number(s&It),l:Number(s>>Ms&It)}:{h:Number(s>>Ms&It)|0,l:Number(s&It)|0}}function Po(s,e=!1){const t=s.length;let r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){const{h:a,l:o}=No(s[i],e);[r[i],n[i]]=[a,o]}return[r,n]}const bo=(s,e,t)=>s<<t|e>>>32-t,xo=(s,e,t)=>e<<t|s>>>32-t,vo=(s,e,t)=>e<<t-32|s>>>64-t,Co=(s,e,t)=>s<<t-32|e>>>64-t,Do=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]),Pe=new Uint32Array(64);class ko extends Oo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:c}=this;return[e,t,r,n,i,a,o,c]}set(e,t,r,n,i,a,o,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,t){for(let g=0;g<16;g++,t+=4)Pe[g]=e.getUint32(t,!1);for(let g=16;g<64;g++){const S=Pe[g-15],E=Pe[g-2],m=_e(S,7)^_e(S,18)^S>>>3,y=_e(E,17)^_e(E,19)^E>>>10;Pe[g]=y+Pe[g-7]+m+Pe[g-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:c,G:u,H:f}=this;for(let g=0;g<64;g++){const S=_e(o,6)^_e(o,11)^_e(o,25),E=f+S+To(o,c,u)+Do[g]+Pe[g]|0,y=(_e(r,2)^_e(r,13)^_e(r,22))+Ro(r,n,i)|0;f=u,u=c,c=o,o=a+E|0,a=i,i=n,n=r,r=E+y|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,n,i,a,o,c,u,f)}roundClean(){Je(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Je(this.buffer)}}class Lo extends ko{constructor(){super(32);T(this,"A",Ne[0]|0);T(this,"B",Ne[1]|0);T(this,"C",Ne[2]|0);T(this,"D",Ne[3]|0);T(this,"E",Ne[4]|0);T(this,"F",Ne[5]|0);T(this,"G",Ne[6]|0);T(this,"H",Ne[7]|0)}}const Uo=Ws(()=>new Lo,Io(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const or=BigInt(0),cr=BigInt(1);function Tt(s,e=""){if(typeof s!="boolean"){const t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function Fs(s){if(typeof s=="bigint"){if(!Nt(s))throw new Error("positive bigint expected, got "+s)}else me(s);return s}function Rt(s){const e=Fs(s).toString(16);return e.length&1?"0"+e:e}function Ks(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?or:BigInt("0x"+s)}function Ot(s){return Ks(tt(s))}function Hs(s){return Ks(tt(Wo($(s)).reverse()))}function lr(s,e){me(e),s=Fs(s);const t=At(s.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Gs(s,e){return lr(s,e).reverse()}function Wo(s){return Uint8Array.from(s)}const Nt=s=>typeof s=="bigint"&&or<=s;function Bo(s,e,t){return Nt(s)&&Nt(e)&&Nt(t)&&e<=s&&s<t}function Mo(s,e,t,r){if(!Bo(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Fo(s){let e;for(e=0;s>or;s>>=cr,e+=1);return e}const dr=s=>(cr<<BigInt(s))-cr;function Ko(s,e,t){if(me(s,"hashLen"),me(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");const r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),a=Uint8Array.of(1),o=1e3;let c=r(s),u=r(s),f=0;const g=()=>{c.fill(1),u.fill(0),f=0},S=(...w)=>t(u,Oe(c,...w)),E=(w=n)=>{u=S(i,w),c=S(),w.length!==0&&(u=S(a,w),c=S())},m=()=>{if(f++>=o)throw new Error("drbg: tried max amount of iterations");let w=0;const A=[];for(;w<e;){c=S();const P=c.slice();A.push(P),w+=c.length}return Oe(...A)};return(w,A)=>{g(),E(w);let P;for(;!(P=A(m()));)E();return g(),P}}function hr(s,e={},t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(i,a,o){const c=s[i];if(o&&c===void 0)return;const u=typeof c;if(u!==a||c===null)throw new Error(`param "${i}" is invalid: expected ${a}, got ${u}`)}const n=(i,a)=>Object.entries(i).forEach(([o,c])=>r(o,c,a));n(e,!1),n(t,!0)}function $s(s){const e=new WeakMap;return(t,...r)=>{const n=e.get(t);if(n!==void 0)return n;const i=s(t,...r);return e.set(t,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),Q=BigInt(1),ve=BigInt(2),Vs=BigInt(3),Js=BigInt(4),qs=BigInt(5),Ho=BigInt(7),Ys=BigInt(8),Go=BigInt(9),zs=BigInt(16);function de(s,e){const t=s%e;return t>=se?t:e+t}function ae(s,e,t){let r=s;for(;e-- >se;)r*=r,r%=t;return r}function Xs(s,e){if(s===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let t=de(s,e),r=e,n=se,i=Q;for(;t!==se;){const o=r/t,c=r%t,u=n-i*o;r=t,t=c,n=i,i=u}if(r!==Q)throw new Error("invert: does not exist");return de(n,e)}function ur(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function js(s,e){const t=(s.ORDER+Q)/Js,r=s.pow(e,t);return ur(s,r,e),r}function $o(s,e){const t=(s.ORDER-qs)/Ys,r=s.mul(e,ve),n=s.pow(r,t),i=s.mul(e,n),a=s.mul(s.mul(i,ve),n),o=s.mul(i,s.sub(a,s.ONE));return ur(s,o,e),o}function Vo(s){const e=Pt(s),t=Zs(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),a=(s+Ho)/zs;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,r);const g=o.mul(u,n),S=o.mul(u,i),E=o.eql(o.sqr(f),c),m=o.eql(o.sqr(g),c);u=o.cmov(u,f,E),f=o.cmov(S,g,m);const y=o.eql(o.sqr(f),c),w=o.cmov(u,f,y);return ur(o,w,c),w}}function Zs(s){if(s<Vs)throw new Error("sqrt is not defined for small field");let e=s-Q,t=0;for(;e%ve===se;)e/=ve,t++;let r=ve;const n=Pt(s);for(;en(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return js;let i=n.pow(r,e);const a=(e+Q)/ve;return function(c,u){if(c.is0(u))return u;if(en(c,u)!==1)throw new Error("Cannot find square root");let f=t,g=c.mul(c.ONE,i),S=c.pow(u,e),E=c.pow(u,a);for(;!c.eql(S,c.ONE);){if(c.is0(S))return c.ZERO;let m=1,y=c.sqr(S);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===f)throw new Error("Cannot find square root");const w=Q<<BigInt(f-m-1),A=c.pow(g,w);f=m,g=c.sqr(A),S=c.mul(S,g),E=c.mul(E,A)}return E}}function Jo(s){return s%Js===Vs?js:s%Ys===qs?$o:s%zs===Go?Vo(s):Zs(s)}const qo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=qo.reduce((r,n)=>(r[n]="function",r),e);return hr(s,t),s}function zo(s,e,t){if(t<se)throw new Error("invalid exponent, negatives unsupported");if(t===se)return s.ONE;if(t===Q)return e;let r=s.ONE,n=e;for(;t>se;)t&Q&&(r=s.mul(r,n)),n=s.sqr(n),t>>=Q;return r}function Qs(s,e,t=!1){const r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((a,o,c)=>s.is0(o)?a:(r[c]=a,s.mul(a,o)),s.ONE),i=s.inv(n);return e.reduceRight((a,o,c)=>s.is0(o)?a:(r[c]=s.mul(a,r[c]),s.mul(a,o)),i),r}function en(s,e){const t=(s.ORDER-Q)/ve,r=s.pow(e,t),n=s.eql(r,s.ONE),i=s.eql(r,s.ZERO),a=s.eql(r,s.neg(s.ONE));if(!n&&!i&&!a)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Xo(s,e){e!==void 0&&me(e);const t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}class jo{constructor(e,t={}){T(this,"ORDER");T(this,"BITS");T(this,"BYTES");T(this,"isLE");T(this,"ZERO",se);T(this,"ONE",Q);T(this,"_lengths");T(this,"_sqrt");T(this,"_mod");var a;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=(a=t.allowedLengths)==null?void 0:a.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));const{nBitLength:n,nByteLength:i}=Xo(e,r);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 de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return de(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return de(e*e,this.ORDER)}add(e,t){return de(e+t,this.ORDER)}sub(e,t){return de(e-t,this.ORDER)}mul(e,t){return de(e*t,this.ORDER)}pow(e,t){return zo(this,e,t)}div(e,t){return de(e*Xs(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Xs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Jo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Gs(e,this.BYTES):lr(e,this.BYTES)}fromBytes(e,t=!1){$(e);const{_lengths:r,BYTES:n,isLE:i,ORDER:a,_mod:o}=this;if(r){if(!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Hs(e):Ot(e);if(o&&(c=de(c,a)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Qs(this,e)}cmov(e,t,r){return r?t:e}}function Pt(s,e={}){return new jo(s,e)}function tn(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function rn(s){const e=tn(s);return e+Math.ceil(e/2)}function Zo(s,e,t=!1){$(s);const r=s.length,n=tn(e),i=rn(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=t?Hs(s):Ot(s),o=de(a,e-Q)+Q;return t?Gs(o,n):lr(o,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),Ce=BigInt(1);function bt(s,e){const t=e.negate();return s?t:e}function sn(s,e){const t=Qs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function nn(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function fr(s,e){nn(s,e);const t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=dr(s),a=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:a}}function an(s,e,t){const{windowSize:r,mask:n,maxNumber:i,shiftBy:a}=t;let o=Number(s&n),c=s>>a;o>r&&(o-=i,c+=Ce);const u=e*r,f=u+Math.abs(o)-1,g=o===0,S=o<0,E=e%2!==0;return{nextN:c,offset:f,isZero:g,isNeg:S,isNegF:E,offsetF:u}}const gr=new WeakMap,on=new WeakMap;function _r(s){return on.get(s)||1}function cn(s){if(s!==qe)throw new Error("invalid wNAF")}class Qo{constructor(e,t){T(this,"BASE");T(this,"ZERO");T(this,"Fn");T(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>qe;)t&Ce&&(r=r.add(n)),n=n.double(),t>>=Ce;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=fr(t,this.bits),i=[];let a=e,o=a;for(let c=0;c<r;c++){o=a,i.push(o);for(let u=1;u<n;u++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const a=fr(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:g,isNegF:S,offsetF:E}=an(r,o,a);r=c,f?i=i.add(bt(S,t[E])):n=n.add(bt(g,t[u]))}return cn(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=fr(e,this.bits);for(let a=0;a<i.windows&&r!==qe;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=an(r,a,i);if(r=o,!u){const g=t[c];n=n.add(f?g.negate():g)}}return cn(r),n}getPrecomputes(e,t,r){let n=gr.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),gr.set(t,n))),n}cached(e,t,r){const n=_r(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=_r(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){nn(t,this.bits),on.set(e,t),gr.delete(e)}hasCache(e){return _r(e)!==1}}function ec(s,e,t,r){let n=e,i=s.ZERO,a=s.ZERO;for(;t>qe||r>qe;)t&Ce&&(i=i.add(n)),r&Ce&&(a=a.add(n)),n=n.double(),t>>=Ce,r>>=Ce;return{p1:i,p2:a}}function ln(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yo(e),e}else return Pt(s,{isLE:t})}function tc(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ln(e.p,t.Fp,r),i=ln(e.n,t.Fn,r),o=["Gx","Gy","a","b"];for(const c of o)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 rc(s,e){return function(r){const n=s(r);return{secretKey:n,publicKey:e(n)}}}class dn{constructor(e,t){T(this,"oHash");T(this,"iHash");T(this,"blockLen");T(this,"outputLen");T(this,"finished",!1);T(this,"destroyed",!1);if(Cs(e),$(t,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 r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);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),Je(n)}update(e){return Ve(this),this.iHash.update(e),this}digestInto(e){Ve(this),$(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:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hn=(s,e,t)=>new dn(s,e).update(t).digest();hn.create=(s,e)=>new dn(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=(s,e)=>(s+(s>=0?e:-e)/fn)/e;function sc(s,e,t){const[[r,n],[i,a]]=e,o=un(a*s,t),c=un(-n*s,t);let u=s-o*r-c*i,f=-o*n-c*a;const g=u<Ae,S=f<Ae;g&&(u=-u),S&&(f=-f);const E=dr(Math.ceil(Fo(t)/2))+Ye;if(u<Ae||u>=E||f<Ae||f>=E)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:g,k1:u,k2neg:S,k2:f}}function pr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function wr(s,e){const t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Tt(t.lowS,"lowS"),Tt(t.prehash,"prehash"),t.format!==void 0&&pr(t.format),t}class nc extends Error{constructor(e=""){super(e)}}const be={Err:nc,_tlv:{encode:(s,e)=>{const{Err:t}=be;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,n=Rt(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");const i=r>127?Rt(n.length/2|128):"";return Rt(s)+i+n+e},decode(s,e){const{Err:t}=be;let r=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");const n=e[r++],i=!!(n&128);let a=0;if(!i)a=n;else{const c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const f of u)a=a<<8|f;if(r+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}const o=e.subarray(r,r+a);if(o.length!==a)throw new t("tlv.decode: wrong value length");return{v:o,l:e.subarray(r+a)}}},_int:{encode(s){const{Err:e}=be;if(s<Ae)throw new e("integer: negative integers are not allowed");let t=Rt(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){const{Err:e}=be;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Ot(s)}},toSig(s){const{Err:e,_int:t,_tlv:r}=be,n=$(s,void 0,"signature"),{v:i,l:a}=r.decode(48,n);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=r.decode(2,i),{v:u,l:f}=r.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(o),s:t.decode(u)}},hexFromSig(s){const{_tlv:e,_int:t}=be,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Ae=BigInt(0),Ye=BigInt(1),fn=BigInt(2),xt=BigInt(3),ic=BigInt(4);function ac(s,e={}){const t=tc("weierstrass",s,e),{Fp:r,Fn:n}=t;let i=t.CURVE;const{h:a,n:o}=i;hr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=_n(r,n);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(k,_,p){const{x:I,y:R}=_.toAffine(),b=r.toBytes(I);if(Tt(p,"isCompressed"),p){f();const N=!r.isOdd(R);return Oe(gn(N),b)}else return Oe(Uint8Array.of(4),b,r.toBytes(R))}function S(k){$(k,void 0,"Point");const{publicKey:_,publicKeyUncompressed:p}=u,I=k.length,R=k[0],b=k.subarray(1);if(I===_&&(R===2||R===3)){const N=r.fromBytes(b);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const x=y(N);let O;try{O=r.sqrt(x)}catch(Y){const G=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();const C=r.isOdd(O);return(R&1)===1!==C&&(O=r.neg(O)),{x:N,y:O}}else if(I===p&&R===4){const N=r.BYTES,x=r.fromBytes(b.subarray(0,N)),O=r.fromBytes(b.subarray(N,N*2));if(!w(x,O))throw new Error("bad point: is not on curve");return{x,y:O}}else throw new Error(`bad point: got length ${I}, expected compressed=${_} or uncompressed=${p}`)}const E=e.toBytes||g,m=e.fromBytes||S;function y(k){const _=r.sqr(k),p=r.mul(_,k);return r.add(r.add(p,r.mul(k,i.a)),i.b)}function w(k,_){const p=r.sqr(_),I=y(k);return r.eql(p,I)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(i.a,xt),ic),P=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(A,P)))throw new Error("bad curve params: a or b");function F(k,_,p=!1){if(!r.isValid(_)||p&&r.is0(_))throw new Error(`bad point coordinate ${k}`);return _}function M(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function V(k){if(!c||!c.basises)throw new Error("no endo");return sc(k,c.basises,n.ORDER)}const U=$s((k,_)=>{const{X:p,Y:I,Z:R}=k;if(r.eql(R,r.ONE))return{x:p,y:I};const b=k.is0();_==null&&(_=b?r.ONE:r.inv(R));const N=r.mul(p,_),x=r.mul(I,_),O=r.mul(R,_);if(b)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:N,y:x}}),H=$s(k=>{if(k.is0()){if(e.allowInfinityPoint&&!r.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:p}=k.toAffine();if(!r.isValid(_)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!w(_,p))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(k,_,p,I,R){return p=new v(r.mul(p.X,k),p.Y,p.Z),_=bt(I,_),p=bt(R,p),_.add(p)}const K=class K{constructor(_,p,I){T(this,"X");T(this,"Y");T(this,"Z");this.X=F("x",_),this.Y=F("y",p,!0),this.Z=F("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){const{x:p,y:I}=_||{};if(!_||!r.isValid(p)||!r.isValid(I))throw new Error("invalid affine point");if(_ instanceof K)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(I)?K.ZERO:new K(p,I,r.ONE)}static fromBytes(_){const p=K.fromAffine(m($(_,void 0,"point")));return p.assertValidity(),p}static fromHex(_){return K.fromBytes(At(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,p=!0){return B.createCache(this,_),p||this.multiply(xt),this}assertValidity(){H(this)}hasEvenY(){const{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_,O=r.eql(r.mul(p,x),r.mul(b,R)),C=r.eql(r.mul(I,x),r.mul(N,R));return O&&C}negate(){return new K(this.X,r.neg(this.Y),this.Z)}double(){const{a:_,b:p}=i,I=r.mul(p,xt),{X:R,Y:b,Z:N}=this;let x=r.ZERO,O=r.ZERO,C=r.ZERO,L=r.mul(R,R),Y=r.mul(b,b),G=r.mul(N,N),D=r.mul(R,b);return D=r.add(D,D),C=r.mul(R,N),C=r.add(C,C),x=r.mul(_,C),O=r.mul(I,G),O=r.add(x,O),x=r.sub(Y,O),O=r.add(Y,O),O=r.mul(x,O),x=r.mul(D,x),C=r.mul(I,C),G=r.mul(_,G),D=r.sub(L,G),D=r.mul(_,D),D=r.add(D,C),C=r.add(L,L),L=r.add(C,L),L=r.add(L,G),L=r.mul(L,D),O=r.add(O,L),G=r.mul(b,N),G=r.add(G,G),L=r.mul(G,D),x=r.sub(x,L),C=r.mul(G,Y),C=r.add(C,C),C=r.add(C,C),new K(x,O,C)}add(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_;let O=r.ZERO,C=r.ZERO,L=r.ZERO;const Y=i.a,G=r.mul(i.b,xt);let D=r.mul(p,b),X=r.mul(I,N),te=r.mul(R,x),ne=r.add(p,I),J=r.add(b,N);ne=r.mul(ne,J),J=r.add(D,X),ne=r.sub(ne,J),J=r.add(p,R);let re=r.add(b,x);return J=r.mul(J,re),re=r.add(D,te),J=r.sub(J,re),re=r.add(I,R),O=r.add(N,x),re=r.mul(re,O),O=r.add(X,te),re=r.sub(re,O),L=r.mul(Y,J),O=r.mul(G,te),L=r.add(O,L),O=r.sub(X,L),L=r.add(X,L),C=r.mul(O,L),X=r.add(D,D),X=r.add(X,D),te=r.mul(Y,te),J=r.mul(G,J),X=r.add(X,te),te=r.sub(D,te),te=r.mul(Y,te),J=r.add(J,te),D=r.mul(X,J),C=r.add(C,D),D=r.mul(re,J),O=r.mul(ne,O),O=r.sub(O,D),D=r.mul(ne,X),L=r.mul(re,L),L=r.add(L,D),new K(O,C,L)}subtract(_){return this.add(_.negate())}is0(){return this.equals(K.ZERO)}multiply(_){const{endo:p}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let I,R;const b=N=>B.cached(this,N,x=>sn(K,x));if(p){const{k1neg:N,k1:x,k2neg:O,k2:C}=V(_),{p:L,f:Y}=b(x),{p:G,f:D}=b(C);R=Y.add(D),I=Z(p.beta,L,G,N,O)}else{const{p:N,f:x}=b(_);I=N,R=x}return sn(K,[I,R])[0]}multiplyUnsafe(_){const{endo:p}=e,I=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ae||I.is0())return K.ZERO;if(_===Ye)return I;if(B.hasCache(this))return this.multiply(_);if(p){const{k1neg:R,k1:b,k2neg:N,k2:x}=V(_),{p1:O,p2:C}=ec(K,I,b,x);return Z(p.beta,O,C,R,N)}else return B.unsafe(I,_)}toAffine(_){return U(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return a===Ye?!0:_?_(K,this):B.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:_}=e;return a===Ye?this:_?_(K,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(_=!0){return Tt(_,"isCompressed"),this.assertValidity(),E(K,this,_)}toHex(_=!0){return tt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};T(K,"BASE",new K(i.Gx,i.Gy,r.ONE)),T(K,"ZERO",new K(r.ZERO,r.ONE,r.ZERO)),T(K,"Fp",r),T(K,"Fn",n);let v=K;const ee=n.BITS,B=new Qo(v,e.endo?Math.ceil(ee/2):ee);return v.BASE.precompute(8),v}function gn(s){return Uint8Array.of(s?2:3)}function _n(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function oc(s,e={}){const{Fn:t}=s,r=e.randomBytes||Bs,n=Object.assign(_n(s.Fp,t),{seed:rn(t.ORDER)});function i(E){try{const m=t.fromBytes(E);return t.isValidNot0(m)}catch{return!1}}function a(E,m){const{publicKey:y,publicKeyUncompressed:w}=n;try{const A=E.length;return m===!0&&A!==y||m===!1&&A!==w?!1:!!s.fromBytes(E)}catch{return!1}}function o(E=r(n.seed)){return Zo($(E,n.seed,"seed"),t.ORDER)}function c(E,m=!0){return s.BASE.multiply(t.fromBytes(E)).toBytes(m)}function u(E){const{secretKey:m,publicKey:y,publicKeyUncompressed:w}=n;if(!ir(E)||"_lengths"in t&&t._lengths||m===y)return;const A=$(E,void 0,"key").length;return A===y||A===w}function f(E,m,y=!0){if(u(E)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");const w=t.fromBytes(E);return s.fromBytes(m).multiply(w).toBytes(y)}const g={isValidSecretKey:i,isValidPublicKey:a,randomSecretKey:o},S=rc(o,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:S,Point:s,utils:g,lengths:n})}function cc(s,e,t={}){Cs(e),hr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);const r=t.randomBytes||Bs,n=t.hmac||((_,p)=>hn(e,_,p)),{Fp:i,Fn:a}=s,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E}=oc(s,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},y=o*fn<i.ORDER;function w(_){const p=o>>Ye;return _>p}function A(_,p){if(!a.isValidNot0(p))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return p}function P(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(_,p){pr(p);const I=E.signature,R=p==="compact"?I:p==="recovered"?I+1:void 0;return $(_,R)}class M{constructor(p,I,R){T(this,"r");T(this,"s");T(this,"recovery");if(this.r=A("r",p),this.s=A("s",I),R!=null){if(P(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(p,I=m.format){F(p,I);let R;if(I==="der"){const{r:O,s:C}=be.toSig($(p));return new M(O,C)}I==="recovered"&&(R=p[0],I="compact",p=p.subarray(1));const b=E.signature/2,N=p.subarray(0,b),x=p.subarray(b,b*2);return new M(a.fromBytes(N),a.fromBytes(x),R)}static fromHex(p,I){return this.fromBytes(At(p),I)}assertRecovery(){const{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new M(this.r,this.s,p)}recoverPublicKey(p){const{r:I,s:R}=this,b=this.assertRecovery(),N=b===2||b===3?I+o:I;if(!i.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const x=i.toBytes(N),O=s.fromBytes(Oe(gn((b&1)===0),x)),C=a.inv(N),L=U($(p,void 0,"msgHash")),Y=a.create(-L*C),G=a.create(R*C),D=s.BASE.multiplyUnsafe(Y).add(O.multiplyUnsafe(G));if(D.is0())throw new Error("invalid recovery: point at infinify");return D.assertValidity(),D}hasHighS(){return w(this.s)}toBytes(p=m.format){if(pr(p),p==="der")return At(be.hexFromSig(this));const{r:I,s:R}=this,b=a.toBytes(I),N=a.toBytes(R);return p==="recovered"?(P(),Oe(Uint8Array.of(this.assertRecovery()),b,N)):Oe(b,N)}toHex(p){return tt(this.toBytes(p))}}const V=t.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const I=Ot(p),R=p.length*8-c;return R>0?I>>BigInt(R):I},U=t.bits2int_modN||function(p){return a.create(V(p))},H=dr(c);function Z(_){return Mo("num < 2^"+c,_,Ae,H),a.toBytes(_)}function v(_,p){return $(_,void 0,"message"),p?$(e(_),void 0,"prehashed message"):_}function ee(_,p,I){const{lowS:R,prehash:b,extraEntropy:N}=wr(I,m);_=v(_,b);const x=U(_),O=a.fromBytes(p);if(!a.isValidNot0(O))throw new Error("invalid private key");const C=[Z(O),Z(x)];if(N!=null&&N!==!1){const D=N===!0?r(E.secretKey):N;C.push($(D,void 0,"extraEntropy"))}const L=Oe(...C),Y=x;function G(D){const X=V(D);if(!a.isValidNot0(X))return;const te=a.inv(X),ne=s.BASE.multiply(X).toAffine(),J=a.create(ne.x);if(J===Ae)return;const re=a.create(te*a.create(Y+J*O));if(re===Ae)return;let vn=(ne.x===J?0:2)|Number(ne.y&Ye),Cn=re;return R&&w(re)&&(Cn=a.neg(re),vn^=1),new M(J,Cn,y?void 0:vn)}return{seed:L,k2sig:G}}function B(_,p,I={}){const{seed:R,k2sig:b}=ee(_,p,I);return Ko(e.outputLen,a.BYTES,n)(R,b).toBytes(I.format)}function K(_,p,I,R={}){const{lowS:b,prehash:N,format:x}=wr(R,m);if(I=$(I,void 0,"publicKey"),p=v(p,N),!ir(_)){const O=_ instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}F(_,x);try{const O=M.fromBytes(_,x),C=s.fromBytes(I);if(b&&O.hasHighS())return!1;const{r:L,s:Y}=O,G=U(p),D=a.inv(Y),X=a.create(G*D),te=a.create(L*D),ne=s.BASE.multiplyUnsafe(X).add(C.multiplyUnsafe(te));return ne.is0()?!1:a.create(ne.x)===L}catch{return!1}}function k(_,p,I={}){const{prehash:R}=wr(I,m);return p=v(p,R),M.fromBytes(_,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E,Point:s,sign:B,verify:K,recoverPublicKey:k,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},lc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},pn=BigInt(2);function dc(s){const e=Sr.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=s*s*s%e,f=u*u*s%e,g=ae(f,t,e)*f%e,S=ae(g,t,e)*f%e,E=ae(S,pn,e)*u%e,m=ae(E,n,e)*E%e,y=ae(m,i,e)*m%e,w=ae(y,o,e)*y%e,A=ae(w,c,e)*w%e,P=ae(A,o,e)*y%e,F=ae(P,t,e)*f%e,M=ae(F,a,e)*m%e,V=ae(M,r,e)*u%e,U=ae(V,pn,e);if(!Er.eql(Er.sqr(U),s))throw new Error("Cannot find square root");return U}const Er=Pt(Sr.p,{sqrt:dc}),hc=cc(ac(Sr,{Fp:Er,endo:lc}),Uo),uc=BigInt(0),rt=BigInt(1),fc=BigInt(2),gc=BigInt(7),_c=BigInt(256),pc=BigInt(113),wn=[],Sn=[],En=[];for(let s=0,e=rt,t=1,r=0;s<24;s++){[t,r]=[r,(2*t+3*r)%5],wn.push(2*(5*r+t)),Sn.push((s+1)*(s+2)/2%64);let n=uc;for(let i=0;i<7;i++)e=(e<<rt^(e>>gc)*pc)%_c,e&fc&&(n^=rt<<(rt<<BigInt(i))-rt);En.push(n)}const mn=Po(En,!0),wc=mn[0],Sc=mn[1],yn=(s,e,t)=>t>32?vo(s,e,t):bo(s,e,t),An=(s,e,t)=>t>32?Co(s,e,t):xo(s,e,t);function Ec(s,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let a=0;a<10;a++)t[a]=s[a]^s[a+10]^s[a+20]^s[a+30]^s[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=t[c],f=t[c+1],g=yn(u,f,1)^t[o],S=An(u,f,1)^t[o+1];for(let E=0;E<50;E+=10)s[a+E]^=g,s[a+E+1]^=S}let n=s[2],i=s[3];for(let a=0;a<24;a++){const o=Sn[a],c=yn(n,i,o),u=An(n,i,o),f=wn[a];n=s[f],i=s[f+1],s[f]=c,s[f+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=s[a+o];for(let o=0;o<10;o++)s[a+o]^=~t[(o+2)%10]&t[(o+4)%10]}s[0]^=wc[r],s[1]^=Sc[r]}Je(t)}class mr{constructor(e,t,r,n=!1,i=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,me(r,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=So(this.state)}clone(){return this._cloneInto()}keccak(){ks(this.state32),Ec(this.state32,this.rounds),ks(this.state32),this.posOut=0,this.pos=0}update(e){Ve(this),$(e);const{blockLen:t,state:r}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(t-this.pos,n-i);for(let o=0;o<a;o++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,(t&128)!==0&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ve(this,!1),$(e),this.finish();const t=this.state,{blockLen:r}=this;for(let n=0,i=e.length;n<i;){this.posOut>=r&&this.keccak();const a=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+a),n),this.posOut+=a,n+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return me(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ds(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,Je(this.state)}_cloneInto(e){const{blockLen:t,suffix:r,outputLen:n,rounds:i,enableXOF:a}=this;return e||(e=new mr(t,r,n,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=a,e.destroyed=this.destroyed,e}}const In=((s,e,t,r={})=>Ws(()=>new mr(e,s,t),r))(1,136,32),mc=60;class yc{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=_o(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(t){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",t)}}async verifyJWT(e,t){try{const r=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:r.sub,exp:r.exp,iat:r.iat});const n=Math.floor(Date.now()/1e3);if(r.exp&&r.exp+mc<n)return d.warn("[CROSSx] 토큰 만료:",{exp:r.exp,now:n,만료시간:new Date(r.exp*1e3).toISOString()}),{payload:r,valid:!1,signatureVerified:!1};if(!r.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:r,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await io(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:r,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:r,valid:!0,signatureVerified:!1}}catch(r){throw d.error("[CROSSx] JWT 검증 중 에러:",r),r}}decodeJWT(e){return wo(e)}recoverPersonalSignSigner(e,t){const r=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
7
7
|
${r.length}`),i=new Uint8Array(n.length+r.length);i.set(n,0),i.set(r,n.length);const a=In(i),o=t.startsWith("0x")?t.slice(2):t;if(o.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${o.length}`);const c=Ac(o),u=c.slice(0,32),f=c.slice(32,64),g=c[64],S=g>=27?g-27:g,y=new hc.Signature(Tn(u),Tn(f)).addRecoveryBit(S).recoverPublicKey(a).toBytes(!1).slice(1),w=In(y);return"0x"+tt(w.slice(12))}}function Ac(s){const e=new Uint8Array(s.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(s.substring(t*2,t*2+2),16);return e}function Tn(s){let e="0x";for(const t of s)e+=t.toString(16).padStart(2,"0");return BigInt(e)}const Ic=5e3;class Tc{constructor(e,t){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.required=!1,this.adapterConfig=e,this.transport=t}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const t=this.required;if(!t&&this.hasFreshFailure())return e;try{const{version:r,key:n}=await this.currentKey(),i=await Rc(n,e);return`${r}.${Oc(i)}`}catch(r){if(t)throw this.keyFailedAt=Date.now(),r instanceof h?r:new h(l.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(r)});return this.keyFailedAt=Date.now(),d.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(Pr/1e3)}초 후 재확인)`),e}}invalidate(){d.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(d.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<Pr}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<Mn?{version:this.cachedVersion,key:this.cachedKey}:this.keyInFlight?this.keyInFlight:(this.keyInFlight=this.fetchAndImportKey().then(e=>(this.cachedVersion=e.version,this.cachedKey=e.key,this.cachedAt=Date.now(),this.keyFailedAt=0,d.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=Rn();if(!e)throw new h(l.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다. HTTPS 환경에서 다시 시도해 주세요.");const t=await this.transport.request({url:`${this.baseUrl}/pin-key`,method:"GET",headers:{"X-Project-Id":this.adapterConfig.projectId},timeoutMs:Ic}),r=xc(t.data);if(!(r!=null&&r.keyVersion)||!(r!=null&&r.publicKey))throw new h(l.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const n=Pc(r.publicKey),i=await e.importKey("spki",bc(n),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:r.keyVersion,key:i}}}async function Rc(s,e){const t=Rn();if(!t)throw new h(l.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const r=await t.encrypt({name:"RSA-OAEP"},s,new TextEncoder().encode(e));return new Uint8Array(r)}function Rn(){const s=globalThis.crypto;return(s==null?void 0:s.subtle)??null}function Oc(s){return Nc(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Nc(s){let e="";for(let t=0;t<s.length;t+=3){const r=s[t],n=s[t+1],i=s[t+2];e+=st[r>>2],e+=st[(r&3)<<4|(n??0)>>4],e+=n===void 0?"=":st[(n&15)<<2|(i??0)>>6],e+=i===void 0?"=":st[i&63]}return e}function Pc(s){const e=s.replace(/-----BEGIN [A-Z ]+-----/g,"").replace(/-----END [A-Z ]+-----/g,"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4===0?e:e+"=".repeat(4-e.length%4),r=[];for(let n=0;n<t.length;n+=4){const i=[0,1,2,3].map(a=>{const o=t[n+a];if(o==="="||o===void 0)return-1;const c=st.indexOf(o);if(c===-1)throw new h(l.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return c});r.push((i[0]&63)<<2|(i[1]&63)>>4),i[2]!==-1&&r.push((i[1]&15)<<4|(i[2]&63)>>2),i[3]!==-1&&r.push((i[2]&3)<<6|i[3]&63)}return new Uint8Array(r)}function bc(s){const e=new Uint8Array(s.length);return e.set(s),e.buffer}function xc(s){if(!s||typeof s!="object")return null;const e=s;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new h(l.PIN_ENCRYPTION_FAILED,`pin-key 조회 실패 (${e.code}): ${String(e.message??e.data??"")}`);const t=e.data;if(t&&typeof t=="object")return t}return typeof e.keyVersion=="string"&&typeof e.publicKey=="string"?e:null}const vc=3e4,Cc=1e3;class Dc{async request(e){const t=e.retries??0;for(let r=0;r<=t;r++){try{const n=await this._doRequest(e);if(n.status<500||r===t)return n}catch(n){if(r===t)throw n}await new Promise(n=>setTimeout(n,Cc*2**r))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs??vc);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:t.signal,credentials:e.credentials});let i;const a=await n.text();try{i=a?JSON.parse(a):null}catch{i={_raw:a}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(r)}}}function kc(s){const e={raw:s},t=s.search(/(^|;)\s*info=/i),r=t>=0?s.slice(0,t):s;if(t>=0){const n=s.slice(t).replace(/^;?\s*info=/i,"").trim();n&&(e.infoUrl=n)}for(const n of r.split(";")){const[i,...a]=n.split("=");if((i==null?void 0:i.trim().toLowerCase())==="sunset"){const o=a.join("=").trim();o&&(e.sunset=o)}}return e}function On(s){try{return new URL(s).origin}catch{return null}}class Lc{constructor(e,t){this.inner=e,this.options=t}async request(e){if(!this.isGateway(e.url))return this.inner.request(e);const t=await this.inner.request(this.options.sendVersionHeader===!1?e:{...e,headers:{...e.headers,[Fn]:this.options.version}});return this.inspect(t),t}isGateway(e){const t=On(e);return t===null?!1:this.options.getGatewayBaseUrls().some(r=>On(r)===t)}inspect(e){var n,i,a,o;const t=Wc(e.headers,Hn);t&&((i=(n=this.options).onDeprecation)==null||i.call(n,kc(t)));const r=e.data;r&&r.code===ct&&((o=(a=this.options).onUnsupported)==null||o.call(a,{message:Uc(r)}))}}function Uc(s){for(const e of[s.data,s.message])if(typeof e=="string"&&e.trim())return e}function Wc(s,e){if(!s)return;const t=e.toLowerCase();for(const[r,n]of Object.entries(s))if(r.toLowerCase()===t&&n)return n}const Bc=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function yr(){return typeof window>"u"?void 0:window}function Mc(){const s=yr();return s==null?void 0:s.__crossx}function Fc(s){return s==="ios"||s==="android"?s:null}function Ar(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function Kc(s,e){const t=a=>a.split(/[^\d]+/).filter(o=>o!=="").map(o=>Number.parseInt(o,10)),r=t(s),n=t(e),i=Math.max(r.length,n.length);for(let a=0;a<i;a+=1){const o=(r[a]??0)-(n[a]??0);if(o!==0)return o}return 0}function Hc(){const s=yr();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function Nn(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of Bc){const t=e.exec(s);if(t)return t[1]??null}}function nt(){const s=Mc();if(s!=null&&s.browser)return{version:s.version??null,platform:Fc(s.platform)??Ar(),detectedBy:"marker"};if(Hc())return{version:Nn()??null,platform:Ar(),detectedBy:"bridge"};const e=Nn();return e!==void 0?{version:e,platform:Ar(),detectedBy:"user-agent"}:null}function Gc(){return nt()!==null}function $c(s=3e3){const e=nt();return e?Promise.resolve(e):yr()?new Promise(t=>{const r=Date.now(),n=setInterval(()=>{const i=nt();if(i){clearInterval(n),t(i);return}Date.now()-r>=s&&(clearInterval(n),t(null))},50)}):Promise.resolve(null)}const Vc=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://one-wallet-oauth.onechain.nexus","https://stg-one-wallet-oauth.onechain.nexus","https://dev-one-wallet-oauth.onechain.nexus"]),Jc="crossx://oauth-callback",qc="2.3.2";function Yc(s){return s.platform!=="ios"?!1:s.version?Kc(s.version,qc)<=0:!0}class De{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const t=this.abortPending;t&&(d.log("[CROSSx] OAuth 대기 중단 —",e),t(e))}static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const t=e.split(".");if(t.length<2)throw new Error("Invalid JWT format");const r=(t[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(r);return JSON.parse(n)}static async sha256Hex(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,t){const r=De.parseJwtPayload(e),n=r.nonce,i=typeof r.iss=="string"?r.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:r.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(r)});return}if(i.includes("appleid.apple.com")){const a=await De.sha256Hex(t);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:a.length,receivedHashLength:n.length,match:n===a}),n!==a)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:t.length,receivedLength:n.length,match:n===t}),n!==t)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((t,r)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),a=window.screenX+(window.outerWidth-n)/2,o=window.screenY+(window.outerHeight-i)/2,c=De.generateRandom16Hex(),u=De.generateRandom16Hex(),f=nt();let g=e.authUrl;f&&e.legacyAuthUrl&&Yc(f)&&(g=e.legacyAuthUrl,d.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:f.version??"(unknown)",detectedBy:f.detectedBy,authUrlBase:e.legacyAuthUrl}));const S=g.includes("?")?"&":"?",E=encodeURIComponent(window.location.origin);let m=`${g}${S}state=${c}&nonce=${u}&origin=${E}`;f&&!m.includes("redirectUrl=")&&(m+=`&redirectUrl=${encodeURIComponent(Jc)}`,d.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:f.detectedBy,appVersion:f.version??"(unknown)",platform:f.platform??"(unknown)"})),d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:u.length,authUrlBase:g});const y=window.open(m,f?"_blank":"CROSSx OAuth",`width=${n},height=${i},left=${a},top=${o}`);if(!y){r(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),H(),r(new Error("Authentication timeout"))},300*1e3),A=10,P=30;let F=0,M=null;const V=()=>{clearInterval(U),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+P+"초간 대기합니다"),M=setTimeout(()=>{H(),r(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},P*1e3)},U=setInterval(()=>{F++;try{if(!y.closed)return;if(!!f){H(),r(new h(l.USER_REJECTED,"로그인이 취소되었습니다"));return}const ee=typeof document<"u"&&document.hasFocus();F<=A&&!ee?V():(H(),r(new h(l.USER_REJECTED,"로그인이 취소되었습니다")))}catch{V()}},1e3),H=()=>{this.abortPending=null,clearTimeout(w),clearInterval(U),M&&clearTimeout(M),window.removeEventListener("message",Z)},Z=v=>{if(!Vc.has(v.origin))return;H();const ee=typeof v.data.status=="string",B=ee?v.data.data??{}:v.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ee?"wrapped":"flat",status:ee?v.data.status:"(flat)"});const K=(B==null?void 0:B.state)??v.data.state;if(!K||K!==c){r(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ee&&v.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",B==null?void 0:B.error),r(new Error((B==null?void 0:B.error)||"Authentication failed"));return}if(!ee&&(B!=null&&B.error)){d.error("[CROSSx] OAuth 실패:",B.error),r(new Error(B.error||"Authentication failed"));return}const k=B==null?void 0:B.idToken,_=B==null?void 0:B.accessToken,p=_??k,I=(B==null?void 0:B.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!k,hasEmail:!!I}),!p){d.error("[CROSSx] 토큰을 찾을 수 없음:",v.data),r(new Error("Token not found in response"));return}const R={token:p,email:I},b=N=>{De.verifyIdTokenNonce(N,u).then(()=>t(R)).catch(x=>{d.error("[CROSSx] nonce 검증 실패:",x),r(x instanceof Error?x:new Error("nonce verification failed"))})};_?_.split(".").length===3?b(_):k?b(k):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),t(R)):k?b(k):r(new Error("Token not found in response"))};this.abortPending=v=>{H(),r(new Error(v))},window.addEventListener("message",Z)})}}const it="crossx_wallet_data",ze="crossx_mock_pin_hash";class zc{constructor(e,t){this.storage=e,this.pinStore=t??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const t=await this.storage.get(it)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${t}`),t}async getOrCreateWallet(e){var t;try{const r=await this.storage.get(it);if(r)return r;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(it,n);const i=(t=this.pinStore)==null?void 0:t.get();return i&&(await this.storage.set(ze,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(r){throw new h(l.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",r)}}async getAddresses(e){const t=await this.storage.get(it);return t?[{address:t.address,index:0}]:[]}async getAddress(e,t){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${t}`}}async prepare(e,t){const r="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${r}`),{uuid:r,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,t,r,n=0,i,a){return d.log(`[Mock] signMessage chainId=${t} index=${n} uuid=${i} from=${a}: "${r}"`),{chainId:t,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,t,r,n=0,i,a){return d.log(`[Mock] signTypedData chainId=${t} index=${n} uuid=${i} from=${a}`),{chainId:t,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,t,r,n=0,i){d.log(`[Mock] signTransaction chainId=${t} index=${n} uuid=${i}:`,r);const a="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:t,signature:this.generateMockSignature(),txHash:a,format:"hex"}}async sendTransaction(e,t,r,n){return d.log(`[Mock] sendTransaction chainId=${t} uuid=${n}:`,r),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var r;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const t=await this.storage.get(ze);return t&&t!==e?!1:(t||await this.storage.set(ze,e),(r=this.pinStore)==null||r.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,t){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new h(l.PIN_WRONG,"Incorrect PIN.");const r=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(ze);if(n&&r&&n!==r)throw new h(l.PIN_WRONG,"Incorrect PIN.");await this.storage.set(ze,t),d.log("[Mock] changePin 완료")}async migrateWallet(e,t){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${t}`),this.migrateScenario==="wrong_pin")throw new h(l.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 o={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new h(l.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",o)}const r={id:t,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(it,r);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(ze,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),r}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,t){return d.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("")}}const Xc=["password","newPassword","recoveryPin"];class ke{constructor(e,t,r,n,i,a){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=t,this.transport=r,this.tokenStore=n,this.pinStore=i??null,this.pinEncryptor=a??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(Nr))return e;const t=!e||this.tokenStore.isExpiringSoon(Nr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(t)throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async sealPinFields(e){if(!this.pinEncryptor||!e||typeof e!="object")return e;let t=null;for(const r of Xc){const n=e[r];if(typeof n!="string"||n==="")continue;const i=await this.pinEncryptor.seal(n);i!==n&&(t||(t={...e}),t[r]=i)}return t??e}async request(e,t,r,n=!1,i=!1){var f,g,S,E;const a=await this.ensureValidToken(),o=`${this.baseUrl}${t}`,c={Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Project-Id":this.projectId},u=await this.sealPinFields(r);try{const y=(await this.transport.request({url:o,method:e,headers:c,body:u??void 0})).data;if(y&&typeof y.code=="number"){if(y.code<0||y.code>=400){const w=y.message||y.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:y.code,message:w,url:o,method:e});const A=ke.mapGatewayError(y.code,y.data);if(A===l.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!i))return d.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,t,r,n,!0);if(A===l.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,t,r,!0,i);throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(A===l.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(f=this._onUnauthorized)==null||f.call(this),new h(l.USER_NOT_FOUND,ke.getGatewayErrorMessage(y.code,w));const P=A===l.AUTH_NOT_AUTHENTICATED?l.SESSION_EXPIRED:A,F=P===l.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ke.getGatewayErrorMessage(y.code,w),M=y.data;let V;throw A===l.PIN_LOCKED?V=ke.extractLockDetails(M):A===l.ADDRESS_LIMIT_EXCEEDED?V={limit:kt,raw:M}:V=M??void 0,new h(P,F,V)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:y.code,url:o,method:e}),y.data??y}return y}catch(m){if(m instanceof h)throw m;const y=((g=m.response)==null?void 0:g.status)??m.status;if((y===401||y===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${y} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,t,r,!0,i);throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((S=m.response)!=null&&S.data){const w=m.response.data,A=w.message||w.data||"API 요청에 실패했습니다",P=w.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:P,message:A,url:o,method:e,status:(E=m.response)==null?void 0:E.status}),new h(l.UNKNOWN_ERROR,`Wallet Gateway 오류 (${P}): ${A}`)}throw m}}async checkWallet(){var t,r;d.log("[CROSSx] GET /mnemonic/check"),(r=(t=this.pinEncryptor)==null?void 0:t.prewarm)==null||r.call(t);const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let t;if(this._walletStatusCache!==null?(t=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",t)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),t=await this.checkWallet(),this._walletStatusCache=null),t==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new h(l.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(t==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const r={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",r);return d.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(r=>({address:r.address,index:r.index,name:r.name}))}async getAddress(e,t){const r={password:this.requirePin(),index:t};return{address:(await this.request("POST","/mnemonic/address",r)).address,derivationPath:`m/44'/60'/0'/0/${t}`}}async prepare(e,t){let r;switch(e){case"sign":case"send":if(!t.tx)throw new h(l.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");r={unsignedTx:this.buildUnsignedTx(t.tx)};break;case"sign-message":if(!t.message)throw new h(l.TX_INVALID_PARAMS,"prepare: message가 필요합니다");r={message:t.message},t.from&&(r.from=t.from);break;case"sign-typed-data":if(!t.typedData)throw new h(l.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");r={typedData:t.typedData},t.from&&(r.from=t.from);break}const n={action:e,params:r},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,t,r,n,i,a){const o={message:r,password:this.requirePin()};i&&(o.uuid=i),a&&(o.from=a);const c=await this.request("POST","/mnemonic/sign-message",o);return{chainId:t,signature:c.signature,format:"hex"}}async signTypedData(e,t,r,n,i,a){const o={typedData:r,password:this.requirePin()};i&&(o.uuid=i),a&&(o.from=a);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(t)}`,o);return{chainId:t,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,t,r,n,i){const a={unsignedTx:this.buildUnsignedTx(r),password:this.requirePin()};i&&(a.uuid=i);const o=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(t)}`,a);return{chainId:t,signature:o.signedTx,txHash:o.txHash,format:"hex"}}async sendTransaction(e,t,r,n){const i={unsignedTx:this.buildUnsignedTx(r),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(t)}`,i)).txHash}}async migrateWallet(e,t){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const r={recoveryPin:e,sub:t,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",r);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:t,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const t={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",t)}async verifyPin(e){const t={password:e},r=await this.request("POST","/mnemonic/verify-password",t);if(!r.valid&&r.passwordStatus){const n=r.passwordStatus;if(n.permanent)throw new h(l.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 h(l.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 h(l.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return r.valid}async changePin(e,t){const r={password:this.requirePin(),newPassword:t};await this.request("POST","/mnemonic/change-password",r)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,t){const r={recoveryPin:e,sub:t};return this.request("POST","/mnemonic/verify-recovery-pin",r)}requirePin(){const e=this.getPin();if(!e)throw new h(l.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const t=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,r={},n=(t==null?void 0:t.lockExpiresAt)??(t==null?void 0:t.lock_expires_at);n&&(r.lockExpiresAt=n>1e10?n:n*1e3);const i=(t==null?void 0:t.remainingAttempts)??(t==null?void 0:t.remaining_attempts);typeof i=="number"&&(r.remainingAttempts=i);const a=(t==null?void 0:t.maxAttempts)??(t==null?void 0:t.max_attempts);return typeof a=="number"&&(r.maxAttempts=a),typeof(t==null?void 0:t.permanent)=="boolean"&&(r.permanent=t.permanent),r}static hasLockInfo(e){const t=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!t||typeof t!="object"?!1:typeof t.remainingAttempts=="number"||typeof t.remaining_attempts=="number"||typeof t.maxAttempts=="number"||typeof t.max_attempts=="number"}static mapGatewayError(e,t){switch(e){case-10002:return l.AUTH_NOT_AUTHENTICATED;case-10001:return l.UNKNOWN_ERROR;case-10006:return l.GATEWAY_INTERNAL_ERROR;case-10007:return l.BROADCAST_FAILED;case-10008:return l.GATEWAY_LOCK_CONFLICT;case-10004:return l.WALLET_ALREADY_EXISTS;case-10005:return l.WALLET_NOT_FOUND;case-10011:return l.WALLET_NOT_FOUND;case-10030:return l.WALLET_INCONSISTENT_STATE;case-10010:return l.MIGRATION_FAILED;case-10012:return l.MIGRATION_BACKUP_EXISTS;case-10013:return l.WITHDRAW_FAILED;case-10033:return l.USER_NOT_FOUND;case-10036:return l.ADDRESS_LIMIT_EXCEEDED;case-10027:return l.MIGRATION_PIN_LOCKED;case-10022:return l.PROJECT_NOT_REGISTERED;case-10023:return l.PROJECT_ID_MISSING;case-10024:return l.ORIGIN_NOT_ALLOWED;case-10025:return l.INVALID_APP_TYPE;case ct:return l.SDK_VERSION_UNSUPPORTED;case-10028:return ke.hasLockInfo(t)?l.PIN_LOCKED:l.PIN_WRONG;case-10029:return l.PIN_INVALID;case-10031:return l.PIN_LOCKED;case-10032:return l.PIN_REPEATED_PATTERN;case-10045:return l.PIN_ENCRYPTION_INVALID;case-10046:return l.PIN_POLICY_VIOLATION;case-10026:return l.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return l.PREPARE_FAILED;case-10016:return l.PREPARE_EXPIRED;case-10017:case-10018:return l.PREPARE_MISMATCH;case-10020:return l.CHAIN_NOT_SUPPORTED;case-10021:return l.INVALID_CHAIN;case-10040:return l.HMAC_REQUIRED;case-10041:return l.HMAC_VERIFICATION_FAILED;default:return l.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,t){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 (${t}). 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 ct:return`This SDK version is no longer supported. Update @nexus-cross/crossx-sdk-core.${t?` (${t})`:""}`;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 ${kt} accounts allowed.`;case-10045:return"Could not securely send your PIN. Please try again.";case-10046:return t||"This PIN does not meet the security policy. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${t}`}}}class jc{constructor(e,t,r,n=()=>{},i=()=>{},a=()=>{}){this.inner=e,this.getBridge=t,this.isAuthenticatedViaRNBridge=r,this.assertBridgeSessionActive=n,this.getAppName=i,this.onBridgeUnauthorized=a,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(o,c)=>e.prepare(o,c)),e.migrateWallet&&(this.migrateWallet=(o,c)=>e.migrateWallet(o,c)),e.verifyPin&&(this.verifyPin=o=>e.verifyPin(o)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(o,c)=>e.verifyRecoveryPin(o,c))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async innerOwnsAddress(e,t){if(!t)return!0;try{return(await this.inner.getAddresses(e)).some(n=>n.address.toLowerCase()===t.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,t,r,n){return!vr(e)||!await this.innerOwnsAddress(t,r)?!1:(this.onBridgeUnauthorized(`native 가 ${n} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,t,r,n,i,a){const o=this.shouldUseBridge();if(o!=null&&o.signMessage){this.assertBridgeSessionActive();try{const c=await o.signMessage({chainId:t,message:r,from:a,index:n,dappName:this.getAppName()});return{chainId:t,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,a,"signMessage"))throw Ue(c,l.SIGNATURE_FAILED)}}return this.inner.signMessage(e,t,r,n,i,a)}async signTypedData(e,t,r,n,i,a){const o=this.shouldUseBridge();if(o!=null&&o.signTypedData){this.assertBridgeSessionActive();try{const c=await o.signTypedData({chainId:t,typedData:r,from:a,index:n,dappName:this.getAppName()});return{chainId:t,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,a,"signTypedData"))throw Ue(c,l.SIGNATURE_FAILED)}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,t,r,n,i,a)}async signTransaction(e,t,r,n,i){const a=this.shouldUseBridge();if(a!=null&&a.signTransaction){this.assertBridgeSessionActive();try{const o=await a.signTransaction({chainId:t,tx:this.toBridgeTx(r),from:r.from,index:n,dappName:this.getAppName()});return{chainId:t,signature:o.signedTx,format:"hex"}}catch(o){if(!await this.recoverFromUnauthorized(o,e,r.from,"signTransaction"))throw Ue(o,l.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,t,r,n,i)}async sendTransaction(e,t,r,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await i.sendTransaction({chainId:t,tx:this.toBridgeTx(r),from:r.from,dappName:this.getAppName()})).txHash}}catch(a){if(!await this.recoverFromUnauthorized(a,e,r.from,"sendTransaction"))throw Ue(a,l.TRANSACTION_FAILED)}}if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,t,r,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,t){return this.inner.getAddress(e,t)}setOnUnauthorized(e){var t,r;(r=(t=this.inner).setOnUnauthorized)==null||r.call(t,e)}setTokenRefresher(e){var t,r;(r=(t=this.inner).setTokenRefresher)==null||r.call(t,e)}}class at{constructor(e,t){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=t}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 t=e.data.chains;return this.populateCache(t,!1),t}catch{const e=at.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const r=(await this.getChains()).find(n=>n.chainId===e);return r||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Bn:Wn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,t){this.cache.clear();for(const r of e)this.cache.set(r.chainId,r);this.loadedAt=Date.now(),this.usingFallback=t}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 t=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new h(at.mapErrorCode(e.code),t)}}fallbackOrThrow(e){const t=at.fallbackChains().find(r=>r.chainId===e);if(t)return t;throw new h(l.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(lt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return l.CHAIN_NOT_SUPPORTED;case-10021:return l.INVALID_CHAIN;case-10022:return l.PROJECT_NOT_REGISTERED;case-10023:return l.PROJECT_ID_MISSING;case-10024:return l.APP_IDENTIFIER_MISSING;case-10025:return l.INVALID_APP_TYPE;case ct:return l.SDK_VERSION_UNSUPPORTED;default:return l.UNKNOWN_ERROR}}}function Le(s){return Promise.reject(new h(l.UI_NOT_PROVIDED,`[CROSSx] "${s}" needs a UI adapter. Create the SDK with createCROSSxSDKWithOverrides(config, { ui }) from @nexus-cross/crossx-sdk-core/internal.`))}class Zc{requestConfirmation(e){return Le("requestConfirmation")}showLoginSelector(){return Le("showLoginSelector")}showMigrationFoundPrompt(){return Le("showMigrationFoundPrompt")}showRecoveryPinInputPrompt(){return Le("showRecoveryPinInputPrompt")}showWalletSelector(){return Le("showWalletSelector")}showPinSetupPrompt(){return Le("showPinSetupPrompt")}showPinInputPrompt(){return Le("showPinInputPrompt")}async showSessionAlert(){return"signout"}async showTransactionComplete(e){}async showTransactionProgress(e,t){try{await t}catch{}}async showRecoveryPinLockedPrompt(e,t){}async showUpdateRequired(){}setTheme(){}setMessages(){}setPinKeyboard(){}}class Qc{constructor(e,t,r,n=()=>!1){this.browserConfirmation=e,this.getBridge=t,this.getOrigin=r,this.isAuthenticatedViaRNBridge=n}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const t=this.getBridge();if(!t)return{approved:!1,reason:"Bridge not available"};const{operation:r,payload:n,chainId:i}=this.mapToNativeParams(e),a={operation:r,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await t.requestUserConfirmation(a)}mapToNativeParams(e){const t=e.type;switch(t){case"sign-message":{const r=e;return{operation:"signMessage",payload:{message:r.message,from:r.from,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"sign-typed-data":{const r=e;return{operation:"signTypedData",payload:{typedData:r.typedData,from:r.from,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"sign":{const r=e;return{operation:"signTransaction",payload:{from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:r.nativeSymbol,nativeDecimals:r.nativeDecimals,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"send":{const r=e;return{operation:"sendTransaction",payload:{from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:r.nativeSymbol,nativeDecimals:r.nativeDecimals,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}default:throw new h(l.INVALID_CONFIG,`Unknown confirmation type: ${String(t)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,t){if(this.shouldDelegateToBridge()){try{await t}catch{}return}return this.browserConfirmation.showTransactionProgress(e,t)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,t){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,t)}async showWalletSelector(e,t,r,n){const i=this.getBridge();if(this.shouldDelegateToBridge()&&(i!=null&&i.showWalletSelector))try{const a=await i.showWalletSelector({requiredAddress:r}),o=e.find(c=>c.address.toLowerCase()===a.address.toLowerCase());return{address:a.address,index:(o==null?void 0:o.index)??a.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,t,r,n)}async showWalletCreatedPrompt(){var e,t;if(!this.shouldDelegateToBridge())return((t=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:t.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}showUpdateRequired(e){return this.browserConfirmation.showUpdateRequired(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,t){return this.browserConfirmation.setTheme(e,t)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var t,r;(r=(t=this.browserConfirmation).setPinKeyboard)==null||r.call(t,e)}}class Pn{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const t=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof t.exp=="number"?t.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}}const el=new WeakMap;function tl(s,e){el.set(s,e)}function bn(s){return rl(s)}function rl(s,e){var Z;if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
|
|
8
8
|
Set the projectId field in SDKConfig when calling createCROSSxSDK().
|
|
9
9
|
Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);if(s.walletServer==="one-wallet"&&!((Z=s.oneId)!=null&&Z.clientId))throw new Error("[CROSSx] Fatal: walletServer 'one-wallet' requires SDKConfig.oneId (ONE ID login) — DEV2TF-2755");s.debug;const t=Me.production,r={...s,oauthServiceUrl:t.oauthServiceUrl,legacyOauthServiceUrl:t.legacyOauthServiceUrl,authApiUrl:t.authApiUrl,walletGatewayUrl:t.walletGatewayUrl,pinReuse:e==null?void 0:e.pinReuse},n={gatewayUrl:t.walletGatewayUrl,projectId:s.projectId},i=r.authMode!=="cookie"&&ls.isAvailable();!i&&r.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),r.secureStorageAvailable=i;const a=i?new ls(s.projectId):new Oa,o=new yc;let c=null;const u=new Lc(new Dc,{version:ot,sendVersionHeader:Kn,getGatewayBaseUrls:()=>[n.gatewayUrl],onDeprecation:v=>c==null?void 0:c.handleSdkVersionDeprecation(v),onUnsupported:v=>c==null?void 0:c.handleSdkVersionUnsupported(v)}),f=new De,g=new Pn,S=new Mt,E=new Tc(n,u);let m;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),m=new zc(a,S)):s.walletServer==="one-wallet"?(d.log("[CROSSx] one-wallet-api Wallet Provider 사용"),m=new is({baseUrl:()=>_t().oneWalletApiUrl,transport:u,pinStore:S,getAccessToken:()=>c?c.getOneIdAccessToken():Promise.reject(new h(l.AUTH_NOT_INITIALIZED,"SDK가 아직 만들어지지 않았습니다"))})):(d.log("[CROSSx] Remote Wallet Provider 사용"),m=new ke(n,a,u,g,S,E));const y=()=>{var v;return((v=c==null?void 0:c.isAuthenticatedViaRNBridge)==null?void 0:v.call(c))??!1},w=()=>{var v;return(v=c==null?void 0:c.assertRNBridgeSessionActive)==null?void 0:v.call(c)},A=v=>{var ee;(ee=c==null?void 0:c.clearRNBridgeDelegation)==null||ee.call(c,v)};s.walletServer!=="one-wallet"&&(m=new jc(m,()=>{var v;return(v=c==null?void 0:c.getRNBridge)==null?void 0:v.call(c)},y,w,()=>s.appName,A));const P=new at(n,u);_t();const F=new Zc,V=new Qc(F,()=>{var v;return(v=c==null?void 0:c.getRNBridge)==null?void 0:v.call(c)},()=>typeof window<"u"?window.location.origin:"http://localhost",y),U=new Ze(r,n,a,o,u,f,m,g,V,P,S,E,new gi);c=U,tl(U,{transport:u,storage:a,walletProvider:m,confirmation:V,tokenStore:g,pinStore:S,adapterConfig:n,pinEncryptor:E});const H=U.signInUseCase;return H&&typeof H.setFreshTokenCallback=="function"&&H.setFreshTokenCallback(()=>U.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=U),U}const sl=bn;function nl(s){const e=il(s),t=al(e),r=JSON.parse(t);cl(r);const{data:n}=r;return{status:r.status,state:r.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:r}}function il(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),t=e.searchParams.get("crossx_oauth_result");if(t)return t;const r=e.searchParams.get("data");if(r)return r;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function al(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=ol(s);return decodeURIComponent(e)}function ol(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function cl(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;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 t=e.data;if(typeof t.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof t.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return W.CONNECT_OTHER_WALLET_DISPLAY_ORDER=xr,W.CROSSxError=h,W.CROSSxEthereumProvider=Ut,W.CROSSxSDK=Ze,W.ChainId=zn,W.ConnectOtherWalletItem=br,W.ErrorCode=l,W.MESSAGES_EN=Wt,W.MESSAGES_KO=kr,W.MNEMONIC_ADDRESS_LIMIT=kt,W.ONEpocketError=h,W.ONEpocketEthereumProvider=Ut,W.ONEpocketSDK=Ze,W.PinMemoryStore=Mt,W.TokenMemoryStore=Pn,W.WALLET_BRAND_NAME=Lt,W.WEI_DISPLAY_DECIMALS=Dt,W.createCROSSxSDK=bn,W.createONEpocketSDK=sl,W.getConnectOtherWalletLabel=$n,W.getWalletBrowserInfo=nt,W.isWalletInAppBrowser=Gc,W.parseOAuthDeeplink=nl,W.waitForWalletBrowser=$c,Object.defineProperty(W,Symbol.toStringTag,{value:"Module"}),W})({});
|