Socket
Socket
Sign inDemoInstall

@getalby/sdk

Package Overview
Dependencies
Maintainers
4
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@getalby/sdk - npm Package Compare versions

Comparing version 3.2.2 to 3.2.3

2

dist/index.modern.js

@@ -1,1 +0,1 @@

import e from"events";import{generatePrivateKey as t,relayInit as n,nip19 as s,getPublicKey as o,finishEvent as r,getEventHash as i,nip04 as a}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},c.apply(this,arguments)}function u(e,t){if(null==e)return{};var n,s,o={},r=Object.keys(e);for(s=0;s<r.length;s++)t.indexOf(n=r[s])>=0||(o[n]=e[n]);return o}function h(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").filter(e=>e).join("&")}function l(e,t){return`Basic ${btoa(`${e}:${t}`)}`}class d extends Error{constructor(e,t,n,s){let o=e.toString();t&&(o+=` ${t}`),o+=": ",o+=s.message?s.message:JSON.stringify(s),super(o),this.status=void 0,this.statusText=void 0,this.headers=void 0,this.error=void 0,this.status=e,this.statusText=t,this.headers=n,this.error=s}}var p={__proto__:null,OAuthClient:class{},AuthClient:class{},AlbyResponseError:d};const m=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],y="https://api.getalby.com";async function w(e,t,n=0){const s=await fetch(e,t);if(429===s.status&&n>0){const o=Number(s.headers.get("x-rate-limit-reset")),r=Number(s.headers.get("x-rate-limit-remaining")),i=1e3*o-Date.now();let a=1e3;return 0===r&&(a=i),await new Promise(e=>setTimeout(e,a)),w(e,t,n-1)}return s}async function g(e){let{auth:t,endpoint:n,params:s={},request_body:o,method:r,max_retries:i,base_url:a=y,user_agent:l,headers:p}=e,g=u(e,m);const f=new URL(a+n);f.search=h(s);const b="POST"===r&&!!o,v=t?await t.getAuthHeader(f.href,r):void 0,_=await w(f.toString(),c({headers:c({},b?{"Content-Type":"application/json; charset=utf-8"}:void 0,v,p,{"User-Agent":null!=l?l:"@getalby/sdk","X-User-Agent":null!=l?l:"@getalby/sdk"}),method:r,body:b?JSON.stringify(o):void 0},g),i);if(!_.ok){const e=await _.json();throw new d(_.status,_.statusText,_.headers,e)}return _}async function f(e){return(await g(e)).json()}const b=["expires_in"],v=["token"];function _(e){const{expires_in:t}=e;return c({},u(e,b),!!t&&{expires_at:Date.now()+1e3*t})}class k{constructor(e){this.bearer_token=void 0,this.bearer_token=e}getAuthHeader(){return{Authorization:`Bearer ${this.bearer_token}`}}}var E={__proto__:null,OAuth2User:class{constructor(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;const{token:n}=t,s=u(t,v);this.options=c({client_secret:""},s),this.token=n,this._refreshAccessTokenPromise=null}on(e,t){this._tokenEvents.on(e,t)}async refreshAccessToken(){var e=this;return this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=new Promise(async function(t,n){try{var s;const n=null==(s=e.token)?void 0:s.refresh_token,{client_id:o,client_secret:r,request_options:i,user_agent:a}=e.options;if(!o)throw new Error("client_id is required");if(!n)throw new Error("refresh_token is required");const u=_(await f(c({},i,{endpoint:"/oauth/token",params:{client_id:o,grant_type:"refresh_token",refresh_token:n},user_agent:a,method:"POST",headers:c({},null==i?void 0:i.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:l(o,r)})})));e.token=u,t({token:u}),e._tokenEvents.emit("tokenRefreshed",e.token)}catch(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)}finally{e._refreshAccessTokenPromise=null}})),this._refreshAccessTokenPromise}isAccessTokenExpired(){var e,t;const n=null==(e=this.token)?void 0:e.refresh_token,s=null==(t=this.token)?void 0:t.expires_at;return!s||!!n&&s<=Date.now()+1e3}async requestAccessToken(e){const{client_id:t,client_secret:n,callback:s,request_options:o,user_agent:r}=this.options,i=this.code_verifier;if(!t)throw new Error("client_id is required");if(!n&&!i)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");const a={code:e,grant_type:"authorization_code",code_verifier:i,client_id:t,redirect_uri:s},u=_(await f(c({},o,{endpoint:"/oauth/token",params:a,user_agent:r,method:"POST",headers:c({},null==o?void 0:o.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:l(t,n)})})));return this.token=u,{token:u}}async generateAuthURL(e){e||(e={});const{client_id:t,callback:n,scopes:s}=this.options;if(!n)throw new Error("callback required");if(!s)throw new Error("scopes required");let o;"S256"===e.code_challenge_method?(await this._generateS256Challenge(),o="S256"):"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,o="plain");const r=this.code_challenge,i=new URL(e.authorizeUrl||"https://getalby.com/oauth");return i.search=h(c({},e,{client_id:t,scope:s.join(" "),response_type:"code",redirect_uri:n,code_challenge_method:o,code_challenge:r})),i.toString()}async getAuthHeader(){var e;if(null==(e=this.token)||!e.access_token)throw new Error("access_token is required");return this.isAccessTokenExpired()&&await this.refreshAccessToken(),{Authorization:`Bearer ${this.token.access_token}`}}async _generateS256Challenge(){const e=crypto.getRandomValues(new Uint8Array(64));this.code_verifier=e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"");const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(this.code_verifier)),n=new Uint8Array(t);this.code_challenge=btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},OAuth2Bearer:k};const A={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},T={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"};class P{static parseWalletConnectUrl(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");const t=new URL(e),n={};n.walletPubkey=t.host;const s=t.searchParams.get("secret"),o=t.searchParams.get("relay");return s&&(n.secret=s),o&&(n.relayUrl=o),n}static withNewSecret(e){return(e=e||{}).secret=t(),new P(e)}constructor(e){var t;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,e&&e.nostrWalletConnectUrl&&(e=c({},P.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const o=A[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=c({},o,e||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?s.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?s.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}getNostrWalletConnectUrl(e=!0){let t=`nostr+walletconnect://${this.walletPubkey}?relay=${this.relayUrl}&pubkey=${this.publicKey}`;return e&&(t=`${t}&secret=${this.secret}`),t}get nostrWalletConnectUrl(){return this.getNostrWalletConnectUrl()}get connected(){return 1===this.relay.status}get publicKey(){if(!this.secret)throw new Error("Missing secret key");return o(this.secret)}getPublicKey(){return Promise.resolve(this.publicKey)}signEvent(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(r(e,this.secret))}getEventHash(e){return i(e)}async enable(){this._enabled=!0}close(){return this.relay.close()}async encrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.encrypt(this.secret,e,t)}async decrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.decrypt(this.secret,e,t)}async getInfo(){await this.checkConnected();const e=["lightning","nostr"],t="Alby JS SDK";try{return await this.executeNip47Request("get_info",void 0,e=>!!e.methods,n=>({methods:n.methods.map(e=>T[e]),node:{alias:n.alias,pubkey:n.pubkey,color:n.color},supports:e,version:t}))}catch(n){return console.error("Failed to request get_info",n),{methods:["sendPayment"],node:{},supports:e,version:t}}}async getBalance(){return await this.checkConnected(),this.executeNip47Request("get_balance",void 0,e=>void 0!==e.balance,e=>({balance:Math.floor(e.balance/1e3),currency:"sats"}))}async sendPayment(e){return await this.checkConnected(),this.executeNip47Request("pay_invoice",{invoice:e},e=>!!e.preimage,e=>({preimage:e.preimage}))}async keysend(e){return await this.checkConnected(),this.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(e=>({type:parseInt(e[0]),value:e[1]})):[]},e=>!!e.preimage,e=>({preimage:e.preimage}))}lnurl(e){throw new Error("Method not implemented.")}async makeInvoice(e){var t;await this.checkConnected();const n="object"==typeof e?e:void 0,s=+(null!=(t=null==n?void 0:n.amount)?t:e);if(!s)throw new Error("No amount specified");return this.executeNip47Request("make_invoice",{amount:1e3*s,description:null==n?void 0:n.defaultMemo},e=>!!e.invoice,e=>({paymentRequest:e.invoice}))}async lookupInvoice(e){return await this.checkConnected(),this.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},e=>!!e.invoice,e=>({preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}))}async listTransactions(e){return await this.checkConnected(),this.executeNip47Request("list_transactions",e,e=>!!e.transactions,e=>({transactions:e.transactions.map(q)}))}request(e,t){throw new Error("Method not implemented.")}signMessage(e){throw new Error("Method not implemented.")}verifyMessage(e,t){throw new Error("Method not implemented.")}getAuthorizationUrl(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");const t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("c",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),t}initNWC(e={}){e.name||(e.name=document.location.host);const t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,s=window.outerWidth/2+window.screenX-200;return new Promise((e,o)=>{const r=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!r)return void o();const i=n=>{const s=n.data;s&&"nwc:success"===s.type&&n.origin===`${t.protocol}//${t.host}`&&(e(s),clearInterval(a),window.removeEventListener("message",i),r&&r.close())},a=setInterval(()=>{r&&r.closed&&(o(),clearInterval(a),window.removeEventListener("message",i))},500);window.addEventListener("message",i)})}async checkConnected(){if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!this.secret)throw new Error("Missing secret key");await this.relay.connect()}executeNip47Request(e,t,n,s){var o=this;const r=T[e];return new Promise((i,a)=>{!async function(){const c={method:e,params:t},u=await o.encrypt(o.walletPubkey,JSON.stringify(c)),h={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:u,pubkey:o.publicKey},l=await o.signEvent(h),d=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[l.id]}]),p=setTimeout(function(){d.unsub(),a({error:`reply timeout: event ${l.id}`,code:"INTERNAL"})},6e4);d.on("event",async function(e){clearTimeout(p),d.unsub();const t=await o.decrypt(o.walletPubkey,e.content);let c;try{c=JSON.parse(t)}catch(e){return void a({error:"invalid response",code:"INTERNAL"})}var u,h;23195==e.kind&&c.result?n(c.result)?(i(s(c.result)),o.notify(r,c.result)):a({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):a({error:null==(u=c.error)?void 0:u.message,code:null==(h=c.error)?void 0:h.code})});const m=setTimeout(function(){a({error:`Publish timeout: event ${l.id}`})},5e3);try{await o.relay.publish(l),clearTimeout(m)}catch(e){clearTimeout(m),a({error:`Failed to publish request: ${e}`})}}()})}}function q(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}const R=P;function O(e){const t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}class x{constructor(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new k(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}accountBalance(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))}accountSummary(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))}accountInformation(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))}accountValue4Value(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))}incomingInvoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))}outgoingInvoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))}invoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))}getInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${e}`,method:"GET"}))}decodeInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/decode/bolt11/${e}`,method:"GET"}))}createInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))}keysend(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e}):(n="/payments/keysend",s=e),f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendPayment(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))}sendBoostagram(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>O(e))}):(n="/payments/keysend",s=O(e)),f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendToAlbyAccount(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)}sendBoostagramToAlbyAccount(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))}createWebhookEndpoint(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))}deleteWebhookEndpoint(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/webhook_endpoints/${e}`,method:"DELETE"}))}getSwapInfo(e){return f(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))}createSwap(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))}}var S={__proto__:null,NostrWebLNProvider:P,NWC:R,OauthWeblnProvider:class{constructor(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new x(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}async enable(){var e;if(!this.isExecuting){if(null!=(e=this.auth.token)&&e.access_token)return{enabled:!0};if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");try{this.isExecuting=!0,await this.openAuthorization()}finally{this.isExecuting=!1}}}async sendPayment(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.sendPayment({invoice:e});return this.notify("sendPayment",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async keysend(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.keysend(e);return this.notify("keysend",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async getInfo(){return{alias:"Alby"}}async makeInvoice(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo});return this.notify("makeInvoice",t),{paymentRequest:t.payment_request}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=await this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((o,r)=>{const i=window.open(s,`${document.title} - WebLN enable`,`height=700,width=600,top=${t},left=${n}`);let a=!1;window.addEventListener("message",async function(t){const n=t.data;if(n&&"alby:oauth:success"===n.type&&t.origin===`${document.location.protocol}//${document.location.host}`&&!a){a=!0,console.info("Processing OAuth code response");const t=n.payload.code;try{await e.auth.requestAccessToken(t),e.client=new x(e.auth),i&&i.close(),e.notify("enable"),o({enabled:!0})}catch(e){console.error(e),r({enabled:!1})}}})})}}};export{x as Client,E as auth,p as types,S as webln};
import e from"events";import{generatePrivateKey as t,relayInit as n,nip19 as s,getPublicKey as o,finishEvent as r,getEventHash as i,nip04 as a}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},c.apply(this,arguments)}function u(e,t){if(null==e)return{};var n,s,o={},r=Object.keys(e);for(s=0;s<r.length;s++)t.indexOf(n=r[s])>=0||(o[n]=e[n]);return o}function h(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").filter(e=>e).join("&")}function l(e,t){return`Basic ${btoa(`${e}:${t}`)}`}class d extends Error{constructor(e,t,n,s){let o=e.toString();t&&(o+=` ${t}`),o+=": ",o+=s.message?s.message:JSON.stringify(s),super(o),this.status=void 0,this.statusText=void 0,this.headers=void 0,this.error=void 0,this.status=e,this.statusText=t,this.headers=n,this.error=s}}var p={__proto__:null,OAuthClient:class{},AuthClient:class{},AlbyResponseError:d};const m=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],y="https://api.getalby.com";async function w(e,t,n=0){const s=await fetch(e,t);if(429===s.status&&n>0){const o=Number(s.headers.get("x-rate-limit-reset")),r=Number(s.headers.get("x-rate-limit-remaining")),i=1e3*o-Date.now();let a=1e3;return 0===r&&(a=i),await new Promise(e=>setTimeout(e,a)),w(e,t,n-1)}return s}async function g(e){let{auth:t,endpoint:n,params:s={},request_body:o,method:r,max_retries:i,base_url:a=y,user_agent:l,headers:p}=e,g=u(e,m);const f=new URL(a+n);f.search=h(s);const b="POST"===r&&!!o,v=t?await t.getAuthHeader(f.href,r):void 0,_=await w(f.toString(),c({headers:c({},b?{"Content-Type":"application/json; charset=utf-8"}:void 0,v,p,{"User-Agent":null!=l?l:"@getalby/sdk","X-User-Agent":null!=l?l:"@getalby/sdk"}),method:r,body:b?JSON.stringify(o):void 0},g),i);if(!_.ok){const e=await _.json();throw new d(_.status,_.statusText,_.headers,e)}return _}async function f(e){return(await g(e)).json()}const b=["expires_in"],v=["token"];function _(e){const{expires_in:t}=e;return c({},u(e,b),!!t&&{expires_at:Date.now()+1e3*t})}class k{constructor(e){this.bearer_token=void 0,this.bearer_token=e}getAuthHeader(){return{Authorization:`Bearer ${this.bearer_token}`}}}var E={__proto__:null,OAuth2User:class{constructor(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;const{token:n}=t,s=u(t,v);this.options=c({client_secret:""},s),this.token=n,this._refreshAccessTokenPromise=null}on(e,t){this._tokenEvents.on(e,t)}async refreshAccessToken(){var e=this;return this._refreshAccessTokenPromise||(this._refreshAccessTokenPromise=new Promise(async function(t,n){try{var s;const n=null==(s=e.token)?void 0:s.refresh_token,{client_id:o,client_secret:r,request_options:i,user_agent:a}=e.options;if(!o)throw new Error("client_id is required");if(!n)throw new Error("refresh_token is required");const u=_(await f(c({},i,{endpoint:"/oauth/token",params:{client_id:o,grant_type:"refresh_token",refresh_token:n},user_agent:a,method:"POST",headers:c({},null==i?void 0:i.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:l(o,r)})})));e.token=u,t({token:u}),e._tokenEvents.emit("tokenRefreshed",e.token)}catch(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)}finally{e._refreshAccessTokenPromise=null}})),this._refreshAccessTokenPromise}isAccessTokenExpired(){var e,t;const n=null==(e=this.token)?void 0:e.refresh_token,s=null==(t=this.token)?void 0:t.expires_at;return!s||!!n&&s<=Date.now()+1e3}async requestAccessToken(e){const{client_id:t,client_secret:n,callback:s,request_options:o,user_agent:r}=this.options,i=this.code_verifier;if(!t)throw new Error("client_id is required");if(!n&&!i)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");const a={code:e,grant_type:"authorization_code",code_verifier:i,client_id:t,redirect_uri:s},u=_(await f(c({},o,{endpoint:"/oauth/token",params:a,user_agent:r,method:"POST",headers:c({},null==o?void 0:o.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:l(t,n)})})));return this.token=u,{token:u}}async generateAuthURL(e){e||(e={});const{client_id:t,callback:n,scopes:s}=this.options;if(!n)throw new Error("callback required");if(!s)throw new Error("scopes required");let o;"S256"===e.code_challenge_method?(await this._generateS256Challenge(),o="S256"):"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,o="plain");const r=this.code_challenge,i=new URL(e.authorizeUrl||"https://getalby.com/oauth");return i.search=h(c({},e,{client_id:t,scope:s.join(" "),response_type:"code",redirect_uri:n,code_challenge_method:o,code_challenge:r})),i.toString()}async getAuthHeader(){var e;if(null==(e=this.token)||!e.access_token)throw new Error("access_token is required");return this.isAccessTokenExpired()&&await this.refreshAccessToken(),{Authorization:`Bearer ${this.token.access_token}`}}async _generateS256Challenge(){const e=crypto.getRandomValues(new Uint8Array(64));this.code_verifier=e.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"");const t=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(this.code_verifier)),n=new Uint8Array(t);this.code_challenge=btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},OAuth2Bearer:k};const q={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},A={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"};class P{static parseWalletConnectUrl(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");const t=new URL(e),n={};n.walletPubkey=t.host;const s=t.searchParams.get("secret"),o=t.searchParams.get("relay");return s&&(n.secret=s),o&&(n.relayUrl=o),n}static withNewSecret(e){return(e=e||{}).secret=t(),new P(e)}constructor(e){var t;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,e&&e.nostrWalletConnectUrl&&(e=c({},P.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const o=q[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=c({},o,e||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?s.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?s.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}getNostrWalletConnectUrl(e=!0){let t=`nostr+walletconnect://${this.walletPubkey}?relay=${this.relayUrl}&pubkey=${this.publicKey}`;return e&&(t=`${t}&secret=${this.secret}`),t}get nostrWalletConnectUrl(){return this.getNostrWalletConnectUrl()}get connected(){return 1===this.relay.status}get publicKey(){if(!this.secret)throw new Error("Missing secret key");return o(this.secret)}getPublicKey(){return Promise.resolve(this.publicKey)}signEvent(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(r(e,this.secret))}getEventHash(e){return i(e)}async enable(){this._enabled=!0}close(){return this.relay.close()}async encrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.encrypt(this.secret,e,t)}async decrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await a.decrypt(this.secret,e,t)}async getInfo(){await this.checkConnected();const e=["lightning","nostr"],t="Alby JS SDK";try{return await this.executeNip47Request("get_info",void 0,e=>!!e.methods,n=>({methods:n.methods.map(e=>A[e]),node:{alias:n.alias,pubkey:n.pubkey,color:n.color},supports:e,version:t}))}catch(n){return console.error("Failed to request get_info",n),{methods:["sendPayment"],node:{},supports:e,version:t}}}async getBalance(){return await this.checkConnected(),this.executeNip47Request("get_balance",void 0,e=>void 0!==e.balance,e=>({balance:Math.floor(e.balance/1e3),currency:"sats"}))}async sendPayment(e){return await this.checkConnected(),this.executeNip47Request("pay_invoice",{invoice:e},e=>!!e.preimage,e=>({preimage:e.preimage}))}async keysend(e){return await this.checkConnected(),this.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(e=>({type:parseInt(e[0]),value:e[1]})):[]},e=>!!e.preimage,e=>({preimage:e.preimage}))}lnurl(e){throw new Error("Method not implemented.")}async makeInvoice(e){var t;await this.checkConnected();const n="object"==typeof e?e:void 0,s=+(null!=(t=null==n?void 0:n.amount)?t:e);if(!s)throw new Error("No amount specified");return this.executeNip47Request("make_invoice",{amount:1e3*s,description:null==n?void 0:n.defaultMemo},e=>!!e.invoice,e=>({paymentRequest:e.invoice}))}async lookupInvoice(e){return await this.checkConnected(),this.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},e=>!!e.invoice,e=>({preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}))}async listTransactions(e){return await this.checkConnected(),this.executeNip47Request("list_transactions",e,e=>!!e.transactions,e=>({transactions:e.transactions.map(T)}))}request(e,t){throw new Error("Method not implemented.")}signMessage(e){throw new Error("Method not implemented.")}verifyMessage(e,t){throw new Error("Method not implemented.")}getAuthorizationUrl(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");const t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t}initNWC(e={}){e.name||(e.name=document.location.host);const t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,s=window.outerWidth/2+window.screenX-200;return new Promise((e,o)=>{const r=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!r)return void o();const i=n=>{const s=n.data;s&&"nwc:success"===s.type&&n.origin===`${t.protocol}//${t.host}`&&(e(s),clearInterval(a),window.removeEventListener("message",i),r&&r.close())},a=setInterval(()=>{r&&r.closed&&(o(),clearInterval(a),window.removeEventListener("message",i))},500);window.addEventListener("message",i)})}async checkConnected(){if(!this._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!this.secret)throw new Error("Missing secret key");await this.relay.connect()}executeNip47Request(e,t,n,s){var o=this;const r=A[e];return new Promise((i,a)=>{!async function(){const c={method:e,params:t},u=await o.encrypt(o.walletPubkey,JSON.stringify(c)),h={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:u,pubkey:o.publicKey},l=await o.signEvent(h),d=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[l.id]}]),p=setTimeout(function(){d.unsub(),a({error:`reply timeout: event ${l.id}`,code:"INTERNAL"})},6e4);d.on("event",async function(e){clearTimeout(p),d.unsub();const t=await o.decrypt(o.walletPubkey,e.content);let c;try{c=JSON.parse(t)}catch(e){return void a({error:"invalid response",code:"INTERNAL"})}var u,h;23195==e.kind&&c.result?n(c.result)?(i(s(c.result)),o.notify(r,c.result)):a({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):a({error:null==(u=c.error)?void 0:u.message,code:null==(h=c.error)?void 0:h.code})});const m=setTimeout(function(){a({error:`Publish timeout: event ${l.id}`})},5e3);try{await o.relay.publish(l),clearTimeout(m)}catch(e){clearTimeout(m),a({error:`Failed to publish request: ${e}`})}}()})}}function T(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}const R=P;function O(e){const t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}class x{constructor(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new k(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}accountBalance(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))}accountSummary(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))}accountInformation(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))}accountValue4Value(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))}incomingInvoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))}outgoingInvoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))}invoices(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))}getInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${e}`,method:"GET"}))}decodeInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/decode/bolt11/${e}`,method:"GET"}))}createInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))}keysend(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e}):(n="/payments/keysend",s=e),f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendPayment(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))}sendBoostagram(e,t){let n,s;return Array.isArray(e)?(n="/payments/keysend/multi",s={keysends:e.map(e=>O(e))}):(n="/payments/keysend",s=O(e)),f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendToAlbyAccount(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)}sendBoostagramToAlbyAccount(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))}createWebhookEndpoint(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))}deleteWebhookEndpoint(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/webhook_endpoints/${e}`,method:"DELETE"}))}getSwapInfo(e){return f(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))}createSwap(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))}}var S={__proto__:null,NostrWebLNProvider:P,NWC:R,OauthWeblnProvider:class{constructor(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new x(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}on(e,t){this.subscribers[e]=t}notify(e,t){const n=this.subscribers[e];n&&n(t)}async enable(){var e;if(!this.isExecuting){if(null!=(e=this.auth.token)&&e.access_token)return{enabled:!0};if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");try{this.isExecuting=!0,await this.openAuthorization()}finally{this.isExecuting=!1}}}async sendPayment(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.sendPayment({invoice:e});return this.notify("sendPayment",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async keysend(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.keysend(e);return this.notify("keysend",t),{preimage:t.payment_preimage}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async getInfo(){return{alias:"Alby"}}async makeInvoice(e){if(!this.isExecuting)try{this.isExecuting=!0;const t=await this.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo});return this.notify("makeInvoice",t),{paymentRequest:t.payment_request}}catch(e){let t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)}finally{this.isExecuting=!1}}async openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=await this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((o,r)=>{const i=window.open(s,`${document.title} - WebLN enable`,`height=700,width=600,top=${t},left=${n}`);let a=!1;window.addEventListener("message",async function(t){const n=t.data;if(n&&"alby:oauth:success"===n.type&&t.origin===`${document.location.protocol}//${document.location.host}`&&!a){a=!0,console.info("Processing OAuth code response");const t=n.payload.code;try{await e.auth.requestAccessToken(t),e.client=new x(e.auth),i&&i.close(),e.notify("enable"),o({enabled:!0})}catch(e){console.error(e),r({enabled:!1})}}})})}}};export{x as Client,E as auth,p as types,S as webln};

@@ -1,1 +0,1 @@

import e from"events";import{generatePrivateKey as t,relayInit as n,nip19 as r,finishEvent as o,getEventHash as i,nip04 as s,getPublicKey as u}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(this,arguments)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function d(e,t,n){return d=l()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&h(o,n.prototype),o},d.apply(null,arguments)}function f(e){var t="function"==typeof Map?new Map:void 0;return f=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return d(e,arguments,a(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},f(e)}function p(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function m(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function v(e,t){return"Basic "+btoa(e+":"+t)}var y=/*#__PURE__*/function(e){var t,n;function r(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,h(t,n),r}(/*#__PURE__*/f(Error)),g={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:y},b=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],w=function(e){return Promise.resolve(_(e)).then(function(e){return e.json()})},_=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,u=e.max_retries,a=e.base_url,h=void 0===a?k:a,l=e.user_agent,d=e.headers,f=p(e,b);try{var v=function(e){return Promise.resolve(P(g.toString(),c({headers:c({},w?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,d,{"User-Agent":null!=l?l:"@getalby/sdk","X-User-Agent":null!=l?l:"@getalby/sdk"}),method:s,body:w?JSON.stringify(i):void 0},f),u)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new y(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},g=new URL(h+n);g.search=m(o);var w="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(g.href,s)).then(v):v(void 0))}catch(e){return Promise.reject(e)}},P=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},k="https://api.getalby.com",E=["expires_in"],O=["token"];function T(e){var t=e.expires_in;return c({},p(e,E),!!t&&{expires_at:Date.now()+1e3*t})}var A=/*#__PURE__*/function(){function t(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;var n=t.token,r=p(t,O);this.options=c({client_secret:""},r),this.token=n,this._refreshAccessTokenPromise=null}var n=t.prototype;return n.on=function(e,t){this._tokenEvents.on(e,t)},n.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,u=o.request_options,a=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(w(c({},u,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:c({},null==u?void 0:u.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:v(i,s)})}))).then(function(n){var r=T(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},n.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},n.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,u=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(w(c({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:i},user_agent:u,method:"POST",headers:c({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:v(r,o)})}))).then(function(e){var n=T(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},n.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=m(c({},e,{client_id:i,scope:u.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,u=o.scopes;if(!s)throw new Error("callback required");if(!u)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},n.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},n._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=t.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},""),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},t}(),q=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),R={__proto__:null,OAuth2User:A,OAuth2Bearer:q};function j(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var x={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},S={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"},U=/*#__PURE__*/function(){function e(t){var o;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,t&&t.nostrWalletConnectUrl&&(t=c({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=x[(null==(o=t)?void 0:o.providerName)||"alby"];this.options=c({},i,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?r.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?r.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");var t=new URL(e),n={};n.walletPubkey=t.host;var r=t.searchParams.get("secret"),o=t.searchParams.get("relay");return r&&(n.secret=r),o&&(n.relayUrl=o),n},e.withNewSecret=function(n){return(n=n||{}).secret=t(),new e(n)};var a,h,l=e.prototype;return l.on=function(e,t){this.subscribers[e]=t},l.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},l.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},l.getPublicKey=function(){return Promise.resolve(this.publicKey)},l.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(o(e,this.secret))},l.getEventHash=function(e){return i(e)},l.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},l.close=function(){return this.relay.close()},l.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},l.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},l.getInfo=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return j(function(){return Promise.resolve(e.executeNip47Request("get_info",void 0,function(e){return!!e.methods},function(e){return{methods:e.methods.map(function(e){return S[e]}),node:{alias:e.alias,pubkey:e.pubkey,color:e.color},supports:t,version:n}}))},function(e){return console.error("Failed to request get_info",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},l.getBalance=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){return e.executeNip47Request("get_balance",void 0,function(e){return void 0!==e.balance},function(e){return{balance:Math.floor(e.balance/1e3),currency:"sats"}})})}catch(e){return Promise.reject(e)}},l.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_invoice",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},l.keysend=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:e[1]}}):[]},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},l.lnurl=function(e){throw new Error("Method not implemented.")},l.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return t.executeNip47Request("make_invoice",{amount:1e3*o,description:null==r?void 0:r.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})})}catch(e){return Promise.reject(e)}},l.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},function(e){return!!e.invoice},function(e){return{preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}})})}catch(e){return Promise.reject(e)}},l.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions},function(e){return{transactions:e.transactions.map(N)}})})}catch(e){return Promise.reject(e)}},l.request=function(e,t){throw new Error("Method not implemented.")},l.signMessage=function(e){throw new Error("Method not implemented.")},l.verifyMessage=function(e,t){throw new Error("Method not implemented.")},l.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("c",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),t},l.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(o(),clearInterval(u),window.removeEventListener("message",s))},500);window.addEventListener("message",s)}else o()})},l.checkConnected=function(){try{var e=this;if(!e._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(e.relay.connect()).then(function(){})}catch(e){return Promise.reject(e)}},l.executeNip47Request=function(e,t,n,r){var o=this,i=S[e];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){t.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);t.on("event",function(e){try{return clearTimeout(c),t.unsub(),Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(t){var c,a,h;try{c=JSON.parse(t)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?n(c.result)?(s(r(c.result)),o.notify(i,c.result)):u({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):u({error:null==(a=c.error)?void 0:a.message,code:null==(h=c.error)?void 0:h.code})})}catch(e){return Promise.reject(e)}});var a=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3),h=j(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),u({error:"Failed to publish request: "+e})});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})},a=e,(h=[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return u(this.secret)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(a.prototype,h),Object.defineProperty(a,"prototype",{writable:!1}),e}();function N(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}var C=U;function I(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}var M=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new q(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e}):(n="/payments/keysend",r=e),w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return I(e)})}):(n="/payments/keysend",r=I(e)),w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return w(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function W(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function L(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var z={__proto__:null,NostrWebLNProvider:U,NWC:C,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new M(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=W(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=L(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new M(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};export{M as Client,R as auth,g as types,z as webln};
import e from"events";import{generatePrivateKey as t,relayInit as n,nip19 as r,finishEvent as o,getEventHash as i,nip04 as s,getPublicKey as u}from"nostr-tools";function c(){return c=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},c.apply(this,arguments)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function d(e,t,n){return d=l()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&h(o,n.prototype),o},d.apply(null,arguments)}function f(e){var t="function"==typeof Map?new Map:void 0;return f=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return d(e,arguments,a(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},f(e)}function p(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function m(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function v(e,t){return"Basic "+btoa(e+":"+t)}var y=/*#__PURE__*/function(e){var t,n;function r(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,h(t,n),r}(/*#__PURE__*/f(Error)),g={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:y},b=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],w=function(e){return Promise.resolve(_(e)).then(function(e){return e.json()})},_=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,u=e.max_retries,a=e.base_url,h=void 0===a?k:a,l=e.user_agent,d=e.headers,f=p(e,b);try{var v=function(e){return Promise.resolve(P(g.toString(),c({headers:c({},w?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,d,{"User-Agent":null!=l?l:"@getalby/sdk","X-User-Agent":null!=l?l:"@getalby/sdk"}),method:s,body:w?JSON.stringify(i):void 0},f),u)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new y(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},g=new URL(h+n);g.search=m(o);var w="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(g.href,s)).then(v):v(void 0))}catch(e){return Promise.reject(e)}},P=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},k="https://api.getalby.com",E=["expires_in"],O=["token"];function q(e){var t=e.expires_in;return c({},p(e,E),!!t&&{expires_at:Date.now()+1e3*t})}var T=/*#__PURE__*/function(){function t(t){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new e;var n=t.token,r=p(t,O);this.options=c({client_secret:""},r),this.token=n,this._refreshAccessTokenPromise=null}var n=t.prototype;return n.on=function(e,t){this._tokenEvents.on(e,t)},n.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var i=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,i=o.client_id,s=o.client_secret,u=o.request_options,a=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(w(c({},u,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:c({},null==u?void 0:u.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:v(i,s)})}))).then(function(n){var r=q(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return i&&i.then?i.then(o.bind(null,!1),o.bind(null,!0)):o(!1,i)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},n.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},n.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,i=n.callback,s=n.request_options,u=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!i)throw new Error("callback is required");return Promise.resolve(w(c({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:i},user_agent:u,method:"POST",headers:c({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:v(r,o)})}))).then(function(e){var n=q(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},n.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=m(c({},e,{client_id:i,scope:u.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,i=o.client_id,s=o.callback,u=o.scopes;if(!s)throw new Error("callback required");if(!u)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},n.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},n._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=t.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},""),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},t}(),A=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),R={__proto__:null,OAuth2User:T,OAuth2Bearer:A};function j(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var x={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},S={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"},U=/*#__PURE__*/function(){function e(t){var o;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,t&&t.nostrWalletConnectUrl&&(t=c({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=x[(null==(o=t)?void 0:o.providerName)||"alby"];this.options=c({},i,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?r.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?r.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");var t=new URL(e),n={};n.walletPubkey=t.host;var r=t.searchParams.get("secret"),o=t.searchParams.get("relay");return r&&(n.secret=r),o&&(n.relayUrl=o),n},e.withNewSecret=function(n){return(n=n||{}).secret=t(),new e(n)};var a,h,l=e.prototype;return l.on=function(e,t){this.subscribers[e]=t},l.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},l.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},l.getPublicKey=function(){return Promise.resolve(this.publicKey)},l.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(o(e,this.secret))},l.getEventHash=function(e){return i(e)},l.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},l.close=function(){return this.relay.close()},l.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},l.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(s.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},l.getInfo=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return j(function(){return Promise.resolve(e.executeNip47Request("get_info",void 0,function(e){return!!e.methods},function(e){return{methods:e.methods.map(function(e){return S[e]}),node:{alias:e.alias,pubkey:e.pubkey,color:e.color},supports:t,version:n}}))},function(e){return console.error("Failed to request get_info",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},l.getBalance=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){return e.executeNip47Request("get_balance",void 0,function(e){return void 0!==e.balance},function(e){return{balance:Math.floor(e.balance/1e3),currency:"sats"}})})}catch(e){return Promise.reject(e)}},l.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_invoice",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},l.keysend=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:e[1]}}):[]},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},l.lnurl=function(e){throw new Error("Method not implemented.")},l.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return t.executeNip47Request("make_invoice",{amount:1e3*o,description:null==r?void 0:r.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})})}catch(e){return Promise.reject(e)}},l.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},function(e){return!!e.invoice},function(e){return{preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}})})}catch(e){return Promise.reject(e)}},l.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions},function(e){return{transactions:e.transactions.map(N)}})})}catch(e){return Promise.reject(e)}},l.request=function(e,t){throw new Error("Method not implemented.")},l.signMessage=function(e){throw new Error("Method not implemented.")},l.verifyMessage=function(e,t){throw new Error("Method not implemented.")},l.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},l.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(o(),clearInterval(u),window.removeEventListener("message",s))},500);window.addEventListener("message",s)}else o()})},l.checkConnected=function(){try{var e=this;if(!e._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(e.relay.connect()).then(function(){})}catch(e){return Promise.reject(e)}},l.executeNip47Request=function(e,t,n,r){var o=this,i=S[e];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){t.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);t.on("event",function(e){try{return clearTimeout(c),t.unsub(),Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(t){var c,a,h;try{c=JSON.parse(t)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?n(c.result)?(s(r(c.result)),o.notify(i,c.result)):u({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):u({error:null==(a=c.error)?void 0:a.message,code:null==(h=c.error)?void 0:h.code})})}catch(e){return Promise.reject(e)}});var a=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3),h=j(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),u({error:"Failed to publish request: "+e})});if(h&&h.then)return h.then(function(){})})})}catch(e){Promise.reject(e)}})},a=e,(h=[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return u(this.secret)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(a.prototype,h),Object.defineProperty(a,"prototype",{writable:!1}),e}();function N(e){return c({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}var C=U;function I(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}var M=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new A(e):e,this.defaultRequestOptions=c({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e}):(n="/payments/keysend",r=e),w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return I(e)})}):(n="/payments/keysend",r=I(e)),w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return w(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return w(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function W(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function L(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var z={__proto__:null,NostrWebLNProvider:U,NWC:C,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new M(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=W(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(W(function(){return L(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=L(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new M(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};export{M as Client,R as auth,g as types,z as webln};

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("events"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","events","nostr-tools"],t):t((e||self).sdk={},e.events,e.nostrTools)}(this,function(e,t,n){function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/r(t);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i.apply(this,arguments)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function u(e,t){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},u(e,t)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function a(e,t,n){return a=c()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&u(o,n.prototype),o},a.apply(null,arguments)}function l(e){var t="function"==typeof Map?new Map:void 0;return l=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return a(e,arguments,s(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),u(n,e)},l(e)}function h(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function d(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function f(e,t){return"Basic "+btoa(e+":"+t)}var p=/*#__PURE__*/function(e){var t,n;function r(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,u(t,n),r}(/*#__PURE__*/l(Error)),m={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:p},v=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],y=function(e){return Promise.resolve(g(e)).then(function(e){return e.json()})},g=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,s=e.request_body,u=e.method,c=e.max_retries,a=e.base_url,l=void 0===a?w:a,f=e.user_agent,m=e.headers,y=h(e,v);try{var g=function(e){return Promise.resolve(b(_.toString(),i({headers:i({},P?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,m,{"User-Agent":null!=f?f:"@getalby/sdk","X-User-Agent":null!=f?f:"@getalby/sdk"}),method:u,body:P?JSON.stringify(s):void 0},y),c)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new p(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},_=new URL(l+n);_.search=d(o);var P="POST"===u&&!!s;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(_.href,u)).then(g):g(void 0))}catch(e){return Promise.reject(e)}},b=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},w="https://api.getalby.com",_=["expires_in"],P=["token"];function k(e){var t=e.expires_in;return i({},h(e,_),!!t&&{expires_at:Date.now()+1e3*t})}var E=/*#__PURE__*/function(){function e(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new o.default;var t=e.token,n=h(e,P);this.options=i({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var t=e.prototype;return t.on=function(e,t){this._tokenEvents.on(e,t)},t.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var s=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,s=o.client_id,u=o.client_secret,c=o.request_options,a=o.user_agent;if(!s)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(y(i({},c,{endpoint:"/oauth/token",params:{client_id:s,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:i({},null==c?void 0:c.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:f(s,u)})}))).then(function(n){var r=k(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return s&&s.then?s.then(o.bind(null,!1),o.bind(null,!0)):o(!1,s)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},t.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},t.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,s=n.callback,u=n.request_options,c=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");return Promise.resolve(y(i({},u,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:s},user_agent:c,method:"POST",headers:i({},null==u?void 0:u.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:f(r,o)})}))).then(function(e){var n=k(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},t.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=d(i({},e,{client_id:s,scope:c.join(" "),response_type:"code",redirect_uri:u,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,s=o.client_id,u=o.callback,c=o.scopes;if(!u)throw new Error("callback required");if(!c)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},t.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},t._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=t.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},""),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},e}(),O=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),T={__proto__:null,OAuth2User:E,OAuth2Bearer:O};function q(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var A={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},R={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"},j=/*#__PURE__*/function(){function e(t){var r;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,t&&t.nostrWalletConnectUrl&&(t=i({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var o=A[(null==(r=t)?void 0:r.providerName)||"alby"];this.options=i({},o,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n.relayInit(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?n.nip19.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?n.nip19.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");var t=new URL(e),n={};n.walletPubkey=t.host;var r=t.searchParams.get("secret"),o=t.searchParams.get("relay");return r&&(n.secret=r),o&&(n.relayUrl=o),n},e.withNewSecret=function(t){return(t=t||{}).secret=n.generatePrivateKey(),new e(t)};var t,r,o=e.prototype;return o.on=function(e,t){this.subscribers[e]=t},o.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},o.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},o.getPublicKey=function(){return Promise.resolve(this.publicKey)},o.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(n.finishEvent(e,this.secret))},o.getEventHash=function(e){return n.getEventHash(e)},o.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},o.close=function(){return this.relay.close()},o.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},o.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},o.getInfo=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return q(function(){return Promise.resolve(e.executeNip47Request("get_info",void 0,function(e){return!!e.methods},function(e){return{methods:e.methods.map(function(e){return R[e]}),node:{alias:e.alias,pubkey:e.pubkey,color:e.color},supports:t,version:n}}))},function(e){return console.error("Failed to request get_info",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},o.getBalance=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){return e.executeNip47Request("get_balance",void 0,function(e){return void 0!==e.balance},function(e){return{balance:Math.floor(e.balance/1e3),currency:"sats"}})})}catch(e){return Promise.reject(e)}},o.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_invoice",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},o.keysend=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:e[1]}}):[]},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},o.lnurl=function(e){throw new Error("Method not implemented.")},o.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return t.executeNip47Request("make_invoice",{amount:1e3*o,description:null==r?void 0:r.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})})}catch(e){return Promise.reject(e)}},o.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},function(e){return!!e.invoice},function(e){return{preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}})})}catch(e){return Promise.reject(e)}},o.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions},function(e){return{transactions:e.transactions.map(x)}})})}catch(e){return Promise.reject(e)}},o.request=function(e,t){throw new Error("Method not implemented.")},o.signMessage=function(e){throw new Error("Method not implemented.")},o.verifyMessage=function(e,t){throw new Error("Method not implemented.")},o.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("c",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),t},o.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(o(),clearInterval(u),window.removeEventListener("message",s))},500);window.addEventListener("message",s)}else o()})},o.checkConnected=function(){try{var e=this;if(!e._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(e.relay.connect()).then(function(){})}catch(e){return Promise.reject(e)}},o.executeNip47Request=function(e,t,n,r){var o=this,i=R[e];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){t.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);t.on("event",function(e){try{return clearTimeout(c),t.unsub(),Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(t){var c,a,l;try{c=JSON.parse(t)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?n(c.result)?(s(r(c.result)),o.notify(i,c.result)):u({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):u({error:null==(a=c.error)?void 0:a.message,code:null==(l=c.error)?void 0:l.code})})}catch(e){return Promise.reject(e)}});var a=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3),l=q(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),u({error:"Failed to publish request: "+e})});if(l&&l.then)return l.then(function(){})})})}catch(e){Promise.reject(e)}})},t=e,(r=[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return n.getPublicKey(this.secret)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function x(e){return i({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}var S=j;function U(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}var N=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new O(e):e,this.defaultRequestOptions=i({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e}):(n="/payments/keysend",r=e),y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return U(e)})}):(n="/payments/keysend",r=U(e)),y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return y(i({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function C(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function I(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var M={__proto__:null,NostrWebLNProvider:j,NWC:S,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new N(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=C(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=I(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new N(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};e.Client=N,e.auth=T,e.types=m,e.webln=M});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("events"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","events","nostr-tools"],t):t((e||self).sdk={},e.events,e.nostrTools)}(this,function(e,t,n){function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o=/*#__PURE__*/r(t);function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i.apply(this,arguments)}function s(e){return s=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},s(e)}function u(e,t){return u=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},u(e,t)}function c(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function a(e,t,n){return a=c()?Reflect.construct.bind():function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&u(o,n.prototype),o},a.apply(null,arguments)}function l(e){var t="function"==typeof Map?new Map:void 0;return l=function(e){if(null===e||-1===Function.toString.call(e).indexOf("[native code]"))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,n)}function n(){return a(e,arguments,s(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),u(n,e)},l(e)}function h(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)t.indexOf(n=i[r])>=0||(o[n]=e[n]);return o}function d(e){return Object.entries(e).map(function(e){var t=e[0],n=e[1];return t&&n?t+"="+n:""}).filter(function(e){return e}).join("&")}function f(e,t){return"Basic "+btoa(e+":"+t)}var p=/*#__PURE__*/function(e){var t,n;function r(t,n,r,o){var i,s=t.toString();return n&&(s+=" "+n),s+=": ",s+=o.message?o.message:JSON.stringify(o),(i=e.call(this,s)||this).status=void 0,i.statusText=void 0,i.headers=void 0,i.error=void 0,i.status=t,i.statusText=n,i.headers=r,i.error=o,i}return n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,u(t,n),r}(/*#__PURE__*/l(Error)),m={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:p},v=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],y=function(e){return Promise.resolve(g(e)).then(function(e){return e.json()})},g=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,s=e.request_body,u=e.method,c=e.max_retries,a=e.base_url,l=void 0===a?w:a,f=e.user_agent,m=e.headers,y=h(e,v);try{var g=function(e){return Promise.resolve(b(_.toString(),i({headers:i({},P?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,m,{"User-Agent":null!=f?f:"@getalby/sdk","X-User-Agent":null!=f?f:"@getalby/sdk"}),method:u,body:P?JSON.stringify(s):void 0},y),c)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new p(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},_=new URL(l+n);_.search=d(o);var P="POST"===u&&!!s;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(_.href,u)).then(g):g(void 0))}catch(e){return Promise.reject(e)}},b=function e(t,n,r){void 0===r&&(r=0);try{return Promise.resolve(fetch(t,n)).then(function(o){var i,s=function(){if(429===o.status&&r>0){var s=Number(o.headers.get("x-rate-limit-reset")),u=Number(o.headers.get("x-rate-limit-remaining")),c=1e3*s-Date.now(),a=1e3;return 0===u&&(a=c),Promise.resolve(new Promise(function(e){return setTimeout(e,a)})).then(function(){var o=e(t,n,r-1);return i=1,o})}}();return s&&s.then?s.then(function(e){return i?e:o}):i?s:o})}catch(e){return Promise.reject(e)}},w="https://api.getalby.com",_=["expires_in"],P=["token"];function k(e){var t=e.expires_in;return i({},h(e,_),!!t&&{expires_at:Date.now()+1e3*t})}var E=/*#__PURE__*/function(){function e(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0,this._tokenEvents=void 0,this._tokenEvents=new o.default;var t=e.token,n=h(e,P);this.options=i({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var t=e.prototype;return t.on=function(e,t){this._tokenEvents.on(e,t)},t.refreshAccessToken=function(){try{var e=this;return e._refreshAccessTokenPromise||(e._refreshAccessTokenPromise=new Promise(function(t,n){try{return Promise.resolve(function(r,o){try{var s=function(n,r){try{var o=function(){var n,r=null==(n=e.token)?void 0:n.refresh_token,o=e.options,s=o.client_id,u=o.client_secret,c=o.request_options,a=o.user_agent;if(!s)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(y(i({},c,{endpoint:"/oauth/token",params:{client_id:s,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:i({},null==c?void 0:c.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:f(s,u)})}))).then(function(n){var r=k(n);e.token=r,t({token:r}),e._tokenEvents.emit("tokenRefreshed",e.token)})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(t){console.error(t),n(t),e._tokenEvents.emit("tokenRefreshFailed",t)})}catch(e){return o(!0,e)}return s&&s.then?s.then(o.bind(null,!1),o.bind(null,!0)):o(!1,s)}(0,function(t,n){if(e._refreshAccessTokenPromise=null,t)throw n;return n}))}catch(e){return Promise.reject(e)}})),Promise.resolve(e._refreshAccessTokenPromise)}catch(e){return Promise.reject(e)}},t.isAccessTokenExpired=function(){var e,t,n=null==(e=this.token)?void 0:e.refresh_token,r=null==(t=this.token)?void 0:t.expires_at;return!r||!!n&&r<=Date.now()+1e3},t.requestAccessToken=function(e){try{var t=this,n=t.options,r=n.client_id,o=n.client_secret,s=n.callback,u=n.request_options,c=n.user_agent,a=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!a)throw new Error("either client_secret is required, or code should be generated using a challenge");if(!s)throw new Error("callback is required");return Promise.resolve(y(i({},u,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:s},user_agent:c,method:"POST",headers:i({},null==u?void 0:u.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:f(r,o)})}))).then(function(e){var n=k(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},t.generateAuthURL=function(e){try{var t=function(){var t=n.code_challenge,o=new URL(e.authorizeUrl||"https://getalby.com/oauth");return o.search=d(i({},e,{client_id:s,scope:c.join(" "),response_type:"code",redirect_uri:u,code_challenge_method:r,code_challenge:t})),o.toString()},n=this;e||(e={});var r,o=n.options,s=o.client_id,u=o.callback,c=o.scopes;if(!u)throw new Error("callback required");if(!c)throw new Error("scopes required");var a=function(){if("S256"===e.code_challenge_method)return Promise.resolve(n._generateS256Challenge()).then(function(){r="S256"});"plain"===e.code_challenge_method&&e.code_challenge&&(n.code_challenge=e.code_challenge,n.code_verifier=e.code_challenge,r="plain")}();return Promise.resolve(a&&a.then?a.then(t):t())}catch(e){return Promise.reject(e)}},t.getAuthHeader=function(){try{var e,t=function(){return{Authorization:"Bearer "+n.token.access_token}},n=this;if(null==(e=n.token)||!e.access_token)throw new Error("access_token is required");var r=function(){if(n.isAccessTokenExpired())return Promise.resolve(n.refreshAccessToken()).then(function(){})}();return Promise.resolve(r&&r.then?r.then(t):t())}catch(e){return Promise.reject(e)}},t._generateS256Challenge=function(){try{var e=this,t=crypto.getRandomValues(new Uint8Array(64));return e.code_verifier=t.reduce(function(e,t){return e+t.toString(16).padStart(2,"0")},""),Promise.resolve(crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e.code_verifier))).then(function(t){var n=new Uint8Array(t);e.code_challenge=btoa(String.fromCharCode.apply(String,n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")})}catch(e){return Promise.reject(e)}},e}(),O=/*#__PURE__*/function(){function e(e){this.bearer_token=void 0,this.bearer_token=e}return e.prototype.getAuthHeader=function(){return{Authorization:"Bearer "+this.bearer_token}},e}(),T={__proto__:null,OAuth2User:E,OAuth2Bearer:O};function q(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var A={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},R={get_info:"getInfo",get_balance:"getBalance",make_invoice:"makeInvoice",pay_invoice:"sendPayment",pay_keysend:"payKeysend",lookup_invoice:"lookupInvoice",list_transactions:"listTransactions"},j=/*#__PURE__*/function(){function e(t){var r;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,this._enabled=!1,t&&t.nostrWalletConnectUrl&&(t=i({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var o=A[(null==(r=t)?void 0:r.providerName)||"alby"];this.options=i({},o,t||{}),this.relayUrl=this.options.relayUrl,this.relay=n.relayInit(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?n.nip19.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?n.nip19.decode(this.options.walletPubkey).data:this.options.walletPubkey,this.subscribers={},void 0===globalThis.WebSocket&&console.error("WebSocket is undefined. Make sure to `import websocket-polyfill` for nodejs environments")}e.parseWalletConnectUrl=function(e){e=e.replace("nostrwalletconnect://","http://").replace("nostr+walletconnect://","http://");var t=new URL(e),n={};n.walletPubkey=t.host;var r=t.searchParams.get("secret"),o=t.searchParams.get("relay");return r&&(n.secret=r),o&&(n.relayUrl=o),n},e.withNewSecret=function(t){return(t=t||{}).secret=n.generatePrivateKey(),new e(t)};var t,r,o=e.prototype;return o.on=function(e,t){this.subscribers[e]=t},o.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},o.getNostrWalletConnectUrl=function(e){void 0===e&&(e=!0);var t="nostr+walletconnect://"+this.walletPubkey+"?relay="+this.relayUrl+"&pubkey="+this.publicKey;return e&&(t=t+"&secret="+this.secret),t},o.getPublicKey=function(){return Promise.resolve(this.publicKey)},o.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(n.finishEvent(e,this.secret))},o.getEventHash=function(e){return n.getEventHash(e)},o.enable=function(){try{return this._enabled=!0,Promise.resolve()}catch(e){return Promise.reject(e)}},o.close=function(){return this.relay.close()},o.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},o.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(n.nip04.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},o.getInfo=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){var t=["lightning","nostr"],n="Alby JS SDK";return q(function(){return Promise.resolve(e.executeNip47Request("get_info",void 0,function(e){return!!e.methods},function(e){return{methods:e.methods.map(function(e){return R[e]}),node:{alias:e.alias,pubkey:e.pubkey,color:e.color},supports:t,version:n}}))},function(e){return console.error("Failed to request get_info",e),{methods:["sendPayment"],node:{},supports:t,version:n}})})}catch(e){return Promise.reject(e)}},o.getBalance=function(){try{var e=this;return Promise.resolve(e.checkConnected()).then(function(){return e.executeNip47Request("get_balance",void 0,function(e){return void 0!==e.balance},function(e){return{balance:Math.floor(e.balance/1e3),currency:"sats"}})})}catch(e){return Promise.reject(e)}},o.sendPayment=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_invoice",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},o.keysend=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("pay_keysend",{amount:1e3*+e.amount,pubkey:e.destination,tlv_records:e.customRecords?Object.entries(e.customRecords).map(function(e){return{type:parseInt(e[0]),value:e[1]}}):[]},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})})}catch(e){return Promise.reject(e)}},o.lnurl=function(e){throw new Error("Method not implemented.")},o.makeInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){var n,r="object"==typeof e?e:void 0,o=+(null!=(n=null==r?void 0:r.amount)?n:e);if(!o)throw new Error("No amount specified");return t.executeNip47Request("make_invoice",{amount:1e3*o,description:null==r?void 0:r.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})})}catch(e){return Promise.reject(e)}},o.lookupInvoice=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("lookup_invoice",{invoice:e.paymentRequest,payment_hash:e.paymentHash},function(e){return!!e.invoice},function(e){return{preimage:e.preimage,paymentRequest:e.invoice,paid:!!e.settled_at}})})}catch(e){return Promise.reject(e)}},o.listTransactions=function(e){try{var t=this;return Promise.resolve(t.checkConnected()).then(function(){return t.executeNip47Request("list_transactions",e,function(e){return!!e.transactions},function(e){return{transactions:e.transactions.map(x)}})})}catch(e){return Promise.reject(e)}},o.request=function(e,t){throw new Error("Method not implemented.")},o.signMessage=function(e){throw new Error("Method not implemented.")},o.verifyMessage=function(e,t){throw new Error("Method not implemented.")},o.getAuthorizationUrl=function(e){if(!this.options.authorizationUrl)throw new Error("Missing authorizationUrl option");var t=new URL(this.options.authorizationUrl);return null!=e&&e.name&&t.searchParams.set("name",null==e?void 0:e.name),t.searchParams.set("pubkey",this.publicKey),null!=e&&e.returnTo&&t.searchParams.set("return_to",e.returnTo),null!=e&&e.budgetRenewal&&t.searchParams.set("budget_renewal",e.budgetRenewal),null!=e&&e.expiresAt&&t.searchParams.set("expires_at",Math.floor(e.expiresAt.getTime()/1e3).toString()),null!=e&&e.maxAmount&&t.searchParams.set("max_amount",e.maxAmount.toString()),void 0!==(null==e?void 0:e.editable)&&t.searchParams.set("editable",e.editable.toString()),null!=e&&e.requestMethods&&t.searchParams.set("request_methods",e.requestMethods.join(" ")),t},o.initNWC=function(e){void 0===e&&(e={}),e.name||(e.name=document.location.host);var t=this.getAuthorizationUrl(e),n=window.outerHeight/2+window.screenY-300,r=window.outerWidth/2+window.screenX-200;return new Promise(function(e,o){var i=window.open(t.toString(),document.title+" - Wallet Connect","height=600,width=400,top="+n+",left="+r);if(i){var s=function n(r){var o=r.data;o&&"nwc:success"===o.type&&r.origin===t.protocol+"//"+t.host&&(e(o),clearInterval(u),window.removeEventListener("message",n),i&&i.close())},u=setInterval(function(){i&&i.closed&&(o(),clearInterval(u),window.removeEventListener("message",s))},500);window.addEventListener("message",s)}else o()})},o.checkConnected=function(){try{var e=this;if(!e._enabled)throw new Error("please call enable() and await the promise before calling this function");if(!e.secret)throw new Error("Missing secret key");return Promise.resolve(e.relay.connect()).then(function(){})}catch(e){return Promise.reject(e)}},o.executeNip47Request=function(e,t,n,r){var o=this,i=R[e];return new Promise(function(s,u){try{return Promise.resolve(o.encrypt(o.walletPubkey,JSON.stringify({method:e,params:t}))).then(function(e){var t={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",o.walletPubkey]],content:e,pubkey:o.publicKey};return Promise.resolve(o.signEvent(t)).then(function(e){var t=o.relay.sub([{kinds:[23195],authors:[o.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){t.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);t.on("event",function(e){try{return clearTimeout(c),t.unsub(),Promise.resolve(o.decrypt(o.walletPubkey,e.content)).then(function(t){var c,a,l;try{c=JSON.parse(t)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?n(c.result)?(s(r(c.result)),o.notify(i,c.result)):u({error:"Response from NWC failed validation: "+JSON.stringify(c.result),code:"INTERNAL"}):u({error:null==(a=c.error)?void 0:a.message,code:null==(l=c.error)?void 0:l.code})})}catch(e){return Promise.reject(e)}});var a=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3),l=q(function(){return Promise.resolve(o.relay.publish(e)).then(function(){clearTimeout(a)})},function(e){clearTimeout(a),u({error:"Failed to publish request: "+e})});if(l&&l.then)return l.then(function(){})})})}catch(e){Promise.reject(e)}})},t=e,(r=[{key:"nostrWalletConnectUrl",get:function(){return this.getNostrWalletConnectUrl()}},{key:"connected",get:function(){return 1===this.relay.status}},{key:"publicKey",get:function(){if(!this.secret)throw new Error("Missing secret key");return n.getPublicKey(this.secret)}}])&&function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();function x(e){return i({},e,{amount:Math.floor(e.amount/1e3),fees_paid:e.fees_paid?Math.floor(e.fees_paid/1e3):0})}var S=j;function U(e){var t={};return e.recipient.customKey&&e.recipient.customValue&&(t[e.recipient.customKey]=e.recipient.customValue),t[7629169]=JSON.stringify(e.boostagram),{destination:e.recipient.address,amount:e.amount,customRecords:t}}var N=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new O(e):e,this.defaultRequestOptions=i({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.invoices=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",params:e,method:"GET"}))},t.getInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.decodeInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/decode/bolt11/"+e,method:"GET"}))},t.createInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices",request_body:e,method:"POST"}))},t.keysend=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e}):(n="/payments/keysend",r=e),y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/bolt11",request_body:e,method:"POST"}))},t.sendBoostagram=function(e,t){var n,r;return Array.isArray(e)?(n="/payments/keysend/multi",r={keysends:e.map(function(e){return U(e)})}):(n="/payments/keysend",r=U(e)),y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return console.warn("sendToAlbyAccount is deprecated. Please use sendBoostagramToAlbyAccount instead."),this.sendBoostagramToAlbyAccount(e,t)},t.sendBoostagramToAlbyAccount=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/payments/keysend",request_body:{destination:"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3",customRecords:{696969:e.account},amount:e.amount,memo:e.memo},method:"POST"}))},t.createWebhookEndpoint=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return y(i({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function C(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}function I(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var M={__proto__:null,NostrWebLNProvider:j,NWC:S,OauthWeblnProvider:/*#__PURE__*/function(){function e(e){this.client=void 0,this.auth=void 0,this.oauth=void 0,this.subscribers=void 0,this.isExecuting=void 0,this.auth=e.auth,this.client=new N(e.auth),this.oauth=!0,this.subscribers={},this.isExecuting=!1}var t=e.prototype;return t.on=function(e,t){this.subscribers[e]=t},t.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},t.enable=function(){try{var e,t=this;return t.isExecuting?Promise.resolve():null!=(e=t.auth.token)&&e.access_token?Promise.resolve({enabled:!0}):Promise.resolve(function(){if("undefined"==typeof window||void 0===window.document)throw new Error("Missing access token");var e=C(function(){return t.isExecuting=!0,Promise.resolve(t.openAuthorization()).then(function(){})},function(e,n){if(t.isExecuting=!1,e)throw n;return n});if(e&&e.then)return e.then(function(){})}())}catch(e){return Promise.reject(e)}},t.sendPayment=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.sendPayment({invoice:e})).then(function(e){return t.notify("sendPayment",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.keysend=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.keysend(e)).then(function(e){return t.notify("keysend",e),{preimage:e.payment_preimage}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.getInfo=function(){try{return Promise.resolve({alias:"Alby"})}catch(e){return Promise.reject(e)}},t.makeInvoice=function(e){try{var t=this;return t.isExecuting?Promise.resolve():Promise.resolve(C(function(){return I(function(){return t.isExecuting=!0,Promise.resolve(t.client.createInvoice({amount:parseInt(e.amount.toString()),description:e.defaultMemo})).then(function(e){return t.notify("makeInvoice",e),{paymentRequest:e.payment_request}})},function(e){var t="Unknown Error";throw e instanceof Error&&(t=e.message),new Error(t)})},function(e,n){if(t.isExecuting=!1,e)throw n;return n}))}catch(e){return Promise.reject(e)}},t.openAuthorization=function(){try{var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300;return Promise.resolve(e.auth.generateAuthURL({code_challenge_method:"S256"})).then(function(r){return new Promise(function(o,i){var s=window.open(r,document.title+" - WebLN enable","height=700,width=600,top="+t+",left="+n),u=!1;window.addEventListener("message",function(t){try{var n=t.data,r=function(){if(n&&"alby:oauth:success"===n.type&&t.origin===document.location.protocol+"//"+document.location.host&&!u){u=!0,console.info("Processing OAuth code response");var r=n.payload.code,c=I(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new N(e.auth),s&&s.close(),e.notify("enable"),o({enabled:!0})})},function(e){console.error(e),i({enabled:!1})});if(c&&c.then)return c.then(function(){})}}();return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}})})})}catch(e){return Promise.reject(e)}},e}()};e.Client=N,e.auth=T,e.types=m,e.webln=M});

@@ -187,4 +187,9 @@ import { AlbyResponseError } from "./AlbyResponseError";

} & Record<string, unknown>;
export type GetNWCAuthorizationUrlOptions = {
/**
* @deprecated please use NWCAuthorizationUrlOptions
*/
export type GetNWCAuthorizationUrlOptions = NWCAuthorizationUrlOptions;
export type NWCAuthorizationUrlOptions = {
name?: string;
requestMethods?: string[];
returnTo?: string;

@@ -191,0 +196,0 @@ expiresAt?: Date;

import { Relay, Event, UnsignedEvent } from "nostr-tools";
import { GetBalanceResponse, KeysendArgs, RequestInvoiceArgs, MakeInvoiceResponse, SendPaymentResponse, SignMessageResponse, WebLNProvider, WebLNRequestMethod, LookupInvoiceArgs, LookupInvoiceResponse } from "@webbtc/webln-types";
import { GetInfoResponse } from "@webbtc/webln-types";
import { GetNWCAuthorizationUrlOptions } from "../types";
import { NWCAuthorizationUrlOptions } from "../types";
export type Transaction = Nip47Transaction;

@@ -89,4 +89,4 @@ export type ListTransactionsResponse = {

verifyMessage(signature: string, message: string): Promise<void>;
getAuthorizationUrl(options?: GetNWCAuthorizationUrlOptions): URL;
initNWC(options?: GetNWCAuthorizationUrlOptions): Promise<unknown>;
getAuthorizationUrl(options?: NWCAuthorizationUrlOptions): URL;
initNWC(options?: NWCAuthorizationUrlOptions): Promise<unknown>;
private checkConnected;

@@ -93,0 +93,0 @@ private executeNip47Request;

{
"name": "@getalby/sdk",
"version": "3.2.2",
"version": "3.2.3",
"description": "The SDK to integrate with Nostr Wallet Connect and the Alby API",

@@ -5,0 +5,0 @@ "repository": "https://github.com/getAlby/js-sdk.git",

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc