const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["chunks/headers-DBBLE3ii.js","chunks/_virtual_wxt-plugins-D2Qy6pl9.js","chunks/index-YPJa-kxZ.js"])))=>i.map(i=>d[i]);
import{gs as H,l as L,hb as K,bi as A,i8 as E,i9 as g,ia as l,ib as m,bv as v,ic as N,id as R,ie as M,ig as F,bu as D,ih as $,ii as j,i7 as q,br as z,__tla as __tla_0}from"./headers-DBBLE3ii.js";import{b0 as h,aw as y,a_ as V,__tla as __tla_1}from"./_virtual_wxt-plugins-D2Qy6pl9.js";import{_ as w,__tla as __tla_2}from"./index-YPJa-kxZ.js";let fe,se,ae,Q,ee,k,T,he,ye;let __tla=Promise.all([(()=>{try{return __tla_0}catch{}})(),(()=>{try{return __tla_1}catch{}})(),(()=>{try{return __tla_2}catch{}})()]).then(async()=>{let Y;fe={fromKeyStore:e=>({publicKey:e.getPublicKey(),addressHex:e.getAddress(),address:e.getBech32Address().asString()})};Q=(e,t)=>{const r={getSecretKey:()=>Buffer.from(e),getBech32Address:()=>{const n=r.getAddress(),o=Buffer.from(n,"hex");return A.codec.encode(t,new A(o))},getPublicKey:()=>K(r.getSecretKey().toString("hex")),getAddress:()=>L(r.getPublicKey()),signData:n=>H(r.getSecretKey().toString("hex"),n)};return r};Y="/assets/midnight_ledger_wasm_bg-BE18Z0iE.wasm";let S=!1,d=null,f=null;const W="0".repeat(64);function _(e,t){if(typeof e=="bigint")return e;if(typeof e=="number"&&Number.isFinite(e))return BigInt(Math.trunc(e));if(typeof e=="string"&&e.trim().length>0)try{return BigInt(e)}catch{const r=Number(e);if(Number.isFinite(r))return BigInt(Math.trunc(r))}return t}function Z(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="bigint")return Number(e);if(typeof e=="string"&&e.trim().length>0){const r=Number(e);if(Number.isFinite(r))return r}return t}function J(e){const t=e&&typeof e=="object"?e:{},r=_(t.secondsSinceEpoch??t.timestamp??t.blockTimestamp,0n);return{...t,secondsSinceEpoch:r,secondsSinceEpochErr:Z(t.secondsSinceEpochErr,0),parentBlockHash:typeof t.parentBlockHash=="string"&&t.parentBlockHash.length>0?t.parentBlockHash:W,lastBlockTime:_(t.lastBlockTime??t.previousBlockTime??t.prevBlockTime,r)}}let X,x,te;X=async()=>{const t=(await w(()=>import("./headers-DBBLE3ii.js").then(async m=>{await m.__tla;return m}).then(n=>n.eY),__vite__mapDeps([0,1,2]))).default;if(typeof t!="function")throw new Error("Ledger WASM initializer is unavailable");const r=t;return()=>r({module_or_path:new URL(Y,self.location.href)})};ee=async()=>{f||(f=w(()=>import("./headers-DBBLE3ii.js").then(async m=>{await m.__tla;return m}).then(e=>e.eY),__vite__mapDeps([0,1,2])).then(e=>{const t=e.QueryContext;if(!t?.prototype)return;const r=Object.getOwnPropertyDescriptor(t.prototype,"block");if(!r?.set||r.set.__oneAmPatched)return;const n=r.set,o=function(a){return n.call(this,J(a))};o.__oneAmPatched=!0,Object.defineProperty(t.prototype,"block",{...r,set:o})}).catch(e=>{throw f=null,e})),await f};ye=async()=>(await k(),w(()=>import("./headers-DBBLE3ii.js").then(async m=>{await m.__tla;return m}).then(e=>e.eY),__vite__mapDeps([0,1,2])));k=async()=>{S||(d||(d=X().then(async e=>(await ee(),e)).then(e=>e()).then(()=>{S=!0}).catch(e=>{throw d=null,e})),await d)};x=5e3;te=31536e3;function re(e){if(e.devApiUrl)return e.devApiUrl;const t=e.environment;return V(t)}function p(e){return E(re(e))}async function U(e,t){return await k(),Q(e,t)}async function b(e,t){const r=await U(e,t);return String(r.getBech32Address())}function P(e,t){const r=new AbortController,n=()=>r.abort(e?.reason);e?.aborted?n():e?.addEventListener("abort",n,{once:!0});const o=setTimeout(()=>r.abort(new Error("Gateway auth timed out")),t);return{signal:r.signal,cleanup:()=>{clearTimeout(o),e?.removeEventListener("abort",n)}}}T=async function(e,t){if(!h(e.environment))throw new Error(`No gateway on the ${e.environment} network`);const r=p(e),n=P(t,x);let o;try{o=await y().fetch(`${r}/auth/challenge`,{signal:n.signal})}catch(c){throw console.warn("[GatewayAuth] fetchChallenge failed",{baseUrl:r,environment:e.environment,name:c instanceof Error?c.name:void 0,message:c instanceof Error?c.message:String(c),signalAborted:n.signal.aborted}),c}finally{n.cleanup()}if(!o.ok)throw new Error(`Challenge request failed: ${o.status}`);const s=await o.json(),a=Math.floor(y().now()/1e3),i=`1AM-AUTH-v1
${s.domain}
${s.nonce}
${a}`;return{challenge:s,timestamp:a,message:i,baseUrl:r}};async function ne(e,t,r){const n=await U(t,r),o=n.signData(new TextEncoder().encode(e)),s=n.getPublicKey(),a=typeof s=="object"&&"toBytes"in s?s.toBytes():s;return{signatureHex:typeof o=="string"?o:Buffer.from(o).toString("hex"),pubkeyHex:typeof s=="string"?s:Buffer.from(a).toString("hex"),addressBech32:String(n.getBech32Address())}}async function C(e,t,r,n){const o=await ne(e.message,t,r),s=P(n,x);let a;try{a=await y().fetch(`${e.baseUrl}/auth/verify`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",signal:s.signal,body:JSON.stringify({pubkey:o.pubkeyHex,nonce:e.challenge.nonce,timestamp:e.timestamp,signature:o.signatureHex,address:o.addressBech32})})}finally{s.cleanup()}if(!a.ok){const u=await a.text().catch(()=>"");throw new Error(`Auth verify failed: ${a.status} ${u}`)}const i=await a.json();if(!i||typeof i.token!="string"||i.token.length===0)throw new Error("Auth verify response is missing a session token");const c=typeof i.address=="string"&&i.address.length>0?i.address:void 0;if(c&&c!==o.addressBech32)throw new Error("Auth verify returned an address that does not match the signing key");return{token:i.token,address:o.addressBech32,expiresAt:Math.floor(y().now()/1e3)+(i.expires_in||te),baseUrl:E(e.baseUrl)}}function I(e,t){return r=>async({signal:n})=>{const o=await T(e,n),s=await C(o,t,e.environment,n);return{token:s.token,expiresAtMs:s.expiresAt*1e3,issuer:r.issuer,walletIdentity:r.walletIdentity,metadata:{address:s.address}}}}function oe(e,t){return{token:t.token,expiresAtMs:t.expiresAt*1e3,issuer:e.issuer,walletIdentity:e.walletIdentity,metadata:{address:t.address}}}async function O(e,t){const r=await v(e,t.walletIdentity,t.issuer);return!r||!N(r.baseUrl,t.issuer)?null:(l.get(t)||l.set(t,{...R(r),walletIdentity:t.walletIdentity}),r)}async function B(e,t){const r=l.get(t.scope);return r&&await M(e,t,r.token)?F(r):null}async function G(e,t,r){if(!h(e.environment))return null;const n=e.environment,o=p(e),s=await b(t,n),a=g(n,o,s),i=a.scope;if(!r&&(l.get(i)||await O(n,i)))return B(n,a);const c=I(e,t)(i),u=await l.ensure(i,c,{forceRefresh:r});return u?m(n,a,u):null}se=async function(e,t,r){const n=r;if(!h(n))throw new Error(`No gateway on the ${n} network`);const o=await b(t,n),s=g(n,e.baseUrl,o),a=s.scope,i=await l.ensure(a,async({signal:u})=>oe(a,await C(e,t,r,u)),{forceRefresh:!0});if(!i)throw new Error("Gateway sign-in was cancelled");const c=await m(n,s,i);if(!c)throw new Error("Gateway sign-in was cleared before it could be stored");return c};ae=async function(e,t){try{return await G(e,t,!1)}catch(r){return console.warn("[GatewayAuth] auto sign-in failed",r),null}};async function ie(e,t){try{return await G(e,t,!0)}catch(r){return console.warn("[GatewayAuth] refresh failed",r),null}}async function ce(e,t,r,n){if(!h(e.environment))return null;try{const o=e.environment,s=p(e),a=await b(t,o),i=g(o,s,a),c=i.scope;await O(o,c);const u=await l.recoverUnauthorized(c,r,n,I(e,t)(c));return u?m(o,i,u):null}catch(o){return console.warn("[GatewayAuth] 401 recovery failed",o),null}}he=Object.freeze(Object.defineProperty({__proto__:null,clearAllSessions:$,clearSession:D,confirmSignIn:se,ensureGatewaySession:ae,fetchChallenge:T,getGatewayAuthHeaders:j,getGatewayAuthTokenForRequest:q,getStoredSession:v,recoverGatewaySessionAfterUnauthorized:ce,refreshGatewaySession:ie,withGatewayAuthHeaders:z},Symbol.toStringTag,{value:"Module"}))});export{fe as P,se as a,ae as b,Q as c,ee as d,k as e,T as f,he as g,ye as l,__tla};