@enbox/browser 0.3.63 → 0.3.64

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