chirli 0.1.0 → 0.2.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.
Files changed (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
package/dist/relay.js CHANGED
@@ -1,8 +1,8 @@
1
- import { RelayPool, DEFAULT_RELAY_TIMEOUTS } from './relay-pool.js';
2
- export { DEFAULT_RELAY_TIMEOUTS } from './relay-pool.js';
3
- import { RelayError } from './errors.js';
4
- import { randomUUID } from 'node:crypto';
5
- import { matchFilter } from 'nostr-tools';
1
+ import { RelayPool, DEFAULT_RELAY_TIMEOUTS, } from "./relay-pool.js";
2
+ export { DEFAULT_RELAY_TIMEOUTS } from "./relay-pool.js";
3
+ import { RelayError } from "./errors.js";
4
+ import { randomUUID } from "node:crypto";
5
+ import { matchFilter, } from "nostr-tools";
6
6
  // Internal optional capability: a custom Transport without a socket probe stays unknown.
7
7
  const socketProbes = new WeakMap();
8
8
  export function physicalConnectionState(transport, relay) {
@@ -10,16 +10,21 @@ export function physicalConnectionState(transport, relay) {
10
10
  }
11
11
  const localReadBoundaries = new WeakMap();
12
12
  /** Verified layers may use this local-window boundary; it is never supplied by event tags. */
13
- export function localReadBoundary(event) { return localReadBoundaries.get(event); }
13
+ export function localReadBoundary(event) {
14
+ return localReadBoundaries.get(event);
15
+ }
14
16
  const managedSubscribers = new WeakMap();
15
17
  /** Only SDK long-lived inbox demand opts into a local initial-read window. */
16
18
  export function subscribeInbox(transport, ...args) {
17
19
  const subscribe = managedSubscribers.get(transport);
18
- return subscribe ? subscribe('inbox', ...args) : transport.subscribe(...args);
20
+ return subscribe ? subscribe("inbox", ...args) : transport.subscribe(...args);
19
21
  }
20
22
  /** RPC response subscriptions are ready once REQ has been issued on the socket. */
21
23
  export function subscribeRequests(transport, ...args) {
22
- return managedSubscribers.get(transport)('requests', ...args);
24
+ const subscribe = managedSubscribers.get(transport);
25
+ if (!subscribe)
26
+ throw new Error("Transport does not support request subscriptions");
27
+ return subscribe("requests", ...args);
23
28
  }
24
29
  export class WebSocketTransport {
25
30
  sign;
@@ -34,19 +39,24 @@ export class WebSocketTransport {
34
39
  this.sign = sign;
35
40
  this.onTiming = onTiming;
36
41
  // Preserve the numeric constructor as an explicit override of operation budgets.
37
- const configured = typeof options === 'number' ? {
38
- connectionTimeoutMs: options,
39
- eoseTimeoutMs: options,
40
- publishTimeoutMs: options,
41
- authTimeoutMs: options
42
- } : options;
42
+ const configured = typeof options === "number"
43
+ ? {
44
+ connectionTimeoutMs: options,
45
+ eoseTimeoutMs: options,
46
+ publishTimeoutMs: options,
47
+ authTimeoutMs: options,
48
+ }
49
+ : options;
43
50
  const { maxConcurrentQueriesPerRelay = 5, ...durations } = configured;
44
- if (!Number.isSafeInteger(maxConcurrentQueriesPerRelay) || maxConcurrentQueriesPerRelay < 1 || maxConcurrentQueriesPerRelay > 1000) {
45
- throw new TypeError('maxConcurrentQueriesPerRelay must be in 1..1000');
51
+ if (!Number.isSafeInteger(maxConcurrentQueriesPerRelay) ||
52
+ maxConcurrentQueriesPerRelay < 1 ||
53
+ maxConcurrentQueriesPerRelay > 1000) {
54
+ throw new TypeError("maxConcurrentQueriesPerRelay must be in 1..1000");
46
55
  }
47
56
  this.maxConcurrentQueriesPerRelay = maxConcurrentQueriesPerRelay;
48
57
  const timeouts = {
49
- ...DEFAULT_RELAY_TIMEOUTS, ...durations
58
+ ...DEFAULT_RELAY_TIMEOUTS,
59
+ ...durations,
50
60
  };
51
61
  for (const [name, value] of Object.entries(timeouts)) {
52
62
  if (!Number.isSafeInteger(value) || value < 1 || value > 2147483647) {
@@ -56,53 +66,68 @@ export class WebSocketTransport {
56
66
  this.timeouts = Object.freeze(timeouts);
57
67
  this.timeoutMs = timeouts.eoseTimeoutMs;
58
68
  this.pool = new RelayPool(timeouts, sign);
59
- socketProbes.set(this, url => this.pool.isConnected(url));
69
+ socketProbes.set(this, (url) => this.pool.isConnected(url));
60
70
  managedSubscribers.set(this, (mode, relays, filter, receive, disconnect) => this.subscribeMode(relays, filter, receive, disconnect, mode));
61
71
  }
62
72
  timing(operation, url, kinds, start, error) {
63
73
  if (!this.onTiming) {
64
74
  return;
65
75
  }
66
- let relay = '(invalid relay URL)';
76
+ let relay = "(invalid relay URL)";
67
77
  try {
68
78
  const value = new URL(url);
69
- if (['ws:', 'wss:'].includes(value.protocol)) {
79
+ if (["ws:", "wss:"].includes(value.protocol)) {
70
80
  relay = value.origin;
71
81
  }
72
82
  }
73
- catch {
74
- }
83
+ catch { }
75
84
  const metric = {
76
85
  operation,
77
86
  relay,
78
- kinds: kinds.filter(kind => Number.isInteger(kind) && kind >= 0 && kind <= 65535),
87
+ kinds: kinds.filter((kind) => Number.isInteger(kind) && kind >= 0 && kind <= 65535),
79
88
  durationMs: Math.max(0, Math.round(performance.now() - start)),
80
- outcome: error === undefined ? 'ok' : 'error',
81
- ...(error instanceof RelayError ? {
82
- code: error.code
83
- } : {})
89
+ outcome: error === undefined ? "ok" : "error",
90
+ ...(error instanceof RelayError
91
+ ? {
92
+ code: error.code,
93
+ }
94
+ : {}),
84
95
  };
85
96
  try {
86
- void Promise.resolve(this.onTiming(metric)).catch(() => {
87
- });
97
+ void Promise.resolve(this.onTiming(metric)).catch(() => { });
88
98
  }
89
- catch { /* Observers cannot alter transport success or retries. */
99
+ catch {
100
+ /* Observers cannot alter transport success or retries. */
90
101
  }
91
102
  }
92
103
  subscribe(relays, filter, onEvent, onDisconnect) {
93
- return this.subscribeMode(relays, filter, onEvent, onDisconnect, 'strict');
104
+ return this.subscribeMode(relays, filter, onEvent, onDisconnect, "strict");
94
105
  }
95
106
  subscribeMode(relays, filter, onEvent, onDisconnect, mode, onAttempt) {
96
107
  const closers = [];
97
108
  let stopped = false;
98
- const ready = Promise.all([...new Set(relays)].map(url => new Promise((resolve, reject) => {
99
- let id = '';
109
+ const ready = Promise.all([...new Set(relays)].map((url) => new Promise((resolve, reject) => {
110
+ let id = "";
100
111
  let live = false, settled = false, ended = false, rawCount = 0, acceptedCount = 0;
101
112
  let boundary;
102
113
  let lease, sub;
103
114
  let hardTimer, authTimer;
104
- const error = (code, reason) => new RelayError(code === 'RELAY_EOSE_TIMEOUT' ? 'Relay EOSE timeout' : 'Relay subscription failed', { relay: url, operation: code.startsWith('RELAY_AUTH') ? 'auth' : 'subscribe', code, reason });
105
- const clear = () => { clearTimeout(hardTimer); clearTimeout(authTimer); hardTimer = undefined; authTimer = undefined; };
115
+ const error = (code, reason) => new RelayError(code === "RELAY_EOSE_TIMEOUT"
116
+ ? "Relay EOSE timeout"
117
+ : "Relay subscription failed", {
118
+ relay: url,
119
+ operation: code.startsWith("RELAY_AUTH")
120
+ ? "auth"
121
+ : "subscribe",
122
+ code,
123
+ reason,
124
+ });
125
+ const clear = () => {
126
+ clearTimeout(hardTimer);
127
+ clearTimeout(authTimer);
128
+ hardTimer = undefined;
129
+ authTimer = undefined;
130
+ };
106
131
  const retire = () => {
107
132
  if (!sub)
108
133
  return;
@@ -115,7 +140,11 @@ export class WebSocketTransport {
115
140
  if (!prior.closed)
116
141
  prior.close();
117
142
  };
118
- const finish = () => { settled = true; clear(); resolve(); };
143
+ const finish = () => {
144
+ settled = true;
145
+ clear();
146
+ resolve();
147
+ };
119
148
  const fail = (failure) => {
120
149
  if (ended || stopped)
121
150
  return;
@@ -137,14 +166,14 @@ export class WebSocketTransport {
137
166
  return;
138
167
  live = false;
139
168
  boundary = undefined;
140
- id = '';
169
+ id = "";
141
170
  retire();
142
- authTimer ??= setTimeout(() => fail(error('RELAY_AUTH_TIMEOUT')), this.timeouts.authTimeoutMs);
171
+ authTimer ??= setTimeout(() => fail(error("RELAY_AUTH_TIMEOUT")), this.timeouts.authTimeoutMs);
143
172
  };
144
173
  const request = () => {
145
- if (ended || stopped)
174
+ if (ended || stopped || !lease)
146
175
  return;
147
- if (lease?.authenticating) {
176
+ if (lease.authenticating) {
148
177
  waitAuth();
149
178
  return;
150
179
  }
@@ -159,43 +188,54 @@ export class WebSocketTransport {
159
188
  const attempt = id;
160
189
  onAttempt?.();
161
190
  // This caps repeated AUTH/replay cycles, not the library's EOSE timer.
162
- if (mode !== 'requests')
163
- hardTimer ??= setTimeout(() => fail(error('RELAY_EOSE_TIMEOUT')), Math.min(2147483647, this.timeouts.eoseTimeoutMs + this.timeouts.authTimeoutMs));
191
+ if (mode !== "requests")
192
+ hardTimer ??= setTimeout(() => fail(error("RELAY_EOSE_TIMEOUT")), Math.min(2147483647, this.timeouts.eoseTimeoutMs + this.timeouts.authTimeoutMs));
164
193
  sub = lease.subscribe(filter, {
165
- id, eoseTimeout: this.timeouts.eoseTimeoutMs,
166
- onevent: event => {
167
- if (ended || stopped || id !== attempt || lease?.authenticating || !matchFilter(filter, event))
194
+ id,
195
+ eoseTimeout: this.timeouts.eoseTimeoutMs,
196
+ onevent: (event) => {
197
+ if (ended ||
198
+ stopped ||
199
+ id !== attempt ||
200
+ lease?.authenticating ||
201
+ !matchFilter(filter, event))
168
202
  return;
169
203
  acceptedCount++;
170
204
  if (!live && boundary !== undefined)
171
205
  localReadBoundaries.set(event, boundary);
172
206
  try {
173
- onEvent(event, live ? 'live' : 'history');
207
+ onEvent(event, live ? "live" : "history");
208
+ }
209
+ catch {
210
+ /* Isolate caller callbacks from library diagnostics. */
174
211
  }
175
- catch { /* Isolate caller callbacks from library diagnostics. */ }
176
212
  },
177
213
  oneose: () => {
178
- if (ended || stopped || id !== attempt || lease?.authenticating || authTimer)
214
+ if (ended ||
215
+ stopped ||
216
+ id !== attempt ||
217
+ lease?.authenticating ||
218
+ authTimer)
179
219
  return;
180
- if (mode === 'requests')
220
+ if (mode === "requests")
181
221
  return;
182
222
  if (live) {
183
223
  // Filtered/invalid wire entries cannot make a capped strict page look complete.
184
- if (mode === 'strict' && rawCount !== acceptedCount) {
185
- fail(error('RELAY_HISTORY_INCOMPLETE'));
224
+ if (mode === "strict" && rawCount !== acceptedCount) {
225
+ fail(error("RELAY_HISTORY_INCOMPLETE"));
186
226
  return;
187
227
  }
188
228
  finish();
189
229
  }
190
- else if (mode === 'inbox') {
230
+ else if (mode === "inbox") {
191
231
  boundary = Date.now() / 1000;
192
232
  finish();
193
233
  }
194
234
  else
195
- fail(error('RELAY_EOSE_TIMEOUT'));
235
+ fail(error("RELAY_EOSE_TIMEOUT"));
196
236
  },
197
- onclose: reason => {
198
- reason = typeof reason === 'string' ? reason : '';
237
+ onclose: (reason) => {
238
+ reason = typeof reason === "string" ? reason : "";
199
239
  if (ended || stopped || id !== attempt)
200
240
  return;
201
241
  // The library has already removed/decremented this subscription.
@@ -204,47 +244,74 @@ export class WebSocketTransport {
204
244
  sub.receivedEose();
205
245
  sub = undefined;
206
246
  }
207
- if (this.sign && reason.startsWith('auth-required:')) {
247
+ if (this.sign && reason.startsWith("auth-required:")) {
208
248
  waitAuth();
209
249
  return;
210
250
  }
211
- fail(error(reason.startsWith('auth-required:') ? 'RELAY_AUTH_REQUIRED' : 'RELAY_SUBSCRIPTION_REJECTED', reason));
212
- }
251
+ fail(error(reason.startsWith("auth-required:")
252
+ ? "RELAY_AUTH_REQUIRED"
253
+ : "RELAY_SUBSCRIPTION_REJECTED", reason));
254
+ },
213
255
  });
214
256
  // The library matches filters before validating malformed events. An empty
215
257
  // local filter lets its verifier reject them quietly; the callback applies
216
258
  // the actual filter after verification. The original REQ is already sent.
217
259
  sub.filters = [{}];
218
- if (mode === 'requests')
260
+ if (mode === "requests")
219
261
  finish();
220
262
  };
221
- closers.push(() => { ended = true; clear(); retire(); lease?.release(); resolve(); });
263
+ closers.push(() => {
264
+ ended = true;
265
+ clear();
266
+ retire();
267
+ lease?.release();
268
+ resolve();
269
+ });
222
270
  try {
223
271
  lease = this.pool.acquire(url, {
224
- failed: fail, authenticating: waitAuth, authenticated: request,
225
- rawEvent: incoming => { if (incoming === id)
226
- rawCount++; },
227
- wireEose: incoming => {
228
- if (incoming !== id || ended || stopped || lease?.authenticating || authTimer)
272
+ failed: fail,
273
+ authenticating: waitAuth,
274
+ authenticated: request,
275
+ rawEvent: (incoming) => {
276
+ if (incoming === id)
277
+ rawCount++;
278
+ },
279
+ wireEose: (incoming) => {
280
+ if (incoming !== id ||
281
+ ended ||
282
+ stopped ||
283
+ lease?.authenticating ||
284
+ authTimer)
229
285
  return;
230
286
  live = true;
231
287
  boundary = undefined;
232
- }
288
+ },
233
289
  });
234
290
  void lease.ready.then(request, fail);
235
291
  }
236
292
  catch (failure) {
237
- fail(failure instanceof RelayError ? failure : error('RELAY_CONNECTION_FAILED'));
293
+ fail(failure instanceof RelayError
294
+ ? failure
295
+ : error("RELAY_CONNECTION_FAILED"));
238
296
  }
239
297
  }))).then(() => { });
240
- return { ready, close: () => { if (stopped)
241
- return; stopped = true; closers.forEach(close => close()); } };
298
+ return {
299
+ ready,
300
+ close: () => {
301
+ if (stopped)
302
+ return;
303
+ stopped = true;
304
+ closers.forEach((close) => {
305
+ close();
306
+ });
307
+ },
308
+ };
242
309
  }
243
310
  queuedQuery(url, task) {
244
- const closedError = () => new RelayError('Relay pool closed', {
311
+ const closedError = () => new RelayError("Relay pool closed", {
245
312
  relay: url,
246
- operation: 'connect',
247
- code: 'RELAY_CLOSED'
313
+ operation: "connect",
314
+ code: "RELAY_CLOSED",
248
315
  });
249
316
  if (this.closed) {
250
317
  return Promise.reject(closedError());
@@ -259,7 +326,8 @@ export class WebSocketTransport {
259
326
  let queue = this.queries.get(key);
260
327
  if (!queue) {
261
328
  queue = {
262
- active: 0, pending: []
329
+ active: 0,
330
+ pending: [],
263
331
  };
264
332
  this.queries.set(key, queue);
265
333
  }
@@ -267,7 +335,10 @@ export class WebSocketTransport {
267
335
  return new Promise((resolve, reject) => {
268
336
  const start = () => {
269
337
  current.active++;
270
- void Promise.resolve().then(task).then(resolve, reject).finally(() => {
338
+ void Promise.resolve()
339
+ .then(task)
340
+ .then(resolve, reject)
341
+ .finally(() => {
271
342
  current.active--;
272
343
  if (!this.closed) {
273
344
  current.pending.shift()?.start();
@@ -282,54 +353,63 @@ export class WebSocketTransport {
282
353
  }
283
354
  else {
284
355
  current.pending.push({
285
- start, cancel: () => reject(closedError())
356
+ start,
357
+ cancel: () => reject(closedError()),
286
358
  });
287
359
  }
288
360
  });
289
361
  }
290
362
  async query(relays, filter) {
291
363
  if (!relays.length) {
292
- throw new Error('No discovery relays');
364
+ throw new Error("No discovery relays");
293
365
  }
294
- const results = await Promise.allSettled([...new Set(relays)].map(relay => this.queuedQuery(relay, async () => {
366
+ const results = await Promise.allSettled([...new Set(relays)].map((relay) => this.queuedQuery(relay, async () => {
295
367
  const events = [], start = performance.now();
296
368
  let sub;
297
369
  try {
298
370
  sub = this.subscribeMode([relay], filter, (event, source) => {
299
- if (source === 'history') {
371
+ if (source === "history") {
300
372
  events.push(event);
301
373
  }
302
- }, undefined, 'strict', () => { events.length = 0; });
374
+ }, undefined, "strict", () => {
375
+ events.length = 0;
376
+ });
303
377
  await sub.ready;
304
- this.timing('query', relay, filter.kinds ?? [], start);
378
+ this.timing("query", relay, filter.kinds ?? [], start);
305
379
  return events;
306
380
  }
307
381
  catch (error) {
308
- this.timing('query', relay, filter.kinds ?? [], start, error);
382
+ this.timing("query", relay, filter.kinds ?? [], start, error);
309
383
  throw error;
310
384
  }
311
385
  finally {
312
386
  sub?.close();
313
387
  }
314
388
  })));
315
- const successful = results.filter((r) => r.status === 'fulfilled');
389
+ const successful = results.filter((r) => r.status === "fulfilled");
316
390
  if (!successful.length) {
317
391
  if (results.length === 1) {
318
392
  throw results[0].reason;
319
393
  }
320
- throw new AggregateError(results.map(r => r.reason), 'All discovery relays failed');
394
+ throw new AggregateError(results.map((r) => r.reason), "All discovery relays failed");
321
395
  }
322
396
  // Preserve per-relay results; callers still own cross-relay deduplication.
323
- return successful.flatMap(r => r.value);
397
+ return successful.flatMap((r) => r.value);
324
398
  }
325
399
  async publish(relays, event) {
326
400
  if (!relays.length)
327
- throw new Error('No delivery relays');
328
- await Promise.any([...new Set(relays)].map(url => new Promise((resolve, reject) => {
401
+ throw new Error("No delivery relays");
402
+ await Promise.any([...new Set(relays)].map((url) => new Promise((resolve, reject) => {
329
403
  const start = performance.now();
330
404
  let settled = false, generation = 0, attempted = false, authRetries = 0, lease;
331
405
  let authTimer, hardTimer;
332
- const error = (code, reason) => new RelayError('Relay publication failed', { relay: url, operation: code.startsWith('RELAY_AUTH') ? 'auth' : 'publish', code, reason, eventKind: event.kind });
406
+ const error = (code, reason) => new RelayError("Relay publication failed", {
407
+ relay: url,
408
+ operation: code.startsWith("RELAY_AUTH") ? "auth" : "publish",
409
+ code,
410
+ reason,
411
+ eventKind: event.kind,
412
+ });
333
413
  const finish = (failure) => {
334
414
  if (settled)
335
415
  return;
@@ -337,19 +417,19 @@ export class WebSocketTransport {
337
417
  clearTimeout(authTimer);
338
418
  clearTimeout(hardTimer);
339
419
  lease?.release();
340
- this.timing('publish', url, [event.kind], start, failure);
420
+ this.timing("publish", url, [event.kind], start, failure);
341
421
  failure ? reject(failure) : resolve();
342
422
  };
343
423
  const waitAuth = () => {
344
424
  if (settled)
345
425
  return;
346
426
  generation++;
347
- authTimer ??= setTimeout(() => finish(error('RELAY_AUTH_TIMEOUT')), this.timeouts.authTimeoutMs);
427
+ authTimer ??= setTimeout(() => finish(error("RELAY_AUTH_TIMEOUT")), this.timeouts.authTimeoutMs);
348
428
  };
349
429
  const publish = (afterAuth = false) => {
350
- if (settled)
430
+ if (settled || !lease)
351
431
  return;
352
- hardTimer ??= setTimeout(() => finish(error('RELAY_ACK_TIMEOUT')), Math.min(2147483647, this.timeouts.publishTimeoutMs + this.timeouts.authTimeoutMs));
432
+ hardTimer ??= setTimeout(() => finish(error("RELAY_ACK_TIMEOUT")), Math.min(2147483647, this.timeouts.publishTimeoutMs + this.timeouts.authTimeoutMs));
353
433
  if (lease?.authenticating) {
354
434
  waitAuth();
355
435
  return;
@@ -358,32 +438,46 @@ export class WebSocketTransport {
358
438
  authTimer = undefined;
359
439
  const replay = afterAuth && attempted;
360
440
  if (replay && authRetries++ >= 1) {
361
- finish(error('RELAY_AUTH_REQUIRED'));
441
+ finish(error("RELAY_AUTH_REQUIRED"));
362
442
  return;
363
443
  }
364
444
  attempted = true;
365
445
  const attempt = ++generation;
366
- void lease.publish(event, replay).then(() => { if (attempt === generation)
367
- finish(); }, failure => {
446
+ void lease.publish(event, replay).then(() => {
447
+ if (attempt === generation)
448
+ finish();
449
+ }, (failure) => {
368
450
  if (settled || attempt !== generation)
369
451
  return;
370
- const reason = failure instanceof Error ? failure.message : '';
371
- if (this.sign && reason.startsWith('auth-required:')) {
452
+ const reason = failure instanceof Error ? failure.message : "";
453
+ if (this.sign && reason.startsWith("auth-required:")) {
372
454
  if (authRetries >= 1)
373
- finish(error('RELAY_AUTH_REQUIRED', reason));
455
+ finish(error("RELAY_AUTH_REQUIRED", reason));
374
456
  else
375
457
  waitAuth();
376
458
  return;
377
459
  }
378
- finish(error(reason === 'publish timed out' ? 'RELAY_ACK_TIMEOUT' : reason.startsWith('auth-required:') ? 'RELAY_AUTH_REQUIRED' : 'RELAY_EVENT_REJECTED', reason));
460
+ finish(error(reason === "publish timed out"
461
+ ? "RELAY_ACK_TIMEOUT"
462
+ : reason.startsWith("auth-required:")
463
+ ? "RELAY_AUTH_REQUIRED"
464
+ : "RELAY_EVENT_REJECTED", reason));
379
465
  });
380
466
  };
381
467
  try {
382
- lease = this.pool.acquire(url, { failed: finish, authenticating: waitAuth, authenticated: () => publish(true), rawEvent: () => { }, wireEose: () => { } });
468
+ lease = this.pool.acquire(url, {
469
+ failed: finish,
470
+ authenticating: waitAuth,
471
+ authenticated: () => publish(true),
472
+ rawEvent: () => { },
473
+ wireEose: () => { },
474
+ });
383
475
  void lease.ready.then(() => publish(), finish);
384
476
  }
385
477
  catch (failure) {
386
- finish(failure instanceof RelayError ? failure : error('RELAY_CONNECTION_FAILED'));
478
+ finish(failure instanceof RelayError
479
+ ? failure
480
+ : error("RELAY_CONNECTION_FAILED"));
387
481
  }
388
482
  })));
389
483
  }
@@ -1,8 +1,8 @@
1
- import type { Next } from './bot-handlers.js';
1
+ import type { Next } from "./bot-handlers.js";
2
2
  export declare function markDeferredRequestFailure(context: object): void;
3
3
  export interface RequestTiming {
4
4
  readonly durationMs: number;
5
- readonly outcome: 'success' | 'failure';
5
+ readonly outcome: "success" | "failure";
6
6
  }
7
7
  export type RequestTimingObserver = (timing: Readonly<RequestTiming>) => void | Promise<void>;
8
8
  export interface RequestTimingOptions {
@@ -1,25 +1,37 @@
1
1
  // Internal identity-only signal: no body, raw exception or reply-capable context is exposed.
2
2
  const deferredFailures = new WeakSet();
3
- export function markDeferredRequestFailure(context) { deferredFailures.add(context); }
3
+ export function markDeferredRequestFailure(context) {
4
+ deferredFailures.add(context);
5
+ }
4
6
  /** Time the downstream middleware/command chain without inspecting any context or error data. */
5
7
  export function requestTiming(options) {
6
8
  const observer = options?.onTiming;
7
- if (typeof observer !== 'function')
8
- throw new TypeError('requestTiming requires an onTiming observer');
9
+ if (typeof observer !== "function")
10
+ throw new TypeError("requestTiming requires an onTiming observer");
9
11
  return async (_context, next) => {
10
12
  const start = performance.now();
11
- let outcome = 'failure';
13
+ let outcome = "failure";
12
14
  try {
13
15
  await next();
14
- outcome = ((typeof _context === 'object' && _context !== null) || typeof _context === 'function') && deferredFailures.has(_context) ? 'failure' : 'success';
16
+ outcome =
17
+ ((typeof _context === "object" && _context !== null) ||
18
+ typeof _context === "function") &&
19
+ deferredFailures.has(_context)
20
+ ? "failure"
21
+ : "success";
15
22
  }
16
23
  finally {
17
- const metric = Object.freeze({ durationMs: Math.max(0, performance.now() - start), outcome });
24
+ const metric = Object.freeze({
25
+ durationMs: Math.max(0, performance.now() - start),
26
+ outcome,
27
+ });
18
28
  try {
19
29
  // Monitoring cannot delay/replace processing or turn success into a retryable failure.
20
30
  void Promise.resolve(observer(metric)).catch(() => { });
21
31
  }
22
- catch { /* Observer exceptions are isolated, including while unwinding a handler failure. */ }
32
+ catch {
33
+ /* Observer exceptions are isolated, including while unwinding a handler failure. */
34
+ }
23
35
  }
24
36
  };
25
37
  }
package/dist/session.js CHANGED
@@ -1,10 +1,10 @@
1
1
  /** A message sees its own writes. Commit once after successful processing. */
2
2
  export function messageSession(store, conversation) {
3
3
  let snapshot;
4
- const load = () => snapshot ??= Promise.resolve().then(async () => {
5
- const data = await store.get(conversation) ?? {};
4
+ const load = () => (snapshot ??= Promise.resolve().then(async () => {
5
+ const data = (await store.get(conversation)) ?? {};
6
6
  return structuredClone(data);
7
- });
7
+ }));
8
8
  let writes = Object.create(null);
9
9
  const removals = new Set();
10
10
  let cleared = false;
@@ -21,7 +21,7 @@ export function messageSession(store, conversation) {
21
21
  },
22
22
  setItem(key, value) {
23
23
  if (value === undefined)
24
- throw new TypeError('Use removeItem to delete a session value');
24
+ throw new TypeError("Use removeItem to delete a session value");
25
25
  writes[key] = structuredClone(value);
26
26
  removals.delete(key);
27
27
  },
@@ -40,7 +40,9 @@ export function messageSession(store, conversation) {
40
40
  async commit() {
41
41
  if (!cleared && !Object.keys(writes).length && !removals.size)
42
42
  return;
43
- const updated = cleared ? { ...writes } : { ...await load(), ...writes };
43
+ const updated = cleared
44
+ ? { ...writes }
45
+ : { ...(await load()), ...writes };
44
46
  for (const key of removals)
45
47
  delete updated[key];
46
48
  await store.set(conversation, updated);
package/dist/signer.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Event, EventTemplate } from 'nostr-tools';
1
+ import type { Event, EventTemplate } from "nostr-tools";
2
2
  /** Account capabilities only: callers never inspect signer type or secret material. */
3
3
  export interface Signer {
4
4
  getPublicKey(): Promise<string>;
@@ -1,5 +1,5 @@
1
- import { type Event, type Filter } from 'nostr-tools';
2
- import { AbstractSimplePool, type SubscribeManyParams } from 'nostr-tools/abstract-pool';
1
+ import { type Event, type Filter } from "nostr-tools";
2
+ import { AbstractSimplePool, type SubscribeManyParams } from "nostr-tools/abstract-pool";
3
3
  export declare function bunkerRelayURLs(values: string[]): string[];
4
4
  /** Bridge the two pool operations used by nostr-tools' BunkerSigner. */
5
5
  export declare class BunkerRelayPool extends AbstractSimplePool {