applesauce-relay 2.3.0 → 3.0.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/README.md +6 -5
- package/dist/group.d.ts +2 -2
- package/dist/group.js +2 -2
- package/dist/pool.d.ts +4 -2
- package/dist/pool.js +20 -1
- package/dist/relay.d.ts +28 -9
- package/dist/relay.js +99 -42
- package/dist/types.d.ts +60 -62
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -56,9 +56,8 @@ const event = {
|
|
|
56
56
|
// ... other required fields
|
|
57
57
|
};
|
|
58
58
|
|
|
59
|
-
relay.
|
|
60
|
-
|
|
61
|
-
});
|
|
59
|
+
const response = await relay.publish(event);
|
|
60
|
+
console.log(`Published:`, response.ok);
|
|
62
61
|
```
|
|
63
62
|
|
|
64
63
|
### Relay Pool
|
|
@@ -85,7 +84,8 @@ pool
|
|
|
85
84
|
});
|
|
86
85
|
|
|
87
86
|
// Publish to multiple relays
|
|
88
|
-
pool.
|
|
87
|
+
const responses = await pool.publish(relays, event);
|
|
88
|
+
responses.forEach((response) => {
|
|
89
89
|
console.log(`Published to ${response.from}:`, response.ok);
|
|
90
90
|
});
|
|
91
91
|
```
|
|
@@ -112,7 +112,8 @@ group
|
|
|
112
112
|
});
|
|
113
113
|
|
|
114
114
|
// Publish to all relays in group
|
|
115
|
-
group.
|
|
115
|
+
const responses = await group.publish(event);
|
|
116
|
+
responses.forEach((response) => {
|
|
116
117
|
console.log(`Published to ${response.from}:`, response.ok);
|
|
117
118
|
});
|
|
118
119
|
```
|
package/dist/group.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type NostrEvent } from "nostr-tools";
|
|
2
2
|
import { Observable } from "rxjs";
|
|
3
|
-
import { IGroup, IRelay,
|
|
3
|
+
import { FilterInput, IGroup, IRelay, PublishOptions, PublishResponse, RequestOptions, SubscriptionOptions, SubscriptionResponse } from "./types.js";
|
|
4
4
|
export declare class RelayGroup implements IGroup {
|
|
5
5
|
relays: IRelay[];
|
|
6
6
|
constructor(relays: IRelay[]);
|
|
@@ -11,7 +11,7 @@ export declare class RelayGroup implements IGroup {
|
|
|
11
11
|
/** Send an event to all relays */
|
|
12
12
|
event(event: NostrEvent): Observable<PublishResponse>;
|
|
13
13
|
/** Publish an event to all relays with retries ( default 3 retries ) */
|
|
14
|
-
publish(event: NostrEvent, opts?: PublishOptions):
|
|
14
|
+
publish(event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse[]>;
|
|
15
15
|
/** Request events from all relays with retries ( default 3 retries ) */
|
|
16
16
|
request(filters: FilterInput, opts?: RequestOptions): Observable<NostrEvent>;
|
|
17
17
|
/** Open a subscription to all relays with retries ( default 3 retries ) */
|
package/dist/group.js
CHANGED
|
@@ -35,9 +35,9 @@ export class RelayGroup {
|
|
|
35
35
|
}
|
|
36
36
|
/** Publish an event to all relays with retries ( default 3 retries ) */
|
|
37
37
|
publish(event, opts) {
|
|
38
|
-
return
|
|
38
|
+
return Promise.all(this.relays.map((relay) => relay.publish(event, opts).catch(
|
|
39
39
|
// Catch error and return as PublishResponse
|
|
40
|
-
|
|
40
|
+
(err) => ({ ok: false, from: relay.url, message: err?.message || "Unknown error" }))));
|
|
41
41
|
}
|
|
42
42
|
/** Request events from all relays with retries ( default 3 retries ) */
|
|
43
43
|
request(filters, opts) {
|
package/dist/pool.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { type NostrEvent } from "nostr-tools";
|
|
|
2
2
|
import { BehaviorSubject, Observable } from "rxjs";
|
|
3
3
|
import { RelayGroup } from "./group.js";
|
|
4
4
|
import { Relay, RelayOptions } from "./relay.js";
|
|
5
|
-
import { IPool, PublishResponse, PublishOptions, RequestOptions, SubscriptionOptions, SubscriptionResponse, FilterInput } from "./types.js";
|
|
5
|
+
import { IPool, PublishResponse, PublishOptions, RequestOptions, SubscriptionOptions, SubscriptionResponse, FilterInput, IRelay } from "./types.js";
|
|
6
6
|
export declare class RelayPool implements IPool {
|
|
7
7
|
options?: RelayOptions | undefined;
|
|
8
8
|
groups$: BehaviorSubject<Map<string, RelayGroup>>;
|
|
@@ -17,12 +17,14 @@ export declare class RelayPool implements IPool {
|
|
|
17
17
|
relay(url: string): Relay;
|
|
18
18
|
/** Create a group of relays */
|
|
19
19
|
group(relays: string[]): RelayGroup;
|
|
20
|
+
/** Removes a relay from the pool and defaults to closing the connection */
|
|
21
|
+
remove(relay: string | IRelay, close?: boolean): void;
|
|
20
22
|
/** Make a REQ to multiple relays that does not deduplicate events */
|
|
21
23
|
req(relays: string[], filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
22
24
|
/** Send an EVENT message to multiple relays */
|
|
23
25
|
event(relays: string[], event: NostrEvent): Observable<PublishResponse>;
|
|
24
26
|
/** Publish an event to multiple relays */
|
|
25
|
-
publish(relays: string[], event: NostrEvent, opts?: PublishOptions):
|
|
27
|
+
publish(relays: string[], event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse[]>;
|
|
26
28
|
/** Request events from multiple relays */
|
|
27
29
|
request(relays: string[], filters: FilterInput, opts?: RequestOptions): Observable<NostrEvent>;
|
|
28
30
|
/** Open a subscription to multiple relays */
|
package/dist/pool.js
CHANGED
|
@@ -33,7 +33,8 @@ export class RelayPool {
|
|
|
33
33
|
return relay;
|
|
34
34
|
// Create a new relay
|
|
35
35
|
relay = new Relay(url, this.options);
|
|
36
|
-
this.relays
|
|
36
|
+
this.relays.set(url, relay);
|
|
37
|
+
this.relays$.next(this.relays);
|
|
37
38
|
return relay;
|
|
38
39
|
}
|
|
39
40
|
/** Create a group of relays */
|
|
@@ -50,6 +51,24 @@ export class RelayPool {
|
|
|
50
51
|
this.groups$.next(this.groups.set(key, group));
|
|
51
52
|
return group;
|
|
52
53
|
}
|
|
54
|
+
/** Removes a relay from the pool and defaults to closing the connection */
|
|
55
|
+
remove(relay, close = true) {
|
|
56
|
+
let instance;
|
|
57
|
+
if (typeof relay === "string") {
|
|
58
|
+
instance = this.relays.get(relay);
|
|
59
|
+
if (!instance)
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
else if (Array.from(this.relays.values()).some((r) => r === relay)) {
|
|
63
|
+
instance = relay;
|
|
64
|
+
}
|
|
65
|
+
else
|
|
66
|
+
return;
|
|
67
|
+
if (close)
|
|
68
|
+
instance?.close();
|
|
69
|
+
this.relays.delete(instance.url);
|
|
70
|
+
this.relays$.next(this.relays);
|
|
71
|
+
}
|
|
53
72
|
/** Make a REQ to multiple relays that does not deduplicate events */
|
|
54
73
|
req(relays, filters, id) {
|
|
55
74
|
return this.group(relays).req(filters, id);
|
package/dist/relay.d.ts
CHANGED
|
@@ -1,14 +1,21 @@
|
|
|
1
1
|
import { logger } from "applesauce-core";
|
|
2
2
|
import { type Filter, type NostrEvent } from "nostr-tools";
|
|
3
|
-
import { BehaviorSubject, Observable } from "rxjs";
|
|
4
|
-
import { WebSocketSubject, WebSocketSubjectConfig } from "rxjs/webSocket";
|
|
5
3
|
import { RelayInformation } from "nostr-tools/nip11";
|
|
4
|
+
import { BehaviorSubject, MonoTypeOperatorFunction, Observable, RepeatConfig, RetryConfig, Subject } from "rxjs";
|
|
5
|
+
import { WebSocketSubject, WebSocketSubjectConfig } from "rxjs/webSocket";
|
|
6
6
|
import { AuthSigner, FilterInput, IRelay, PublishOptions, PublishResponse, RequestOptions, SubscriptionOptions, SubscriptionResponse } from "./types.js";
|
|
7
7
|
/** An error that is thrown when a REQ is closed from the relay side */
|
|
8
8
|
export declare class ReqCloseError extends Error {
|
|
9
9
|
}
|
|
10
10
|
export type RelayOptions = {
|
|
11
|
+
/** Custom WebSocket implementation */
|
|
11
12
|
WebSocket?: WebSocketSubjectConfig<any>["WebSocketCtor"];
|
|
13
|
+
/** How long to wait for an EOSE message (default 10s) */
|
|
14
|
+
eoseTimeout?: number;
|
|
15
|
+
/** How long to wait for an OK message from the relay (default 10s) */
|
|
16
|
+
eventTimeout?: number;
|
|
17
|
+
/** How long to keep the connection alive after nothing is subscribed (default 30s) */
|
|
18
|
+
keepAlive?: number;
|
|
12
19
|
};
|
|
13
20
|
export declare class Relay implements IRelay {
|
|
14
21
|
url: string;
|
|
@@ -47,17 +54,23 @@ export declare class Relay implements IRelay {
|
|
|
47
54
|
protected _nip11: RelayInformation | null;
|
|
48
55
|
/** An observable that emits the limitations for the relay */
|
|
49
56
|
limitations$: Observable<RelayInformation["limitation"] | null>;
|
|
57
|
+
/** An observable that emits when underlying websocket is opened */
|
|
58
|
+
open$: Subject<Event>;
|
|
59
|
+
/** An observable that emits when underlying websocket is closed */
|
|
60
|
+
close$: Subject<CloseEvent>;
|
|
61
|
+
/** An observable that emits when underlying websocket is closing due to unsubscription */
|
|
62
|
+
closing$: Subject<void>;
|
|
50
63
|
get connected(): boolean;
|
|
51
64
|
get challenge(): string | null;
|
|
52
65
|
get notices(): string[];
|
|
53
66
|
get authenticated(): boolean;
|
|
54
67
|
get authenticationResponse(): PublishResponse | null;
|
|
55
68
|
get information(): RelayInformation | null;
|
|
56
|
-
/** If an EOSE message is not seen in this time, emit one locally */
|
|
69
|
+
/** If an EOSE message is not seen in this time, emit one locally (default 10s) */
|
|
57
70
|
eoseTimeout: number;
|
|
58
|
-
/** How long to wait for an OK message from the relay */
|
|
71
|
+
/** How long to wait for an OK message from the relay (default 10s) */
|
|
59
72
|
eventTimeout: number;
|
|
60
|
-
/** How long to keep the connection alive after nothing is subscribed */
|
|
73
|
+
/** How long to keep the connection alive after nothing is subscribed (default 30s) */
|
|
61
74
|
keepAlive: number;
|
|
62
75
|
protected receivedAuthRequiredForReq: BehaviorSubject<boolean>;
|
|
63
76
|
protected receivedAuthRequiredForEvent: BehaviorSubject<boolean>;
|
|
@@ -75,21 +88,27 @@ export declare class Relay implements IRelay {
|
|
|
75
88
|
protected waitForReady<T extends unknown = unknown>(observable: Observable<T>): Observable<T>;
|
|
76
89
|
multiplex<T>(open: () => any, close: () => any, filter: (message: any) => boolean): Observable<T>;
|
|
77
90
|
/** Send a message to the relay */
|
|
78
|
-
|
|
91
|
+
send(message: any): void;
|
|
79
92
|
/** Create a REQ observable that emits events or "EOSE" or errors */
|
|
80
93
|
req(filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
81
94
|
/** Send an EVENT or AUTH message and return an observable of PublishResponse that completes or errors */
|
|
82
95
|
event(event: NostrEvent, verb?: "EVENT" | "AUTH"): Observable<PublishResponse>;
|
|
83
96
|
/** send and AUTH message */
|
|
84
|
-
auth(event: NostrEvent):
|
|
97
|
+
auth(event: NostrEvent): Promise<PublishResponse>;
|
|
85
98
|
/** Authenticate with the relay using a signer */
|
|
86
|
-
authenticate(signer: AuthSigner):
|
|
99
|
+
authenticate(signer: AuthSigner): Promise<PublishResponse>;
|
|
100
|
+
/** Internal operator for creating the retry() operator */
|
|
101
|
+
protected customRetryOperator<T extends unknown = unknown>(times: number | RetryConfig): MonoTypeOperatorFunction<T>;
|
|
102
|
+
/** Internal operator for creating the repeat() operator */
|
|
103
|
+
protected customRepeatOperator<T extends unknown = unknown>(times: boolean | number | RepeatConfig | undefined): MonoTypeOperatorFunction<T>;
|
|
87
104
|
/** Creates a REQ that retries when relay errors ( default 3 retries ) */
|
|
88
105
|
subscription(filters: Filter | Filter[], opts?: SubscriptionOptions): Observable<SubscriptionResponse>;
|
|
89
106
|
/** Makes a single request that retires on errors and completes on EOSE */
|
|
90
107
|
request(filters: Filter | Filter[], opts?: RequestOptions): Observable<NostrEvent>;
|
|
91
108
|
/** Publishes an event to the relay and retries when relay errors or responds with auth-required ( default 3 retries ) */
|
|
92
|
-
publish(event: NostrEvent, opts?: PublishOptions):
|
|
109
|
+
publish(event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse>;
|
|
110
|
+
/** Force close the connection */
|
|
111
|
+
close(): void;
|
|
93
112
|
/** Static method to fetch the NIP-11 information document for a relay */
|
|
94
113
|
static fetchInformationDocument(url: string): Observable<RelayInformation | null>;
|
|
95
114
|
/** Static method to create a reconnection method for each relay */
|
package/dist/relay.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { logger } from "applesauce-core";
|
|
2
|
+
import { ensureHttpURL } from "applesauce-core/helpers";
|
|
2
3
|
import { simpleTimeout } from "applesauce-core/observable";
|
|
3
4
|
import { nanoid } from "nanoid";
|
|
4
5
|
import { nip42 } from "nostr-tools";
|
|
5
|
-
import { BehaviorSubject, catchError, combineLatest, defer, endWith, filter, finalize, from, ignoreElements, isObservable, map, merge, mergeMap, mergeWith, NEVER, of, retry, scan, share, shareReplay, Subject, switchMap, take, takeUntil, tap, throwError, timeout, timer, } from "rxjs";
|
|
6
|
+
import { BehaviorSubject, catchError, combineLatest, defer, endWith, filter, finalize, from, identity, ignoreElements, isObservable, lastValueFrom, map, merge, mergeMap, mergeWith, NEVER, of, repeat, retry, scan, share, shareReplay, Subject, switchMap, take, takeUntil, tap, throwError, timeout, timer, } from "rxjs";
|
|
6
7
|
import { webSocket } from "rxjs/webSocket";
|
|
7
|
-
import { ensureHttpURL } from "applesauce-core/helpers";
|
|
8
8
|
import { completeOnEose } from "./operators/complete-on-eose.js";
|
|
9
9
|
import { markFromRelay } from "./operators/mark-from-relay.js";
|
|
10
10
|
/** An error that is thrown when a REQ is closed from the relay side */
|
|
@@ -47,6 +47,12 @@ export class Relay {
|
|
|
47
47
|
_nip11 = null;
|
|
48
48
|
/** An observable that emits the limitations for the relay */
|
|
49
49
|
limitations$;
|
|
50
|
+
/** An observable that emits when underlying websocket is opened */
|
|
51
|
+
open$ = new Subject();
|
|
52
|
+
/** An observable that emits when underlying websocket is closed */
|
|
53
|
+
close$ = new Subject();
|
|
54
|
+
/** An observable that emits when underlying websocket is closing due to unsubscription */
|
|
55
|
+
closing$ = new Subject();
|
|
50
56
|
// sync state
|
|
51
57
|
get connected() {
|
|
52
58
|
return this.connected$.value;
|
|
@@ -66,11 +72,11 @@ export class Relay {
|
|
|
66
72
|
get information() {
|
|
67
73
|
return this._nip11;
|
|
68
74
|
}
|
|
69
|
-
/** If an EOSE message is not seen in this time, emit one locally */
|
|
75
|
+
/** If an EOSE message is not seen in this time, emit one locally (default 10s) */
|
|
70
76
|
eoseTimeout = 10_000;
|
|
71
|
-
/** How long to wait for an OK message from the relay */
|
|
77
|
+
/** How long to wait for an OK message from the relay (default 10s) */
|
|
72
78
|
eventTimeout = 10_000;
|
|
73
|
-
/** How long to keep the connection alive after nothing is subscribed */
|
|
79
|
+
/** How long to keep the connection alive after nothing is subscribed (default 30s) */
|
|
74
80
|
keepAlive = 30_000;
|
|
75
81
|
// Subjects that track if an "auth-required" message has been received for REQ or EVENT
|
|
76
82
|
receivedAuthRequiredForReq = new BehaviorSubject(false);
|
|
@@ -96,32 +102,39 @@ export class Relay {
|
|
|
96
102
|
constructor(url, opts) {
|
|
97
103
|
this.url = url;
|
|
98
104
|
this.log = this.log.extend(url);
|
|
105
|
+
// Set common options
|
|
106
|
+
if (opts?.eoseTimeout !== undefined)
|
|
107
|
+
this.eoseTimeout = opts.eoseTimeout;
|
|
108
|
+
if (opts?.eventTimeout !== undefined)
|
|
109
|
+
this.eventTimeout = opts.eventTimeout;
|
|
110
|
+
if (opts?.keepAlive !== undefined)
|
|
111
|
+
this.keepAlive = opts.keepAlive;
|
|
99
112
|
// Create an observable that tracks boolean authentication state
|
|
100
113
|
this.authenticated$ = this.authenticationResponse$.pipe(map((response) => response?.ok === true));
|
|
101
114
|
/** Use the static method to create a new reconnect method for this relay */
|
|
102
115
|
this.reconnectTimer = Relay.createReconnectTimer(url);
|
|
116
|
+
// Subscribe to open and close events
|
|
117
|
+
this.open$.subscribe(() => {
|
|
118
|
+
this.log("Connected");
|
|
119
|
+
this.connected$.next(true);
|
|
120
|
+
this.attempts$.next(0);
|
|
121
|
+
this.error$.next(null);
|
|
122
|
+
this.resetState();
|
|
123
|
+
});
|
|
124
|
+
this.close$.subscribe((event) => {
|
|
125
|
+
this.log("Disconnected");
|
|
126
|
+
this.connected$.next(false);
|
|
127
|
+
this.attempts$.next(this.attempts$.value + 1);
|
|
128
|
+
this.resetState();
|
|
129
|
+
// Start the reconnect timer if the connection was not closed cleanly
|
|
130
|
+
if (!event.wasClean)
|
|
131
|
+
this.startReconnectTimer(event);
|
|
132
|
+
});
|
|
103
133
|
this.socket = webSocket({
|
|
104
134
|
url,
|
|
105
|
-
openObserver:
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
this.connected$.next(true);
|
|
109
|
-
this.attempts$.next(0);
|
|
110
|
-
this.error$.next(null);
|
|
111
|
-
this.resetState();
|
|
112
|
-
},
|
|
113
|
-
},
|
|
114
|
-
closeObserver: {
|
|
115
|
-
next: (event) => {
|
|
116
|
-
this.log("Disconnected");
|
|
117
|
-
this.connected$.next(false);
|
|
118
|
-
this.attempts$.next(this.attempts$.value + 1);
|
|
119
|
-
this.resetState();
|
|
120
|
-
// Start the reconnect timer if the connection was not closed cleanly
|
|
121
|
-
if (!event.wasClean)
|
|
122
|
-
this.startReconnectTimer(event);
|
|
123
|
-
},
|
|
124
|
-
},
|
|
135
|
+
openObserver: this.open$,
|
|
136
|
+
closeObserver: this.close$,
|
|
137
|
+
closingObserver: this.closing$,
|
|
125
138
|
WebSocketCtor: opts?.WebSocket,
|
|
126
139
|
});
|
|
127
140
|
// Create an observable to fetch the NIP-11 information document
|
|
@@ -200,7 +213,7 @@ export class Relay {
|
|
|
200
213
|
}
|
|
201
214
|
/** Wait for authentication state, make connection and then wait for authentication if required */
|
|
202
215
|
waitForAuth(
|
|
203
|
-
// NOTE: require BehaviorSubject so it always has a value
|
|
216
|
+
// NOTE: require BehaviorSubject or shareReplay so it always has a value
|
|
204
217
|
requireAuth, observable) {
|
|
205
218
|
return combineLatest([requireAuth, this.authenticated$]).pipe(
|
|
206
219
|
// Once the auth state is known, make a connection and watch for auth challenges
|
|
@@ -230,7 +243,7 @@ export class Relay {
|
|
|
230
243
|
return this.socket.multiplex(open, close, filter);
|
|
231
244
|
}
|
|
232
245
|
/** Send a message to the relay */
|
|
233
|
-
|
|
246
|
+
send(message) {
|
|
234
247
|
this.socket.next(message);
|
|
235
248
|
}
|
|
236
249
|
/** Create a REQ observable that emits events or "EOSE" or errors */
|
|
@@ -238,21 +251,26 @@ export class Relay {
|
|
|
238
251
|
// Convert filters input into an observable, if its a normal value merge it with NEVER so it never completes
|
|
239
252
|
const input = isObservable(filters) ? filters : merge(of(filters), NEVER);
|
|
240
253
|
// Create an observable that completes when the upstream observable completes
|
|
241
|
-
const
|
|
254
|
+
const filtersComplete = input.pipe(ignoreElements(), endWith(null));
|
|
242
255
|
// Create an observable that filters responses from the relay to just the ones for this REQ
|
|
243
|
-
const messages = this.socket.pipe(filter((m) => Array.isArray(m) && (m[0] === "EVENT" || m[0] === "CLOSED" || m[0] === "EOSE") && m[1] === id)
|
|
256
|
+
const messages = this.socket.pipe(filter((m) => Array.isArray(m) && (m[0] === "EVENT" || m[0] === "CLOSED" || m[0] === "EOSE") && m[1] === id),
|
|
257
|
+
// Singleton (prevents the .pipe() operator later from sending two REQ messages )
|
|
258
|
+
share());
|
|
244
259
|
// Create an observable that controls sending the filters and closing the REQ
|
|
245
260
|
const control = input.pipe(
|
|
246
261
|
// Send the filters when they change
|
|
247
262
|
tap((filters) => this.socket.next(Array.isArray(filters) ? ["REQ", id, ...filters] : ["REQ", id, filters])),
|
|
248
|
-
//
|
|
263
|
+
// Send the CLOSE message when unsubscribed or input completes
|
|
249
264
|
finalize(() => this.socket.next(["CLOSE", id])),
|
|
250
265
|
// Once filters have been sent, switch to listening for messages
|
|
251
266
|
switchMap(() => messages));
|
|
252
267
|
// Start the watch tower with the observables
|
|
253
268
|
const observable = merge(this.watchTower, control).pipe(
|
|
269
|
+
// Complete the subscription when the control observable completes
|
|
270
|
+
// This is to work around the fact that merge() waits for both observables to complete
|
|
271
|
+
takeUntil(messages.pipe(ignoreElements(), endWith(true))),
|
|
254
272
|
// Complete the subscription when the input is completed
|
|
255
|
-
takeUntil(
|
|
273
|
+
takeUntil(filtersComplete),
|
|
256
274
|
// Map the messages to events, EOSE, or throw an error
|
|
257
275
|
map((message) => {
|
|
258
276
|
if (message[0] === "EOSE")
|
|
@@ -287,15 +305,20 @@ export class Relay {
|
|
|
287
305
|
}
|
|
288
306
|
/** Send an EVENT or AUTH message and return an observable of PublishResponse that completes or errors */
|
|
289
307
|
event(event, verb = "EVENT") {
|
|
290
|
-
const
|
|
308
|
+
const messages = defer(() => {
|
|
291
309
|
// Send event when subscription starts
|
|
292
310
|
this.socket.next([verb, event]);
|
|
293
311
|
return this.socket.pipe(filter((m) => m[0] === "OK" && m[1] === event.id),
|
|
294
312
|
// format OK message
|
|
295
313
|
map((m) => ({ ok: m[2], message: m[3], from: this.url })));
|
|
296
|
-
})
|
|
314
|
+
}).pipe(
|
|
315
|
+
// Singleton (prevents the .pipe() operator later from sending two EVENT messages )
|
|
316
|
+
share());
|
|
297
317
|
// Start the watch tower and add complete operators
|
|
298
|
-
const observable = merge(this.watchTower,
|
|
318
|
+
const observable = merge(this.watchTower, messages).pipe(
|
|
319
|
+
// Complete the subscription when the messages observable completes
|
|
320
|
+
// This is to work around the fact that merge() waits for both observables to complete
|
|
321
|
+
takeUntil(messages.pipe(ignoreElements(), endWith(true))),
|
|
299
322
|
// complete on first value
|
|
300
323
|
take(1),
|
|
301
324
|
// listen for OK auth-required
|
|
@@ -320,9 +343,9 @@ export class Relay {
|
|
|
320
343
|
}
|
|
321
344
|
/** send and AUTH message */
|
|
322
345
|
auth(event) {
|
|
323
|
-
return this.event(event, "AUTH").pipe(
|
|
346
|
+
return lastValueFrom(this.event(event, "AUTH").pipe(
|
|
324
347
|
// update authenticated
|
|
325
|
-
tap((result) => this.authenticationResponse$.next(result)));
|
|
348
|
+
tap((result) => this.authenticationResponse$.next(result))));
|
|
326
349
|
}
|
|
327
350
|
/** Authenticate with the relay using a signer */
|
|
328
351
|
authenticate(signer) {
|
|
@@ -330,32 +353,66 @@ export class Relay {
|
|
|
330
353
|
throw new Error("Have not received authentication challenge");
|
|
331
354
|
const p = signer.signEvent(nip42.makeAuthEvent(this.url, this.challenge));
|
|
332
355
|
const start = p instanceof Promise ? from(p) : of(p);
|
|
333
|
-
return start.pipe(switchMap((event) => this.auth(event)));
|
|
356
|
+
return lastValueFrom(start.pipe(switchMap((event) => this.auth(event))));
|
|
357
|
+
}
|
|
358
|
+
/** Internal operator for creating the retry() operator */
|
|
359
|
+
customRetryOperator(times) {
|
|
360
|
+
if (typeof times === "number")
|
|
361
|
+
return retry(times);
|
|
362
|
+
else
|
|
363
|
+
return retry(times);
|
|
364
|
+
}
|
|
365
|
+
/** Internal operator for creating the repeat() operator */
|
|
366
|
+
customRepeatOperator(times) {
|
|
367
|
+
if (times === false || times === undefined)
|
|
368
|
+
return identity;
|
|
369
|
+
else if (times === true)
|
|
370
|
+
return repeat();
|
|
371
|
+
else if (typeof times === "number")
|
|
372
|
+
return repeat(times);
|
|
373
|
+
else
|
|
374
|
+
return repeat(times);
|
|
334
375
|
}
|
|
335
376
|
/** Creates a REQ that retries when relay errors ( default 3 retries ) */
|
|
336
377
|
subscription(filters, opts) {
|
|
337
378
|
return this.req(filters, opts?.id).pipe(
|
|
338
379
|
// Retry on connection errors
|
|
339
|
-
|
|
380
|
+
this.customRetryOperator(opts?.retries ?? 3),
|
|
381
|
+
// Create reconnect logic (repeat operator)
|
|
382
|
+
this.customRepeatOperator(opts?.reconnect),
|
|
383
|
+
// Single subscription
|
|
384
|
+
share());
|
|
340
385
|
}
|
|
341
386
|
/** Makes a single request that retires on errors and completes on EOSE */
|
|
342
387
|
request(filters, opts) {
|
|
343
388
|
return this.req(filters, opts?.id).pipe(
|
|
344
389
|
// Retry on connection errors
|
|
345
|
-
|
|
390
|
+
this.customRetryOperator(opts?.retries ?? 3),
|
|
391
|
+
// Create reconnect logic (repeat operator)
|
|
392
|
+
this.customRepeatOperator(opts?.reconnect),
|
|
346
393
|
// Complete when EOSE is received
|
|
347
|
-
completeOnEose()
|
|
394
|
+
completeOnEose(),
|
|
395
|
+
// Single subscription
|
|
396
|
+
share());
|
|
348
397
|
}
|
|
349
398
|
/** Publishes an event to the relay and retries when relay errors or responds with auth-required ( default 3 retries ) */
|
|
350
399
|
publish(event, opts) {
|
|
351
|
-
return this.event(event).pipe(mergeMap((result) => {
|
|
400
|
+
return lastValueFrom(this.event(event).pipe(mergeMap((result) => {
|
|
352
401
|
// If the relay responds with auth-required, throw an error for the retry operator to handle
|
|
353
402
|
if (result.ok === false && result.message?.startsWith("auth-required:"))
|
|
354
403
|
return throwError(() => new Error(result.message));
|
|
355
404
|
return of(result);
|
|
356
405
|
}),
|
|
357
406
|
// Retry the publish until it succeeds or the number of retries is reached
|
|
358
|
-
|
|
407
|
+
this.customRetryOperator(opts?.retries ?? 3),
|
|
408
|
+
// Create reconnect logic (repeat operator)
|
|
409
|
+
this.customRepeatOperator(opts?.reconnect),
|
|
410
|
+
// Single subscription
|
|
411
|
+
share()));
|
|
412
|
+
}
|
|
413
|
+
/** Force close the connection */
|
|
414
|
+
close() {
|
|
415
|
+
this.socket.unsubscribe();
|
|
359
416
|
}
|
|
360
417
|
/** Static method to fetch the NIP-11 information document for a relay */
|
|
361
418
|
static fetchInformationDocument(url) {
|
package/dist/types.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type EventTemplate, type Filter, type NostrEvent } from "nostr-tools";
|
|
2
|
-
import { Observable } from "rxjs";
|
|
2
|
+
import { Observable, repeat, retry } from "rxjs";
|
|
3
3
|
import { WebSocketSubject } from "rxjs/webSocket";
|
|
4
4
|
export type SubscriptionResponse = NostrEvent | "EOSE";
|
|
5
5
|
export type PublishResponse = {
|
|
@@ -8,99 +8,97 @@ export type PublishResponse = {
|
|
|
8
8
|
from: string;
|
|
9
9
|
};
|
|
10
10
|
export type MultiplexWebSocket<T = any> = Pick<WebSocketSubject<T>, "multiplex">;
|
|
11
|
-
|
|
12
|
-
connected$: Observable<boolean>;
|
|
13
|
-
challenge$: Observable<string | null>;
|
|
14
|
-
authenticated$: Observable<boolean>;
|
|
15
|
-
notices$: Observable<string[]>;
|
|
16
|
-
}
|
|
11
|
+
/** Options for the publish method on the pool and relay */
|
|
17
12
|
export type PublishOptions = {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
retries?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Number of times to retry the publish. default is 3
|
|
15
|
+
* @see https://rxjs.dev/api/index/function/retry
|
|
16
|
+
*/
|
|
17
|
+
retries?: number | Parameters<typeof retry>[0];
|
|
18
|
+
/**
|
|
19
|
+
* Whether to reconnect when socket is closed. A number of times or true for infinite. default is false
|
|
20
|
+
* @see https://rxjs.dev/api/index/function/repeat
|
|
21
|
+
*/
|
|
22
|
+
reconnect?: boolean | Parameters<typeof repeat>[0];
|
|
23
23
|
};
|
|
24
|
+
/** Options for the request method on the pool and relay */
|
|
25
|
+
export type RequestOptions = SubscriptionOptions;
|
|
26
|
+
/** Options for the subscription method on the pool and relay */
|
|
24
27
|
export type SubscriptionOptions = {
|
|
28
|
+
/** Custom REQ id for the subscription */
|
|
25
29
|
id?: string;
|
|
26
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Number of times to retry a request. default is 3
|
|
32
|
+
* @see https://rxjs.dev/api/index/function/retry
|
|
33
|
+
*/
|
|
34
|
+
retries?: number | Parameters<typeof retry>[0];
|
|
35
|
+
/**
|
|
36
|
+
* Whether to reconnect when socket is closed. A number of times or true for infinite. default is false
|
|
37
|
+
* @see https://rxjs.dev/api/index/function/repeat
|
|
38
|
+
*/
|
|
39
|
+
reconnect?: boolean | Parameters<typeof repeat>[0];
|
|
27
40
|
};
|
|
28
41
|
export type AuthSigner = {
|
|
29
42
|
signEvent: (event: EventTemplate) => NostrEvent | Promise<NostrEvent>;
|
|
30
43
|
};
|
|
31
44
|
/** The type of input the REQ method accepts */
|
|
32
45
|
export type FilterInput = Filter | Filter[] | Observable<Filter | Filter[]>;
|
|
33
|
-
export interface
|
|
34
|
-
/** Send an EVENT message */
|
|
35
|
-
event(event: NostrEvent): Observable<PublishResponse>;
|
|
36
|
-
/** Send a REQ message */
|
|
37
|
-
req(filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
38
|
-
}
|
|
39
|
-
export interface IRelay extends MultiplexWebSocket, Nip01Actions, IRelayState {
|
|
46
|
+
export interface IRelay extends MultiplexWebSocket {
|
|
40
47
|
url: string;
|
|
41
48
|
message$: Observable<any>;
|
|
42
49
|
notice$: Observable<string>;
|
|
50
|
+
connected$: Observable<boolean>;
|
|
51
|
+
challenge$: Observable<string | null>;
|
|
52
|
+
authenticated$: Observable<boolean>;
|
|
53
|
+
notices$: Observable<string[]>;
|
|
43
54
|
readonly connected: boolean;
|
|
44
55
|
readonly authenticated: boolean;
|
|
45
56
|
readonly challenge: string | null;
|
|
46
57
|
readonly notices: string[];
|
|
58
|
+
/** Force close the connection */
|
|
59
|
+
close(): void;
|
|
60
|
+
/** Send a REQ message */
|
|
61
|
+
req(filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
62
|
+
/** Send an EVENT message */
|
|
63
|
+
event(event: NostrEvent): Observable<PublishResponse>;
|
|
47
64
|
/** Send an AUTH message */
|
|
48
|
-
auth(event: NostrEvent):
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
}>;
|
|
65
|
+
auth(event: NostrEvent): Promise<PublishResponse>;
|
|
66
|
+
/** Authenticate with the relay using a signer */
|
|
67
|
+
authenticate(signer: AuthSigner): Promise<PublishResponse>;
|
|
52
68
|
/** Send an EVENT message with retries */
|
|
53
|
-
publish(event: NostrEvent, opts?:
|
|
54
|
-
retries?: number;
|
|
55
|
-
}): Observable<PublishResponse>;
|
|
69
|
+
publish(event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse>;
|
|
56
70
|
/** Send a REQ message with retries */
|
|
57
|
-
request(filters: FilterInput, opts?:
|
|
58
|
-
id?: string;
|
|
59
|
-
retries?: number;
|
|
60
|
-
}): Observable<NostrEvent>;
|
|
71
|
+
request(filters: FilterInput, opts?: RequestOptions): Observable<NostrEvent>;
|
|
61
72
|
/** Open a subscription with retries */
|
|
62
|
-
subscription(filters: FilterInput, opts?:
|
|
63
|
-
id?: string;
|
|
64
|
-
retries?: number;
|
|
65
|
-
}): Observable<SubscriptionResponse>;
|
|
73
|
+
subscription(filters: FilterInput, opts?: SubscriptionOptions): Observable<SubscriptionResponse>;
|
|
66
74
|
}
|
|
67
|
-
export interface IGroup
|
|
75
|
+
export interface IGroup {
|
|
76
|
+
/** Send a REQ message */
|
|
77
|
+
req(filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
78
|
+
/** Send an EVENT message */
|
|
79
|
+
event(event: NostrEvent): Observable<PublishResponse>;
|
|
68
80
|
/** Send an EVENT message with retries */
|
|
69
|
-
publish(event: NostrEvent, opts?:
|
|
70
|
-
retries?: number;
|
|
71
|
-
}): Observable<PublishResponse>;
|
|
81
|
+
publish(event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse[]>;
|
|
72
82
|
/** Send a REQ message with retries */
|
|
73
|
-
request(filters: FilterInput, opts?:
|
|
74
|
-
id?: string;
|
|
75
|
-
retries?: number;
|
|
76
|
-
}): Observable<NostrEvent>;
|
|
83
|
+
request(filters: FilterInput, opts?: RequestOptions): Observable<NostrEvent>;
|
|
77
84
|
/** Open a subscription with retries */
|
|
78
|
-
subscription(filters: FilterInput, opts?:
|
|
79
|
-
id?: string;
|
|
80
|
-
retries?: number;
|
|
81
|
-
}): Observable<SubscriptionResponse>;
|
|
85
|
+
subscription(filters: FilterInput, opts?: SubscriptionOptions): Observable<SubscriptionResponse>;
|
|
82
86
|
}
|
|
83
87
|
export interface IPool {
|
|
84
|
-
/** Send an EVENT message */
|
|
85
|
-
event(relays: string[], event: NostrEvent): Observable<PublishResponse>;
|
|
86
|
-
/** Send a REQ message */
|
|
87
|
-
req(relays: string[], filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
88
88
|
/** Get or create a relay */
|
|
89
89
|
relay(url: string): IRelay;
|
|
90
90
|
/** Create a relay group */
|
|
91
91
|
group(relays: string[]): IGroup;
|
|
92
|
+
/** Removes a relay from the pool and defaults to closing the connection */
|
|
93
|
+
remove(relay: string | IRelay, close?: boolean): void;
|
|
94
|
+
/** Send a REQ message */
|
|
95
|
+
req(relays: string[], filters: FilterInput, id?: string): Observable<SubscriptionResponse>;
|
|
96
|
+
/** Send an EVENT message */
|
|
97
|
+
event(relays: string[], event: NostrEvent): Observable<PublishResponse>;
|
|
92
98
|
/** Send an EVENT message to relays with retries */
|
|
93
|
-
publish(relays: string[], event: NostrEvent, opts?:
|
|
94
|
-
retries?: number;
|
|
95
|
-
}): Observable<PublishResponse>;
|
|
99
|
+
publish(relays: string[], event: NostrEvent, opts?: PublishOptions): Promise<PublishResponse[]>;
|
|
96
100
|
/** Send a REQ message to relays with retries */
|
|
97
|
-
request(relays: string[], filters: FilterInput, opts?:
|
|
98
|
-
id?: string;
|
|
99
|
-
retries?: number;
|
|
100
|
-
}): Observable<NostrEvent>;
|
|
101
|
+
request(relays: string[], filters: FilterInput, opts?: RequestOptions): Observable<NostrEvent>;
|
|
101
102
|
/** Open a subscription to relays with retries */
|
|
102
|
-
subscription(relays: string[], filters: FilterInput, opts?:
|
|
103
|
-
id?: string;
|
|
104
|
-
retries?: number;
|
|
105
|
-
}): Observable<SubscriptionResponse>;
|
|
103
|
+
subscription(relays: string[], filters: FilterInput, opts?: SubscriptionOptions): Observable<SubscriptionResponse>;
|
|
106
104
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "applesauce-relay",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "3.0.0",
|
|
4
4
|
"description": "nostr relay communication framework built on rxjs",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -54,14 +54,14 @@
|
|
|
54
54
|
},
|
|
55
55
|
"dependencies": {
|
|
56
56
|
"@noble/hashes": "^1.7.1",
|
|
57
|
-
"applesauce-core": "^
|
|
57
|
+
"applesauce-core": "^3.0.0",
|
|
58
58
|
"nanoid": "^5.0.9",
|
|
59
59
|
"nostr-tools": "^2.13",
|
|
60
60
|
"rxjs": "^7.8.1"
|
|
61
61
|
},
|
|
62
62
|
"devDependencies": {
|
|
63
63
|
"@hirez_io/observer-spy": "^2.2.0",
|
|
64
|
-
"applesauce-signers": "^
|
|
64
|
+
"applesauce-signers": "^3.0.0",
|
|
65
65
|
"@vitest/expect": "^3.1.1",
|
|
66
66
|
"typescript": "^5.7.3",
|
|
67
67
|
"vitest": "^3.2.3",
|