@enbox/browser 0.3.48 → 0.3.51

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.
Files changed (37) hide show
  1. package/dist/browser.mjs +58 -46
  2. package/dist/browser.mjs.map +3 -3
  3. package/dist/esm/browser-connect-handler.js +10 -0
  4. package/dist/esm/browser-connect-handler.js.map +1 -1
  5. package/dist/esm/dweb-connect-client.js +64 -9
  6. package/dist/esm/dweb-connect-client.js.map +1 -1
  7. package/dist/esm/dweb-connect-messages.js +7 -1
  8. package/dist/esm/dweb-connect-messages.js.map +1 -1
  9. package/dist/esm/dweb-connect-wallet.js +48 -2
  10. package/dist/esm/dweb-connect-wallet.js.map +1 -1
  11. package/dist/esm/index.js +1 -1
  12. package/dist/esm/index.js.map +1 -1
  13. package/dist/esm/relay-connect-runner.js +35 -2
  14. package/dist/esm/relay-connect-runner.js.map +1 -1
  15. package/dist/esm/ui/connect-modal.js +220 -101
  16. package/dist/esm/ui/connect-modal.js.map +1 -1
  17. package/dist/types/browser-connect-handler.d.ts.map +1 -1
  18. package/dist/types/dweb-connect-client.d.ts +9 -0
  19. package/dist/types/dweb-connect-client.d.ts.map +1 -1
  20. package/dist/types/dweb-connect-messages.d.ts +14 -1
  21. package/dist/types/dweb-connect-messages.d.ts.map +1 -1
  22. package/dist/types/dweb-connect-wallet.d.ts +23 -1
  23. package/dist/types/dweb-connect-wallet.d.ts.map +1 -1
  24. package/dist/types/index.d.ts +2 -2
  25. package/dist/types/index.d.ts.map +1 -1
  26. package/dist/types/relay-connect-runner.d.ts +11 -1
  27. package/dist/types/relay-connect-runner.d.ts.map +1 -1
  28. package/dist/types/ui/connect-modal.d.ts +11 -10
  29. package/dist/types/ui/connect-modal.d.ts.map +1 -1
  30. package/package.json +6 -6
  31. package/src/browser-connect-handler.ts +10 -0
  32. package/src/dweb-connect-client.ts +61 -7
  33. package/src/dweb-connect-messages.ts +16 -1
  34. package/src/dweb-connect-wallet.ts +50 -1
  35. package/src/index.ts +2 -0
  36. package/src/relay-connect-runner.ts +42 -2
  37. package/src/ui/connect-modal.ts +246 -110
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import{AuthManager as Po,AuthSession as Ro,normalizeProtocolRequests as Mo,WalletConnect as To}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as Wo,ConnectProvider as Lo}from"@enbox/connect";import{DidDht as At,DidWeb as Ut,UniversalResolver as ot}from"@enbox/dids";function ee(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 ke=new ot({didResolvers:[At,Ut]}),rt=/^http:/,me=/\/$/,it="drl";async function at(e){let{didDocument:t}=await ke.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 st(){if(!(typeof caches>"u"))return caches.open(it)}async function qt(e,t,n,r){let o=e.request.url.replace(rt,"https:").replace(me,""),i=await st(),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 It(e,t,o,n,i,r);{let a=await ke.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 It(e,t,n,r,o,i){let s=await at(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 p=`${d.replace(me,"")}/${t}/${r}`,u=await fetch(p,{headers:e.request.headers});if(u.ok)return await i?.onCacheCheck?.(e,n)&&o&&Bt(n,p,u,o),u;console.log(`DWN endpoint error: ${u.status}`),a=new Response("DWeb Node request failed",{status:u.status})}catch(p){console.log(`DWN endpoint error: ${p}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function Bt(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 jt(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=ee(n.request.url);r&&n.respondWith(qt(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 lt=`
1
+ import{Enbox as qo,defineProtocol as Io,repository as Ho}from"@enbox/api";import{AuthManager as jo,AuthSession as $o,normalizeProtocolRequests as Ko,WalletConnect as zo}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as Yo,ConnectProvider as Fo}from"@enbox/connect";import{DidDht as Qt,DidWeb as Jt,UniversalResolver as ut}from"@enbox/dids";function oe(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 ut({didResolvers:[Qt,Jt]}),ft=/^http:/,ye=/\/$/,mt="drl";async function ht(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 gt(){if(!(typeof caches>"u"))return caches.open(mt)}async function Xt(e,t,n,r){let o=e.request.url.replace(ft,"https:").replace(ye,""),i=await gt(),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 Vt(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 Vt(e,t,n,r,o,i){let s=await ht(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 p=`${d.replace(ye,"")}/${t}/${r}`,u=await fetch(p,{headers:e.request.headers});if(u.ok)return await i?.onCacheCheck?.(e,n)&&o&&Zt(n,p,u,o),u;console.log(`DWN endpoint error: ${u.status}`),a=new Response("DWeb Node request failed",{status:u.status})}catch(p){console.log(`DWN endpoint error: ${p}`),a=new Response("DWeb Node request failed",{status:500})}return a}async function Zt(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 en(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=oe(n.request.url);r&&n.respondWith(Xt(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 wt=`
2
2
  .drl-loading-overlay {
3
3
  position: fixed;
4
4
  inset: 0;
@@ -103,7 +103,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
103
103
  opacity: 0;
104
104
  }
105
105
  }
106
- `,Ht=`
106
+ `,tn=`
107
107
  <!DOCTYPE html>
108
108
  <html lang='en'>
109
109
  <head>
@@ -119,7 +119,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
119
119
  font-family: Arial, sans-serif;
120
120
  text-align: center;
121
121
  }
122
- ${lt}
122
+ ${wt}
123
123
  </style>
124
124
  </head>
125
125
  <body>
@@ -132,8 +132,8 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
132
132
  </div>
133
133
  </body>
134
134
  </html>
135
- `,he=!1,H=null,te=null;function nt(){he||(te=document.createElement("style"),te.innerHTML=`
136
- ${lt}
135
+ `,Ee=!1,z=null,re=null;function pt(){Ee||(re=document.createElement("style"),re.innerHTML=`
136
+ ${wt}
137
137
 
138
138
  .drl-loading-overlay {
139
139
  opacity: 0;
@@ -145,13 +145,13 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
145
145
  opacity: 1;
146
146
  pointer-events: all;
147
147
  }
148
- `,document.head.append(te),H=document.createElement("div"),H.classList.add("drl-loading-overlay"),H.innerHTML=`
148
+ `,document.head.append(re),z=document.createElement("div"),z.classList.add("drl-loading-overlay"),z.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
- `,H.lastElementChild.addEventListener("click",Pe),document.body.prepend(H),he=!0)}function zt(){he&&(te?.remove(),te=null,H?.remove(),H=null,he=!1)}function Pe(){document.documentElement.removeAttribute("drl-link-loading"),fe=null}var fe=null,ge=!1,ne=null,oe=null;function Kt(){ge||(ne=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=ee(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(Ht)):(fe=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await at(o);if(!d.length)throw new Error("no valid DWN endpoints found");let p=`${d[0].replace(me,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=p):fe===i&&(window.location.href=p)}catch{throw fe===i&&Pe(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},oe=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(G(),t?.src&&ee(t.src)){z=t,t.__src__=t.src;let n=t.src.replace(rt,"https:").replace(me,""),o=await(await st())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",G,{once:!0})}}else t===z&&G()},document.addEventListener("click",ne),document.addEventListener("pointercancel",G),document.addEventListener("pointerdown",oe),ge=!0)}function $t(){ge&&(ne&&(document.removeEventListener("click",ne),ne=null),oe&&(document.removeEventListener("pointerdown",oe),oe=null),document.removeEventListener("pointercancel",G),G(),Pe(),ge=!1)}var z=null;async function G(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),z&&(z.src=z.__src__,delete z.__src__,z=null)}function Kn(e={}){e.didResolvers&&(ke=new ot({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&jt(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",nt,{once:!0}):nt()),e.links!==!1&&Kt())}function $n(){typeof window<"u"&&typeof window.document<"u"&&($t(),zt())}async function Gn(){return typeof caches>"u"?!1:caches.delete(it)}import{ConnectClient as bn}from"@enbox/connect";function re(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=Gt(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 Gt(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 Yt,CONNECT_DENIED_TOKEN as Ft,ConnectClient as Jt}from"@enbox/connect";var Re="/dweb-connect",ie="enbox-connect-loaded",ae="enbox-connect-request",se="enbox-connect-response";function we(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var Qt=3e5,Xt=500,Vt="enbox-dweb-connect",Zt="width=500,height=700,menubar=no,toolbar=no,location=no,status=no";function en(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var K=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},Y=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;en(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??Qt;let n=new URL(Re,t.walletUrl).toString(),r=window.open(n,Vt,Zt);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()},Xt)}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:ae,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}onMessage(t){let n=we(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===ie){this.onLoadedBeacon(n);return}n.type===se&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{Yt(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 K);return}this._settled=!0,this.cleanup(),this._resolveResponse?.(Ft)}}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 ve(){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 tn(e){let t=new Y({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new Jt({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:ve(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof K)return;throw r}}var pt=[-1,10,16,26,18,24,16,18,22,22,26],ut=[-1,1,1,1,2,2,4,4,4,5,5],ft=[-1,26,44,70,100,134,172,196,242,292,346],nn=0,ct=10;function dt(e){return ft[e]-pt[e]*ut[e]}function Ne(e,t){let n=new TextEncoder().encode(e),r=0;for(let f=1;f<=ct;f++){let m=dt(f)*8;if(4+(f<=9?8:16)+n.length*8<=m){r=f;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${ct}-M capacity).`);let o=[],i=(f,m)=>{for(let P=m-1;P>=0;P--)o.push(f>>>P&1)};i(4,4),i(n.length,r<=9?8:16);for(let f of n)i(f,8);let s=dt(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let f=0;o.length<s;f++)i(a[f%2],8);let d=new Uint8Array(s/8);for(let f=0;f<o.length;f++)d[f>>3]|=o[f]<<7-(f&7);let p=on(d,r),u=17+4*r,v=Array.from({length:u},()=>new Array(u).fill(!1)),R=Array.from({length:u},()=>new Array(u).fill(!1));ln(v,R,r),pn(v,R,p);let E=t??-1;if(E===-1){let f=1/0;for(let m=0;m<8;m++){Te(v,R,m),Le(v,R,m);let P=un(v);P<f&&(f=P,E=m),Te(v,R,m)}}return Te(v,R,E),Le(v,R,E),{size:u,modules:v,version:r,mask:E}}function on(e,t){let n=ut[t],r=pt[t],o=ft[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],p=rn(r),u=0;for(let f=0;f<n;f++){let m=s-r+(f<i?0:1),P=e.slice(u,u+m);u+=m,a.push(P),d.push(an(P,p))}let v=new Uint8Array(o),R=0,E=s-r+1;for(let f=0;f<E;f++)for(let m=0;m<n;m++)f<a[m].length&&(v[R++]=a[m][f]);for(let f=0;f<r;f++)for(let m=0;m<n;m++)v[R++]=d[m][f];return v}function We(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 rn(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]=We(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=We(n,2)}return t}function an(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]^=We(t[i],o)}return n}var sn=[[],[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50]];function M(e,t,n,r,o){e[r][n]=o,t[r][n]=!0}function ln(e,t,n){let r=e.length;for(let i=0;i<r;i++)M(e,t,6,i,i%2===0),M(e,t,i,6,i%2===0);Me(e,t,3,3),Me(e,t,r-4,3),Me(e,t,3,r-4);let o=sn[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||cn(e,t,o[i],o[s]);Le(e,t,0),M(e,t,8,r-8,!0),n>=7&&dn(e,t,n)}function Me(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 p=Math.max(Math.abs(s),Math.abs(i));M(e,t,a,d,p!==2&&p!==4)}}function cn(e,t,n,r){for(let o=-2;o<=2;o++)for(let i=-2;i<=2;i++)M(e,t,n+i,r+o,Math.max(Math.abs(i),Math.abs(o))!==1)}function Le(e,t,n){let r=e.length,o=nn<<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++)M(e,t,8,a,(s>>>a&1)!==0);M(e,t,8,7,(s>>>6&1)!==0),M(e,t,8,8,(s>>>7&1)!==0),M(e,t,7,8,(s>>>8&1)!==0);for(let a=9;a<15;a++)M(e,t,14-a,8,(s>>>a&1)!==0);for(let a=0;a<8;a++)M(e,t,r-1-a,8,(s>>>a&1)!==0);for(let a=8;a<15;a++)M(e,t,8,r-15+a,(s>>>a&1)!==0)}function dn(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,p=Math.floor(s/3);M(e,t,d,p,a),M(e,t,p,d,a)}}function pn(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,u=(i+1&2)===0?r-1-s:s;!t[u][d]&&o<n.length*8&&(e[u][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function Te(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 un(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[a][u]!==d?(d=e[a][u],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[u][a]!==d?(d=e[u][a],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let p=e[a][d];p===e[a][d+1]&&p===e[a+1][d]&&p===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((E,f)=>a[d+f]===E))return 0;let v=d>=4&&a.slice(d-4,d).every(E=>!E),R=d+11<=a.length&&a.slice(d+7,d+11).every(E=>!E);return(v?40:0)+(R?40:0)};for(let a=0;a<t;a++){let d=e[a],p=e.map(u=>u[a]);for(let u=0;u+7<=t;u++)n+=r(d,u),n+=r(p,u)}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 Se="http://www.w3.org/2000/svg";function Oe(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let u=0;u<e.size;u++)for(let v=0;v<e.size;v++)e.modules[u][v]&&(s+=`M${v+o} ${u+o}h1v1h-1z`);let a=document.createElementNS(Se,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(Se,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let p=document.createElementNS(Se,"path");return p.setAttribute("d",s),p.setAttribute("fill",n),a.appendChild(p),a}var mt="/.well-known/enbox-connect";async function be(e){try{let t=new URL(mt,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 De(e){return await be(e)!==void 0}import{DidJwk as fn}from"@enbox/dids";import{X25519 as mn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as hn,openResponse as gn,randomToken as ht,RelayClientTransport as wn,sealRequest as vn}from"@enbox/connect";var Ae=6,F=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};async function Ue(e){let n=(e.createTransport??(m=>new wn(m)))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed}),r=await fn.create(),o=await mn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=ht(),a=ht(),d=await n.requestProfile(a),p={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:a,responseKey:i,reply:d.reply},u=await vn({request:p,signer:r,encryption:d.encryption}),v=await n.deliverRequest(u);v!==void 0&&e.onWalletUriReady(v);let E=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(E===hn)return;let f;for(let m=1;m<=Ae;m++){let P=await(e.cancelled===void 0?e.requestPin(m,f):Promise.race([e.requestPin(m,f),e.cancelled]));try{let C=await gn({jwe:E,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:s,state:a},pin:P});if(C.delegatePortableDid===void 0)throw new Error("Connect: wallet response omitted `delegatePortableDid`.");return{delegatePortableDid:C.delegatePortableDid,delegateGrants:C.delegateGrants,connectedDid:C.providerDid,sessionRevocations:C.sessionRevocations}}catch(C){let S=C instanceof Error?C:new Error(String(C));if(S.message.startsWith("Connect:"))throw S;f=S}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ae} attempts.`)}var bt="enbox:connect:lastChoice",yn=3e4,xn=1e4,ye=4,En=4,gt=3,qe={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 yt(e){return(await be(e))?.connectServerUrl}async function Cn(e){let t=new Y({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new bn({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:ve(),permissionRequests:e.permissionRequests})}function _n(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function kn(){return{runRelay:Ue,runPopup:Cn,discoverConnectServerUrl:yt,validateWalletUrl:De,isMobile:_n,storage:typeof localStorage>"u"?void 0:localStorage}}function Pn(e){try{let t=e?.getItem(bt);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&typeof n.walletUrl=="string")return{method:n.method,walletUrl:n.walletUrl}}catch{}}function Rn(e,t){try{e?.setItem(bt,JSON.stringify(t))}catch{}}function Mn(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new F))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Be(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");let t={...kn(),...e.deps},n=Sn(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=r?Pn(t.storage):void 0,d=e.walletUrl!==void 0,p=e.walletUrl??(a!==void 0&&(d||Tn(n,a.walletUrl))?a.walletUrl:void 0)??n[0]?.url,u=e.preferredMethod??a?.method??"phone";return new Promise((v,R)=>{let E=document.createElement("div");E.id="enbox-connect-modal";let f=E.attachShadow({mode:"open"}),m=document.createElement("style");m.textContent=On,f.appendChild(m);let P=document.createElement("div");P.className="overlay";let C=document.createElement("div");C.className="modal",C.setAttribute("role","dialog"),C.setAttribute("aria-modal","true"),C.setAttribute("aria-label",`Connect to ${o}`);let S=e.theme??{},J=S.appearance??"auto";J!=="auto"&&C.setAttribute("data-appearance",J);let xe=window.matchMedia?.("(prefers-color-scheme: dark)"),Et=S.accent!==void 0||S.accentContrast!==void 0||S.light!==void 0||S.dark!==void 0,He=()=>{let l=J==="auto"?xe?.matches===!0?"dark":"light":J,c={accent:S.accent,accentContrast:S.accentContrast,...S[l]};for(let x of Object.keys(qe)){let w=c[x];typeof w=="string"&&w.trim()!==""?C.style.setProperty(qe[x],w):C.style.removeProperty(qe[x])}},ze=()=>He();Et&&(He(),J==="auto"&&xe?.addEventListener?.("change",ze));let O=!1,Q,D,Ee=!1,X,Ke=new Map,$=[],$e=l=>n.find(c=>c.url===l)??{name:Wn(l)??l,url:l},Ct=()=>{if(p===void 0){$=n.slice(0,gt);return}if($.some(c=>c.url===p))return;let l=$e(p);$=[l,...n.filter(c=>c.url!==l.url)].slice(0,gt)},ce=l=>{p=l,Z(),V()},_t=()=>{Q?.cancel(),clearTimeout(D),document.removeEventListener("keydown",Ve),xe?.removeEventListener?.("change",ze);try{document.body.removeChild(E)}catch{}},de=l=>{O||(O=!0,_t(),l())},Ge=l=>{r&&Rn(t.storage,{method:u,walletUrl:p??""}),Mt(),setTimeout(()=>de(()=>v(l)),1200)},Ce=()=>de(()=>R(new Error("[@enbox/browser] Connect cancelled.")));C.appendChild(Ln(o,e.appIcon,Ce));let q=document.createElement("div");q.className="stage",q.setAttribute("aria-live","polite"),C.appendChild(q);let I=document.createElement("div");I.className="footer",C.appendChild(I);let W=(...l)=>{q.replaceChildren(...l),q.classList.remove("fade-in"),q.offsetWidth,q.classList.add("fade-in")},Ye=l=>{W(y("div","spinner"),y("p","stage-caption",l))},kt=l=>{let c=p!==void 0?$e(p):void 0,x=c?.name??"your wallet";if(s){let b=document.createElement("a");b.className="deep-link",b.href=l.walletUri,c!==void 0&&b.appendChild(re(c)),b.appendChild(y("span","deep-link-label",`Continue in ${x}`)),W(b,y("p","stage-caption",`${x} opens to approve this connection.`),y("p","stage-subline","Come back here when you\u2019re done."));return}let w=document.createElement("div");if(w.className="qr-box",w.replaceChildren(Oe(Ne(l.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),c!==void 0){let b=y("div","qr-logo");b.appendChild(re(c)),w.appendChild(b)}W(w,y("p","stage-caption","Scan with your phone\u2019s camera"),y("p","stage-subline",`${x} stays on your phone.`))},Pt=()=>{let l=document.createElement("div");l.className="claimed-pulse",W(l,y("p","stage-caption","Phone connected \u2014 finish there"),y("p","stage-subline","Approve the request on your phone, then come back here."))},Rt=(l,c)=>new Promise(x=>{X=x;let w=document.createElement("div");w.className="pin-row",c!==void 0&&w.classList.add("shake");let b=[];for(let k=0;k<ye;k++){let _=document.createElement("input");_.className="pin-input",_.type="text",_.inputMode="numeric",_.maxLength=1,_.setAttribute("aria-label",`Code digit ${k+1}`),b.push(_),w.appendChild(_)}let B=()=>{let k=b.map(_=>_.value).join("");if(k.length===ye&&X!==void 0){let _=X;X=void 0,Ye("Checking the code\u2026"),_(k)}};b.forEach((k,_)=>{k.addEventListener("input",()=>{k.value=k.value.replace(/\D/g,"").slice(0,1),k.value!==""&&_+1<b.length&&b[_+1].focus(),B()}),k.addEventListener("keydown",A=>{A.key==="Backspace"&&k.value===""&&_>0&&b[_-1].focus()}),k.addEventListener("paste",A=>{let U=(A.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,ye);U.length!==0&&(A.preventDefault(),U.split("").forEach((L,T)=>{b[T]!==void 0&&(b[T].value=L)}),b[Math.min(U.length,ye)-1]?.focus(),B())})}),W(y("p","stage-caption","Enter the code shown on your phone"),w,...c!==void 0?[y("p","stage-error","That code doesn\u2019t match \u2014 check your phone.")]:[y("p","stage-subline",l===1?"Phone connected.":"")]),b[0].focus()}),Mt=()=>{let l=y("div","check");l.textContent="\u2713",W(l,y("p","stage-caption","You\u2019re connected."))},Fe=()=>{W(y("p","stage-caption","No problem \u2014 nothing was shared."),le("Start over",()=>{V()}),Ie("Close",()=>de(()=>v(void 0))))},pe=(l,c)=>{W(y("p","stage-caption",l),le("Start over",()=>{V()}),Ie("Close",()=>de(()=>R(c??new Error(`[@enbox/browser] ${l}`)))))},Tt=()=>{W(y("p","stage-caption","This wallet can\u2019t connect by phone here."),y("p","stage-subline","You can continue in this browser instead."),le("Use this browser",()=>{ue()}))},St=()=>{W(y("p","stage-caption","Connect with a wallet in this browser"),y("p","stage-subline","Your wallet opens in a small window to approve this connection."),le("Open wallet window",()=>{ue()}))},Wt=()=>{W(y("div","spinner"),y("p","stage-caption","Finish in the wallet window"),y("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},Je=l=>{W(y("p","stage-caption",l?"Your browser blocked the wallet window.":"The wallet window was closed."),le(l?"Open it now":"Reopen window",()=>{ue()}),...s?[]:[Ie("Use your phone instead",()=>{Xe("phone")})])},Lt=async l=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let c=Ke.get(l);return c===void 0&&(c=t.discoverConnectServerUrl(l),Ke.set(l,c)),c},Nt=l=>{clearTimeout(D);let c=Math.max(xn,l*1e3-yn);D=setTimeout(()=>{!O&&X===void 0&&u==="phone"&&Qe()},c)},Qe=async()=>{if(Q?.cancel(),clearTimeout(D),p===void 0){pe("No wallet is configured.");return}u="phone",Z(),Ye("Getting things ready\u2026");let l=new URL(p).origin,c=await Lt(l);if(c===void 0){Tt();return}let x=Mn();Q=x;try{let w=await t.runRelay({connectServerUrl:c,walletUri:new URL(i,l).toString(),appName:o,appIcon:e.appIcon,clientMetadata:ve(),permissionRequests:e.permissionRequests,timeoutMs:e.timeout,cancelled:x.cancelled,onWalletUriReady:b=>{x.active&&!O&&(kt(b),Nt(b.expiresIn))},onClaimed:()=>{x.active&&!O&&(clearTimeout(D),Pt())},requestPin:(b,B)=>(clearTimeout(D),Rt(b,B))});if(!x.active||O)return;w===void 0?Fe():Ge(w)}catch(w){if(!x.active||O||w instanceof F)return;let b=w instanceof Error?w:new Error(String(w));pe(/timed out/i.test(b.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",b)}},ue=()=>{if(Q?.cancel(),clearTimeout(D),p===void 0){pe("No wallet is configured.");return}if(Ee)return;u="browser",Z();let l;try{l=t.runPopup({walletUrl:p,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout})}catch(c){let x=c instanceof Error&&/popup blocked/i.test(c.message);Je(x);return}Ee=!0,Wt(),l.then(c=>{O||(c===void 0?Fe():Ge(c))}).catch(c=>{if(O)return;if(c instanceof K){Je(!1);return}let x=c instanceof Error?c:new Error(String(c));pe(/timed out/i.test(x.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",x)}).finally(()=>{Ee=!1})},V=async()=>{u==="browser"?(Q?.cancel(),clearTimeout(D),Z(),St()):await Qe()},Xe=async l=>{u=l,await V()},Z=()=>{if(I.replaceChildren(),!d){Ct();let c=Ot();c.label!==void 0&&I.appendChild(c.label),I.appendChild(c.row),I.appendChild(c.panel)}let l=document.createElement("div");if(l.className="footer-row",u==="phone"){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="No phone? Use this browser \u2192",c.addEventListener("click",()=>{ue()}),l.appendChild(c)}else if(!s){let c=document.createElement("button");c.className="footer-link method-link",c.textContent="Use your phone instead \u2192",c.addEventListener("click",()=>{Xe("phone")}),l.appendChild(c)}l.childElementCount>0&&I.appendChild(l)},Ot=()=>{let l=document.createElement("div");l.className="wallet-row",l.setAttribute("role","radiogroup"),l.setAttribute("aria-label","Wallet");for(let h of $){let g=document.createElement("button");g.className="row-tile",g.title=h.description??h.name,g.setAttribute("role","radio");let N=h.url===p;g.setAttribute("aria-checked",N?"true":"false"),N&&g.classList.add("selected"),g.appendChild(re(h)),g.appendChild(y("span","row-tile-name",h.name)),g.addEventListener("click",()=>{h.url!==p&&ce(h.url)}),l.appendChild(g)}let c=document.createElement("div");c.className="wallet-panel",c.hidden=!0;let x=n.filter(h=>!$.some(g=>g.url===h.url)).length,w=document.createElement("button");w.className="row-tile more-tile",w.title="All wallets",w.setAttribute("aria-expanded","false"),w.appendChild(y("span","more-count",x>0?`+${x}`:"\u22EF")),w.appendChild(y("span","row-tile-name","More")),w.addEventListener("click",()=>{c.hidden=!c.hidden,w.setAttribute("aria-expanded",c.hidden?"false":"true")}),l.appendChild(w);let b=$.length>0?y("div","wallet-row-label","Connecting with"):void 0,B=[],k=document.createElement("div");if(k.className="wallet-empty",k.textContent="No wallets match your search.",k.hidden=!0,n.length>En){let h=document.createElement("input");h.type="search",h.className="wallet-search",h.placeholder="Search wallets\u2026",h.setAttribute("aria-label","Search wallets"),h.addEventListener("input",()=>{let g=h.value.trim().toLowerCase(),N=0;for(let{wallet:et,el:Dt}of B){let tt=g===""||et.name.toLowerCase().includes(g)||et.url.toLowerCase().includes(g);Dt.hidden=!tt,tt&&(N+=1)}k.hidden=N>0}),c.appendChild(h)}let _=document.createElement("div");_.className="wallet-scroll";let A=document.createElement("div");A.className="wallet-grid";for(let h of n){let g=document.createElement("button");g.className="wallet-tile",g.title=h.name,g.appendChild(re(h));let N=document.createElement("span");N.className="wallet-tile-name",N.textContent=h.name,g.appendChild(N),h.url===p&&(g.classList.add("selected"),g.setAttribute("aria-pressed","true")),g.addEventListener("click",()=>{ce(h.url)}),B.push({wallet:h,el:g}),A.appendChild(g)}_.appendChild(A),_.appendChild(k),c.appendChild(_);let U=document.createElement("div");U.className="wallet-custom";let L=document.createElement("input");L.className="url-input",L.type="url",L.placeholder="https://your-wallet.example";let T=document.createElement("button");T.className="url-go",T.textContent="Use";let j=document.createElement("div");j.className="url-error",j.hidden=!0;let _e=!1,Ze=async()=>{let h=L.value.trim();if(h==="")return;let g;try{g=new URL(h.includes("://")?h:`https://${h}`).origin}catch{L.classList.add("invalid");return}if(_e){ce(g);return}T.disabled=!0,T.textContent="Checking\u2026",j.hidden=!0;let N=await t.validateWalletUrl(g);if(T.disabled=!1,N){T.textContent="Use",ce(g);return}_e=!0,T.textContent="Use anyway",L.classList.add("invalid"),j.textContent=`Couldn't verify a wallet at ${g}.`,j.hidden=!1};return L.addEventListener("input",()=>{_e=!1,T.textContent="Use",L.classList.remove("invalid"),j.hidden=!0}),L.addEventListener("keydown",h=>{h.key==="Enter"&&Ze()}),T.addEventListener("click",()=>{Ze()}),U.appendChild(L),U.appendChild(T),c.appendChild(U),c.appendChild(j),{label:b,row:l,panel:c}};P.addEventListener("click",l=>{l.target===P&&Ce()});let Ve=l=>{if(l.key==="Escape"){Ce();return}l.key==="Tab"&&Nn(f,l)};document.addEventListener("keydown",Ve),P.appendChild(C),f.appendChild(P),document.body.appendChild(E),Z(),V()})}function Tn(e,t){return e.some(n=>n.url===t)}function Sn(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Wn(e){if(e!==void 0)try{return new URL(e).hostname}catch{return e}}function y(e,t,n){let r=document.createElement(e);return r.className=t,n!==void 0&&(r.textContent=n),r}function le(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Ie(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function Ln(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=`Connect to ${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 Nn(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 wt=`
154
+ `,z.lastElementChild.addEventListener("click",Oe),document.body.prepend(z),Ee=!0)}function nn(){Ee&&(re?.remove(),re=null,z?.remove(),z=null,Ee=!1)}function Oe(){document.documentElement.removeAttribute("drl-link-loading"),be=null}var be=null,xe=!1,ie=null,ae=null;function on(){xe||(ie=async e=>{let t=e.target?.closest("a");if(t){let n=t.href,r=oe(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(tn)):(be=i,setTimeout(()=>document.documentElement.setAttribute("drl-link-loading",""),50));let d=await ht(o);if(!d.length)throw new Error("no valid DWN endpoints found");let p=`${d[0].replace(ye,"")}/${o}/${i}`;s?a&&!a.closed&&(a.location.href=p):be===i&&(window.location.href=p)}catch{throw be===i&&Oe(),new Error(`DID endpoint resolution failed for the DRL: ${n}`)}}}},ae=async e=>{let t=e.composedPath()[0];if(e.pointerType==="mouse"&&e.button===2||e.pointerType==="touch"&&e.isPrimary){if(J(),t?.src&&oe(t.src)){G=t,t.__src__=t.src;let n=t.src.replace(ft,"https:").replace(ye,""),o=await(await gt())?.match(n);if(o){let i=o.headers.get("dwn-composed-url");i&&(t.src=i)}t.addEventListener("pointerup",J,{once:!0})}}else t===G&&J()},document.addEventListener("click",ie),document.addEventListener("pointercancel",J),document.addEventListener("pointerdown",ae),xe=!0)}function rn(){xe&&(ie&&(document.removeEventListener("click",ie),ie=null),ae&&(document.removeEventListener("pointerdown",ae),ae=null),document.removeEventListener("pointercancel",J),J(),Oe(),xe=!1)}var G=null;async function J(e){e?.type==="pointerup"&&await new Promise(t=>requestAnimationFrame(()=>t())),G&&(G.src=G.__src__,delete G.__src__,G=null)}function ao(e={}){e.didResolvers&&(Ne=new ut({didResolvers:e.didResolvers})),e.serviceWorker!==!1&&en(e),typeof window<"u"&&typeof window.document<"u"&&(e.injectStyles!==!1&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",pt,{once:!0}):pt()),e.links!==!1&&on())}function so(){typeof window<"u"&&typeof window.document<"u"&&(rn(),nn())}async function lo(){return typeof caches>"u"?!1:caches.delete(mt)}import{ConnectClient as On}from"@enbox/connect";function se(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=an(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 an(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 sn,CONNECT_DENIED_TOKEN as ln,ConnectClient as cn}from"@enbox/connect";var Ae="/dweb-connect",le="enbox-connect-loaded",ce="enbox-connect-request",X="enbox-connect-response",de="enbox-connect-ack";function Ce(e,t,n){if(e.origin!==t||e.source!==n)return;let r=e.data;if(!(typeof r!="object"||r===null))return r}var dn=3e5,pn=500,un=1500,fn="enbox-dweb-connect",vt=500,bt=700;function mn(){let e=`width=${vt},height=${bt},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-vt)/2)),o=Math.max(0,Math.round((window.screenY??0)+(n-bt)/2));return`${e},left=${r},top=${o}`}function hn(){if(typeof window>"u")throw new Error("[@enbox/browser] DWeb Connect is only available in browser environments.")}var Y=class extends Error{constructor(){super("[@enbox/browser] Wallet popup was closed before the wallet finished loading."),this.name="PopupWindowClosedError"}},V=class{constructor(t){this.requiresPin=!1;this._settled=!1;this._walletEpkReceived=!1;hn(),this._walletOrigin=new URL(t.walletUrl).origin,this._timeoutMs=t.timeoutMs??dn;let n=new URL(Ae,t.walletUrl).toString(),r=window.open(n,fn,mn());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()},pn)}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:ce,jwe:t},this._walletOrigin)}async awaitResponse(){return await this._responsePromise}async confirmComplete(){this._popup.closed!==!0&&this._popup.postMessage({type:de},this._walletOrigin)}onMessage(t){let n=Ce(t,this._walletOrigin,this._popup);if(n!==void 0){if(n.type===le){this.onLoadedBeacon(n);return}n.type===X&&this.onResponseMessage(n)}}onLoadedBeacon(t){if(this._settled||this._walletEpkReceived)return;let n;try{sn(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 Y);return}clearInterval(this._closedPollId),setTimeout(()=>{this._settled||(this._settled=!0,this.cleanup(),this._resolveResponse?.(ln))},un)}}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 _e(){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 gn(e){let t=new V({walletUrl:e.walletUrl,timeoutMs:e.timeout}),n=new cn({transport:t});try{return await n.connect({appName:e.appName??globalThis.location.host,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests})}catch(r){if(r instanceof Y)return;throw r}}var xt=[-1,10,16,26,18,24,16,18,22,22,26],Ct=[-1,1,1,1,2,2,4,4,4,5,5],_t=[-1,26,44,70,100,134,172,196,242,292,346],wn=0,yt=10;function Et(e){return _t[e]-xt[e]*Ct[e]}function Be(e,t){let n=new TextEncoder().encode(e),r=0;for(let f=1;f<=yt;f++){let g=Et(f)*8;if(4+(f<=9?8:16)+n.length*8<=g){r=f;break}}if(r===0)throw new Error(`[@enbox/browser] QR payload too long (${n.length} bytes exceeds version ${yt}-M capacity).`);let o=[],i=(f,g)=>{for(let P=g-1;P>=0;P--)o.push(f>>>P&1)};i(4,4),i(n.length,r<=9?8:16);for(let f of n)i(f,8);let s=Et(r)*8;i(0,Math.min(4,s-o.length)),i(0,(8-o.length%8)%8);let a=[236,17];for(let f=0;o.length<s;f++)i(a[f%2],8);let d=new Uint8Array(s/8);for(let f=0;f<o.length;f++)d[f>>3]|=o[f]<<7-(f&7);let p=vn(d,r),u=17+4*r,y=Array.from({length:u},()=>new Array(u).fill(!1)),M=Array.from({length:u},()=>new Array(u).fill(!1));xn(y,M,r),kn(y,M,p);let x=t??-1;if(x===-1){let f=1/0;for(let g=0;g<8;g++){Ue(y,M,g),He(y,M,g);let P=Pn(y);P<f&&(f=P,x=g),Ue(y,M,g)}}return Ue(y,M,x),He(y,M,x),{size:u,modules:y,version:r,mask:x}}function vn(e,t){let n=Ct[t],r=xt[t],o=_t[t],i=n-o%n,s=Math.floor(o/n),a=[],d=[],p=bn(r),u=0;for(let f=0;f<n;f++){let g=s-r+(f<i?0:1),P=e.slice(u,u+g);u+=g,a.push(P),d.push(yn(P,p))}let y=new Uint8Array(o),M=0,x=s-r+1;for(let f=0;f<x;f++)for(let g=0;g<n;g++)f<a[g].length&&(y[M++]=a[g][f]);for(let f=0;f<r;f++)for(let g=0;g<n;g++)y[M++]=d[g][f];return y}function Ie(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 bn(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]=Ie(t[o],n),o+1<e&&(t[o]^=t[o+1]);n=Ie(n,2)}return t}function yn(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]^=Ie(t[i],o)}return n}var En=[[],[],[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 xn(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);De(e,t,3,3),De(e,t,r-4,3),De(e,t,3,r-4);let o=En[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||Cn(e,t,o[i],o[s]);He(e,t,0),T(e,t,8,r-8,!0),n>=7&&_n(e,t,n)}function De(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 p=Math.max(Math.abs(s),Math.abs(i));T(e,t,a,d,p!==2&&p!==4)}}function Cn(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 He(e,t,n){let r=e.length,o=wn<<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 _n(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,p=Math.floor(s/3);T(e,t,d,p,a),T(e,t,p,d,a)}}function kn(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,u=(i+1&2)===0?r-1-s:s;!t[u][d]&&o<n.length*8&&(e[u][d]=(n[o>>3]>>>7-(o&7)&1)!==0,o++)}}}function Ue(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 Pn(e){let t=e.length,n=0;for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[a][u]!==d?(d=e[a][u],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t;a++){let d=!1,p=0;for(let u=0;u<t;u++)u===0||e[u][a]!==d?(d=e[u][a],p=1):(p++,p===5?n+=3:p>5&&(n+=1))}for(let a=0;a<t-1;a++)for(let d=0;d<t-1;d++){let p=e[a][d];p===e[a][d+1]&&p===e[a+1][d]&&p===e[a+1][d+1]&&(n+=3)}let r=(a,d)=>{if(![!0,!1,!0,!0,!0,!1,!0].every((x,f)=>a[d+f]===x))return 0;let y=d>=4&&a.slice(d-4,d).every(x=>!x),M=d+11<=a.length&&a.slice(d+7,d+11).every(x=>!x);return(y?40:0)+(M?40:0)};for(let a=0;a<t;a++){let d=e[a],p=e.map(u=>u[a]);for(let u=0;u+7<=t;u++)n+=r(d,u),n+=r(p,u)}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 qe="http://www.w3.org/2000/svg";function je(e,t={}){let n=t.dark??"#000000",r=t.light??"#ffffff",o=t.quietZone??2,i=e.size+o*2,s="";for(let u=0;u<e.size;u++)for(let y=0;y<e.size;y++)e.modules[u][y]&&(s+=`M${y+o} ${u+o}h1v1h-1z`);let a=document.createElementNS(qe,"svg");a.setAttribute("viewBox",`0 0 ${i} ${i}`),a.setAttribute("shape-rendering","crispEdges"),a.setAttribute("role","img");let d=document.createElementNS(qe,"rect");d.setAttribute("width",String(i)),d.setAttribute("height",String(i)),d.setAttribute("fill",r),a.appendChild(d);let p=document.createElementNS(qe,"path");return p.setAttribute("d",s),p.setAttribute("fill",n),a.appendChild(p),a}var kt="/.well-known/enbox-connect";async function ke(e){try{let t=new URL(kt,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 $e(e){return await ke(e)!==void 0}import{DidJwk as Mn}from"@enbox/dids";import{X25519 as Rn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Tn,openResponse as Sn,randomToken as Pt,RelayClientTransport as Wn,sealRequest as Ln}from"@enbox/connect";var Ke=6,Z=class extends Error{constructor(){super("[@enbox/browser] Relay connect cancelled."),this.name="RelayConnectCancelledError"}};function Nn(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 ze(e){let n=(e.createTransport??(g=>new Wn({...g,sleep:Nn})))({connectServerUrl:e.connectServerUrl,walletUri:e.walletUri,timeoutMs:e.timeoutMs,pollIntervalMs:e.pollIntervalMs,onClaimed:e.onClaimed}),r=await Mn.create(),o=await Rn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=Pt(),a=Pt(),d=await n.requestProfile(a),p={clientDid:r.uri,appName:e.appName,appIcon:e.appIcon,clientMetadata:e.clientMetadata,permissionRequests:e.permissionRequests,supportedDidMethods:["did:dht","did:jwk"],nonce:s,state:a,responseKey:i,reply:d.reply},u=await Ln({request:p,signer:r,encryption:d.encryption}),y=await n.deliverRequest(u);y!==void 0&&e.onWalletUriReady(y);let x=await(e.cancelled===void 0?n.awaitResponse():Promise.race([n.awaitResponse(),e.cancelled]));if(x===Tn)return;let f;for(let g=1;g<=Ke;g++){let P=await(e.cancelled===void 0?e.requestPin(g,f):Promise.race([e.requestPin(g,f),e.cancelled]));try{let C=await Sn({jwe:x,recipientPrivateKey:o,expected:{clientDid:r.uri,nonce:s,state:a},pin:P});if(C.delegatePortableDid===void 0)throw new Error("Connect: wallet response omitted `delegatePortableDid`.");return n.confirmComplete?.().catch(()=>{}),{delegatePortableDid:C.delegatePortableDid,delegateGrants:C.delegateGrants,connectedDid:C.providerDid,sessionRevocations:C.sessionRevocations}}catch(C){let L=C instanceof Error?C:new Error(String(C));if(L.message.startsWith("Connect:"))throw L;f=L}}throw new Error(`[@enbox/browser] The pairing code did not match after ${Ke} attempts.`)}var St="enbox:connect:lastChoice",An=12e4,Dn=1e4,Pe=4,Un=4,Mt=3,Ge={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 Wt(e){return(await ke(e))?.connectServerUrl}async function qn(e){let t=new V({walletUrl:e.walletUrl,timeoutMs:e.timeoutMs});return await new On({transport:t}).connect({appName:e.appName,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests})}function In(){return typeof window>"u"?!1:(window.matchMedia?.("(pointer: coarse)").matches??!1)&&Math.min(window.innerWidth,window.innerHeight)<900}function Hn(){return{runRelay:ze,runPopup:qn,discoverConnectServerUrl:Wt,validateWalletUrl:$e,isMobile:In,storage:typeof localStorage>"u"?void 0:localStorage}}function Bn(e){try{let t=e?.getItem(St);if(t==null)return;let n=JSON.parse(t);if((n.method==="phone"||n.method==="browser")&&typeof n.walletUrl=="string")return{method:n.method,walletUrl:n.walletUrl}}catch{}}function jn(e,t){try{e?.setItem(St,JSON.stringify(t))}catch{}}function $n(){let e,t={active:!0},n=new Promise((r,o)=>{e=()=>{t.active===!0&&(t.active=!1,o(new Z))}});return n.catch(()=>{}),t.cancelled=n,t.cancel=e,t}function Ye(e){if(typeof window>"u"||typeof document>"u")throw new Error("[@enbox/browser] The connect modal is only available in browser environments.");let t={...Hn(),...e.deps},n=zn(e.wallets??[]),r=e.rememberChoice??!0,o=e.appName??window.location.host,i=e.relayWalletPath??"/connect/app",s=t.isMobile(),a=r?Bn(t.storage):void 0,d=e.walletUrl!==void 0,p=e.walletUrl??(a!==void 0&&(d||Kn(n,a.walletUrl))?a.walletUrl:void 0)??n[0]?.url,u=e.preferredMethod??a?.method??"phone";return new Promise((y,M)=>{let x=document.createElement("div");x.id="enbox-connect-modal";let f=x.attachShadow({mode:"open"}),g=document.createElement("style");g.textContent=Qn,f.appendChild(g);let P=document.createElement("div");P.className="overlay";let C=document.createElement("div");C.className="modal",C.setAttribute("role","dialog"),C.setAttribute("aria-modal","true"),C.setAttribute("aria-label",`Connect to ${o}`);let L=e.theme??{},ee=L.appearance??"auto";ee!=="auto"&&C.setAttribute("data-appearance",ee);let Re=window.matchMedia?.("(prefers-color-scheme: dark)"),Nt=L.accent!==void 0||L.accentContrast!==void 0||L.light!==void 0||L.dark!==void 0,Qe=()=>{let c=ee==="auto"?Re?.matches===!0?"dark":"light":ee,l={accent:L.accent,accentContrast:L.accentContrast,...L[c]};for(let w of Object.keys(Ge)){let m=l[w];typeof m=="string"&&m.trim()!==""?C.style.setProperty(Ge[w],m):C.style.removeProperty(Ge[w])}},Je=()=>Qe();Nt&&(Qe(),ee==="auto"&&Re?.addEventListener?.("change",Je));let N=!1,q,Xe,ue,Te=!1,I,Ve=new Map,F=[],fe=c=>n.find(l=>l.url===c)??{name:Gn(c)??c,url:c},Ot=()=>{if(p===void 0){F=n.slice(0,Mt);return}if(F.some(l=>l.url===p))return;let c=fe(p);F=[c,...n.filter(l=>l.url!==c.url)].slice(0,Mt)},me=c=>{p=c,ne(),te()},At=()=>{q?.cancel(),j(),document.removeEventListener("keydown",at),document.removeEventListener("visibilitychange",st),Re?.removeEventListener?.("change",Je);try{document.body.removeChild(x)}catch{}},he=c=>{N||(N=!0,At(),c())},Ze=c=>{r&&jn(t.storage,{method:u,walletUrl:p??""}),Bt(),setTimeout(()=>he(()=>y(c)),1200)},Se=()=>he(()=>M(new Error("[@enbox/browser] Connect cancelled.")));C.appendChild(Yn(o,e.appIcon,Se));let H=document.createElement("div");H.className="stage",H.setAttribute("aria-live","polite"),C.appendChild(H);let B=document.createElement("div");B.className="footer",C.appendChild(B);let S=(...c)=>{H.replaceChildren(...c),H.classList.remove("fade-in"),H.offsetWidth,H.classList.add("fade-in")},et=c=>{S(v("div","spinner"),v("p","stage-caption",c))},Dt=c=>{let l=q;setTimeout(()=>{N||l!==q||l?.active!==!0||I!==void 0||qt(c)},0)},tt=(c,l,w)=>{let m=document.createElement("a");return m.className=w,m.href=c.walletUri,m.target="_blank",m.rel="noopener noreferrer",m.addEventListener("click",()=>{Dt(l)}),m},Ut=c=>{let l=p!==void 0?fe(p):void 0,w=l?.name??"your wallet",m=tt(c,w,"qr-box qr-link");if(m.setAttribute("aria-label",`Open ${w} on this device`),m.replaceChildren(je(Be(c.walletUri),{dark:"#14141f",light:"transparent",quietZone:2})),l!==void 0){let _=v("div","qr-logo");_.appendChild(se(l)),m.appendChild(_)}if(s){let _=tt(c,w,"deep-link");l!==void 0&&_.appendChild(se(l)),_.appendChild(v("span","deep-link-label",`Continue in ${w}`)),m.classList.add("compact"),S(_,v("p","stage-subline",`${w} opens in a new tab \u2014 approve there, then come back for your code.`),v("div","stage-divider","or scan with another phone"),m);return}S(m,v("p","stage-caption","Scan with your phone\u2019s camera"),v("p","stage-subline",`${w} stays on your phone \u2014 or click the code to open it here.`))},qt=c=>{S(v("div","spinner"),v("p","stage-caption",`Finish in ${c}`),v("p","stage-subline",s?`Approve the connection in the ${c} tab, then come back here for your code.`:"Approve the connection in the tab that just opened, then come back here for your code."),Me("Start over",()=>{We()}))},It=()=>{let c=p!==void 0?fe(p).name:"your wallet",l=document.createElement("div");l.className="claimed-pulse",S(l,v("p","stage-caption",`Request received \u2014 approve in ${c}`),v("p","stage-subline","Once you approve, you\u2019ll get a code to enter here."))},Ht=(c,l)=>new Promise(w=>{I=w;let m=p!==void 0?fe(p).name:"your wallet",_=document.createElement("div");_.className="pin-row",l!==void 0&&_.classList.add("shake");let R=[];for(let k=0;k<Pe;k++){let E=document.createElement("input");E.className="pin-input",E.type="text",E.inputMode="numeric",E.maxLength=1,E.setAttribute("aria-label",`Code digit ${k+1}`),R.push(E),_.appendChild(E)}let D=()=>{let k=R.map(E=>E.value).join("");if(k.length===Pe&&I!==void 0){let E=I;I=void 0,et("Checking the code\u2026"),E(k)}};R.forEach((k,E)=>{k.addEventListener("input",()=>{k.value=k.value.replace(/\D/g,"").slice(0,1),k.value!==""&&E+1<R.length&&R[E+1].focus(),D()}),k.addEventListener("keydown",U=>{U.key==="Backspace"&&k.value===""&&E>0&&R[E-1].focus()}),k.addEventListener("paste",U=>{let $=(U.clipboardData?.getData("text")??"").replace(/\D/g,"").slice(0,Pe);$.length!==0&&(U.preventDefault(),$.split("").forEach((Q,W)=>{R[W]!==void 0&&(R[W].value=Q)}),R[Math.min($.length,Pe)-1]?.focus(),D())})}),S(v("p","stage-caption",`Enter the code shown in ${m}`),_,...l!==void 0?[v("p","stage-error",`That code doesn\u2019t match \u2014 check ${m}.`)]:[v("p","stage-subline",c===1?"This confirms you\u2019re the one approving.":"")]),R[0].focus()}),Bt=()=>{let c=v("div","check");c.textContent="\u2713",S(c,v("p","stage-caption","You\u2019re connected."))},nt=()=>{S(v("p","stage-caption","No problem \u2014 nothing was shared."),pe("Start over",()=>{te()}),Me("Close",()=>he(()=>y(void 0))))},ge=(c,l)=>{S(v("p","stage-caption",c),pe("Start over",()=>{te()}),Me("Close",()=>he(()=>M(l??new Error(`[@enbox/browser] ${c}`)))))},jt=()=>{S(v("p","stage-caption","This wallet can\u2019t connect by phone here."),v("p","stage-subline","You can continue in this browser instead."),pe("Use this browser",()=>{ve()}))},we=s?"tab":"window",$t=()=>{S(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."),pe(s?"Open wallet":"Open wallet window",()=>{ve()}))},Kt=()=>{S(v("div","spinner"),v("p","stage-caption",`Finish in the wallet ${we}`),v("p","stage-subline","We\u2019ll wrap up here as soon as you\u2019re done."))},ot=c=>{S(v("p","stage-caption",c?`Your browser blocked the wallet ${we}.`:`The wallet ${we} was closed.`),pe(c?"Open it now":`Reopen ${we}`,()=>{ve()}),Me(s?"Use a code instead":"Use your phone instead",()=>{it("phone")}))},zt=async c=>{if(e.connectServerUrl!==void 0)return e.connectServerUrl;let l=Ve.get(c);return l===void 0&&(l=t.discoverConnectServerUrl(c),Ve.set(c,l)),l},j=()=>{clearTimeout(Xe),ue=void 0},rt=()=>{!N&&I===void 0&&u==="phone"&&We()},Gt=c=>{j();let l=Math.max(Dn,c*1e3-An);ue=Date.now()+l,Xe=setTimeout(rt,l)},We=async()=>{if(q?.cancel(),j(),p===void 0){ge("No wallet is configured.");return}u="phone",ne(),et("Getting things ready\u2026");let c=new URL(p).origin,l=await zt(c);if(l===void 0){jt();return}let w=$n();q=w;try{let m=await t.runRelay({connectServerUrl:l,walletUri:new URL(i,c).toString(),appName:o,appIcon:e.appIcon,clientMetadata:_e(),permissionRequests:e.permissionRequests,timeoutMs:e.timeout,cancelled:w.cancelled,onWalletUriReady:_=>{w.active&&!N&&(Ut(_),Gt(_.expiresIn))},onClaimed:()=>{w.active&&!N&&(j(),It())},requestPin:(_,R)=>(j(),Ht(_,R))});if(!w.active||N)return;m===void 0?nt():Ze(m)}catch(m){if(!w.active||N||m instanceof Z)return;let _=m instanceof Error?m:new Error(String(m));ge(/timed out/i.test(_.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",_)}},ve=()=>{if(q?.cancel(),j(),p===void 0){ge("No wallet is configured.");return}if(Te)return;u="browser",ne();let c;try{c=t.runPopup({walletUrl:p,permissionRequests:e.permissionRequests,appName:o,appIcon:e.appIcon,timeoutMs:e.timeout})}catch(l){let w=l instanceof Error&&/popup blocked/i.test(l.message);ot(w);return}Te=!0,Kt(),c.then(l=>{N||(l===void 0?nt():Ze(l))}).catch(l=>{if(N)return;if(l instanceof Y){ot(!1);return}let w=l instanceof Error?l:new Error(String(l));ge(/timed out/i.test(w.message)?"That took too long, so we stopped for safety.":"Something went wrong while connecting.",w)}).finally(()=>{Te=!1})},te=async()=>{u==="browser"?(q?.cancel(),j(),ne(),$t()):await We()},it=async c=>{u=c,await te()},ne=()=>{if(B.replaceChildren(),!d){Ot();let l=Yt();l.label!==void 0&&B.appendChild(l.label),B.appendChild(l.row),B.appendChild(l.panel)}let c=document.createElement("div");if(c.className="footer-row",u==="phone"){let l=document.createElement("button");l.className="footer-link method-link",l.textContent=s?"Or connect without a code \u2192":"No phone? Use this browser \u2192",l.addEventListener("click",()=>{ve()}),c.appendChild(l)}else{let l=document.createElement("button");l.className="footer-link method-link",l.textContent=s?"Use a code instead \u2192":"Use your phone instead \u2192",l.addEventListener("click",()=>{it("phone")}),c.appendChild(l)}c.childElementCount>0&&B.appendChild(c)},Yt=()=>{let c=document.createElement("div");c.className="wallet-row",c.setAttribute("role","radiogroup"),c.setAttribute("aria-label","Wallet");for(let h of F){let b=document.createElement("button");b.className="row-tile",b.title=h.description??h.name,b.setAttribute("role","radio");let O=h.url===p;b.setAttribute("aria-checked",O?"true":"false"),O&&b.classList.add("selected"),b.appendChild(se(h)),b.appendChild(v("span","row-tile-name",h.name)),b.addEventListener("click",()=>{h.url!==p&&me(h.url)}),c.appendChild(b)}let l=document.createElement("div");l.className="wallet-panel",l.hidden=!0;let w=n.filter(h=>!F.some(b=>b.url===h.url)),m=document.createElement("button");m.className="row-tile more-tile",m.title="All wallets",m.setAttribute("aria-expanded","false"),m.appendChild(v("span","more-count",w.length>0?`+${w.length}`:"\u22EF")),m.appendChild(v("span","row-tile-name","More")),m.addEventListener("click",()=>{l.hidden=!l.hidden,m.setAttribute("aria-expanded",l.hidden?"false":"true"),l.hidden||$()}),c.appendChild(m);let _=F.length>0?v("div","wallet-row-label","Connecting with"):void 0,R=[],D=document.createElement("div");if(D.className="wallet-empty",D.textContent="No other wallets match your search.",D.hidden=!0,w.length>Un){let h=document.createElement("input");h.type="search",h.className="wallet-search",h.placeholder="Search wallets\u2026",h.setAttribute("aria-label","Search wallets"),h.addEventListener("input",()=>{let b=h.value.trim().toLowerCase(),O=0;for(let{wallet:ct,el:Ft}of R){let dt=b===""||ct.name.toLowerCase().includes(b)||ct.url.toLowerCase().includes(b);Ft.hidden=!dt,dt&&(O+=1)}D.hidden=O>0,$()}),l.appendChild(h)}let k=document.createElement("div");k.className="wallet-scroll-wrap",k.hidden=w.length===0;let E=document.createElement("div");E.className="wallet-scroll";let U=document.createElement("div");U.className="wallet-grid";let $=()=>{let h=E.scrollHeight-E.clientHeight>1,b=E.scrollTop+E.clientHeight>=E.scrollHeight-1;k.classList.toggle("scroll-hint",h&&!b)};E.addEventListener("scroll",$);for(let h of w){let b=document.createElement("button");b.className="wallet-tile",b.title=h.description??h.name,b.appendChild(se(h));let O=document.createElement("span");O.className="wallet-tile-name",O.textContent=h.name,b.appendChild(O),b.addEventListener("click",()=>{me(h.url)}),R.push({wallet:h,el:b}),U.appendChild(b)}E.appendChild(U),E.appendChild(D),k.appendChild(E),l.appendChild(k);let Q=document.createElement("div");Q.className="wallet-custom";let W=document.createElement("input");W.className="url-input",W.type="url",W.placeholder="https://your-wallet.example";let A=document.createElement("button");A.className="url-go",A.textContent="Use";let K=document.createElement("div");K.className="url-error",K.hidden=!0;let Le=!1,lt=async()=>{let h=W.value.trim();if(h==="")return;let b;try{b=new URL(h.includes("://")?h:`https://${h}`).origin}catch{W.classList.add("invalid");return}if(Le){me(b);return}A.disabled=!0,A.textContent="Checking\u2026",K.hidden=!0;let O=await t.validateWalletUrl(b);if(A.disabled=!1,O){A.textContent="Use",me(b);return}Le=!0,A.textContent="Use anyway",W.classList.add("invalid"),K.textContent=`Couldn't verify a wallet at ${b}.`,K.hidden=!1};return W.addEventListener("input",()=>{Le=!1,A.textContent="Use",W.classList.remove("invalid"),K.hidden=!0}),W.addEventListener("keydown",h=>{h.key==="Enter"&&lt()}),A.addEventListener("click",()=>{lt()}),Q.appendChild(W),Q.appendChild(A),l.appendChild(Q),l.appendChild(K),{label:_,row:c,panel:l}};P.addEventListener("click",c=>{c.target===P&&Se()});let at=c=>{if(c.key==="Escape"){Se();return}c.key==="Tab"&&Fn(f,c)};document.addEventListener("keydown",at);let st=()=>{if(!(document.visibilityState!=="visible"||N)){if(ue!==void 0&&Date.now()>=ue){rt();return}I!==void 0&&Array.from(f.querySelectorAll(".pin-input")).find(l=>l.value==="")?.focus()}};document.addEventListener("visibilitychange",st),P.appendChild(C),f.appendChild(P),document.body.appendChild(x),ne(),te()})}function Kn(e,t){return e.some(n=>n.url===t)}function zn(e){return e.filter((t,n)=>e.findIndex(r=>r.url===t.url)===n)}function Gn(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 pe(e,t){let n=document.createElement("button");return n.className="stage-btn",n.textContent=e,n.addEventListener("click",t),n}function Me(e,t){let n=document.createElement("button");return n.className="footer-link",n.textContent=e,n.addEventListener("click",t),n}function Yn(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=`Connect to ${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 Fn(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 Rt=`
155
155
  --ec-bg: #ffffff;
156
156
  --ec-surface: #f5f6f8;
157
157
  --ec-text: #17171f;
@@ -160,7 +160,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
160
160
  --ec-accent: #0a62d0;
161
161
  --ec-accent-contrast: #ffffff;
162
162
  --ec-danger: #c0392b;
163
- --ec-success: #1e9e5a;`,vt=`
163
+ --ec-success: #1e9e5a;`,Tt=`
164
164
  --ec-bg: #181822;
165
165
  --ec-surface: #23232f;
166
166
  --ec-text: #e9e9f0;
@@ -169,7 +169,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
169
169
  --ec-accent: #58a6ff;
170
170
  --ec-accent-contrast: #0b1526;
171
171
  --ec-danger: #ff7a7a;
172
- --ec-success: #43d17c;`,On=`
172
+ --ec-success: #43d17c;`,Qn=`
173
173
  * { box-sizing: border-box; margin: 0; padding: 0; }
174
174
 
175
175
  /* Keep the hidden attribute authoritative: author display values (e.g.
@@ -204,7 +204,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
204
204
  50% { transform: scale(1); opacity: 1; }
205
205
  }
206
206
 
207
- .modal {${wt}
207
+ .modal {${Rt}
208
208
  --ec-accent-soft: color-mix(in srgb, var(--ec-accent) 14%, transparent);
209
209
  background: var(--ec-bg);
210
210
  color: var(--ec-text);
@@ -220,12 +220,12 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
220
220
  flex-direction: column;
221
221
  }
222
222
  @media (prefers-color-scheme: dark) {
223
- .modal {${vt}
223
+ .modal {${Tt}
224
224
  }
225
225
  }
226
- .modal[data-appearance='light'] {${wt}
226
+ .modal[data-appearance='light'] {${Rt}
227
227
  }
228
- .modal[data-appearance='dark'] {${vt}
228
+ .modal[data-appearance='dark'] {${Tt}
229
229
  }
230
230
 
231
231
  button, input { font-family: inherit; }
@@ -288,6 +288,31 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
288
288
  .qr-logo .wallet-icon { width: 30px; height: 30px; }
289
289
  .qr-logo .wallet-badge { border-radius: 8px; font-size: 15px; }
290
290
 
291
+ /* The QR card doubles as the same-device handoff link. */
292
+ a.qr-box { display: block; cursor: pointer; }
293
+ .qr-box.qr-link:hover {
294
+ border-color: var(--ec-accent);
295
+ box-shadow: 0 0 0 3px var(--ec-accent-soft);
296
+ }
297
+ .qr-box.compact { width: 160px; height: 160px; }
298
+ .qr-box.compact .qr-logo { width: 36px; height: 36px; }
299
+ .qr-box.compact .qr-logo .wallet-icon { width: 24px; height: 24px; }
300
+
301
+ .stage-divider {
302
+ display: flex;
303
+ align-items: center;
304
+ gap: 10px;
305
+ width: 100%;
306
+ color: var(--ec-muted);
307
+ font-size: 12px;
308
+ }
309
+ .stage-divider::before, .stage-divider::after {
310
+ content: '';
311
+ flex: 1;
312
+ height: 1px;
313
+ background: var(--ec-border);
314
+ }
315
+
291
316
  .claimed-pulse {
292
317
  width: 64px; height: 64px; border-radius: 50%;
293
318
  background: var(--ec-accent-soft); position: relative;
@@ -404,7 +429,7 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
404
429
  grid-template-columns: repeat(4, 1fr);
405
430
  gap: 8px;
406
431
  }
407
- .row-tile {
432
+ .row-tile, .wallet-tile {
408
433
  display: flex;
409
434
  flex-direction: column;
410
435
  align-items: center;
@@ -419,15 +444,15 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
419
444
  font-size: 11px;
420
445
  cursor: pointer;
421
446
  }
422
- .row-tile:hover { border-color: var(--ec-accent); }
447
+ .row-tile:hover, .wallet-tile:hover { border-color: var(--ec-accent); }
423
448
  .row-tile.selected {
424
449
  border-color: var(--ec-accent);
425
450
  background: var(--ec-accent-soft);
426
451
  box-shadow: inset 0 0 0 1px var(--ec-accent);
427
452
  }
428
453
  .row-tile.selected .row-tile-name { font-weight: 600; }
429
- .row-tile .wallet-icon { width: 28px; height: 28px; }
430
- .row-tile-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
454
+ .row-tile .wallet-icon, .wallet-tile .wallet-icon { width: 28px; height: 28px; }
455
+ .row-tile-name, .wallet-tile-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
431
456
 
432
457
  .more-tile { color: var(--ec-muted); }
433
458
  .more-tile:hover { color: var(--ec-text); }
@@ -453,46 +478,33 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
453
478
  }
454
479
  .wallet-search:focus { outline: none; border-color: var(--ec-accent); }
455
480
 
456
- .wallet-scroll { max-height: 260px; overflow-y: auto; }
481
+ /* Cap the grid at three rows of tiles; past that it scrolls in place,
482
+ and the wrapper's bottom fade hints that more wallets are below. */
483
+ .wallet-scroll-wrap { position: relative; }
484
+ .wallet-scroll { max-height: 220px; overflow-y: auto; }
485
+ .wallet-scroll-wrap.scroll-hint::after {
486
+ content: '';
487
+ position: absolute;
488
+ left: 0;
489
+ right: 0;
490
+ bottom: 0;
491
+ height: 28px;
492
+ background: linear-gradient(to bottom, transparent, var(--ec-bg));
493
+ pointer-events: none;
494
+ }
457
495
  .wallet-grid {
458
496
  display: grid;
459
- grid-template-columns: repeat(3, 1fr);
460
- gap: 8px;
461
- }
462
- .wallet-tile {
463
- aspect-ratio: 1;
464
- display: flex;
465
- flex-direction: column;
466
- align-items: center;
467
- justify-content: center;
497
+ grid-template-columns: repeat(4, 1fr);
468
498
  gap: 8px;
469
- padding: 8px;
470
- min-width: 0;
471
- background: var(--ec-surface);
472
- border: 1px solid var(--ec-border);
473
- border-radius: 12px;
474
- color: var(--ec-text);
475
- font-size: 12px;
476
- cursor: pointer;
477
- }
478
- .wallet-tile:hover { border-color: var(--ec-accent); }
479
- .wallet-tile.selected {
480
- border-color: var(--ec-accent);
481
- background: var(--ec-accent-soft);
482
- box-shadow: inset 0 0 0 1px var(--ec-accent);
483
499
  }
484
- .wallet-tile-name { max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
485
500
 
486
501
  .wallet-icon { position: relative; width: 28px; height: 28px; flex-shrink: 0; display: inline-flex; }
487
- .wallet-tile .wallet-icon { width: 40px; height: 40px; }
488
502
  .wallet-badge {
489
503
  width: 100%; height: 100%; border-radius: 8px; display: inline-flex;
490
504
  align-items: center; justify-content: center; font-size: 13px;
491
505
  font-weight: 600; background: var(--ec-accent-soft); color: var(--ec-accent);
492
506
  }
493
- .wallet-tile .wallet-badge { border-radius: 10px; font-size: 17px; }
494
507
  .wallet-img { position: absolute; inset: 0; width: 100%; height: 100%; border-radius: 8px; object-fit: cover; }
495
- .wallet-tile .wallet-img { border-radius: 10px; }
496
508
 
497
509
  .wallet-empty { padding: 10px 4px; font-size: 12px; color: var(--ec-muted); text-align: center; }
498
510
 
@@ -524,5 +536,5 @@ import{Enbox as Eo,defineProtocol as Co,repository as _o}from"@enbox/api";import
524
536
  .overlay, .modal, .stage.fade-in > *, .pin-row.shake { animation: none; }
525
537
  .claimed-pulse::after { animation: none; }
526
538
  }
527
- `;var xt=[{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"}];function Dn(e={}){let{wallets:t=xt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:p,theme:u}=e;return{async requestAccess(v){return Be({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:p,timeout:r,theme:u,permissionRequests:v.permissionRequests})}}}import{X25519 as An}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Un,ConnectProvider as qn}from"@enbox/connect";var In=3e5,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=Bn(t.dappOrigin),o=await An.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??In});return n.postMessage({type:ie,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:se,payload:t},this._dappOrigin),this.close()}deny(){this.sendResponse(Un)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=we(t,this._dappOrigin,this._dappWindow);if(n!==void 0&&!(n.type!==ae||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 qn.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 Bn(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 zo}from"@enbox/api";import{BrowserStorage as $o}from"@enbox/auth/browser";import{DwnInterface as Yo}from"@enbox/agent";import{DateSort as Jo,DwnInterfaceName as Qo,DwnMethodName as Xo}from"@enbox/dwn-sdk-js";export{Po as AuthManager,Ro as AuthSession,Dn as BrowserConnectHandler,$o as BrowserStorage,Wo as CONNECT_DENIED_TOKEN,Lo as ConnectProvider,xt as DEFAULT_WALLETS,ie as DWEB_CONNECT_LOADED_MESSAGE_TYPE,Re as DWEB_CONNECT_PATH,ae as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,se as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,Jo as DateSort,Yo as DwnInterface,Qo as DwnInterfaceName,Xo as DwnMethodName,Eo as Enbox,Ae as MAX_PIN_ATTEMPTS,Y as PopupClientTransport,K as PopupWindowClosedError,F as RelayConnectCancelledError,zo as TypedRecord,mt as WALLET_WELL_KNOWN_PATH,To as WalletConnect,je as WalletPostMessageTransport,Kn as activatePolyfills,Bt as cacheResponse,Gn as clearDrlCache,tn as connectViaPopup,$n as deactivatePolyfills,Co as defineProtocol,yt as discoverWalletConnectServerUrl,Ne as encodeQr,It as fetchResource,be as fetchWalletWellKnown,at as getDwnEndpoints,qt as handleEvent,Mo as normalizeProtocolRequests,ee as parseDrlUrl,De as probeWalletWellKnown,Oe as qrToSvg,_o as repository,Be as runConnectModal,Ue as runRelayConnect};
539
+ `;var Lt=[{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 Jn(e={}){let{wallets:t=Lt,walletUrl:n,timeout:r,appName:o,appIcon:i,preferredMethod:s,rememberChoice:a,connectServerUrl:d,relayWalletPath:p,theme:u}=e;return{async requestAccess(y){return Ye({wallets:t,walletUrl:n,preferredMethod:s,rememberChoice:a,appName:o,appIcon:i??`${window.location.origin}/favicon.ico`,connectServerUrl:d,relayWalletPath:p,timeout:r,theme:u,permissionRequests:y.permissionRequests})}}}import{X25519 as Xn}from"@enbox/crypto";import{CONNECT_DENIED_TOKEN as Vn,ConnectProvider as Zn}from"@enbox/connect";var eo=3e5,to=5e3,Fe=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=no(t.dappOrigin),o=await Xn.generateKey(),i={kty:"OKP",crv:"X25519",x:o.x},s=new e({dappOrigin:r,dappWindow:n,recipientPrivateKey:o,timeoutMs:t.timeoutMs??eo});return n.postMessage({type:le,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??to),i=await r;return clearTimeout(o),this._resolveAck=void 0,this.close(),i}deny(){this.sendResponse(Vn)}close(){clearTimeout(this._timeoutId),this._messageListener!==void 0&&(window.removeEventListener("message",this._messageListener),this._messageListener=void 0)}onMessage(t){let n=Ce(t,this._dappOrigin,this._dappWindow);if(n!==void 0){if(n.type===de){this._resolveAck?.(!0);return}if(!(n.type!==ce||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 Zn.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 no(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 ir}from"@enbox/api";import{BrowserStorage as sr}from"@enbox/auth/browser";import{DwnInterface as cr}from"@enbox/agent";import{DateSort as pr,DwnInterfaceName as ur,DwnMethodName as fr}from"@enbox/dwn-sdk-js";export{jo as AuthManager,$o as AuthSession,Jn as BrowserConnectHandler,sr as BrowserStorage,Yo as CONNECT_DENIED_TOKEN,Fo as ConnectProvider,Lt as DEFAULT_WALLETS,de as DWEB_CONNECT_ACK_MESSAGE_TYPE,le as DWEB_CONNECT_LOADED_MESSAGE_TYPE,Ae as DWEB_CONNECT_PATH,ce as DWEB_CONNECT_REQUEST_MESSAGE_TYPE,X as DWEB_CONNECT_RESPONSE_MESSAGE_TYPE,pr as DateSort,cr as DwnInterface,ur as DwnInterfaceName,fr as DwnMethodName,qo as Enbox,Ke as MAX_PIN_ATTEMPTS,V as PopupClientTransport,Y as PopupWindowClosedError,Z as RelayConnectCancelledError,ir as TypedRecord,kt as WALLET_WELL_KNOWN_PATH,zo as WalletConnect,Fe as WalletPostMessageTransport,ao as activatePolyfills,Zt as cacheResponse,lo as clearDrlCache,gn as connectViaPopup,so as deactivatePolyfills,Io as defineProtocol,Wt as discoverWalletConnectServerUrl,Be as encodeQr,Vt as fetchResource,ke as fetchWalletWellKnown,ht as getDwnEndpoints,Xt as handleEvent,Ko as normalizeProtocolRequests,oe as parseDrlUrl,$e as probeWalletWellKnown,je as qrToSvg,Ho as repository,Ye as runConnectModal,ze as runRelayConnect};
528
540
  //# sourceMappingURL=browser.mjs.map