@private.me/xbind 1.3.5 → 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/LICENSES.md +212 -0
- package/README.md +388 -6
- package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
- package/dist-standalone/_deps/shared/cjs/errors.js +1 -639
- package/dist-standalone/_deps/shared/cjs/index.js +1 -496
- package/dist-standalone/_deps/shared/cjs/types.js +1 -317
- package/dist-standalone/_deps/shared/errors.js +1 -255
- package/dist-standalone/_deps/shared/index.js +1 -74
- package/dist-standalone/_deps/shared/types.js +1 -90
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
- package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
- package/dist-standalone/_deps/ux-helpers/index.js +1 -1
- package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
- package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
- package/dist-standalone/_deps/ux-helpers/search.js +1 -1
- package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
- package/dist-standalone/_deps/xchange/errors.js +1 -1
- package/dist-standalone/_deps/xchange/index.js +1 -1
- package/dist-standalone/_deps/xchange/invite-client.js +1 -1
- package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
- package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
- package/dist-standalone/_deps/xchange/xchange.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
- package/dist-standalone/_deps/xregistry/discovery.js +1 -1
- package/dist-standalone/_deps/xregistry/errors.js +1 -1
- package/dist-standalone/_deps/xregistry/index.js +1 -1
- package/dist-standalone/_deps/xregistry/registry.js +1 -1
- package/dist-standalone/_deps/xregistry/schema.js +1 -1
- package/dist-standalone/_deps/xregistry/types.js +1 -1
- package/dist-standalone/agent-call.js +1 -642
- package/dist-standalone/agent-sdk.js +1 -328
- package/dist-standalone/agent.d.ts +95 -5
- package/dist-standalone/agent.js +1 -1545
- package/dist-standalone/approval.js +1 -193
- package/dist-standalone/async-iterators.d.ts +275 -0
- package/dist-standalone/async-iterators.js +1 -0
- package/dist-standalone/auth.js +1 -219
- package/dist-standalone/auto-accept.js +1 -229
- package/dist-standalone/backup-config.js +1 -201
- package/dist-standalone/backup.d.ts +114 -0
- package/dist-standalone/backup.js +1 -0
- package/dist-standalone/batch-operations.d.ts +297 -0
- package/dist-standalone/batch-operations.js +1 -0
- package/dist-standalone/cancellation.d.ts +301 -0
- package/dist-standalone/cancellation.js +1 -0
- package/dist-standalone/checkpoint.js +1 -186
- package/dist-standalone/circuit-breaker.d.ts +351 -0
- package/dist-standalone/circuit-breaker.js +1 -0
- package/dist-standalone/cjs/agent-call.js +1 -651
- package/dist-standalone/cjs/agent-sdk.js +1 -332
- package/dist-standalone/cjs/agent.js +1 -1582
- package/dist-standalone/cjs/approval.js +1 -199
- package/dist-standalone/cjs/async-iterators.js +1 -0
- package/dist-standalone/cjs/auth.js +1 -225
- package/dist-standalone/cjs/auto-accept.js +1 -233
- package/dist-standalone/cjs/backup-config.js +1 -207
- package/dist-standalone/cjs/backup.js +1 -0
- package/dist-standalone/cjs/batch-operations.js +1 -0
- package/dist-standalone/cjs/cancellation.js +1 -0
- package/dist-standalone/cjs/checkpoint.js +1 -193
- package/dist-standalone/cjs/circuit-breaker.js +1 -0
- package/dist-standalone/cjs/cli/init.js +1 -486
- package/dist-standalone/cjs/config-validation.js +1 -0
- package/dist-standalone/cjs/connect.js +1 -312
- package/dist-standalone/cjs/connection-pool.js +1 -0
- package/dist-standalone/cjs/correlation-id.js +1 -339
- package/dist-standalone/cjs/crypto-utils.js +1 -0
- package/dist-standalone/cjs/debug-mode.js +1 -0
- package/dist-standalone/cjs/did-document.js +1 -101
- package/dist-standalone/cjs/did-privateme.js +1 -130
- package/dist-standalone/cjs/did-web.js +1 -201
- package/dist-standalone/cjs/discovery.js +1 -462
- package/dist-standalone/cjs/dual-mode.js +1 -251
- package/dist-standalone/cjs/email-templates.js +1 -313
- package/dist-standalone/cjs/email-transport.js +1 -239
- package/dist-standalone/cjs/envelope.js +1 -510
- package/dist-standalone/cjs/errors.js +1 -826
- package/dist-standalone/cjs/event-emitter.js +1 -0
- package/dist-standalone/cjs/gateway-state.js +1 -55
- package/dist-standalone/cjs/gateway-transport.js +1 -120
- package/dist-standalone/cjs/graceful-degradation.js +1 -0
- package/dist-standalone/cjs/guardrails.js +1 -223
- package/dist-standalone/cjs/health-check.js +1 -0
- package/dist-standalone/cjs/http-compat.js +1 -272
- package/dist-standalone/cjs/http-status-map.js +1 -571
- package/dist-standalone/cjs/identity.js +1 -540
- package/dist-standalone/cjs/index.js +1 -237
- package/dist-standalone/cjs/invitation.js +1 -421
- package/dist-standalone/cjs/invite.js +1 -328
- package/dist-standalone/cjs/key-agreement.js +1 -246
- package/dist-standalone/cjs/lazy-init.js +1 -300
- package/dist-standalone/cjs/logger.js +1 -0
- package/dist-standalone/cjs/mdns-discovery.js +1 -202
- package/dist-standalone/cjs/nonce-store.js +1 -66
- package/dist-standalone/cjs/pairing-manager.js +1 -223
- package/dist-standalone/cjs/plugin-system.js +1 -0
- package/dist-standalone/cjs/plugins/logging.js +1 -0
- package/dist-standalone/cjs/plugins/metrics.js +1 -0
- package/dist-standalone/cjs/plugins/validation.js +1 -0
- package/dist-standalone/cjs/policy.js +1 -320
- package/dist-standalone/cjs/progress-callbacks.js +1 -0
- package/dist-standalone/cjs/redis-nonce-store.js +1 -76
- package/dist-standalone/cjs/registry-middleware.js +1 -50
- package/dist-standalone/cjs/retry-strategies.js +1 -0
- package/dist-standalone/cjs/retry-transport.js +1 -102
- package/dist-standalone/cjs/runtime/browser.js +1 -0
- package/dist-standalone/cjs/runtime/edge.js +1 -0
- package/dist-standalone/cjs/runtime/react-native.js +1 -0
- package/dist-standalone/cjs/security-policy.js +1 -245
- package/dist-standalone/cjs/serialization.js +1 -0
- package/dist-standalone/cjs/split-channel.js +1 -177
- package/dist-standalone/cjs/subscription-proof.js +1 -230
- package/dist-standalone/cjs/succession.js +1 -148
- package/dist-standalone/cjs/timeouts.js +1 -0
- package/dist-standalone/cjs/trace-context.js +1 -0
- package/dist-standalone/cjs/trace-spans.js +1 -0
- package/dist-standalone/cjs/transport.js +1 -63
- package/dist-standalone/cjs/trust-registry.js +1 -742
- package/dist-standalone/cjs/types/error-response.js +1 -56
- package/dist-standalone/cjs/vault-auth.js +1 -0
- package/dist-standalone/cjs/vault-store-loader.js +1 -0
- package/dist-standalone/cjs/verify.js +1 -25
- package/dist-standalone/cjs/version-info.js +1 -0
- package/dist-standalone/cjs/xfetch.js +1 -252
- package/dist-standalone/cli/init.js +1 -449
- package/dist-standalone/cli/setup.js +1 -514
- package/dist-standalone/cli/types.js +1 -27
- package/dist-standalone/cli/xbind.js +1 -148
- package/dist-standalone/config-validation.d.ts +185 -0
- package/dist-standalone/config-validation.js +1 -0
- package/dist-standalone/connect.js +1 -274
- package/dist-standalone/connection-pool.d.ts +251 -0
- package/dist-standalone/connection-pool.js +1 -0
- package/dist-standalone/correlation-id.js +1 -326
- package/dist-standalone/crypto-utils.d.ts +60 -0
- package/dist-standalone/crypto-utils.js +1 -0
- package/dist-standalone/debug-mode.d.ts +286 -0
- package/dist-standalone/debug-mode.js +1 -0
- package/dist-standalone/did-document.js +1 -96
- package/dist-standalone/did-privateme.js +1 -121
- package/dist-standalone/did-web.js +1 -196
- package/dist-standalone/discovery.js +1 -458
- package/dist-standalone/dual-mode.js +1 -247
- package/dist-standalone/email-templates.js +1 -309
- package/dist-standalone/email-transport.js +1 -232
- package/dist-standalone/envelope.d.ts +29 -1
- package/dist-standalone/envelope.js +1 -497
- package/dist-standalone/errors.d.ts +10 -0
- package/dist-standalone/errors.js +1 -811
- package/dist-standalone/event-emitter.d.ts +395 -0
- package/dist-standalone/event-emitter.js +1 -0
- package/dist-standalone/gateway-state.js +1 -51
- package/dist-standalone/gateway-transport.js +1 -116
- package/dist-standalone/graceful-degradation.d.ts +246 -0
- package/dist-standalone/graceful-degradation.js +1 -0
- package/dist-standalone/guardrails.js +1 -216
- package/dist-standalone/health-check.d.ts +150 -0
- package/dist-standalone/health-check.js +1 -0
- package/dist-standalone/http-compat.js +1 -267
- package/dist-standalone/http-status-map.js +1 -561
- package/dist-standalone/identity.d.ts +64 -1
- package/dist-standalone/identity.js +1 -515
- package/dist-standalone/index.d.ts +45 -3
- package/dist-standalone/index.js +1 -52
- package/dist-standalone/invitation.js +1 -415
- package/dist-standalone/invite.js +1 -324
- package/dist-standalone/key-agreement.d.ts +61 -13
- package/dist-standalone/key-agreement.js +1 -236
- package/dist-standalone/lazy-init.js +1 -295
- package/dist-standalone/logger.d.ts +77 -0
- package/dist-standalone/logger.js +1 -0
- package/dist-standalone/mdns-discovery.js +1 -195
- package/dist-standalone/nonce-store.d.ts +16 -3
- package/dist-standalone/nonce-store.js +1 -62
- package/dist-standalone/package.json +0 -1
- package/dist-standalone/pairing-manager.js +1 -219
- package/dist-standalone/plugin-system.d.ts +145 -0
- package/dist-standalone/plugin-system.js +1 -0
- package/dist-standalone/policy.js +1 -315
- package/dist-standalone/progress-callbacks.d.ts +394 -0
- package/dist-standalone/progress-callbacks.js +1 -0
- package/dist-standalone/redis-nonce-store.js +1 -72
- package/dist-standalone/registry-middleware.js +1 -47
- package/dist-standalone/retry-strategies.d.ts +382 -0
- package/dist-standalone/retry-strategies.js +1 -0
- package/dist-standalone/retry-transport.js +1 -98
- package/dist-standalone/security-policy.js +1 -239
- package/dist-standalone/serialization.d.ts +244 -0
- package/dist-standalone/serialization.js +1 -0
- package/dist-standalone/split-channel.d.ts +49 -1
- package/dist-standalone/split-channel.js +1 -171
- package/dist-standalone/subscription-proof.js +1 -224
- package/dist-standalone/succession.js +1 -142
- package/dist-standalone/timeouts.d.ts +275 -0
- package/dist-standalone/timeouts.js +1 -0
- package/dist-standalone/trace-context.d.ts +252 -0
- package/dist-standalone/trace-context.js +1 -0
- package/dist-standalone/trace-spans.d.ts +360 -0
- package/dist-standalone/trace-spans.js +1 -0
- package/dist-standalone/transport.js +1 -59
- package/dist-standalone/trust-registry.d.ts +106 -5
- package/dist-standalone/trust-registry.js +1 -702
- package/dist-standalone/vault-auth.d.ts +91 -0
- package/dist-standalone/vault-auth.js +1 -0
- package/dist-standalone/vault-store-loader.d.ts +110 -0
- package/dist-standalone/vault-store-loader.js +1 -0
- package/dist-standalone/verify.js +1 -16
- package/dist-standalone/version-info.d.ts +259 -0
- package/dist-standalone/version-info.js +1 -0
- package/dist-standalone/xfetch.js +1 -247
- package/llms.txt +1 -0
- package/package.json +65 -5
- package/share1.dat +0 -0
- package/dist-standalone/_deps/crypto/base64.d.ts +0 -29
- package/dist-standalone/_deps/crypto/base64.js +0 -222
- package/dist-standalone/_deps/crypto/cjs/base64.js +0 -665
- package/dist-standalone/_deps/crypto/cjs/errors.js +0 -675
- package/dist-standalone/_deps/crypto/cjs/hmac.js +0 -473
- package/dist-standalone/_deps/crypto/cjs/index.js +0 -852
- package/dist-standalone/_deps/crypto/cjs/package.json +0 -1
- package/dist-standalone/_deps/crypto/cjs/padding.js +0 -511
- package/dist-standalone/_deps/crypto/cjs/share-header.js +0 -372
- package/dist-standalone/_deps/crypto/cjs/shares.js +0 -874
- package/dist-standalone/_deps/crypto/cjs/tlv.js +0 -1021
- package/dist-standalone/_deps/crypto/cjs/uuid.js +0 -443
- package/dist-standalone/_deps/crypto/cjs/verify.js +0 -414
- package/dist-standalone/_deps/crypto/cjs/xorida.js +0 -923
- package/dist-standalone/_deps/crypto/errors.d.ts +0 -51
- package/dist-standalone/_deps/crypto/errors.js +0 -199
- package/dist-standalone/_deps/crypto/hmac.d.ts +0 -39
- package/dist-standalone/_deps/crypto/hmac.js +0 -134
- package/dist-standalone/_deps/crypto/index.d.ts +0 -20
- package/dist-standalone/_deps/crypto/index.js +0 -145
- package/dist-standalone/_deps/crypto/padding.d.ts +0 -19
- package/dist-standalone/_deps/crypto/padding.js +0 -159
- package/dist-standalone/_deps/crypto/share-header.d.ts +0 -44
- package/dist-standalone/_deps/crypto/share-header.js +0 -92
- package/dist-standalone/_deps/crypto/shares.d.ts +0 -27
- package/dist-standalone/_deps/crypto/shares.js +0 -295
- package/dist-standalone/_deps/crypto/tlv.d.ts +0 -26
- package/dist-standalone/_deps/crypto/tlv.js +0 -364
- package/dist-standalone/_deps/crypto/uuid.d.ts +0 -22
- package/dist-standalone/_deps/crypto/uuid.js +0 -136
- package/dist-standalone/_deps/crypto/verify.d.ts +0 -15
- package/dist-standalone/_deps/crypto/verify.js +0 -71
- package/dist-standalone/_deps/crypto/xorida.d.ts +0 -44
- package/dist-standalone/_deps/crypto/xorida.js +0 -366
- package/dist-standalone/_deps/shared/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/errors.js.map +0 -1
- package/dist-standalone/_deps/shared/index.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/index.js.map +0 -1
- package/dist-standalone/_deps/shared/types.d.ts.map +0 -1
- package/dist-standalone/_deps/shared/types.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/errors.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/index.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/pagination.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/progress.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/search.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/cjs/types.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/errors.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/index.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/index.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/pagination.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/pagination.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/progress.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/progress.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/search.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/search.js.map +0 -1
- package/dist-standalone/_deps/ux-helpers/types.d.ts.map +0 -1
- package/dist-standalone/_deps/ux-helpers/types.js.map +0 -1
- package/dist-standalone/_deps/xregistry/discovery.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/discovery.js.map +0 -1
- package/dist-standalone/_deps/xregistry/errors.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/errors.js.map +0 -1
- package/dist-standalone/_deps/xregistry/index.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/index.js.map +0 -1
- package/dist-standalone/_deps/xregistry/registry.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/registry.js.map +0 -1
- package/dist-standalone/_deps/xregistry/schema.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/schema.js.map +0 -1
- package/dist-standalone/_deps/xregistry/types.d.ts.map +0 -1
- package/dist-standalone/_deps/xregistry/types.js.map +0 -1
|
@@ -0,0 +1,395 @@
|
|
|
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 type { Result } from '@private.me/shared';
|
|
13
|
+
import type { AgentMessage } from './agent.js';
|
|
14
|
+
/** Connection status values */
|
|
15
|
+
export type ConnectionStatus = 'connected' | 'disconnected' | 'reconnecting' | 'error';
|
|
16
|
+
/** Event payload types mapped to event names */
|
|
17
|
+
export interface XBindEventMap {
|
|
18
|
+
'message-sent': MessageSentEvent;
|
|
19
|
+
'message-received': MessageReceivedEvent;
|
|
20
|
+
'key-rotated': KeyRotatedEvent;
|
|
21
|
+
'error': ErrorEvent;
|
|
22
|
+
'connection-status': ConnectionStatusEvent;
|
|
23
|
+
}
|
|
24
|
+
/** Base event interface with common fields */
|
|
25
|
+
export interface XBindBaseEvent {
|
|
26
|
+
/** Event type identifier */
|
|
27
|
+
readonly type: string;
|
|
28
|
+
/** ISO 8601 timestamp when event was emitted */
|
|
29
|
+
readonly timestamp: string;
|
|
30
|
+
/** Unique event identifier for tracking and deduplication */
|
|
31
|
+
readonly eventId: string;
|
|
32
|
+
}
|
|
33
|
+
/** Emitted when a message is successfully sent */
|
|
34
|
+
export interface MessageSentEvent extends XBindBaseEvent {
|
|
35
|
+
readonly type: 'message-sent';
|
|
36
|
+
/** Recipient DID */
|
|
37
|
+
readonly recipientDid: string;
|
|
38
|
+
/** Message identifier */
|
|
39
|
+
readonly messageId: string;
|
|
40
|
+
/** Message payload size in bytes */
|
|
41
|
+
readonly payloadSize: number;
|
|
42
|
+
/** Envelope version used (v1-v4) */
|
|
43
|
+
readonly envelopeVersion: string;
|
|
44
|
+
}
|
|
45
|
+
/** Emitted when a message is received */
|
|
46
|
+
export interface MessageReceivedEvent extends XBindBaseEvent {
|
|
47
|
+
readonly type: 'message-received';
|
|
48
|
+
/** Sender DID */
|
|
49
|
+
readonly senderDid: string;
|
|
50
|
+
/** Decoded message */
|
|
51
|
+
readonly message: AgentMessage;
|
|
52
|
+
/** Message identifier */
|
|
53
|
+
readonly messageId: string;
|
|
54
|
+
/** Whether signature was verified */
|
|
55
|
+
readonly verified: boolean;
|
|
56
|
+
}
|
|
57
|
+
/** Emitted when encryption keys are rotated */
|
|
58
|
+
export interface KeyRotatedEvent extends XBindBaseEvent {
|
|
59
|
+
readonly type: 'key-rotated';
|
|
60
|
+
/** Key type rotated (ed25519, x25519, mlkem, mldsa) */
|
|
61
|
+
readonly keyType: 'ed25519' | 'x25519' | 'mlkem' | 'mldsa';
|
|
62
|
+
/** New public key (base64) */
|
|
63
|
+
readonly newPublicKey: string;
|
|
64
|
+
/** Previous public key (base64, if available) */
|
|
65
|
+
readonly previousPublicKey?: string;
|
|
66
|
+
/** Reason for rotation */
|
|
67
|
+
readonly reason: string;
|
|
68
|
+
}
|
|
69
|
+
/** Emitted when an error occurs */
|
|
70
|
+
export interface ErrorEvent extends XBindBaseEvent {
|
|
71
|
+
readonly type: 'error';
|
|
72
|
+
/** Error code */
|
|
73
|
+
readonly code: string;
|
|
74
|
+
/** Error message */
|
|
75
|
+
readonly message: string;
|
|
76
|
+
/** Context where error occurred */
|
|
77
|
+
readonly context: string;
|
|
78
|
+
/** Detailed error information */
|
|
79
|
+
readonly details?: Record<string, unknown>;
|
|
80
|
+
}
|
|
81
|
+
/** Emitted when connection status changes */
|
|
82
|
+
export interface ConnectionStatusEvent extends XBindBaseEvent {
|
|
83
|
+
readonly type: 'connection-status';
|
|
84
|
+
/** Current connection status */
|
|
85
|
+
readonly status: ConnectionStatus;
|
|
86
|
+
/** Previous connection status */
|
|
87
|
+
readonly previousStatus?: ConnectionStatus;
|
|
88
|
+
/** Additional context (error message, reconnect attempt, etc.) */
|
|
89
|
+
readonly context?: string;
|
|
90
|
+
}
|
|
91
|
+
/** Event listener function signature */
|
|
92
|
+
export type EventListener<T extends XBindBaseEvent = XBindBaseEvent> = (event: T) => void | Promise<void>;
|
|
93
|
+
/** Options for event emission */
|
|
94
|
+
export interface EmitOptions {
|
|
95
|
+
/** Whether to bubble event to parent emitters */
|
|
96
|
+
bubble?: boolean;
|
|
97
|
+
/** Whether to stop propagation after first listener */
|
|
98
|
+
stopPropagation?: boolean;
|
|
99
|
+
/** Custom event ID (auto-generated if not provided) */
|
|
100
|
+
eventId?: string;
|
|
101
|
+
}
|
|
102
|
+
/** Options for event listener registration */
|
|
103
|
+
export interface ListenerOptions {
|
|
104
|
+
/** Listener priority (higher = called first) */
|
|
105
|
+
priority?: number;
|
|
106
|
+
/** Whether listener should only fire once */
|
|
107
|
+
once?: boolean;
|
|
108
|
+
}
|
|
109
|
+
/** Event emitter error codes */
|
|
110
|
+
export type EventEmitterErrorCode = 'INVALID_EVENT_TYPE' | 'INVALID_LISTENER' | 'LISTENER_ERROR' | 'MAX_LISTENERS_EXCEEDED' | 'DISPOSED';
|
|
111
|
+
/**
|
|
112
|
+
* Type-safe event emitter for xBind agent events.
|
|
113
|
+
*
|
|
114
|
+
* Features:
|
|
115
|
+
* - Type-safe event names and payloads
|
|
116
|
+
* - Listener priority support
|
|
117
|
+
* - Once listeners
|
|
118
|
+
* - Event bubbling to parent emitters
|
|
119
|
+
* - Async listener support with error handling
|
|
120
|
+
* - Memory leak detection
|
|
121
|
+
*
|
|
122
|
+
* @example
|
|
123
|
+
* ```typescript
|
|
124
|
+
* const emitter = new XBindEventEmitter();
|
|
125
|
+
*
|
|
126
|
+
* // Register listener
|
|
127
|
+
* emitter.on('message-received', (event) => {
|
|
128
|
+
* console.log('Received from:', event.senderDid);
|
|
129
|
+
* });
|
|
130
|
+
*
|
|
131
|
+
* // Register one-time listener
|
|
132
|
+
* emitter.once('connection-status', (event) => {
|
|
133
|
+
* console.log('Status:', event.status);
|
|
134
|
+
* });
|
|
135
|
+
*
|
|
136
|
+
* // Emit event
|
|
137
|
+
* await emitter.emit('message-received', {
|
|
138
|
+
* type: 'message-received',
|
|
139
|
+
* timestamp: new Date().toISOString(),
|
|
140
|
+
* eventId: '123',
|
|
141
|
+
* senderDid: 'did:key:z6Mk...',
|
|
142
|
+
* message: { payload: 'Hello' },
|
|
143
|
+
* messageId: 'msg-1',
|
|
144
|
+
* verified: true
|
|
145
|
+
* });
|
|
146
|
+
* ```
|
|
147
|
+
*/
|
|
148
|
+
export declare class XBindEventEmitter {
|
|
149
|
+
private listeners;
|
|
150
|
+
private parent?;
|
|
151
|
+
private disposed;
|
|
152
|
+
private eventCounter;
|
|
153
|
+
/** Maximum listeners per event type before warning (0 = unlimited) */
|
|
154
|
+
private maxListeners;
|
|
155
|
+
/** Whether warnings are enabled */
|
|
156
|
+
private warningsEnabled;
|
|
157
|
+
/**
|
|
158
|
+
* Create a new event emitter.
|
|
159
|
+
*
|
|
160
|
+
* @param parent - Optional parent emitter for event bubbling
|
|
161
|
+
*/
|
|
162
|
+
constructor(parent?: XBindEventEmitter);
|
|
163
|
+
/**
|
|
164
|
+
* Register an event listener.
|
|
165
|
+
*
|
|
166
|
+
* @param eventType - Event type to listen for
|
|
167
|
+
* @param listener - Listener function
|
|
168
|
+
* @param options - Listener options (priority, once)
|
|
169
|
+
* @returns This emitter for chaining
|
|
170
|
+
*
|
|
171
|
+
* @example
|
|
172
|
+
* ```typescript
|
|
173
|
+
* emitter.on('error', (event) => {
|
|
174
|
+
* console.error('Error:', event.message);
|
|
175
|
+
* }, { priority: 10 });
|
|
176
|
+
* ```
|
|
177
|
+
*/
|
|
178
|
+
on<K extends keyof XBindEventMap>(eventType: K, listener: EventListener<XBindEventMap[K]>, options?: ListenerOptions): this;
|
|
179
|
+
/**
|
|
180
|
+
* Register a one-time event listener.
|
|
181
|
+
* Listener is automatically removed after first invocation.
|
|
182
|
+
*
|
|
183
|
+
* @param eventType - Event type to listen for
|
|
184
|
+
* @param listener - Listener function
|
|
185
|
+
* @param options - Listener options (priority)
|
|
186
|
+
* @returns This emitter for chaining
|
|
187
|
+
*
|
|
188
|
+
* @example
|
|
189
|
+
* ```typescript
|
|
190
|
+
* emitter.once('connection-status', (event) => {
|
|
191
|
+
* console.log('First status change:', event.status);
|
|
192
|
+
* });
|
|
193
|
+
* ```
|
|
194
|
+
*/
|
|
195
|
+
once<K extends keyof XBindEventMap>(eventType: K, listener: EventListener<XBindEventMap[K]>, options?: Omit<ListenerOptions, 'once'>): this;
|
|
196
|
+
/**
|
|
197
|
+
* Remove an event listener.
|
|
198
|
+
*
|
|
199
|
+
* @param eventType - Event type
|
|
200
|
+
* @param listener - Listener function to remove
|
|
201
|
+
* @returns This emitter for chaining
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* ```typescript
|
|
205
|
+
* const handler = (event) => console.log(event);
|
|
206
|
+
* emitter.on('error', handler);
|
|
207
|
+
* emitter.off('error', handler);
|
|
208
|
+
* ```
|
|
209
|
+
*/
|
|
210
|
+
off<K extends keyof XBindEventMap>(eventType: K, listener: EventListener<XBindEventMap[K]>): this;
|
|
211
|
+
/**
|
|
212
|
+
* Remove all listeners for an event type, or all listeners if no type specified.
|
|
213
|
+
*
|
|
214
|
+
* @param eventType - Optional event type (removes all if not specified)
|
|
215
|
+
* @returns This emitter for chaining
|
|
216
|
+
*
|
|
217
|
+
* @example
|
|
218
|
+
* ```typescript
|
|
219
|
+
* emitter.removeAllListeners('error'); // Remove all error listeners
|
|
220
|
+
* emitter.removeAllListeners(); // Remove all listeners
|
|
221
|
+
* ```
|
|
222
|
+
*/
|
|
223
|
+
removeAllListeners<K extends keyof XBindEventMap>(eventType?: K): this;
|
|
224
|
+
/**
|
|
225
|
+
* Emit an event to all registered listeners.
|
|
226
|
+
* Listeners are called in priority order (highest first).
|
|
227
|
+
* Async listeners are awaited in sequence.
|
|
228
|
+
*
|
|
229
|
+
* @param eventType - Event type to emit
|
|
230
|
+
* @param event - Event payload
|
|
231
|
+
* @param options - Emission options (bubble, stopPropagation)
|
|
232
|
+
* @returns Result indicating success or first error encountered
|
|
233
|
+
*
|
|
234
|
+
* @example
|
|
235
|
+
* ```typescript
|
|
236
|
+
* await emitter.emit('error', {
|
|
237
|
+
* type: 'error',
|
|
238
|
+
* timestamp: new Date().toISOString(),
|
|
239
|
+
* eventId: '123',
|
|
240
|
+
* code: 'NETWORK_ERROR',
|
|
241
|
+
* message: 'Connection failed',
|
|
242
|
+
* context: 'transport'
|
|
243
|
+
* });
|
|
244
|
+
* ```
|
|
245
|
+
*/
|
|
246
|
+
emit<K extends keyof XBindEventMap>(eventType: K, event: Omit<XBindEventMap[K], 'eventId' | 'timestamp'>, options?: EmitOptions): Promise<Result<void, EventEmitterErrorCode>>;
|
|
247
|
+
/**
|
|
248
|
+
* Check if there are any listeners for an event type.
|
|
249
|
+
*
|
|
250
|
+
* @param eventType - Event type to check
|
|
251
|
+
* @returns True if there are listeners
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* ```typescript
|
|
255
|
+
* if (emitter.hasListeners('error')) {
|
|
256
|
+
* await emitter.emit('error', errorEvent);
|
|
257
|
+
* }
|
|
258
|
+
* ```
|
|
259
|
+
*/
|
|
260
|
+
hasListeners<K extends keyof XBindEventMap>(eventType: K): boolean;
|
|
261
|
+
/**
|
|
262
|
+
* Get the number of listeners for an event type.
|
|
263
|
+
*
|
|
264
|
+
* @param eventType - Event type
|
|
265
|
+
* @returns Number of listeners
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* ```typescript
|
|
269
|
+
* const count = emitter.listenerCount('message-received');
|
|
270
|
+
* console.log(`${count} listeners registered`);
|
|
271
|
+
* ```
|
|
272
|
+
*/
|
|
273
|
+
listenerCount<K extends keyof XBindEventMap>(eventType: K): number;
|
|
274
|
+
/**
|
|
275
|
+
* Get all registered event types.
|
|
276
|
+
*
|
|
277
|
+
* @returns Array of event types with active listeners
|
|
278
|
+
*
|
|
279
|
+
* @example
|
|
280
|
+
* ```typescript
|
|
281
|
+
* const events = emitter.eventNames();
|
|
282
|
+
* console.log('Active events:', events);
|
|
283
|
+
* ```
|
|
284
|
+
*/
|
|
285
|
+
eventNames(): Array<keyof XBindEventMap>;
|
|
286
|
+
/**
|
|
287
|
+
* Set the maximum number of listeners per event before warning.
|
|
288
|
+
* Use 0 for unlimited listeners.
|
|
289
|
+
*
|
|
290
|
+
* @param n - Maximum listeners (0 = unlimited)
|
|
291
|
+
* @returns This emitter for chaining
|
|
292
|
+
*
|
|
293
|
+
* @example
|
|
294
|
+
* ```typescript
|
|
295
|
+
* emitter.setMaxListeners(20); // Allow up to 20 listeners
|
|
296
|
+
* emitter.setMaxListeners(0); // Unlimited
|
|
297
|
+
* ```
|
|
298
|
+
*/
|
|
299
|
+
setMaxListeners(n: number): this;
|
|
300
|
+
/**
|
|
301
|
+
* Get the maximum number of listeners per event.
|
|
302
|
+
*
|
|
303
|
+
* @returns Maximum listeners (0 = unlimited)
|
|
304
|
+
*/
|
|
305
|
+
getMaxListeners(): number;
|
|
306
|
+
/**
|
|
307
|
+
* Enable or disable memory leak warnings.
|
|
308
|
+
*
|
|
309
|
+
* @param enabled - Whether warnings are enabled
|
|
310
|
+
* @returns This emitter for chaining
|
|
311
|
+
*/
|
|
312
|
+
setWarningsEnabled(enabled: boolean): this;
|
|
313
|
+
/**
|
|
314
|
+
* Set the parent emitter for event bubbling.
|
|
315
|
+
*
|
|
316
|
+
* @param parent - Parent emitter (undefined to remove parent)
|
|
317
|
+
* @returns This emitter for chaining
|
|
318
|
+
*
|
|
319
|
+
* @example
|
|
320
|
+
* ```typescript
|
|
321
|
+
* const parent = new XBindEventEmitter();
|
|
322
|
+
* const child = new XBindEventEmitter();
|
|
323
|
+
* child.setParent(parent);
|
|
324
|
+
*
|
|
325
|
+
* parent.on('error', (event) => console.log('Parent received:', event));
|
|
326
|
+
* await child.emit('error', errorEvent, { bubble: true });
|
|
327
|
+
* ```
|
|
328
|
+
*/
|
|
329
|
+
setParent(parent: XBindEventEmitter | undefined): this;
|
|
330
|
+
/**
|
|
331
|
+
* Get the parent emitter.
|
|
332
|
+
*
|
|
333
|
+
* @returns Parent emitter or undefined
|
|
334
|
+
*/
|
|
335
|
+
getParent(): XBindEventEmitter | undefined;
|
|
336
|
+
/**
|
|
337
|
+
* Wait for a specific event to be emitted.
|
|
338
|
+
* Returns a promise that resolves with the event payload.
|
|
339
|
+
*
|
|
340
|
+
* @param eventType - Event type to wait for
|
|
341
|
+
* @param timeout - Optional timeout in milliseconds
|
|
342
|
+
* @returns Promise resolving to event or rejecting on timeout
|
|
343
|
+
*
|
|
344
|
+
* @example
|
|
345
|
+
* ```typescript
|
|
346
|
+
* const event = await emitter.waitFor('connection-status', 5000);
|
|
347
|
+
* console.log('Status changed to:', event.status);
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
waitFor<K extends keyof XBindEventMap>(eventType: K, timeout?: number): Promise<XBindEventMap[K]>;
|
|
351
|
+
/**
|
|
352
|
+
* Dispose the event emitter and remove all listeners.
|
|
353
|
+
* After disposal, no events can be emitted and listeners cannot be registered.
|
|
354
|
+
*
|
|
355
|
+
* @example
|
|
356
|
+
* ```typescript
|
|
357
|
+
* emitter.dispose();
|
|
358
|
+
* ```
|
|
359
|
+
*/
|
|
360
|
+
dispose(): void;
|
|
361
|
+
/**
|
|
362
|
+
* Check if the emitter has been disposed.
|
|
363
|
+
*
|
|
364
|
+
* @returns True if disposed
|
|
365
|
+
*/
|
|
366
|
+
isDisposed(): boolean;
|
|
367
|
+
private checkDisposed;
|
|
368
|
+
private generateEventId;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Create a scoped event emitter that only emits specific event types.
|
|
372
|
+
* Useful for isolating event channels.
|
|
373
|
+
*
|
|
374
|
+
* @param parent - Parent emitter
|
|
375
|
+
* @param allowedEvents - Array of allowed event types
|
|
376
|
+
* @returns Scoped event emitter
|
|
377
|
+
*
|
|
378
|
+
* @example
|
|
379
|
+
* ```typescript
|
|
380
|
+
* const parent = new XBindEventEmitter();
|
|
381
|
+
* const errorOnly = createScopedEmitter(parent, ['error']);
|
|
382
|
+
*
|
|
383
|
+
* errorOnly.emit('error', errorEvent); // OK
|
|
384
|
+
* errorOnly.emit('message-sent', event); // TypeScript error
|
|
385
|
+
* ```
|
|
386
|
+
*/
|
|
387
|
+
export declare function createScopedEmitter<K extends keyof XBindEventMap>(parent: XBindEventEmitter, allowedEvents: readonly K[]): {
|
|
388
|
+
on: <T extends K>(type: T, listener: EventListener<XBindEventMap[T]>, options?: ListenerOptions) => XBindEventEmitter;
|
|
389
|
+
once: <T extends K>(type: T, listener: EventListener<XBindEventMap[T]>, options?: Omit<ListenerOptions, 'once'>) => XBindEventEmitter;
|
|
390
|
+
off: <T extends K>(type: T, listener: EventListener<XBindEventMap[T]>) => XBindEventEmitter;
|
|
391
|
+
emit: <T extends K>(type: T, event: Omit<XBindEventMap[T], 'eventId' | 'timestamp'>, options?: EmitOptions) => Promise<Result<void, EventEmitterErrorCode>>;
|
|
392
|
+
hasListeners: <T extends K>(type: T) => boolean;
|
|
393
|
+
listenerCount: <T extends K>(type: T) => number;
|
|
394
|
+
dispose: () => void;
|
|
395
|
+
};
|
|
@@ -0,0 +1 @@
|
|
|
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,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{}}}
|