forked from nbd-wtf/nostr-tools
-
Notifications
You must be signed in to change notification settings - Fork 1
/
test-helpers.ts
120 lines (97 loc) · 3.03 KB
/
test-helpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import { Server, WebSocket } from 'mock-socket'
import { finalizeEvent, type Event, getPublicKey, generateSecretKey } from './pure.ts'
import { matchFilters, type Filter } from './filter.ts'
export const MockWebSocketClient = WebSocket
export function buildEvent(params: Partial<Event>): Event {
return {
id: '',
kind: 1,
pubkey: '',
created_at: 0,
content: '',
tags: [],
sig: '',
...params,
}
}
let serial = 0
export class MockRelay {
private _server: Server
public url: string
public secretKeys: Uint8Array[]
public preloadedEvents: Event[]
constructor(url?: string | undefined) {
serial++
this.url = url ?? `wss://random.mock.relay/${serial}`
this.secretKeys = [generateSecretKey(), generateSecretKey(), generateSecretKey(), generateSecretKey()]
this.preloadedEvents = this.secretKeys.map(sk =>
finalizeEvent(
{
kind: 1,
content: 'autogenerated by relay',
created_at: Math.floor(Date.now() / 1000),
tags: [['t', 'auto']],
},
sk,
),
)
this._server = new Server(this.url)
this._server.on('connection', (conn: any) => {
let subs: { [subId: string]: { conn: any; filters: Filter[] } } = {}
conn.on('message', (message: string) => {
const data = JSON.parse(message)
switch (data[0]) {
case 'REQ': {
let subId = data[1]
let filters = data.slice(2)
subs[subId] = { conn, filters }
this.preloadedEvents.forEach(event => {
conn.send(JSON.stringify(['EVENT', subId, event]))
})
filters.forEach((filter: Filter) => {
const kinds = filter.kinds?.length ? filter.kinds : [1]
kinds.forEach(kind => {
this.secretKeys.forEach(sk => {
const event = finalizeEvent(
{
kind,
content: 'kind-aware autogenerated by relay',
created_at: Math.floor(Date.now() / 1000),
tags: [['t', 'auto']],
},
sk,
)
conn.send(JSON.stringify(['EVENT', subId, event]))
})
})
})
conn.send(JSON.stringify(['EOSE', subId]))
break
}
case 'CLOSE': {
let subId = data[1]
delete subs[subId]
break
}
case 'EVENT': {
let event = data[1]
conn.send(JSON.stringify(['OK', event.id, 'true']))
for (let subId in subs) {
const { filters, conn: listener } = subs[subId]
if (matchFilters(filters, event)) {
listener.send(JSON.stringify(['EVENT', subId, event]))
}
}
break
}
}
})
})
}
get authors() {
return this.secretKeys.map(getPublicKey)
}
get ids() {
return this.preloadedEvents.map(evt => evt.id)
}
}