@enbox/browser 0.3.54 → 0.3.56

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/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{Enbox as Ko,defineProtocol as zo,repository as Go}from"@enbox/api";import{AuthManager as Fo,AuthSession as Qo,SESSION_EXPIRED_ERROR_CODE as Jo,SESSION_REVOKED_ERROR_CODE as Vo,computeConnectionStatus as Xo,isSessionExpiredError as Zo,isSessionInvalidError as er,normalizeProtocolRequests as tr,WalletConnect as nr}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as rr,ConnectProvider as ir}from"@enbox/connect";import{DidDht as Zt,DidWeb as en,UniversalResolver as ht}from"@enbox/dids";function ie(e){let t=e.indexOf("://dweb/");if(t===-1)return null;let n=e.slice(0,t);if(n!=="http"&&n!=="https")return null;let r=e.slice(t+8);if(r.length===0)return null;let o=r.indexOf("/");return o===-1?[r,""]:o===0?null:[r.slice(0,o),r.slice(o+1)]}var Ne=new ht({didResolvers:[Zt,en]}),gt=/^http:/,Ce=/\/$/,wt="drl";async function vt(e){let{didDocument:t}=await Ne.resolve(e),n=t?.service?.find(r=>r.type==="DecentralizedWebNode")?.serviceEndpoint;return n?(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.startsWith("http")):[]}async function bt(){if(!(typeof caches>"u"))return caches.open(wt)}async function tn(e,t,n,r){let o=e.request.url.replace(gt,"https:").replace(Ce,""),i=await bt(),s=await i?.match(o);if(s){if(!navigator.onLine)return s;let a=await r?.onCacheCheck?.(e,o);if(a){let d=s.headers.get("dwn-cache-time");if(d&&Date.now()<Number(d)+(Number(a.ttl)||0))return s}}try{if(n)return await nn(e,t,o,n,i,r);{let a=await Ne.resolve(t);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}}catch(a){return a instanceof Response?a:(console.log(`Error in DID URL fetch: ${a}`),new Response("DID URL fetch error",{status:500}))}}async function nn(e,t,n,r,o,i){let s=await vt(t);if(!s?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let a;for(let d of s)try{let u=`${d.replace(Ce,"")}/${t}/${r}`,p=await fetch(u,{headers:e.request.headers});if(p.ok)return await i?.onCacheCheck?.(e,n)&&o&&on(n,u,p,o),p;console.log(`DWN endpoint error: ${p.status}`),a=new Response("DWeb Node request failed",{status:p.status})}catch(u){console.log(`DWN endpoint error: ${u}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function on(e,t,n,r){try{let o=n.clone(),i=new Headers(o.headers);i.append("dwn-cache-time",Date.now().toString()),i.append("dwn-composed-url",t);let s=new Response(o.body,{headers:i});await r.put(e,s)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function rn(e={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let t=self;t.skipWaiting(),t.addEventListener("activate",n=>{n.waitUntil(t.clients.claim())}),t.addEventListener("fetch",n=>{let r=ie(n.request.url);r&&n.respondWith(tn(n,r[0],r[1],e))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let n=e.path||document?.currentScript?.src||import.meta.url;n&&navigator.serviceWorker.register(n,{type:"module"}).catch(r=>{console.error("DWeb networking feature installation failed: ",r)})}}else throw new Error("DWeb networking features are not available for install in this environment")}catch(t){console.error("Error in installing networking features:",t)}}var yt=`
1
+ import{Enbox as Ko,defineProtocol as zo,repository as Go}from"@enbox/api";import{AuthManager as Fo,AuthSession as Qo,SESSION_EXPIRED_ERROR_CODE as Jo,SESSION_REVOKED_ERROR_CODE as Vo,computeConnectionStatus as Xo,isSessionExpiredError as Zo,isSessionInvalidError as er,normalizeProtocolRequests as tr,WalletConnect as nr}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as rr,ConnectProvider as ir}from"@enbox/connect";import{DidDht as Zt,DidWeb as en,UniversalResolver as ht}from"@enbox/dids";function re(e){let t=e.indexOf("://dweb/");if(t===-1)return null;let n=e.slice(0,t);if(n!=="http"&&n!=="https")return null;let r=e.slice(t+8);if(r.length===0)return null;let o=r.indexOf("/");return o===-1?[r,""]:o===0?null:[r.slice(0,o),r.slice(o+1)]}var Ne=new ht({didResolvers:[Zt,en]}),gt=/^http:/,Ce=/\/$/,wt="drl";async function vt(e){let{didDocument:t}=await Ne.resolve(e),n=t?.service?.find(r=>r.type==="DecentralizedWebNode")?.serviceEndpoint;return n?(Array.isArray(n)?n:[n]).filter(r=>typeof r=="string"&&r.startsWith("http")):[]}async function bt(){if(!(typeof caches>"u"))return caches.open(wt)}async function tn(e,t,n,r){let o=e.request.url.replace(gt,"https:").replace(Ce,""),i=await bt(),s=await i?.match(o);if(s){if(!navigator.onLine)return s;let a=await r?.onCacheCheck?.(e,o);if(a){let d=s.headers.get("dwn-cache-time");if(d&&Date.now()<Number(d)+(Number(a.ttl)||0))return s}}try{if(n)return await nn(e,t,o,n,i,r);{let a=await Ne.resolve(t);return new Response(JSON.stringify(a),{status:200,headers:{"Content-Type":"application/json"}})}}catch(a){return a instanceof Response?a:(console.log(`Error in DID URL fetch: ${a}`),new Response("DID URL fetch error",{status:500}))}}async function nn(e,t,n,r,o,i){let s=await vt(t);if(!s?.length)throw new Response("DWeb Node resolution failed: no valid endpoints found.",{status:530});let a;for(let d of s)try{let u=`${d.replace(Ce,"")}/${t}/${r}`,p=await fetch(u,{headers:e.request.headers});if(p.ok)return await i?.onCacheCheck?.(e,n)&&o&&on(n,u,p,o),p;console.log(`DWN endpoint error: ${p.status}`),a=new Response("DWeb Node request failed",{status:p.status})}catch(u){console.log(`DWN endpoint error: ${u}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function on(e,t,n,r){try{let o=n.clone(),i=new Headers(o.headers);i.append("dwn-cache-time",Date.now().toString()),i.append("dwn-composed-url",t);let s=new Response(o.body,{headers:i});await r.put(e,s)}catch(o){console.log(`Failed to cache DRL response: ${o}`)}}async function rn(e={}){try{if(typeof ServiceWorkerGlobalScope<"u"&&self instanceof ServiceWorkerGlobalScope){let t=self;t.skipWaiting(),t.addEventListener("activate",n=>{n.waitUntil(t.clients.claim())}),t.addEventListener("fetch",n=>{let r=re(n.request.url);r&&n.respondWith(tn(n,r[0],r[1],e))})}else if(globalThis?.navigator?.serviceWorker){if(!await navigator.serviceWorker.getRegistration("/")){let n=e.path||document?.currentScript?.src||import.meta.url;n&&navigator.serviceWorker.register(n,{type:"module"}).catch(r=>{console.error("DWeb networking feature installation failed: ",r)})}}else throw new Error("DWeb networking features are not available for install in this environment")}catch(t){console.error("Error in installing networking features:",t)}}var yt=`
2
2
  .drl-loading-overlay {
3
3
  position: fixed;
4
4
  inset: 0;
@@ -132,7 +132,7 @@ import{Enbox as Ko,defineProtocol as zo,repository as Go}from"@enbox/api";import
132
132
  </div>
133
133
  </body>
134
134
  </html>
135
- `,_e=!1,Y=null,ae=null;function mt(){_e||(ae=document.createElement("style"),ae.innerHTML=`
135
+ `,_e=!1,G=null,ie=null;function mt(){_e||(ie=document.createElement("style"),ie.innerHTML=`
136
136
  ${yt}
137
137
 
138
138
  .drl-loading-overlay {
@@ -145,13 +145,13 @@ import{Enbox as Ko,defineProtocol as zo,repository as Go}from"@enbox/api";import
145
145
  opacity: 1;
146
146
  pointer-events: all;
147
147
  }
148
- `,document.head.append(ae),Y=document.createElement("div"),Y.classList.add("drl-loading-overlay"),Y.innerHTML=`
148
+ `,document.head.append(ie),G=document.createElement("div"),G.classList.add("drl-loading-overlay"),G.innerHTML=`
149
149
  <div class='drl-loading-spinner'>
150
150
  <div></div>
151
151
  Loading DRL
152
152
  </div>
153
153
  <span tabindex='0'></span>
154
- `,Y.lastElementChild.addEventListener("click",Ae),document.body.prepend(Y),_e=!0)}function sn(){_e&&(ae?.remove(),ae=null,Y?.remove(),Y=null,_e=!1)}function Ae(){document.documentElement.removeAttribute("drl-link-loading"),xe=null}var xe=null,Pe=!1,se=null,le=null;function ln(){Pe||(se=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=ie(n);if(r){let o=r[0],i=r[1],s=t.target==="_blank";e.preventDefault();try{let a=null;s?(a=window.open("","_blank"),a&&a.document.write(an)):(xe=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await vt(o);if(!d.length)throw new Error("no valid DWN endpoints found");let u=`${d[0].replace(Ce,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=u):xe===i&&(window.location.href=u)}catch{throw xe===i&&Ae(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},le=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(X(),t?.src&&ie(t.src)){F=t,t.__src__=t.src;let n=t.src.replace(gt,"https:").replace(Ce,""),o=await(await bt())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",X,{once:!0})}}else t===F&&X()},document.addEventListener("click",se),document.addEventListener("pointercancel",X),document.addEventListener("pointerdown",le),Pe=!0)}function cn(){Pe&&(se&&(document.removeEventListener("click",se),se=null),le&&(document.removeEventListener("pointerdown",le),le=null),document.removeEventListener("pointercancel",X),X(),Ae(),Pe=!1)}var F=null;async function X(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),F&&(F.src=F.__src__,delete F.__src__,F=null)}function fo(e={}){e.didResolvers&&(Ne=new ht({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&rn(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",mt,{once:!0}):mt()),e.links!==!1&&ln())}function mo(){typeof window<"u"&&typeof window.document<"u"&&(cn(),sn())}async function ho(){return typeof caches>"u"?!1:caches.delete(wt)}import{ConnectClient as In}from"@enbox/connect";function ce(e){let t=document.createElement("span");t.className="wallet-icon";let n=document.createElement("span");n.className="wallet-badge",n.textContent=e.name.charAt(0).toUpperCase(),t.appendChild(n);let r=dn(e);if(r.length===0)return t;let o=document.createElement("img");o.className="wallet-img",o.alt="",o.width=28,o.height=28;let i=0;return o.addEventListener("error",()=>{i+=1,i<r.length?o.src=r[i]:o.remove()}),o.src=r[i],t.appendChild(o),t}function dn(e){if(e.icon!==void 0)return[e.icon];let t;try{t=new URL(e.url).origin}catch{return[]}return[`${t}/favicon.svg`,`${t}/favicon.ico`,`${t}/favicon.png`]}import{assertX25519PublicJwk as pn,CONNECT_DENIED_TOKEN as un,ConnectClient as fn}from"@enbox/connect";var qe="/dweb-connect",de="enbox-connect-loaded",pe="enbox-connect-request",Z="enbox-connect-response",ue="enbox-connect-ack";function ke(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var mn=3e5,hn=500,gn=1500,wn="enbox-dweb-connect",Et=500,xt=700;function vn(){let e=`width=${Et},height=${xt},menubar=no,toolbar=no,location=no,status=no`,t=window.outerWidth>0?window.outerWidth:window.screen?.availWidth??0,n=window.outerHeight>0?window.outerHeight:window.screen?.availHeight??0;if(t===0||n===0)return e;let r=Math.max(0,Math.round((window.screenX??0)+(t-Et)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-xt)/2));return`${e},left=${r},top=${o}`}function bn(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var Q=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},ee=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;bn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??mn;let n=new URL(qe,t.walletUrl).toString(),r=window.open(n,wn,vn());if(!r)throw new Error("[@enbox/browser] Popup blocked. Allow popups for this site to connect to a wallet.");this._popup=r,this._walletEpkPromise=new Promise((o,i)=>{this._resolveWalletEpk=o,this._rejectWalletEpk=i}),this._responsePromise=new Promise((o,i)=>{this._resolveResponse=o,this._rejectResponse=i}),this._responsePromise.catch(()=>{}),this._messageListener=o=>{this.onMessage(o)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.fail(new Error("[@enbox/browser] DWeb Connect timed out waiting for wallet response."))},this._timeoutMs),this._closedPollId=setInterval(()=>{this.onClosedPoll()},hn)}async requestProfile(t){return{encryption:{mode:"ecdh-es",walletEpk:await this._walletEpkPromise,walletOrigin:this._walletOrigin},reply:{mode:"post_message"},state:t}}async deliverRequest(t){this._popup.postMessage({type:pe,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:ue},this._walletOrigin)}onMessage(t){let n=ke(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===de){this.onLoadedBeacon(n);return}n.type===Z&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{pn(t.walletEpk),n=t.walletEpk}catch{this.fail(new Error("[@enbox/browser] Wallet loaded beacon did not carry a valid X25519 public key."));return}if(t.walletOrigin!==this._walletOrigin){this.fail(new Error("[@enbox/browser] Wallet loaded beacon origin does not match the configured wallet origin."));return}this._walletEpkReceived=!0,this._resolveWalletEpk?.(n)}onResponseMessage(t){if(!this._settled){if(typeof t.payload!="string"){this.fail(new Error("[@enbox/browser] Wallet response message did not carry a ciphertext payload."));return}this._settled=!0,this.cleanup(),this._rejectWalletEpk?.(new Error("[@enbox/browser] Wallet responded before the handshake was established.")),this._resolveResponse?.(t.payload)}}onClosedPoll(){if(!(this._settled||this._popup.closed!==!0)){if(!this._walletEpkReceived){this.fail(new Q);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse?.(un))},gn)}}fail(t){if(!this._settled){this._settled=!0,this.cleanup();try{this._popup.close()}catch{}this._rejectWalletEpk?.(t),this._rejectResponse?.(t)}}cleanup(){clearTimeout(this._timeoutId),clearInterval(this._closedPollId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}};function Re(){let e=Intl.DateTimeFormat().resolvedOptions(),t=Array.isArray(globalThis.navigator.languages)?globalThis.navigator.languages.filter(n=>typeof n=="string"&&n.length>0):void 0;return{origin:globalThis.location.origin,userAgent:globalThis.navigator.userAgent,platform:globalThis.navigator.platform,language:globalThis.navigator.language,...t&&t.length>0?{languages:t}:{},...e.timeZone?{timezone:e.timeZone}:{}}}async function yn(e){let t=new ee({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new fn({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof Q)return;throw r}}var Pt=[-1,10,16,26,18,24,16,18,22,22,26],kt=[-1,1,1,1,2,2,4,4,4,5,5],Rt=[-1,26,44,70,100,134,172,196,242,292,346],En=0,Ct=10;function _t(e){return Rt[e]-Pt[e]*kt[e]}function $e(e,t){let n=new TextEncoder().encode(e),r=0;for(let m=1;m<=Ct;m++){let g=_t(m)*8;if(4+(m<=9?8:16)+n.length*8<=g){r=m;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${Ct}-M capacity).`);let o=[],i=(m,g)=>{for(let k=g-1;k>=0;k--)o.push(m>>>k&1)};i(4,4),i(n.length,r<=9?8:16);for(let m of n)i(m,8);let s=_t(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let m=0;o.length<s;m++)i(a[m%2],8);let d=new Uint8Array(s/8);for(let m=0;m<o.length;m++)d[m>>3]|=o[m]<<7-(m&7);let u=xn(d,r),p=17+4*r,f=Array.from({length:p},()=>new Array(p).fill(!1)),x=Array.from({length:p},()=>new Array(p).fill(!1));kn(f,x,r),Mn(f,x,u);let P=t??-1;if(P===-1){let m=1/0;for(let g=0;g<8;g++){Ie(f,x,g),je(f,x,g);let k=Sn(f);k<m&&(m=k,P=g),Ie(f,x,g)}}return Ie(f,x,P),je(f,x,P),{size:p,modules:f,version:r,mask:P}}function xn(e,t){let n=kt[t],r=Pt[t],o=Rt[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],u=Cn(r),p=0;for(let m=0;m<n;m++){let g=s-r+(m<i?0:1),k=e.slice(p,p+g);p+=g,a.push(k),d.push(_n(k,u))}let f=new Uint8Array(o),x=0,P=s-r+1;for(let m=0;m<P;m++)for(let g=0;g<n;g++)m<a[g].length&&(f[x++]=a[g][m]);for(let m=0;m<r;m++)for(let g=0;g<n;g++)f[x++]=d[g][m];return f}function Be(e,t){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n&255}function Cn(e){let t=new Uint8Array(e);t[e-1]=1;let n=1;for(let r=0;r<e;r++){for(let o=0;o<e;o++)t[o]=Be(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Be(n,2)}return t}function _n(e,t){let n=new Uint8Array(t.length);for(let r of e){let o=r^n[0];n.copyWithin(0,1),n[n.length-1]=0;for(let i=0;i<t.length;i++)n[i]^=Be(t[i],o)}return n}var Pn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function T(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function kn(e,t,n){let r=e.length;for(let i=0;i<r;i++)T(e,t,6,i,i%2===0),T(e,t,i,6,i%2===0);Ue(e,t,3,3),Ue(e,t,r-4,3),Ue(e,t,3,r-4);let o=Pn[n];for(let i=0;i<o.length;i++)for(let s=0;s<o.length;s++)i===0&&s===0||i===0&&s===o.length-1||i===o.length-1&&s===0||Rn(e,t,o[i],o[s]);je(e,t,0),T(e,t,8,r-8,!0),n>=7&&Tn(e,t,n)}function Ue(e,t,n,r){let o=e.length;for(let i=-4;i<=4;i++)for(let s=-4;s<=4;s++){let a=n+s,d=r+i;if(a<0||a>=o||d<0||d>=o)continue;let u=Math.max(Math.abs(s),Math.abs(i));T(e,t,a,d,u!==2&&u!==4)}}function Rn(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)T(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function je(e,t,n){let r=e.length,o=En<<3|n,i=o;for(let a=0;a<10;a++)i=i<<1^(i>>>9)*1335;let s=(o<<10|i)^21522;for(let a=0;a<=5;a++)T(e,t,8,a,(s>>>a&1)!==0);T(e,t,8,7,(s>>>6&1)!==0),T(e,t,8,8,(s>>>7&1)!==0),T(e,t,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)T(e,t,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)T(e,t,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)T(e,t,8,r-15+a,(s>>>a&1)!==0)}function Tn(e,t,n){let r=e.length,o=n;for(let s=0;s<12;s++)o=o<<1^(o>>>11)*7973;let i=n<<12|o;for(let s=0;s<18;s++){let a=(i>>>s&1)!==0,d=r-11+s%3,u=Math.floor(s/3);T(e,t,d,u,a),T(e,t,u,d,a)}}function Mn(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){i===6&&(i=5);for(let s=0;s<r;s++)for(let a=0;a<2;a++){let d=i-a,p=(i+1&2)===0?r-1-s:s;!t[p][d]&&o<n.length*8&&(e[p][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function Ie(e,t,n){let r=e.length;for(let o=0;o<r;o++)for(let i=0;i<r;i++){if(t[o][i])continue;let s;switch(n){case 0:s=(i+o)%2===0;break;case 1:s=o%2===0;break;case 2:s=i%3===0;break;case 3:s=(i+o)%3===0;break;case 4:s=(Math.floor(i/3)+Math.floor(o/2))%2===0;break;case 5:s=i*o%2+i*o%3===0;break;case 6:s=(i*o%2+i*o%3)%2===0;break;default:s=((i+o)%2+i*o%3)%2===0;break}s&&(e[o][i]=!e[o][i])}}function Sn(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,u=0;for(let p=0;p<t;p++)p===0||e[a][p]!==d?(d=e[a][p],u=1):(u++,u===5?n+=3:u>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,u=0;for(let p=0;p<t;p++)p===0||e[p][a]!==d?(d=e[p][a],u=1):(u++,u===5?n+=3:u>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let u=e[a][d];u===e[a][d+1]&&u===e[a+1][d]&&u===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((P,m)=>a[d+m]===P))return 0;let f=d>=4&&a.slice(d-4,d).every(P=>!P),x=d+11<=a.length&&a.slice(d+7,d+11).every(P=>!P);return(f?40:0)+(x?40:0)};for(let a=0;a<t;a++){let d=e[a],u=e.map(p=>p[a]);for(let p=0;p+7<=t;p++)n+=r(d,p),n+=r(u,p)}let o=0;for(let a of e)for(let d of a)d&&o++;let i=t*t,s=Math.ceil(Math.abs(o*20-i*10)/i)-1;return n+=s*10,n}var He="http://www.w3.org/2000/svg";function Ke(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let p=0;p<e.size;p++)for(let f=0;f<e.size;f++)e.modules[p][f]&&(s+=`M${f+o} ${p+o}h1v1h-1z`);let a=document.createElementNS(He,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(He,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let u=document.createElementNS(He,"path");return u.setAttribute("d",s),u.setAttribute("fill",n),a.appendChild(u),a}var Tt="/.well-known/enbox-connect";async function Te(e){try{let t=new URL(Tt,e).toString(),n=await fetch(t,{signal:AbortSignal.timeout(6e3)});if(!n.ok)return;let r=await n.json();return typeof r?.connectServerUrl!="string"?void 0:{connectServerUrl:r.connectServerUrl}}catch{return}}async function ze(e){return await Te(e)!==void 0}import{DidJwk as Dn}from"@enbox/dids";import{X25519 as Wn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as On,openResponse as Ln,randomToken as Mt,RelayClientTransport as Nn,resolveDelegatePortableDid as An,sealRequest as qn}from"@enbox/connect";var Ge=6,te=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function Un(e){return new Promise(t=>{if(typeof document>"u"){setTimeout(t,e);return}let n=()=>{clearTimeout(o),document.removeEventListener("visibilitychange",r),t()},r=()=>{document.visibilityState==="visible"&&n()},o=setTimeout(n,e);document.addEventListener("visibilitychange",r)})}async function Ye(e){if(e.requestType==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let n=(e.createTransport??(g=>new Nn({...g,sleep:Un})))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed}),r=await Dn.create(),o=await Wn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=Mt(),a=Mt(),d=await n.requestProfile(a),u={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,delegateDid:e.delegatePortableDid?.uri,requestType:e.requestType,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:a,responseKey:i,reply:d.reply},p=await qn({request:u,signer:r,encryption:d.encryption}),f=await n.deliverRequest(p);f!==void 0&&e.onWalletUriReady(f);let P=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(P===On)return;let m;for(let g=1;g<=Ge;g++){let k=await(e.cancelled===void 0?e.requestPin(g,m):Promise.race([e.requestPin(g,m),e.cancelled]));try{let D=await Ln({jwe:P,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:s,state:a},pin:k}),W=An({localDelegatePortableDid:e.delegatePortableDid,response:D});return n.confirmComplete?.().catch(()=>{}),{delegatePortableDid:W,delegateGrants:D.delegateGrants,connectedDid:D.providerDid,sessionRevocations:D.sessionRevocations}}catch(D){let W=D instanceof Error?D:new Error(String(D));if(W.message.startsWith("Connect:"))throw W;m=W}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ge} attempts.`)}var Ot="enbox:connect:lastChoice",Hn=12e4,Bn=1e4,Me=4,jn=4,St=3,Fe={background:"--ec-bg",surface:"--ec-surface",text:"--ec-text",textMuted:"--ec-muted",border:"--ec-border",accent:"--ec-accent",accentContrast:"--ec-accent-contrast",danger:"--ec-danger",success:"--ec-success"};async function Lt(e){return(await Te(e))?.connectServerUrl}async function $n(e){let t=new ee({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new In({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.requestType})}function Kn(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function zn(){return{runRelay:Ye,runPopup:$n,discoverConnectServerUrl:Lt,validateWalletUrl:ze,isMobile:Kn,storage:typeof localStorage>"u"?void 0:localStorage}}function Gn(e){try{let t=e?.getItem(Ot);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&Jn(n.walletUrl))return{method:n.method,walletUrl:n.walletUrl}}catch{}}function Yn(e,t){try{e?.setItem(Ot,JSON.stringify(t))}catch{}}function Fn(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new te))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Qe(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");if(e.mode==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let t={...zn(),...e.deps},n=Vn(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=e.mode==="refresh",d=r?Gn(t.storage):void 0,u=d!==void 0&&(a||Qn(n,d.walletUrl))?d.walletUrl:void 0,p=e.walletUrl!==void 0||a&&u!==void 0,f=e.walletUrl??u??n[0]?.url,x=e.preferredMethod??d?.method??"phone";return new Promise((P,m)=>{let g=document.createElement("div");g.id="enbox-connect-modal";let k=g.attachShadow({mode:"open"}),D=document.createElement("style");D.textContent=to,k.appendChild(D);let W=document.createElement("div");W.className="overlay";let O=document.createElement("div");O.className="modal",O.setAttribute("role","dialog"),O.setAttribute("aria-modal","true");let Ve=a?`Reconnect to ${o}`:`Connect to ${o}`;O.setAttribute("aria-label",Ve);let q=e.theme??{},ne=q.appearance??"auto";ne!=="auto"&&O.setAttribute("data-appearance",ne);let De=window.matchMedia?.("(prefers-color-scheme: dark)"),At=q.accent!==void 0||q.accentContrast!==void 0||q.light!==void 0||q.dark!==void 0,Xe=()=>{let l=ne==="auto"?De?.matches===!0?"dark":"light":ne,c={accent:q.accent,accentContrast:q.accentContrast,...q[l]};for(let y of Object.keys(Fe)){let h=c[y];typeof h=="string"&&h.trim()!==""?O.style.setProperty(Fe[y],h):O.style.removeProperty(Fe[y])}},Ze=()=>Xe();At&&(Xe(),ne==="auto"&&De?.addEventListener?.("change",Ze));let L=!1,H,et,me,he=!1,B,tt=new Map,J=[],ge=l=>n.find(c=>c.url===l)??{name:Xn(l)??l,url:l},qt=()=>{if(f===void 0){J=n.slice(0,St);return}if(J.some(c=>c.url===f))return;let l=ge(f);J=[l,...n.filter(c=>c.url!==l.url)].slice(0,St)},we=l=>{f=l,re(),oe()},Ut=()=>{H?.cancel(),K(),document.removeEventListener("keydown",ct),document.removeEventListener("visibilitychange",dt),De?.removeEventListener?.("change",Ze);try{document.body.removeChild(g)}catch{}},ve=l=>{L||(L=!0,Ut(),l())},nt=l=>{r&&Yn(t.storage,{method:x,walletUrl:f??""}),Kt(),setTimeout(()=>ve(()=>P(l)),1200)},We=()=>ve(()=>m(new Error("[@enbox/browser] Connect cancelled.")));O.appendChild(Zn(Ve,e.appIcon,We));let j=document.createElement("div");j.className="stage",j.setAttribute("aria-live","polite"),O.appendChild(j);let $=document.createElement("div");$.className="footer",O.appendChild($);let M=(...l)=>{j.replaceChildren(...l),j.classList.remove("fade-in"),j.offsetWidth,j.classList.add("fade-in")},ot=l=>{M(v("div","spinner"),v("p","stage-caption",l))},It=l=>{let c=H;setTimeout(()=>{L||c!==H||c?.active!==!0||B!==void 0||Bt(l)},0)},rt=(l,c,y)=>{let h=document.createElement("a");return h.className=y,h.href=l.walletUri,h.target="_blank",h.rel="noopener noreferrer",h.addEventListener("click",()=>{It(c)}),h},Ht=l=>{let c=f!==void 0?ge(f):void 0,y=c?.name??"your wallet",h=rt(l,y,"qr-box qr-link");if(h.setAttribute("aria-label",`Open ${y} on this device`),h.replaceChildren(Ke($e(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let C=v("div","qr-logo");C.appendChild(ce(c)),h.appendChild(C)}if(s){let C=rt(l,y,"deep-link");c!==void 0&&C.appendChild(ce(c)),C.appendChild(v("span","deep-link-label",`Continue in ${y}`)),h.classList.add("compact"),M(C,v("p","stage-subline",`${y} opens in a new tab \u2014 approve there, then come back for your code.`),v("div","stage-divider","or scan with another phone"),h);return}M(h,v("p","stage-caption","Scan with your phone\u2019s camera"),v("p","stage-subline",`${y} stays on your phone \u2014 or click the code to open it here.`))},Bt=l=>{M(v("div","spinner"),v("p","stage-caption",`Finish in ${l}`),v("p","stage-subline",s?`Approve the connection in the ${l} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),Se("Start over",()=>{Oe()}))},jt=()=>{let l=f!==void 0?ge(f).name:"your wallet",c=document.createElement("div");c.className="claimed-pulse",M(c,v("p","stage-caption",`Request received \u2014 approve in ${l}`),v("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},$t=(l,c)=>new Promise(y=>{B=y;let h=f!==void 0?ge(f).name:"your wallet",C=document.createElement("div");C.className="pin-row",c!==void 0&&C.classList.add("shake");let R=[];for(let _=0;_<Me;_++){let E=document.createElement("input");E.className="pin-input",E.type="text",E.inputMode="numeric",E.maxLength=1,E.setAttribute("aria-label",`Code digit ${_+1}`),R.push(E),C.appendChild(E)}let U=()=>{let _=R.map(E=>E.value).join("");if(_.length===Me&&B!==void 0){let E=B;B=void 0,ot("Checking the code\u2026"),E(_)}};R.forEach((_,E)=>{_.addEventListener("input",()=>{_.value=_.value.replace(/\D/g,"").slice(0,1),_.value!==""&&E+1<R.length&&R[E+1].focus(),U()}),_.addEventListener("keydown",I=>{I.key==="Backspace"&&_.value===""&&E>0&&R[E-1].focus()}),_.addEventListener("paste",I=>{let z=(I.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Me);z.length!==0&&(I.preventDefault(),z.split("").forEach((V,S)=>{R[S]!==void 0&&(R[S].value=V)}),R[Math.min(z.length,Me)-1]?.focus(),U())})}),M(v("p","stage-caption",`Enter the code shown in ${h}`),C,...c!==void 0?[v("p","stage-error",`That code doesn\u2019t match \u2014 check ${h}.`)]:[v("p","stage-subline",l===1?"This confirms you\u2019re the one approving.":"")]),R[0].focus()}),Kt=()=>{let l=v("div","check");l.textContent="\u2713",M(l,v("p","stage-caption","You\u2019re connected."))},it=()=>{M(v("p","stage-caption","No problem \u2014 nothing was shared."),fe("Start over",()=>{oe()}),Se("Close",()=>ve(()=>P(void 0))))},be=(l,c)=>{M(v("p","stage-caption",l),fe("Start over",()=>{oe()}),Se("Close",()=>ve(()=>m(c??new Error(`[@enbox/browser] ${l}`)))))},zt=()=>{M(v("p","stage-caption","This wallet can\u2019t connect by phone here."),v("p","stage-subline","You can continue in this browser instead."),fe("Use this browser",()=>{Ee()}))},ye=s?"tab":"window",Gt=()=>{M(v("p","stage-caption","Connect with a wallet in this browser"),v("p","stage-subline",s?"Your wallet opens in a new tab to approve this connection \u2014 no code needed.":"Your wallet opens in a small window to approve this connection."),fe(s?"Open wallet":"Open wallet window",()=>{Ee()}))},Yt=()=>{M(v("div","spinner"),v("p","stage-caption",`Finish in the wallet ${ye}`),v("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},Ft=l=>{M(v("p","stage-caption",l?`Your browser blocked the wallet ${ye}.`:`The wallet ${ye} was closed.`),fe(l?"Open it now":`Reopen ${ye}`,()=>{Ee()}),Se(s?"Use a code instead":"Use your phone instead",()=>{lt("phone")}))},at=l=>{if(L)return;let c=l instanceof Error?l:new Error(String(l)),y=/popup blocked/i.test(c.message);if(l instanceof Q||y){Ft(y);return}be(/timed out/i.test(c.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",c)},Qt=async l=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let c=tt.get(l);return c===void 0&&(c=t.discoverConnectServerUrl(l),tt.set(l,c)),c},K=()=>{clearTimeout(et),me=void 0},st=()=>{!L&&B===void 0&&x==="phone"&&Oe()},Jt=l=>{K();let c=Math.max(Bn,l*1e3-Hn);me=Date.now()+c,et=setTimeout(st,c)},Oe=async()=>{if(H?.cancel(),K(),f===void 0){be("No wallet is configured.");return}x="phone",re(),ot("Getting things ready\u2026");let l=new URL(f).origin,c=await Qt(l);if(c===void 0){zt();return}let y=Fn();H=y;try{let h=await t.runRelay({connectServerUrl:c,walletUri:new URL(i,l).toString(),appName:o,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.mode,timeoutMs:e.timeout,cancelled:y.cancelled,onWalletUriReady:C=>{y.active&&!L&&(Ht(C),Jt(C.expiresIn))},onClaimed:()=>{y.active&&!L&&(K(),jt())},requestPin:(C,R)=>(K(),$t(C,R))});if(!y.active||L)return;h===void 0?it():nt(h)}catch(h){if(!y.active||L||h instanceof te)return;let C=h instanceof Error?h:new Error(String(h));be(/timed out/i.test(C.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",C)}},Ee=()=>{if(H?.cancel(),K(),f===void 0){be("No wallet is configured.");return}if(!he){x="browser",re(),he=!0,Yt();try{t.runPopup({walletUrl:f,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout,delegatePortableDid:e.delegatePortableDid,requestType:e.mode}).then(l=>{L||(l===void 0?it():nt(l))}).catch(at).finally(()=>{he=!1})}catch(l){he=!1,at(l)}}},oe=async()=>{x==="browser"?(H?.cancel(),K(),re(),Gt()):await Oe()},lt=async l=>{x=l,await oe()},re=()=>{if($.replaceChildren(),!p){qt();let c=Vt();c.label!==void 0&&$.appendChild(c.label),$.appendChild(c.row),$.appendChild(c.panel)}let l=document.createElement("div");if(l.className="footer-row",x==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Or connect without a code \u2192":"No phone? Use this browser \u2192",c.addEventListener("click",()=>{Ee()}),l.appendChild(c)}else{let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Use a code instead \u2192":"Use your phone instead \u2192",c.addEventListener("click",()=>{lt("phone")}),l.appendChild(c)}l.childElementCount>0&&$.appendChild(l)},Vt=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let w of J){let b=document.createElement("button");b.className="row-tile",b.title=w.description??w.name,b.setAttribute("role","radio");let N=w.url===f;b.setAttribute("aria-checked",N?"true":"false"),N&&b.classList.add("selected"),b.appendChild(ce(w)),b.appendChild(v("span","row-tile-name",w.name)),b.addEventListener("click",()=>{w.url!==f&&we(w.url)}),l.appendChild(b)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let y=n.filter(w=>!J.some(b=>b.url===w.url)),h=document.createElement("button");h.className="row-tile more-tile",h.title="All wallets",h.setAttribute("aria-expanded","false"),h.appendChild(v("span","more-count",y.length>0?`+${y.length}`:"\u22EF")),h.appendChild(v("span","row-tile-name","More")),h.addEventListener("click",()=>{c.hidden=!c.hidden,h.setAttribute("aria-expanded",c.hidden?"false":"true"),c.hidden||z()}),l.appendChild(h);let C=J.length>0?v("div","wallet-row-label","Connecting with"):void 0,R=[],U=document.createElement("div");if(U.className="wallet-empty",U.textContent="No other wallets match your search.",U.hidden=!0,y.length>jn){let w=document.createElement("input");w.type="search",w.className="wallet-search",w.placeholder="Search wallets\u2026",w.setAttribute("aria-label","Search wallets"),w.addEventListener("input",()=>{let b=w.value.trim().toLowerCase(),N=0;for(let{wallet:ut,el:Xt}of R){let ft=b===""||ut.name.toLowerCase().includes(b)||ut.url.toLowerCase().includes(b);Xt.hidden=!ft,ft&&(N+=1)}U.hidden=N>0,z()}),c.appendChild(w)}let _=document.createElement("div");_.className="wallet-scroll-wrap",_.hidden=y.length===0;let E=document.createElement("div");E.className="wallet-scroll";let I=document.createElement("div");I.className="wallet-grid";let z=()=>{let w=E.scrollHeight-E.clientHeight>1,b=E.scrollTop+E.clientHeight>=E.scrollHeight-1;_.classList.toggle("scroll-hint",w&&!b)};E.addEventListener("scroll",z);for(let w of y){let b=document.createElement("button");b.className="wallet-tile",b.title=w.description??w.name,b.appendChild(ce(w));let N=document.createElement("span");N.className="wallet-tile-name",N.textContent=w.name,b.appendChild(N),b.addEventListener("click",()=>{we(w.url)}),R.push({wallet:w,el:b}),I.appendChild(b)}E.appendChild(I),E.appendChild(U),_.appendChild(E),c.appendChild(_);let V=document.createElement("div");V.className="wallet-custom";let S=document.createElement("input");S.className="url-input",S.type="url",S.placeholder="https://your-wallet.example";let A=document.createElement("button");A.className="url-go",A.textContent="Use";let G=document.createElement("div");G.className="url-error",G.hidden=!0;let Le=!1,pt=async()=>{let w=S.value.trim();if(w==="")return;let b;try{b=new URL(w.includes("://")?w:`https://${w}`).origin}catch{S.classList.add("invalid");return}if(Le){we(b);return}A.disabled=!0,A.textContent="Checking\u2026",G.hidden=!0;let N=await t.validateWalletUrl(b);if(A.disabled=!1,N){A.textContent="Use",we(b);return}Le=!0,A.textContent="Use anyway",S.classList.add("invalid"),G.textContent=`Couldn't verify a wallet at ${b}.`,G.hidden=!1};return S.addEventListener("input",()=>{Le=!1,A.textContent="Use",S.classList.remove("invalid"),G.hidden=!0}),S.addEventListener("keydown",w=>{w.key==="Enter"&&pt()}),A.addEventListener("click",()=>{pt()}),V.appendChild(S),V.appendChild(A),c.appendChild(V),c.appendChild(G),{label:C,row:l,panel:c}};W.addEventListener("click",l=>{l.target===W&&We()});let ct=l=>{if(l.key==="Escape"){We();return}l.key==="Tab"&&eo(k,l)};document.addEventListener("keydown",ct);let dt=()=>{if(!(document.visibilityState!=="visible"||L)){if(me!==void 0&&Date.now()>=me){st();return}B!==void 0&&Array.from(k.querySelectorAll(".pin-input")).find(c=>c.value==="")?.focus()}};document.addEventListener("visibilitychange",dt),W.appendChild(O),k.appendChild(W),document.body.appendChild(g),re(),oe()})}function Qn(e,t){return e.some(n=>n.url===t)}function Jn(e){if(typeof e!="string"||e.trim()==="")return!1;try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vn(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Xn(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function v(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function fe(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Se(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function Zn(e,t,n){let r=document.createElement("div");r.className="header";let o=document.createElement("div");if(o.className="header-identity",t!==void 0){let a=document.createElement("img");a.className="header-icon",a.src=t,a.alt="",a.width=24,a.height=24,a.addEventListener("error",()=>a.remove()),o.appendChild(a)}let i=document.createElement("h2");i.textContent=e,o.appendChild(i);let s=document.createElement("button");return s.className="close-btn",s.setAttribute("aria-label","Close"),s.textContent="\xD7",s.addEventListener("click",n),r.appendChild(o),r.appendChild(s),r}function eo(e,t){let n=Array.from(e.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(n.length===0)return;let r=n[0],o=n[n.length-1],i=e.activeElement;t.shiftKey&&(i===r||i===null)?(t.preventDefault(),o.focus()):!t.shiftKey&&i===o&&(t.preventDefault(),r.focus())}var Dt=`
154
+ `,G.lastElementChild.addEventListener("click",Ae),document.body.prepend(G),_e=!0)}function sn(){_e&&(ie?.remove(),ie=null,G?.remove(),G=null,_e=!1)}function Ae(){document.documentElement.removeAttribute("drl-link-loading"),xe=null}var xe=null,Pe=!1,ae=null,se=null;function ln(){Pe||(ae=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=re(n);if(r){let o=r[0],i=r[1],s=t.target==="_blank";e.preventDefault();try{let a=null;s?(a=window.open("","_blank"),a&&a.document.write(an)):(xe=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await vt(o);if(!d.length)throw new Error("no valid DWN endpoints found");let u=`${d[0].replace(Ce,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=u):xe===i&&(window.location.href=u)}catch{throw xe===i&&Ae(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},se=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(V(),t?.src&&re(t.src)){Y=t,t.__src__=t.src;let n=t.src.replace(gt,"https:").replace(Ce,""),o=await(await bt())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",V,{once:!0})}}else t===Y&&V()},document.addEventListener("click",ae),document.addEventListener("pointercancel",V),document.addEventListener("pointerdown",se),Pe=!0)}function cn(){Pe&&(ae&&(document.removeEventListener("click",ae),ae=null),se&&(document.removeEventListener("pointerdown",se),se=null),document.removeEventListener("pointercancel",V),V(),Ae(),Pe=!1)}var Y=null;async function V(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),Y&&(Y.src=Y.__src__,delete Y.__src__,Y=null)}function fo(e={}){e.didResolvers&&(Ne=new ht({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&rn(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",mt,{once:!0}):mt()),e.links!==!1&&ln())}function mo(){typeof window<"u"&&typeof window.document<"u"&&(cn(),sn())}async function ho(){return typeof caches>"u"?!1:caches.delete(wt)}import{ConnectClient as In}from"@enbox/connect";function le(e){let t=document.createElement("span");t.className="wallet-icon";let n=document.createElement("span");n.className="wallet-badge",n.textContent=e.name.charAt(0).toUpperCase(),t.appendChild(n);let r=dn(e);if(r.length===0)return t;let o=document.createElement("img");o.className="wallet-img",o.alt="",o.width=28,o.height=28;let i=0;return o.addEventListener("error",()=>{i+=1,i<r.length?o.src=r[i]:o.remove()}),o.src=r[i],t.appendChild(o),t}function dn(e){if(e.icon!==void 0)return[e.icon];let t;try{t=new URL(e.url).origin}catch{return[]}return[`${t}/favicon.svg`,`${t}/favicon.ico`,`${t}/favicon.png`]}import{assertX25519PublicJwk as pn,CONNECT_DENIED_TOKEN as un,ConnectClient as fn}from"@enbox/connect";var qe="/dweb-connect",ce="enbox-connect-loaded",de="enbox-connect-request",X="enbox-connect-response",pe="enbox-connect-ack";function ke(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var mn=3e5,hn=500,gn=1500,wn="enbox-dweb-connect",Et=500,xt=700;function vn(){let e=`width=${Et},height=${xt},menubar=no,toolbar=no,location=no,status=no`,t=window.outerWidth>0?window.outerWidth:window.screen?.availWidth??0,n=window.outerHeight>0?window.outerHeight:window.screen?.availHeight??0;if(t===0||n===0)return e;let r=Math.max(0,Math.round((window.screenX??0)+(t-Et)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-xt)/2));return`${e},left=${r},top=${o}`}function bn(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var F=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},Z=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;bn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??mn;let n=new URL(qe,t.walletUrl).toString(),r=window.open(n,wn,vn());if(!r)throw new Error("[@enbox/browser] Popup blocked. Allow popups for this site to connect to a wallet.");this._popup=r,this._walletEpkPromise=new Promise((o,i)=>{this._resolveWalletEpk=o,this._rejectWalletEpk=i}),this._responsePromise=new Promise((o,i)=>{this._resolveResponse=o,this._rejectResponse=i}),this._responsePromise.catch(()=>{}),this._messageListener=o=>{this.onMessage(o)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.fail(new Error("[@enbox/browser] DWeb Connect timed out waiting for wallet response."))},this._timeoutMs),this._closedPollId=setInterval(()=>{this.onClosedPoll()},hn)}async requestProfile(t){return{encryption:{mode:"ecdh-es",walletEpk:await this._walletEpkPromise,walletOrigin:this._walletOrigin},reply:{mode:"post_message"},state:t}}async deliverRequest(t){this._popup.postMessage({type:de,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:pe},this._walletOrigin)}onMessage(t){let n=ke(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===ce){this.onLoadedBeacon(n);return}n.type===X&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{pn(t.walletEpk),n=t.walletEpk}catch{this.fail(new Error("[@enbox/browser] Wallet loaded beacon did not carry a valid X25519 public key."));return}if(t.walletOrigin!==this._walletOrigin){this.fail(new Error("[@enbox/browser] Wallet loaded beacon origin does not match the configured wallet origin."));return}this._walletEpkReceived=!0,this._resolveWalletEpk?.(n)}onResponseMessage(t){if(!this._settled){if(typeof t.payload!="string"){this.fail(new Error("[@enbox/browser] Wallet response message did not carry a ciphertext payload."));return}this._settled=!0,this.cleanup(),this._rejectWalletEpk?.(new Error("[@enbox/browser] Wallet responded before the handshake was established.")),this._resolveResponse?.(t.payload)}}onClosedPoll(){if(!(this._settled||this._popup.closed!==!0)){if(!this._walletEpkReceived){this.fail(new F);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse?.(un))},gn)}}fail(t){if(!this._settled){this._settled=!0,this.cleanup();try{this._popup.close()}catch{}this._rejectWalletEpk?.(t),this._rejectResponse?.(t)}}cleanup(){clearTimeout(this._timeoutId),clearInterval(this._closedPollId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}};function Re(){let e=Intl.DateTimeFormat().resolvedOptions(),t=Array.isArray(globalThis.navigator.languages)?globalThis.navigator.languages.filter(n=>typeof n=="string"&&n.length>0):void 0;return{origin:globalThis.location.origin,userAgent:globalThis.navigator.userAgent,platform:globalThis.navigator.platform,language:globalThis.navigator.language,...t&&t.length>0?{languages:t}:{},...e.timeZone?{timezone:e.timeZone}:{}}}async function yn(e){let t=new Z({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new fn({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof F)return;throw r}}var Pt=[-1,10,16,26,18,24,16,18,22,22,26],kt=[-1,1,1,1,2,2,4,4,4,5,5],Rt=[-1,26,44,70,100,134,172,196,242,292,346],En=0,Ct=10;function _t(e){return Rt[e]-Pt[e]*kt[e]}function $e(e,t){let n=new TextEncoder().encode(e),r=0;for(let m=1;m<=Ct;m++){let v=_t(m)*8;if(4+(m<=9?8:16)+n.length*8<=v){r=m;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${Ct}-M capacity).`);let o=[],i=(m,v)=>{for(let x=v-1;x>=0;x--)o.push(m>>>x&1)};i(4,4),i(n.length,r<=9?8:16);for(let m of n)i(m,8);let s=_t(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let m=0;o.length<s;m++)i(a[m%2],8);let d=new Uint8Array(s/8);for(let m=0;m<o.length;m++)d[m>>3]|=o[m]<<7-(m&7);let u=xn(d,r),p=17+4*r,f=Array.from({length:p},()=>new Array(p).fill(!1)),C=Array.from({length:p},()=>new Array(p).fill(!1));kn(f,C,r),Mn(f,C,u);let k=t??-1;if(k===-1){let m=1/0;for(let v=0;v<8;v++){Ie(f,C,v),je(f,C,v);let x=Sn(f);x<m&&(m=x,k=v),Ie(f,C,v)}}return Ie(f,C,k),je(f,C,k),{size:p,modules:f,version:r,mask:k}}function xn(e,t){let n=kt[t],r=Pt[t],o=Rt[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],u=Cn(r),p=0;for(let m=0;m<n;m++){let v=s-r+(m<i?0:1),x=e.slice(p,p+v);p+=v,a.push(x),d.push(_n(x,u))}let f=new Uint8Array(o),C=0,k=s-r+1;for(let m=0;m<k;m++)for(let v=0;v<n;v++)m<a[v].length&&(f[C++]=a[v][m]);for(let m=0;m<r;m++)for(let v=0;v<n;v++)f[C++]=d[v][m];return f}function Be(e,t){let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n&255}function Cn(e){let t=new Uint8Array(e);t[e-1]=1;let n=1;for(let r=0;r<e;r++){for(let o=0;o<e;o++)t[o]=Be(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Be(n,2)}return t}function _n(e,t){let n=new Uint8Array(t.length);for(let r of e){let o=r^n[0];n.copyWithin(0,1),n[n.length-1]=0;for(let i=0;i<t.length;i++)n[i]^=Be(t[i],o)}return n}var Pn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function S(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function kn(e,t,n){let r=e.length;for(let i=0;i<r;i++)S(e,t,6,i,i%2===0),S(e,t,i,6,i%2===0);Ue(e,t,3,3),Ue(e,t,r-4,3),Ue(e,t,3,r-4);let o=Pn[n];for(let i=0;i<o.length;i++)for(let s=0;s<o.length;s++)i===0&&s===0||i===0&&s===o.length-1||i===o.length-1&&s===0||Rn(e,t,o[i],o[s]);je(e,t,0),S(e,t,8,r-8,!0),n>=7&&Tn(e,t,n)}function Ue(e,t,n,r){let o=e.length;for(let i=-4;i<=4;i++)for(let s=-4;s<=4;s++){let a=n+s,d=r+i;if(a<0||a>=o||d<0||d>=o)continue;let u=Math.max(Math.abs(s),Math.abs(i));S(e,t,a,d,u!==2&&u!==4)}}function Rn(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)S(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function je(e,t,n){let r=e.length,o=En<<3|n,i=o;for(let a=0;a<10;a++)i=i<<1^(i>>>9)*1335;let s=(o<<10|i)^21522;for(let a=0;a<=5;a++)S(e,t,8,a,(s>>>a&1)!==0);S(e,t,8,7,(s>>>6&1)!==0),S(e,t,8,8,(s>>>7&1)!==0),S(e,t,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)S(e,t,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)S(e,t,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)S(e,t,8,r-15+a,(s>>>a&1)!==0)}function Tn(e,t,n){let r=e.length,o=n;for(let s=0;s<12;s++)o=o<<1^(o>>>11)*7973;let i=n<<12|o;for(let s=0;s<18;s++){let a=(i>>>s&1)!==0,d=r-11+s%3,u=Math.floor(s/3);S(e,t,d,u,a),S(e,t,u,d,a)}}function Mn(e,t,n){let r=e.length,o=0;for(let i=r-1;i>=1;i-=2){i===6&&(i=5);for(let s=0;s<r;s++)for(let a=0;a<2;a++){let d=i-a,p=(i+1&2)===0?r-1-s:s;!t[p][d]&&o<n.length*8&&(e[p][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function Ie(e,t,n){let r=e.length;for(let o=0;o<r;o++)for(let i=0;i<r;i++){if(t[o][i])continue;let s;switch(n){case 0:s=(i+o)%2===0;break;case 1:s=o%2===0;break;case 2:s=i%3===0;break;case 3:s=(i+o)%3===0;break;case 4:s=(Math.floor(i/3)+Math.floor(o/2))%2===0;break;case 5:s=i*o%2+i*o%3===0;break;case 6:s=(i*o%2+i*o%3)%2===0;break;default:s=((i+o)%2+i*o%3)%2===0;break}s&&(e[o][i]=!e[o][i])}}function Sn(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,u=0;for(let p=0;p<t;p++)p===0||e[a][p]!==d?(d=e[a][p],u=1):(u++,u===5?n+=3:u>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,u=0;for(let p=0;p<t;p++)p===0||e[p][a]!==d?(d=e[p][a],u=1):(u++,u===5?n+=3:u>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let u=e[a][d];u===e[a][d+1]&&u===e[a+1][d]&&u===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((k,m)=>a[d+m]===k))return 0;let f=d>=4&&a.slice(d-4,d).every(k=>!k),C=d+11<=a.length&&a.slice(d+7,d+11).every(k=>!k);return(f?40:0)+(C?40:0)};for(let a=0;a<t;a++){let d=e[a],u=e.map(p=>p[a]);for(let p=0;p+7<=t;p++)n+=r(d,p),n+=r(u,p)}let o=0;for(let a of e)for(let d of a)d&&o++;let i=t*t,s=Math.ceil(Math.abs(o*20-i*10)/i)-1;return n+=s*10,n}var He="http://www.w3.org/2000/svg";function Ke(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let p=0;p<e.size;p++)for(let f=0;f<e.size;f++)e.modules[p][f]&&(s+=`M${f+o} ${p+o}h1v1h-1z`);let a=document.createElementNS(He,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(He,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let u=document.createElementNS(He,"path");return u.setAttribute("d",s),u.setAttribute("fill",n),a.appendChild(u),a}var Tt="/.well-known/enbox-connect";async function Te(e){try{let t=new URL(Tt,e).toString(),n=await fetch(t,{signal:AbortSignal.timeout(6e3)});if(!n.ok)return;let r=await n.json();return typeof r?.connectServerUrl!="string"?void 0:{connectServerUrl:r.connectServerUrl}}catch{return}}async function ze(e){return await Te(e)!==void 0}import{DidJwk as Dn}from"@enbox/dids";import{X25519 as Wn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as On,openResponse as Ln,randomToken as Mt,RelayClientTransport as Nn,resolveDelegatePortableDid as An,sealRequest as qn}from"@enbox/connect";var Ge=6,ee=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function Un(e){return new Promise(t=>{if(typeof document>"u"){setTimeout(t,e);return}let n=()=>{clearTimeout(o),document.removeEventListener("visibilitychange",r),t()},r=()=>{document.visibilityState==="visible"&&n()},o=setTimeout(n,e);document.addEventListener("visibilitychange",r)})}async function Ye(e){if(e.requestType==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let t=e.createTransport??(x=>new Nn({...x,sleep:Un})),n=e.cancelled===void 0?void 0:new AbortController,r=t({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed,signal:n?.signal}),o=await Dn.create(),i=await Wn.generateKey(),s={kty:"OKP",crv:"X25519",x:i.x},a=Mt(),d=Mt(),u=await r.requestProfile(d),p={clientDid:o.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,delegateDid:e.delegatePortableDid?.uri,requestType:e.requestType,supportedDidMethods:["did:dht","did:jwk"],nonce:a,state:d,responseKey:s,reply:u.reply},f=await qn({request:p,signer:o,encryption:u.encryption}),C=await r.deliverRequest(f);C!==void 0&&e.onWalletUriReady(C);let k=e.cancelled===void 0?r.awaitResponse():Promise.race([r.awaitResponse(),e.cancelled]),m;try{m=await k}catch(x){throw n?.abort(),x}if(m===On)return;let v;for(let x=1;x<=Ge;x++){let fe=await(e.cancelled===void 0?e.requestPin(x,v):Promise.race([e.requestPin(x,v),e.cancelled]));try{let M=await Ln({jwe:m,recipientPrivateKey:i,expected:{clientDid:o.uri,nonce:a,state:d},pin:fe}),R=An({localDelegatePortableDid:e.delegatePortableDid,response:M});return r.confirmComplete?.().catch(()=>{}),{delegatePortableDid:R,delegateGrants:M.delegateGrants,connectedDid:M.providerDid,sessionRevocations:M.sessionRevocations}}catch(M){let R=M instanceof Error?M:new Error(String(M));if(R.message.startsWith("Connect:"))throw R;v=R}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ge} attempts.`)}var Ot="enbox:connect:lastChoice",Hn=12e4,Bn=1e4,Me=4,jn=4,St=3,Fe={background:"--ec-bg",surface:"--ec-surface",text:"--ec-text",textMuted:"--ec-muted",border:"--ec-border",accent:"--ec-accent",accentContrast:"--ec-accent-contrast",danger:"--ec-danger",success:"--ec-success"};async function Lt(e){return(await Te(e))?.connectServerUrl}async function $n(e){let t=new Z({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new In({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.requestType})}function Kn(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function zn(){return{runRelay:Ye,runPopup:$n,discoverConnectServerUrl:Lt,validateWalletUrl:ze,isMobile:Kn,storage:typeof localStorage>"u"?void 0:localStorage}}function Gn(e){try{let t=e?.getItem(Ot);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&Jn(n.walletUrl))return{method:n.method,walletUrl:n.walletUrl}}catch{}}function Yn(e,t){try{e?.setItem(Ot,JSON.stringify(t))}catch{}}function Fn(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new ee))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Qe(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");if(e.mode==="refresh"&&e.delegatePortableDid===void 0)throw new Error("Connect: refresh requests require an existing `delegatePortableDid`.");let t={...zn(),...e.deps},n=Vn(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=e.mode==="refresh",d=r?Gn(t.storage):void 0,u=d!==void 0&&(a||Qn(n,d.walletUrl))?d.walletUrl:void 0,p=e.walletUrl!==void 0||a&&u!==void 0,f=e.walletUrl??u??n[0]?.url,C=e.preferredMethod??d?.method??"phone";return new Promise((k,m)=>{let v=document.createElement("div");v.id="enbox-connect-modal";let x=v.attachShadow({mode:"open"}),fe=document.createElement("style");fe.textContent=to,x.appendChild(fe);let M=document.createElement("div");M.className="overlay";let R=document.createElement("div");R.className="modal",R.setAttribute("role","dialog"),R.setAttribute("aria-modal","true");let Ve=a?`Reconnect to ${o}`:`Connect to ${o}`;R.setAttribute("aria-label",Ve);let A=e.theme??{},te=A.appearance??"auto";te!=="auto"&&R.setAttribute("data-appearance",te);let De=window.matchMedia?.("(prefers-color-scheme: dark)"),At=A.accent!==void 0||A.accentContrast!==void 0||A.light!==void 0||A.dark!==void 0,Xe=()=>{let l=te==="auto"?De?.matches===!0?"dark":"light":te,c={accent:A.accent,accentContrast:A.accentContrast,...A[l]};for(let y of Object.keys(Fe)){let h=c[y];typeof h=="string"&&h.trim()!==""?R.style.setProperty(Fe[y],h):R.style.removeProperty(Fe[y])}},Ze=()=>Xe();At&&(Xe(),te==="auto"&&De?.addEventListener?.("change",Ze));let O=!1,I,et,me,he=!1,H,tt=new Map,Q=[],ge=l=>n.find(c=>c.url===l)??{name:Xn(l)??l,url:l},qt=()=>{if(f===void 0){Q=n.slice(0,St);return}if(Q.some(c=>c.url===f))return;let l=ge(f);Q=[l,...n.filter(c=>c.url!==l.url)].slice(0,St)},we=l=>{f=l,oe(),ne()},Ut=()=>{I?.cancel(),$(),document.removeEventListener("keydown",ct),document.removeEventListener("visibilitychange",dt),De?.removeEventListener?.("change",Ze);try{document.body.removeChild(v)}catch{}},ve=l=>{O||(O=!0,Ut(),l())},nt=l=>{r&&Yn(t.storage,{method:C,walletUrl:f??""}),Kt(),setTimeout(()=>ve(()=>k(l)),1200)},We=()=>ve(()=>m(new Error("[@enbox/browser] Connect cancelled.")));R.appendChild(Zn(Ve,e.appIcon,We));let B=document.createElement("div");B.className="stage",B.setAttribute("aria-live","polite"),R.appendChild(B);let j=document.createElement("div");j.className="footer",R.appendChild(j);let D=(...l)=>{B.replaceChildren(...l),B.classList.remove("fade-in"),B.offsetWidth,B.classList.add("fade-in")},ot=l=>{D(w("div","spinner"),w("p","stage-caption",l))},It=l=>{let c=I;setTimeout(()=>{O||c!==I||c?.active!==!0||H!==void 0||Bt(l)},0)},rt=(l,c,y)=>{let h=document.createElement("a");return h.className=y,h.href=l.walletUri,h.target="_blank",h.rel="noopener noreferrer",h.addEventListener("click",()=>{It(c)}),h},Ht=l=>{let c=f!==void 0?ge(f):void 0,y=c?.name??"your wallet",h=rt(l,y,"qr-box qr-link");if(h.setAttribute("aria-label",`Open ${y} on this device`),h.replaceChildren(Ke($e(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let _=w("div","qr-logo");_.appendChild(le(c)),h.appendChild(_)}if(s){let _=rt(l,y,"deep-link");c!==void 0&&_.appendChild(le(c)),_.appendChild(w("span","deep-link-label",`Continue in ${y}`)),h.classList.add("compact"),D(_,w("p","stage-subline",`${y} opens in a new tab \u2014 approve there, then come back for your code.`),w("div","stage-divider","or scan with another phone"),h);return}D(h,w("p","stage-caption","Scan with your phone\u2019s camera"),w("p","stage-subline",`${y} stays on your phone \u2014 or click the code to open it here.`))},Bt=l=>{D(w("div","spinner"),w("p","stage-caption",`Finish in ${l}`),w("p","stage-subline",s?`Approve the connection in the ${l} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),Se("Start over",()=>{Oe()}))},jt=()=>{let l=f!==void 0?ge(f).name:"your wallet",c=document.createElement("div");c.className="claimed-pulse",D(c,w("p","stage-caption",`Request received \u2014 approve in ${l}`),w("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},$t=(l,c)=>new Promise(y=>{H=y;let h=f!==void 0?ge(f).name:"your wallet",_=document.createElement("div");_.className="pin-row",c!==void 0&&_.classList.add("shake");let T=[];for(let P=0;P<Me;P++){let E=document.createElement("input");E.className="pin-input",E.type="text",E.inputMode="numeric",E.maxLength=1,E.setAttribute("aria-label",`Code digit ${P+1}`),T.push(E),_.appendChild(E)}let q=()=>{let P=T.map(E=>E.value).join("");if(P.length===Me&&H!==void 0){let E=H;H=void 0,ot("Checking the code\u2026"),E(P)}};T.forEach((P,E)=>{P.addEventListener("input",()=>{P.value=P.value.replace(/\D/g,"").slice(0,1),P.value!==""&&E+1<T.length&&T[E+1].focus(),q()}),P.addEventListener("keydown",U=>{U.key==="Backspace"&&P.value===""&&E>0&&T[E-1].focus()}),P.addEventListener("paste",U=>{let K=(U.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Me);K.length!==0&&(U.preventDefault(),K.split("").forEach((J,W)=>{T[W]!==void 0&&(T[W].value=J)}),T[Math.min(K.length,Me)-1]?.focus(),q())})}),D(w("p","stage-caption",`Enter the code shown in ${h}`),_,...c!==void 0?[w("p","stage-error",`That code doesn\u2019t match \u2014 check ${h}.`)]:[w("p","stage-subline",l===1?"This confirms you\u2019re the one approving.":"")]),T[0].focus()}),Kt=()=>{let l=w("div","check");l.textContent="\u2713",D(l,w("p","stage-caption","You\u2019re connected."))},it=()=>{D(w("p","stage-caption","No problem \u2014 nothing was shared."),ue("Start over",()=>{ne()}),Se("Close",()=>ve(()=>k(void 0))))},be=(l,c)=>{D(w("p","stage-caption",l),ue("Start over",()=>{ne()}),Se("Close",()=>ve(()=>m(c??new Error(`[@enbox/browser] ${l}`)))))},zt=()=>{D(w("p","stage-caption","This wallet can\u2019t connect by phone here."),w("p","stage-subline","You can continue in this browser instead."),ue("Use this browser",()=>{Ee()}))},ye=s?"tab":"window",Gt=()=>{D(w("p","stage-caption","Connect with a wallet in this browser"),w("p","stage-subline",s?"Your wallet opens in a new tab to approve this connection \u2014 no code needed.":"Your wallet opens in a small window to approve this connection."),ue(s?"Open wallet":"Open wallet window",()=>{Ee()}))},Yt=()=>{D(w("div","spinner"),w("p","stage-caption",`Finish in the wallet ${ye}`),w("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},Ft=l=>{D(w("p","stage-caption",l?`Your browser blocked the wallet ${ye}.`:`The wallet ${ye} was closed.`),ue(l?"Open it now":`Reopen ${ye}`,()=>{Ee()}),Se(s?"Use a code instead":"Use your phone instead",()=>{lt("phone")}))},at=l=>{if(O)return;let c=l instanceof Error?l:new Error(String(l)),y=/popup blocked/i.test(c.message);if(l instanceof F||y){Ft(y);return}be(/timed out/i.test(c.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",c)},Qt=async l=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let c=tt.get(l);return c===void 0&&(c=t.discoverConnectServerUrl(l),tt.set(l,c)),c},$=()=>{clearTimeout(et),me=void 0},st=()=>{!O&&H===void 0&&C==="phone"&&Oe()},Jt=l=>{$();let c=Math.max(Bn,l*1e3-Hn);me=Date.now()+c,et=setTimeout(st,c)},Oe=async()=>{if(I?.cancel(),$(),f===void 0){be("No wallet is configured.");return}C="phone",oe(),ot("Getting things ready\u2026");let l=new URL(f).origin,c=await Qt(l);if(c===void 0){zt();return}let y=Fn();I=y;try{let h=await t.runRelay({connectServerUrl:c,walletUri:new URL(i,l).toString(),appName:o,appIcon:e.appIcon,clientMetadata:Re(),permissionRequests:e.permissionRequests,delegatePortableDid:e.delegatePortableDid,requestType:e.mode,timeoutMs:e.timeout,cancelled:y.cancelled,onWalletUriReady:_=>{y.active&&!O&&(Ht(_),Jt(_.expiresIn))},onClaimed:()=>{y.active&&!O&&($(),jt())},requestPin:(_,T)=>($(),$t(_,T))});if(!y.active||O)return;h===void 0?it():nt(h)}catch(h){if(!y.active||O||h instanceof ee)return;let _=h instanceof Error?h:new Error(String(h));be(/timed out/i.test(_.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",_)}},Ee=()=>{if(I?.cancel(),$(),f===void 0){be("No wallet is configured.");return}if(!he){C="browser",oe(),he=!0,Yt();try{t.runPopup({walletUrl:f,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout,delegatePortableDid:e.delegatePortableDid,requestType:e.mode}).then(l=>{O||(l===void 0?it():nt(l))}).catch(at).finally(()=>{he=!1})}catch(l){he=!1,at(l)}}},ne=async()=>{C==="browser"?(I?.cancel(),$(),oe(),Gt()):await Oe()},lt=async l=>{C=l,await ne()},oe=()=>{if(j.replaceChildren(),!p){qt();let c=Vt();c.label!==void 0&&j.appendChild(c.label),j.appendChild(c.row),j.appendChild(c.panel)}let l=document.createElement("div");if(l.className="footer-row",C==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Or connect without a code \u2192":"No phone? Use this browser \u2192",c.addEventListener("click",()=>{Ee()}),l.appendChild(c)}else{let c=document.createElement("button");c.className="footer-link method-link",c.textContent=s?"Use a code instead \u2192":"Use your phone instead \u2192",c.addEventListener("click",()=>{lt("phone")}),l.appendChild(c)}l.childElementCount>0&&j.appendChild(l)},Vt=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let g of Q){let b=document.createElement("button");b.className="row-tile",b.title=g.description??g.name,b.setAttribute("role","radio");let L=g.url===f;b.setAttribute("aria-checked",L?"true":"false"),L&&b.classList.add("selected"),b.appendChild(le(g)),b.appendChild(w("span","row-tile-name",g.name)),b.addEventListener("click",()=>{g.url!==f&&we(g.url)}),l.appendChild(b)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let y=n.filter(g=>!Q.some(b=>b.url===g.url)),h=document.createElement("button");h.className="row-tile more-tile",h.title="All wallets",h.setAttribute("aria-expanded","false"),h.appendChild(w("span","more-count",y.length>0?`+${y.length}`:"\u22EF")),h.appendChild(w("span","row-tile-name","More")),h.addEventListener("click",()=>{c.hidden=!c.hidden,h.setAttribute("aria-expanded",c.hidden?"false":"true"),c.hidden||K()}),l.appendChild(h);let _=Q.length>0?w("div","wallet-row-label","Connecting with"):void 0,T=[],q=document.createElement("div");if(q.className="wallet-empty",q.textContent="No other wallets match your search.",q.hidden=!0,y.length>jn){let g=document.createElement("input");g.type="search",g.className="wallet-search",g.placeholder="Search wallets\u2026",g.setAttribute("aria-label","Search wallets"),g.addEventListener("input",()=>{let b=g.value.trim().toLowerCase(),L=0;for(let{wallet:ut,el:Xt}of T){let ft=b===""||ut.name.toLowerCase().includes(b)||ut.url.toLowerCase().includes(b);Xt.hidden=!ft,ft&&(L+=1)}q.hidden=L>0,K()}),c.appendChild(g)}let P=document.createElement("div");P.className="wallet-scroll-wrap",P.hidden=y.length===0;let E=document.createElement("div");E.className="wallet-scroll";let U=document.createElement("div");U.className="wallet-grid";let K=()=>{let g=E.scrollHeight-E.clientHeight>1,b=E.scrollTop+E.clientHeight>=E.scrollHeight-1;P.classList.toggle("scroll-hint",g&&!b)};E.addEventListener("scroll",K);for(let g of y){let b=document.createElement("button");b.className="wallet-tile",b.title=g.description??g.name,b.appendChild(le(g));let L=document.createElement("span");L.className="wallet-tile-name",L.textContent=g.name,b.appendChild(L),b.addEventListener("click",()=>{we(g.url)}),T.push({wallet:g,el:b}),U.appendChild(b)}E.appendChild(U),E.appendChild(q),P.appendChild(E),c.appendChild(P);let J=document.createElement("div");J.className="wallet-custom";let W=document.createElement("input");W.className="url-input",W.type="url",W.placeholder="https://your-wallet.example";let N=document.createElement("button");N.className="url-go",N.textContent="Use";let z=document.createElement("div");z.className="url-error",z.hidden=!0;let Le=!1,pt=async()=>{let g=W.value.trim();if(g==="")return;let b;try{b=new URL(g.includes("://")?g:`https://${g}`).origin}catch{W.classList.add("invalid");return}if(Le){we(b);return}N.disabled=!0,N.textContent="Checking\u2026",z.hidden=!0;let L=await t.validateWalletUrl(b);if(N.disabled=!1,L){N.textContent="Use",we(b);return}Le=!0,N.textContent="Use anyway",W.classList.add("invalid"),z.textContent=`Couldn't verify a wallet at ${b}.`,z.hidden=!1};return W.addEventListener("input",()=>{Le=!1,N.textContent="Use",W.classList.remove("invalid"),z.hidden=!0}),W.addEventListener("keydown",g=>{g.key==="Enter"&&pt()}),N.addEventListener("click",()=>{pt()}),J.appendChild(W),J.appendChild(N),c.appendChild(J),c.appendChild(z),{label:_,row:l,panel:c}};M.addEventListener("click",l=>{l.target===M&&We()});let ct=l=>{if(l.key==="Escape"){We();return}l.key==="Tab"&&eo(x,l)};document.addEventListener("keydown",ct);let dt=()=>{if(!(document.visibilityState!=="visible"||O)){if(me!==void 0&&Date.now()>=me){st();return}H!==void 0&&Array.from(x.querySelectorAll(".pin-input")).find(c=>c.value==="")?.focus()}};document.addEventListener("visibilitychange",dt),M.appendChild(R),x.appendChild(M),document.body.appendChild(v),oe(),ne()})}function Qn(e,t){return e.some(n=>n.url===t)}function Jn(e){if(typeof e!="string"||e.trim()==="")return!1;try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Vn(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Xn(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function w(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function ue(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Se(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function Zn(e,t,n){let r=document.createElement("div");r.className="header";let o=document.createElement("div");if(o.className="header-identity",t!==void 0){let a=document.createElement("img");a.className="header-icon",a.src=t,a.alt="",a.width=24,a.height=24,a.addEventListener("error",()=>a.remove()),o.appendChild(a)}let i=document.createElement("h2");i.textContent=e,o.appendChild(i);let s=document.createElement("button");return s.className="close-btn",s.setAttribute("aria-label","Close"),s.textContent="\xD7",s.addEventListener("click",n),r.appendChild(o),r.appendChild(s),r}function eo(e,t){let n=Array.from(e.querySelectorAll('button, input, a[href], [tabindex]:not([tabindex="-1"])')).filter(s=>!s.hasAttribute("disabled")&&s.offsetParent!==null);if(n.length===0)return;let r=n[0],o=n[n.length-1],i=e.activeElement;t.shiftKey&&(i===r||i===null)?(t.preventDefault(),o.focus()):!t.shiftKey&&i===o&&(t.preventDefault(),r.focus())}var Dt=`
155
155
  --ec-bg: #ffffff;
156
156
  --ec-surface: #f5f6f8;
157
157
  --ec-text: #17171f;
@@ -536,5 +536,5 @@ import{Enbox as Ko,defineProtocol as zo,repository as Go}from"@enbox/api";import
536
536
  .overlay, .modal, .stage.fade-in > *, .pin-row.shake { animation: none; }
537
537
  .claimed-pulse::after { animation: none; }
538
538
  }
539
- `;var Nt=[{name:"Enbox",url:"https://enbox-wallet.pages.dev",description:"Manage your digital identity and data"},{name:"Prism",url:"https://prism-wallet.pages.dev",description:"A clear view into your digital identity"},{name:"Matcha",url:"https://matcha-wallet.pages.dev",description:"A fresh approach to digital identity"},{name:"Onyx",url:"https://onyx-wallet.pages.dev",description:"A refined home for your digital identity"},{name:"Taffy",url:"https://taffy-wallet.pages.dev",description:"A playful take on your digital identity"},{name:"Astoria",url:"https://astoria-wallet.pages.dev",description:"A grand home for your digital identity"}];function no(e={}){let{wallets:t=Nt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:u,theme:p}=e;return{async requestAccess(f){return Qe({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:u,timeout:r,theme:p,mode:f.requestType,delegatePortableDid:f.delegatePortableDid,permissionRequests:f.permissionRequests})}}}import{X25519 as oo}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as ro,ConnectProvider as io}from"@enbox/connect";var ao=3e5,so=5e3,Je=class e{constructor(t){this._requestReceived=!1;this._dappOrigin=t.dappOrigin,this._dappWindow=t.dappWindow,this._recipientPrivateKey=t.recipientPrivateKey,this._requestPromise=new Promise((n,r)=>{this._resolveRequest=n,this._rejectRequest=r}),this._requestPromise.catch(()=>{}),this._messageListener=n=>{this.onMessage(n)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.close(),this._rejectRequest?.(new Error("[@enbox/browser] Timed out waiting for the connect request from the dapp."))},t.timeoutMs)}static async create(t={}){if(typeof window>"u")throw new Error("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let n=t.dappWindow??window.opener;if(!n)throw new Error("[@enbox/browser] No opener window: the DWeb Connect page must be opened as a popup by the dapp.");let r=lo(t.dappOrigin),o=await oo.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??ao});return n.postMessage({type:de,walletEpk:i,walletOrigin:globalThis.location.origin},r),s}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(t){this._dappWindow.postMessage({type:Z,payload:t},this._dappOrigin),this.close()}async sendResponseAwaitingAck(t,n={}){let r=new Promise(s=>{this._resolveAck=s});this._dappWindow.postMessage({type:Z,payload:t},this._dappOrigin);let o=setTimeout(()=>{this._resolveAck?.(!1)},n.timeoutMs??so),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(ro)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=ke(t,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===ue){this._resolveAck?.(!0);return}if(!(n.type!==pe||this._requestReceived)){if(this._requestReceived=!0,typeof n.jwe!="string"){this.settleRequest(new Error("[@enbox/browser] Connect request message did not carry a ciphertext payload."));return}this.openRequest(n.jwe)}}}async openRequest(t){try{let n=await io.openRequest({jwe:t,decryption:{mode:"ecdh-es",recipientPrivateKey:this._recipientPrivateKey,walletOrigin:globalThis.location.origin}});if(n.reply.mode!=="post_message"){this.settleRequest(new Error("[@enbox/browser] Connect request over the popup channel must use the `post_message` reply mode."));return}this.settleRequest(n)}catch(n){this.settleRequest(n instanceof Error?n:new Error(String(n)))}}settleRequest(t){if(clearTimeout(this._timeoutId),t instanceof Error){this.close(),this._rejectRequest?.(t);return}this._resolveRequest?.(t)}};function lo(e){if(e!==void 0)return new URL(e).origin;if(document.referrer)return new URL(document.referrer).origin;throw new Error("[@enbox/browser] Unable to determine the dapp origin: no `dappOrigin` option was provided and `document.referrer` is empty.")}import{TypedRecord as gr}from"@enbox/api";import{BrowserStorage as vr}from"@enbox/auth/browser";import{DwnInterface as yr}from"@enbox/agent";import{DateSort as xr,DwnInterfaceName as Cr,DwnMethodName as _r}from"@enbox/dwn-sdk-js";export{Fo as AuthManager,Qo as AuthSession,no as BrowserConnectHandler,vr as BrowserStorage,rr as CONNECT_DENIED_TOKEN,ir as ConnectProvider,Nt as DEFAULT_WALLETS,ue as DWEB_CONNECT_ACK_MESSAGE_TYPE,de as DWEB_CONNECT_LOADED_MESSAGE_TYPE,qe as DWEB_CONNECT_PATH,pe as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,Z as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,xr as DateSort,yr as DwnInterface,Cr as DwnInterfaceName,_r as DwnMethodName,Ko as Enbox,Ge as MAX_PIN_ATTEMPTS,ee as PopupClientTransport,Q as PopupWindowClosedError,te as RelayConnectCancelledError,Jo as SESSION_EXPIRED_ERROR_CODE,Vo as SESSION_REVOKED_ERROR_CODE,gr as TypedRecord,Tt as WALLET_WELL_KNOWN_PATH,nr as WalletConnect,Je as WalletPostMessageTransport,fo as activatePolyfills,on as cacheResponse,ho as clearDrlCache,Xo as computeConnectionStatus,yn as connectViaPopup,mo as deactivatePolyfills,zo as defineProtocol,Lt as discoverWalletConnectServerUrl,$e as encodeQr,nn as fetchResource,Te as fetchWalletWellKnown,vt as getDwnEndpoints,tn as handleEvent,Zo as isSessionExpiredError,er as isSessionInvalidError,tr as normalizeProtocolRequests,ie as parseDrlUrl,ze as probeWalletWellKnown,Ke as qrToSvg,Go as repository,Qe as runConnectModal,Ye as runRelayConnect};
539
+ `;var Nt=[{name:"Enbox",url:"https://enbox-wallet.pages.dev",description:"Manage your digital identity and data"},{name:"Prism",url:"https://prism-wallet.pages.dev",description:"A clear view into your digital identity"},{name:"Matcha",url:"https://matcha-wallet.pages.dev",description:"A fresh approach to digital identity"},{name:"Onyx",url:"https://onyx-wallet.pages.dev",description:"A refined home for your digital identity"},{name:"Taffy",url:"https://taffy-wallet.pages.dev",description:"A playful take on your digital identity"},{name:"Astoria",url:"https://astoria-wallet.pages.dev",description:"A grand home for your digital identity"}];function no(e={}){let{wallets:t=Nt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:u,theme:p}=e;return{async requestAccess(f){return Qe({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:u,timeout:r,theme:p,mode:f.requestType,delegatePortableDid:f.delegatePortableDid,permissionRequests:f.permissionRequests})}}}import{X25519 as oo}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as ro,ConnectProvider as io}from"@enbox/connect";var ao=3e5,so=5e3,Je=class e{constructor(t){this._requestReceived=!1;this._dappOrigin=t.dappOrigin,this._dappWindow=t.dappWindow,this._recipientPrivateKey=t.recipientPrivateKey,this._requestPromise=new Promise((n,r)=>{this._resolveRequest=n,this._rejectRequest=r}),this._requestPromise.catch(()=>{}),this._messageListener=n=>{this.onMessage(n)},window.addEventListener("message",this._messageListener),this._timeoutId=setTimeout(()=>{this.close(),this._rejectRequest?.(new Error("[@enbox/browser] Timed out waiting for the connect request from the dapp."))},t.timeoutMs)}static async create(t={}){if(typeof window>"u")throw new Error("[@enbox/browser] WalletPostMessageTransport is only available in browser environments.");let n=t.dappWindow??window.opener;if(!n)throw new Error("[@enbox/browser] No opener window: the DWeb Connect page must be opened as a popup by the dapp.");let r=lo(t.dappOrigin),o=await oo.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??ao});return n.postMessage({type:ce,walletEpk:i,walletOrigin:globalThis.location.origin},r),s}get dappOrigin(){return this._dappOrigin}async awaitRequest(){return await this._requestPromise}sendResponse(t){this._dappWindow.postMessage({type:X,payload:t},this._dappOrigin),this.close()}async sendResponseAwaitingAck(t,n={}){let r=new Promise(s=>{this._resolveAck=s});this._dappWindow.postMessage({type:X,payload:t},this._dappOrigin);let o=setTimeout(()=>{this._resolveAck?.(!1)},n.timeoutMs??so),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(ro)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=ke(t,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===pe){this._resolveAck?.(!0);return}if(!(n.type!==de||this._requestReceived)){if(this._requestReceived=!0,typeof n.jwe!="string"){this.settleRequest(new Error("[@enbox/browser] Connect request message did not carry a ciphertext payload."));return}this.openRequest(n.jwe)}}}async openRequest(t){try{let n=await io.openRequest({jwe:t,decryption:{mode:"ecdh-es",recipientPrivateKey:this._recipientPrivateKey,walletOrigin:globalThis.location.origin}});if(n.reply.mode!=="post_message"){this.settleRequest(new Error("[@enbox/browser] Connect request over the popup channel must use the `post_message` reply mode."));return}this.settleRequest(n)}catch(n){this.settleRequest(n instanceof Error?n:new Error(String(n)))}}settleRequest(t){if(clearTimeout(this._timeoutId),t instanceof Error){this.close(),this._rejectRequest?.(t);return}this._resolveRequest?.(t)}};function lo(e){if(e!==void 0)return new URL(e).origin;if(document.referrer)return new URL(document.referrer).origin;throw new Error("[@enbox/browser] Unable to determine the dapp origin: no `dappOrigin` option was provided and `document.referrer` is empty.")}import{TypedRecord as gr}from"@enbox/api";import{BrowserStorage as vr}from"@enbox/auth/browser";import{DwnInterface as yr}from"@enbox/agent";import{DateSort as xr,DwnInterfaceName as Cr,DwnMethodName as _r}from"@enbox/dwn-sdk-js";export{Fo as AuthManager,Qo as AuthSession,no as BrowserConnectHandler,vr as BrowserStorage,rr as CONNECT_DENIED_TOKEN,ir as ConnectProvider,Nt as DEFAULT_WALLETS,pe as DWEB_CONNECT_ACK_MESSAGE_TYPE,ce as DWEB_CONNECT_LOADED_MESSAGE_TYPE,qe as DWEB_CONNECT_PATH,de as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,X as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,xr as DateSort,yr as DwnInterface,Cr as DwnInterfaceName,_r as DwnMethodName,Ko as Enbox,Ge as MAX_PIN_ATTEMPTS,Z as PopupClientTransport,F as PopupWindowClosedError,ee as RelayConnectCancelledError,Jo as SESSION_EXPIRED_ERROR_CODE,Vo as SESSION_REVOKED_ERROR_CODE,gr as TypedRecord,Tt as WALLET_WELL_KNOWN_PATH,nr as WalletConnect,Je as WalletPostMessageTransport,fo as activatePolyfills,on as cacheResponse,ho as clearDrlCache,Xo as computeConnectionStatus,yn as connectViaPopup,mo as deactivatePolyfills,zo as defineProtocol,Lt as discoverWalletConnectServerUrl,$e as encodeQr,nn as fetchResource,Te as fetchWalletWellKnown,vt as getDwnEndpoints,tn as handleEvent,Zo as isSessionExpiredError,er as isSessionInvalidError,tr as normalizeProtocolRequests,re as parseDrlUrl,ze as probeWalletWellKnown,Ke as qrToSvg,Go as repository,Qe as runConnectModal,Ye as runRelayConnect};
540
540
  //# sourceMappingURL=browser.mjs.map