@enbox/browser 0.3.64 → 0.3.65

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/README.md CHANGED
@@ -41,7 +41,7 @@ API from `@enbox/api`, auth/session helpers from `@enbox/auth`, and
41
41
  browser-specific connect utilities.
42
42
 
43
43
  ```ts
44
- import { BrowserConnectHandler, Enbox, defineProtocol } from '@enbox/browser';
44
+ import { BrowserConnectHandler, Enbox, defineProtocol, recordCodecs } from '@enbox/browser';
45
45
 
46
46
  const { enbox } = await Enbox.connect({
47
47
  connectHandler : BrowserConnectHandler({ appName: 'Notes' }),
package/dist/browser.mjs CHANGED
@@ -1,4 +1,4 @@
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=`
1
+ import{AudienceDecryptError as dr,createConnectionStore as pr,DwnResponseError as ur,Enbox as fr,defineProtocol as mr,recordCodecs as hr}from"@enbox/api";import{AuthManager as wr,AuthSession as vr,ConnectDeniedError as br,SESSION_EXPIRED_ERROR_CODE as yr,SESSION_REVOKED_ERROR_CODE as Er,computeConnectionStatus as xr,isConnectDeniedError as Cr,isSessionExpiredError as Pr,isSessionInvalidError as _r,normalizeProtocolRequests as Rr,WalletConnect as kr}from"@enbox/auth/browser";import{CONNECT_DENIED_TOKEN as Mr,ConnectProvider as Sr}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;
@@ -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{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};
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 Br}from"@enbox/api";import{BrowserStorage as Kr}from"@enbox/auth/browser";import{createProfileReader as zr,isRetryableProfileReadStatus as Gr}from"@enbox/protocols";import{DwnInterface as Fr}from"@enbox/agent";import{DateSort as Jr,DwnInterfaceName as Vr,DwnMethodName as Xr}from"@enbox/dwn-sdk-js";export{dr as AudienceDecryptError,wr as AuthManager,vr as AuthSession,yo as BrowserConnectHandler,Kr as BrowserStorage,Mr as CONNECT_DENIED_TOKEN,br as ConnectDeniedError,Sr 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,Jr as DateSort,Fr as DwnInterface,Vr as DwnInterfaceName,Xr as DwnMethodName,ur as DwnResponseError,fr as Enbox,Ye as MAX_PIN_ATTEMPTS,F as PopupClientTransport,B as PopupWindowClosedError,Br as Record,Q as RelayConnectCancelledError,yr as SESSION_EXPIRED_ERROR_CODE,Er as SESSION_REVOKED_ERROR_CODE,St as WALLET_WELL_KNOWN_PATH,kr as WalletConnect,Xe as WalletPostMessageTransport,So as activatePolyfills,dn as cacheResponse,Lo as clearDrlCache,xr as computeConnectionStatus,kn as connectViaPopup,pr as createConnectionStore,zr as createProfileReader,Do as deactivatePolyfills,mr as defineProtocol,qt as discoverWalletConnectServerUrl,Ke as encodeQr,cn as fetchResource,Re as fetchWalletWellKnown,bt as getDwnEndpoints,ln as handleEvent,Cr as isConnectDeniedError,Gr as isRetryableProfileReadStatus,Pr as isSessionExpiredError,_r as isSessionInvalidError,Rr as normalizeProtocolRequests,te as parseDrlUrl,Ge as probeWalletWellKnown,ze as qrToSvg,hr as recordCodecs,Ve as runConnectModal,Fe as runRelayConnect};
540
540
  //# sourceMappingURL=browser.mjs.map