nostr.js (1494B)
1 2 function insert_event_sorted(evs, new_ev) { 3 for (let i = 0; i < evs.length; i++) { 4 const ev = evs[i] 5 6 if (new_ev.id === ev.id) { 7 return false 8 } 9 10 if (new_ev.created_at > ev.created_at) { 11 evs.splice(i, 0, new_ev) 12 return true 13 } 14 } 15 16 evs.push(new_ev) 17 return true 18 } 19 20 function Relay(relay, opts={}) 21 { 22 if (!(this instanceof Relay)) 23 return new Relay(relay, opts) 24 25 this.relay = relay 26 this.opts = opts 27 28 const me = this 29 return new Promise((resolve, reject) => { 30 const ws = me.ws = new WebSocket(relay); 31 let resolved = false 32 ws.onmessage = (m) => { handle_nostr_message(me, m) } 33 ws.onclose = () => { me.close && me.close() } 34 ws.onerror = () => { me.error && me.error() } 35 ws.onopen = () => { 36 if (resolved) { 37 me.open.bind(me) 38 return 39 } 40 41 resolved = true 42 resolve(me) 43 } 44 }) 45 } 46 47 Relay.prototype.subscribe = function relay_subscribe(sub_id, ...filters) { 48 const tosend = ["REQ", sub_id, ...filters] 49 this.ws.send(JSON.stringify(tosend)) 50 } 51 52 Relay.prototype.unsubscribe = function relay_unsubscribe(sub_id) { 53 const tosend = ["CLOSE", sub_id] 54 this.ws.send(JSON.stringify(tosend)) 55 } 56 57 function handle_nostr_message(relay, msg) 58 { 59 const data = JSON.parse(msg.data) 60 if (data.length >= 2) { 61 switch (data[0]) { 62 case "EVENT": 63 if (data.length < 3) 64 return 65 return relay.event && relay.event(data[1], data[2]) 66 case "EOSE": 67 return relay.eose && relay.eose(data[1]) 68 case "NOTICE": 69 return relay.note && relay.note(...data.slice(1)) 70 } 71 } 72 } 73