alby-js-sdk
Advanced tools
Comparing version 2.2.3 to 2.3.0
@@ -1,3 +0,3 @@ | ||
export * from './OAuth2User'; | ||
export * from "./OAuth2User"; | ||
export * from "./OAuth2Bearer"; | ||
//# sourceMappingURL=auth.d.ts.map |
export * as auth from "./auth"; | ||
export * as types from './types'; | ||
export * as types from "./types"; | ||
export * as webln from "./webln"; | ||
export { Client } from "./client"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,2 +0,2 @@ | ||
import e from"crypto-js";import{generatePrivateKey as t,relayInit as n,nip19 as s,getPublicKey as r,finishEvent as o,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,r={},o=Object.keys(e);for(s=0;s<o.length;s++)t.indexOf(n=o[s])>=0||(r[n]=e[n]);return r}function h(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").join("&")}function l(e,t){return`Basic ${btoa(`${e}:${t}`)}`}class d extends Error{constructor(e,t,n,s){let r=e.toString();t&&(r+=` ${t}`),r+=": ",r+=s.message?s.message:JSON.stringify(s),super(r),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 r=Number(s.headers.get("x-rate-limit-reset")),o=Number(s.headers.get("x-rate-limit-remaining")),i=1e3*r-Date.now();let a=1e3;return 0===o&&(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:r,method:o,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"===o&&!!r,v=t?await t.getAuthHeader(f.href,o):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:o,body:b?JSON.stringify(r):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(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0;const{token:t}=e,n=u(e,v);this.options=c({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}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:r,client_secret:o,request_options:i,user_agent:a}=e.options;if(!r)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:r,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(r,o)})})));e.token=u,t({token:u})}catch(e){n(e)}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:r,user_agent:o}=this.options,i=this.code_verifier;if(!t)throw new Error("client_id is required");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({},r,{endpoint:"/oauth/token",params:a,user_agent:o,method:"POST",headers:c({},null==r?void 0:r.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:l(t,n)})})));return this.token=u,{token:u}}generateAuthURL(t){t||(t={}),console.log(t);const{client_id:n,callback:s,scopes:r}=this.options;if(!s)throw new Error("callback required");if(!r)throw new Error("scopes required");let o;if("S256"===t.code_challenge_method){const t=e.lib.WordArray.random(64);this.code_verifier=t.toString(),this.code_challenge=e.SHA256(this.code_verifier).toString(e.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),o="S256"}else"plain"===t.code_challenge_method&&t.code_challenge&&(this.code_challenge=t.code_challenge,this.code_verifier=t.code_challenge,o="plain");const i=this.code_challenge,a=new URL(t.authorizeUrl||"https://getalby.com/oauth");return a.search=h(c({},t,{client_id:n,scope:r.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:o,code_challenge:i})),a.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}`}}},OAuth2Bearer:k};const P={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}};class T{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"),r=t.searchParams.get("relay");return s&&(n.secret=s),r&&(n.relayUrl=r),n}static withNewSecret(e){return(e=e||{}).secret=t(),new T(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,e&&e.nostrWalletConnectUrl&&(e=c({},T.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const r=P[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=c({},r,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 r(this.secret)}getPublicKey(){return Promise.resolve(this.publicKey)}signEvent(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(o(e,this.secret))}getEventHash(e){return i(e)}async enable(){if(this.connected)return Promise.resolve();await this.relay.connect()}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(){return{methods:["getInfo","sendPayment","getBalance"],node:{},supports:["lightning"],version:"NWC"}}getBalance(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,e=>void 0!==e.balance,e=>e)}sendPayment(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},e=>!!e.preimage,e=>({preimage:e.preimage}))}keysend(e){throw new Error("Method not implemented.")}lnurl(e){throw new Error("Method not implemented.")}makeInvoice(e){throw new Error("Method not implemented.")}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,r)=>{const o=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!o)return void r();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),o&&o.close())},a=setInterval(()=>{o&&o.closed&&(r(),clearInterval(a),window.removeEventListener("message",i))},500);window.addEventListener("message",i)})}checkConnected(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")}executeNip47Request(e,t,n,s,r){var o=this;return new Promise(async function(i,a){const c={method:e,params:n},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);let 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 n=await o.decrypt(o.walletPubkey,e.content);let c;try{c=JSON.parse(n)}catch(e){return void a({error:"invalid response",code:"INTERNAL"})}var u,h;23195==e.kind&&c.result?s(c.result)?(i(r(c.result)),o.notify(t,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})});let m=o.relay.publish(l),y=setTimeout(function(){a({error:`Publish timeout: event ${l.id}`})},5e3);m.on("failed",e=>{clearTimeout(y),a({error:`Failed to publish request: ${e}`})}),m.on("ok",()=>{clearTimeout(y)})})}}const A=T;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 q{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"}))}getInvoice(e,t){return f(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${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 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 x={__proto__:null,NostrWebLNProvider:T,NWC:A,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 q(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}}openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((r,o)=>{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 q(e.auth),i&&i.close(),e.notify("enable"),r({enabled:!0})}catch(e){console.error(e),o({enabled:!1})}}})})}}};export{q as Client,E as auth,p as types,x as webln}; | ||
import e from"crypto-js";import t from"events";import{generatePrivateKey as n,relayInit as s,nip19 as r,getPublicKey as o,finishEvent as i,getEventHash as a,nip04 as c}from"nostr-tools";function u(){return u=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},u.apply(this,arguments)}function h(e,t){if(null==e)return{};var n,s,r={},o=Object.keys(e);for(s=0;s<o.length;s++)t.indexOf(n=o[s])>=0||(r[n]=e[n]);return r}function l(e){return Object.entries(e).map(([e,t])=>e&&t?`${e}=${t}`:"").filter(e=>e).join("&")}function d(e,t){return`Basic ${btoa(`${e}:${t}`)}`}class p extends Error{constructor(e,t,n,s){let r=e.toString();t&&(r+=` ${t}`),r+=": ",r+=s.message?s.message:JSON.stringify(s),super(r),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 m={__proto__:null,OAuthClient:class{},AuthClient:class{},AlbyResponseError:p};const y=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],w="https://api.getalby.com";async function f(e,t,n=0){const s=await fetch(e,t);if(429===s.status&&n>0){const r=Number(s.headers.get("x-rate-limit-reset")),o=Number(s.headers.get("x-rate-limit-remaining")),i=1e3*r-Date.now();let a=1e3;return 0===o&&(a=i),await new Promise(e=>setTimeout(e,a)),f(e,t,n-1)}return s}async function g(e){let{auth:t,endpoint:n,params:s={},request_body:r,method:o,max_retries:i,base_url:a=w,user_agent:c,headers:d}=e,m=h(e,y);const g=new URL(a+n);g.search=l(s);const v="POST"===o&&!!r,b=t?await t.getAuthHeader(g.href,o):void 0,_=await f(g.toString(),u({headers:u({},v?{"Content-Type":"application/json; charset=utf-8"}:void 0,b,d,{"User-Agent":null!=c?c:"@getalby/sdk","X-User-Agent":null!=c?c:"@getalby/sdk"}),method:o,body:v?JSON.stringify(r):void 0},m),i);if(!_.ok){const e=await _.json();throw new p(_.status,_.statusText,_.headers,e)}return _}async function v(e){return(await g(e)).json()}const b=["expires_in"],_=["token"];function k(e){const{expires_in:t}=e;return u({},h(e,b),!!t&&{expires_at:Date.now()+1e3*t})}class E{constructor(e){this.bearer_token=void 0,this.bearer_token=e}getAuthHeader(){return{Authorization:`Bearer ${this.bearer_token}`}}}var P={__proto__:null,OAuth2User:class{constructor(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 t;const{token:n}=e,s=h(e,_);this.options=u({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:r,client_secret:o,request_options:i,user_agent:a}=e.options;if(!r)throw new Error("client_id is required");if(!n)throw new Error("refresh_token is required");const c=k(await v(u({},i,{endpoint:"/oauth/token",params:{client_id:r,grant_type:"refresh_token",refresh_token:n},user_agent:a,method:"POST",headers:u({},null==i?void 0:i.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:d(r,o)})})));e.token=c,t({token:c}),e._tokenEvents.emit("tokenRefreshed",e.token)}catch(t){console.log(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:r,user_agent:o}=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},c=k(await v(u({},r,{endpoint:"/oauth/token",params:a,user_agent:o,method:"POST",headers:u({},null==r?void 0:r.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:d(t,n)})})));return this.token=c,{token:c}}generateAuthURL(t){t||(t={}),console.log(t);const{client_id:n,callback:s,scopes:r}=this.options;if(!s)throw new Error("callback required");if(!r)throw new Error("scopes required");let o;if("S256"===t.code_challenge_method){const t=e.lib.WordArray.random(64);this.code_verifier=t.toString(),this.code_challenge=e.SHA256(this.code_verifier).toString(e.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),o="S256"}else"plain"===t.code_challenge_method&&t.code_challenge&&(this.code_challenge=t.code_challenge,this.code_verifier=t.code_challenge,o="plain");const i=this.code_challenge,a=new URL(t.authorizeUrl||"https://getalby.com/oauth");return a.search=l(u({},t,{client_id:n,scope:r.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:o,code_challenge:i})),a.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}`}}},OAuth2Bearer:E};const T={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}};class A{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"),r=t.searchParams.get("relay");return s&&(n.secret=s),r&&(n.relayUrl=r),n}static withNewSecret(e){return(e=e||{}).secret=n(),new A(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,e&&e.nostrWalletConnectUrl&&(e=u({},A.parseWalletConnectUrl(e.nostrWalletConnectUrl),e));const n=T[(null==(t=e)?void 0:t.providerName)||"alby"];this.options=u({},n,e||{}),this.relayUrl=this.options.relayUrl,this.relay=s(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")}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(i(e,this.secret))}getEventHash(e){return a(e)}async enable(){if(this.connected)return Promise.resolve();await this.relay.connect()}close(){return this.relay.close()}async encrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await c.encrypt(this.secret,e,t)}async decrypt(e,t){if(!this.secret)throw new Error("Missing secret");return await c.decrypt(this.secret,e,t)}async getInfo(){return{methods:["getInfo","sendPayment","addinvoice","getBalance"],node:{},supports:["lightning"],version:"NWC"}}getBalance(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,e=>void 0!==e.balance,e=>e)}sendPayment(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},e=>!!e.preimage,e=>({preimage:e.preimage}))}keysend(e){throw new Error("Method not implemented.")}lnurl(e){throw new Error("Method not implemented.")}makeInvoice(e){var t;this.checkConnected();const n="object"==typeof e?e:void 0,s=null!=(t=null==n?void 0:n.amount)?t:"string"==typeof e?parseInt(e):e;if(!s)throw new Error("No amount specified");return this.executeNip47Request("make_invoice","addinvoice",{amount:s,description:null==n?void 0:n.defaultMemo},e=>!!e.invoice,e=>({paymentRequest:e.invoice}))}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,r)=>{const o=window.open(t.toString(),`${document.title} - Wallet Connect`,`height=600,width=400,top=${n},left=${s}`);if(!o)return void r();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),o&&o.close())},a=setInterval(()=>{o&&o.closed&&(r(),clearInterval(a),window.removeEventListener("message",i))},500);window.addEventListener("message",i)})}checkConnected(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")}executeNip47Request(e,t,n,s,r){var o=this;return new Promise(async function(i,a){const c={method:e,params:n},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);let 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 n=await o.decrypt(o.walletPubkey,e.content);let c;try{c=JSON.parse(n)}catch(e){return void a({error:"invalid response",code:"INTERNAL"})}var u,h;23195==e.kind&&c.result?s(c.result)?(i(r(c.result)),o.notify(t,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})});let m=o.relay.publish(l),y=setTimeout(function(){a({error:`Publish timeout: event ${l.id}`})},5e3);m.on("failed",e=>{clearTimeout(y),a({error:`Failed to publish request: ${e}`})}),m.on("ok",()=>{clearTimeout(y)})})}}const q=A;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 E(e):e,this.defaultRequestOptions=u({},t,{user_agent:null==t?void 0:t.user_agent})}accountBalance(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))}accountSummary(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))}accountInformation(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))}accountValue4Value(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))}incomingInvoices(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))}outgoingInvoices(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))}getInvoice(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/invoices/${e}`,method:"GET"}))}createInvoice(e,t){return v(u({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),v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendPayment(e,t){return v(u({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)),v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:s,method:"POST"}))}sendToAlbyAccount(e,t){return v(u({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 v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))}deleteWebhookEndpoint(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:`/webhook_endpoints/${e}`,method:"DELETE"}))}getSwapInfo(e){return v(u({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))}createSwap(e,t){return v(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))}}var R={__proto__:null,NostrWebLNProvider:A,NWC:q,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}}openAuthorization(){var e=this;const t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,s=this.auth.generateAuthURL({code_challenge_method:"S256"});return new Promise((r,o)=>{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"),r({enabled:!0})}catch(e){console.error(e),o({enabled:!1})}}})})}}};export{x as Client,P as auth,m as types,R as webln}; | ||
//# sourceMappingURL=index.modern.js.map |
@@ -1,2 +0,2 @@ | ||
import e from"crypto-js";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:""}).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)),w={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:y},g=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],b=function(e){return Promise.resolve(P(e)).then(function(e){return e.json()})},P=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,g);try{var v=function(e){return Promise.resolve(_(w.toString(),c({headers:c({},b?{"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:b?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})},w=new URL(h+n);w.search=m(o);var b="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(w.href,s)).then(v):v(void 0))}catch(e){return Promise.reject(e)}},_=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(e){this.token=void 0,this.options=void 0,this.code_verifier=void 0,this.code_challenge=void 0,this._refreshAccessTokenPromise=void 0;var t=e.token,n=p(e,O);this.options=c({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var n=t.prototype;return 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(b(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})})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(e){n(e)})}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(!i)throw new Error("callback is required");return Promise.resolve(b(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(t){t||(t={}),console.log(t);var n,r=this.options,o=r.client_id,i=r.callback,s=r.scopes;if(!i)throw new Error("callback required");if(!s)throw new Error("scopes required");if("S256"===t.code_challenge_method){var u=e.lib.WordArray.random(64);this.code_verifier=u.toString(),this.code_challenge=e.SHA256(this.code_verifier).toString(e.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),n="S256"}else"plain"===t.code_challenge_method&&t.code_challenge&&(this.code_challenge=t.code_challenge,this.code_verifier=t.code_challenge,n="plain");var a=this.code_challenge,h=new URL(t.authorizeUrl||"https://getalby.com/oauth");return h.search=m(c({},t,{client_id:o,scope:s.join(" "),response_type:"code",redirect_uri:i,code_challenge_method:n,code_challenge:a})),h.toString()},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)}},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}(),x={__proto__:null,OAuth2User:A,OAuth2Bearer:q},R={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},j=/*#__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,t&&t.nostrWalletConnectUrl&&(t=c({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=R[(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.connected?Promise.resolve():Promise.resolve(this.relay.connect()).then(function(){})}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{return Promise.resolve({methods:["getInfo","sendPayment","getBalance"],node:{},supports:["lightning"],version:"NWC"})}catch(e){return Promise.reject(e)}},l.getBalance=function(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,function(e){return void 0!==e.balance},function(e){return e})},l.sendPayment=function(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})},l.keysend=function(e){throw new Error("Method not implemented.")},l.lnurl=function(e){throw new Error("Method not implemented.")},l.makeInvoice=function(e){throw new Error("Method not implemented.")},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(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")},l.executeNip47Request=function(e,t,n,r,o){var i=this;return new Promise(function(s,u){try{return Promise.resolve(i.encrypt(i.walletPubkey,JSON.stringify({method:e,params:n}))).then(function(e){var n={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",i.walletPubkey]],content:e,pubkey:i.publicKey};return Promise.resolve(i.signEvent(n)).then(function(e){var n=i.relay.sub([{kinds:[23195],authors:[i.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){n.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);n.on("event",function(e){try{return clearTimeout(c),n.unsub(),Promise.resolve(i.decrypt(i.walletPubkey,e.content)).then(function(n){var c,a,h;try{c=JSON.parse(n)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?r(c.result)?(s(o(c.result)),i.notify(t,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=i.relay.publish(e),h=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3);a.on("failed",function(e){clearTimeout(h),u({error:"Failed to publish request: "+e})}),a.on("ok",function(){clearTimeout(h)})})})}catch(e){return 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}(),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 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 b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.getInvoice=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.createInvoice=function(e,t){return b(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),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return b(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 U(e)})}):(n="/payments/keysend",r=U(e)),b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return b(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 b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return b(c({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return b(c({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return b(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 C(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var I={__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=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 C(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 C(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 C(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(){var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,r=this.auth.generateAuthURL({code_challenge_method:"S256"});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=C(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)}})})},e}()};export{N as Client,x as auth,w as types,I as webln}; | ||
import e from"crypto-js";import t from"events";import{generatePrivateKey as n,relayInit as r,nip19 as o,finishEvent as i,getEventHash as s,nip04 as u,getPublicKey as c}from"nostr-tools";function a(){return a=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},a.apply(this,arguments)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function h(e,t){return h=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},h(e,t)}function d(){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 f(e,t,n){return f=d()?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},f.apply(null,arguments)}function p(e){var t="function"==typeof Map?new Map:void 0;return p=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 f(e,arguments,l(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),h(n,e)},p(e)}function m(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 v(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 y(e,t){return"Basic "+btoa(e+":"+t)}var g=/*#__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__*/p(Error)),w={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:g},b=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],_=function(e){return Promise.resolve(P(e)).then(function(e){return e.json()})},P=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,c=e.base_url,l=void 0===c?E:c,h=e.user_agent,d=e.headers,f=m(e,b);try{var p=function(e){return Promise.resolve(k(y.toString(),a({headers:a({},w?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,d,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@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 g(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},y=new URL(l+n);y.search=v(o);var w="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(y.href,s)).then(p):p(void 0))}catch(e){return Promise.reject(e)}},k=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)}},E="https://api.getalby.com",O=["expires_in"],T=["token"];function A(e){var t=e.expires_in;return a({},m(e,O),!!t&&{expires_at:Date.now()+1e3*t})}var q=/*#__PURE__*/function(){function n(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 t;var n=e.token,r=m(e,T);this.options=a({client_secret:""},r),this.token=n,this._refreshAccessTokenPromise=null}var r=n.prototype;return r.on=function(e,t){this._tokenEvents.on(e,t)},r.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,c=o.user_agent;if(!i)throw new Error("client_id is required");if(!r)throw new Error("refresh_token is required");return Promise.resolve(_(a({},u,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:c,method:"POST",headers:a({},null==u?void 0:u.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:y(i,s)})}))).then(function(n){var r=A(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.log(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)}},r.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},r.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,c=t.code_verifier;if(!r)throw new Error("client_id is required");if(!o&&!c)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(_(a({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:c,client_id:r,redirect_uri:i},user_agent:u,method:"POST",headers:a({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:y(r,o)})}))).then(function(e){var n=A(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},r.generateAuthURL=function(t){t||(t={}),console.log(t);var n,r=this.options,o=r.client_id,i=r.callback,s=r.scopes;if(!i)throw new Error("callback required");if(!s)throw new Error("scopes required");if("S256"===t.code_challenge_method){var u=e.lib.WordArray.random(64);this.code_verifier=u.toString(),this.code_challenge=e.SHA256(this.code_verifier).toString(e.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),n="S256"}else"plain"===t.code_challenge_method&&t.code_challenge&&(this.code_challenge=t.code_challenge,this.code_verifier=t.code_challenge,n="plain");var c=this.code_challenge,l=new URL(t.authorizeUrl||"https://getalby.com/oauth");return l.search=v(a({},t,{client_id:o,scope:s.join(" "),response_type:"code",redirect_uri:i,code_challenge_method:n,code_challenge:c})),l.toString()},r.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}(),R=/*#__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}(),x={__proto__:null,OAuth2User:q,OAuth2Bearer:R},j={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},S=/*#__PURE__*/function(){function e(t){var n;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,t&&t.nostrWalletConnectUrl&&(t=a({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var i=j[(null==(n=t)?void 0:n.providerName)||"alby"];this.options=a({},i,t||{}),this.relayUrl=this.options.relayUrl,this.relay=r(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?o.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?o.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(),new e(t)};var t,l,h=e.prototype;return h.on=function(e,t){this.subscribers[e]=t},h.notify=function(e,t){var n=this.subscribers[e];n&&n(t)},h.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},h.getPublicKey=function(){return Promise.resolve(this.publicKey)},h.signEvent=function(e){if(!this.secret)throw new Error("Missing secret key");return Promise.resolve(i(e,this.secret))},h.getEventHash=function(e){return s(e)},h.enable=function(){try{return this.connected?Promise.resolve():Promise.resolve(this.relay.connect()).then(function(){})}catch(e){return Promise.reject(e)}},h.close=function(){return this.relay.close()},h.encrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(u.encrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},h.decrypt=function(e,t){try{if(!this.secret)throw new Error("Missing secret");return Promise.resolve(u.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},h.getInfo=function(){try{return Promise.resolve({methods:["getInfo","sendPayment","addinvoice","getBalance"],node:{},supports:["lightning"],version:"NWC"})}catch(e){return Promise.reject(e)}},h.getBalance=function(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,function(e){return void 0!==e.balance},function(e){return e})},h.sendPayment=function(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})},h.keysend=function(e){throw new Error("Method not implemented.")},h.lnurl=function(e){throw new Error("Method not implemented.")},h.makeInvoice=function(e){var t;this.checkConnected();var n="object"==typeof e?e:void 0,r=null!=(t=null==n?void 0:n.amount)?t:"string"==typeof e?parseInt(e):e;if(!r)throw new Error("No amount specified");return this.executeNip47Request("make_invoice","addinvoice",{amount:r,description:null==n?void 0:n.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})},h.request=function(e,t){throw new Error("Method not implemented.")},h.signMessage=function(e){throw new Error("Method not implemented.")},h.verifyMessage=function(e,t){throw new Error("Method not implemented.")},h.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},h.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()})},h.checkConnected=function(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")},h.executeNip47Request=function(e,t,n,r,o){var i=this;return new Promise(function(s,u){try{return Promise.resolve(i.encrypt(i.walletPubkey,JSON.stringify({method:e,params:n}))).then(function(e){var n={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",i.walletPubkey]],content:e,pubkey:i.publicKey};return Promise.resolve(i.signEvent(n)).then(function(e){var n=i.relay.sub([{kinds:[23195],authors:[i.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){n.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);n.on("event",function(e){try{return clearTimeout(c),n.unsub(),Promise.resolve(i.decrypt(i.walletPubkey,e.content)).then(function(n){var c,a,l;try{c=JSON.parse(n)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?r(c.result)?(s(o(c.result)),i.notify(t,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=i.relay.publish(e),l=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3);a.on("failed",function(e){clearTimeout(l),u({error:"Failed to publish request: "+e})}),a.on("ok",function(){clearTimeout(l)})})})}catch(e){return Promise.reject(e)}})},t=e,(l=[{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 c(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,l),Object.defineProperty(t,"prototype",{writable:!1}),e}(),U=S;function N(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 W=/*#__PURE__*/function(){function e(e,t){this.auth=void 0,this.defaultRequestOptions=void 0,this.auth="string"==typeof e?new R(e):e,this.defaultRequestOptions=a({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.getInvoice=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.createInvoice=function(e,t){return _(a({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),_(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return _(a({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 N(e)})}):(n="/payments/keysend",r=N(e)),_(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return _(a({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 _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return _(a({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return _(a({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return _(a({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:S,NWC:U,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 W(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(){var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,r=this.auth.generateAuthURL({code_challenge_method:"S256"});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 W(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)}})})},e}()};export{W as Client,x as auth,w as types,M as webln}; | ||
//# sourceMappingURL=index.module.js.map |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto-js"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","crypto-js","nostr-tools"],t):t((e||self).albyJsSdk={},e.cryptoJs,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:""}).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?b:a,f=e.user_agent,m=e.headers,y=h(e,v);try{var g=function(e){return Promise.resolve(w(P.toString(),i({headers:i({},_?{"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:_?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})},P=new URL(l+n);P.search=d(o);var _="POST"===u&&!!s;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(P.href,u)).then(g):g(void 0))}catch(e){return Promise.reject(e)}},w=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)}},b="https://api.getalby.com",P=["expires_in"],_=["token"];function k(e){var t=e.expires_in;return i({},h(e,P),!!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;var t=e.token,n=h(e,_);this.options=i({client_secret:""},n),this.token=t,this._refreshAccessTokenPromise=null}var t=e.prototype;return 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})})}()}catch(e){return r(e)}return o&&o.then?o.then(void 0,r):o}(0,function(e){n(e)})}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(!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){e||(e={}),console.log(e);var t,n=this.options,r=n.client_id,s=n.callback,u=n.scopes;if(!s)throw new Error("callback required");if(!u)throw new Error("scopes required");if("S256"===e.code_challenge_method){var c=o.default.lib.WordArray.random(64);this.code_verifier=c.toString(),this.code_challenge=o.default.SHA256(this.code_verifier).toString(o.default.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),t="S256"}else"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,t="plain");var a=this.code_challenge,l=new URL(e.authorizeUrl||"https://getalby.com/oauth");return l.search=d(i({},e,{client_id:r,scope:u.join(" "),response_type:"code",redirect_uri:s,code_challenge_method:t,code_challenge:a})),l.toString()},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)}},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},A={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},q=/*#__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,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.connected?Promise.resolve():Promise.resolve(this.relay.connect()).then(function(){})}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{return Promise.resolve({methods:["getInfo","sendPayment","getBalance"],node:{},supports:["lightning"],version:"NWC"})}catch(e){return Promise.reject(e)}},o.getBalance=function(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,function(e){return void 0!==e.balance},function(e){return e})},o.sendPayment=function(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})},o.keysend=function(e){throw new Error("Method not implemented.")},o.lnurl=function(e){throw new Error("Method not implemented.")},o.makeInvoice=function(e){throw new Error("Method not implemented.")},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(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")},o.executeNip47Request=function(e,t,n,r,o){var i=this;return new Promise(function(s,u){try{return Promise.resolve(i.encrypt(i.walletPubkey,JSON.stringify({method:e,params:n}))).then(function(e){var n={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",i.walletPubkey]],content:e,pubkey:i.publicKey};return Promise.resolve(i.signEvent(n)).then(function(e){var n=i.relay.sub([{kinds:[23195],authors:[i.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){n.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);n.on("event",function(e){try{return clearTimeout(c),n.unsub(),Promise.resolve(i.decrypt(i.walletPubkey,e.content)).then(function(n){var c,a,l;try{c=JSON.parse(n)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?r(c.result)?(s(o(c.result)),i.notify(t,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=i.relay.publish(e),l=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3);a.on("failed",function(e){clearTimeout(l),u({error:"Failed to publish request: "+e})}),a.on("ok",function(){clearTimeout(l)})})})}catch(e){return 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}(),x=q;function j(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 R=/*#__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.getInvoice=function(e,t){return y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+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 j(e)})}):(n="/payments/keysend",r=j(e)),y(i({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=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 S(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 U(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var N={__proto__:null,NostrWebLNProvider:q,NWC:x,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 R(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=S(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(S(function(){return U(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(S(function(){return U(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(S(function(){return U(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(){var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,r=this.auth.generateAuthURL({code_challenge_method:"S256"});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=U(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new R(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)}})})},e}()};e.Client=R,e.auth=T,e.types=m,e.webln=N}); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("crypto-js"),require("events"),require("nostr-tools")):"function"==typeof define&&define.amd?define(["exports","crypto-js","events","nostr-tools"],t):t((e||self).albyJsSdk={},e.cryptoJs,e.events,e.nostrTools)}(this,function(e,t,n,r){function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var i=/*#__PURE__*/o(t),s=/*#__PURE__*/o(n);function u(){return u=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},u.apply(this,arguments)}function c(e){return c=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},c(e)}function a(e,t){return a=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},a(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 h(e,t,n){return h=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&&a(o,n.prototype),o},h.apply(null,arguments)}function d(e){var t="function"==typeof Map?new Map:void 0;return d=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 h(e,arguments,c(this).constructor)}return n.prototype=Object.create(e.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),a(n,e)},d(e)}function f(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 p(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 m(e,t){return"Basic "+btoa(e+":"+t)}var v=/*#__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,a(t,n),r}(/*#__PURE__*/d(Error)),y={__proto__:null,OAuthClient:function(){},AuthClient:function(){},AlbyResponseError:v},g=["auth","endpoint","params","request_body","method","max_retries","base_url","user_agent","headers"],w=function(e){return Promise.resolve(b(e)).then(function(e){return e.json()})},b=function(e){var t=e.auth,n=e.endpoint,r=e.params,o=void 0===r?{}:r,i=e.request_body,s=e.method,c=e.max_retries,a=e.base_url,l=void 0===a?P:a,h=e.user_agent,d=e.headers,m=f(e,g);try{var y=function(e){return Promise.resolve(_(w.toString(),u({headers:u({},b?{"Content-Type":"application/json; charset=utf-8"}:void 0,e,d,{"User-Agent":null!=h?h:"@getalby/sdk","X-User-Agent":null!=h?h:"@getalby/sdk"}),method:s,body:b?JSON.stringify(i):void 0},m),c)).then(function(e){var t=function(){if(!e.ok)return Promise.resolve(e.json()).then(function(t){throw new v(e.status,e.statusText,e.headers,t)})}();return t&&t.then?t.then(function(t){return e}):e})},w=new URL(l+n);w.search=p(o);var b="POST"===s&&!!i;return Promise.resolve(t?Promise.resolve(t.getAuthHeader(w.href,s)).then(y):y(void 0))}catch(e){return Promise.reject(e)}},_=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)}},P="https://api.getalby.com",k=["expires_in"],E=["token"];function O(e){var t=e.expires_in;return u({},f(e,k),!!t&&{expires_at:Date.now()+1e3*t})}var T=/*#__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 s.default;var t=e.token,n=f(e,E);this.options=u({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 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,c=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(u({},c,{endpoint:"/oauth/token",params:{client_id:i,grant_type:"refresh_token",refresh_token:r},user_agent:a,method:"POST",headers:u({},null==c?void 0:c.headers,{"Content-type":"application/x-www-form-urlencoded"},{Authorization:m(i,s)})}))).then(function(n){var r=O(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.log(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)}},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,i=n.callback,s=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(!i)throw new Error("callback is required");return Promise.resolve(w(u({},s,{endpoint:"/oauth/token",params:{code:e,grant_type:"authorization_code",code_verifier:a,client_id:r,redirect_uri:i},user_agent:c,method:"POST",headers:u({},null==s?void 0:s.headers,{"Content-Type":"application/x-www-form-urlencoded"},{Authorization:m(r,o)})}))).then(function(e){var n=O(e);return t.token=n,{token:n}})}catch(e){return Promise.reject(e)}},t.generateAuthURL=function(e){e||(e={}),console.log(e);var t,n=this.options,r=n.client_id,o=n.callback,s=n.scopes;if(!o)throw new Error("callback required");if(!s)throw new Error("scopes required");if("S256"===e.code_challenge_method){var c=i.default.lib.WordArray.random(64);this.code_verifier=c.toString(),this.code_challenge=i.default.SHA256(this.code_verifier).toString(i.default.enc.Base64).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=+$/,""),t="S256"}else"plain"===e.code_challenge_method&&e.code_challenge&&(this.code_challenge=e.code_challenge,this.code_verifier=e.code_challenge,t="plain");var a=this.code_challenge,l=new URL(e.authorizeUrl||"https://getalby.com/oauth");return l.search=p(u({},e,{client_id:r,scope:s.join(" "),response_type:"code",redirect_uri:o,code_challenge_method:t,code_challenge:a})),l.toString()},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)}},e}(),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}(),A={__proto__:null,OAuth2User:T,OAuth2Bearer:q},x={alby:{authorizationUrl:"https://nwc.getalby.com/apps/new",relayUrl:"wss://relay.getalby.com/v1",walletPubkey:"69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9"}},R=/*#__PURE__*/function(){function e(t){var n;this.relay=void 0,this.relayUrl=void 0,this.secret=void 0,this.walletPubkey=void 0,this.options=void 0,this.subscribers=void 0,t&&t.nostrWalletConnectUrl&&(t=u({},e.parseWalletConnectUrl(t.nostrWalletConnectUrl),t));var o=x[(null==(n=t)?void 0:n.providerName)||"alby"];this.options=u({},o,t||{}),this.relayUrl=this.options.relayUrl,this.relay=r.relayInit(this.relayUrl),this.options.secret&&(this.secret=this.options.secret.toLowerCase().startsWith("nsec")?r.nip19.decode(this.options.secret).data:this.options.secret),this.walletPubkey=this.options.walletPubkey.toLowerCase().startsWith("npub")?r.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=r.generatePrivateKey(),new e(t)};var t,n,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(r.finishEvent(e,this.secret))},o.getEventHash=function(e){return r.getEventHash(e)},o.enable=function(){try{return this.connected?Promise.resolve():Promise.resolve(this.relay.connect()).then(function(){})}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(r.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(r.nip04.decrypt(this.secret,e,t))}catch(e){return Promise.reject(e)}},o.getInfo=function(){try{return Promise.resolve({methods:["getInfo","sendPayment","addinvoice","getBalance"],node:{},supports:["lightning"],version:"NWC"})}catch(e){return Promise.reject(e)}},o.getBalance=function(){return this.checkConnected(),this.executeNip47Request("get_balance","getBalance",void 0,function(e){return void 0!==e.balance},function(e){return e})},o.sendPayment=function(e){return this.checkConnected(),this.executeNip47Request("pay_invoice","sendPayment",{invoice:e},function(e){return!!e.preimage},function(e){return{preimage:e.preimage}})},o.keysend=function(e){throw new Error("Method not implemented.")},o.lnurl=function(e){throw new Error("Method not implemented.")},o.makeInvoice=function(e){var t;this.checkConnected();var n="object"==typeof e?e:void 0,r=null!=(t=null==n?void 0:n.amount)?t:"string"==typeof e?parseInt(e):e;if(!r)throw new Error("No amount specified");return this.executeNip47Request("make_invoice","addinvoice",{amount:r,description:null==n?void 0:n.defaultMemo},function(e){return!!e.invoice},function(e){return{paymentRequest:e.invoice}})},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(){if(!this.connected)throw new Error("please call enable() and await the promise before calling this function")},o.executeNip47Request=function(e,t,n,r,o){var i=this;return new Promise(function(s,u){try{return Promise.resolve(i.encrypt(i.walletPubkey,JSON.stringify({method:e,params:n}))).then(function(e){var n={kind:23194,created_at:Math.floor(Date.now()/1e3),tags:[["p",i.walletPubkey]],content:e,pubkey:i.publicKey};return Promise.resolve(i.signEvent(n)).then(function(e){var n=i.relay.sub([{kinds:[23195],authors:[i.walletPubkey],"#e":[e.id]}]),c=setTimeout(function(){n.unsub(),u({error:"reply timeout: event "+e.id,code:"INTERNAL"})},6e4);n.on("event",function(e){try{return clearTimeout(c),n.unsub(),Promise.resolve(i.decrypt(i.walletPubkey,e.content)).then(function(n){var c,a,l;try{c=JSON.parse(n)}catch(e){return void u({error:"invalid response",code:"INTERNAL"})}23195==e.kind&&c.result?r(c.result)?(s(o(c.result)),i.notify(t,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=i.relay.publish(e),l=setTimeout(function(){u({error:"Publish timeout: event "+e.id})},5e3);a.on("failed",function(e){clearTimeout(l),u({error:"Failed to publish request: "+e})}),a.on("ok",function(){clearTimeout(l)})})})}catch(e){return Promise.reject(e)}})},t=e,(n=[{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 r.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,n),Object.defineProperty(t,"prototype",{writable:!1}),e}(),j=R;function S(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 U=/*#__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=u({},t,{user_agent:null==t?void 0:t.user_agent})}var t=e.prototype;return t.accountBalance=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/balance",params:e,method:"GET"}))},t.accountSummary=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/summary",params:e,method:"GET"}))},t.accountInformation=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/me",params:e,method:"GET"}))},t.accountValue4Value=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/user/value4value",params:e,method:"GET"}))},t.incomingInvoices=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/incoming",params:e,method:"GET"}))},t.outgoingInvoices=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/outgoing",params:e,method:"GET"}))},t.getInvoice=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/invoices/"+e,method:"GET"}))},t.createInvoice=function(e,t){return w(u({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(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendPayment=function(e,t){return w(u({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 S(e)})}):(n="/payments/keysend",r=S(e)),w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:n,request_body:r,method:"POST"}))},t.sendToAlbyAccount=function(e,t){return w(u({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(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints",request_body:e,method:"POST"}))},t.deleteWebhookEndpoint=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/webhook_endpoints/"+e,method:"DELETE"}))},t.getSwapInfo=function(e){return w(u({auth:this.auth},this.defaultRequestOptions,e,{endpoint:"/swaps/info",method:"GET"}))},t.createSwap=function(e,t){return w(u({auth:this.auth},this.defaultRequestOptions,t,{endpoint:"/swaps",method:"POST",request_body:e}))},e}();function N(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 C(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var W={__proto__:null,NostrWebLNProvider:R,NWC:j,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 U(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=N(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(N(function(){return C(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(N(function(){return C(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(N(function(){return C(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(){var e=this,t=window.outerHeight/2+window.screenY-350,n=window.outerWidth/2+window.screenX-300,r=this.auth.generateAuthURL({code_challenge_method:"S256"});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=C(function(){return Promise.resolve(e.auth.requestAccessToken(r)).then(function(){e.client=new U(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)}})})},e}()};e.Client=U,e.auth=A,e.types=y,e.webln=W}); | ||
//# sourceMappingURL=index.umd.js.map |
@@ -13,2 +13,6 @@ import { OAuthClient, AuthHeader, Token, GenerateAuthUrlOptions } from "./types"; | ||
} | ||
export type TokenRefreshedListener = (tokens: Token) => void; | ||
export type TokenRefreshFailedListener = (error: Error) => void; | ||
export type EventName = "tokenRefreshed" | "tokenRefreshFailed"; | ||
export type EventListener = TokenRefreshedListener | TokenRefreshFailedListener; | ||
export declare class OAuth2User implements OAuthClient { | ||
@@ -20,4 +24,9 @@ token?: Token; | ||
private _refreshAccessTokenPromise; | ||
private _tokenEvents; | ||
constructor(options: OAuth2UserOptions); | ||
/** | ||
* Subscribe to the events | ||
*/ | ||
on(eventName: EventName, listener: EventListener): void; | ||
/** | ||
* Refresh the access token | ||
@@ -24,0 +33,0 @@ */ |
@@ -1,3 +0,3 @@ | ||
export declare function buildQueryString(query: Record<string, any>): string; | ||
export declare function buildQueryString(query: Record<string, unknown>): string; | ||
export declare function basicAuthHeader(client_id: string, client_secret: string | undefined): string; | ||
//# sourceMappingURL=utils.d.ts.map |
@@ -1,3 +0,3 @@ | ||
export * from './NostrWeblnProvider'; | ||
export * from './OauthWeblnProvider'; | ||
export * from "./NostrWeblnProvider"; | ||
export * from "./OauthWeblnProvider"; | ||
//# sourceMappingURL=index.d.ts.map |
@@ -1,5 +0,5 @@ | ||
import { Relay, Event, UnsignedEvent } from 'nostr-tools'; | ||
import { Relay, Event, UnsignedEvent } from "nostr-tools"; | ||
import { KeysendArgs, RequestInvoiceArgs, RequestInvoiceResponse, RequestMethod, SendPaymentResponse, SignMessageResponse, WebLNProvider } from "@webbtc/webln-types"; | ||
import { GetInfoResponse } from '@webbtc/webln-types'; | ||
import { GetNWCAuthorizationUrlOptions } from '../types'; | ||
import { GetInfoResponse } from "@webbtc/webln-types"; | ||
import { GetNWCAuthorizationUrlOptions } from "../types"; | ||
interface GetBalanceResponse { | ||
@@ -55,5 +55,5 @@ balance: number; | ||
lnurl(lnurl: string): Promise<{ | ||
status: 'OK'; | ||
status: "OK"; | ||
} | { | ||
status: 'ERROR'; | ||
status: "ERROR"; | ||
reason: string; | ||
@@ -60,0 +60,0 @@ }>; |
@@ -1,2 +0,2 @@ | ||
import { Client } from '../client'; | ||
import { Client } from "../client"; | ||
import { OAuthClient, KeysendRequestParams } from "../types"; | ||
@@ -3,0 +3,0 @@ interface RequestInvoiceArgs { |
// assign alby-sdk exports to global window object (for index.browser.js) | ||
// @ts-ignore | ||
window["albySDK"] = require('./index.cjs'); | ||
window["albySDK"] = require("./index.cjs"); |
{ | ||
"name": "alby-js-sdk", | ||
"version": "2.2.3", | ||
"description": "The SDK to integrate with Nostr Wallet Connect and the Alby API", | ||
"version": "2.3.0", | ||
"description": "(deprecated use: @getalby/sdk )", | ||
"repository": "https://github.com/getAlby/js-sdk.git", | ||
@@ -27,2 +27,8 @@ "bugs": "https://github.com/getAlby/js-sdk/issues", | ||
"prebuild": "yarn run clean", | ||
"lint": "yarn lint:js && yarn tsc:compile && yarn format:fix", | ||
"lint:js": "eslint src --ext .js,.ts --max-warnings 0", | ||
"lint:js:fix": "eslint src --ext .js,.ts --fix", | ||
"tsc:compile": "tsc --noEmit", | ||
"format": "prettier --check '**/*.(md|json)' 'src/**/*.(js|ts)' 'examples/**/*.(js|jsx)'", | ||
"format:fix": "prettier --loglevel silent --write '**/*.(md|json)' 'src/**/*.(js|ts)' 'examples/**/*.(js|jsx)'", | ||
"prepack": "yarn run build", | ||
@@ -33,17 +39,28 @@ "test": "jest", | ||
"build": "microbundle && yarn build:browser", | ||
"dev": "microbundle watch" | ||
"dev": "microbundle watch", | ||
"prepare": "husky install" | ||
}, | ||
"dependencies": { | ||
"crypto-js": "^4.1.1", | ||
"nostr-tools": "1.13.1" | ||
"nostr-tools": "1.13.1", | ||
"events": "^3.3.0" | ||
}, | ||
"devDependencies": { | ||
"@commitlint/cli": "^17.7.1", | ||
"@commitlint/config-conventional": "^17.7.0", | ||
"@types/crypto-js": "^4.1.1", | ||
"@types/jest": "^29.4.0", | ||
"@types/node": "^18.11.0", | ||
"@typescript-eslint/eslint-plugin": "^6.3.0", | ||
"@typescript-eslint/parser": "^6.3.0", | ||
"@webbtc/webln-types": "^1.0.11", | ||
"browserify": "^17.0.0", | ||
"eslint": "^8.46.0", | ||
"eslint-config-prettier": "^9.0.0", | ||
"express": "^4.18.2", | ||
"husky": "^8.0.3", | ||
"jest": "^29.5.0", | ||
"lint-staged": "^13.2.3", | ||
"microbundle": "^0.15.1", | ||
"prettier": "^3.0.1", | ||
"ts-jest": "^29.0.5", | ||
@@ -50,0 +67,0 @@ "ts-node": "^10.9.1", |
246
README.md
@@ -17,7 +17,6 @@ # Alby JS SDK | ||
* [Nostr Wallet Connect](#nostr-wallet-connect-documentation) | ||
* [Alby OAuth API](#oauth-api-documentation) | ||
* [Need help?](#need-help) | ||
- [Nostr Wallet Connect](#nostr-wallet-connect-documentation) | ||
- [Alby OAuth API](#oauth-api-documentation) | ||
- [Need help?](#need-help) | ||
## Nostr Wallet Connect Documentation | ||
@@ -31,12 +30,12 @@ | ||
(note: in the future more WebLN functions will be added to Nostr Wallet Connect) | ||
(Note: in the future more WebLN functions will be added to Nostr Wallet Connect) | ||
### NostrWebLNProvider (aliased as NWC) Options | ||
* `providerName`: name of the provider to load the default options. currently `alby` (default) | ||
* `nostrWalletConnectUrl`: full Nostr Wallet Connect URL as defined by the [spec](https://github.com/getAlby/nips/blob/master/47.md) | ||
* `relayUrl`: URL of the Nostr relay to be used (e.g. wss://nostr-relay.getalby.com) | ||
* `walletPubkey`: pubkey of the Nostr Wallet Connect app | ||
* `secret`: secret key to sign the request event (if not available window.nostr will be used) | ||
* `authorizationUrl`: URL to the NWC interface for the user to and the app connection | ||
- `providerName`: name of the provider to load the default options. currently `alby` (default) | ||
- `nostrWalletConnectUrl`: full Nostr Wallet Connect URL as defined by the [spec](https://github.com/getAlby/nips/blob/master/47.md) | ||
- `relayUrl`: URL of the Nostr relay to be used (e.g. wss://nostr-relay.getalby.com) | ||
- `walletPubkey`: pubkey of the Nostr Wallet Connect app | ||
- `secret`: secret key to sign the request event (if not available window.nostr will be used) | ||
- `authorizationUrl`: URL to the NWC interface for the user to and the app connection | ||
@@ -47,3 +46,5 @@ ### Quick start example | ||
import { webln } from "@getalby/sdk"; | ||
const nwc = new webln.NostrWebLNProvider({ nostrWalletConnectUrl: loadNWCUrl() }); // loadNWCUrl is some function to get the NWC URL from some (encrypted) storage | ||
const nwc = new webln.NostrWebLNProvider({ | ||
nostrWalletConnectUrl: loadNWCUrl(), | ||
}); // loadNWCUrl is some function to get the NWC URL from some (encrypted) storage | ||
// or use the short version | ||
@@ -57,5 +58,6 @@ const nwc = new webln.NWC({ nostrWalletConnectUrl: loadNWCUrl }); | ||
const response = await nwc.sendPayment(invoice); | ||
``` | ||
``` | ||
You can use NWC as a webln compatible object in your web app: | ||
```js | ||
@@ -65,3 +67,5 @@ // you can set the window.webln object to use the universal API to send payments: | ||
// prompt the user to connect to NWC | ||
window.webln = new webln.NostrWebLNProvider({ nostrWalletConnectUrl: loadNWCUrl }) | ||
window.webln = new webln.NostrWebLNProvider({ | ||
nostrWalletConnectUrl: loadNWCUrl, | ||
}); | ||
// now use any webln code | ||
@@ -72,5 +76,7 @@ } | ||
### NostrWebLNProvider Functions | ||
The goal of the Nostr Wallet Connect provider is to be API compatible with [webln](https://www.webln.guide/). Currently not all methods are supported and only `sendPayment` is specified. | ||
#### `static withNewSecret()` | ||
Initialized a new `NostrWebLNProvider` instance but generates a new random secret. The pubkey of that secret then needs to be authorized by the user (this can be initiated by redirecting the user to the `getAuthorizationUrl()` URL or calling `initNWC()` to open an authorization popup. | ||
@@ -86,2 +92,3 @@ | ||
#### sendPayment(invice: string) | ||
Takes a bolt11 invoice and calls the NWC `pay_invoice` function. | ||
@@ -100,2 +107,3 @@ It returns a promise object that is resolved with an object with the preimage or is rejected with an error | ||
#### getNostrWalletConnectUrl() | ||
Returns the `nostr+walletconnect://` URL which includes all the connection information (`walletPubkey`, `relayUrl`, `secret`) | ||
@@ -105,2 +113,3 @@ This can be used to get and persist the string for later use. | ||
#### initNWC({name: string}) | ||
Opens a new window prompt with the `getAuthorizationUrl()` (the user's NWC UI) to ask the user to authorize the app connection. | ||
@@ -129,3 +138,2 @@ The promise resolves when the connection is authorized and the popup sends a `nwc:success` message or rejects when the prompt is closed. | ||
#### For Node.js | ||
@@ -136,3 +144,3 @@ | ||
```js | ||
import 'websocket-polyfill'; | ||
import "websocket-polyfill"; | ||
// or: require('websocket-polyfill'); | ||
@@ -149,8 +157,8 @@ ``` | ||
### Examples | ||
#### Defaults | ||
```js | ||
import { NostrWebLNProvider } from '@getalby/sdk'; | ||
import { NostrWebLNProvider } from "@getalby/sdk"; | ||
@@ -166,2 +174,3 @@ const webln = new NostrWebLNProvider(); // use defaults (connects to Alby's relay, will use window.nostr to sign the request) | ||
#### Use a custom, user provided Nostr Wallet Connect URL | ||
```js | ||
@@ -179,2 +188,3 @@ import { NostrWebLNProvider } from '@getalby/sdk'; | ||
#### Generate a new NWC connect url using a locally-generated secret | ||
```js | ||
@@ -187,3 +197,6 @@ // same options can be provided to .withNewSecret() as creating a new NostrWebLNProvider() | ||
// an optional return_to parameter can be passed in | ||
webln.getConnectUrl({ name: `My app name`, returnTo: document.location.toString() }); | ||
webln.getConnectUrl({ | ||
name: `My app name`, | ||
returnTo: document.location.toString(), | ||
}); | ||
@@ -200,3 +213,2 @@ // or use the `initNWC` helper which opens a popup to initiate the connection flow. | ||
// const nostrWalletConnectUrl nwc.getNostrWalletConnectUrl(true) | ||
``` | ||
@@ -210,21 +222,19 @@ | ||
### Avalilable methods | ||
* accountBalance | ||
* accountSummary | ||
* accountInformation | ||
* accountValue4Value | ||
* incomingInvoices | ||
* outgoingInvoices | ||
* getInvoice | ||
* createInvoice | ||
* keysend | ||
* sendPayment | ||
* sendBoostagram | ||
* sendToAlbyAccount | ||
* createWebhookEndpoint | ||
* deleteWebhookEndpoint | ||
- accountBalance | ||
- accountSummary | ||
- accountInformation | ||
- accountValue4Value | ||
- incomingInvoices | ||
- outgoingInvoices | ||
- getInvoice | ||
- createInvoice | ||
- keysend | ||
- sendPayment | ||
- sendBoostagram | ||
- sendToAlbyAccount | ||
- createWebhookEndpoint | ||
- deleteWebhookEndpoint | ||
### Examples | ||
@@ -239,4 +249,15 @@ | ||
callback: "http://localhost:8080/callback", | ||
scopes: ["invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send"], | ||
token: {access_token: undefined, refresh_token: undefined, expires_at: undefined} // initialize with existing token | ||
scopes: [ | ||
"invoices:read", | ||
"account:read", | ||
"balance:read", | ||
"invoices:create", | ||
"invoices:read", | ||
"payments:send", | ||
], | ||
token: { | ||
access_token: undefined, | ||
refresh_token: undefined, | ||
expires_at: undefined, | ||
}, // initialize with existing token | ||
}); | ||
@@ -249,3 +270,3 @@ | ||
// open auth URL | ||
// `code` is passed as a query parameter when the user is redirected back aufter authorization | ||
// `code` is passed as a query parameter when the user is redirected back after authorization | ||
await authClient.requestAccessToken(code); | ||
@@ -269,4 +290,11 @@ | ||
callback: "http://localhost:8080/callback", | ||
scopes: ["invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send"], | ||
token: token | ||
scopes: [ | ||
"invoices:read", | ||
"account:read", | ||
"balance:read", | ||
"invoices:create", | ||
"invoices:read", | ||
"payments:send", | ||
], | ||
token: token, | ||
}); | ||
@@ -276,5 +304,42 @@ | ||
// the authClient will automatically refresh the access token if expired using the refresh token | ||
const result = await client.createInvoice({amount: 1000}); | ||
const result = await client.createInvoice({ amount: 1000 }); | ||
``` | ||
#### Handling refresh token | ||
Access tokens do expire. If an access token is about to expire, this library will automatically use a refresh token to retrieve a fresh one. Utilising the _tokenRefreshed_ event is a simple approach to guarantee that you always save the most recent tokens. | ||
If token refresh fails, you can restart the OAuth Authentication flow or log the error by listening for the _tokenRefreshFailed_ event. | ||
(Note: To prevent losing access to the user's token, only initialize one instance of the client per token pair at a time) | ||
```js | ||
const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number} | ||
const authClient = new auth.OAuth2User({ | ||
client_id: process.env.CLIENT_ID, | ||
callback: "http://localhost:8080/callback", | ||
scopes: [ | ||
"invoices:read", | ||
"account:read", | ||
"balance:read", | ||
"invoices:create", | ||
"invoices:read", | ||
"payments:send", | ||
], | ||
token: token, | ||
}); | ||
// listen to the tokenRefreshed event | ||
authClient.on("tokenRefreshed", (tokens) => { | ||
// store the tokens in database | ||
console.log(tokens); | ||
}); | ||
// Listen to the tokenRefreshFailed event | ||
authClient.on("tokenRefreshFailed", (error) => { | ||
// Handle the token refresh failure, for example, log the error or launch OAuth authentication flow | ||
console.error("Token refresh failed:", error.message); | ||
}); | ||
``` | ||
#### Sending payments | ||
@@ -287,4 +352,11 @@ | ||
callback: "http://localhost:8080/callback", | ||
scopes: ["invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send"], | ||
token: token | ||
scopes: [ | ||
"invoices:read", | ||
"account:read", | ||
"balance:read", | ||
"invoices:create", | ||
"invoices:read", | ||
"payments:send", | ||
], | ||
token: token, | ||
}); | ||
@@ -300,3 +372,3 @@ | ||
amount: 10, | ||
memo: memo | ||
memo: memo, | ||
}); | ||
@@ -315,3 +387,3 @@ ``` | ||
scopes: ["payments:send"], | ||
token: token | ||
token: token, | ||
}); | ||
@@ -325,5 +397,6 @@ | ||
recipient: { | ||
address: '030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3', | ||
customKey: '696969', | ||
customValue: 'bNVHj0WZ0aLPPAesnn9M' | ||
address: | ||
"030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3", | ||
customKey: "696969", | ||
customValue: "bNVHj0WZ0aLPPAesnn9M", | ||
}, | ||
@@ -333,17 +406,16 @@ amount: 10, | ||
boostagram: { | ||
"app_name": "Alby SDK Demo", | ||
"value_msat_total": 49960, // TOTAL Number of millisats for the payment (all splits together, before fees. The actual number someone entered in their player, for numerology purposes.) | ||
"value_msat": 2121, // Number of millisats for this split payment | ||
"url": "https://feeds.buzzsprout.com/xxx.rss", | ||
"podcast": "Podcast title", | ||
"action": "boost", | ||
"episode": "The episode title", | ||
"episode_guid": "Buzzsprout-xxx", | ||
"ts": 574, | ||
"name": "Podcaster - the recipient name", | ||
"sender_name": "Satoshi - the sender/listener name" | ||
} | ||
app_name: "Alby SDK Demo", | ||
value_msat_total: 49960, // TOTAL Number of millisats for the payment (all splits together, before fees. The actual number someone entered in their player, for numerology purposes.) | ||
value_msat: 2121, // Number of millisats for this split payment | ||
url: "https://feeds.buzzsprout.com/xxx.rss", | ||
podcast: "Podcast title", | ||
action: "boost", | ||
episode: "The episode title", | ||
episode_guid: "Buzzsprout-xxx", | ||
ts: 574, | ||
name: "Podcaster - the recipient name", | ||
sender_name: "Satoshi - the sender/listener name", | ||
}, | ||
}); | ||
// or manually through the keysend: | ||
@@ -356,5 +428,5 @@ | ||
customRecords: { | ||
"7629169": JSON.stringify(boostagram), | ||
"696969": "user", | ||
} | ||
7629169: JSON.stringify(boostagram), | ||
696969: "user", | ||
}, | ||
}); | ||
@@ -364,9 +436,15 @@ ``` | ||
#### Send multiple boostagrams | ||
You often want to send a boostagram for multiple splits. You can do this with one API call. Simply pass in an array of boostagrams. See example above. | ||
```js | ||
const response = await client.sendBoostagram([boostagram1, boostagram2, boostagram3]); | ||
const response = await client.sendBoostagram([ | ||
boostagram1, | ||
boostagram2, | ||
boostagram3, | ||
]); | ||
console.log(response.keysends); | ||
``` | ||
`response.keysends` is an array of objects that either has an `error` key if a payment faild or the `keysend` key if everything succeeded. | ||
@@ -376,8 +454,20 @@ | ||
{ | ||
"keysends":[ | ||
"keysends": [ | ||
{ | ||
"keysend": { "amount":10, "fee":0, "destination":"xx","payment_preimage":"xx","payment_hash":"xx"} | ||
"keysend": { | ||
"amount": 10, | ||
"fee": 0, | ||
"destination": "xx", | ||
"payment_preimage": "xx", | ||
"payment_hash": "xx" | ||
} | ||
}, | ||
{ | ||
"keysend":{"amount":10,"fee":0,"destination":"xxx","payment_preimage":"xxx","payment_hash":"xxx"} | ||
"keysend": { | ||
"amount": 10, | ||
"fee": 0, | ||
"destination": "xxx", | ||
"payment_preimage": "xxx", | ||
"payment_hash": "xxx" | ||
} | ||
} | ||
@@ -389,5 +479,7 @@ ] | ||
## fetch() dependency | ||
This library relies on a global `fetch()` function which will only work in browsers and node v18.x or newer. In older versions you can manually install a global fetch option or polyfill if needed. | ||
For example: | ||
```js | ||
@@ -398,6 +490,5 @@ import fetch from "cross-fetch"; // or "@inrupt/universal-fetch" | ||
// or as a polyfill: | ||
import 'cross-fetch/polyfill'; | ||
import "cross-fetch/polyfill"; | ||
``` | ||
## Full usage examples | ||
@@ -407,3 +498,2 @@ | ||
## Need help? | ||
@@ -413,9 +503,8 @@ | ||
* [Twitter: @getAlby](https://twitter.com/getAlby) | ||
* [Telegram group](https://t.me/getAlby) | ||
* support at getalby.com | ||
* [bitcoin.design](https://bitcoin.design/) Slack community [#lightning-browser-extension](https://bitcoindesign.slack.com/archives/C02591ADXM2) | ||
* Read the [Alby developer guide](https://guides.getalby.com/overall-guide/alby-for-developers/getting-started) to better understand how Alby packages and APIs can be used to power your app. | ||
- [Twitter: @getAlby](https://twitter.com/getAlby) | ||
- [Telegram group](https://t.me/getAlby) | ||
- support at getalby.com | ||
- [bitcoin.design](https://bitcoin.design/) Slack community [#lightning-browser-extension](https://bitcoindesign.slack.com/archives/C02591ADXM2) | ||
- Read the [Alby developer guide](https://guides.getalby.com/overall-guide/alby-for-developers/getting-started) to better understand how Alby packages and APIs can be used to power your app. | ||
## Thanks | ||
@@ -425,5 +514,4 @@ | ||
## License | ||
MIT |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
890858
15351
484
3
21
44
+ Addedevents@^3.3.0
+ Addedevents@3.3.0(transitive)