@getalby/lightning-tools 5.0.2 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.modern.js +1 -1
- package/dist/index.module.js +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/invoice.d.ts +1 -0
- package/dist/lightning-address.d.ts +6 -1
- package/dist/types.d.ts +1 -0
- package/package.json +3 -4
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),r={__proto__:null,MemoryStorage:e,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:e},t=new e,n=function(e,r,n){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};n||(n={});var s=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=n.store||t;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},o={__proto__:null,storage:r,fetchWithL402:n,default:n},i=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},s={__proto__:null,boost:i,default:i};function a(){return a=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},a.apply(this,arguments)}var c,u,l=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,f=function(e){return!!e&&h.test(e)},d=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},p=(c=function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function m(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(m(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function x(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=p(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=x("bech32"),r.bech32m=x("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const P={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(P).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!P.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return P[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!P.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return P[e].decode(r)},r.bytes=r.stringToBytes},c(u={exports:{}},u.exports),u.exports);const{bech32:m,hex:y,utf8:v}=p,w={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},g={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},x=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],P={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},_=BigInt("2100000000000000000"),A=BigInt(1e11),k={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},N={};for(let e=0,r=Object.keys(k);e<r.length;e++){const t=r[e],n=k[r[e]].toString();N[n]=t}const S={1:e=>y.encode(m.fromWordsUnsafe(e)),16:e=>y.encode(m.fromWordsUnsafe(e)),13:e=>v.encode(m.fromWordsUnsafe(e)),19:e=>y.encode(m.fromWordsUnsafe(e)),23:e=>y.encode(m.fromWordsUnsafe(e)),27:e=>y.encode(m.fromWordsUnsafe(e)),6:I,24:I,3:function(e){const r=[];let t,n,o,i,s,a=m.fromWordsUnsafe(e);for(;a.length>0;)t=y.encode(a.slice(0,33)),n=y.encode(a.slice(33,41)),o=parseInt(y.encode(a.slice(41,45)),16),i=parseInt(y.encode(a.slice(45,49)),16),s=parseInt(y.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*x.length;)r.push(!1);const t={};x.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*x.length);return t.extra_bits={start_bit:2*x.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function j(e){return r=>({tagCode:parseInt(e),words:m.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function I(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}var U=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=m.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*A/P[t]:o*A;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>_)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=I(i.slice(0,7));let p,v,x,U;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();p=N[e]||"unknown_tag",v=S[e]||j(e),i=i.slice(1),x=I(i.slice(0,2)),i=i.slice(2),U=i.slice(0,x),i=i.slice(x),t.push({name:p,tag:s[0],letters:s.slice(0,3+x),value:v(U)}),s=s.slice(3+x)}t.push({name:"signature",letters:s.slice(0,104),value:y.encode(m.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let D={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return R("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in k)"route_hint"!==e&&Object.defineProperty(D,e,{get:()=>R(e)});return D;function R(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&function(t,n){try{var o=Promise.resolve(l((i=e,Uint8Array.from(i.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e})}catch(e){return!1}var i;return o&&o.then?o.then(void 0,function(){return!1}):o}())}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})}catch(e){return Promise.reject(e)}},e}(),D=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(W(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function R(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function $(e){if(!R(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function W(e){return l($(e))}function L(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var T={__proto__:null,generateZapEvent:D,validateEvent:R,serializeEvent:$,getEventHash:W,parseNostrResponse:L},O=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,B=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseResponse(r.lnurlp,r.keysend,r.nostr)).then(function(){})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){return Promise.resolve(fetch(e.keysendUrl())).then(function(t){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function r(){function r(){return Promise.resolve(e.parseResponse(i,o,t)).then(function(){})}var t,s=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){t=e})}();return s&&s.then?s.then(r):r()}var o,s=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){o=e})}();return s&&s.then?s.then(r):r()}var i,s=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){i=e})}();return s&&s.then?s.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new U(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(a({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!f(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!d({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,s=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(i({destination:o,customKey:s,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!d({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(D({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseResponse=function(e,r,t){try{var n=function(){if(r&&(o.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(r)),t){var e=L(t,o.username);o.nostrData=e[0],o.nostrPubkey=e[1],o.nostrRelays=e[2]}},o=this,i=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u=0;u<n.length;u++){var l=n[u],h=l[0],f=l[1];switch(h){case"text/plain":a=f;break;case"text/identifier":c=f;break;case"image/png;base64":case"image/jpeg;base64":r="data:"+h+","+f}}var d,p=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:n,metadataHash:o,identifier:c,description:a,image:r,payerData:p,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!f(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(l(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(l("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){o.lnurlpData=e})}();return Promise.resolve(i&&i.then?i.then(n):n())}catch(e){return Promise.reject(e)}},e}(),H=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},K=function(e){var r=e.satoshi;return Promise.resolve(H(e.currency)).then(function(e){return Number(r)*e})},q={__proto__:null,getFiatBtcRate:H,getFiatValue:K,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(H(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(K({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};exports.Invoice=U,exports.LightningAddress=B,exports.boostagrams=s,exports.fetchWithL402=n,exports.fiat=q,exports.l402=o,exports.nostr=T,exports.sendBoostagram=i;
|
|
1
|
+
var e=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),r={__proto__:null,MemoryStorage:e,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:e},t=new e,n=function(e,r,n){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};n||(n={});var s=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=n.store||t;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},o={__proto__:null,storage:r,fetchWithL402:n,default:n},i=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},s={__proto__:null,boost:i,default:i};function a(){return a=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},a.apply(this,arguments)}var c,u,l=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,f=function(e){return!!e&&h.test(e)},d=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},p=(c=function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function m(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(m(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=p(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes},c(u={exports:{}},u.exports),u.exports);const{bech32:m,hex:y,utf8:v}=p,w={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},g={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},P={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},x=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],_={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},k=BigInt("2100000000000000000"),A=BigInt(1e11),N={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},j={};for(let e=0,r=Object.keys(N);e<r.length;e++){const t=r[e],n=N[r[e]].toString();j[n]=t}const D={1:e=>y.encode(m.fromWordsUnsafe(e)),16:e=>y.encode(m.fromWordsUnsafe(e)),13:e=>v.encode(m.fromWordsUnsafe(e)),19:e=>y.encode(m.fromWordsUnsafe(e)),23:e=>y.encode(m.fromWordsUnsafe(e)),27:e=>y.encode(m.fromWordsUnsafe(e)),6:U,24:U,3:function(e){const r=[];let t,n,o,i,s,a=m.fromWordsUnsafe(e);for(;a.length>0;)t=y.encode(a.slice(0,33)),n=y.encode(a.slice(33,41)),o=parseInt(y.encode(a.slice(41,45)),16),i=parseInt(y.encode(a.slice(45,49)),16),s=parseInt(y.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*x.length;)r.push(!1);const t={};x.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*x.length);return t.extra_bits={start_bit:2*x.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function S(e){return r=>({tagCode:parseInt(e),words:m.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function U(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}function I(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}var R=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=m.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E;break;case P.bech32:l=P}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*A/_[t]:o*A;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>k)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=U(i.slice(0,7));let p,v,x,I;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();p=j[e]||"unknown_tag",v=D[e]||S(e),i=i.slice(1),x=U(i.slice(0,2)),i=i.slice(2),I=i.slice(0,x),i=i.slice(x),t.push({name:p,tag:s[0],letters:s.slice(0,3+x),value:v(I)}),s=s.slice(3+x)}t.push({name:"signature",letters:s.slice(0,104),value:y.encode(m.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let R={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return L("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in N)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>L(e)});return R;function L(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&I(function(){return Promise.resolve(l((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e});var t},function(){return!1}))}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(I(function(){return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})},function(e){return console.error("failed to check LNURL-verify",e),!1}))}catch(e){return Promise.reject(e)}},r.hasExpired=function(){var e=this.expiryDate;return!!e&&e.getTime()<Date.now()},e}(),L=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(T(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function $(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function W(e){if(!$(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function T(e){return l(W(e))}function K(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var O={__proto__:null,generateZapEvent:L,validateEvent:$,serializeEvent:W,getEventHash:T,parseNostrResponse:K},H=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,B=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=H.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r.lnurlp)).then(function(){e.parseKeysendResponse(r.keysend),e.parseNostrResponse(r.nostr)})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(Promise.all([e.fetchLnurlData(),e.fetchKeysendData(),e.fetchNostrData()])).then(function(){}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.fetchLnurlData=function(){try{var e=this;return Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r)).then(function(){})})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchKeysendData=function(){try{var e=this;return Promise.resolve(fetch(e.keysendUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseKeysendResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchNostrData=function(){try{var e=this;return Promise.resolve(fetch(e.nostrUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseNostrResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new R(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(a({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!f(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!d({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,s=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(i({destination:o,customKey:s,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!d({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(L({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseLnUrlPayResponse=function(e){try{var r=this,t=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u="",l=0;l<n.length;l++){var h=n[l],f=h[0],d=h[1];switch(f){case"text/plain":c=d;break;case"text/identifier":u=d;break;case"text/email":r=d;break;case"image/png;base64":case"image/jpeg;base64":a="data:"+f+","+d}}var p,m=e.payerData;try{p=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:p,metadata:n,metadataHash:o,identifier:u,email:r,description:c,image:a,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!f(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(l(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(l("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){r.lnurlpData=e})}();return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.parseKeysendResponse=function(e){e&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(e))},r.parseNostrResponse=function(e){if(e){var r=K(e,this.username);this.nostrData=r[0],this.nostrPubkey=r[1],this.nostrRelays=r[2]}},e}(),q=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},C=function(e){var r=e.satoshi;return Promise.resolve(q(e.currency)).then(function(e){return Number(r)*e})},V={__proto__:null,getFiatBtcRate:q,getFiatValue:C,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(q(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(C({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};exports.Invoice=R,exports.LightningAddress=B,exports.boostagrams=s,exports.fetchWithL402=n,exports.fiat=V,exports.l402=o,exports.nostr=O,exports.sendBoostagram=i;
|
package/dist/index.modern.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
class e{constructor(e){this.storage=void 0,this.storage=e||{}}getItem(e){return this.storage[e]}setItem(e,t){this.storage[e]=t}}var t={__proto__:null,MemoryStorage:e,NoStorage:class{constructor(e){}getItem(e){return null}setItem(e,t){}},default:e};const r=new e,n=async(e,t,n)=>{n||(n={});const o=n.headerKey||"L402",s=n.webln||globalThis.webln;if(!s)throw new Error("WebLN is missing");const a=n.store||r;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});const i=a.getItem(e);if(i){const r=JSON.parse(i);return t.headers.Authorization=`${o} ${r.token}:${r.preimage}`,await fetch(e,t)}t.headers["Accept-Authenticate"]=o;const c=await fetch(e,t),l=c.headers.get("www-authenticate");if(!l)return c;const h=(e=>{const t=e.replace("L402","").replace("LSAT","").trim(),r={},n=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;let o;for(;null!==(o=n.exec(t));)r[o[1]]=o[3]||o[4]||o[5];return r})(l),u=h.token||h.macaroon,d=h.invoice;await s.enable();const f=await s.sendPayment(d);return a.setItem(e,JSON.stringify({token:u,preimage:f.preimage})),t.headers.Authorization=`${o} ${u}:${f.preimage}`,await fetch(e,t)};var o={__proto__:null,storage:t,fetchWithL402:n,default:n};const s=async(e,t)=>{const{boost:r}=e;t||(t={});const n=t.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");const o=e.amount||Math.floor(r.value_msat/1e3),s={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(r)}};return e.customKey&&e.customValue&&(s.customRecords[e.customKey]=e.customValue),await n.enable(),await n.keysend(s)};var a={__proto__:null,boost:s,default:s};function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i.apply(this,arguments)}async function c(e){const t="string"==typeof e?(new TextEncoder).encode(e):e,r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}const l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=e=>!!e&&l.test(e),u=({amount:e,min:t,max:r})=>e>0&&e>=t&&e<=r;var d,f,p=(d=function(e,t){function r(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const t=(e,t)=>r=>e(t(r));return{encode:Array.from(e).reverse().reduce((e,r)=>e?t(e,r.encode):r.encode,void 0),decode:e.reduce((e,r)=>e?t(e,r.decode):r.decode,void 0)}}function o(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map(t=>{if(r(t),t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const r=e.indexOf(t);if(-1===r)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return r})}}}function s(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function a(e,t="="){if(r(e),"string"!=typeof t)throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function i(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function c(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const s=[],a=Array.from(e);for(a.forEach(e=>{if(r(e),e<0||e>=t)throw new Error(`Wrong integer: ${e}`)});;){let e=0,r=!0;for(let s=o;s<a.length;s++){const i=a[s],c=t*e+i;if(!Number.isSafeInteger(c)||t*e/t!==e||c-i!=t*e)throw new Error("convertRadix: carry overflow");if(e=c%n,a[s]=Math.floor(c/n),!Number.isSafeInteger(a[s])||a[s]*n+e!==c)throw new Error("convertRadix: carry overflow");r&&(a[s]?r=!1:o=s)}if(s.push(e),r)break}for(let t=0;t<e.length-1&&0===e[t];t++)s.push(0);return s.reverse()}Object.defineProperty(t,"__esModule",{value:!0}),t.bytes=t.stringToBytes=t.str=t.bytesToString=t.hex=t.utf8=t.bech32m=t.bech32=t.base58check=t.base58xmr=t.base58xrp=t.base58flickr=t.base58=t.base64url=t.base64=t.base32crockford=t.base32hex=t.base32=t.base16=t.utils=t.assertNumber=void 0,t.assertNumber=r;const l=(e,t)=>t?l(t,e%t):e,h=(e,t)=>e+(t-l(e,t));function u(e,t,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(h(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${h(t,n)}`);let s=0,a=0;const i=2**n-1,c=[];for(const o of e){if(r(o),o>=2**t)throw new Error(`convertRadix2: invalid data word=${o} from=${t}`);if(s=s<<t|o,a+t>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${t}`);for(a+=t;a>=n;a-=n)c.push((s>>a-n&i)>>>0);s&=2**a-1}if(s=s<<n-a&i,!o&&a>=t)throw new Error("Excess padding");if(!o&&s)throw new Error(`Non-zero padding: ${s}`);return o&&a>0&&c.push(s>>>0),c}function d(e){return r(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(t,e,256))}}}function f(e,t=!1){if(r(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(h(8,e)>32||h(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return u(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(u(r,e,8,t))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function w(e,t){if(r(e),"function"!=typeof t)throw new Error("checksum fn should be function");return{encode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=t(r).slice(0,e),o=new Uint8Array(r.length+e);return o.set(r),o.set(n,r.length),o},decode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=r.slice(0,-e),o=t(n).slice(0,e),s=r.slice(-e);for(let t=0;t<e;t++)if(o[t]!==s[t])throw new Error("Invalid checksum");return n}}}t.utils={alphabet:o,chain:n,checksum:w,radix:d,radix2:f,join:s,padding:a},t.base16=n(f(4),o("0123456789ABCDEF"),s("")),t.base32=n(f(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),a(5),s("")),t.base32hex=n(f(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),a(5),s("")),t.base32crockford=n(f(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),s(""),i(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),t.base64=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),a(6),s("")),t.base64url=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),a(6),s(""));const m=e=>n(d(58),o(e),s(""));t.base58=m("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.base58flickr=m("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),t.base58xrp=m("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const y=[0,2,3,5,6,7,9,10,11];t.base58xmr={encode(e){let r="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);r+=t.base58.encode(o).padStart(y[o.length],"1")}return r},decode(e){let r=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),s=y.indexOf(o.length),a=t.base58.decode(o);for(let e=0;e<a.length-s;e++)if(0!==a[e])throw new Error("base58xmr: wrong padding");r=r.concat(Array.from(a.slice(a.length-s)))}return Uint8Array.from(r)}},t.base58check=e=>n(w(4,t=>e(e(t))),t.base58);const g=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),b=[996825010,642813549,513874426,1027748829,705979059];function v(e){const t=e>>25;let r=(33554431&e)<<5;for(let e=0;e<b.length;e++)1==(t>>e&1)&&(r^=b[e]);return r}function E(e,t,r=1){const n=e.length;let o=1;for(let t=0;t<n;t++){const r=e.charCodeAt(t);if(r<33||r>126)throw new Error(`Invalid prefix (${e})`);o=v(o)^r>>5}o=v(o);for(let t=0;t<n;t++)o=v(o)^31&e.charCodeAt(t);for(let e of t)o=v(o)^e;for(let e=0;e<6;e++)o=v(o);return o^=r,g.encode(u([o%2**30],30,5,!1))}function x(e){const t="bech32"===e?1:734539939,r=f(5),n=r.decode,o=r.encode,s=p(n);function a(e,r=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==r&&e.length>r)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${r})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const s=e.slice(0,o),a=e.slice(o+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const i=g.decode(a).slice(0,-6),c=E(s,i,t);if(!a.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:s,words:i}}return{encode:function(e,r,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof r);const o=e.length+7+r.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${g.encode(r)}${E(e,r,t)}`},decode:a,decodeToBytes:function(e){const{prefix:t,words:r}=a(e,!1);return{prefix:t,words:r,bytes:n(r)}},decodeUnsafe:p(a),fromWords:n,fromWordsUnsafe:s,toWords:o}}t.bech32=x("bech32"),t.bech32m=x("bech32m"),t.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},t.hex=n(f(4),o("0123456789abcdef"),s(""),i(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const _={utf8:t.utf8,hex:t.hex,base16:t.base16,base32:t.base32,base64:t.base64,base64url:t.base64url,base58:t.base58,base58xmr:t.base58xmr},A=`Invalid encoding type. Available types: ${Object.keys(_).join(", ")}`;t.bytesToString=(e,t)=>{if("string"!=typeof e||!_.hasOwnProperty(e))throw new TypeError(A);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return _[e].encode(t)},t.str=t.bytesToString,t.stringToBytes=(e,t)=>{if(!_.hasOwnProperty(e))throw new TypeError(A);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return _[e].decode(t)},t.bytes=t.stringToBytes},d(f={exports:{}},f.exports),f.exports);const{bech32:w,hex:m,utf8:y}=p,g={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},b={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},v={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},x=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],_={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},A=BigInt("2100000000000000000"),k=BigInt(1e11),$={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},N={};for(let e=0,t=Object.keys($);e<t.length;e++){const r=t[e],n=$[t[e]].toString();N[n]=r}const S={1:e=>m.encode(w.fromWordsUnsafe(e)),16:e=>m.encode(w.fromWordsUnsafe(e)),13:e=>y.encode(w.fromWordsUnsafe(e)),19:e=>m.encode(w.fromWordsUnsafe(e)),23:e=>m.encode(w.fromWordsUnsafe(e)),27:e=>m.encode(w.fromWordsUnsafe(e)),6:U,24:U,3:function(e){const t=[];let r,n,o,s,a,i=w.fromWordsUnsafe(e);for(;i.length>0;)r=m.encode(i.slice(0,33)),n=m.encode(i.slice(33,41)),o=parseInt(m.encode(i.slice(41,45)),16),s=parseInt(m.encode(i.slice(45,49)),16),a=parseInt(m.encode(i.slice(49,51)),16),i=i.slice(51),t.push({pubkey:r,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:s,cltv_expiry_delta:a});return t},5:function(e){const t=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,t)=>e.concat(t),[]);for(;t.length<2*x.length;)t.push(!1);const r={};x.forEach((e,n)=>{let o;o=t[2*n]?"required":t[2*n+1]?"supported":"unsupported",r[e]=o});const n=t.slice(2*x.length);return r.extra_bits={start_bit:2*x.length,bits:n,has_required:n.reduce((e,t,r)=>r%2!=0?e||!1:e||t,!1)},r}};function I(e){return t=>({tagCode:parseInt(e),words:w.encode("unknown",t,Number.MAX_SAFE_INTEGER)})}function U(e){return e.reverse().reduce((e,t,r)=>e+t*Math.pow(32,r),0)}class D{constructor(e){var t,r,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");const o=(e=>{if(!e)return null;try{const t=function(e,t){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const r=[],n=w.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let s=n.words,a=e.slice(o.length+1),i=s.slice(-104);s=s.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");r.push({name:"lightning_network",letters:"ln"});const l=c[1];let h;switch(l){case g.bech32:h=g;break;case b.bech32:h=b;break;case v.bech32:h=v;break;case E.bech32:h=E}if(!h||h.bech32!==l)throw new Error("Unknown coin bech32 prefix");r.push({name:"coin_network",letters:l,value:h});const u=c[2];let d;u?(d=function(e,t){let r,n;if(e.slice(-1).match(/^[munp]$/))r=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),s=r?o*k/_[r]:o*k;if("p"===r&&o%BigInt(10)!==BigInt(0)||s>A)throw new Error("Amount is outside of valid range");return s.toString()}(u+c[3]),r.push({name:"amount",letters:c[2]+c[3],value:d})):d=null,r.push({name:"separator",letters:"1"});const f=U(s.slice(0,7));let p,y,x,D;for(s=s.slice(7),r.push({name:"timestamp",letters:a.slice(0,7),value:f}),a=a.slice(7);s.length>0;){const e=s[0].toString();p=N[e]||"unknown_tag",y=S[e]||I(e),s=s.slice(1),x=U(s.slice(0,2)),s=s.slice(2),D=s.slice(0,x),s=s.slice(x),r.push({name:p,tag:a[0],letters:a.slice(0,3+x),value:y(D)}),a=a.slice(3+x)}r.push({name:"signature",letters:a.slice(0,104),value:m.encode(w.fromWordsUnsafe(i))}),a=a.slice(104),r.push({name:"checksum",letters:a});let R={paymentRequest:e,sections:r,get expiry(){let e=r.find(e=>"expiry"===e.name);if(e)return W("timestamp")+e.value},get route_hints(){return r.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in $)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>W(e)});return R;function W(e){let t=r.find(t=>t.name===e);return t?t.value:void 0}}(e);if(!t||!t.sections)return null;const r=t.sections.find(e=>"payment_hash"===e.name);if("payment_hash"!==(null==r?void 0:r.name)||!r.value)return null;const n=r.value,o=t.sections.find(e=>"amount"===e.name);if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;const s=parseInt(o.value)/1e3,a=t.sections.find(e=>"timestamp"===e.name);if("timestamp"!==(null==a?void 0:a.name)||!a.value)return null;const i=a.value;let c;const l=t.sections.find(e=>"expiry"===e.name);"expiry"===(null==l?void 0:l.name)&&(c=l.value);const h=t.sections.find(e=>"description"===e.name);return{paymentHash:n,satoshi:s,timestamp:i,expiry:c,description:"description"===(null==h?void 0:h.name)?null==h?void 0:h.value:void 0}}catch(e){return null}})(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(t=o.description)?t:null,this.verify=null!=(r=e.verify)?r:null,this.preimage=null!=(n=e.preimage)?n:null}async isPaid(){if(this.preimage)return this.validatePreimage(this.preimage);if(this.verify)return await this.verifyPayment();throw new Error("Could not verify payment")}async validatePreimage(e){if(!e||!this.paymentHash)return!1;try{const r=await c((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))));return this.paymentHash===r}catch(e){return!1}var t}async verifyPayment(){if(!this.verify)throw new Error("LNURL verify not available");const e=await fetch(this.verify),t=await e.json();return t.preimage&&(this.preimage=t.preimage),t.settled}}async function R({satoshi:e,comment:t,p:r,e:n,relays:o},s={}){const a=s.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");const i=[["relays",...o],["amount",e.toString()]];r&&i.push(["p",r]),n&&i.push(["e",n]);const c={pubkey:await a.getPublicKey(),created_at:Math.floor(Date.now()/1e3),kind:9734,tags:i,content:null!=t?t:""};return c.id=await L(c),await a.signEvent(c)}function W(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){const r=e.tags[t];if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if("object"==typeof r[e])return!1}return!0}function P(e){if(!W(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function L(e){return c(P(e))}function T(e,t){let r,n;var o,s;return t&&e&&(r=null==(o=e.names)?void 0:o[t],n=r?null==(s=e.relays)?void 0:s[r]:void 0),[e,r,n]}var j={__proto__:null,generateZapEvent:R,validateEvent:W,serializeEvent:P,getEventHash:L,parseNostrResponse:T};const O=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;class B{constructor(e,t){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}parse(){const e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])}getWebLN(){return this.webln||globalThis.webln}async fetch(){return this.options.proxy?this.fetchWithProxy():this.fetchWithoutProxy()}async fetchWithProxy(){const e=await fetch(`${this.options.proxy}/lightning-address-details?${new URLSearchParams({ln:this.address}).toString()}`),t=await e.json();await this.parseResponse(t.lnurlp,t.keysend,t.nostr)}async fetchWithoutProxy(){if(!this.domain||!this.username)return;const e=await fetch(this.lnurlpUrl()),t=await fetch(this.keysendUrl()),r=await fetch(this.nostrUrl());let n,o,s;e.ok&&(n=await e.json()),t.ok&&(o=await t.json()),r.ok&&(s=await r.json()),await this.parseResponse(n,o,s)}lnurlpUrl(){return`https://${this.domain}/.well-known/lnurlp/${this.username}`}keysendUrl(){return`https://${this.domain}/.well-known/keysend/${this.username}`}nostrUrl(){return`https://${this.domain}/.well-known/nostr.json?name=${this.username}`}async generateInvoice(e){let t;if(this.options.proxy){const r=await fetch(`${this.options.proxy}/generate-invoice?${new URLSearchParams(i({ln:this.address},e)).toString()}`);t=(await r.json()).invoice}else{if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.lnurlpData.callback||!h(this.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");const r=new URL(this.lnurlpData.callback);r.search=new URLSearchParams(e).toString();const n=await fetch(r.toString());t=await n.json()}const r=t&&t.pr&&t.pr.toString();if(!r)throw new Error("Invalid pay service invoice");const n={pr:r};return t&&t.verify&&(n.verify=t.verify.toString()),new D(n)}async requestInvoice(e){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");const t=1e3*e.satoshi,{commentAllowed:r,min:n,max:o}=this.lnurlpData;if(!u({amount:t,min:n,max:o}))throw new Error("Invalid amount");if(e.comment&&r&&r>0&&e.comment.length>r)throw new Error(`The comment length must be ${r} characters or fewer`);const s={amount:t.toString()};return e.comment&&(s.comment=e.comment),e.payerdata&&(s.payerdata=JSON.stringify(e.payerdata)),this.generateInvoice(s)}async boost(e,t=0){if(!this.keysendData)throw new Error("No keysendData available. Please call fetch() first.");const{destination:r,customKey:n,customValue:o}=this.keysendData,a=this.getWebLN();if(!a)throw new Error("WebLN not available");return s({destination:r,customKey:n,customValue:o,amount:t,boost:e},{webln:a})}async zapInvoice({satoshi:e,comment:t,relays:r,e:n},o={}){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.nostrPubkey)throw new Error("Nostr Pubkey is missing");const s=this.nostrPubkey,a=1e3*e,{allowsNostr:i,min:c,max:l}=this.lnurlpData;if(!u({amount:a,min:c,max:l}))throw new Error("Invalid amount");if(!i)throw new Error("Your provider does not support zaps");const h=await R({satoshi:a,comment:t,p:s,e:n,relays:r},o),d={amount:a.toString(),nostr:JSON.stringify(h)};return await this.generateInvoice(d)}async zap(e,t={}){const r=this.zapInvoice(e,t),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return await n.enable(),n.sendPayment((await r).paymentRequest)}async parseResponse(e,t,r){e&&(this.lnurlpData=await(async e=>{if("payRequest"!==e.tag)throw new Error("Invalid pay service params");const t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");const r=Math.ceil(Number(e.minSendable||0)),n=Math.floor(Number(e.maxSendable));if(!r||!n||r>n)throw new Error("Invalid pay service params");let o,s;try{o=JSON.parse(e.metadata+""),s=await c(e.metadata+"")}catch(e){o=[],s=await c("[]")}let a="",i="",l="";for(let e=0;e<o.length;e++){const[t,r]=o[e];switch(t){case"text/plain":i=r;break;case"text/identifier":l=r;break;case"image/png;base64":case"image/jpeg;base64":a="data:"+t+","+r}}const u=e.payerData;let d;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:r===n,min:r,max:n,domain:d,metadata:o,metadataHash:s,identifier:l,description:i,image:a,payerData:u,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}})(e)),t&&(this.keysendData=(e=>{if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");let t,r;return e.customData&&e.customData[0]&&(t=e.customData[0].customKey,r=e.customData[0].customValue),{destination:e.pubkey,customKey:t,customValue:r}})(t)),r&&([this.nostrData,this.nostrPubkey,this.nostrRelays]=T(r,this.username))}}const H=async e=>{const t="https://getalby.com/api/rates/"+e.toLowerCase()+".json",r=await fetch(t);return(await r.json()).rate_float/1e8},K=async({satoshi:e,currency:t})=>{const r=await H(t);return Number(e)*r};var q={__proto__:null,getFiatBtcRate:H,getFiatValue:K,getSatoshiValue:async({amount:e,currency:t})=>{const r=await H(t);return Math.floor(Number(e)/r)},getFormattedFiatValue:async({satoshi:e,currency:t,locale:r})=>(r||(r="en"),(await K({satoshi:e,currency:t})).toLocaleString(r,{style:"currency",currency:t}))};export{D as Invoice,B as LightningAddress,a as boostagrams,n as fetchWithL402,q as fiat,o as l402,j as nostr,s as sendBoostagram};
|
|
1
|
+
class e{constructor(e){this.storage=void 0,this.storage=e||{}}getItem(e){return this.storage[e]}setItem(e,t){this.storage[e]=t}}var t={__proto__:null,MemoryStorage:e,NoStorage:class{constructor(e){}getItem(e){return null}setItem(e,t){}},default:e};const r=new e,n=async(e,t,n)=>{n||(n={});const o=n.headerKey||"L402",s=n.webln||globalThis.webln;if(!s)throw new Error("WebLN is missing");const a=n.store||r;t||(t={}),t.cache="no-store",t.mode="cors",t.headers||(t.headers={});const i=a.getItem(e);if(i){const r=JSON.parse(i);return t.headers.Authorization=`${o} ${r.token}:${r.preimage}`,await fetch(e,t)}t.headers["Accept-Authenticate"]=o;const c=await fetch(e,t),l=c.headers.get("www-authenticate");if(!l)return c;const h=(e=>{const t=e.replace("L402","").replace("LSAT","").trim(),r={},n=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;let o;for(;null!==(o=n.exec(t));)r[o[1]]=o[3]||o[4]||o[5];return r})(l),u=h.token||h.macaroon,d=h.invoice;await s.enable();const f=await s.sendPayment(d);return a.setItem(e,JSON.stringify({token:u,preimage:f.preimage})),t.headers.Authorization=`${o} ${u}:${f.preimage}`,await fetch(e,t)};var o={__proto__:null,storage:t,fetchWithL402:n,default:n};const s=async(e,t)=>{const{boost:r}=e;t||(t={});const n=t.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");const o=e.amount||Math.floor(r.value_msat/1e3),s={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(r)}};return e.customKey&&e.customValue&&(s.customRecords[e.customKey]=e.customValue),await n.enable(),await n.keysend(s)};var a={__proto__:null,boost:s,default:s};function i(){return i=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i.apply(this,arguments)}async function c(e){const t="string"==typeof e?(new TextEncoder).encode(e):e,r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,"0")).join("")}const l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=e=>!!e&&l.test(e),u=({amount:e,min:t,max:r})=>e>0&&e>=t&&e<=r;var d,f,p=(d=function(e,t){function r(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const t=(e,t)=>r=>e(t(r));return{encode:Array.from(e).reverse().reduce((e,r)=>e?t(e,r.encode):r.encode,void 0),decode:e.reduce((e,r)=>e?t(e,r.decode):r.decode,void 0)}}function o(e){return{encode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("alphabet.encode input should be an array of numbers");return t.map(t=>{if(r(t),t<0||t>=e.length)throw new Error(`Digit index outside alphabet: ${t} (alphabet: ${e.length})`);return e[t]})},decode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("alphabet.decode input should be array of strings");return t.map(t=>{if("string"!=typeof t)throw new Error(`alphabet.decode: not string element=${t}`);const r=e.indexOf(t);if(-1===r)throw new Error(`Unknown letter: "${t}". Allowed: ${e}`);return r})}}}function s(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:t=>{if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("join.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return t.join(e)},decode:t=>{if("string"!=typeof t)throw new Error("join.decode input should be string");return t.split(e)}}}function a(e,t="="){if(r(e),"string"!=typeof t)throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;r.length*e%8;)r.push(t);return r},decode(r){if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("padding.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=r.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===t;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function i(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:t=>e(t)}}function c(e,t,n){if(t<2)throw new Error(`convertRadix: wrong from=${t}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const s=[],a=Array.from(e);for(a.forEach(e=>{if(r(e),e<0||e>=t)throw new Error(`Wrong integer: ${e}`)});;){let e=0,r=!0;for(let s=o;s<a.length;s++){const i=a[s],c=t*e+i;if(!Number.isSafeInteger(c)||t*e/t!==e||c-i!=t*e)throw new Error("convertRadix: carry overflow");if(e=c%n,a[s]=Math.floor(c/n),!Number.isSafeInteger(a[s])||a[s]*n+e!==c)throw new Error("convertRadix: carry overflow");r&&(a[s]?r=!1:o=s)}if(s.push(e),r)break}for(let t=0;t<e.length-1&&0===e[t];t++)s.push(0);return s.reverse()}Object.defineProperty(t,"__esModule",{value:!0}),t.bytes=t.stringToBytes=t.str=t.bytesToString=t.hex=t.utf8=t.bech32m=t.bech32=t.base58check=t.base58xmr=t.base58xrp=t.base58flickr=t.base58=t.base64url=t.base64=t.base32crockford=t.base32hex=t.base32=t.base16=t.utils=t.assertNumber=void 0,t.assertNumber=r;const l=(e,t)=>t?l(t,e%t):e,h=(e,t)=>e+(t-l(e,t));function u(e,t,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(t<=0||t>32)throw new Error(`convertRadix2: wrong from=${t}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(h(t,n)>32)throw new Error(`convertRadix2: carry overflow from=${t} to=${n} carryBits=${h(t,n)}`);let s=0,a=0;const i=2**n-1,c=[];for(const o of e){if(r(o),o>=2**t)throw new Error(`convertRadix2: invalid data word=${o} from=${t}`);if(s=s<<t|o,a+t>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${t}`);for(a+=t;a>=n;a-=n)c.push((s>>a-n&i)>>>0);s&=2**a-1}if(s=s<<n-a&i,!o&&a>=t)throw new Error("Excess padding");if(!o&&s)throw new Error(`Non-zero padding: ${s}`);return o&&a>0&&c.push(s>>>0),c}function d(e){return r(e),{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(t),256,e)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(t,e,256))}}}function f(e,t=!1){if(r(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(h(8,e)>32||h(e,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return u(Array.from(r),8,e,!t)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(u(r,e,8,t))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...t){try{return e.apply(null,t)}catch(e){}}}function w(e,t){if(r(e),"function"!=typeof t)throw new Error("checksum fn should be function");return{encode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=t(r).slice(0,e),o=new Uint8Array(r.length+e);return o.set(r),o.set(n,r.length),o},decode(r){if(!(r instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=r.slice(0,-e),o=t(n).slice(0,e),s=r.slice(-e);for(let t=0;t<e;t++)if(o[t]!==s[t])throw new Error("Invalid checksum");return n}}}t.utils={alphabet:o,chain:n,checksum:w,radix:d,radix2:f,join:s,padding:a},t.base16=n(f(4),o("0123456789ABCDEF"),s("")),t.base32=n(f(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),a(5),s("")),t.base32hex=n(f(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),a(5),s("")),t.base32crockford=n(f(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),s(""),i(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),t.base64=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),a(6),s("")),t.base64url=n(f(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),a(6),s(""));const y=e=>n(d(58),o(e),s(""));t.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),t.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),t.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const m=[0,2,3,5,6,7,9,10,11];t.base58xmr={encode(e){let r="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);r+=t.base58.encode(o).padStart(m[o.length],"1")}return r},decode(e){let r=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),s=m.indexOf(o.length),a=t.base58.decode(o);for(let e=0;e<a.length-s;e++)if(0!==a[e])throw new Error("base58xmr: wrong padding");r=r.concat(Array.from(a.slice(a.length-s)))}return Uint8Array.from(r)}},t.base58check=e=>n(w(4,t=>e(e(t))),t.base58);const g=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),s("")),b=[996825010,642813549,513874426,1027748829,705979059];function v(e){const t=e>>25;let r=(33554431&e)<<5;for(let e=0;e<b.length;e++)1==(t>>e&1)&&(r^=b[e]);return r}function E(e,t,r=1){const n=e.length;let o=1;for(let t=0;t<n;t++){const r=e.charCodeAt(t);if(r<33||r>126)throw new Error(`Invalid prefix (${e})`);o=v(o)^r>>5}o=v(o);for(let t=0;t<n;t++)o=v(o)^31&e.charCodeAt(t);for(let e of t)o=v(o)^e;for(let e=0;e<6;e++)o=v(o);return o^=r,g.encode(u([o%2**30],30,5,!1))}function x(e){const t="bech32"===e?1:734539939,r=f(5),n=r.decode,o=r.encode,s=p(n);function a(e,r=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==r&&e.length>r)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${r})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const s=e.slice(0,o),a=e.slice(o+1);if(a.length<6)throw new Error("Data must be at least 6 characters long");const i=g.decode(a).slice(0,-6),c=E(s,i,t);if(!a.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:s,words:i}}return{encode:function(e,r,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof r);const o=e.length+7+r.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${g.encode(r)}${E(e,r,t)}`},decode:a,decodeToBytes:function(e){const{prefix:t,words:r}=a(e,!1);return{prefix:t,words:r,bytes:n(r)}},decodeUnsafe:p(a),fromWords:n,fromWordsUnsafe:s,toWords:o}}t.bech32=x("bech32"),t.bech32m=x("bech32m"),t.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},t.hex=n(f(4),o("0123456789abcdef"),s(""),i(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const _={utf8:t.utf8,hex:t.hex,base16:t.base16,base32:t.base32,base64:t.base64,base64url:t.base64url,base58:t.base58,base58xmr:t.base58xmr},k=`Invalid encoding type. Available types: ${Object.keys(_).join(", ")}`;t.bytesToString=(e,t)=>{if("string"!=typeof e||!_.hasOwnProperty(e))throw new TypeError(k);if(!(t instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return _[e].encode(t)},t.str=t.bytesToString,t.stringToBytes=(e,t)=>{if(!_.hasOwnProperty(e))throw new TypeError(k);if("string"!=typeof t)throw new TypeError("stringToBytes() expects string");return _[e].decode(t)},t.bytes=t.stringToBytes},d(f={exports:{}},f.exports),f.exports);const{bech32:w,hex:y,utf8:m}=p,g={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},b={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},v={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},x={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},_=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],k={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},A=BigInt("2100000000000000000"),$=BigInt(1e11),N={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},D={};for(let e=0,t=Object.keys(N);e<t.length;e++){const r=t[e],n=N[t[e]].toString();D[n]=r}const S={1:e=>y.encode(w.fromWordsUnsafe(e)),16:e=>y.encode(w.fromWordsUnsafe(e)),13:e=>m.encode(w.fromWordsUnsafe(e)),19:e=>y.encode(w.fromWordsUnsafe(e)),23:e=>y.encode(w.fromWordsUnsafe(e)),27:e=>y.encode(w.fromWordsUnsafe(e)),6:I,24:I,3:function(e){const t=[];let r,n,o,s,a,i=w.fromWordsUnsafe(e);for(;i.length>0;)r=y.encode(i.slice(0,33)),n=y.encode(i.slice(33,41)),o=parseInt(y.encode(i.slice(41,45)),16),s=parseInt(y.encode(i.slice(45,49)),16),a=parseInt(y.encode(i.slice(49,51)),16),i=i.slice(51),t.push({pubkey:r,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:s,cltv_expiry_delta:a});return t},5:function(e){const t=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,t)=>e.concat(t),[]);for(;t.length<2*_.length;)t.push(!1);const r={};_.forEach((e,n)=>{let o;o=t[2*n]?"required":t[2*n+1]?"supported":"unsupported",r[e]=o});const n=t.slice(2*_.length);return r.extra_bits={start_bit:2*_.length,bits:n,has_required:n.reduce((e,t,r)=>r%2!=0?e||!1:e||t,!1)},r}};function U(e){return t=>({tagCode:parseInt(e),words:w.encode("unknown",t,Number.MAX_SAFE_INTEGER)})}function I(e){return e.reverse().reduce((e,t,r)=>e+t*Math.pow(32,r),0)}class R{constructor(e){var t,r,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");const o=(e=>{if(!e)return null;try{const t=function(e,t){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const r=[],n=w.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let s=n.words,a=e.slice(o.length+1),i=s.slice(-104);s=s.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");r.push({name:"lightning_network",letters:"ln"});const l=c[1];let h;switch(l){case g.bech32:h=g;break;case b.bech32:h=b;break;case v.bech32:h=v;break;case E.bech32:h=E;break;case x.bech32:h=x}if(!h||h.bech32!==l)throw new Error("Unknown coin bech32 prefix");r.push({name:"coin_network",letters:l,value:h});const u=c[2];let d;u?(d=function(e,t){let r,n;if(e.slice(-1).match(/^[munp]$/))r=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),s=r?o*$/k[r]:o*$;if("p"===r&&o%BigInt(10)!==BigInt(0)||s>A)throw new Error("Amount is outside of valid range");return s.toString()}(u+c[3]),r.push({name:"amount",letters:c[2]+c[3],value:d})):d=null,r.push({name:"separator",letters:"1"});const f=I(s.slice(0,7));let p,m,_,R;for(s=s.slice(7),r.push({name:"timestamp",letters:a.slice(0,7),value:f}),a=a.slice(7);s.length>0;){const e=s[0].toString();p=D[e]||"unknown_tag",m=S[e]||U(e),s=s.slice(1),_=I(s.slice(0,2)),s=s.slice(2),R=s.slice(0,_),s=s.slice(_),r.push({name:p,tag:a[0],letters:a.slice(0,3+_),value:m(R)}),a=a.slice(3+_)}r.push({name:"signature",letters:a.slice(0,104),value:y.encode(w.fromWordsUnsafe(i))}),a=a.slice(104),r.push({name:"checksum",letters:a});let L={paymentRequest:e,sections:r,get expiry(){let e=r.find(e=>"expiry"===e.name);if(e)return P("timestamp")+e.value},get route_hints(){return r.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in N)"route_hint"!==e&&Object.defineProperty(L,e,{get:()=>P(e)});return L;function P(e){let t=r.find(t=>t.name===e);return t?t.value:void 0}}(e);if(!t||!t.sections)return null;const r=t.sections.find(e=>"payment_hash"===e.name);if("payment_hash"!==(null==r?void 0:r.name)||!r.value)return null;const n=r.value,o=t.sections.find(e=>"amount"===e.name);if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;const s=parseInt(o.value)/1e3,a=t.sections.find(e=>"timestamp"===e.name);if("timestamp"!==(null==a?void 0:a.name)||!a.value)return null;const i=a.value;let c;const l=t.sections.find(e=>"expiry"===e.name);"expiry"===(null==l?void 0:l.name)&&(c=l.value);const h=t.sections.find(e=>"description"===e.name);return{paymentHash:n,satoshi:s,timestamp:i,expiry:c,description:"description"===(null==h?void 0:h.name)?null==h?void 0:h.value:void 0}}catch(e){return null}})(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(t=o.description)?t:null,this.verify=null!=(r=e.verify)?r:null,this.preimage=null!=(n=e.preimage)?n:null}async isPaid(){if(this.preimage)return this.validatePreimage(this.preimage);if(this.verify)return await this.verifyPayment();throw new Error("Could not verify payment")}async validatePreimage(e){if(!e||!this.paymentHash)return!1;try{const r=await c((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(e=>parseInt(e,16)))));return this.paymentHash===r}catch(e){return!1}var t}async verifyPayment(){if(!this.verify)throw new Error("LNURL verify not available");try{const e=await fetch(this.verify),t=await e.json();return t.preimage&&(this.preimage=t.preimage),t.settled}catch(e){return console.error("failed to check LNURL-verify",e),!1}}hasExpired(){const{expiryDate:e}=this;return!!e&&e.getTime()<Date.now()}}async function L({satoshi:e,comment:t,p:r,e:n,relays:o},s={}){const a=s.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");const i=[["relays",...o],["amount",e.toString()]];r&&i.push(["p",r]),n&&i.push(["e",n]);const c={pubkey:await a.getPublicKey(),created_at:Math.floor(Date.now()/1e3),kind:9734,tags:i,content:null!=t?t:""};return c.id=await T(c),await a.signEvent(c)}function P(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(let t=0;t<e.tags.length;t++){const r=e.tags[t];if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e++)if("object"==typeof r[e])return!1}return!0}function W(e){if(!P(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function T(e){return c(W(e))}function j(e,t){let r,n;var o,s;return t&&e&&(r=null==(o=e.names)?void 0:o[t],n=r?null==(s=e.relays)?void 0:s[r]:void 0),[e,r,n]}var K={__proto__:null,generateZapEvent:L,validateEvent:P,serializeEvent:W,getEventHash:T,parseNostrResponse:j};const O=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;class H{constructor(e,t){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,t),this.parse(),this.webln=this.options.webln}parse(){const e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])}getWebLN(){return this.webln||globalThis.webln}async fetch(){return this.options.proxy?this.fetchWithProxy():this.fetchWithoutProxy()}async fetchWithProxy(){const e=await fetch(`${this.options.proxy}/lightning-address-details?${new URLSearchParams({ln:this.address}).toString()}`),t=await e.json();await this.parseLnUrlPayResponse(t.lnurlp),this.parseKeysendResponse(t.keysend),this.parseNostrResponse(t.nostr)}async fetchWithoutProxy(){this.domain&&this.username&&await Promise.all([this.fetchLnurlData(),this.fetchKeysendData(),this.fetchNostrData()])}async fetchLnurlData(){const e=await fetch(this.lnurlpUrl());if(e.ok){const t=await e.json();await this.parseLnUrlPayResponse(t)}}async fetchKeysendData(){const e=await fetch(this.keysendUrl());if(e.ok){const t=await e.json();this.parseKeysendResponse(t)}}async fetchNostrData(){const e=await fetch(this.nostrUrl());if(e.ok){const t=await e.json();this.parseNostrResponse(t)}}lnurlpUrl(){return`https://${this.domain}/.well-known/lnurlp/${this.username}`}keysendUrl(){return`https://${this.domain}/.well-known/keysend/${this.username}`}nostrUrl(){return`https://${this.domain}/.well-known/nostr.json?name=${this.username}`}async generateInvoice(e){let t;if(this.options.proxy){const r=await fetch(`${this.options.proxy}/generate-invoice?${new URLSearchParams(i({ln:this.address},e)).toString()}`);t=(await r.json()).invoice}else{if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.lnurlpData.callback||!h(this.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");const r=new URL(this.lnurlpData.callback);r.search=new URLSearchParams(e).toString();const n=await fetch(r.toString());t=await n.json()}const r=t&&t.pr&&t.pr.toString();if(!r)throw new Error("Invalid pay service invoice");const n={pr:r};return t&&t.verify&&(n.verify=t.verify.toString()),new R(n)}async requestInvoice(e){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");const t=1e3*e.satoshi,{commentAllowed:r,min:n,max:o}=this.lnurlpData;if(!u({amount:t,min:n,max:o}))throw new Error("Invalid amount");if(e.comment&&r&&r>0&&e.comment.length>r)throw new Error(`The comment length must be ${r} characters or fewer`);const s={amount:t.toString()};return e.comment&&(s.comment=e.comment),e.payerdata&&(s.payerdata=JSON.stringify(e.payerdata)),this.generateInvoice(s)}async boost(e,t=0){if(!this.keysendData)throw new Error("No keysendData available. Please call fetch() first.");const{destination:r,customKey:n,customValue:o}=this.keysendData,a=this.getWebLN();if(!a)throw new Error("WebLN not available");return s({destination:r,customKey:n,customValue:o,amount:t,boost:e},{webln:a})}async zapInvoice({satoshi:e,comment:t,relays:r,e:n},o={}){if(!this.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!this.nostrPubkey)throw new Error("Nostr Pubkey is missing");const s=this.nostrPubkey,a=1e3*e,{allowsNostr:i,min:c,max:l}=this.lnurlpData;if(!u({amount:a,min:c,max:l}))throw new Error("Invalid amount");if(!i)throw new Error("Your provider does not support zaps");const h=await L({satoshi:a,comment:t,p:s,e:n,relays:r},o),d={amount:a.toString(),nostr:JSON.stringify(h)};return await this.generateInvoice(d)}async zap(e,t={}){const r=this.zapInvoice(e,t),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return await n.enable(),n.sendPayment((await r).paymentRequest)}async parseLnUrlPayResponse(e){e&&(this.lnurlpData=await(async e=>{if("payRequest"!==e.tag)throw new Error("Invalid pay service params");const t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");const r=Math.ceil(Number(e.minSendable||0)),n=Math.floor(Number(e.maxSendable));if(!r||!n||r>n)throw new Error("Invalid pay service params");let o,s;try{o=JSON.parse(e.metadata+""),s=await c(e.metadata+"")}catch(e){o=[],s=await c("[]")}let a="",i="",l="",u="";for(let e=0;e<o.length;e++){const[t,r]=o[e];switch(t){case"text/plain":l=r;break;case"text/identifier":u=r;break;case"text/email":a=r;break;case"image/png;base64":case"image/jpeg;base64":i="data:"+t+","+r}}const d=e.payerData;let f;try{f=new URL(t).hostname}catch(e){}return{callback:t,fixed:r===n,min:r,max:n,domain:f,metadata:o,metadataHash:s,identifier:u,email:a,description:l,image:i,payerData:d,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}})(e))}parseKeysendResponse(e){e&&(this.keysendData=(e=>{if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");let t,r;return e.customData&&e.customData[0]&&(t=e.customData[0].customKey,r=e.customData[0].customValue),{destination:e.pubkey,customKey:t,customValue:r}})(e))}parseNostrResponse(e){e&&([this.nostrData,this.nostrPubkey,this.nostrRelays]=j(e,this.username))}}const B=async e=>{const t="https://getalby.com/api/rates/"+e.toLowerCase()+".json",r=await fetch(t);return(await r.json()).rate_float/1e8},q=async({satoshi:e,currency:t})=>{const r=await B(t);return Number(e)*r};var C={__proto__:null,getFiatBtcRate:B,getFiatValue:q,getSatoshiValue:async({amount:e,currency:t})=>{const r=await B(t);return Math.floor(Number(e)/r)},getFormattedFiatValue:async({satoshi:e,currency:t,locale:r})=>(r||(r="en"),(await q({satoshi:e,currency:t})).toLocaleString(r,{style:"currency",currency:t}))};export{R as Invoice,H as LightningAddress,a as boostagrams,n as fetchWithL402,C as fiat,o as l402,K as nostr,s as sendBoostagram};
|
package/dist/index.module.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),r={__proto__:null,MemoryStorage:e,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:e},t=new e,n=function(e,r,n){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};n||(n={});var s=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=n.store||t;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},o={__proto__:null,storage:r,fetchWithL402:n,default:n},i=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},s={__proto__:null,boost:i,default:i};function a(){return a=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},a.apply(this,arguments)}var c,u,l=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,f=function(e){return!!e&&h.test(e)},d=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},m=(c=function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function m(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function p(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:p,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(p(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=m(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:m(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes},c(u={exports:{}},u.exports),u.exports);const{bech32:p,hex:y,utf8:v}=m,w={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},g={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},P=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],x={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},_=BigInt("2100000000000000000"),A=BigInt(1e11),k={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},N={};for(let e=0,r=Object.keys(k);e<r.length;e++){const t=r[e],n=k[r[e]].toString();N[n]=t}const S={1:e=>y.encode(p.fromWordsUnsafe(e)),16:e=>y.encode(p.fromWordsUnsafe(e)),13:e=>v.encode(p.fromWordsUnsafe(e)),19:e=>y.encode(p.fromWordsUnsafe(e)),23:e=>y.encode(p.fromWordsUnsafe(e)),27:e=>y.encode(p.fromWordsUnsafe(e)),6:I,24:I,3:function(e){const r=[];let t,n,o,i,s,a=p.fromWordsUnsafe(e);for(;a.length>0;)t=y.encode(a.slice(0,33)),n=y.encode(a.slice(33,41)),o=parseInt(y.encode(a.slice(41,45)),16),i=parseInt(y.encode(a.slice(45,49)),16),s=parseInt(y.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*P.length;)r.push(!1);const t={};P.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*P.length);return t.extra_bits={start_bit:2*P.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function j(e){return r=>({tagCode:parseInt(e),words:p.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function I(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}var U=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=p.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*A/x[t]:o*A;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>_)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=I(i.slice(0,7));let m,v,P,U;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();m=N[e]||"unknown_tag",v=S[e]||j(e),i=i.slice(1),P=I(i.slice(0,2)),i=i.slice(2),U=i.slice(0,P),i=i.slice(P),t.push({name:m,tag:s[0],letters:s.slice(0,3+P),value:v(U)}),s=s.slice(3+P)}t.push({name:"signature",letters:s.slice(0,104),value:y.encode(p.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let D={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return R("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in k)"route_hint"!==e&&Object.defineProperty(D,e,{get:()=>R(e)});return D;function R(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&function(t,n){try{var o=Promise.resolve(l((i=e,Uint8Array.from(i.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e})}catch(e){return!1}var i;return o&&o.then?o.then(void 0,function(){return!1}):o}())}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})}catch(e){return Promise.reject(e)}},e}(),D=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(W(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function R(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function $(e){if(!R(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function W(e){return l($(e))}function L(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var T={__proto__:null,generateZapEvent:D,validateEvent:R,serializeEvent:$,getEventHash:W,parseNostrResponse:L},O=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,B=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseResponse(r.lnurlp,r.keysend,r.nostr)).then(function(){})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){return Promise.resolve(fetch(e.keysendUrl())).then(function(t){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function r(){function r(){return Promise.resolve(e.parseResponse(i,o,t)).then(function(){})}var t,s=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){t=e})}();return s&&s.then?s.then(r):r()}var o,s=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){o=e})}();return s&&s.then?s.then(r):r()}var i,s=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){i=e})}();return s&&s.then?s.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new U(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(a({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!f(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!d({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,s=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(i({destination:o,customKey:s,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!d({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(D({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseResponse=function(e,r,t){try{var n=function(){if(r&&(o.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(r)),t){var e=L(t,o.username);o.nostrData=e[0],o.nostrPubkey=e[1],o.nostrRelays=e[2]}},o=this,i=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u=0;u<n.length;u++){var l=n[u],h=l[0],f=l[1];switch(h){case"text/plain":a=f;break;case"text/identifier":c=f;break;case"image/png;base64":case"image/jpeg;base64":r="data:"+h+","+f}}var d,m=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:n,metadataHash:o,identifier:c,description:a,image:r,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!f(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(l(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(l("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){o.lnurlpData=e})}();return Promise.resolve(i&&i.then?i.then(n):n())}catch(e){return Promise.reject(e)}},e}(),H=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},K=function(e){var r=e.satoshi;return Promise.resolve(H(e.currency)).then(function(e){return Number(r)*e})},q={__proto__:null,getFiatBtcRate:H,getFiatValue:K,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(H(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(K({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};export{U as Invoice,B as LightningAddress,s as boostagrams,n as fetchWithL402,q as fiat,o as l402,T as nostr,i as sendBoostagram};
|
|
1
|
+
var e=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),r={__proto__:null,MemoryStorage:e,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:e},t=new e,n=function(e,r,n){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};n||(n={});var s=n.headerKey||"L402",a=n.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=n.store||t;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},o={__proto__:null,storage:r,fetchWithL402:n,default:n},i=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},s={__proto__:null,boost:i,default:i};function a(){return a=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},a.apply(this,arguments)}var c,u,l=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},h=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,f=function(e){return!!e&&h.test(e)},d=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},p=(c=function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function m(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(m(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=p(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes},c(u={exports:{}},u.exports),u.exports);const{bech32:m,hex:y,utf8:v}=p,w={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},g={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},P={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},x=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],_={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},k=BigInt("2100000000000000000"),A=BigInt(1e11),N={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},j={};for(let e=0,r=Object.keys(N);e<r.length;e++){const t=r[e],n=N[r[e]].toString();j[n]=t}const D={1:e=>y.encode(m.fromWordsUnsafe(e)),16:e=>y.encode(m.fromWordsUnsafe(e)),13:e=>v.encode(m.fromWordsUnsafe(e)),19:e=>y.encode(m.fromWordsUnsafe(e)),23:e=>y.encode(m.fromWordsUnsafe(e)),27:e=>y.encode(m.fromWordsUnsafe(e)),6:U,24:U,3:function(e){const r=[];let t,n,o,i,s,a=m.fromWordsUnsafe(e);for(;a.length>0;)t=y.encode(a.slice(0,33)),n=y.encode(a.slice(33,41)),o=parseInt(y.encode(a.slice(41,45)),16),i=parseInt(y.encode(a.slice(45,49)),16),s=parseInt(y.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*x.length;)r.push(!1);const t={};x.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*x.length);return t.extra_bits={start_bit:2*x.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function S(e){return r=>({tagCode:parseInt(e),words:m.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function U(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}function I(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}var R=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=m.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E;break;case P.bech32:l=P}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*A/_[t]:o*A;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>k)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=U(i.slice(0,7));let p,v,x,I;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();p=j[e]||"unknown_tag",v=D[e]||S(e),i=i.slice(1),x=U(i.slice(0,2)),i=i.slice(2),I=i.slice(0,x),i=i.slice(x),t.push({name:p,tag:s[0],letters:s.slice(0,3+x),value:v(I)}),s=s.slice(3+x)}t.push({name:"signature",letters:s.slice(0,104),value:y.encode(m.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let R={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return L("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in N)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>L(e)});return R;function L(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&I(function(){return Promise.resolve(l((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e});var t},function(){return!1}))}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(I(function(){return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})},function(e){return console.error("failed to check LNURL-verify",e),!1}))}catch(e){return Promise.reject(e)}},r.hasExpired=function(){var e=this.expiryDate;return!!e&&e.getTime()<Date.now()},e}(),L=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(T(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function $(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function W(e){if(!$(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function T(e){return l(W(e))}function K(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var O={__proto__:null,generateZapEvent:L,validateEvent:$,serializeEvent:W,getEventHash:T,parseNostrResponse:K},H=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,B=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=H.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r.lnurlp)).then(function(){e.parseKeysendResponse(r.keysend),e.parseNostrResponse(r.nostr)})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(Promise.all([e.fetchLnurlData(),e.fetchKeysendData(),e.fetchNostrData()])).then(function(){}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.fetchLnurlData=function(){try{var e=this;return Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r)).then(function(){})})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchKeysendData=function(){try{var e=this;return Promise.resolve(fetch(e.keysendUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseKeysendResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchNostrData=function(){try{var e=this;return Promise.resolve(fetch(e.nostrUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseNostrResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new R(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(a({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!f(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!d({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,s=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(i({destination:o,customKey:s,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!d({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(L({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseLnUrlPayResponse=function(e){try{var r=this,t=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u="",l=0;l<n.length;l++){var h=n[l],f=h[0],d=h[1];switch(f){case"text/plain":c=d;break;case"text/identifier":u=d;break;case"text/email":r=d;break;case"image/png;base64":case"image/jpeg;base64":a="data:"+f+","+d}}var p,m=e.payerData;try{p=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:p,metadata:n,metadataHash:o,identifier:u,email:r,description:c,image:a,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!f(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(l(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(l("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){r.lnurlpData=e})}();return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.parseKeysendResponse=function(e){e&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(e))},r.parseNostrResponse=function(e){if(e){var r=K(e,this.username);this.nostrData=r[0],this.nostrPubkey=r[1],this.nostrRelays=r[2]}},e}(),q=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},C=function(e){var r=e.satoshi;return Promise.resolve(q(e.currency)).then(function(e){return Number(r)*e})},V={__proto__:null,getFiatBtcRate:q,getFiatValue:C,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(q(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(C({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};export{R as Invoice,B as LightningAddress,s as boostagrams,n as fetchWithL402,V as fiat,o as l402,O as nostr,i as sendBoostagram};
|
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e||self).lightningTools={})}(this,function(e){var r=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),t={__proto__:null,MemoryStorage:r,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:r},n=new r,o=function(e,r,t){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};t||(t={});var s=t.headerKey||"L402",a=t.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=t.store||n;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},i={__proto__:null,storage:t,fetchWithL402:o,default:o},s=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},a={__proto__:null,boost:s,default:s};function c(){return c=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},c.apply(this,arguments)}var u=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=function(e){return!!e&&l.test(e)},f=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},d=function(e){var r={exports:{}};return function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function m(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(m(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function x(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=p(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=x("bech32"),r.bech32m=x("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const P={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(P).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!P.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return P[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!P.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return P[e].decode(r)},r.bytes=r.stringToBytes}(0,r.exports),r.exports}();const{bech32:p,hex:m,utf8:y}=d,v={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},w={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},g={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},E=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],x={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},P=BigInt("2100000000000000000"),_=BigInt(1e11),A={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},k={};for(let e=0,r=Object.keys(A);e<r.length;e++){const t=r[e],n=A[r[e]].toString();k[n]=t}const j={1:e=>m.encode(p.fromWordsUnsafe(e)),16:e=>m.encode(p.fromWordsUnsafe(e)),13:e=>y.encode(p.fromWordsUnsafe(e)),19:e=>m.encode(p.fromWordsUnsafe(e)),23:e=>m.encode(p.fromWordsUnsafe(e)),27:e=>m.encode(p.fromWordsUnsafe(e)),6:S,24:S,3:function(e){const r=[];let t,n,o,i,s,a=p.fromWordsUnsafe(e);for(;a.length>0;)t=m.encode(a.slice(0,33)),n=m.encode(a.slice(33,41)),o=parseInt(m.encode(a.slice(41,45)),16),i=parseInt(m.encode(a.slice(45,49)),16),s=parseInt(m.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*E.length;)r.push(!1);const t={};E.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*E.length);return t.extra_bits={start_bit:2*E.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function N(e){return r=>({tagCode:parseInt(e),words:p.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function S(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}var I=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=p.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case v.bech32:l=v;break;case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*_/x[t]:o*_;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>P)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=S(i.slice(0,7));let y,E,I,U;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();y=k[e]||"unknown_tag",E=j[e]||N(e),i=i.slice(1),I=S(i.slice(0,2)),i=i.slice(2),U=i.slice(0,I),i=i.slice(I),t.push({name:y,tag:s[0],letters:s.slice(0,3+I),value:E(U)}),s=s.slice(3+I)}t.push({name:"signature",letters:s.slice(0,104),value:m.encode(p.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let D={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return R("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in A)"route_hint"!==e&&Object.defineProperty(D,e,{get:()=>R(e)});return D;function R(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&function(t,n){try{var o=Promise.resolve(u((i=e,Uint8Array.from(i.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e})}catch(e){return!1}var i;return o&&o.then?o.then(void 0,function(){return!1}):o}())}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})}catch(e){return Promise.reject(e)}},e}(),U=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve($(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function D(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function R(e){if(!D(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function $(e){return u(R(e))}function W(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var L={__proto__:null,generateZapEvent:U,validateEvent:D,serializeEvent:R,getEventHash:$,parseNostrResponse:W},T=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,O=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=T.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseResponse(r.lnurlp,r.keysend,r.nostr)).then(function(){})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){return Promise.resolve(fetch(e.keysendUrl())).then(function(t){return Promise.resolve(fetch(e.nostrUrl())).then(function(n){function o(){function r(){function r(){return Promise.resolve(e.parseResponse(i,o,t)).then(function(){})}var t,s=function(){if(n.ok)return Promise.resolve(n.json()).then(function(e){t=e})}();return s&&s.then?s.then(r):r()}var o,s=function(){if(t.ok)return Promise.resolve(t.json()).then(function(e){o=e})}();return s&&s.then?s.then(r):r()}var i,s=function(){if(r.ok)return Promise.resolve(r.json()).then(function(e){i=e})}();return s&&s.then?s.then(o):o()})})}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new I(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(c({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!h(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!f({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,i=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(s({destination:o,customKey:i,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!f({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(U({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseResponse=function(e,r,t){try{var n=function(){if(r&&(o.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(r)),t){var e=W(t,o.username);o.nostrData=e[0],o.nostrPubkey=e[1],o.nostrRelays=e[2]}},o=this,i=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u=0;u<n.length;u++){var l=n[u],h=l[0],f=l[1];switch(h){case"text/plain":a=f;break;case"text/identifier":c=f;break;case"image/png;base64":case"image/jpeg;base64":r="data:"+h+","+f}}var d,p=e.payerData;try{d=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:d,metadata:n,metadataHash:o,identifier:c,description:a,image:r,payerData:p,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(u(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(u("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){o.lnurlpData=e})}();return Promise.resolve(i&&i.then?i.then(n):n())}catch(e){return Promise.reject(e)}},e}(),B=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},H=function(e){var r=e.satoshi;return Promise.resolve(B(e.currency)).then(function(e){return Number(r)*e})},K={__proto__:null,getFiatBtcRate:B,getFiatValue:H,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(B(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(H({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};e.Invoice=I,e.LightningAddress=O,e.boostagrams=a,e.fetchWithL402=o,e.fiat=K,e.l402=i,e.nostr=L,e.sendBoostagram=s});
|
|
1
|
+
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e||self).lightningTools={})}(this,function(e){var r=/*#__PURE__*/function(){function e(e){this.storage=void 0,this.storage=e||{}}var r=e.prototype;return r.getItem=function(e){return this.storage[e]},r.setItem=function(e,r){this.storage[e]=r},e}(),t={__proto__:null,MemoryStorage:r,NoStorage:/*#__PURE__*/function(){function e(e){}var r=e.prototype;return r.getItem=function(e){return null},r.setItem=function(e,r){},e}(),default:r},n=new r,o=function(e,r,t){try{var o,i=function(t){return o?t:(r.headers["Accept-Authenticate"]=s,Promise.resolve(fetch(e,r)).then(function(t){var n=t.headers.get("www-authenticate");if(!n)return t;var o=function(e){for(var r,t=e.replace("L402","").replace("LSAT","").trim(),n={},o=/(\w+)=("([^"]*)"|'([^']*)'|([^,]*))/g;null!==(r=o.exec(t));)n[r[1]]=r[3]||r[4]||r[5];return n}(n),i=o.token||o.macaroon,u=o.invoice;return Promise.resolve(a.enable()).then(function(){return Promise.resolve(a.sendPayment(u)).then(function(t){return c.setItem(e,JSON.stringify({token:i,preimage:t.preimage})),r.headers.Authorization=s+" "+i+":"+t.preimage,Promise.resolve(fetch(e,r))})})}))};t||(t={});var s=t.headerKey||"L402",a=t.webln||globalThis.webln;if(!a)throw new Error("WebLN is missing");var c=t.store||n;r||(r={}),r.cache="no-store",r.mode="cors",r.headers||(r.headers={});var u=c.getItem(e),l=function(){if(u){var t=JSON.parse(u);return r.headers.Authorization=s+" "+t.token+":"+t.preimage,Promise.resolve(fetch(e,r)).then(function(e){return o=1,e})}}();return Promise.resolve(l&&l.then?l.then(i):i(l))}catch(e){return Promise.reject(e)}},i={__proto__:null,storage:t,fetchWithL402:o,default:o},s=function(e,r){try{var t=e.boost;r||(r={});var n=r.webln||globalThis.webln;if(!n)throw new Error("WebLN not available");if(!n.keysend)throw new Error("Keysend not available in current WebLN provider");var o=e.amount||Math.floor(t.value_msat/1e3),i={destination:e.destination,amount:o,customRecords:{7629169:JSON.stringify(t)}};return e.customKey&&e.customValue&&(i.customRecords[e.customKey]=e.customValue),Promise.resolve(n.enable()).then(function(){return Promise.resolve(n.keysend(i))})}catch(e){return Promise.reject(e)}},a={__proto__:null,boost:s,default:s};function c(){return c=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},c.apply(this,arguments)}var u=function(e){try{var r="string"==typeof e?(new TextEncoder).encode(e):e;return Promise.resolve(crypto.subtle.digest("SHA-256",r)).then(function(e){return Array.from(new Uint8Array(e)).map(function(e){return e.toString(16).padStart(2,"0")}).join("")})}catch(e){return Promise.reject(e)}},l=/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=+$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=+$,\w]+@)[A-Za-z0-9.-]+)((?:\/[+~%/.\w-_]*)?\??(?:[-+=&;%@.\w_]*)#?(?:[\w]*))?)/,h=function(e){return!!e&&l.test(e)},f=function(e){var r=e.amount;return r>0&&r>=e.min&&r<=e.max},d=function(e){var r={exports:{}};return function(e,r){function t(e){if(!Number.isSafeInteger(e))throw new Error(`Wrong integer: ${e}`)}function n(...e){const r=(e,r)=>t=>e(r(t));return{encode:Array.from(e).reverse().reduce((e,t)=>e?r(e,t.encode):t.encode,void 0),decode:e.reduce((e,t)=>e?r(e,t.decode):t.decode,void 0)}}function o(e){return{encode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("alphabet.encode input should be an array of numbers");return r.map(r=>{if(t(r),r<0||r>=e.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${e.length})`);return e[r]})},decode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("alphabet.decode input should be array of strings");return r.map(r=>{if("string"!=typeof r)throw new Error(`alphabet.decode: not string element=${r}`);const t=e.indexOf(r);if(-1===t)throw new Error(`Unknown letter: "${r}". Allowed: ${e}`);return t})}}}function i(e=""){if("string"!=typeof e)throw new Error("join separator should be string");return{encode:r=>{if(!Array.isArray(r)||r.length&&"string"!=typeof r[0])throw new Error("join.encode input should be array of strings");for(let e of r)if("string"!=typeof e)throw new Error(`join.encode: non-string input=${e}`);return r.join(e)},decode:r=>{if("string"!=typeof r)throw new Error("join.decode input should be string");return r.split(e)}}}function s(e,r="="){if(t(e),"string"!=typeof r)throw new Error("padding chr should be string");return{encode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.encode: non-string input=${e}`);for(;t.length*e%8;)t.push(r);return t},decode(t){if(!Array.isArray(t)||t.length&&"string"!=typeof t[0])throw new Error("padding.encode input should be array of strings");for(let e of t)if("string"!=typeof e)throw new Error(`padding.decode: non-string input=${e}`);let n=t.length;if(n*e%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&t[n-1]===r;n--)if(!((n-1)*e%8))throw new Error("Invalid padding: string has too much padding");return t.slice(0,n)}}}function a(e){if("function"!=typeof e)throw new Error("normalize fn should be function");return{encode:e=>e,decode:r=>e(r)}}function c(e,r,n){if(r<2)throw new Error(`convertRadix: wrong from=${r}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: wrong to=${n}, base cannot be less than 2`);if(!Array.isArray(e))throw new Error("convertRadix: data should be array");if(!e.length)return[];let o=0;const i=[],s=Array.from(e);for(s.forEach(e=>{if(t(e),e<0||e>=r)throw new Error(`Wrong integer: ${e}`)});;){let e=0,t=!0;for(let i=o;i<s.length;i++){const a=s[i],c=r*e+a;if(!Number.isSafeInteger(c)||r*e/r!==e||c-a!=r*e)throw new Error("convertRadix: carry overflow");if(e=c%n,s[i]=Math.floor(c/n),!Number.isSafeInteger(s[i])||s[i]*n+e!==c)throw new Error("convertRadix: carry overflow");t&&(s[i]?t=!1:o=i)}if(i.push(e),t)break}for(let r=0;r<e.length-1&&0===e[r];r++)i.push(0);return i.reverse()}Object.defineProperty(r,"__esModule",{value:!0}),r.bytes=r.stringToBytes=r.str=r.bytesToString=r.hex=r.utf8=r.bech32m=r.bech32=r.base58check=r.base58xmr=r.base58xrp=r.base58flickr=r.base58=r.base64url=r.base64=r.base32crockford=r.base32hex=r.base32=r.base16=r.utils=r.assertNumber=void 0,r.assertNumber=t;const u=(e,r)=>r?u(r,e%r):e,l=(e,r)=>e+(r-u(e,r));function h(e,r,n,o){if(!Array.isArray(e))throw new Error("convertRadix2: data should be array");if(r<=0||r>32)throw new Error(`convertRadix2: wrong from=${r}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(l(r,n)>32)throw new Error(`convertRadix2: carry overflow from=${r} to=${n} carryBits=${l(r,n)}`);let i=0,s=0;const a=2**n-1,c=[];for(const o of e){if(t(o),o>=2**r)throw new Error(`convertRadix2: invalid data word=${o} from=${r}`);if(i=i<<r|o,s+r>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${r}`);for(s+=r;s>=n;s-=n)c.push((i>>s-n&a)>>>0);i&=2**s-1}if(i=i<<n-s&a,!o&&s>=r)throw new Error("Excess padding");if(!o&&i)throw new Error(`Non-zero padding: ${i}`);return o&&s>0&&c.push(i>>>0),c}function f(e){return t(e),{encode:r=>{if(!(r instanceof Uint8Array))throw new Error("radix.encode input should be Uint8Array");return c(Array.from(r),256,e)},decode:r=>{if(!Array.isArray(r)||r.length&&"number"!=typeof r[0])throw new Error("radix.decode input should be array of strings");return Uint8Array.from(c(r,e,256))}}}function d(e,r=!1){if(t(e),e<=0||e>32)throw new Error("radix2: bits should be in (0..32]");if(l(8,e)>32||l(e,8)>32)throw new Error("radix2: carry overflow");return{encode:t=>{if(!(t instanceof Uint8Array))throw new Error("radix2.encode input should be Uint8Array");return h(Array.from(t),8,e,!r)},decode:t=>{if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("radix2.decode input should be array of strings");return Uint8Array.from(h(t,e,8,r))}}}function p(e){if("function"!=typeof e)throw new Error("unsafeWrapper fn should be function");return function(...r){try{return e.apply(null,r)}catch(e){}}}function m(e,r){if(t(e),"function"!=typeof r)throw new Error("checksum fn should be function");return{encode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.encode: input should be Uint8Array");const n=r(t).slice(0,e),o=new Uint8Array(t.length+e);return o.set(t),o.set(n,t.length),o},decode(t){if(!(t instanceof Uint8Array))throw new Error("checksum.decode: input should be Uint8Array");const n=t.slice(0,-e),o=r(n).slice(0,e),i=t.slice(-e);for(let r=0;r<e;r++)if(o[r]!==i[r])throw new Error("Invalid checksum");return n}}}r.utils={alphabet:o,chain:n,checksum:m,radix:f,radix2:d,join:i,padding:s},r.base16=n(d(4),o("0123456789ABCDEF"),i("")),r.base32=n(d(5),o("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),s(5),i("")),r.base32hex=n(d(5),o("0123456789ABCDEFGHIJKLMNOPQRSTUV"),s(5),i("")),r.base32crockford=n(d(5),o("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),i(""),a(e=>e.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1"))),r.base64=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),s(6),i("")),r.base64url=n(d(6),o("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),s(6),i(""));const y=e=>n(f(58),o(e),i(""));r.base58=y("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),r.base58flickr=y("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),r.base58xrp=y("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const v=[0,2,3,5,6,7,9,10,11];r.base58xmr={encode(e){let t="";for(let n=0;n<e.length;n+=8){const o=e.subarray(n,n+8);t+=r.base58.encode(o).padStart(v[o.length],"1")}return t},decode(e){let t=[];for(let n=0;n<e.length;n+=11){const o=e.slice(n,n+11),i=v.indexOf(o.length),s=r.base58.decode(o);for(let e=0;e<s.length-i;e++)if(0!==s[e])throw new Error("base58xmr: wrong padding");t=t.concat(Array.from(s.slice(s.length-i)))}return Uint8Array.from(t)}},r.base58check=e=>n(m(4,r=>e(e(r))),r.base58);const w=n(o("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),i("")),g=[996825010,642813549,513874426,1027748829,705979059];function b(e){const r=e>>25;let t=(33554431&e)<<5;for(let e=0;e<g.length;e++)1==(r>>e&1)&&(t^=g[e]);return t}function E(e,r,t=1){const n=e.length;let o=1;for(let r=0;r<n;r++){const t=e.charCodeAt(r);if(t<33||t>126)throw new Error(`Invalid prefix (${e})`);o=b(o)^t>>5}o=b(o);for(let r=0;r<n;r++)o=b(o)^31&e.charCodeAt(r);for(let e of r)o=b(o)^e;for(let e=0;e<6;e++)o=b(o);return o^=t,w.encode(h([o%2**30],30,5,!1))}function P(e){const r="bech32"===e?1:734539939,t=d(5),n=t.decode,o=t.encode,i=p(n);function s(e,t=90){if("string"!=typeof e)throw new Error("bech32.decode input should be string, not "+typeof e);if(e.length<8||!1!==t&&e.length>t)throw new TypeError(`Wrong string length: ${e.length} (${e}). Expected (8..${t})`);const n=e.toLowerCase();if(e!==n&&e!==e.toUpperCase())throw new Error("String must be lowercase or uppercase");const o=(e=n).lastIndexOf("1");if(0===o||-1===o)throw new Error('Letter "1" must be present between prefix and data only');const i=e.slice(0,o),s=e.slice(o+1);if(s.length<6)throw new Error("Data must be at least 6 characters long");const a=w.decode(s).slice(0,-6),c=E(i,a,r);if(!s.endsWith(c))throw new Error(`Invalid checksum in ${e}: expected "${c}"`);return{prefix:i,words:a}}return{encode:function(e,t,n=90){if("string"!=typeof e)throw new Error("bech32.encode prefix should be string, not "+typeof e);if(!Array.isArray(t)||t.length&&"number"!=typeof t[0])throw new Error("bech32.encode words should be array of numbers, not "+typeof t);const o=e.length+7+t.length;if(!1!==n&&o>n)throw new TypeError(`Length ${o} exceeds limit ${n}`);return`${e=e.toLowerCase()}1${w.encode(t)}${E(e,t,r)}`},decode:s,decodeToBytes:function(e){const{prefix:r,words:t}=s(e,!1);return{prefix:r,words:t,bytes:n(t)}},decodeUnsafe:p(s),fromWords:n,fromWordsUnsafe:i,toWords:o}}r.bech32=P("bech32"),r.bech32m=P("bech32m"),r.utf8={encode:e=>(new TextDecoder).decode(e),decode:e=>(new TextEncoder).encode(e)},r.hex=n(d(4),o("0123456789abcdef"),i(""),a(e=>{if("string"!=typeof e||e.length%2)throw new TypeError(`hex.decode: expected string, got ${typeof e} with length ${e.length}`);return e.toLowerCase()}));const x={utf8:r.utf8,hex:r.hex,base16:r.base16,base32:r.base32,base64:r.base64,base64url:r.base64url,base58:r.base58,base58xmr:r.base58xmr},_=`Invalid encoding type. Available types: ${Object.keys(x).join(", ")}`;r.bytesToString=(e,r)=>{if("string"!=typeof e||!x.hasOwnProperty(e))throw new TypeError(_);if(!(r instanceof Uint8Array))throw new TypeError("bytesToString() expects Uint8Array");return x[e].encode(r)},r.str=r.bytesToString,r.stringToBytes=(e,r)=>{if(!x.hasOwnProperty(e))throw new TypeError(_);if("string"!=typeof r)throw new TypeError("stringToBytes() expects string");return x[e].decode(r)},r.bytes=r.stringToBytes}(0,r.exports),r.exports}();const{bech32:p,hex:m,utf8:y}=d,v={bech32:"bc",pubKeyHash:0,scriptHash:5,validWitnessVersions:[0]},w={bech32:"tb",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},g={bech32:"tbs",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},b={bech32:"bcrt",pubKeyHash:111,scriptHash:196,validWitnessVersions:[0]},E={bech32:"sb",pubKeyHash:63,scriptHash:123,validWitnessVersions:[0]},P=["option_data_loss_protect","initial_routing_sync","option_upfront_shutdown_script","gossip_queries","var_onion_optin","gossip_queries_ex","option_static_remotekey","payment_secret","basic_mpp","option_support_large_channel"],x={m:BigInt(1e3),u:BigInt(1e6),n:BigInt(1e9),p:BigInt(1e12)},_=BigInt("2100000000000000000"),k=BigInt(1e11),A={payment_hash:1,payment_secret:16,description:13,payee:19,description_hash:23,expiry:6,min_final_cltv_expiry:24,fallback_address:9,route_hint:3,feature_bits:5,metadata:27},N={};for(let e=0,r=Object.keys(A);e<r.length;e++){const t=r[e],n=A[r[e]].toString();N[n]=t}const j={1:e=>m.encode(p.fromWordsUnsafe(e)),16:e=>m.encode(p.fromWordsUnsafe(e)),13:e=>y.encode(p.fromWordsUnsafe(e)),19:e=>m.encode(p.fromWordsUnsafe(e)),23:e=>m.encode(p.fromWordsUnsafe(e)),27:e=>m.encode(p.fromWordsUnsafe(e)),6:S,24:S,3:function(e){const r=[];let t,n,o,i,s,a=p.fromWordsUnsafe(e);for(;a.length>0;)t=m.encode(a.slice(0,33)),n=m.encode(a.slice(33,41)),o=parseInt(m.encode(a.slice(41,45)),16),i=parseInt(m.encode(a.slice(45,49)),16),s=parseInt(m.encode(a.slice(49,51)),16),a=a.slice(51),r.push({pubkey:t,short_channel_id:n,fee_base_msat:o,fee_proportional_millionths:i,cltv_expiry_delta:s});return r},5:function(e){const r=e.slice().reverse().map(e=>[!!(1&e),!!(2&e),!!(4&e),!!(8&e),!!(16&e)]).reduce((e,r)=>e.concat(r),[]);for(;r.length<2*P.length;)r.push(!1);const t={};P.forEach((e,n)=>{let o;o=r[2*n]?"required":r[2*n+1]?"supported":"unsupported",t[e]=o});const n=r.slice(2*P.length);return t.extra_bits={start_bit:2*P.length,bits:n,has_required:n.reduce((e,r,t)=>t%2!=0?e||!1:e||r,!1)},t}};function D(e){return r=>({tagCode:parseInt(e),words:p.encode("unknown",r,Number.MAX_SAFE_INTEGER)})}function S(e){return e.reverse().reduce((e,r,t)=>e+r*Math.pow(32,t),0)}function U(e,r){try{var t=e()}catch(e){return r(e)}return t&&t.then?t.then(void 0,r):t}var I=/*#__PURE__*/function(){function e(e){var r,t,n;if(this.paymentRequest=void 0,this.paymentHash=void 0,this.preimage=void 0,this.verify=void 0,this.satoshi=void 0,this.expiry=void 0,this.timestamp=void 0,this.createdDate=void 0,this.expiryDate=void 0,this.description=void 0,this.paymentRequest=e.pr,!this.paymentRequest)throw new Error("Invalid payment request");var o=function(e){if(!e)return null;try{var r=function(e,r){if("string"!=typeof e)throw new Error("Lightning Payment Request must be string");if("ln"!==e.slice(0,2).toLowerCase())throw new Error("Not a proper lightning payment request");const t=[],n=p.decode(e,Number.MAX_SAFE_INTEGER);e=e.toLowerCase();const o=n.prefix;let i=n.words,s=e.slice(o.length+1),a=i.slice(-104);i=i.slice(0,-104);let c=o.match(/^ln(\S+?)(\d*)([a-zA-Z]?)$/);if(c&&!c[2]&&(c=o.match(/^ln(\S+)$/)),!c)throw new Error("Not a proper lightning payment request");t.push({name:"lightning_network",letters:"ln"});const u=c[1];let l;switch(u){case v.bech32:l=v;break;case w.bech32:l=w;break;case g.bech32:l=g;break;case b.bech32:l=b;break;case E.bech32:l=E}if(!l||l.bech32!==u)throw new Error("Unknown coin bech32 prefix");t.push({name:"coin_network",letters:u,value:l});const h=c[2];let f;h?(f=function(e,r){let t,n;if(e.slice(-1).match(/^[munp]$/))t=e.slice(-1),n=e.slice(0,-1);else{if(e.slice(-1).match(/^[^munp0-9]$/))throw new Error("Not a valid multiplier for the amount");n=e}if(!n.match(/^\d+$/))throw new Error("Not a valid human readable amount");const o=BigInt(n),i=t?o*k/x[t]:o*k;if("p"===t&&o%BigInt(10)!==BigInt(0)||i>_)throw new Error("Amount is outside of valid range");return i.toString()}(h+c[3]),t.push({name:"amount",letters:c[2]+c[3],value:f})):f=null,t.push({name:"separator",letters:"1"});const d=S(i.slice(0,7));let y,P,U,I;for(i=i.slice(7),t.push({name:"timestamp",letters:s.slice(0,7),value:d}),s=s.slice(7);i.length>0;){const e=i[0].toString();y=N[e]||"unknown_tag",P=j[e]||D(e),i=i.slice(1),U=S(i.slice(0,2)),i=i.slice(2),I=i.slice(0,U),i=i.slice(U),t.push({name:y,tag:s[0],letters:s.slice(0,3+U),value:P(I)}),s=s.slice(3+U)}t.push({name:"signature",letters:s.slice(0,104),value:m.encode(p.fromWordsUnsafe(a))}),s=s.slice(104),t.push({name:"checksum",letters:s});let R={paymentRequest:e,sections:t,get expiry(){let e=t.find(e=>"expiry"===e.name);if(e)return L("timestamp")+e.value},get route_hints(){return t.filter(e=>"route_hint"===e.name).map(e=>e.value)}};for(let e in A)"route_hint"!==e&&Object.defineProperty(R,e,{get:()=>L(e)});return R;function L(e){let r=t.find(r=>r.name===e);return r?r.value:void 0}}(e);if(!r||!r.sections)return null;var t=r.sections.find(function(e){return"payment_hash"===e.name});if("payment_hash"!==(null==t?void 0:t.name)||!t.value)return null;var n=t.value,o=r.sections.find(function(e){return"amount"===e.name});if("amount"!==(null==o?void 0:o.name)||void 0===o.value)return null;var i=parseInt(o.value)/1e3,s=r.sections.find(function(e){return"timestamp"===e.name});if("timestamp"!==(null==s?void 0:s.name)||!s.value)return null;var a,c=s.value,u=r.sections.find(function(e){return"expiry"===e.name});"expiry"===(null==u?void 0:u.name)&&(a=u.value);var l=r.sections.find(function(e){return"description"===e.name});return{paymentHash:n,satoshi:i,timestamp:c,expiry:a,description:"description"===(null==l?void 0:l.name)?null==l?void 0:l.value:void 0}}catch(e){return null}}(this.paymentRequest);if(!o)throw new Error("Failed to decode payment request");this.paymentHash=o.paymentHash,this.satoshi=o.satoshi,this.timestamp=o.timestamp,this.expiry=o.expiry,this.createdDate=new Date(1e3*this.timestamp),this.expiryDate=this.expiry?new Date(1e3*(this.timestamp+this.expiry)):void 0,this.description=null!=(r=o.description)?r:null,this.verify=null!=(t=e.verify)?t:null,this.preimage=null!=(n=e.preimage)?n:null}var r=e.prototype;return r.isPaid=function(){try{var e=this;if(e.preimage)return Promise.resolve(e.validatePreimage(e.preimage));if(e.verify)return Promise.resolve(e.verifyPayment());throw new Error("Could not verify payment")}catch(e){return Promise.reject(e)}},r.validatePreimage=function(e){try{var r=this;return Promise.resolve(!(!e||!r.paymentHash)&&U(function(){return Promise.resolve(u((t=e,Uint8Array.from(t.match(/.{1,2}/g).map(function(e){return parseInt(e,16)}))))).then(function(e){return r.paymentHash===e});var t},function(){return!1}))}catch(e){return Promise.reject(e)}},r.verifyPayment=function(){try{var e=this;if(!e.verify)throw new Error("LNURL verify not available");return Promise.resolve(U(function(){return Promise.resolve(fetch(e.verify)).then(function(r){return Promise.resolve(r.json()).then(function(r){return r.preimage&&(e.preimage=r.preimage),r.settled})})},function(e){return console.error("failed to check LNURL-verify",e),!1}))}catch(e){return Promise.reject(e)}},r.hasExpired=function(){var e=this.expiryDate;return!!e&&e.getTime()<Date.now()},e}(),R=function(e,r){var t=e.satoshi,n=e.comment,o=e.p,i=e.e,s=e.relays;void 0===r&&(r={});try{var a=r.nostr||globalThis.nostr;if(!a)throw new Error("nostr option or window.nostr is not available");var c=[["relays"].concat(s),["amount",t.toString()]];return o&&c.push(["p",o]),i&&c.push(["e",i]),Promise.resolve(a.getPublicKey()).then(function(e){var r={pubkey:e,created_at:Math.floor(Date.now()/1e3),kind:9734,tags:c,content:null!=n?n:""};return Promise.resolve(W(r)).then(function(e){return r.id=e,Promise.resolve(a.signEvent(r))})})}catch(i){return Promise.reject(i)}};function L(e){if("string"!=typeof e.content)return!1;if("number"!=typeof e.created_at)return!1;if(!Array.isArray(e.tags))return!1;for(var r=0;r<e.tags.length;r++){var t=e.tags[r];if(!Array.isArray(t))return!1;for(var n=0;n<t.length;n++)if("object"==typeof t[n])return!1}return!0}function $(e){if(!L(e))throw new Error("can't serialize event with wrong or missing properties");return JSON.stringify([0,e.pubkey,e.created_at,e.kind,e.tags,e.content])}function W(e){return u($(e))}function T(e,r){var t,n,o,i;return r&&e&&(n=(t=null==(o=e.names)?void 0:o[r])?null==(i=e.relays)?void 0:i[t]:void 0),[e,t,n]}var K={__proto__:null,generateZapEvent:R,validateEvent:L,serializeEvent:$,getEventHash:W,parseNostrResponse:T},O=/^((?:[^<>()[\]\\.,;:\s@"]+(?:\.[^<>()[\]\\.,;:\s@"]+)*)|(?:".+"))@((?:\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(?:(?:[a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,H=/*#__PURE__*/function(){function e(e,r){this.address=void 0,this.options=void 0,this.username=void 0,this.domain=void 0,this.pubkey=void 0,this.lnurlpData=void 0,this.keysendData=void 0,this.nostrData=void 0,this.nostrPubkey=void 0,this.nostrRelays=void 0,this.webln=void 0,this.address=e,this.options={proxy:"https://api.getalby.com/lnurl"},this.options=Object.assign(this.options,r),this.parse(),this.webln=this.options.webln}var r=e.prototype;return r.parse=function(){var e=O.exec(this.address.toLowerCase());e&&(this.username=e[1],this.domain=e[2])},r.getWebLN=function(){return this.webln||globalThis.webln},r.fetch=function(){try{var e=this;return Promise.resolve(e.options.proxy?e.fetchWithProxy():e.fetchWithoutProxy())}catch(e){return Promise.reject(e)}},r.fetchWithProxy=function(){try{var e=this;return Promise.resolve(fetch(e.options.proxy+"/lightning-address-details?"+new URLSearchParams({ln:e.address}).toString())).then(function(r){return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r.lnurlp)).then(function(){e.parseKeysendResponse(r.keysend),e.parseNostrResponse(r.nostr)})})})}catch(e){return Promise.reject(e)}},r.fetchWithoutProxy=function(){try{var e=this;return e.domain&&e.username?Promise.resolve(Promise.all([e.fetchLnurlData(),e.fetchKeysendData(),e.fetchNostrData()])).then(function(){}):Promise.resolve()}catch(e){return Promise.reject(e)}},r.fetchLnurlData=function(){try{var e=this;return Promise.resolve(fetch(e.lnurlpUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){return Promise.resolve(e.parseLnUrlPayResponse(r)).then(function(){})})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchKeysendData=function(){try{var e=this;return Promise.resolve(fetch(e.keysendUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseKeysendResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.fetchNostrData=function(){try{var e=this;return Promise.resolve(fetch(e.nostrUrl())).then(function(r){var t=function(){if(r.ok)return Promise.resolve(r.json()).then(function(r){e.parseNostrResponse(r)})}();if(t&&t.then)return t.then(function(){})})}catch(e){return Promise.reject(e)}},r.lnurlpUrl=function(){return"https://"+this.domain+"/.well-known/lnurlp/"+this.username},r.keysendUrl=function(){return"https://"+this.domain+"/.well-known/keysend/"+this.username},r.nostrUrl=function(){return"https://"+this.domain+"/.well-known/nostr.json?name="+this.username},r.generateInvoice=function(e){try{var r,t=function(e){var t=r&&r.pr&&r.pr.toString();if(!t)throw new Error("Invalid pay service invoice");var n={pr:t};return r&&r.verify&&(n.verify=r.verify.toString()),new I(n)},n=this,o=function(){if(n.options.proxy)return Promise.resolve(fetch(n.options.proxy+"/generate-invoice?"+new URLSearchParams(c({ln:n.address},e)).toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e.invoice})});if(!n.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!n.lnurlpData.callback||!h(n.lnurlpData.callback))throw new Error("Valid callback does not exist in lnurlpData");var t=new URL(n.lnurlpData.callback);return t.search=new URLSearchParams(e).toString(),Promise.resolve(fetch(t.toString())).then(function(e){return Promise.resolve(e.json()).then(function(e){r=e})})}();return Promise.resolve(o&&o.then?o.then(t):t())}catch(e){return Promise.reject(e)}},r.requestInvoice=function(e){try{var r=this;if(!r.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");var t=1e3*e.satoshi,n=r.lnurlpData,o=n.commentAllowed;if(!f({amount:t,min:n.min,max:n.max}))throw new Error("Invalid amount");if(e.comment&&o&&o>0&&e.comment.length>o)throw new Error("The comment length must be "+o+" characters or fewer");var i={amount:t.toString()};return e.comment&&(i.comment=e.comment),e.payerdata&&(i.payerdata=JSON.stringify(e.payerdata)),Promise.resolve(r.generateInvoice(i))}catch(e){return Promise.reject(e)}},r.boost=function(e,r){void 0===r&&(r=0);try{var t=this;if(!t.keysendData)throw new Error("No keysendData available. Please call fetch() first.");var n=t.keysendData,o=n.destination,i=n.customKey,a=n.customValue,c=t.getWebLN();if(!c)throw new Error("WebLN not available");return Promise.resolve(s({destination:o,customKey:i,customValue:a,amount:r,boost:e},{webln:c}))}catch(e){return Promise.reject(e)}},r.zapInvoice=function(e,r){var t=e.satoshi,n=e.comment,o=e.relays,i=e.e;void 0===r&&(r={});try{var s=this;if(!s.lnurlpData)throw new Error("No lnurlpData available. Please call fetch() first.");if(!s.nostrPubkey)throw new Error("Nostr Pubkey is missing");var a=s.nostrPubkey,c=1e3*t,u=s.lnurlpData,l=u.allowsNostr;if(!f({amount:c,min:u.min,max:u.max}))throw new Error("Invalid amount");if(!l)throw new Error("Your provider does not support zaps");return Promise.resolve(R({satoshi:c,comment:n,p:a,e:i,relays:o},r)).then(function(e){var r={amount:c.toString(),nostr:JSON.stringify(e)};return Promise.resolve(s.generateInvoice(r))})}catch(i){return Promise.reject(i)}},r.zap=function(e,r){void 0===r&&(r={});try{var t=this.zapInvoice(e,r),n=this.getWebLN();if(!n)throw new Error("WebLN not available");return Promise.resolve(n.enable()).then(function(){var e=n.sendPayment;return Promise.resolve(t).then(function(r){return e.call(n,r.paymentRequest)})})}catch(e){return Promise.reject(e)}},r.parseLnUrlPayResponse=function(e){try{var r=this,t=function(){if(e)return Promise.resolve(function(e){try{var r=function(){for(var r="",a="",c="",u="",l=0;l<n.length;l++){var h=n[l],f=h[0],d=h[1];switch(f){case"text/plain":c=d;break;case"text/identifier":u=d;break;case"text/email":r=d;break;case"image/png;base64":case"image/jpeg;base64":a="data:"+f+","+d}}var p,m=e.payerData;try{p=new URL(t).hostname}catch(e){}return{callback:t,fixed:i===s,min:i,max:s,domain:p,metadata:n,metadataHash:o,identifier:u,email:r,description:c,image:a,payerData:m,commentAllowed:Number(e.commentAllowed)||0,rawData:e,allowsNostr:e.allowsNostr||!1}};if("payRequest"!==e.tag)throw new Error("Invalid pay service params");var t=(e.callback+"").trim();if(!h(t))throw new Error("Callback must be a valid url");var n,o,i=Math.ceil(Number(e.minSendable||0)),s=Math.floor(Number(e.maxSendable));if(!i||!s||i>s)throw new Error("Invalid pay service params");var a=function(r,t){try{var i=(n=JSON.parse(e.metadata+""),Promise.resolve(u(e.metadata+"")).then(function(e){o=e}))}catch(e){return t()}return i&&i.then?i.then(void 0,t):i}(0,function(){return n=[],Promise.resolve(u("[]")).then(function(e){o=e})});return Promise.resolve(a&&a.then?a.then(r):r())}catch(e){return Promise.reject(e)}}(e)).then(function(e){r.lnurlpData=e})}();return Promise.resolve(t&&t.then?t.then(function(){}):void 0)}catch(e){return Promise.reject(e)}},r.parseKeysendResponse=function(e){e&&(this.keysendData=function(e){if("keysend"!==e.tag)throw new Error("Invalid keysend params");if("OK"!==e.status)throw new Error("Keysend status not OK");if(!e.pubkey)throw new Error("Pubkey does not exist");var r,t;return e.customData&&e.customData[0]&&(r=e.customData[0].customKey,t=e.customData[0].customValue),{destination:e.pubkey,customKey:r,customValue:t}}(e))},r.parseNostrResponse=function(e){if(e){var r=T(e,this.username);this.nostrData=r[0],this.nostrPubkey=r[1],this.nostrRelays=r[2]}},e}(),B=function(e){try{var r="https://getalby.com/api/rates/"+e.toLowerCase()+".json";return Promise.resolve(fetch(r)).then(function(e){return Promise.resolve(e.json()).then(function(e){return e.rate_float/1e8})})}catch(e){return Promise.reject(e)}},q=function(e){var r=e.satoshi;return Promise.resolve(B(e.currency)).then(function(e){return Number(r)*e})},C={__proto__:null,getFiatBtcRate:B,getFiatValue:q,getSatoshiValue:function(e){var r=e.amount;return Promise.resolve(B(e.currency)).then(function(e){return Math.floor(Number(r)/e)})},getFormattedFiatValue:function(e){var r=e.currency,t=e.locale;return t||(t="en"),Promise.resolve(q({satoshi:e.satoshi,currency:r})).then(function(e){return e.toLocaleString(t,{style:"currency",currency:r})})}};e.Invoice=I,e.LightningAddress=H,e.boostagrams=a,e.fetchWithL402=o,e.fiat=C,e.l402=i,e.nostr=K,e.sendBoostagram=s});
|
package/dist/invoice.d.ts
CHANGED
|
@@ -26,6 +26,9 @@ export default class LightningAddress {
|
|
|
26
26
|
fetch(): Promise<void>;
|
|
27
27
|
fetchWithProxy(): Promise<void>;
|
|
28
28
|
fetchWithoutProxy(): Promise<void>;
|
|
29
|
+
fetchLnurlData(): Promise<void>;
|
|
30
|
+
fetchKeysendData(): Promise<void>;
|
|
31
|
+
fetchNostrData(): Promise<void>;
|
|
29
32
|
lnurlpUrl(): string;
|
|
30
33
|
keysendUrl(): string;
|
|
31
34
|
nostrUrl(): string;
|
|
@@ -34,6 +37,8 @@ export default class LightningAddress {
|
|
|
34
37
|
boost(boost: Boost, amount?: number): Promise<SendPaymentResponse>;
|
|
35
38
|
zapInvoice({ satoshi, comment, relays, e }: ZapArgs, options?: ZapOptions): Promise<Invoice>;
|
|
36
39
|
zap(args: ZapArgs, options?: ZapOptions): Promise<SendPaymentResponse>;
|
|
37
|
-
private
|
|
40
|
+
private parseLnUrlPayResponse;
|
|
41
|
+
private parseKeysendResponse;
|
|
42
|
+
private parseNostrResponse;
|
|
38
43
|
}
|
|
39
44
|
export {};
|
package/dist/types.d.ts
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@getalby/lightning-tools",
|
|
3
|
-
"version": "5.0
|
|
3
|
+
"version": "5.1.0",
|
|
4
4
|
"description": "Collection of helpful building blocks and tools to develop Bitcoin Lightning web apps",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "src/index.ts",
|
|
@@ -44,20 +44,19 @@
|
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@commitlint/cli": "^
|
|
47
|
+
"@commitlint/cli": "^19.5.0",
|
|
48
48
|
"@commitlint/config-conventional": "^17.7.0",
|
|
49
49
|
"@types/jest": "^29.4.0",
|
|
50
50
|
"@types/node": "^20.8.2",
|
|
51
51
|
"@typescript-eslint/eslint-plugin": "^6.4.0",
|
|
52
52
|
"@typescript-eslint/parser": "^6.4.0",
|
|
53
53
|
"@webbtc/webln-types": "^2.1.0",
|
|
54
|
-
"browserify": "^17.0.0",
|
|
55
54
|
"eslint": "^8.47.0",
|
|
56
55
|
"eslint-config-prettier": "^9.0.0",
|
|
57
56
|
"husky": "^8.0.3",
|
|
58
57
|
"jest": "^29.5.0",
|
|
59
58
|
"jest-fetch-mock": "^3.0.3",
|
|
60
|
-
"light-bolt11-decoder": "^3.
|
|
59
|
+
"light-bolt11-decoder": "^3.2.0",
|
|
61
60
|
"lint-staged": "^14.0.0",
|
|
62
61
|
"microbundle": "^0.15.1",
|
|
63
62
|
"nostr-tools": "^1.17.0",
|