@silicaclaw/cli 1.0.0-beta.3 → 1.0.0-beta.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 (86) hide show
  1. package/package.json +5 -1
  2. package/packages/core/dist/crypto.d.ts +6 -0
  3. package/packages/core/dist/crypto.js +50 -0
  4. package/packages/core/dist/directory.d.ts +17 -0
  5. package/packages/core/dist/directory.js +145 -0
  6. package/packages/core/dist/identity.d.ts +2 -0
  7. package/packages/core/dist/identity.js +18 -0
  8. package/packages/core/dist/index.d.ts +11 -0
  9. package/packages/core/dist/index.js +27 -0
  10. package/packages/core/dist/indexing.d.ts +6 -0
  11. package/packages/core/dist/indexing.js +43 -0
  12. package/packages/core/dist/presence.d.ts +4 -0
  13. package/packages/core/dist/presence.js +23 -0
  14. package/packages/core/dist/profile.d.ts +4 -0
  15. package/packages/core/dist/profile.js +39 -0
  16. package/packages/core/dist/publicProfileSummary.d.ts +70 -0
  17. package/packages/core/dist/publicProfileSummary.js +103 -0
  18. package/packages/core/dist/socialConfig.d.ts +99 -0
  19. package/packages/core/dist/socialConfig.js +287 -0
  20. package/packages/core/dist/socialResolver.d.ts +46 -0
  21. package/packages/core/dist/socialResolver.js +227 -0
  22. package/packages/core/dist/socialTemplate.d.ts +2 -0
  23. package/packages/core/dist/socialTemplate.js +88 -0
  24. package/packages/core/dist/types.d.ts +37 -0
  25. package/packages/core/dist/types.js +2 -0
  26. package/packages/network/dist/abstractions/messageEnvelope.d.ts +28 -0
  27. package/packages/network/dist/abstractions/messageEnvelope.js +36 -0
  28. package/packages/network/dist/abstractions/peerDiscovery.d.ts +43 -0
  29. package/packages/network/dist/abstractions/peerDiscovery.js +2 -0
  30. package/packages/network/dist/abstractions/topicCodec.d.ts +4 -0
  31. package/packages/network/dist/abstractions/topicCodec.js +2 -0
  32. package/packages/network/dist/abstractions/transport.d.ts +36 -0
  33. package/packages/network/dist/abstractions/transport.js +2 -0
  34. package/packages/network/dist/codec/jsonMessageEnvelopeCodec.d.ts +5 -0
  35. package/packages/network/dist/codec/jsonMessageEnvelopeCodec.js +24 -0
  36. package/packages/network/dist/codec/jsonTopicCodec.d.ts +5 -0
  37. package/packages/network/dist/codec/jsonTopicCodec.js +12 -0
  38. package/packages/network/dist/discovery/heartbeatPeerDiscovery.d.ts +28 -0
  39. package/packages/network/dist/discovery/heartbeatPeerDiscovery.js +144 -0
  40. package/packages/network/dist/index.d.ts +13 -0
  41. package/packages/network/dist/index.js +29 -0
  42. package/packages/network/dist/localEventBus.d.ts +9 -0
  43. package/packages/network/dist/localEventBus.js +47 -0
  44. package/packages/network/dist/mock.d.ts +8 -0
  45. package/packages/network/dist/mock.js +24 -0
  46. package/packages/network/dist/realPreview.d.ts +105 -0
  47. package/packages/network/dist/realPreview.js +327 -0
  48. package/packages/network/dist/transport/udpLanBroadcastTransport.d.ts +23 -0
  49. package/packages/network/dist/transport/udpLanBroadcastTransport.js +153 -0
  50. package/packages/network/dist/types.d.ts +6 -0
  51. package/packages/network/dist/types.js +2 -0
  52. package/packages/network/dist/webrtcPreview.d.ts +163 -0
  53. package/packages/network/dist/webrtcPreview.js +844 -0
  54. package/packages/storage/dist/core/src/crypto.d.ts +6 -0
  55. package/packages/storage/dist/core/src/crypto.js +50 -0
  56. package/packages/storage/dist/core/src/directory.d.ts +17 -0
  57. package/packages/storage/dist/core/src/directory.js +145 -0
  58. package/packages/storage/dist/core/src/identity.d.ts +2 -0
  59. package/packages/storage/dist/core/src/identity.js +18 -0
  60. package/packages/storage/dist/core/src/index.d.ts +11 -0
  61. package/packages/storage/dist/core/src/index.js +27 -0
  62. package/packages/storage/dist/core/src/indexing.d.ts +6 -0
  63. package/packages/storage/dist/core/src/indexing.js +43 -0
  64. package/packages/storage/dist/core/src/presence.d.ts +4 -0
  65. package/packages/storage/dist/core/src/presence.js +23 -0
  66. package/packages/storage/dist/core/src/profile.d.ts +4 -0
  67. package/packages/storage/dist/core/src/profile.js +39 -0
  68. package/packages/storage/dist/core/src/publicProfileSummary.d.ts +70 -0
  69. package/packages/storage/dist/core/src/publicProfileSummary.js +103 -0
  70. package/packages/storage/dist/core/src/socialConfig.d.ts +99 -0
  71. package/packages/storage/dist/core/src/socialConfig.js +287 -0
  72. package/packages/storage/dist/core/src/socialResolver.d.ts +46 -0
  73. package/packages/storage/dist/core/src/socialResolver.js +227 -0
  74. package/packages/storage/dist/core/src/socialTemplate.d.ts +2 -0
  75. package/packages/storage/dist/core/src/socialTemplate.js +88 -0
  76. package/packages/storage/dist/core/src/types.d.ts +37 -0
  77. package/packages/storage/dist/core/src/types.js +2 -0
  78. package/packages/storage/dist/storage/src/index.d.ts +3 -0
  79. package/packages/storage/dist/storage/src/index.js +19 -0
  80. package/packages/storage/dist/storage/src/jsonRepo.d.ts +7 -0
  81. package/packages/storage/dist/storage/src/jsonRepo.js +29 -0
  82. package/packages/storage/dist/storage/src/repos.d.ts +21 -0
  83. package/packages/storage/dist/storage/src/repos.js +41 -0
  84. package/packages/storage/dist/storage/src/socialRuntimeRepo.d.ts +5 -0
  85. package/packages/storage/dist/storage/src/socialRuntimeRepo.js +52 -0
  86. package/scripts/quickstart.sh +1 -1
@@ -0,0 +1,105 @@
1
+ import { NetworkAdapter } from "./types";
2
+ import { MessageEnvelopeCodec } from "./abstractions/messageEnvelope";
3
+ import { TopicCodec } from "./abstractions/topicCodec";
4
+ import { NetworkTransport } from "./abstractions/transport";
5
+ import { PeerDiscovery, PeerSnapshot } from "./abstractions/peerDiscovery";
6
+ type RealNetworkAdapterPreviewOptions = {
7
+ peerId?: string;
8
+ namespace?: string;
9
+ transport?: NetworkTransport;
10
+ envelopeCodec?: MessageEnvelopeCodec;
11
+ topicCodec?: TopicCodec;
12
+ peerDiscovery?: PeerDiscovery;
13
+ maxMessageBytes?: number;
14
+ dedupeWindowMs?: number;
15
+ dedupeMaxEntries?: number;
16
+ maxFutureDriftMs?: number;
17
+ maxPastDriftMs?: number;
18
+ };
19
+ type NetworkDiagnostics = {
20
+ adapter: string;
21
+ peer_id: string;
22
+ namespace: string;
23
+ components: {
24
+ transport: string;
25
+ discovery: string;
26
+ envelope_codec: string;
27
+ topic_codec: string;
28
+ };
29
+ limits: {
30
+ max_message_bytes: number;
31
+ dedupe_window_ms: number;
32
+ dedupe_max_entries: number;
33
+ max_future_drift_ms: number;
34
+ max_past_drift_ms: number;
35
+ };
36
+ config: {
37
+ started: boolean;
38
+ topic_handler_count: number;
39
+ transport: ReturnType<NonNullable<NetworkTransport["getConfig"]>> | null;
40
+ discovery: ReturnType<NonNullable<PeerDiscovery["getConfig"]>> | null;
41
+ };
42
+ peers: {
43
+ total: number;
44
+ online: number;
45
+ stale: number;
46
+ items: PeerSnapshot[];
47
+ };
48
+ stats: {
49
+ publish_attempted: number;
50
+ publish_sent: number;
51
+ received_total: number;
52
+ delivered_total: number;
53
+ dropped_duplicate: number;
54
+ dropped_self: number;
55
+ dropped_malformed: number;
56
+ dropped_oversized: number;
57
+ dropped_namespace_mismatch: number;
58
+ dropped_timestamp_future_drift: number;
59
+ dropped_timestamp_past_drift: number;
60
+ dropped_decode_failed: number;
61
+ dropped_topic_decode_error: number;
62
+ dropped_handler_error: number;
63
+ send_errors: number;
64
+ discovery_errors: number;
65
+ start_errors: number;
66
+ stop_errors: number;
67
+ received_validated: number;
68
+ };
69
+ transport_stats: ReturnType<NonNullable<NetworkTransport["getStats"]>> | null;
70
+ discovery_stats: ReturnType<NonNullable<PeerDiscovery["getStats"]>> | null;
71
+ };
72
+ export declare class RealNetworkAdapterPreview implements NetworkAdapter {
73
+ private started;
74
+ private peerId;
75
+ private namespace;
76
+ private transport;
77
+ private envelopeCodec;
78
+ private topicCodec;
79
+ private peerDiscovery;
80
+ private maxMessageBytes;
81
+ private dedupeWindowMs;
82
+ private dedupeMaxEntries;
83
+ private maxFutureDriftMs;
84
+ private maxPastDriftMs;
85
+ private seenMessageIds;
86
+ private offTransportMessage;
87
+ private handlers;
88
+ private stats;
89
+ constructor(options?: RealNetworkAdapterPreviewOptions);
90
+ start(): Promise<void>;
91
+ stop(): Promise<void>;
92
+ publish(topic: string, data: any): Promise<void>;
93
+ subscribe(topic: string, handler: (data: any) => void): void;
94
+ listPeers(): PeerSnapshot[];
95
+ getDiagnostics(): NetworkDiagnostics;
96
+ private onTransportMessage;
97
+ private topicKey;
98
+ private stripNamespace;
99
+ private isDuplicateMessage;
100
+ private cleanupSeenMessageIds;
101
+ private isValidTopic;
102
+ private normalizeNamespace;
103
+ private errorMessage;
104
+ }
105
+ export {};
@@ -0,0 +1,327 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RealNetworkAdapterPreview = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const messageEnvelope_1 = require("./abstractions/messageEnvelope");
6
+ const jsonMessageEnvelopeCodec_1 = require("./codec/jsonMessageEnvelopeCodec");
7
+ const jsonTopicCodec_1 = require("./codec/jsonTopicCodec");
8
+ const udpLanBroadcastTransport_1 = require("./transport/udpLanBroadcastTransport");
9
+ const heartbeatPeerDiscovery_1 = require("./discovery/heartbeatPeerDiscovery");
10
+ class RealNetworkAdapterPreview {
11
+ started = false;
12
+ peerId;
13
+ namespace;
14
+ transport;
15
+ envelopeCodec;
16
+ topicCodec;
17
+ peerDiscovery;
18
+ maxMessageBytes;
19
+ dedupeWindowMs;
20
+ dedupeMaxEntries;
21
+ maxFutureDriftMs;
22
+ maxPastDriftMs;
23
+ seenMessageIds = new Map();
24
+ offTransportMessage = null;
25
+ handlers = new Map();
26
+ stats = {
27
+ publish_attempted: 0,
28
+ publish_sent: 0,
29
+ received_total: 0,
30
+ delivered_total: 0,
31
+ dropped_duplicate: 0,
32
+ dropped_self: 0,
33
+ dropped_malformed: 0,
34
+ dropped_oversized: 0,
35
+ dropped_namespace_mismatch: 0,
36
+ dropped_timestamp_future_drift: 0,
37
+ dropped_timestamp_past_drift: 0,
38
+ dropped_decode_failed: 0,
39
+ dropped_topic_decode_error: 0,
40
+ dropped_handler_error: 0,
41
+ send_errors: 0,
42
+ discovery_errors: 0,
43
+ start_errors: 0,
44
+ stop_errors: 0,
45
+ received_validated: 0,
46
+ };
47
+ constructor(options = {}) {
48
+ this.peerId = options.peerId ?? `peer-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
49
+ this.namespace = this.normalizeNamespace(options.namespace ?? "silicaclaw.preview");
50
+ this.transport = options.transport ?? new udpLanBroadcastTransport_1.UdpLanBroadcastTransport();
51
+ this.envelopeCodec = options.envelopeCodec ?? new jsonMessageEnvelopeCodec_1.JsonMessageEnvelopeCodec();
52
+ this.topicCodec = options.topicCodec ?? new jsonTopicCodec_1.JsonTopicCodec();
53
+ this.peerDiscovery = options.peerDiscovery ?? new heartbeatPeerDiscovery_1.HeartbeatPeerDiscovery();
54
+ this.maxMessageBytes = options.maxMessageBytes ?? 64 * 1024;
55
+ this.dedupeWindowMs = options.dedupeWindowMs ?? 90_000;
56
+ this.dedupeMaxEntries = options.dedupeMaxEntries ?? 10_000;
57
+ this.maxFutureDriftMs = options.maxFutureDriftMs ?? 30_000;
58
+ this.maxPastDriftMs = options.maxPastDriftMs ?? 120_000;
59
+ }
60
+ async start() {
61
+ if (this.started) {
62
+ return;
63
+ }
64
+ try {
65
+ await this.transport.start();
66
+ }
67
+ catch (error) {
68
+ this.stats.start_errors += 1;
69
+ throw new Error(`Transport start failed: ${this.errorMessage(error)}`);
70
+ }
71
+ this.started = true;
72
+ this.offTransportMessage = this.transport.onMessage((raw) => {
73
+ this.onTransportMessage(raw);
74
+ });
75
+ try {
76
+ await this.peerDiscovery.start({
77
+ self_peer_id: this.peerId,
78
+ publishControl: async (topic, payload) => {
79
+ await this.publish(topic, payload);
80
+ },
81
+ });
82
+ }
83
+ catch (error) {
84
+ this.stats.start_errors += 1;
85
+ this.started = false;
86
+ if (this.offTransportMessage) {
87
+ this.offTransportMessage();
88
+ this.offTransportMessage = null;
89
+ }
90
+ try {
91
+ await this.transport.stop();
92
+ }
93
+ catch {
94
+ this.stats.stop_errors += 1;
95
+ }
96
+ throw new Error(`Peer discovery start failed: ${this.errorMessage(error)}`);
97
+ }
98
+ }
99
+ async stop() {
100
+ if (!this.started) {
101
+ return;
102
+ }
103
+ try {
104
+ await this.peerDiscovery.stop();
105
+ }
106
+ catch {
107
+ this.stats.discovery_errors += 1;
108
+ this.stats.stop_errors += 1;
109
+ }
110
+ if (this.offTransportMessage) {
111
+ this.offTransportMessage();
112
+ this.offTransportMessage = null;
113
+ }
114
+ try {
115
+ await this.transport.stop();
116
+ }
117
+ catch {
118
+ this.stats.stop_errors += 1;
119
+ }
120
+ this.started = false;
121
+ }
122
+ async publish(topic, data) {
123
+ if (!this.started) {
124
+ return;
125
+ }
126
+ this.stats.publish_attempted += 1;
127
+ if (!this.isValidTopic(topic)) {
128
+ this.stats.dropped_malformed += 1;
129
+ return;
130
+ }
131
+ const envelope = {
132
+ version: 1,
133
+ message_id: (0, crypto_1.randomUUID)(),
134
+ topic: this.topicKey(topic),
135
+ source_peer_id: this.peerId,
136
+ timestamp: Date.now(),
137
+ payload: this.topicCodec.encode(topic, data),
138
+ };
139
+ const raw = this.envelopeCodec.encode(envelope);
140
+ if (raw.length > this.maxMessageBytes) {
141
+ this.stats.dropped_oversized += 1;
142
+ return;
143
+ }
144
+ try {
145
+ await this.transport.send(raw);
146
+ this.stats.publish_sent += 1;
147
+ }
148
+ catch {
149
+ this.stats.send_errors += 1;
150
+ throw new Error("Transport send failed");
151
+ }
152
+ }
153
+ subscribe(topic, handler) {
154
+ if (!this.isValidTopic(topic)) {
155
+ return;
156
+ }
157
+ const key = this.topicKey(topic);
158
+ if (!this.handlers.has(key)) {
159
+ this.handlers.set(key, new Set());
160
+ }
161
+ this.handlers.get(key)?.add(handler);
162
+ }
163
+ listPeers() {
164
+ return this.peerDiscovery.listPeers();
165
+ }
166
+ getDiagnostics() {
167
+ const peers = this.listPeers();
168
+ const online = peers.filter((peer) => peer.status === "online").length;
169
+ return {
170
+ adapter: "real-preview",
171
+ peer_id: this.peerId,
172
+ namespace: this.namespace,
173
+ components: {
174
+ transport: this.transport.constructor.name,
175
+ discovery: this.peerDiscovery.constructor.name,
176
+ envelope_codec: this.envelopeCodec.constructor.name,
177
+ topic_codec: this.topicCodec.constructor.name,
178
+ },
179
+ limits: {
180
+ max_message_bytes: this.maxMessageBytes,
181
+ dedupe_window_ms: this.dedupeWindowMs,
182
+ dedupe_max_entries: this.dedupeMaxEntries,
183
+ max_future_drift_ms: this.maxFutureDriftMs,
184
+ max_past_drift_ms: this.maxPastDriftMs,
185
+ },
186
+ config: {
187
+ started: this.started,
188
+ topic_handler_count: this.handlers.size,
189
+ transport: this.transport.getConfig?.() ?? null,
190
+ discovery: this.peerDiscovery.getConfig?.() ?? null,
191
+ },
192
+ peers: {
193
+ total: peers.length,
194
+ online,
195
+ stale: Math.max(0, peers.length - online),
196
+ items: peers,
197
+ },
198
+ stats: { ...this.stats },
199
+ transport_stats: this.transport.getStats?.() ?? null,
200
+ discovery_stats: this.peerDiscovery.getStats?.() ?? null,
201
+ };
202
+ }
203
+ onTransportMessage(raw) {
204
+ this.stats.received_total += 1;
205
+ if (raw.length > this.maxMessageBytes) {
206
+ this.stats.dropped_oversized += 1;
207
+ return;
208
+ }
209
+ const decoded = this.envelopeCodec.decode(raw);
210
+ if (!decoded) {
211
+ this.stats.dropped_decode_failed += 1;
212
+ this.stats.dropped_malformed += 1;
213
+ return;
214
+ }
215
+ const validated = (0, messageEnvelope_1.validateNetworkMessageEnvelope)(decoded.envelope, {
216
+ max_future_drift_ms: this.maxFutureDriftMs,
217
+ max_past_drift_ms: this.maxPastDriftMs,
218
+ });
219
+ if (!validated.ok || !validated.envelope) {
220
+ if (validated.reason === "timestamp_future_drift") {
221
+ this.stats.dropped_timestamp_future_drift += 1;
222
+ }
223
+ else if (validated.reason === "timestamp_past_drift") {
224
+ this.stats.dropped_timestamp_past_drift += 1;
225
+ }
226
+ else {
227
+ this.stats.dropped_malformed += 1;
228
+ }
229
+ return;
230
+ }
231
+ this.stats.received_validated += 1;
232
+ const envelope = validated.envelope;
233
+ if (!envelope.topic.startsWith(`${this.namespace}:`)) {
234
+ this.stats.dropped_namespace_mismatch += 1;
235
+ return;
236
+ }
237
+ if (this.isDuplicateMessage(envelope.message_id, envelope.timestamp)) {
238
+ this.stats.dropped_duplicate += 1;
239
+ return;
240
+ }
241
+ try {
242
+ this.peerDiscovery.observeEnvelope(envelope);
243
+ }
244
+ catch {
245
+ this.stats.discovery_errors += 1;
246
+ }
247
+ if (envelope.source_peer_id === this.peerId) {
248
+ this.stats.dropped_self += 1;
249
+ return;
250
+ }
251
+ const topic = this.stripNamespace(envelope.topic);
252
+ if (!topic) {
253
+ this.stats.dropped_namespace_mismatch += 1;
254
+ return;
255
+ }
256
+ const handlers = this.handlers.get(envelope.topic);
257
+ if (!handlers || handlers.size === 0) {
258
+ return;
259
+ }
260
+ try {
261
+ const payload = this.topicCodec.decode(topic, envelope.payload);
262
+ for (const handler of handlers) {
263
+ try {
264
+ handler(payload);
265
+ this.stats.delivered_total += 1;
266
+ }
267
+ catch {
268
+ this.stats.dropped_handler_error += 1;
269
+ }
270
+ }
271
+ }
272
+ catch {
273
+ this.stats.dropped_topic_decode_error += 1;
274
+ }
275
+ }
276
+ topicKey(topic) {
277
+ return `${this.namespace}:${topic}`;
278
+ }
279
+ stripNamespace(topicKey) {
280
+ const prefix = `${this.namespace}:`;
281
+ if (!topicKey.startsWith(prefix)) {
282
+ return null;
283
+ }
284
+ return topicKey.slice(prefix.length);
285
+ }
286
+ isDuplicateMessage(messageId, timestamp) {
287
+ const now = Date.now();
288
+ this.cleanupSeenMessageIds(now);
289
+ const existing = this.seenMessageIds.get(messageId);
290
+ if (existing && now - existing <= this.dedupeWindowMs) {
291
+ return true;
292
+ }
293
+ this.seenMessageIds.set(messageId, Number.isFinite(timestamp) ? timestamp : now);
294
+ if (this.seenMessageIds.size > this.dedupeMaxEntries) {
295
+ const oldestKey = this.seenMessageIds.keys().next().value;
296
+ if (oldestKey) {
297
+ this.seenMessageIds.delete(oldestKey);
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+ cleanupSeenMessageIds(now) {
303
+ for (const [id, ts] of this.seenMessageIds.entries()) {
304
+ if (now - ts > this.dedupeWindowMs) {
305
+ this.seenMessageIds.delete(id);
306
+ }
307
+ }
308
+ }
309
+ isValidTopic(topic) {
310
+ if (typeof topic !== "string") {
311
+ return false;
312
+ }
313
+ const normalized = topic.trim();
314
+ return normalized.length > 0 && !normalized.includes(":");
315
+ }
316
+ normalizeNamespace(namespace) {
317
+ const normalized = namespace.trim();
318
+ return normalized.length > 0 ? normalized : "silicaclaw.preview";
319
+ }
320
+ errorMessage(error) {
321
+ if (error instanceof Error) {
322
+ return error.message;
323
+ }
324
+ return String(error);
325
+ }
326
+ }
327
+ exports.RealNetworkAdapterPreview = RealNetworkAdapterPreview;
@@ -0,0 +1,23 @@
1
+ import { NetworkTransport, TransportConfigSnapshot, TransportMessageMeta, TransportStats } from "../abstractions/transport";
2
+ type UdpLanBroadcastTransportOptions = {
3
+ port?: number;
4
+ bindAddress?: string;
5
+ broadcastAddress?: string;
6
+ };
7
+ export declare class UdpLanBroadcastTransport implements NetworkTransport {
8
+ private socket;
9
+ private handlers;
10
+ private state;
11
+ private stats;
12
+ private port;
13
+ private bindAddress;
14
+ private broadcastAddress;
15
+ constructor(options?: UdpLanBroadcastTransportOptions);
16
+ start(): Promise<void>;
17
+ stop(): Promise<void>;
18
+ send(data: Buffer): Promise<void>;
19
+ onMessage(handler: (data: Buffer, meta: TransportMessageMeta) => void): () => void;
20
+ getStats(): TransportStats;
21
+ getConfig(): TransportConfigSnapshot;
22
+ }
23
+ export {};
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.UdpLanBroadcastTransport = void 0;
7
+ const dgram_1 = __importDefault(require("dgram"));
8
+ class UdpLanBroadcastTransport {
9
+ socket = null;
10
+ handlers = new Set();
11
+ state = "stopped";
12
+ stats = {
13
+ starts: 0,
14
+ stops: 0,
15
+ start_errors: 0,
16
+ stop_errors: 0,
17
+ sent_messages: 0,
18
+ sent_bytes: 0,
19
+ send_errors: 0,
20
+ received_messages: 0,
21
+ received_bytes: 0,
22
+ receive_errors: 0,
23
+ last_sent_at: 0,
24
+ last_received_at: 0,
25
+ last_error_at: 0,
26
+ };
27
+ port;
28
+ bindAddress;
29
+ broadcastAddress;
30
+ constructor(options = {}) {
31
+ this.port = options.port ?? 44123;
32
+ this.bindAddress = options.bindAddress ?? "0.0.0.0";
33
+ this.broadcastAddress = options.broadcastAddress ?? "255.255.255.255";
34
+ }
35
+ async start() {
36
+ if (this.socket) {
37
+ return;
38
+ }
39
+ this.state = "starting";
40
+ this.socket = dgram_1.default.createSocket({ type: "udp4", reuseAddr: true });
41
+ this.socket.on("error", () => {
42
+ this.stats.receive_errors += 1;
43
+ this.stats.last_error_at = Date.now();
44
+ this.state = "error";
45
+ });
46
+ this.socket.on("message", (msg, rinfo) => {
47
+ this.stats.received_messages += 1;
48
+ this.stats.received_bytes += msg.length;
49
+ this.stats.last_received_at = Date.now();
50
+ const meta = {
51
+ remote_address: rinfo.address,
52
+ remote_port: rinfo.port,
53
+ transport: "udp-lan-broadcast",
54
+ };
55
+ for (const handler of this.handlers) {
56
+ try {
57
+ handler(msg, meta);
58
+ }
59
+ catch {
60
+ this.stats.receive_errors += 1;
61
+ this.stats.last_error_at = Date.now();
62
+ }
63
+ }
64
+ });
65
+ await new Promise((resolve, reject) => {
66
+ if (!this.socket) {
67
+ this.state = "error";
68
+ reject(new Error("Transport socket unavailable"));
69
+ return;
70
+ }
71
+ this.socket.once("error", reject);
72
+ this.socket.bind(this.port, this.bindAddress, () => {
73
+ if (!this.socket) {
74
+ this.state = "error";
75
+ reject(new Error("Transport socket unavailable after bind"));
76
+ return;
77
+ }
78
+ this.socket.setBroadcast(true);
79
+ this.socket.off("error", reject);
80
+ this.stats.starts += 1;
81
+ this.state = "running";
82
+ resolve();
83
+ });
84
+ }).catch((error) => {
85
+ this.stats.start_errors += 1;
86
+ this.stats.last_error_at = Date.now();
87
+ this.state = "error";
88
+ this.socket = null;
89
+ throw error;
90
+ });
91
+ }
92
+ async stop() {
93
+ if (!this.socket) {
94
+ return;
95
+ }
96
+ this.state = "stopping";
97
+ const socket = this.socket;
98
+ this.socket = null;
99
+ await new Promise((resolve) => {
100
+ socket.close(() => resolve());
101
+ }).then(() => {
102
+ this.stats.stops += 1;
103
+ this.state = "stopped";
104
+ }).catch((error) => {
105
+ this.stats.stop_errors += 1;
106
+ this.stats.last_error_at = Date.now();
107
+ this.state = "error";
108
+ throw error;
109
+ });
110
+ }
111
+ async send(data) {
112
+ if (!this.socket) {
113
+ return;
114
+ }
115
+ await new Promise((resolve, reject) => {
116
+ if (!this.socket) {
117
+ resolve();
118
+ return;
119
+ }
120
+ this.socket.send(data, this.port, this.broadcastAddress, (error) => {
121
+ if (error) {
122
+ this.stats.send_errors += 1;
123
+ this.stats.last_error_at = Date.now();
124
+ reject(error);
125
+ return;
126
+ }
127
+ this.stats.sent_messages += 1;
128
+ this.stats.sent_bytes += data.length;
129
+ this.stats.last_sent_at = Date.now();
130
+ resolve();
131
+ });
132
+ });
133
+ }
134
+ onMessage(handler) {
135
+ this.handlers.add(handler);
136
+ return () => {
137
+ this.handlers.delete(handler);
138
+ };
139
+ }
140
+ getStats() {
141
+ return { ...this.stats };
142
+ }
143
+ getConfig() {
144
+ return {
145
+ transport: "udp-lan-broadcast",
146
+ state: this.state,
147
+ bind_address: this.bindAddress,
148
+ broadcast_address: this.broadcastAddress,
149
+ port: this.port,
150
+ };
151
+ }
152
+ }
153
+ exports.UdpLanBroadcastTransport = UdpLanBroadcastTransport;
@@ -0,0 +1,6 @@
1
+ export interface NetworkAdapter {
2
+ start(): Promise<void>;
3
+ stop(): Promise<void>;
4
+ publish(topic: string, data: any): Promise<void>;
5
+ subscribe(topic: string, handler: (data: any) => void): void;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });