@private.me/xbind 3.0.2 → 3.0.4

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 (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,456 +1 @@
1
- /**
2
- * @module event-emitter
3
- * Type-safe event emitter for xBind agent events.
4
- *
5
- * Provides event-driven architecture for agent lifecycle events:
6
- * - message-sent: Emitted when a message is successfully sent
7
- * - message-received: Emitted when a message is received
8
- * - key-rotated: Emitted when encryption keys are rotated
9
- * - error: Emitted when an error occurs
10
- * - connection-status: Emitted when connection state changes
11
- */
12
- import { ok, err } from"./_deps/shared/index.js";
13
- /**
14
- * Type-safe event emitter for xBind agent events.
15
- *
16
- * Features:
17
- * - Type-safe event names and payloads
18
- * - Listener priority support
19
- * - Once listeners
20
- * - Event bubbling to parent emitters
21
- * - Async listener support with error handling
22
- * - Memory leak detection
23
- *
24
- * @example
25
- * ```typescript
26
- * const emitter = new XBindEventEmitter();
27
- *
28
- * // Register listener
29
- * emitter.on('message-received', (event) => {
30
- * console.log('Received from:', event.senderDid);
31
- * });
32
- *
33
- * // Register one-time listener
34
- * emitter.once('connection-status', (event) => {
35
- * console.log('Status:', event.status);
36
- * });
37
- *
38
- * // Emit event
39
- * await emitter.emit('message-received', {
40
- * type: 'message-received',
41
- * timestamp: new Date().toISOString(),
42
- * eventId: '123',
43
- * senderDid: 'did:key:z6Mk...',
44
- * message: { payload: 'Hello' },
45
- * messageId: 'msg-1',
46
- * verified: true
47
- * });
48
- * ```
49
- */
50
- export class XBindEventEmitter {
51
- listeners = new Map();
52
- parent;
53
- disposed = false;
54
- eventCounter = 0;
55
- /** Maximum listeners per event type before warning (0 = unlimited) */
56
- maxListeners = 10;
57
- /** Whether warnings are enabled */
58
- warningsEnabled = true;
59
- /**
60
- * Create a new event emitter.
61
- *
62
- * @param parent - Optional parent emitter for event bubbling
63
- */
64
- constructor(parent) {
65
- this.parent = parent;
66
- }
67
- /**
68
- * Register an event listener.
69
- *
70
- * @param eventType - Event type to listen for
71
- * @param listener - Listener function
72
- * @param options - Listener options (priority, once)
73
- * @returns This emitter for chaining
74
- *
75
- * @example
76
- * ```typescript
77
- * emitter.on('error', (event) => {
78
- * console.error('Error:', event.message);
79
- * }, { priority: 10 });
80
- * ```
81
- */
82
- on(eventType, listener, options = {}) {
83
- this.checkDisposed();
84
- if (typeof listener !== 'function') {
85
- throw new Error('Listener must be a function');
86
- }
87
- const listeners = this.listeners.get(eventType) ?? [];
88
- const registered = {
89
- listener: listener,
90
- once: options.once ?? false,
91
- priority: options.priority ?? 0,
92
- };
93
- listeners.push(registered);
94
- // Sort by priority (highest first)
95
- listeners.sort((a, b) => b.priority - a.priority);
96
- this.listeners.set(eventType, listeners);
97
- // Check for potential memory leaks
98
- if (this.warningsEnabled && this.maxListeners > 0 && listeners.length > this.maxListeners) {
99
- // eslint-disable-next-line no-console
100
- console.warn(`[xBind EventEmitter] Possible memory leak detected: ${listeners.length} listeners for event '${eventType}'. ` +
101
- `Use emitter.setMaxListeners() to increase limit.`);
102
- }
103
- return this;
104
- }
105
- /**
106
- * Register a one-time event listener.
107
- * Listener is automatically removed after first invocation.
108
- *
109
- * @param eventType - Event type to listen for
110
- * @param listener - Listener function
111
- * @param options - Listener options (priority)
112
- * @returns This emitter for chaining
113
- *
114
- * @example
115
- * ```typescript
116
- * emitter.once('connection-status', (event) => {
117
- * console.log('First status change:', event.status);
118
- * });
119
- * ```
120
- */
121
- once(eventType, listener, options = {}) {
122
- return this.on(eventType, listener, { ...options, once: true });
123
- }
124
- /**
125
- * Remove an event listener.
126
- *
127
- * @param eventType - Event type
128
- * @param listener - Listener function to remove
129
- * @returns This emitter for chaining
130
- *
131
- * @example
132
- * ```typescript
133
- * const handler = (event) => console.log(event);
134
- * emitter.on('error', handler);
135
- * emitter.off('error', handler);
136
- * ```
137
- */
138
- off(eventType, listener) {
139
- this.checkDisposed();
140
- const listeners = this.listeners.get(eventType);
141
- if (!listeners)
142
- return this;
143
- const filtered = listeners.filter(l => l.listener !== listener);
144
- if (filtered.length === 0) {
145
- this.listeners.delete(eventType);
146
- }
147
- else {
148
- this.listeners.set(eventType, filtered);
149
- }
150
- return this;
151
- }
152
- /**
153
- * Remove all listeners for an event type, or all listeners if no type specified.
154
- *
155
- * @param eventType - Optional event type (removes all if not specified)
156
- * @returns This emitter for chaining
157
- *
158
- * @example
159
- * ```typescript
160
- * emitter.removeAllListeners('error'); // Remove all error listeners
161
- * emitter.removeAllListeners(); // Remove all listeners
162
- * ```
163
- */
164
- removeAllListeners(eventType) {
165
- this.checkDisposed();
166
- if (eventType) {
167
- this.listeners.delete(eventType);
168
- }
169
- else {
170
- this.listeners.clear();
171
- }
172
- return this;
173
- }
174
- /**
175
- * Emit an event to all registered listeners.
176
- * Listeners are called in priority order (highest first).
177
- * Async listeners are awaited in sequence.
178
- *
179
- * @param eventType - Event type to emit
180
- * @param event - Event payload
181
- * @param options - Emission options (bubble, stopPropagation)
182
- * @returns Result indicating success or first error encountered
183
- *
184
- * @example
185
- * ```typescript
186
- * await emitter.emit('error', {
187
- * type: 'error',
188
- * timestamp: new Date().toISOString(),
189
- * eventId: '123',
190
- * code: 'NETWORK_ERROR',
191
- * message: 'Connection failed',
192
- * context: 'transport'
193
- * });
194
- * ```
195
- */
196
- async emit(eventType, event, options = {}) {
197
- this.checkDisposed();
198
- // Add standard fields if not present
199
- const fullEvent = {
200
- ...event,
201
- eventId: options.eventId ?? this.generateEventId(),
202
- timestamp: new Date().toISOString(),
203
- };
204
- const listeners = this.listeners.get(eventType);
205
- if (listeners && listeners.length > 0) {
206
- // Create a copy to avoid issues if listeners modify the array
207
- const listenersCopy = [...listeners];
208
- for (const registered of listenersCopy) {
209
- try {
210
- await registered.listener(fullEvent);
211
- // Remove once listeners
212
- if (registered.once) {
213
- this.off(eventType, registered.listener);
214
- }
215
- // Stop propagation if requested
216
- if (options.stopPropagation) {
217
- return ok(undefined);
218
- }
219
- }
220
- catch (error) {
221
- // Log error but continue with other listeners
222
- // eslint-disable-next-line no-console
223
- console.error(`[xBind EventEmitter] Error in listener for '${eventType}':`, error);
224
- // Return first error encountered
225
- return err('LISTENER_ERROR');
226
- }
227
- }
228
- }
229
- // Bubble to parent if requested
230
- if (options.bubble !== false && this.parent) {
231
- return this.parent.emit(eventType, event, { ...options, bubble: true });
232
- }
233
- return ok(undefined);
234
- }
235
- /**
236
- * Check if there are any listeners for an event type.
237
- *
238
- * @param eventType - Event type to check
239
- * @returns True if there are listeners
240
- *
241
- * @example
242
- * ```typescript
243
- * if (emitter.hasListeners('error')) {
244
- * await emitter.emit('error', errorEvent);
245
- * }
246
- * ```
247
- */
248
- hasListeners(eventType) {
249
- const listeners = this.listeners.get(eventType);
250
- return listeners !== undefined && listeners.length > 0;
251
- }
252
- /**
253
- * Get the number of listeners for an event type.
254
- *
255
- * @param eventType - Event type
256
- * @returns Number of listeners
257
- *
258
- * @example
259
- * ```typescript
260
- * const count = emitter.listenerCount('message-received');
261
- * console.log(`${count} listeners registered`);
262
- * ```
263
- */
264
- listenerCount(eventType) {
265
- const listeners = this.listeners.get(eventType);
266
- return listeners?.length ?? 0;
267
- }
268
- /**
269
- * Get all registered event types.
270
- *
271
- * @returns Array of event types with active listeners
272
- *
273
- * @example
274
- * ```typescript
275
- * const events = emitter.eventNames();
276
- * console.log('Active events:', events);
277
- * ```
278
- */
279
- eventNames() {
280
- return Array.from(this.listeners.keys());
281
- }
282
- /**
283
- * Set the maximum number of listeners per event before warning.
284
- * Use 0 for unlimited listeners.
285
- *
286
- * @param n - Maximum listeners (0 = unlimited)
287
- * @returns This emitter for chaining
288
- *
289
- * @example
290
- * ```typescript
291
- * emitter.setMaxListeners(20); // Allow up to 20 listeners
292
- * emitter.setMaxListeners(0); // Unlimited
293
- * ```
294
- */
295
- setMaxListeners(n) {
296
- if (n < 0 || !Number.isInteger(n)) {
297
- throw new Error('Max listeners must be a non-negative integer');
298
- }
299
- this.maxListeners = n;
300
- return this;
301
- }
302
- /**
303
- * Get the maximum number of listeners per event.
304
- *
305
- * @returns Maximum listeners (0 = unlimited)
306
- */
307
- getMaxListeners() {
308
- return this.maxListeners;
309
- }
310
- /**
311
- * Enable or disable memory leak warnings.
312
- *
313
- * @param enabled - Whether warnings are enabled
314
- * @returns This emitter for chaining
315
- */
316
- setWarningsEnabled(enabled) {
317
- this.warningsEnabled = enabled;
318
- return this;
319
- }
320
- /**
321
- * Set the parent emitter for event bubbling.
322
- *
323
- * @param parent - Parent emitter (undefined to remove parent)
324
- * @returns This emitter for chaining
325
- *
326
- * @example
327
- * ```typescript
328
- * const parent = new XBindEventEmitter();
329
- * const child = new XBindEventEmitter();
330
- * child.setParent(parent);
331
- *
332
- * parent.on('error', (event) => console.log('Parent received:', event));
333
- * await child.emit('error', errorEvent, { bubble: true });
334
- * ```
335
- */
336
- setParent(parent) {
337
- this.parent = parent;
338
- return this;
339
- }
340
- /**
341
- * Get the parent emitter.
342
- *
343
- * @returns Parent emitter or undefined
344
- */
345
- getParent() {
346
- return this.parent;
347
- }
348
- /**
349
- * Wait for a specific event to be emitted.
350
- * Returns a promise that resolves with the event payload.
351
- *
352
- * @param eventType - Event type to wait for
353
- * @param timeout - Optional timeout in milliseconds
354
- * @returns Promise resolving to event or rejecting on timeout
355
- *
356
- * @example
357
- * ```typescript
358
- * const event = await emitter.waitFor('connection-status', 5000);
359
- * console.log('Status changed to:', event.status);
360
- * ```
361
- */
362
- waitFor(eventType, timeout) {
363
- return new Promise((resolve, reject) => {
364
- let timeoutId;
365
- const handler = (event) => {
366
- if (timeoutId)
367
- clearTimeout(timeoutId);
368
- resolve(event);
369
- };
370
- this.once(eventType, handler);
371
- if (timeout !== undefined && timeout > 0) {
372
- timeoutId = setTimeout(() => {
373
- this.off(eventType, handler);
374
- reject(new Error(`Timeout waiting for event '${eventType}' after ${timeout}ms`));
375
- }, timeout);
376
- }
377
- });
378
- }
379
- /**
380
- * Dispose the event emitter and remove all listeners.
381
- * After disposal, no events can be emitted and listeners cannot be registered.
382
- *
383
- * @example
384
- * ```typescript
385
- * emitter.dispose();
386
- * ```
387
- */
388
- dispose() {
389
- this.disposed = true;
390
- this.listeners.clear();
391
- this.parent = undefined;
392
- }
393
- /**
394
- * Check if the emitter has been disposed.
395
- *
396
- * @returns True if disposed
397
- */
398
- isDisposed() {
399
- return this.disposed;
400
- }
401
- checkDisposed() {
402
- if (this.disposed) {
403
- throw new Error('EventEmitter has been disposed');
404
- }
405
- }
406
- generateEventId() {
407
- return `evt-${Date.now()}-${++this.eventCounter}`;
408
- }
409
- }
410
- /**
411
- * Create a scoped event emitter that only emits specific event types.
412
- * Useful for isolating event channels.
413
- *
414
- * @param parent - Parent emitter
415
- * @param allowedEvents - Array of allowed event types
416
- * @returns Scoped event emitter
417
- *
418
- * @example
419
- * ```typescript
420
- * const parent = new XBindEventEmitter();
421
- * const errorOnly = createScopedEmitter(parent, ['error']);
422
- *
423
- * errorOnly.emit('error', errorEvent); // OK
424
- * errorOnly.emit('message-sent', event); // TypeScript error
425
- * ```
426
- */
427
- export function createScopedEmitter(parent, allowedEvents) {
428
- const emitter = new XBindEventEmitter(parent);
429
- const allowedSet = new Set(allowedEvents);
430
- return {
431
- on: (type, listener, options) => {
432
- if (!allowedSet.has(type)) {
433
- throw new Error(`Event type '${String(type)}' not allowed in scoped emitter`);
434
- }
435
- return emitter.on(type, listener, options);
436
- },
437
- once: (type, listener, options) => {
438
- if (!allowedSet.has(type)) {
439
- throw new Error(`Event type '${String(type)}' not allowed in scoped emitter`);
440
- }
441
- return emitter.once(type, listener, options);
442
- },
443
- off: (type, listener) => {
444
- return emitter.off(type, listener);
445
- },
446
- emit: (type, event, options) => {
447
- if (!allowedSet.has(type)) {
448
- return Promise.resolve(err('INVALID_EVENT_TYPE'));
449
- }
450
- return emitter.emit(type, event, options);
451
- },
452
- hasListeners: (type) => emitter.hasListeners(type),
453
- listenerCount: (type) => emitter.listenerCount(type),
454
- dispose: () => emitter.dispose(),
455
- };
456
- }
1
+ import{ok,err}from"./_deps/shared/index.js";export class XBindEventEmitter{listeners=new Map;parent;disposed=!1;eventCounter=0;maxListeners=10;warningsEnabled=!0;constructor(e){this.parent=e}on(e,t,s={}){if(this.checkDisposed(),"function"!=typeof t)throw new Error("Listener must be a function");const r=this.listeners.get(e)??[],n={listener:t,once:s.once??!1,priority:s.priority??0};return r.push(n),r.sort((e,t)=>t.priority-e.priority),this.listeners.set(e,r),this.warningsEnabled&&this.maxListeners>0&&r.length>this.maxListeners&&console.warn(`[xBind EventEmitter] Possible memory leak detected: ${r.length} listeners for event '${e}'. Use emitter.setMaxListeners() to increase limit.`),this}once(e,t,s={}){return this.on(e,t,{...s,once:!0})}off(e,t){this.checkDisposed();const s=this.listeners.get(e);if(!s)return this;const r=s.filter(e=>e.listener!==t);return 0===r.length?this.listeners.delete(e):this.listeners.set(e,r),this}removeAllListeners(e){return this.checkDisposed(),e?this.listeners.delete(e):this.listeners.clear(),this}async emit(e,t,s={}){this.checkDisposed();const r={...t,eventId:s.eventId??this.generateEventId(),timestamp:(new Date).toISOString()},n=this.listeners.get(e);if(n&&n.length>0){const t=[...n];for(const n of t)try{if(await n.listener(r),n.once&&this.off(e,n.listener),s.stopPropagation)return ok(void 0)}catch(t){return console.error(`[xBind EventEmitter] Error in listener for '${e}':`,t),err("LISTENER_ERROR")}}return!1!==s.bubble&&this.parent?this.parent.emit(e,t,{...s,bubble:!0}):ok(void 0)}hasListeners(e){const t=this.listeners.get(e);return void 0!==t&&t.length>0}listenerCount(e){const t=this.listeners.get(e);return t?.length??0}eventNames(){return Array.from(this.listeners.keys())}setMaxListeners(e){if(e<0||!Number.isInteger(e))throw new Error("Max listeners must be a non-negative integer");return this.maxListeners=e,this}getMaxListeners(){return this.maxListeners}setWarningsEnabled(e){return this.warningsEnabled=e,this}setParent(e){return this.parent=e,this}getParent(){return this.parent}waitFor(e,t){return new Promise((s,r)=>{let n;const i=e=>{n&&clearTimeout(n),s(e)};this.once(e,i),void 0!==t&&t>0&&(n=setTimeout(()=>{this.off(e,i),r(new Error(`Timeout waiting for event '${e}' after ${t}ms`))},t))})}dispose(){this.disposed=!0,this.listeners.clear(),this.parent=void 0}isDisposed(){return this.disposed}checkDisposed(){if(this.disposed)throw new Error("EventEmitter has been disposed")}generateEventId(){return`evt-${Date.now()}-${++this.eventCounter}`}}export function createScopedEmitter(e,t){const s=new XBindEventEmitter(e),r=new Set(t);return{on:(e,t,n)=>{if(!r.has(e))throw new Error(`Event type '${String(e)}' not allowed in scoped emitter`);return s.on(e,t,n)},once:(e,t,n)=>{if(!r.has(e))throw new Error(`Event type '${String(e)}' not allowed in scoped emitter`);return s.once(e,t,n)},off:(e,t)=>s.off(e,t),emit:(e,t,n)=>r.has(e)?s.emit(e,t,n):Promise.resolve(err("INVALID_EVENT_TYPE")),hasListeners:e=>s.hasListeners(e),listenerCount:e=>s.listenerCount(e),dispose:()=>s.dispose()}}
@@ -1,4 +1,4 @@
1
- type AnyWebSocket = any;
1
+ type AnyWebSocket = unknown;
2
2
  /**
3
3
  * Gateway connection state manager.
4
4
  *
@@ -1,51 +1 @@
1
- /**
2
- * Gateway connection state manager.
3
- *
4
- * Online-only model: State evaporates immediately on disconnect.
5
- * No 12-hour windows, no persistent state.
6
- *
7
- * Note: WebSocket type is runtime-dependent (browser WebSocket or 'ws' package).
8
- */
9
- export class GatewayConnectionState {
10
- connections = new Map(); // did → socket
11
- /**
12
- * Register agent connection.
13
- *
14
- * @param did - DID of the connecting agent
15
- * @param socket - WebSocket connection (browser or Node.js 'ws' package)
16
- */
17
- connect(did, socket) {
18
- this.connections.set(did, socket);
19
- // Handle close event (works for both browser and Node.js ws)
20
- if (typeof socket.on === 'function') {
21
- // Node.js 'ws' package style
22
- socket.on('close', () => {
23
- this.connections.delete(did); // Immediate evaporation
24
- });
25
- }
26
- else if (socket.addEventListener) {
27
- // Browser WebSocket style
28
- socket.addEventListener('close', () => {
29
- this.connections.delete(did);
30
- });
31
- }
32
- }
33
- /**
34
- * Check if agent is currently online.
35
- */
36
- isOnline(did) {
37
- return this.connections.has(did);
38
- }
39
- /**
40
- * Get WebSocket for online agent (or null if offline).
41
- */
42
- getSocket(did) {
43
- return this.connections.get(did) ?? null;
44
- }
45
- /**
46
- * Get all online DIDs.
47
- */
48
- getOnlineDids() {
49
- return Array.from(this.connections.keys());
50
- }
51
- }
1
+ export class GatewayConnectionState{connections=new Map;connect(n,e){this.connections.set(n,e),"function"==typeof e.on?e.on("close",()=>{this.connections.delete(n)}):e.addEventListener&&e.addEventListener("close",()=>{this.connections.delete(n)})}isOnline(n){return this.connections.has(n)}getSocket(n){return this.connections.get(n)??null}getOnlineDids(){return Array.from(this.connections.keys())}}
@@ -1,116 +1 @@
1
- /**
2
- * Gateway transport adapter for delivering envelopes to Xail inbox users.
3
- *
4
- * Sends envelopes via POST /gateway/deliver on the hosted gateway API.
5
- * For agent-to-agent (M2M), use HttpsTransportAdapter with direct URLs.
6
- * Optionally polls for incoming messages.
7
- */
8
- import { ok, err } from"./_deps/shared/index.js";
9
- /**
10
- * Transport adapter for the Xail Gateway.
11
- *
12
- * Sends envelopes via POST /gateway/deliver with API key auth.
13
- * Optionally polls GET /gateway/messages/:did for incoming messages.
14
- */
15
- export class GatewayTransport {
16
- apiKey;
17
- gateway;
18
- timeoutMs;
19
- fetchFn;
20
- pollIntervalMs;
21
- handlers = [];
22
- pollTimer = null;
23
- senderDid = null;
24
- constructor(opts) {
25
- this.apiKey = opts.apiKey;
26
- this.gateway = opts.gateway.replace(/\/$/, '');
27
- this.timeoutMs = opts.timeoutMs ?? 15_000;
28
- this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
29
- this.pollIntervalMs = opts.pollIntervalMs ?? 0;
30
- }
31
- /**
32
- * Send a signed envelope to a recipient via the gateway.
33
- * @param envelope - The signed transport envelope.
34
- * @param _recipientDid - Recipient DID (already in envelope.recipient).
35
- * @returns Success or transport error.
36
- */
37
- async send(envelope, _recipientDid) {
38
- const url = `${this.gateway}/gateway/deliver`;
39
- try {
40
- const controller = new AbortController();
41
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
42
- const response = await this.fetchFn(url, {
43
- method: 'POST',
44
- headers: {
45
- 'Content-Type': 'application/json',
46
- 'Authorization': `Bearer ${this.apiKey}`,
47
- },
48
- body: JSON.stringify(envelope),
49
- signal: controller.signal,
50
- });
51
- clearTimeout(timer);
52
- if (!response.ok) {
53
- return err(response.status === 404
54
- ? 'RECIPIENT_UNREACHABLE'
55
- : 'SEND_FAILED');
56
- }
57
- return ok(undefined);
58
- }
59
- catch (e) {
60
- if (e instanceof DOMException && e.name === 'AbortError') {
61
- return err('TIMEOUT');
62
- }
63
- return err('NETWORK_ERROR');
64
- }
65
- }
66
- /** Register a handler for incoming envelopes. */
67
- onReceive(handler) {
68
- this.handlers.push(handler);
69
- }
70
- /**
71
- * Start polling for incoming messages.
72
- * Must be called after Agent.create() sets the sender DID.
73
- * @param did - The agent's own DID for polling.
74
- */
75
- startPolling(did) {
76
- this.senderDid = did;
77
- if (this.pollIntervalMs > 0 && !this.pollTimer) {
78
- this.pollTimer = setInterval(() => void this.poll(), this.pollIntervalMs);
79
- }
80
- }
81
- /** Shut down the transport (stop polling, clear handlers). */
82
- dispose() {
83
- if (this.pollTimer) {
84
- clearInterval(this.pollTimer);
85
- this.pollTimer = null;
86
- }
87
- this.handlers = [];
88
- }
89
- /** Poll for incoming messages and dispatch to handlers. */
90
- async poll() {
91
- if (!this.senderDid)
92
- return;
93
- try {
94
- const url = `${this.gateway}/gateway/messages/${encodeURIComponent(this.senderDid)}`;
95
- const res = await this.fetchFn(url, {
96
- headers: { Authorization: `Bearer ${this.apiKey}` },
97
- });
98
- if (!res.ok)
99
- return;
100
- const data = (await res.json());
101
- for (const msg of data.messages) {
102
- for (const handler of this.handlers) {
103
- handler(msg.envelope);
104
- }
105
- // Ack delivery
106
- await this.fetchFn(`${this.gateway}/gateway/ack/${msg.id}`, {
107
- method: 'POST',
108
- headers: { Authorization: `Bearer ${this.apiKey}` },
109
- });
110
- }
111
- }
112
- catch {
113
- // Silent failure — polling errors are non-fatal
114
- }
115
- }
116
- }
1
+ import{ok,err}from"./_deps/shared/index.js";export class GatewayTransport{apiKey;gateway;timeoutMs;fetchFn;pollIntervalMs;handlers=[];pollTimer=null;senderDid=null;constructor(e){this.apiKey=e.apiKey,this.gateway=e.gateway.replace(/\/$/,""),this.timeoutMs=e.timeoutMs??15e3,this.fetchFn=e.fetch??globalThis.fetch.bind(globalThis),this.pollIntervalMs=e.pollIntervalMs??0}async send(e,t){const s=`${this.gateway}/gateway/deliver`;try{const t=new AbortController,i=setTimeout(()=>t.abort(),this.timeoutMs),a=await this.fetchFn(s,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify(e),signal:t.signal});return clearTimeout(i),a.ok?ok(void 0):err(404===a.status?"RECIPIENT_UNREACHABLE":"SEND_FAILED")}catch(e){return e instanceof DOMException&&"AbortError"===e.name?err("TIMEOUT"):err("NETWORK_ERROR")}}onReceive(e){this.handlers.push(e)}startPolling(e){this.senderDid=e,this.pollIntervalMs>0&&!this.pollTimer&&(this.pollTimer=setInterval(()=>{this.poll()},this.pollIntervalMs))}dispose(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null),this.handlers=[]}async poll(){if(this.senderDid)try{const e=`${this.gateway}/gateway/messages/${encodeURIComponent(this.senderDid)}`,t=await this.fetchFn(e,{headers:{Authorization:`Bearer ${this.apiKey}`}});if(!t.ok)return;const s=await t.json();for(const e of s.messages){for(const t of this.handlers)t(e.envelope);await this.fetchFn(`${this.gateway}/gateway/ack/${e.id}`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`}})}}catch{}}}