UNPKG

nostr-web-components

Version:

collection of web components that provide quick access to basic nostr things

69 lines (68 loc) 2.05 kB
import { SimplePool } from "@nostr/tools/pool"; import { loadRelayList } from "@nostr/gadgets/lists"; import { setPool } from "@nostr/gadgets/global"; import { loadNostrUser } from "@nostr/gadgets/metadata"; import { decode } from "@nostr/tools/nip19"; import { queryProfile } from "@nostr/tools/nip05"; const pool = window.nostrSharedPool || new SimplePool(); window.nostrSharedPool = pool; setPool(pool); const lrl = window.nostrSharedRelayListLoader || loadRelayList; window.nostrSharedRelayListLoader = lrl; const lnu = window.nostrSharedMetadataLoader || loadNostrUser; window.nostrSharedMetadataLoader = lnu; async function fetchNostrUser(pubkey, relays) { return await lnu({ pubkey, relays }); } async function getOutboxRelaysFor(pubkey) { let rl = await lrl(pubkey); return rl.items.filter((r) => r.write).map((r) => r.url); } async function getInboxRelaysFor(pubkey) { let rl = await lrl(pubkey); return rl.items.filter((r) => r.read).map((r) => r.url); } async function inputToPubkey(input) { try { const { type, data } = decode(input); if (type === "nprofile") { return [data.pubkey, data.relays || []]; } else if (type === "npub") { return [data, []]; } } catch (err) { if (input.match(/[0-9a-f]{64}/)) { return [input, []]; } else if (input.match(".")) { let res = await queryProfile(input); if (!res) return [void 0]; return [res.pubkey, res.relays || []]; } } return [void 0]; } async function getWindowNostr() { const wn = window.nostr; if (!wn) { return new Promise((resolve, reject) => { try { let script = document.createElement("script"); script.onload = () => resolve(window.nostr); script.src = "https://cdn.jsdelivr.net/npm/window.nostr.js/dist/window.nostr.min.js"; document.head.appendChild(script); } catch (err) { reject(err); } }); } return wn; } export { fetchNostrUser, getInboxRelaysFor, getOutboxRelaysFor, getWindowNostr, inputToPubkey, pool };