@revibase/lite 0.1.2 → 0.2.0

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/index.cjs CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Install @solana/webcrypto-ed25519-polyfill and call its \`install\` function before generating keys in environments that do not support Ed25519.
4
4
 
5
- For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.`,[jt]:"No signature verification implementation could be found.",[Jt]:"No key generation implementation could be found.",[Qt]:"No signing implementation could be found.",[en]:"No key export implementation could be found.",[Rt]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Io]:"Transaction processing left an account with an outstanding borrowed reference",[Zr]:"Account in use",[qr]:"Account loaded twice",[jr]:"Attempt to debit an account but found no record of a prior credit.",[Do]:"Transaction loads an address table account that doesn't exist",[to]:"This transaction has already been processed",[no]:"Blockhash not found",[ro]:"Loader call chain is too deep",[uo]:"Transactions are currently disabled due to cluster maintenance",[po]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Qr]:"Insufficient funds for fee",[mo]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[eo]:"This account may not be used to pay transaction fees",[io]:"Transaction contains an invalid account reference",[No]:"Transaction loads an address table account with invalid data",[Co]:"Transaction address table lookup uses an invalid index",[go]:"Transaction loads an address table account with an invalid owner",[Mo]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[so]:"This program may not be used for executing instructions",[So]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[lo]:"Transaction loads a writable account that cannot be written",[ho]:"Transaction exceeded max loaded accounts data size cap",[oo]:"Transaction requires a fee but has no signature present",[Jr]:"Attempt to load a program that does not exist",[Lo]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[yo]:"ResanitizationNeeded",[co]:"Transaction failed to sanitize accounts offsets correctly",[ao]:"Transaction did not pass signature verification",[To]:"Transaction locked too many accounts",[Uo]:"Sum of account balances before and after transaction do not match",[Xr]:"The transaction failed with the error `$errorName`",[Ao]:"Transaction version is unsupported",[Ro]:"Transaction would exceed account data limit within the block",[fo]:"Transaction would exceed total account data limit",[Eo]:"Transaction would exceed max account limit within the block",[_o]:"Transaction would exceed max Block Cost Limit",[Oo]:"Transaction would exceed max Vote Cost Limit",[Wr]:"Attempted to sign a transaction with an address that is not a signer for it",[Fr]:"Transaction is missing an address at index: $index.",[xr]:"Transaction has no expected signers therefore it cannot be encoded",[Kr]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[hr]:"Transaction does not have a blockhash lifetime",[Mr]:"Transaction is not a durable nonce transaction",[Lr]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Ur]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[br]:"No fee payer set in CompiledTransaction",[vr]:"Could not find program address at index $index",[Hr]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Vr]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[Br]:"Transaction is missing a fee payer.",[zr]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[kr]:"Transaction first instruction is not advance nonce account instruction.",[wr]:"Transaction with no instructions cannot be durable nonce transaction.",[pr]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[mr]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Gr]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Pr]:"Transaction is missing signatures for addresses: $addresses.",[yr]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[$r]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Yr]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},h="i",S="t";function Oi(t,e={}){let n=Si[t];if(n.length===0)return "";let r;function o(i){if(r[S]===2){let c=n.slice(r[h]+1,i);s.push(c in e?`${e[c]}`:`$${c}`);}else r[S]===1&&s.push(n.slice(r[h],i));}let s=[];return n.split("").forEach((i,c)=>{if(c===0){r={[h]:0,[S]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let a;switch(r[S]){case 0:a={[h]:c,[S]:1};break;case 1:i==="\\"?a={[h]:c,[S]:0}:i==="$"&&(a={[h]:c,[S]:2});break;case 2:i==="\\"?a={[h]:c,[S]:0}:i==="$"?a={[h]:c,[S]:2}:i.match(/\w/)||(a={[h]:c,[S]:1});break}a&&(r!==a&&o(c),r=a);}),o(),s.join("")}function fi(t,e={}){if(process.env.NODE_ENV!=="production")return Oi(t,e);{let n=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(n+=` '${Ci(e)}'`),`${n}\``}}var b=class extends Error{cause=this.cause;context;constructor(...[t,e]){let n,r;e&&Object.entries(Object.getOwnPropertyDescriptors(e)).forEach(([s,i])=>{s==="cause"?r={cause:i.value}:(n===void 0&&(n={}),Object.defineProperty(n,s,i));});let o=fi(t,n);super(o,r),this.context=n===void 0?{}:n,this.context.__code=t,this.name="SolanaError";}};function pi(t,e){return "fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}function B(t){return Object.freeze({...t,encode:e=>{let n=new Uint8Array(pi(e,t));return t.write(e,n,0),n}})}function Ae(t){return Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]})}function mi(t){return "fixedSize"in t&&typeof t.fixedSize=="number"}function hi(t){return !mi(t)}function Ue(t,e){return B({fixedSize:e,write:(n,r,o)=>{let s=t.encode(n),i=s.length>e?s.slice(0,e):s;return r.set(i,o),o+e}})}function ve(t,e){return B({...hi(t)?{...t,getSizeFromValue:n=>t.getSizeFromValue(e(n))}:t,write:(n,r,o)=>t.write(e(n),r,o)})}function Mi(t,e,n=e){if(!e.match(new RegExp(`^[${t}]*$`)))throw new b(_e,{alphabet:t,base:t.length,value:n})}var yi=t=>B({getSizeFromValue:e=>{let[n,r]=be(e,t[0]);if(!r)return e.length;let o=Pe(r,t);return n.length+Math.ceil(o.toString(16).length/2)},write(e,n,r){if(Mi(t,e),e==="")return r;let[o,s]=be(e,t[0]);if(!s)return n.set(new Uint8Array(o.length).fill(0),r),r+o.length;let i=Pe(s,t),c=[];for(;i>0n;)c.unshift(Number(i%256n)),i/=256n;let a=[...Array(o.length).fill(0),...c];return n.set(a,r),r+a.length}});function be(t,e){let[n,r]=t.split(new RegExp(`((?!${e}).*)`));return [n,r]}function Pe(t,e){let n=BigInt(e.length),r=0n;for(let o of t)r*=n,r+=BigInt(e.indexOf(o));return r}var Li="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Be=()=>yi(Li);var L=()=>Ae({read:(t,e=0)=>[Buffer.from(t,e).toString("base64"),t.length]});var le;function ze(){return le||(le=Be()),le}function Ui(t){if(t.length<32||t.length>44)throw new b(ue,{actualLength:t.length});let r=ze().encode(t).byteLength;if(r!==32)throw new b(de,{actualLength:r})}function z(t){return Ui(t),t}function Ee(){return ve(Ue(ze(),32),t=>z(t))}function vi(t,e,n,r){if(r<e||r>n)throw new b(Ie,{codecDescription:t,max:n,min:e,value:r})}function bi(t){return t?.endian!==1}function Pi(t){return B({fixedSize:t.size,write(e,n,r){t.range&&vi(t.name,t.range[0],t.range[1],e);let o=new ArrayBuffer(t.size);return t.set(new DataView(o),e,bi(t.config)),n.set(new Uint8Array(o),r),r+t.size}})}var we=(t={})=>Pi({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,n,r)=>e.setBigUint64(0,BigInt(n),r),size:8});var U="https://auth.revibase.com";var ke="revibase.com";var O=class t extends Error{code;constructor(e,n){super(e),this.name="RevibaseError",this.code=n,Object.setPrototypeOf(this,t.prototype);}},J=class t extends O{constructor(e="Popup blocked. Please enable popups."){super(e,"POPUP_BLOCKED"),this.name="RevibasePopupBlockedError",Object.setPrototypeOf(this,t.prototype);}},H=class t extends O{constructor(e="Popup was closed by the user"){super(e,"POPUP_CLOSED"),this.name="RevibasePopupClosedError",Object.setPrototypeOf(this,t.prototype);}},V=class t extends O{constructor(e="Authentication timed out"){super(e,"TIMEOUT"),this.name="RevibaseTimeoutError",Object.setPrototypeOf(this,t.prototype);}},Q=class t extends O{constructor(e="An authorization flow is already in progress"){super(e,"FLOW_IN_PROGRESS"),this.name="RevibaseFlowInProgressError",Object.setPrototypeOf(this,t.prototype);}},K=class t extends O{constructor(e="Aborted"){super(e,"ABORTED"),this.name="RevibaseAbortedError",Object.setPrototypeOf(this,t.prototype);}},ee=class t extends O{constructor(e="Popup is not open. Call startRequest first."){super(e,"POPUP_NOT_OPEN"),this.name="RevibasePopupNotOpenError",Object.setPrototypeOf(this,t.prototype);}},$=class t extends O{constructor(e){super(e,"AUTH_FAILED"),this.name="RevibaseAuthError",Object.setPrototypeOf(this,t.prototype);}},te=class t extends O{constructor(e="Provider can only be used in a browser environment"){super(e,"ENVIRONMENT"),this.name="RevibaseEnvironmentError",Object.setPrototypeOf(this,t.prototype);}};var zi="device-keys",w="ed25519-keys",We="private-key",xe="public-key",Y=class t{static openDB(){return new Promise((e,n)=>{let r=indexedDB.open(zi,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(w)||o.createObjectStore(w);},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(e,n){let r=await t.openDB();return new Promise((o,s)=>{let i=r.transaction(w,"readwrite");i.objectStore(w).put(n,e),i.oncomplete=()=>o(),i.onerror=()=>s(i.error);})}static async loadFromDB(e){let n=await t.openDB();return new Promise((r,o)=>{let i=n.transaction(w,"readonly").objectStore(w).get(e);i.onsuccess=()=>r(i.result),i.onerror=()=>o(i.error);})}static async create(){let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",e.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await t.saveToDB(We,e.privateKey);}catch(o){throw o instanceof DOMException&&o.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):o}return await t.saveToDB(xe,r),r}static async getOrCreateDevicePublickey(){let e=await t.loadFromDB(xe);return e||(e=await t.create()),{publicKey:e}}static async sign(e){let n=await t.loadFromDB(We);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(e).setProtectedHeader({alg:"EdDSA"}).sign(n)}};function Ge(t){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let e=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=e<=768,o,s,i,c;if(r)o=e,s=n,i=0,c=0;else {let l=window.screenLeft??window.screenX??0,R=window.screenTop??window.screenY??0,A=window.innerWidth??document.documentElement.clientWidth??window.screen.width,f=window.innerHeight??document.documentElement.clientHeight??window.screen.height;o=500,s=600,c=Math.round(l+(A-o)/2),i=Math.round(R+(f-s)/2);}let a=["popup=yes",`width=${o}`,`height=${s}`,`top=${i}`,`left=${c}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(t??"","_blank",a)}var wi=3,ki=1e3,Wi=15e3,xi=8e3,Gi=64*1024,Hi=1008,Vi=1009;function Ki(t,e){return typeof t=="string"?new TextEncoder().encode(t).length<=e?t:null:t.byteLength>e?null:new TextDecoder().decode(t)}var $i=P.z.object({event:P.z.literal("awaiting_recipient")}),Yi=P.z.object({event:P.z.literal("recipient_connected"),data:P.z.object({devicePublicKey:P.z.string()})}),Xi=P.z.object({event:P.z.literal("recipient_disconnected")}),Zi=P.z.discriminatedUnion("event",[$i,Yi,Xi]);function qi(t){try{let e=JSON.parse(t),n=Zi.safeParse(e);return n.success?n.data:null}catch{return null}}function He(t){let{providerOrigin:e,channelId:n,device:r,callbacks:o,maxReconnectAttempts:s=wi,reconnectBaseDelayMs:i=ki,maxMessageBytes:c=Gi,verboseLogging:a=false,heartbeatIntervalMs:l=Wi,heartbeatTimeoutMs:R=xi}=t,{onAwaitingRecipient:A,onRecipientConnected:f,onRecipientDisconnected:W,onClose:p,onError:T,onAutoReconnecting:x,onConnected:X}=o,De=new URL(e),ot=De.protocol==="https:"?"wss:":"ws:",it=De.host,Z=`${ot}//${it}/api/channel/ws?channelId=${encodeURIComponent(n)}&role=sender&device=${encodeURIComponent(JSON.stringify(r))}`,u=t.logger??console,re="Heartbeat timeout";u.info("[Channel WS Sender] Creating socket",{channelId:n,wsUrl:Z});let d=new WebSocket(Z),I=false,oe=false,g=false,C=0,v=null,q=null,m=null,F=false;function j(){v!=null&&(clearTimeout(v),v=null);}function G(){q!=null&&(clearInterval(q),q=null),m!=null&&(clearTimeout(m),m=null);}function ge(_,N){if(!I){I=true,oe=true,g=false,j(),G();try{(d.readyState===WebSocket.OPEN||d.readyState===WebSocket.CONNECTING)&&d.close(_??1e3,N??"Closed");}catch{}}}function ie(_){_.onopen=async()=>{if(!(I||_!==d)){u.info("[Channel WS Sender] Socket opened",{channelId:n});try{if(I||_!==d||_.readyState!==WebSocket.OPEN)return;C=0,F=!1,X?.(),l>0&&R>0&&(q=setInterval(()=>{if(!(I||d.readyState!==WebSocket.OPEN)){if(m!=null){u.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),G();try{d.close(1e3,re);}catch{}return}try{d.send("ping");}catch{return}m=setTimeout(()=>{if(m=null,!I){u.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),G();try{d.close(1e3,re);}catch{}}},R);}},l));}catch(N){u.error("Channel WebSocket (sender) auth failed",N,{channelId:n}),T?.("Auth failed"),ge(Hi,"Auth failed");}}},_.onmessage=N=>{if(I||_!==d)return;let E=Ki(N.data,c);if(E===null){u.warn("[Channel WS Sender] Message too large or invalid",{channelId:n}),oe=true,j();try{_.close(Vi,"Message too large");}catch{}return}if(E==="pong"){m!=null&&(clearTimeout(m),m=null);return}let D=qi(E);if(!D){a&&u.info("[Channel WS Sender] Unparseable message",{channelId:n,preview:E.slice(0,100)});return}a&&u.info("[Channel WS Sender] Message received",{channelId:n,event:D.event,...D.event!=="awaiting_recipient"&&D.event!=="recipient_disconnected"&&{data:D.data}}),D.event==="awaiting_recipient"?A?.():D.event==="recipient_connected"?f?.(D.data):D.event==="recipient_disconnected"&&W?.();},_.onclose=N=>{if(_!==d)return;G();let E={code:N.code,reason:N.reason||"",wasClean:N.wasClean},D=E.reason===re,ae=()=>{g=true,p?.(E,{connectionLost:true});},se=()=>p?.(E);if(I&&!D){F?(F=false,ae()):se();return}if(D?u.info("[Channel WS Sender] Socket closed (heartbeat timeout)",{channelId:n,code:E.code,reason:E.reason||"(none)",retryCount:C}):I||u.info("[Channel WS Sender] Socket closed",{channelId:n,...E,retryCount:C}),oe){I=true,se();return}if(N.wasClean&&!D){I=true,F?(F=false,ae()):se();return}if(C>=s){I=true,u.info("[Channel WS Sender] Max reconnect attempts reached",{channelId:n,maxReconnectAttempts:s}),ae();return}let at=i*Math.pow(2,C),st=.8+.4*Math.random(),Ne=Math.min(Math.round(at*st),3e4);C+=1,x?.(C),u.info("[Channel WS Sender] Scheduling reconnect",{channelId:n,attempt:C,delayMs:Ne}),v=setTimeout(()=>{if(v=null,I)return;u.info("[Channel WS Sender] Reconnecting",{channelId:n,attempt:C});let ce=d;d=new WebSocket(Z);try{(ce.readyState===WebSocket.OPEN||ce.readyState===WebSocket.CONNECTING)&&ce.close(1e3,"Replaced by reconnect");}catch{}ie(d);},Ne);},_.onerror=()=>{_===d&&(u.info("[Channel WS Sender] Socket error",{channelId:n}),I||T?.("Connection error"));};}return ie(d),{reconnect(){if(!g&&!(v!=null&&!I))return u.info("[Channel WS Sender] reconnect() no-op",{channelId:n,closed:I,connectionLost:g}),false;let _=v!=null,N=g;u.info("[Channel WS Sender] reconnect() starting",{channelId:n}),I=false,g=false,C=0,F=_||N,j(),G();let E=d;d=new WebSocket(Z);try{(E.readyState===WebSocket.OPEN||E.readyState===WebSocket.CONNECTING)&&E.close(1e3,"Replaced by reconnect");}catch{}return ie(d),true},closeChannel(){if(!I&&!g&&d.readyState===WebSocket.OPEN)try{u.info("[Channel WS Sender] Sending close",{channelId:n}),d.send(JSON.stringify({type:"close"}));}catch(_){u.error("Channel close send failed",_,{channelId:n}),T?.("Failed to close channel");}else I||u.info("[Channel WS Sender] closeChannel skip send",{channelId:n,closed:I,connectionLost:g,readyState:d.readyState});if(!I){if(u.info("[Channel WS Sender] close() called",{channelId:n,connectionLost:g}),g){I=true,g=false,j(),p?.({code:1e3,reason:"Closed",wasClean:true});return}ge();}},cancelRequest(){if(I||g||d.readyState!==WebSocket.OPEN)return u.info("[Channel WS Sender] cancelRequest() skipped",{channelId:n,readyState:d.readyState}),false;try{return u.info("[Channel WS Sender] Sending cancel_request",{channelId:n}),d.send(JSON.stringify({type:"cancel_request"})),!0}catch(_){return u.error("Channel (sender) cancel_request send failed",_,{channelId:n}),T?.("Failed to cancel request"),false}}}}var Qi=(a=>(a[a.AUTHENTICATING=0]="AUTHENTICATING",a[a.AWAITING_RECIPIENT=1]="AWAITING_RECIPIENT",a[a.RECIPIENT_CONNECTED=2]="RECIPIENT_CONNECTED",a[a.RECIPIENT_DISCONNECTED=3]="RECIPIENT_DISCONNECTED",a[a.AUTO_RECONNECTING=4]="AUTO_RECONNECTING",a[a.CONNECTION_LOST=5]="CONNECTION_LOST",a[a.CHANNEL_CLOSED=6]="CHANNEL_CLOSED",a[a.ERROR=7]="ERROR",a))(Qi||{}),Ve=class t{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelWs=new Map;channelStatusListeners=new Set;logger;static CHANNEL_ID_CHARSET="23456789ABCDEFGHJKMNPQRSTUVWXYZ";static CHANNEL_ID_LENGTH=10;defaultCallback=async(e,n,r,o)=>{let s=await fetch("/api/clientAuthorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request:e,device:r,channelId:o}),signal:n}),i=await s.json();if(!s.ok)throw new $(i.error??"Authorization failed");return i};constructor(e={}){let{providerOrigin:n,onClientAuthorizationCallback:r,rpcEndpoint:o,logger:s}=e;this.onClientAuthorizationCallback=r??this.defaultCallback,this.providerOrigin=n??U,this.logger=s??{info:()=>{},warn:()=>{},error:()=>{}},o&&core.initialize({rpcEndpoint:o});}async getDeviceSignature(e){return {jwk:(await Y.getOrCreateDevicePublickey()).publicKey,jws:await Y.sign(new TextEncoder().encode(e))}}subscribeToChannelStatus(e){return this.channelStatusListeners.add(e),()=>{this.channelStatusListeners.delete(e);}}setChannelStatus(e,n){for(let r of this.channelStatusListeners)try{r(e,n);}catch(o){this.logger.error("[RevibaseProvider] Channel status listener threw",o);}}generateChannelId(){let e="",n=t.CHANNEL_ID_CHARSET.length;for(let r=0;r<t.CHANNEL_ID_LENGTH;r++)e+=t.CHANNEL_ID_CHARSET[Math.floor(Math.random()*n)];return e}async createChannel(){let e=this.generateChannelId(),n=await this.getDeviceSignature(e),r=window.origin;await this.onClientAuthorizationCallback({phase:"start",redirectOrigin:r,data:{channelId:e,device:n,type:"channel"}});let o=He({channelId:e,device:n,providerOrigin:this.providerOrigin,callbacks:{onAwaitingRecipient:()=>this.setChannelStatus(e,{status:1}),onRecipientConnected:({devicePublicKey:s})=>this.setChannelStatus(e,{status:2,recipient:s}),onRecipientDisconnected:()=>this.setChannelStatus(e,{status:3}),onClose:(s,i)=>{i?.connectionLost?this.setChannelStatus(e,{status:5}):(this.setChannelStatus(e,{status:6}),this.channelWs.delete(e));},onError:s=>this.setChannelStatus(e,{status:7,error:s}),onAutoReconnecting:s=>this.setChannelStatus(e,{status:4,reconnectAttempt:s})}});return this.channelWs.set(e,o),this.setChannelStatus(e,{status:0}),{channelId:e,url:`${this.providerOrigin}?channelId=${e}`}}cancelChannelRequest(e){this.channelWs.get(e)?.cancelRequest();}reconnectChannel(e){return this.channelWs.get(e)?.reconnect()??false}closeChannel(e){this.channelWs.get(e)?.closeChannel(),this.channelWs.delete(e);}closeAllChannels(){this.channelWs.entries().forEach(e=>e[1].closeChannel()),this.channelWs.clear();}startRequest(e){let n=window.origin,r=L().decode(crypto.getRandomValues(new Uint8Array(16)));if(!e){let o=new URL(this.providerOrigin);if(o.searchParams.set("rid",r),o.searchParams.set("redirectOrigin",n),this.popUp=Ge(o.toString()),!this.popUp)throw new J}return {rid:r,redirectOrigin:n}}async sendPayloadToProviderViaPopup({rid:e,timeoutMs:n=6e5,signal:r}){if(typeof window>"u")throw new te;if(this.pending.size>0)throw new Q;return new Promise((o,s)=>{let i=setTimeout(()=>{let c=this.pending.get(e);c&&(c.cancel?c.cancel(new V):(this.pending.delete(e),s(new V)));},n);if(!this.popUp||this.popUp.closed)throw new ee;this.pending.set(e,{rid:e,resolve:o,reject:s,timeoutId:i}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:e,signal:r});})}attachTransport(e){let{popup:n,origin:r,rid:o,signal:s}=e,i=this.pending.get(o);if(!i)return;let c=null,a=false,l=()=>{A(new K);},R=()=>{s.removeEventListener("abort",l),window.removeEventListener("message",p);try{c?.close();}catch{}c=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(W);},A=T=>{a||(a=true,clearTimeout(i.timeoutId),this.pending.delete(o),R(),i.reject(T));},f=()=>{a||(a=true,clearTimeout(i.timeoutId),this.pending.delete(o),R(),i.resolve({rid:o}));};if(i.cancel=A,s.aborted){A(new K);return}s.addEventListener("abort",l);let W=setInterval(()=>{n?.closed&&A(new H);},2e3),p=T=>{if(T.origin!==r||T.source!==n)return;let x=T.data;!x||x.type!=="popup-connect"||x.rid!==o||T.ports?.[0]&&(c=T.ports[0],c.start(),c.postMessage({type:"popup-init"}),c.onmessage=X=>{switch(X.data.type){case "popup-complete":f();break;case "popup-error":A(new $(X.data.error));break;case "popup-closed":{A(new H("Lost connection with the popup."));break}}},window.removeEventListener("message",p));};window.addEventListener("message",p);}};function Ke(t){let e=t.domain?`${t.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return t.nonce&&n.push(`Nonce: ${t.nonce}`),n.length>0?`${e}
5
+ For a list of runtimes that currently support Ed25519 operations, visit https://github.com/WICG/webcrypto-secure-curves/issues/20.`,[jt]:"No signature verification implementation could be found.",[Jt]:"No key generation implementation could be found.",[Qt]:"No signing implementation could be found.",[en]:"No key export implementation could be found.",[Rt]:"Timestamp value must be in the range [-(2n ** 63n), (2n ** 63n) - 1]. `$value` given",[Io]:"Transaction processing left an account with an outstanding borrowed reference",[Zr]:"Account in use",[qr]:"Account loaded twice",[jr]:"Attempt to debit an account but found no record of a prior credit.",[Do]:"Transaction loads an address table account that doesn't exist",[to]:"This transaction has already been processed",[no]:"Blockhash not found",[ro]:"Loader call chain is too deep",[uo]:"Transactions are currently disabled due to cluster maintenance",[po]:"Transaction contains a duplicate instruction ($index) that is not allowed",[Qr]:"Insufficient funds for fee",[mo]:"Transaction results in an account ($accountIndex) with insufficient funds for rent",[eo]:"This account may not be used to pay transaction fees",[io]:"Transaction contains an invalid account reference",[No]:"Transaction loads an address table account with invalid data",[Co]:"Transaction address table lookup uses an invalid index",[go]:"Transaction loads an address table account with an invalid owner",[Mo]:"LoadedAccountsDataSizeLimit set for transaction must be greater than 0.",[so]:"This program may not be used for executing instructions",[So]:"Transaction leaves an account with a lower balance than rent-exempt minimum",[lo]:"Transaction loads a writable account that cannot be written",[ho]:"Transaction exceeded max loaded accounts data size cap",[oo]:"Transaction requires a fee but has no signature present",[Jr]:"Attempt to load a program that does not exist",[Lo]:"Execution of the program referenced by account at index $accountIndex is temporarily restricted.",[yo]:"ResanitizationNeeded",[co]:"Transaction failed to sanitize accounts offsets correctly",[ao]:"Transaction did not pass signature verification",[To]:"Transaction locked too many accounts",[Uo]:"Sum of account balances before and after transaction do not match",[Xr]:"The transaction failed with the error `$errorName`",[Ao]:"Transaction version is unsupported",[Ro]:"Transaction would exceed account data limit within the block",[fo]:"Transaction would exceed total account data limit",[Eo]:"Transaction would exceed max account limit within the block",[_o]:"Transaction would exceed max Block Cost Limit",[Oo]:"Transaction would exceed max Vote Cost Limit",[Wr]:"Attempted to sign a transaction with an address that is not a signer for it",[Fr]:"Transaction is missing an address at index: $index.",[xr]:"Transaction has no expected signers therefore it cannot be encoded",[Kr]:"Transaction size $transactionSize exceeds limit of $transactionSizeLimit bytes",[hr]:"Transaction does not have a blockhash lifetime",[Mr]:"Transaction is not a durable nonce transaction",[Lr]:"Contents of these address lookup tables unknown: $lookupTableAddresses",[Ur]:"Lookup of address at index $highestRequestedIndex failed for lookup table `$lookupTableAddress`. Highest known index is $highestKnownIndex. The lookup table may have been extended since its contents were retrieved",[br]:"No fee payer set in CompiledTransaction",[vr]:"Could not find program address at index $index",[Hr]:"Failed to estimate the compute unit consumption for this transaction message. This is likely because simulating the transaction failed. Inspect the `cause` property of this error to learn more",[Vr]:"Transaction failed when it was simulated in order to estimate the compute unit consumption. The compute unit estimate provided is for a transaction that failed when simulated and may not be representative of the compute units this transaction would consume if successful. Inspect the `cause` property of this error to learn more",[Br]:"Transaction is missing a fee payer.",[zr]:"Could not determine this transaction's signature. Make sure that the transaction has been signed by its fee payer.",[kr]:"Transaction first instruction is not advance nonce account instruction.",[wr]:"Transaction with no instructions cannot be durable nonce transaction.",[pr]:"This transaction includes an address (`$programAddress`) which is both invoked and set as the fee payer. Program addresses may not pay fees",[mr]:"This transaction includes an address (`$programAddress`) which is both invoked and marked writable. Program addresses may not be writable",[Gr]:"The transaction message expected the transaction to have $numRequiredSignatures signatures, got $signaturesLength.",[Pr]:"Transaction is missing signatures for addresses: $addresses.",[yr]:"Transaction version must be in the range [0, 127]. `$actualVersion` given",[$r]:"This version of Kit does not support decoding transactions with version $unsupportedVersion. The current max supported version is 0.",[Yr]:"The transaction has a durable nonce lifetime (with nonce `$nonce`), but the nonce account address is in a lookup table. The lifetime constraint cannot be constructed without fetching the lookup tables for the transaction."},h="i",S="t";function Oi(t,e={}){let n=Si[t];if(n.length===0)return "";let r;function o(i){if(r[S]===2){let c=n.slice(r[h]+1,i);s.push(c in e?`${e[c]}`:`$${c}`);}else r[S]===1&&s.push(n.slice(r[h],i));}let s=[];return n.split("").forEach((i,c)=>{if(c===0){r={[h]:0,[S]:n[0]==="\\"?0:n[0]==="$"?2:1};return}let a;switch(r[S]){case 0:a={[h]:c,[S]:1};break;case 1:i==="\\"?a={[h]:c,[S]:0}:i==="$"&&(a={[h]:c,[S]:2});break;case 2:i==="\\"?a={[h]:c,[S]:0}:i==="$"?a={[h]:c,[S]:2}:i.match(/\w/)||(a={[h]:c,[S]:1});break}a&&(r!==a&&o(c),r=a);}),o(),s.join("")}function fi(t,e={}){if(process.env.NODE_ENV!=="production")return Oi(t,e);{let n=`Solana error #${t}; Decode this error by running \`npx @solana/errors decode -- ${t}`;return Object.keys(e).length&&(n+=` '${Ci(e)}'`),`${n}\``}}var b=class extends Error{cause=this.cause;context;constructor(...[t,e]){let n,r;e&&Object.entries(Object.getOwnPropertyDescriptors(e)).forEach(([s,i])=>{s==="cause"?r={cause:i.value}:(n===void 0&&(n={}),Object.defineProperty(n,s,i));});let o=fi(t,n);super(o,r),this.context=n===void 0?{}:n,this.context.__code=t,this.name="SolanaError";}};function pi(t,e){return "fixedSize"in e?e.fixedSize:e.getSizeFromValue(t)}function B(t){return Object.freeze({...t,encode:e=>{let n=new Uint8Array(pi(e,t));return t.write(e,n,0),n}})}function Ae(t){return Object.freeze({...t,decode:(e,n=0)=>t.read(e,n)[0]})}function mi(t){return "fixedSize"in t&&typeof t.fixedSize=="number"}function hi(t){return !mi(t)}function Ue(t,e){return B({fixedSize:e,write:(n,r,o)=>{let s=t.encode(n),i=s.length>e?s.slice(0,e):s;return r.set(i,o),o+e}})}function ve(t,e){return B({...hi(t)?{...t,getSizeFromValue:n=>t.getSizeFromValue(e(n))}:t,write:(n,r,o)=>t.write(e(n),r,o)})}function Mi(t,e,n=e){if(!e.match(new RegExp(`^[${t}]*$`)))throw new b(_e,{alphabet:t,base:t.length,value:n})}var yi=t=>B({getSizeFromValue:e=>{let[n,r]=be(e,t[0]);if(!r)return e.length;let o=Pe(r,t);return n.length+Math.ceil(o.toString(16).length/2)},write(e,n,r){if(Mi(t,e),e==="")return r;let[o,s]=be(e,t[0]);if(!s)return n.set(new Uint8Array(o.length).fill(0),r),r+o.length;let i=Pe(s,t),c=[];for(;i>0n;)c.unshift(Number(i%256n)),i/=256n;let a=[...Array(o.length).fill(0),...c];return n.set(a,r),r+a.length}});function be(t,e){let[n,r]=t.split(new RegExp(`((?!${e}).*)`));return [n,r]}function Pe(t,e){let n=BigInt(e.length),r=0n;for(let o of t)r*=n,r+=BigInt(e.indexOf(o));return r}var Li="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",Be=()=>yi(Li);var L=()=>Ae({read:(t,e=0)=>[Buffer.from(t,e).toString("base64"),t.length]});var le;function ze(){return le||(le=Be()),le}function Ui(t){if(t.length<32||t.length>44)throw new b(ue,{actualLength:t.length});let r=ze().encode(t).byteLength;if(r!==32)throw new b(de,{actualLength:r})}function z(t){return Ui(t),t}function Ee(){return ve(Ue(ze(),32),t=>z(t))}function vi(t,e,n,r){if(r<e||r>n)throw new b(Ie,{codecDescription:t,max:n,min:e,value:r})}function bi(t){return t?.endian!==1}function Pi(t){return B({fixedSize:t.size,write(e,n,r){t.range&&vi(t.name,t.range[0],t.range[1],e);let o=new ArrayBuffer(t.size);return t.set(new DataView(o),e,bi(t.config)),n.set(new Uint8Array(o),r),r+t.size}})}var we=(t={})=>Pi({config:t,name:"u64",range:[0n,BigInt("0xffffffffffffffff")],set:(e,n,r)=>e.setBigUint64(0,BigInt(n),r),size:8});var U="https://auth.revibase.com",ke="revibase.com";var O=class t extends Error{code;constructor(e,n){super(e),this.name="RevibaseError",this.code=n,Object.setPrototypeOf(this,t.prototype);}},J=class t extends O{constructor(e="Popup blocked. Please enable popups."){super(e,"POPUP_BLOCKED"),this.name="RevibasePopupBlockedError",Object.setPrototypeOf(this,t.prototype);}},H=class t extends O{constructor(e="Popup was closed by the user"){super(e,"POPUP_CLOSED"),this.name="RevibasePopupClosedError",Object.setPrototypeOf(this,t.prototype);}},V=class t extends O{constructor(e="Authentication timed out"){super(e,"TIMEOUT"),this.name="RevibaseTimeoutError",Object.setPrototypeOf(this,t.prototype);}},Q=class t extends O{constructor(e="An authorization flow is already in progress"){super(e,"FLOW_IN_PROGRESS"),this.name="RevibaseFlowInProgressError",Object.setPrototypeOf(this,t.prototype);}},K=class t extends O{constructor(e="Aborted"){super(e,"ABORTED"),this.name="RevibaseAbortedError",Object.setPrototypeOf(this,t.prototype);}},ee=class t extends O{constructor(e="Popup is not open. Call startRequest first."){super(e,"POPUP_NOT_OPEN"),this.name="RevibasePopupNotOpenError",Object.setPrototypeOf(this,t.prototype);}},$=class t extends O{constructor(e){super(e,"AUTH_FAILED"),this.name="RevibaseAuthError",Object.setPrototypeOf(this,t.prototype);}},te=class t extends O{constructor(e="Provider can only be used in a browser environment"){super(e,"ENVIRONMENT"),this.name="RevibaseEnvironmentError",Object.setPrototypeOf(this,t.prototype);}};var zi="device-keys",w="ed25519-keys",We="private-key",xe="public-key",Y=class t{static openDB(){return new Promise((e,n)=>{let r=indexedDB.open(zi,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(w)||o.createObjectStore(w);},r.onsuccess=()=>e(r.result),r.onerror=()=>n(r.error);})}static async saveToDB(e,n){let r=await t.openDB();return new Promise((o,s)=>{let i=r.transaction(w,"readwrite");i.objectStore(w).put(n,e),i.oncomplete=()=>o(),i.onerror=()=>s(i.error);})}static async loadFromDB(e){let n=await t.openDB();return new Promise((r,o)=>{let i=n.transaction(w,"readonly").objectStore(w).get(e);i.onsuccess=()=>r(i.result),i.onerror=()=>o(i.error);})}static async create(){let e=await crypto.subtle.generateKey({name:"Ed25519"},false,["sign","verify"]),n=await crypto.subtle.exportKey("jwk",e.publicKey),r=core.convertJWKToBase64String({...n,alg:"EdDSA"});try{await t.saveToDB(We,e.privateKey);}catch(o){throw o instanceof DOMException&&o.name==="DataCloneError"?new Error("Storing device key in this browser is not supported. Try Chrome or ensure you are in a secure context."):o}return await t.saveToDB(xe,r),r}static async getOrCreateDevicePublickey(){let e=await t.loadFromDB(xe);return e||(e=await t.create()),{publicKey:e}}static async sign(e){let n=await t.loadFromDB(We);if(!n)throw new Error("Device key not found. Call DeviceKeyManager.create() first.");return await new jose.CompactSign(e).setProtectedHeader({alg:"EdDSA"}).sign(n)}};function Ge(t){if(typeof window>"u")throw new Error("Function can only be called in a browser environment");let e=window.innerWidth||window.screen.availWidth,n=window.innerHeight||window.screen.availHeight,r=e<=768,o,s,i,c;if(r)o=e,s=n,i=0,c=0;else {let l=window.screenLeft??window.screenX??0,R=window.screenTop??window.screenY??0,A=window.innerWidth??document.documentElement.clientWidth??window.screen.width,f=window.innerHeight??document.documentElement.clientHeight??window.screen.height;o=500,s=600,c=Math.round(l+(A-o)/2),i=Math.round(R+(f-s)/2);}let a=["popup=yes",`width=${o}`,`height=${s}`,`top=${i}`,`left=${c}`,"toolbar=no","location=no","status=no","menubar=no","scrollbars=yes","resizable=yes"].join(",");return window.open(t??"","_blank",a)}var wi=3,ki=1e3,Wi=15e3,xi=8e3,Gi=64*1024,Hi=1008,Vi=1009;function Ki(t,e){return typeof t=="string"?new TextEncoder().encode(t).length<=e?t:null:t.byteLength>e?null:new TextDecoder().decode(t)}var $i=P.z.object({event:P.z.literal("awaiting_recipient")}),Yi=P.z.object({event:P.z.literal("recipient_connected"),data:P.z.object({devicePublicKey:P.z.string()})}),Xi=P.z.object({event:P.z.literal("recipient_disconnected")}),Zi=P.z.discriminatedUnion("event",[$i,Yi,Xi]);function qi(t){try{let e=JSON.parse(t),n=Zi.safeParse(e);return n.success?n.data:null}catch{return null}}function He(t){let{providerOrigin:e,channelId:n,device:r,callbacks:o,maxReconnectAttempts:s=wi,reconnectBaseDelayMs:i=ki,maxMessageBytes:c=Gi,verboseLogging:a=false,heartbeatIntervalMs:l=Wi,heartbeatTimeoutMs:R=xi}=t,{onAwaitingRecipient:A,onRecipientConnected:f,onRecipientDisconnected:W,onClose:p,onError:T,onAutoReconnecting:x,onConnected:X}=o,De=new URL(e),ot=De.protocol==="https:"?"wss:":"ws:",it=De.host,Z=`${ot}//${it}/api/channel/ws?channelId=${encodeURIComponent(n)}&role=sender&device=${encodeURIComponent(JSON.stringify(r))}`,u=t.logger??console,re="Heartbeat timeout";u.info("[Channel WS Sender] Creating socket",{channelId:n,wsUrl:Z});let d=new WebSocket(Z),I=false,oe=false,g=false,C=0,v=null,q=null,m=null,F=false;function j(){v!=null&&(clearTimeout(v),v=null);}function G(){q!=null&&(clearInterval(q),q=null),m!=null&&(clearTimeout(m),m=null);}function ge(_,N){if(!I){I=true,oe=true,g=false,j(),G();try{(d.readyState===WebSocket.OPEN||d.readyState===WebSocket.CONNECTING)&&d.close(_??1e3,N??"Closed");}catch{}}}function ie(_){_.onopen=async()=>{if(!(I||_!==d)){u.info("[Channel WS Sender] Socket opened",{channelId:n});try{if(I||_!==d||_.readyState!==WebSocket.OPEN)return;C=0,F=!1,X?.(),l>0&&R>0&&(q=setInterval(()=>{if(!(I||d.readyState!==WebSocket.OPEN)){if(m!=null){u.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),G();try{d.close(1e3,re);}catch{}return}try{d.send("ping");}catch{return}m=setTimeout(()=>{if(m=null,!I){u.warn("[Channel WS Sender] Heartbeat timeout",{channelId:n}),G();try{d.close(1e3,re);}catch{}}},R);}},l));}catch(N){u.error("Channel WebSocket (sender) auth failed",N,{channelId:n}),T?.("Auth failed"),ge(Hi,"Auth failed");}}},_.onmessage=N=>{if(I||_!==d)return;let E=Ki(N.data,c);if(E===null){u.warn("[Channel WS Sender] Message too large or invalid",{channelId:n}),oe=true,j();try{_.close(Vi,"Message too large");}catch{}return}if(E==="pong"){m!=null&&(clearTimeout(m),m=null);return}let D=qi(E);if(!D){a&&u.info("[Channel WS Sender] Unparseable message",{channelId:n,preview:E.slice(0,100)});return}a&&u.info("[Channel WS Sender] Message received",{channelId:n,event:D.event,...D.event!=="awaiting_recipient"&&D.event!=="recipient_disconnected"&&{data:D.data}}),D.event==="awaiting_recipient"?A?.():D.event==="recipient_connected"?f?.(D.data):D.event==="recipient_disconnected"&&W?.();},_.onclose=N=>{if(_!==d)return;G();let E={code:N.code,reason:N.reason||"",wasClean:N.wasClean},D=E.reason===re,ae=()=>{g=true,p?.(E,{connectionLost:true});},se=()=>p?.(E);if(I&&!D){F?(F=false,ae()):se();return}if(D?u.info("[Channel WS Sender] Socket closed (heartbeat timeout)",{channelId:n,code:E.code,reason:E.reason||"(none)",retryCount:C}):I||u.info("[Channel WS Sender] Socket closed",{channelId:n,...E,retryCount:C}),oe){I=true,se();return}if(N.wasClean&&!D){I=true,F?(F=false,ae()):se();return}if(C>=s){I=true,u.info("[Channel WS Sender] Max reconnect attempts reached",{channelId:n,maxReconnectAttempts:s}),ae();return}let at=i*Math.pow(2,C),st=.8+.4*Math.random(),Ne=Math.min(Math.round(at*st),3e4);C+=1,x?.(C),u.info("[Channel WS Sender] Scheduling reconnect",{channelId:n,attempt:C,delayMs:Ne}),v=setTimeout(()=>{if(v=null,I)return;u.info("[Channel WS Sender] Reconnecting",{channelId:n,attempt:C});let ce=d;d=new WebSocket(Z);try{(ce.readyState===WebSocket.OPEN||ce.readyState===WebSocket.CONNECTING)&&ce.close(1e3,"Replaced by reconnect");}catch{}ie(d);},Ne);},_.onerror=()=>{_===d&&(u.info("[Channel WS Sender] Socket error",{channelId:n}),I||T?.("Connection error"));};}return ie(d),{reconnect(){if(!g&&!(v!=null&&!I))return u.info("[Channel WS Sender] reconnect() no-op",{channelId:n,closed:I,connectionLost:g}),false;let _=v!=null,N=g;u.info("[Channel WS Sender] reconnect() starting",{channelId:n}),I=false,g=false,C=0,F=_||N,j(),G();let E=d;d=new WebSocket(Z);try{(E.readyState===WebSocket.OPEN||E.readyState===WebSocket.CONNECTING)&&E.close(1e3,"Replaced by reconnect");}catch{}return ie(d),true},closeChannel(){if(!I&&!g&&d.readyState===WebSocket.OPEN)try{u.info("[Channel WS Sender] Sending close",{channelId:n}),d.send(JSON.stringify({type:"close"}));}catch(_){u.error("Channel close send failed",_,{channelId:n}),T?.("Failed to close channel");}else I||u.info("[Channel WS Sender] closeChannel skip send",{channelId:n,closed:I,connectionLost:g,readyState:d.readyState});if(!I){if(u.info("[Channel WS Sender] close() called",{channelId:n,connectionLost:g}),g){I=true,g=false,j(),p?.({code:1e3,reason:"Closed",wasClean:true});return}ge();}},cancelRequest(){if(I||g||d.readyState!==WebSocket.OPEN)return u.info("[Channel WS Sender] cancelRequest() skipped",{channelId:n,readyState:d.readyState}),false;try{return u.info("[Channel WS Sender] Sending cancel_request",{channelId:n}),d.send(JSON.stringify({type:"cancel_request"})),!0}catch(_){return u.error("Channel (sender) cancel_request send failed",_,{channelId:n}),T?.("Failed to cancel request"),false}}}}var Qi=(a=>(a[a.AUTHENTICATING=0]="AUTHENTICATING",a[a.AWAITING_RECIPIENT=1]="AWAITING_RECIPIENT",a[a.RECIPIENT_CONNECTED=2]="RECIPIENT_CONNECTED",a[a.RECIPIENT_DISCONNECTED=3]="RECIPIENT_DISCONNECTED",a[a.AUTO_RECONNECTING=4]="AUTO_RECONNECTING",a[a.CONNECTION_LOST=5]="CONNECTION_LOST",a[a.CHANNEL_CLOSED=6]="CHANNEL_CLOSED",a[a.ERROR=7]="ERROR",a))(Qi||{}),Ve=class t{pending=new Map;onClientAuthorizationCallback;providerOrigin;popUp=null;channelWs=new Map;channelStatusListeners=new Set;logger;static CHANNEL_ID_CHARSET="23456789ABCDEFGHJKMNPQRSTUVWXYZ";static CHANNEL_ID_LENGTH=10;defaultCallback=async(e,n,r,o)=>{let s=await fetch("/api/clientAuthorization",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({request:e,device:r,channelId:o}),signal:n}),i=await s.json();if(!s.ok)throw new $(i.error??"Authorization failed");return i};constructor(e={}){let{providerOrigin:n,onClientAuthorizationCallback:r,rpcEndpoint:o,logger:s}=e;this.onClientAuthorizationCallback=r??this.defaultCallback,this.providerOrigin=n??U,this.logger=s??{info:()=>{},warn:()=>{},error:()=>{}},o&&core.initialize({rpcEndpoint:o});}async getDeviceSignature(e){return {jwk:(await Y.getOrCreateDevicePublickey()).publicKey,jws:await Y.sign(new TextEncoder().encode(e))}}subscribeToChannelStatus(e){return this.channelStatusListeners.add(e),()=>{this.channelStatusListeners.delete(e);}}setChannelStatus(e,n){for(let r of this.channelStatusListeners)try{r(e,n);}catch(o){this.logger.error("[RevibaseProvider] Channel status listener threw",o);}}generateChannelId(){let e="",n=t.CHANNEL_ID_CHARSET.length;for(let r=0;r<t.CHANNEL_ID_LENGTH;r++)e+=t.CHANNEL_ID_CHARSET[Math.floor(Math.random()*n)];return e}async createChannel(){let e=this.generateChannelId(),n=await this.getDeviceSignature(e),r=window.origin;await this.onClientAuthorizationCallback({phase:"start",redirectOrigin:r,data:{channelId:e,device:n,type:"channel"}});let o=He({channelId:e,device:n,providerOrigin:this.providerOrigin,callbacks:{onAwaitingRecipient:()=>this.setChannelStatus(e,{status:1}),onRecipientConnected:({devicePublicKey:s})=>this.setChannelStatus(e,{status:2,recipient:s}),onRecipientDisconnected:()=>this.setChannelStatus(e,{status:3}),onClose:(s,i)=>{i?.connectionLost?this.setChannelStatus(e,{status:5}):(this.setChannelStatus(e,{status:6}),this.channelWs.delete(e));},onError:s=>this.setChannelStatus(e,{status:7,error:s}),onAutoReconnecting:s=>this.setChannelStatus(e,{status:4,reconnectAttempt:s})}});return this.channelWs.set(e,o),this.setChannelStatus(e,{status:0}),{channelId:e,url:`${this.providerOrigin}?channelId=${e}`}}cancelChannelRequest(e){this.channelWs.get(e)?.cancelRequest();}reconnectChannel(e){return this.channelWs.get(e)?.reconnect()??false}closeChannel(e){this.channelWs.get(e)?.closeChannel(),this.channelWs.delete(e);}closeAllChannels(){this.channelWs.entries().forEach(e=>e[1].closeChannel()),this.channelWs.clear();}startRequest(e){let n=window.origin,r=L().decode(crypto.getRandomValues(new Uint8Array(16)));if(!e){let o=new URL(this.providerOrigin);if(o.searchParams.set("rid",r),o.searchParams.set("redirectOrigin",n),this.popUp=Ge(o.toString()),!this.popUp)throw new J}return {rid:r,redirectOrigin:n}}async sendPayloadToProviderViaPopup({rid:e,timeoutMs:n=6e5,signal:r}){if(typeof window>"u")throw new te;if(this.pending.size>0)throw new Q;return new Promise((o,s)=>{let i=setTimeout(()=>{let c=this.pending.get(e);c&&(c.cancel?c.cancel(new V):(this.pending.delete(e),s(new V)));},n);if(!this.popUp||this.popUp.closed)throw new ee;this.pending.set(e,{rid:e,resolve:o,reject:s,timeoutId:i}),this.attachTransport({popup:this.popUp,origin:new URL(this.providerOrigin).origin,rid:e,signal:r});})}attachTransport(e){let{popup:n,origin:r,rid:o,signal:s}=e,i=this.pending.get(o);if(!i)return;let c=null,a=false,l=()=>{A(new K);},R=()=>{s.removeEventListener("abort",l),window.removeEventListener("message",p);try{c?.close();}catch{}c=null;try{n&&!n.closed&&n.close();}catch{}this.popUp=null,clearInterval(W);},A=T=>{a||(a=true,clearTimeout(i.timeoutId),this.pending.delete(o),R(),i.reject(T));},f=()=>{a||(a=true,clearTimeout(i.timeoutId),this.pending.delete(o),R(),i.resolve({rid:o}));};if(i.cancel=A,s.aborted){A(new K);return}s.addEventListener("abort",l);let W=setInterval(()=>{n?.closed&&A(new H);},2e3),p=T=>{if(T.origin!==r||T.source!==n)return;let x=T.data;!x||x.type!=="popup-connect"||x.rid!==o||T.ports?.[0]&&(c=T.ports[0],c.start(),c.postMessage({type:"popup-init"}),c.onmessage=X=>{switch(X.data.type){case "popup-complete":f();break;case "popup-error":A(new $(X.data.error));break;case "popup-closed":{A(new H("Lost connection with the popup."));break}}},window.removeEventListener("message",p));};window.addEventListener("message",p);}};function Ke(t){let e=t.domain?`${t.domain} wants you to sign in with your account.`:"Sign in with your account.",n=[];return t.nonce&&n.push(`Nonce: ${t.nonce}`),n.length>0?`${e}
6
6
 
7
7
  ${n.join(`
8
8
  `)}`:e}async function k(t,e,n){let{rid:r,redirectOrigin:o}=t.startRequest(n?.channelId);await new Promise(a=>setTimeout(a,0));let s=e(r,o),i=new AbortController;n?.signal&&(n.signal.aborted?i.abort():n.signal.addEventListener("abort",()=>i.abort())),n?.channelId||t.sendPayloadToProviderViaPopup({rid:r,signal:i.signal}).catch(a=>i.abort(a));let c=n?.channelId?await t.getDeviceSignature(JSON.stringify({rid:r,channelId:n.channelId})):void 0;return t.onClientAuthorizationCallback(s,i.signal,c,n?.channelId)}async function cs(t,e){return k(t,(n,r)=>({phase:"start",rid:n,validTill:Date.now()+6e5,data:{type:"message",payload:Ke({domain:r,nonce:L().decode(crypto.getRandomValues(new Uint8Array(16)))})},redirectOrigin:r}),e)}async function ls(t,e,n){let{instructions:r,signer:o,addressesByLookupTableAddress:s,settingsIndexWithAddress:i}=e,c=core.prepareTransactionMessage({payer:z(o.walletAddress),instructions:r,addressesByLookupTableAddress:s}),a=i??o.settingsIndexWithAddress,l=await core.getSettingsFromIndex(a.index),A=(await core.fetchSettingsAccountData(l,a.settingsAddressTreeIndex)).members.some(f=>f.role===core.UserRole.TransactionManager);return k(t,(f,W)=>{let p={transactionMessageBytes:L().decode(c),transactionAddress:l,transactionActionType:A?"execute":"create_with_preauthorized_execution"};return {phase:"start",rid:f,validTill:Date.now()+6e5,data:{type:"transaction",payload:p,sendTx:true,additionalSigners:e.additionalSigners},redirectOrigin:W,signer:o.publicKey}},n)}var ne="11111111111111111111111111111111";var $e=0,Ye=1,Xe=2,Ze=3,qe=4,je=5,Je=6,Qe=7,et=8;process.env.NODE_ENV!=="production"&&({[$e]:"an account with the same address already exists",[je]:"provided address does not match addressed derived from seed",[Ze]:"cannot allocate account data of this length",[Xe]:"cannot assign account to this program id",[qe]:"length of requested seed is too long",[Qe]:"stored nonce is still in recent_blockhashes",[Je]:"advancing stored nonce requires a populated RecentBlockhashes sysvar",[et]:"specified nonce does not match stored nonce",[Ye]:"account does not have enough SOL to perform the operation"});var Re="TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";async function xp(t,e,n){if(e.amount<=0)throw new Error("Transfer amount must be greater than 0");if(!e.destination||typeof e.destination!="string")throw new Error("Destination address is required");let{mint:r,tokenProgram:o=Re,amount:s,destination:i,signer:c}=e;return k(t,(a,l)=>{let R={transactionActionType:"transfer_intent",transactionAddress:r?o:ne,transactionMessageBytes:L().decode(new Uint8Array([...we().encode(s),...Ee().encode(z(i)),...Ee().encode(z(r??ne))]))};return {phase:"start",rid:a,validTill:Date.now()+6e5,data:{type:"transaction",payload:R,sendTx:true},redirectOrigin:l,signer:c?.publicKey}},n)}var tt=P__default.default.object({phase:P__default.default.literal("start"),redirectOrigin:P__default.default.url(),data:P__default.default.object({type:P__default.default.literal("channel"),device:P__default.default.custom(),channelId:P__default.default.string()})}).strict();async function nt({privateKey:t,request:e,providerOrigin:n=U,signal:r}){let o=core.convertBase64StringToJWK(t);if(!o.alg)throw new Error("Property alg in JWK is missing.");let s=await new jose.CompactSign(new TextEncoder().encode(e.data.channelId)).setProtectedHeader({alg:o.alg}).sign(o),i=await fetch(`${n}/api/startChannel`,{method:"POST",body:JSON.stringify({signature:s,clientOrigin:e.redirectOrigin,device:e.data.device,channelId:e.data.channelId}),signal:r});if(!i.ok)throw new Error((await i.json()).error)}async function Te({privateKey:t,request:e,providerOrigin:n=U,signal:r,device:o,channelId:s}){let i=core.convertBase64StringToJWK(t);if(!i.alg)throw new Error("Property alg in JWK is missing.");let c=await new jose.CompactSign(core.createClientAuthorizationStartRequestChallenge(e)).setProtectedHeader({alg:i.alg}).sign(i),a=await fetch(`${n}/api/startRequest`,{method:"POST",body:JSON.stringify({signature:c,request:e,device:o,channelId:s}),signal:r});if(!a.ok)throw new Error((await a.json()).error);return await a.json()}async function rt(t,e=U,n=ke){let{payload:r}=t.data;if(r.startRequest.data.type!=="message")throw new Error("Invalid request type.");let o=r.startRequest.data.payload,s=core.createMessageChallenge(o,r.client.clientOrigin,r.device.jwk,r.startRequest.rid),{verified:i}=await server.verifyAuthenticationResponse({response:r.authResponse,expectedChallenge:core.bufferToBase64URLString(s),expectedRPID:n,expectedOrigin:e,requireUserVerification:false,credential:{counter:0,id:r.authResponse.id,publicKey:core.convertPubkeyCompressedToCose(r.signer)}});if(!i)throw new Error("WebAuthn message verification failed");return {user:core.UserInfoSchema.parse(r.additionalInfo)}}async function gm({request:t,privateKey:e,providerOrigin:n,rpId:r,signal:o,device:s,channelId:i}){let c=P__default.default.union([core.StartMessageRequestSchema,core.StartTransactionRequestSchema,tt]).parse(t),{data:a,redirectOrigin:l}=c,R=Date.now()+6e5;if(a.type==="message"){let A=await Te({request:{phase:"start",redirectOrigin:l,signer:c.signer,rid:c.rid,validTill:R,data:{type:"message",payload:a.payload}},privateKey:e,providerOrigin:n,signal:o,device:s,channelId:i});return rt({data:A.data},n,r)}else if(a.type==="transaction"){let A=await Te({request:{phase:"start",redirectOrigin:l,signer:c.signer,rid:c.rid,validTill:R,data:{type:"transaction",payload:a.payload,sendTx:true,additionalSigners:a.additionalSigners}},providerOrigin:n,privateKey:e,signal:o,device:s,channelId:i});return {txSig:A.data.payload.txSig,user:A.data.payload.user}}else return await nt({privateKey:e,request:{redirectOrigin:l,data:{channelId:a.channelId,device:a.device,type:"channel"}},signal:o,providerOrigin:n}),{ok:true}}exports.ChannelStatus=Qi;exports.RevibaseAbortedError=K;exports.RevibaseAuthError=$;exports.RevibaseEnvironmentError=te;exports.RevibaseError=O;exports.RevibaseFlowInProgressError=Q;exports.RevibasePopupBlockedError=J;exports.RevibasePopupClosedError=H;exports.RevibasePopupNotOpenError=ee;exports.RevibaseProvider=Ve;exports.RevibaseTimeoutError=V;exports.StartChannelRequestSchema=tt;exports.executeTransaction=ls;exports.processClientAuthCallback=gm;exports.signIn=cs;exports.transferTokens=xp;//# sourceMappingURL=index.cjs.map