mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bf7e00d32a | ||
|
|
9241089997 | ||
|
|
32c47e9bd8 | ||
|
|
6e58fe371c | ||
|
|
26e35d50e0 | ||
|
|
ef3184a6e0 | ||
|
|
56fe3dd5dd | ||
|
|
f1bb5030c8 | ||
|
|
ac212cb5c8 | ||
|
|
204ae0eff1 | ||
|
|
f17ab41d72 | ||
|
|
f6f5ee8223 | ||
|
|
a05506468d | ||
|
|
674ff66b6f | ||
|
|
731705047a | ||
|
|
94b382a49f | ||
|
|
199411a971 | ||
|
|
a1dc6f41b9 | ||
|
|
5b59b93d86 | ||
|
|
12acd7bdca | ||
|
|
3bdb68020d | ||
|
|
b0a58e2ca4 | ||
|
|
b063be76ae |
11
event.ts
11
event.ts
@@ -13,6 +13,7 @@ export enum Kind {
|
||||
EncryptedDirectMessage = 4,
|
||||
EventDeletion = 5,
|
||||
Reaction = 7,
|
||||
BadgeAward = 8,
|
||||
ChannelCreation = 40,
|
||||
ChannelMetadata = 41,
|
||||
ChannelMessage = 42,
|
||||
@@ -23,6 +24,8 @@ export enum Kind {
|
||||
Zap = 9735,
|
||||
RelayList = 10002,
|
||||
ClientAuth = 22242,
|
||||
BadgeDefinition = 30008,
|
||||
ProfileBadge = 30009,
|
||||
Article = 30023
|
||||
}
|
||||
|
||||
@@ -78,8 +81,10 @@ export function getEventHash(event: UnsignedEvent): string {
|
||||
return secp256k1.utils.bytesToHex(eventHash)
|
||||
}
|
||||
|
||||
export function validateEvent(event: UnsignedEvent): boolean {
|
||||
if (typeof event !== 'object') return false
|
||||
const isRecord = (obj: unknown): obj is Record<string, unknown> => obj instanceof Object
|
||||
|
||||
export function validateEvent<T>(event: T): event is T & UnsignedEvent {
|
||||
if (!isRecord(event)) return false
|
||||
if (typeof event.kind !== 'number') return false
|
||||
if (typeof event.content !== 'string') return false
|
||||
if (typeof event.created_at !== 'number') return false
|
||||
@@ -98,7 +103,7 @@ export function validateEvent(event: UnsignedEvent): boolean {
|
||||
return true
|
||||
}
|
||||
|
||||
export function verifySignature(event: Event & {sig: string}): boolean {
|
||||
export function verifySignature(event: Event): boolean {
|
||||
return secp256k1.schnorr.verifySync(
|
||||
event.sig,
|
||||
getEventHash(event),
|
||||
|
||||
@@ -37,6 +37,16 @@ describe('Filter', () => {
|
||||
expect(result).toEqual(false)
|
||||
})
|
||||
|
||||
it('should return true when the event id starts with a prefix', () => {
|
||||
const filter = {ids: ['22', '00']}
|
||||
|
||||
const event = {id: '001'}
|
||||
|
||||
const result = matchFilter(filter, event)
|
||||
|
||||
expect(result).toEqual(true)
|
||||
})
|
||||
|
||||
it('should return false when the event kind is not in the filter', () => {
|
||||
const filter = {kinds: [1, 2, 3]}
|
||||
|
||||
@@ -132,6 +142,20 @@ describe('Filter', () => {
|
||||
expect(result).toEqual(true)
|
||||
})
|
||||
|
||||
it('should return true when at least one prefix matches the event', () => {
|
||||
const filters = [
|
||||
{ids: ['1'], kinds: [1], authors: ['a']},
|
||||
{ids: ['4'], kinds: [2], authors: ['d']},
|
||||
{ids: ['9'], kinds: [3], authors: ['g']}
|
||||
]
|
||||
|
||||
const event = {id: '987', kind: 3, pubkey: 'ghi'}
|
||||
|
||||
const result = matchFilters(filters, event)
|
||||
|
||||
expect(result).toEqual(true)
|
||||
})
|
||||
|
||||
it('should return true when event matches one or more filters and some have limit set', () => {
|
||||
const filters = [
|
||||
{ids: ['123'], limit: 1},
|
||||
|
||||
17
filter.ts
17
filter.ts
@@ -13,12 +13,19 @@ export type Filter = {
|
||||
|
||||
export function matchFilter(
|
||||
filter: Filter,
|
||||
event: Event & {id: string}
|
||||
event: Event
|
||||
): boolean {
|
||||
if (filter.ids && filter.ids.indexOf(event.id) === -1) return false
|
||||
if (filter.ids && filter.ids.indexOf(event.id) === -1) {
|
||||
if (!filter.ids.some(prefix => event.id.startsWith(prefix))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (filter.kinds && filter.kinds.indexOf(event.kind) === -1) return false
|
||||
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1)
|
||||
return false
|
||||
if (filter.authors && filter.authors.indexOf(event.pubkey) === -1) {
|
||||
if (!filter.authors.some(prefix => event.pubkey.startsWith(prefix))) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
for (let f in filter) {
|
||||
if (f[0] === '#') {
|
||||
@@ -42,7 +49,7 @@ export function matchFilter(
|
||||
|
||||
export function matchFilters(
|
||||
filters: Filter[],
|
||||
event: Event & {id: string}
|
||||
event: Event
|
||||
): boolean {
|
||||
for (let i = 0; i < filters.length; i++) {
|
||||
if (matchFilter(filters[i], event)) return true
|
||||
|
||||
2
index.ts
2
index.ts
@@ -9,9 +9,11 @@ export * as nip04 from './nip04'
|
||||
export * as nip05 from './nip05'
|
||||
export * as nip06 from './nip06'
|
||||
export * as nip10 from './nip10'
|
||||
export * as nip13 from './nip13'
|
||||
export * as nip19 from './nip19'
|
||||
export * as nip26 from './nip26'
|
||||
export * as nip39 from './nip39'
|
||||
export * as nip42 from './nip42'
|
||||
export * as nip57 from './nip57'
|
||||
|
||||
export * as fj from './fakejson'
|
||||
|
||||
@@ -17,4 +17,9 @@ test('fetch nip05 profiles', async () => {
|
||||
'32e1827635450ebb3c5a7d12c1f8e7b2b514439ac10a67eef3d9fd9c5c68e245'
|
||||
)
|
||||
expect(p2.relays).toEqual(['wss://relay.damus.io'])
|
||||
|
||||
let p3 = await nip05.queryProfile('channel.ninja@channel.ninja')
|
||||
expect(p3.pubkey).toEqual(
|
||||
'36e65b503eba8a6b698e724a59137603101166a1cddb45ddc704247fc8aa0fce'
|
||||
)
|
||||
})
|
||||
|
||||
2
nip05.ts
2
nip05.ts
@@ -36,7 +36,7 @@ export async function queryProfile(
|
||||
name = '_'
|
||||
}
|
||||
|
||||
if (!name.match(/^[A-Za-z0-9-_]+$/)) return null
|
||||
if (!name.match(/^[A-Za-z0-9-_.]+$/)) return null
|
||||
if (!domain.includes('.')) return null
|
||||
|
||||
let res
|
||||
|
||||
8
nip13.test.js
Normal file
8
nip13.test.js
Normal file
@@ -0,0 +1,8 @@
|
||||
/* eslint-env jest */
|
||||
const {nip13} = require('./lib/nostr.cjs')
|
||||
|
||||
test('identifies proof-of-work difficulty', async () => {
|
||||
const id = '000006d8c378af1779d2feebc7603a125d99eca0ccf1085959b307f64e5dd358'
|
||||
const difficulty = nip13.getPow(id)
|
||||
expect(difficulty).toEqual(21)
|
||||
})
|
||||
42
nip13.ts
Normal file
42
nip13.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import * as secp256k1 from '@noble/secp256k1'
|
||||
|
||||
/** Get POW difficulty from a Nostr hex ID. */
|
||||
export function getPow(id: string): number {
|
||||
return getLeadingZeroBits(secp256k1.utils.hexToBytes(id))
|
||||
}
|
||||
|
||||
/**
|
||||
* Get number of leading 0 bits. Adapted from nostream.
|
||||
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
|
||||
*/
|
||||
function getLeadingZeroBits(hash: Uint8Array): number {
|
||||
let total: number, i: number, bits: number
|
||||
|
||||
for (i = 0, total = 0; i < hash.length; i++) {
|
||||
bits = msb(hash[i])
|
||||
total += bits
|
||||
if (bits !== 8) {
|
||||
break
|
||||
}
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapted from nostream.
|
||||
* https://github.com/Cameri/nostream/blob/fb6948fd83ca87ce552f39f9b5eb780ea07e272e/src/utils/proof-of-work.ts
|
||||
*/
|
||||
function msb(b: number) {
|
||||
let n = 0
|
||||
|
||||
if (b === 0) {
|
||||
return 8
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-cond-assign
|
||||
while (b >>= 1) {
|
||||
n++
|
||||
}
|
||||
|
||||
return 7 - n
|
||||
}
|
||||
@@ -100,3 +100,12 @@ test('decode naddr from go-nostr with different TLV ordering', () => {
|
||||
expect(data.kind).toEqual(30023)
|
||||
expect(data.identifier).toEqual('banana')
|
||||
})
|
||||
|
||||
test('encode and decode nrelay', () => {
|
||||
let url = "wss://relay.nostr.example"
|
||||
let nrelay = nip19.nrelayEncode(url)
|
||||
expect(nrelay).toMatch(/nrelay1\w+/)
|
||||
let {type, data} = nip19.decode(nrelay)
|
||||
expect(type).toEqual('nrelay')
|
||||
expect(data).toEqual(url)
|
||||
})
|
||||
|
||||
32
nip19.ts
32
nip19.ts
@@ -23,10 +23,16 @@ export type AddressPointer = {
|
||||
relays?: string[]
|
||||
}
|
||||
|
||||
export function decode(nip19: string): {
|
||||
type: string
|
||||
data: ProfilePointer | EventPointer | AddressPointer | string
|
||||
} {
|
||||
export type DecodeResult =
|
||||
| {type: 'nprofile'; data: ProfilePointer}
|
||||
| {type: 'nrelay'; data: string}
|
||||
| {type: 'nevent'; data: EventPointer}
|
||||
| {type: 'naddr'; data: AddressPointer}
|
||||
| {type: 'nsec'; data: string}
|
||||
| {type: 'npub'; data: string}
|
||||
| {type: 'note'; data: string}
|
||||
|
||||
export function decode(nip19: string): DecodeResult {
|
||||
let {prefix, words} = bech32.decode(nip19, Bech32MaxSize)
|
||||
let data = new Uint8Array(bech32.fromWords(words))
|
||||
|
||||
@@ -82,6 +88,16 @@ export function decode(nip19: string): {
|
||||
}
|
||||
}
|
||||
|
||||
case 'nrelay': {
|
||||
let tlv = parseTLV(data)
|
||||
if (!tlv[0]?.[0]) throw new Error('missing TLV 0 for nrelay')
|
||||
|
||||
return {
|
||||
type: 'nrelay',
|
||||
data: utf8Decoder.decode(tlv[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
case 'nsec':
|
||||
case 'npub':
|
||||
case 'note':
|
||||
@@ -160,6 +176,14 @@ export function naddrEncode(addr: AddressPointer): string {
|
||||
return bech32.encode('naddr', words, Bech32MaxSize)
|
||||
}
|
||||
|
||||
export function nrelayEncode(url: string): string {
|
||||
let data = encodeTLV({
|
||||
0: [utf8Encoder.encode(url)]
|
||||
})
|
||||
let words = bech32.toWords(data)
|
||||
return bech32.encode('nrelay', words, Bech32MaxSize)
|
||||
}
|
||||
|
||||
function encodeTLV(tlv: TLV): Uint8Array {
|
||||
let entries: Uint8Array[] = []
|
||||
|
||||
|
||||
27
nip42.test.js
Normal file
27
nip42.test.js
Normal file
@@ -0,0 +1,27 @@
|
||||
/* eslint-env jest */
|
||||
|
||||
require('websocket-polyfill')
|
||||
const {
|
||||
relayInit,
|
||||
generatePrivateKey,
|
||||
finishEvent,
|
||||
nip42
|
||||
} = require('./lib/nostr.cjs')
|
||||
|
||||
test('auth flow', done => {
|
||||
const relay = relayInit('wss://nostr.kollider.xyz')
|
||||
relay.connect()
|
||||
const sk = generatePrivateKey()
|
||||
|
||||
relay.on('auth', async challenge => {
|
||||
await expect(
|
||||
nip42.authenticate({
|
||||
challenge,
|
||||
relay,
|
||||
sign: e => finishEvent(e, sk)
|
||||
})
|
||||
).rejects.toBeTruthy()
|
||||
relay.close()
|
||||
done()
|
||||
})
|
||||
})
|
||||
42
nip42.ts
Normal file
42
nip42.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import {EventTemplate, Event, Kind} from './event'
|
||||
import {Relay} from './relay'
|
||||
|
||||
/**
|
||||
* Authenticate via NIP-42 flow.
|
||||
*
|
||||
* @example
|
||||
* const sign = window.nostr.signEvent
|
||||
* relay.on('auth', challenge =>
|
||||
* authenticate({ relay, sign, challenge })
|
||||
* )
|
||||
*/
|
||||
export const authenticate = async ({
|
||||
challenge,
|
||||
relay,
|
||||
sign
|
||||
}: {
|
||||
challenge: string
|
||||
relay: Relay
|
||||
sign: (e: EventTemplate) => Promise<Event>
|
||||
}): Promise<void> => {
|
||||
const e: EventTemplate = {
|
||||
kind: Kind.ClientAuth,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['relay', relay.url],
|
||||
['challenge', challenge]
|
||||
],
|
||||
content: ''
|
||||
}
|
||||
const pub = relay.auth(await sign(e))
|
||||
return new Promise((resolve, reject) => {
|
||||
pub.on('ok', function ok() {
|
||||
pub.off('ok', ok)
|
||||
resolve()
|
||||
})
|
||||
pub.on('failed', function fail(reason: string) {
|
||||
pub.off('failed', fail)
|
||||
reject(reason)
|
||||
})
|
||||
})
|
||||
}
|
||||
19
package.json
19
package.json
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nostr-tools",
|
||||
"version": "1.8.2",
|
||||
"version": "1.10.0",
|
||||
"description": "Tools for making a Nostr client.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -18,12 +18,11 @@
|
||||
},
|
||||
"license": "Public domain",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "1.0.0",
|
||||
"@noble/secp256k1": "^1.7.1",
|
||||
"@scure/base": "^1.1.1",
|
||||
"@scure/bip32": "^1.1.5",
|
||||
"@scure/bip39": "^1.1.1",
|
||||
"prettier": "^2.8.4"
|
||||
"@noble/hashes": "1.2.0",
|
||||
"@noble/secp256k1": "1.7.1",
|
||||
"@scure/base": "1.1.1",
|
||||
"@scure/bip32": "1.1.4",
|
||||
"@scure/bip39": "1.1.1"
|
||||
},
|
||||
"keywords": [
|
||||
"decentralization",
|
||||
@@ -32,6 +31,11 @@
|
||||
"client",
|
||||
"nostr"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "node build",
|
||||
"format": "prettier --plugin-search-dir . --write .",
|
||||
"test": "node build && jest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^18.13.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.51.0",
|
||||
@@ -44,6 +48,7 @@
|
||||
"events": "^3.3.0",
|
||||
"jest": "^29.4.2",
|
||||
"node-fetch": "^2.6.9",
|
||||
"prettier": "^2.8.4",
|
||||
"ts-jest": "^29.0.5",
|
||||
"tsd": "^0.22.0",
|
||||
"typescript": "^4.9.5",
|
||||
|
||||
4
pool.ts
4
pool.ts
@@ -2,7 +2,7 @@ import {Relay, relayInit} from './relay'
|
||||
import {normalizeURL} from './utils'
|
||||
import {Filter} from './filter'
|
||||
import {Event} from './event'
|
||||
import {SubscriptionOptions, Sub, Pub} from './relay'
|
||||
import {SubscriptionOptions, Sub, Pub, CountPayload} from './relay'
|
||||
|
||||
export class SimplePool {
|
||||
private _conn: {[url: string]: Relay}
|
||||
@@ -53,7 +53,7 @@ export class SimplePool {
|
||||
}
|
||||
|
||||
let subs: Sub[] = []
|
||||
let eventListeners: Set<(event: Event) => void> = new Set()
|
||||
let eventListeners: Set<any> = new Set()
|
||||
let eoseListeners: Set<() => void> = new Set()
|
||||
let eosesMissing = relays.length
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ export function parseReferences(evt: Event): Reference[] {
|
||||
}
|
||||
case 'a': {
|
||||
try {
|
||||
let [kind, pubkey, identifier] = ref[1].split(':')
|
||||
let [kind, pubkey, identifier] = tag[1].split(':')
|
||||
references.push({
|
||||
text: ref[0],
|
||||
address: {
|
||||
|
||||
112
relay.ts
112
relay.ts
@@ -9,9 +9,14 @@ type RelayEvent = {
|
||||
disconnect: () => void | Promise<void>
|
||||
error: () => void | Promise<void>
|
||||
notice: (msg: string) => void | Promise<void>
|
||||
auth: (challenge: string) => void | Promise<void>
|
||||
}
|
||||
export type CountPayload = {
|
||||
count: number
|
||||
}
|
||||
type SubEvent = {
|
||||
event: (event: Event) => void | Promise<void>
|
||||
count: (payload: CountPayload) => void | Promise<void>
|
||||
eose: () => void | Promise<void>
|
||||
}
|
||||
export type Relay = {
|
||||
@@ -22,7 +27,12 @@ export type Relay = {
|
||||
sub: (filters: Filter[], opts?: SubscriptionOptions) => Sub
|
||||
list: (filters: Filter[], opts?: SubscriptionOptions) => Promise<Event[]>
|
||||
get: (filter: Filter, opts?: SubscriptionOptions) => Promise<Event | null>
|
||||
count: (
|
||||
filters: Filter[],
|
||||
opts?: SubscriptionOptions
|
||||
) => Promise<CountPayload | null>
|
||||
publish: (event: Event) => Pub
|
||||
auth: (event: Event) => Pub
|
||||
off: <T extends keyof RelayEvent, U extends RelayEvent[T]>(
|
||||
event: T,
|
||||
listener: U
|
||||
@@ -51,27 +61,32 @@ export type Sub = {
|
||||
|
||||
export type SubscriptionOptions = {
|
||||
id?: string
|
||||
verb?: 'REQ' | 'COUNT'
|
||||
skipVerification?: boolean
|
||||
alreadyHaveEvent?: null | ((id: string, relay: string) => boolean)
|
||||
}
|
||||
|
||||
const newListeners = (): {[TK in keyof RelayEvent]: RelayEvent[TK][]} => ({
|
||||
connect: [],
|
||||
disconnect: [],
|
||||
error: [],
|
||||
notice: [],
|
||||
auth: []
|
||||
})
|
||||
|
||||
export function relayInit(
|
||||
url: string,
|
||||
options: {
|
||||
getTimeout?: number
|
||||
listTimeout?: number
|
||||
countTimeout?: number
|
||||
} = {}
|
||||
): Relay {
|
||||
let {listTimeout = 3000, getTimeout = 3000} = options
|
||||
let {listTimeout = 3000, getTimeout = 3000, countTimeout = 3000} = options
|
||||
|
||||
var ws: WebSocket
|
||||
var openSubs: {[id: string]: {filters: Filter[]} & SubscriptionOptions} = {}
|
||||
var listeners: {[TK in keyof RelayEvent]: RelayEvent[TK][]} = {
|
||||
connect: [],
|
||||
disconnect: [],
|
||||
error: [],
|
||||
notice: []
|
||||
}
|
||||
var listeners = newListeners()
|
||||
var subListeners: {
|
||||
[subid: string]: {[TK in keyof SubEvent]: SubEvent[TK][]}
|
||||
} = {}
|
||||
@@ -146,7 +161,7 @@ export function relayInit(
|
||||
// will naturally be caught by the encompassing try..catch block
|
||||
|
||||
switch (data[0]) {
|
||||
case 'EVENT':
|
||||
case 'EVENT': {
|
||||
let id = data[1]
|
||||
let event = data[2]
|
||||
if (
|
||||
@@ -159,6 +174,14 @@ export function relayInit(
|
||||
;(subListeners[id]?.event || []).forEach(cb => cb(event))
|
||||
}
|
||||
return
|
||||
}
|
||||
case 'COUNT':
|
||||
let id = data[1]
|
||||
let payload = data[2]
|
||||
if (openSubs[id]) {
|
||||
;(subListeners[id]?.count || []).forEach(cb => cb(payload))
|
||||
}
|
||||
return
|
||||
case 'EOSE': {
|
||||
let id = data[1]
|
||||
if (id in subListeners) {
|
||||
@@ -183,6 +206,11 @@ export function relayInit(
|
||||
let notice = data[1]
|
||||
listeners.notice.forEach(cb => cb(notice))
|
||||
return
|
||||
case 'AUTH': {
|
||||
let challenge = data[1]
|
||||
listeners.auth?.forEach(cb => cb(challenge))
|
||||
return
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return
|
||||
@@ -220,6 +248,7 @@ export function relayInit(
|
||||
const sub = (
|
||||
filters: Filter[],
|
||||
{
|
||||
verb = 'REQ',
|
||||
skipVerification = false,
|
||||
alreadyHaveEvent = null,
|
||||
id = Math.random().toString().slice(2)
|
||||
@@ -233,7 +262,7 @@ export function relayInit(
|
||||
skipVerification,
|
||||
alreadyHaveEvent
|
||||
}
|
||||
trySend(['REQ', subid, ...filters])
|
||||
trySend([verb, subid, ...filters])
|
||||
|
||||
return {
|
||||
sub: (newFilters, newOpts = {}) =>
|
||||
@@ -253,6 +282,7 @@ export function relayInit(
|
||||
): void => {
|
||||
subListeners[subid] = subListeners[subid] || {
|
||||
event: [],
|
||||
count: [],
|
||||
eose: []
|
||||
}
|
||||
subListeners[subid][type].push(cb)
|
||||
@@ -268,6 +298,29 @@ export function relayInit(
|
||||
}
|
||||
}
|
||||
|
||||
function _publishEvent(event: Event, type: string) {
|
||||
if (!event.id) throw new Error(`event ${event} has no id`)
|
||||
let id = event.id
|
||||
|
||||
trySend([type, event])
|
||||
|
||||
return {
|
||||
on: (type: 'ok' | 'failed', cb: any) => {
|
||||
pubListeners[id] = pubListeners[id] || {
|
||||
ok: [],
|
||||
failed: []
|
||||
}
|
||||
pubListeners[id][type].push(cb)
|
||||
},
|
||||
off: (type: 'ok' | 'failed', cb: any) => {
|
||||
let listeners = pubListeners[id]
|
||||
if (!listeners) return
|
||||
let idx = listeners[type].indexOf(cb)
|
||||
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
url,
|
||||
sub,
|
||||
@@ -318,31 +371,28 @@ export function relayInit(
|
||||
resolve(event)
|
||||
})
|
||||
}),
|
||||
publish(event: Event): Pub {
|
||||
if (!event.id) throw new Error(`event ${event} has no id`)
|
||||
let id = event.id
|
||||
|
||||
trySend(['EVENT', event])
|
||||
|
||||
return {
|
||||
on: (type: 'ok' | 'failed', cb: any) => {
|
||||
pubListeners[id] = pubListeners[id] || {
|
||||
ok: [],
|
||||
failed: []
|
||||
}
|
||||
pubListeners[id][type].push(cb)
|
||||
},
|
||||
off: (type: 'ok' | 'failed', cb: any) => {
|
||||
let listeners = pubListeners[id]
|
||||
if (!listeners) return
|
||||
let idx = listeners[type].indexOf(cb)
|
||||
if (idx >= 0) listeners[type].splice(idx, 1)
|
||||
}
|
||||
}
|
||||
count: (filters: Filter[]): Promise<CountPayload | null> =>
|
||||
new Promise(resolve => {
|
||||
let s = sub(filters, {...sub, verb: 'COUNT'})
|
||||
let timeout = setTimeout(() => {
|
||||
s.unsub()
|
||||
resolve(null)
|
||||
}, countTimeout)
|
||||
s.on('count', (event: CountPayload) => {
|
||||
s.unsub()
|
||||
clearTimeout(timeout)
|
||||
resolve(event)
|
||||
})
|
||||
}),
|
||||
publish(event): Pub {
|
||||
return _publishEvent(event, 'EVENT')
|
||||
},
|
||||
auth(event): Pub {
|
||||
return _publishEvent(event, 'AUTH')
|
||||
},
|
||||
connect,
|
||||
close(): void {
|
||||
listeners = {connect: [], disconnect: [], error: [], notice: []}
|
||||
listeners = newListeners()
|
||||
subListeners = {}
|
||||
pubListeners = {}
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
|
||||
Reference in New Issue
Block a user