@connekt/client 0.0.0-stage → 0.1.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/dist/peer.js ADDED
@@ -0,0 +1,1119 @@
1
+ import { ConnektError, DEFAULT_STREAM_CHUNK_SIZE, Payload, Target, toRawBytes } from "./common.js";
2
+ import { decodeFrame, encodeFrame, FLAG_IS_ERROR, FrameType, isFrameError, makeFrame, parseFrameHeader } from "./protocol.js";
3
+ export { ConnektError, DEFAULT_STREAM_CHUNK_SIZE, Payload, Target };
4
+ const MAX_WS_BUFFERED_BYTES = 4 * 1024 * 1024;
5
+ const SDK_VERSION = "0.1.0";
6
+ export class BrowserWsAdapter {
7
+ kind = "lan";
8
+ ws = null;
9
+ get isOpen() {
10
+ return this.ws !== null && this.ws.readyState === WebSocket.OPEN;
11
+ }
12
+ connect(url, callbacks) {
13
+ this.disconnect();
14
+ return new Promise((resolve, reject)=>{
15
+ let opened = false;
16
+ let closedNotified = false;
17
+ const ws = new WebSocket(url);
18
+ ws.binaryType = "arraybuffer";
19
+ this.ws = ws;
20
+ const notifyClose = (reason)=>{
21
+ if (closedNotified) return;
22
+ closedNotified = true;
23
+ if (this.ws === ws) this.ws = null;
24
+ callbacks.onClose(reason);
25
+ };
26
+ ws.addEventListener("open", ()=>{
27
+ opened = true;
28
+ resolve();
29
+ });
30
+ ws.addEventListener("error", ()=>{
31
+ if (!opened) {
32
+ if (this.ws === ws) this.ws = null;
33
+ reject(new ConnektError("PEER_OFFLINE", `Failed to connect WebSocket to ${url}`));
34
+ }
35
+ });
36
+ ws.addEventListener("close", (evt)=>{
37
+ if (!opened) {
38
+ if (this.ws === ws) this.ws = null;
39
+ reject(new ConnektError("PEER_OFFLINE", `WebSocket closed before opening (code=${evt.code})`));
40
+ return;
41
+ }
42
+ notifyClose(evt.reason || `code=${evt.code}`);
43
+ });
44
+ ws.addEventListener("message", (evt)=>{
45
+ if (evt.data instanceof ArrayBuffer) {
46
+ callbacks.onFrame(new Uint8Array(evt.data));
47
+ } else if (typeof Blob !== "undefined" && evt.data instanceof Blob) {
48
+ void evt.data.arrayBuffer().then((buf)=>callbacks.onFrame(new Uint8Array(buf)));
49
+ }
50
+ });
51
+ });
52
+ }
53
+ disconnect() {
54
+ const ws = this.ws;
55
+ this.ws = null;
56
+ if (ws && (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING)) {
57
+ try {
58
+ ws.close();
59
+ } catch {}
60
+ }
61
+ }
62
+ sendFrame(bytes) {
63
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
64
+ throw new ConnektError("PEER_OFFLINE", "WebSocket transport is not open");
65
+ }
66
+ this.ws.send(bytes);
67
+ }
68
+ canSend() {
69
+ return this.ws !== null && this.ws.readyState === WebSocket.OPEN && this.ws.bufferedAmount < MAX_WS_BUFFERED_BYTES;
70
+ }
71
+ }
72
+ const STORAGE_PEER_ID_KEY = "connekt.peer.id";
73
+ const STORAGE_LAST_HUB_KEY = "connekt.peer.last_hub_url";
74
+ function getSafeStorage() {
75
+ try {
76
+ if (typeof globalThis !== "undefined" && "localStorage" in globalThis && globalThis.localStorage) {
77
+ return globalThis.localStorage;
78
+ }
79
+ } catch {}
80
+ return null;
81
+ }
82
+ function generateRandomId() {
83
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
84
+ return crypto.randomUUID().replace(/-/g, "").slice(0, 12);
85
+ }
86
+ return Math.random().toString(36).slice(2, 14);
87
+ }
88
+ function detectClientEnvironment(options) {
89
+ const g = globalThis;
90
+ const ua = g.navigator?.userAgent ?? "";
91
+ const docTitle = g.document?.title?.trim();
92
+ const host = g.location?.hostname?.trim();
93
+ let manufacturer = "Browser";
94
+ let model = "Web Browser";
95
+ let osVersion = "Web";
96
+ if (/iPhone/i.test(ua)) {
97
+ manufacturer = "Apple";
98
+ model = /CriOS/i.test(ua) ? "iPhone Chrome" : "iPhone Safari";
99
+ const m = ua.match(/OS (\d+[_.]\d+)/);
100
+ osVersion = m ? `iOS ${m[1].replace("_", ".")}` : "iOS";
101
+ } else if (/iPad/i.test(ua)) {
102
+ manufacturer = "Apple";
103
+ model = "iPad Safari";
104
+ const m = ua.match(/OS (\d+[_.]\d+)/);
105
+ osVersion = m ? `iPadOS ${m[1].replace("_", ".")}` : "iPadOS";
106
+ } else if (/Android/i.test(ua)) {
107
+ manufacturer = "Android";
108
+ model = /Chrome/i.test(ua) ? "Android Chrome" : "Android Browser";
109
+ const m = ua.match(/Android\s+([\d.]+)/i);
110
+ osVersion = m ? `Android ${m[1]}` : "Android";
111
+ } else if (/Macintosh|Mac OS X/i.test(ua)) {
112
+ manufacturer = "Apple";
113
+ model = /Chrome/i.test(ua) ? "Mac Chrome" : /Safari/i.test(ua) ? "Mac Safari" : "Mac Browser";
114
+ osVersion = "macOS";
115
+ } else if (/Windows/i.test(ua)) {
116
+ manufacturer = "PC";
117
+ model = /Edg/i.test(ua) ? "Windows Edge" : /Chrome/i.test(ua) ? "Windows Chrome" : "Windows Browser";
118
+ osVersion = "Windows";
119
+ } else if (typeof process !== "undefined" && process.versions?.node) {
120
+ manufacturer = "Node.js";
121
+ model = `Node ${process.versions.node}`;
122
+ osVersion = process.platform;
123
+ }
124
+ return {
125
+ appName: options.appName?.trim() || docTitle || "Web Peer",
126
+ packageName: options.packageName?.trim() || host || "web.page",
127
+ model,
128
+ manufacturer,
129
+ osVersion
130
+ };
131
+ }
132
+ export function resolveHubUrl(explicitUrl) {
133
+ if (explicitUrl && explicitUrl.trim().length > 0) {
134
+ return explicitUrl.trim();
135
+ }
136
+ const loc = typeof globalThis !== "undefined" && "location" in globalThis ? globalThis.location : undefined;
137
+ if (loc && typeof loc.search === "string" && loc.search.length > 0) {
138
+ const params = new URLSearchParams(loc.search);
139
+ const fromQuery = params.get("hub")?.trim();
140
+ if (fromQuery) return fromQuery;
141
+ }
142
+ const storage = getSafeStorage();
143
+ const cached = storage?.getItem(STORAGE_LAST_HUB_KEY)?.trim();
144
+ if (loc && (loc.protocol === "http:" || loc.protocol === "https:") && loc.host) {
145
+ const wsProto = loc.protocol === "https:" ? "wss:" : "ws:";
146
+ return `${wsProto}//${loc.host}/ws`;
147
+ }
148
+ return cached || null;
149
+ }
150
+ function buildTargetFields(to) {
151
+ if (typeof to === "string") {
152
+ return {
153
+ dst: to
154
+ };
155
+ }
156
+ return {
157
+ dst: "",
158
+ dsts: Array.from(to)
159
+ };
160
+ }
161
+ class PeerOutboundStream {
162
+ streamId;
163
+ channel;
164
+ peer;
165
+ closed = false;
166
+ remoteError = null;
167
+ constructor(peer, streamId, channel){
168
+ this.peer = peer;
169
+ this.streamId = streamId;
170
+ this.channel = channel;
171
+ }
172
+ get isClosed() {
173
+ return this.closed;
174
+ }
175
+ _onRemoteClose(code, message) {
176
+ this.closed = true;
177
+ this.remoteError = new ConnektError(code, message);
178
+ }
179
+ async write(data) {
180
+ if (this.closed) {
181
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream is already closed");
182
+ }
183
+ const bytes = toRawBytes(data);
184
+ for(let offset = 0; offset < bytes.byteLength; offset += DEFAULT_STREAM_CHUNK_SIZE){
185
+ if (this.closed) {
186
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream closed mid-write");
187
+ }
188
+ await this.peer._waitWritable();
189
+ if (this.closed) {
190
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream closed mid-write");
191
+ }
192
+ const slice = bytes.subarray(offset, Math.min(offset + DEFAULT_STREAM_CHUNK_SIZE, bytes.byteLength));
193
+ this.peer._sendStreamChunk(this.streamId, slice);
194
+ }
195
+ }
196
+ tryWrite(data) {
197
+ if (this.closed || !this.peer._canSend()) return false;
198
+ const bytes = toRawBytes(data);
199
+ for(let offset = 0; offset < bytes.byteLength; offset += DEFAULT_STREAM_CHUNK_SIZE){
200
+ if (this.closed || !this.peer._canSend()) return false;
201
+ const slice = bytes.subarray(offset, Math.min(offset + DEFAULT_STREAM_CHUNK_SIZE, bytes.byteLength));
202
+ try {
203
+ this.peer._sendStreamChunk(this.streamId, slice);
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ return true;
209
+ }
210
+ async writeFromBlob(blob, chunkSize = DEFAULT_STREAM_CHUNK_SIZE) {
211
+ const step = Math.max(1024, chunkSize);
212
+ let total = 0;
213
+ for(let offset = 0; offset < blob.size; offset += step){
214
+ if (this.closed) {
215
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream closed mid-write");
216
+ }
217
+ const sliceBlob = blob.slice(offset, Math.min(offset + step, blob.size));
218
+ const buf = new Uint8Array(await sliceBlob.arrayBuffer());
219
+ await this.write(buf);
220
+ total += buf.byteLength;
221
+ }
222
+ return total;
223
+ }
224
+ close() {
225
+ if (this.closed) return;
226
+ this.closed = true;
227
+ this.peer._closeOutboundStream(this.streamId, this.channel, true);
228
+ }
229
+ abort(reason = "aborted") {
230
+ if (this.closed) return;
231
+ this.closed = true;
232
+ this.peer._closeOutboundStream(this.streamId, this.channel, false, "HANDLER_ERROR", reason);
233
+ }
234
+ }
235
+ class PeerInboundStream {
236
+ streamId;
237
+ src;
238
+ channel;
239
+ meta;
240
+ peer;
241
+ queue = [];
242
+ waiter = null;
243
+ finished = false;
244
+ constructor(peer, streamId, src, channel, meta){
245
+ this.peer = peer;
246
+ this.streamId = streamId;
247
+ this.src = src;
248
+ this.channel = channel;
249
+ this.meta = meta;
250
+ }
251
+ get isFinished() {
252
+ return this.finished;
253
+ }
254
+ _pushChunk(bytes) {
255
+ if (this.finished) return;
256
+ this.enqueue({
257
+ kind: "chunk",
258
+ payload: new Payload(bytes, "base64")
259
+ });
260
+ }
261
+ _pushClose(ok, errCode, errMsg) {
262
+ if (this.finished) return;
263
+ this.finished = true;
264
+ if (ok) {
265
+ this.enqueue({
266
+ kind: "eof"
267
+ });
268
+ } else {
269
+ this.enqueue({
270
+ kind: "error",
271
+ err: new ConnektError(errCode ?? "INTERNAL_ERROR", errMsg ?? "Stream closed with error")
272
+ });
273
+ }
274
+ }
275
+ enqueue(item) {
276
+ if (this.waiter) {
277
+ const resolve = this.waiter;
278
+ this.waiter = null;
279
+ resolve(item);
280
+ } else {
281
+ this.queue.push(item);
282
+ }
283
+ }
284
+ nextItem() {
285
+ if (this.queue.length > 0) {
286
+ return Promise.resolve(this.queue.shift());
287
+ }
288
+ return new Promise((resolve)=>{
289
+ this.waiter = resolve;
290
+ });
291
+ }
292
+ reject(reason = "rejected") {
293
+ if (this.finished) return;
294
+ this.finished = true;
295
+ this.queue.length = 0;
296
+ this.enqueue({
297
+ kind: "eof"
298
+ });
299
+ this.peer._terminateInboundStream(this.streamId, this.channel, "STREAM_REJECTED", reason);
300
+ }
301
+ cancel(reason = "cancelled") {
302
+ if (this.finished) return;
303
+ this.finished = true;
304
+ this.queue.length = 0;
305
+ this.enqueue({
306
+ kind: "eof"
307
+ });
308
+ this.peer._terminateInboundStream(this.streamId, this.channel, "STREAM_CANCELLED", reason);
309
+ }
310
+ async readToBlob(mimeType) {
311
+ const parts = [];
312
+ for await (const chunk of this){
313
+ const copy = new Uint8Array(chunk.bytes.byteLength);
314
+ copy.set(chunk.bytes);
315
+ parts.push(copy);
316
+ }
317
+ const resolvedType = mimeType ?? this.meta.mime ?? "application/octet-stream";
318
+ return new Blob(parts, {
319
+ type: resolvedType
320
+ });
321
+ }
322
+ async *[Symbol.asyncIterator]() {
323
+ try {
324
+ while(true){
325
+ const item = await this.nextItem();
326
+ if (item.kind === "chunk") {
327
+ yield item.payload;
328
+ } else if (item.kind === "eof") {
329
+ return;
330
+ } else {
331
+ throw item.err;
332
+ }
333
+ }
334
+ } finally{
335
+ if (!this.finished) {
336
+ this.cancel("iterator exited before EOF");
337
+ }
338
+ }
339
+ }
340
+ }
341
+ export class ConnektPeerChannel {
342
+ name;
343
+ peerProvider;
344
+ constructor(name, peerProvider){
345
+ this.name = name;
346
+ this.peerProvider = peerProvider;
347
+ }
348
+ post(data, to = Target.PC) {
349
+ return this.peerProvider()._post(this.name, data, to);
350
+ }
351
+ send(data, to = Target.PC) {
352
+ return this.peerProvider()._send(this.name, data, to);
353
+ }
354
+ request(data = Payload.EMPTY, to = Target.PC, timeoutMs) {
355
+ return this.peerProvider()._request(this.name, data, to, timeoutMs);
356
+ }
357
+ openStream(to = Target.PC, meta = {}) {
358
+ return this.peerProvider()._openStream(this.name, to, meta);
359
+ }
360
+ onMessage(listener) {
361
+ return this.peerProvider()._onMessage(this.name, listener);
362
+ }
363
+ onRequest(handler) {
364
+ return this.peerProvider()._onRequest(this.name, handler);
365
+ }
366
+ onStream(handler) {
367
+ return this.peerProvider()._onStream(this.name, handler);
368
+ }
369
+ }
370
+ export class ConnektPeer {
371
+ peerId;
372
+ deviceId;
373
+ options;
374
+ adapter = null;
375
+ activeUrl = null;
376
+ currentState = {
377
+ status: "disconnected"
378
+ };
379
+ peersCache = [];
380
+ shouldRun = false;
381
+ reconnectAttempt = 0;
382
+ reconnectTimer = null;
383
+ heartbeatTimer = null;
384
+ connectionGeneration = 0;
385
+ reqSeq = 1;
386
+ streamSeq = 1;
387
+ pendingHandshake = null;
388
+ pendingReqs = new Map();
389
+ outboundStreams = new Map();
390
+ inboundStreams = new Map();
391
+ messageListeners = new Map();
392
+ anyMessageListeners = new Set();
393
+ requestHandlers = new Map();
394
+ streamHandlers = new Map();
395
+ stateListeners = new Set();
396
+ peersListeners = new Set();
397
+ constructor(options = {}){
398
+ this.options = {
399
+ ...options
400
+ };
401
+ this.peerId = this.loadOrCreatePeerId(options.persistIdentity !== false);
402
+ this.deviceId = this.peerId;
403
+ }
404
+ get isConnected() {
405
+ return this.currentState.status === "connected";
406
+ }
407
+ get state() {
408
+ return this.currentState;
409
+ }
410
+ get peers() {
411
+ return [
412
+ ...this.peersCache
413
+ ];
414
+ }
415
+ async connect(url) {
416
+ const resolved = resolveHubUrl(url ?? this.options.url);
417
+ if (!resolved) {
418
+ throw new ConnektError("INVALID_REQUEST", "Unable to resolve Hub WebSocket URL; pass { url } or open with ?hub=ws://<ip>:9527/ws");
419
+ }
420
+ this.activeUrl = resolved;
421
+ this.shouldRun = true;
422
+ this.reconnectAttempt = 0;
423
+ this.clearReconnectTimer();
424
+ if (this.options.persistIdentity !== false) {
425
+ getSafeStorage()?.setItem(STORAGE_LAST_HUB_KEY, resolved);
426
+ }
427
+ await this.openOnce(resolved);
428
+ }
429
+ disconnect() {
430
+ this.shouldRun = false;
431
+ this.connectionGeneration += 1;
432
+ this.clearReconnectTimer();
433
+ this.clearHeartbeatTimer();
434
+ this.rejectHandshake(new ConnektError("PEER_OFFLINE", "ConnektPeer disconnected"));
435
+ const adapter = this.adapter;
436
+ this.adapter = null;
437
+ adapter?.disconnect();
438
+ this.failInFlight("ConnektPeer disconnected");
439
+ this.peersCache = [];
440
+ this.setState({
441
+ status: "disconnected"
442
+ });
443
+ this.emitPeers();
444
+ }
445
+ async switchHub(url) {
446
+ this.options = {
447
+ ...this.options,
448
+ url
449
+ };
450
+ this.disconnect();
451
+ await this.connect(url);
452
+ }
453
+ _configure(options) {
454
+ this.options = {
455
+ ...this.options,
456
+ ...options
457
+ };
458
+ }
459
+ channel(name) {
460
+ return new ConnektPeerChannel(name, ()=>this);
461
+ }
462
+ onAnyMessage(listener) {
463
+ this.anyMessageListeners.add(listener);
464
+ return {
465
+ cancel: ()=>this.anyMessageListeners.delete(listener)
466
+ };
467
+ }
468
+ onStateChanged(listener) {
469
+ this.stateListeners.add(listener);
470
+ return {
471
+ cancel: ()=>this.stateListeners.delete(listener)
472
+ };
473
+ }
474
+ onPeersChanged(listener) {
475
+ this.peersListeners.add(listener);
476
+ return {
477
+ cancel: ()=>this.peersListeners.delete(listener)
478
+ };
479
+ }
480
+ _post(channel, data, to) {
481
+ if (!this.isConnected || !this._canSend()) return false;
482
+ try {
483
+ const frame = makeFrame({
484
+ frameType: FrameType.DATA,
485
+ headerObj: {
486
+ src: this.peerId,
487
+ ...buildTargetFields(to),
488
+ ch: channel
489
+ },
490
+ payload: toRawBytes(data)
491
+ });
492
+ this.sendWireFrame(frame);
493
+ return true;
494
+ } catch {
495
+ return false;
496
+ }
497
+ }
498
+ async _send(channel, data, to) {
499
+ if (!this.isConnected || !this.adapter?.isOpen) {
500
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer is not connected");
501
+ }
502
+ await this._waitWritable();
503
+ if (!this.isConnected || !this.adapter?.isOpen) {
504
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer is not connected");
505
+ }
506
+ const frame = makeFrame({
507
+ frameType: FrameType.DATA,
508
+ headerObj: {
509
+ src: this.peerId,
510
+ ...buildTargetFields(to),
511
+ ch: channel
512
+ },
513
+ payload: toRawBytes(data)
514
+ });
515
+ this.sendWireFrame(frame);
516
+ }
517
+ async _request(channel, data, to, timeoutMs) {
518
+ if (!this.isConnected || !this.adapter?.isOpen) {
519
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer is not connected");
520
+ }
521
+ const effectiveTimeout = timeoutMs ?? this.options.defaultRequestTimeoutMs ?? 5_000;
522
+ const reqId = this.allocReqId();
523
+ const frame = makeFrame({
524
+ frameType: FrameType.REQ,
525
+ reqId,
526
+ headerObj: {
527
+ src: this.peerId,
528
+ dst: to,
529
+ ch: channel
530
+ },
531
+ payload: toRawBytes(data)
532
+ });
533
+ return new Promise((resolve, reject)=>{
534
+ const timer = setTimeout(()=>{
535
+ this.pendingReqs.delete(reqId);
536
+ reject(new ConnektError("TIMEOUT", `Request timed out after ${effectiveTimeout}ms`));
537
+ }, effectiveTimeout);
538
+ this.pendingReqs.set(reqId, {
539
+ resolve,
540
+ reject,
541
+ timer
542
+ });
543
+ try {
544
+ this.sendWireFrame(frame);
545
+ } catch (err) {
546
+ clearTimeout(timer);
547
+ this.pendingReqs.delete(reqId);
548
+ reject(err);
549
+ }
550
+ });
551
+ }
552
+ _openStream(channel, to, meta) {
553
+ if (!this.isConnected || !this.adapter?.isOpen) {
554
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer is not connected");
555
+ }
556
+ const streamId = this.allocStreamId();
557
+ const stream = new PeerOutboundStream(this, streamId, channel);
558
+ this.outboundStreams.set(streamId, stream);
559
+ const header = {
560
+ src: this.peerId,
561
+ ...buildTargetFields(to),
562
+ ch: channel
563
+ };
564
+ if (Object.keys(meta).length > 0) {
565
+ header.meta = meta;
566
+ }
567
+ try {
568
+ this.sendWireFrame(makeFrame({
569
+ frameType: FrameType.STREAM_OPEN,
570
+ streamId,
571
+ headerObj: header
572
+ }));
573
+ } catch (err) {
574
+ this.outboundStreams.delete(streamId);
575
+ throw err;
576
+ }
577
+ return stream;
578
+ }
579
+ _canSend() {
580
+ return this.adapter?.canSend() ?? false;
581
+ }
582
+ async _waitWritable() {
583
+ while(this.adapter?.isOpen && !this.adapter.canSend()){
584
+ await new Promise((r)=>setTimeout(r, 4));
585
+ }
586
+ }
587
+ _sendStreamChunk(streamId, payload) {
588
+ if (!this.isConnected || !this.adapter?.isOpen) {
589
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer is not connected");
590
+ }
591
+ this.sendWireFrame(makeFrame({
592
+ frameType: FrameType.STREAM_CHUNK,
593
+ streamId,
594
+ payload
595
+ }));
596
+ }
597
+ _closeOutboundStream(streamId, channel, ok, errCode, errMsg) {
598
+ this.outboundStreams.delete(streamId);
599
+ if (!this.adapter?.isOpen) return;
600
+ try {
601
+ if (ok) {
602
+ this.sendWireFrame(makeFrame({
603
+ frameType: FrameType.STREAM_CLOSE,
604
+ streamId
605
+ }));
606
+ } else {
607
+ this.sendWireFrame(makeFrame({
608
+ frameType: FrameType.STREAM_CLOSE,
609
+ flags: FLAG_IS_ERROR,
610
+ streamId,
611
+ headerObj: {
612
+ src: this.peerId,
613
+ dst: "",
614
+ ch: channel,
615
+ err_code: errCode ?? "HANDLER_ERROR",
616
+ err_msg: errMsg ?? "aborted"
617
+ }
618
+ }));
619
+ }
620
+ } catch {}
621
+ }
622
+ _terminateInboundStream(streamId, channel, errCode, errMsg) {
623
+ this.inboundStreams.delete(streamId);
624
+ if (!this.adapter?.isOpen) return;
625
+ try {
626
+ this.sendWireFrame(makeFrame({
627
+ frameType: FrameType.STREAM_CLOSE,
628
+ flags: FLAG_IS_ERROR,
629
+ streamId,
630
+ headerObj: {
631
+ src: this.peerId,
632
+ dst: "",
633
+ ch: channel,
634
+ err_code: errCode,
635
+ err_msg: errMsg
636
+ }
637
+ }));
638
+ } catch {}
639
+ }
640
+ _onMessage(channel, listener) {
641
+ let set = this.messageListeners.get(channel);
642
+ if (!set) {
643
+ set = new Set();
644
+ this.messageListeners.set(channel, set);
645
+ }
646
+ set.add(listener);
647
+ return {
648
+ cancel: ()=>set.delete(listener)
649
+ };
650
+ }
651
+ _onRequest(channel, handler) {
652
+ this.requestHandlers.set(channel, handler);
653
+ return {
654
+ cancel: ()=>{
655
+ if (this.requestHandlers.get(channel) === handler) {
656
+ this.requestHandlers.delete(channel);
657
+ }
658
+ }
659
+ };
660
+ }
661
+ _onStream(channel, handler) {
662
+ this.streamHandlers.set(channel, handler);
663
+ return {
664
+ cancel: ()=>{
665
+ if (this.streamHandlers.get(channel) === handler) {
666
+ this.streamHandlers.delete(channel);
667
+ }
668
+ }
669
+ };
670
+ }
671
+ async openOnce(url) {
672
+ const gen = ++this.connectionGeneration;
673
+ this.clearHeartbeatTimer();
674
+ this.rejectHandshake(new ConnektError("PEER_OFFLINE", "Replaced by new connection attempt"));
675
+ this.adapter?.disconnect();
676
+ const adapter = this.options.transportAdapter ?? new BrowserWsAdapter();
677
+ this.adapter = adapter;
678
+ this.setState({
679
+ status: "connecting"
680
+ });
681
+ await adapter.connect(url, {
682
+ onFrame: (bytes)=>{
683
+ if (gen !== this.connectionGeneration) return;
684
+ this.handleRawFrame(bytes);
685
+ },
686
+ onClose: ()=>{
687
+ if (gen !== this.connectionGeneration) return;
688
+ this.handleTransportClosed();
689
+ }
690
+ });
691
+ if (gen !== this.connectionGeneration) {
692
+ adapter.disconnect();
693
+ return;
694
+ }
695
+ const env = detectClientEnvironment(this.options);
696
+ const hello = {
697
+ peer_id: this.peerId,
698
+ device_id: this.deviceId,
699
+ package_name: env.packageName,
700
+ app_name: env.appName,
701
+ process_name: "browser",
702
+ pid: 0,
703
+ platform: "web",
704
+ model: env.model,
705
+ manufacturer: env.manufacturer,
706
+ os_version: env.osVersion,
707
+ transport: adapter.kind,
708
+ sdk_version: SDK_VERSION
709
+ };
710
+ const handshakeTimeout = this.options.handshakeTimeoutMs ?? 5_000;
711
+ const ack = await new Promise((resolve, reject)=>{
712
+ const timer = setTimeout(()=>{
713
+ this.pendingHandshake = null;
714
+ adapter.disconnect();
715
+ reject(new ConnektError("TIMEOUT", `HELLO_ACK timed out after ${handshakeTimeout}ms`));
716
+ }, handshakeTimeout);
717
+ this.pendingHandshake = {
718
+ resolve,
719
+ reject,
720
+ timer
721
+ };
722
+ try {
723
+ this.sendWireFrame(makeFrame({
724
+ frameType: FrameType.HELLO,
725
+ headerObj: hello
726
+ }));
727
+ } catch (err) {
728
+ clearTimeout(timer);
729
+ this.pendingHandshake = null;
730
+ reject(err);
731
+ }
732
+ });
733
+ if (gen !== this.connectionGeneration) return;
734
+ this.reconnectAttempt = 0;
735
+ this.setState({
736
+ status: "connected",
737
+ activeTransport: adapter.kind,
738
+ allTransports: [
739
+ adapter.kind
740
+ ]
741
+ });
742
+ this.startHeartbeat(ack.heartbeat_interval_ms);
743
+ }
744
+ handleTransportClosed() {
745
+ this.clearHeartbeatTimer();
746
+ this.rejectHandshake(new ConnektError("PEER_OFFLINE", "Transport closed during handshake"));
747
+ this.failInFlight("Connection closed");
748
+ if (this.shouldRun && this.options.autoReconnect !== false && this.activeUrl) {
749
+ this.setState({
750
+ status: "connecting"
751
+ });
752
+ this.scheduleReconnect();
753
+ } else {
754
+ this.peersCache = [];
755
+ this.setState({
756
+ status: "disconnected"
757
+ });
758
+ this.emitPeers();
759
+ }
760
+ }
761
+ scheduleReconnect() {
762
+ this.clearReconnectTimer();
763
+ const maxDelay = this.options.maxReconnectDelayMs ?? 5_000;
764
+ const delay = Math.min(500 * Math.pow(2, this.reconnectAttempt), maxDelay);
765
+ this.reconnectAttempt += 1;
766
+ this.reconnectTimer = setTimeout(()=>{
767
+ this.reconnectTimer = null;
768
+ if (!this.shouldRun || !this.activeUrl) return;
769
+ void this.openOnce(this.activeUrl).catch(()=>{
770
+ if (this.shouldRun && this.options.autoReconnect !== false) {
771
+ this.scheduleReconnect();
772
+ }
773
+ });
774
+ }, delay);
775
+ }
776
+ startHeartbeat(intervalMs) {
777
+ this.clearHeartbeatTimer();
778
+ const period = Math.max(2_000, intervalMs || 10_000);
779
+ this.heartbeatTimer = setInterval(()=>{
780
+ if (!this.adapter?.isOpen) return;
781
+ try {
782
+ this.sendWireFrame(makeFrame({
783
+ frameType: FrameType.PING
784
+ }));
785
+ } catch {}
786
+ }, period);
787
+ }
788
+ handleRawFrame(bytes) {
789
+ let frame;
790
+ try {
791
+ frame = decodeFrame(bytes);
792
+ } catch {
793
+ return;
794
+ }
795
+ switch(frame.frameType){
796
+ case FrameType.HELLO_ACK:
797
+ {
798
+ const pending = this.pendingHandshake;
799
+ if (!pending) break;
800
+ clearTimeout(pending.timer);
801
+ this.pendingHandshake = null;
802
+ try {
803
+ pending.resolve(parseFrameHeader(frame));
804
+ } catch (err) {
805
+ pending.reject(err instanceof Error ? err : new Error(String(err)));
806
+ }
807
+ break;
808
+ }
809
+ case FrameType.PING:
810
+ {
811
+ try {
812
+ this.sendWireFrame(makeFrame({
813
+ frameType: FrameType.PONG
814
+ }));
815
+ } catch {}
816
+ break;
817
+ }
818
+ case FrameType.PONG:
819
+ break;
820
+ case FrameType.PEER_LIST:
821
+ {
822
+ try {
823
+ const parsed = parseFrameHeader(frame);
824
+ this.peersCache = parsed.peers ?? [];
825
+ this.emitPeers();
826
+ } catch {}
827
+ break;
828
+ }
829
+ case FrameType.DATA:
830
+ {
831
+ let route;
832
+ try {
833
+ route = parseFrameHeader(frame);
834
+ } catch {
835
+ break;
836
+ }
837
+ const payload = new Payload(frame.payload, "base64");
838
+ const msg = {
839
+ src: route.src ?? "",
840
+ dst: route.dst ?? "",
841
+ channel: route.ch ?? "",
842
+ payload,
843
+ text: payload.text,
844
+ bytes: payload.bytes
845
+ };
846
+ for (const l of this.anyMessageListeners)l(msg);
847
+ const set = this.messageListeners.get(msg.channel);
848
+ if (set) {
849
+ for (const l of set)l(msg);
850
+ }
851
+ break;
852
+ }
853
+ case FrameType.REQ:
854
+ {
855
+ let route;
856
+ try {
857
+ route = parseFrameHeader(frame);
858
+ } catch {
859
+ break;
860
+ }
861
+ const payload = new Payload(frame.payload, "base64");
862
+ const req = {
863
+ reqId: frame.reqId,
864
+ src: route.src ?? "",
865
+ channel: route.ch ?? "",
866
+ payload,
867
+ text: payload.text,
868
+ bytes: payload.bytes
869
+ };
870
+ void this.dispatchIncomingRequest(req);
871
+ break;
872
+ }
873
+ case FrameType.RESP:
874
+ {
875
+ const pending = this.pendingReqs.get(frame.reqId);
876
+ if (!pending) break;
877
+ clearTimeout(pending.timer);
878
+ this.pendingReqs.delete(frame.reqId);
879
+ if (isFrameError(frame)) {
880
+ let code = "INTERNAL_ERROR";
881
+ let message = "Request failed";
882
+ if (frame.header.byteLength > 0) {
883
+ try {
884
+ const hdr = parseFrameHeader(frame);
885
+ code = hdr.err_code ?? code;
886
+ message = hdr.err_msg ?? message;
887
+ } catch {}
888
+ }
889
+ pending.reject(new ConnektError(code, message));
890
+ } else {
891
+ pending.resolve(new Payload(frame.payload, "base64"));
892
+ }
893
+ break;
894
+ }
895
+ case FrameType.STREAM_OPEN:
896
+ {
897
+ let route;
898
+ try {
899
+ route = parseFrameHeader(frame);
900
+ } catch {
901
+ break;
902
+ }
903
+ const sid = frame.streamId;
904
+ const ch = route.ch ?? "";
905
+ const handler = this.streamHandlers.get(ch);
906
+ if (!handler) {
907
+ this._terminateInboundStream(sid, ch, "NO_HANDLER", `No stream handler registered for channel '${ch}'`);
908
+ break;
909
+ }
910
+ const stream = new PeerInboundStream(this, sid, route.src ?? "", ch, route.meta ?? {});
911
+ this.inboundStreams.set(sid, stream);
912
+ void Promise.resolve(handler(stream)).catch(()=>{
913
+ if (!stream.isFinished) stream.cancel("stream handler threw");
914
+ }).finally(()=>{
915
+ if (!stream.isFinished) stream.cancel("stream handler returned before EOF");
916
+ });
917
+ break;
918
+ }
919
+ case FrameType.STREAM_CHUNK:
920
+ {
921
+ const inbound = this.inboundStreams.get(frame.streamId);
922
+ if (inbound) {
923
+ inbound._pushChunk(frame.payload);
924
+ }
925
+ break;
926
+ }
927
+ case FrameType.STREAM_CLOSE:
928
+ {
929
+ const sid = frame.streamId;
930
+ const isErr = isFrameError(frame);
931
+ let errCode;
932
+ let errMsg;
933
+ if (isErr && frame.header.byteLength > 0) {
934
+ try {
935
+ const hdr = parseFrameHeader(frame);
936
+ errCode = hdr.err_code;
937
+ errMsg = hdr.err_msg;
938
+ } catch {}
939
+ }
940
+ const outbound = this.outboundStreams.get(sid);
941
+ if (outbound) {
942
+ this.outboundStreams.delete(sid);
943
+ outbound._onRemoteClose(errCode ?? "STREAM_CANCELLED", errMsg ?? "Stream closed by remote");
944
+ break;
945
+ }
946
+ const inbound = this.inboundStreams.get(sid);
947
+ if (inbound) {
948
+ this.inboundStreams.delete(sid);
949
+ inbound._pushClose(!isErr, errCode, errMsg);
950
+ }
951
+ break;
952
+ }
953
+ }
954
+ }
955
+ async dispatchIncomingRequest(req) {
956
+ const handler = this.requestHandlers.get(req.channel);
957
+ if (!handler) {
958
+ this.sendResponseError(req, "NO_HANDLER", `No request handler registered for '${req.channel}'`);
959
+ return;
960
+ }
961
+ try {
962
+ const result = await handler(req);
963
+ if (!this.adapter?.isOpen) return;
964
+ this.sendWireFrame(makeFrame({
965
+ frameType: FrameType.RESP,
966
+ reqId: req.reqId,
967
+ headerObj: {
968
+ src: this.peerId,
969
+ dst: req.src,
970
+ ch: req.channel
971
+ },
972
+ payload: toRawBytes(result)
973
+ }));
974
+ } catch (err) {
975
+ const code = err instanceof ConnektError ? err.code : "HANDLER_ERROR";
976
+ const msg = err instanceof Error ? err.message : String(err);
977
+ this.sendResponseError(req, code, msg);
978
+ }
979
+ }
980
+ sendResponseError(req, code, msg) {
981
+ if (!this.adapter?.isOpen) return;
982
+ try {
983
+ this.sendWireFrame(makeFrame({
984
+ frameType: FrameType.RESP,
985
+ flags: FLAG_IS_ERROR,
986
+ reqId: req.reqId,
987
+ headerObj: {
988
+ src: this.peerId,
989
+ dst: req.src,
990
+ ch: req.channel,
991
+ err_code: code,
992
+ err_msg: msg
993
+ }
994
+ }));
995
+ } catch {}
996
+ }
997
+ sendWireFrame(frame) {
998
+ if (!this.adapter?.isOpen) {
999
+ throw new ConnektError("PEER_OFFLINE", "ConnektPeer transport is not open");
1000
+ }
1001
+ this.adapter.sendFrame(encodeFrame(frame));
1002
+ }
1003
+ allocReqId() {
1004
+ const id = this.reqSeq;
1005
+ this.reqSeq = this.reqSeq + 1 & 0x7fffffff;
1006
+ if (this.reqSeq === 0) this.reqSeq = 1;
1007
+ return id;
1008
+ }
1009
+ allocStreamId() {
1010
+ const id = this.streamSeq;
1011
+ this.streamSeq = this.streamSeq + 1 & 0x7fffffff;
1012
+ if (this.streamSeq === 0) this.streamSeq = 1;
1013
+ return id;
1014
+ }
1015
+ clearReconnectTimer() {
1016
+ if (this.reconnectTimer !== null) {
1017
+ clearTimeout(this.reconnectTimer);
1018
+ this.reconnectTimer = null;
1019
+ }
1020
+ }
1021
+ clearHeartbeatTimer() {
1022
+ if (this.heartbeatTimer !== null) {
1023
+ clearInterval(this.heartbeatTimer);
1024
+ this.heartbeatTimer = null;
1025
+ }
1026
+ }
1027
+ rejectHandshake(err) {
1028
+ if (this.pendingHandshake) {
1029
+ clearTimeout(this.pendingHandshake.timer);
1030
+ const pending = this.pendingHandshake;
1031
+ this.pendingHandshake = null;
1032
+ pending.reject(err);
1033
+ }
1034
+ }
1035
+ failInFlight(reason) {
1036
+ for (const [id, pending] of this.pendingReqs){
1037
+ clearTimeout(pending.timer);
1038
+ pending.reject(new ConnektError("PEER_OFFLINE", reason));
1039
+ this.pendingReqs.delete(id);
1040
+ }
1041
+ for (const [sid, stream] of this.outboundStreams){
1042
+ stream._onRemoteClose("PEER_OFFLINE", reason);
1043
+ this.outboundStreams.delete(sid);
1044
+ }
1045
+ for (const [sid, stream] of this.inboundStreams){
1046
+ stream._pushClose(false, "PEER_OFFLINE", reason);
1047
+ this.inboundStreams.delete(sid);
1048
+ }
1049
+ }
1050
+ setState(next) {
1051
+ this.currentState = next;
1052
+ for (const listener of this.stateListeners){
1053
+ listener(next);
1054
+ }
1055
+ }
1056
+ emitPeers() {
1057
+ const snapshot = [
1058
+ ...this.peersCache
1059
+ ];
1060
+ for (const listener of this.peersListeners){
1061
+ listener(snapshot);
1062
+ }
1063
+ }
1064
+ loadOrCreatePeerId(persist) {
1065
+ const storage = persist ? getSafeStorage() : null;
1066
+ const existing = storage?.getItem(STORAGE_PEER_ID_KEY)?.trim();
1067
+ if (existing) return existing;
1068
+ const created = `web:${generateRandomId()}`;
1069
+ storage?.setItem(STORAGE_PEER_ID_KEY, created);
1070
+ return created;
1071
+ }
1072
+ }
1073
+ let defaultPeer = null;
1074
+ function getOrCreateDefaultPeer() {
1075
+ if (!defaultPeer) {
1076
+ defaultPeer = new ConnektPeer();
1077
+ }
1078
+ return defaultPeer;
1079
+ }
1080
+ export const Connekt = {
1081
+ async connect (options = {}) {
1082
+ const peer = getOrCreateDefaultPeer();
1083
+ peer._configure(options);
1084
+ await peer.connect(options.url);
1085
+ return peer;
1086
+ },
1087
+ disconnect () {
1088
+ defaultPeer?.disconnect();
1089
+ },
1090
+ get peerId () {
1091
+ return getOrCreateDefaultPeer().peerId;
1092
+ },
1093
+ get isConnected () {
1094
+ return defaultPeer?.isConnected ?? false;
1095
+ },
1096
+ get state () {
1097
+ return defaultPeer?.state ?? {
1098
+ status: "disconnected"
1099
+ };
1100
+ },
1101
+ get peers () {
1102
+ return defaultPeer?.peers ?? [];
1103
+ },
1104
+ switchHub (url) {
1105
+ return getOrCreateDefaultPeer().switchHub(url);
1106
+ },
1107
+ channel (name) {
1108
+ return new ConnektPeerChannel(name, getOrCreateDefaultPeer);
1109
+ },
1110
+ onAnyMessage (listener) {
1111
+ return getOrCreateDefaultPeer().onAnyMessage(listener);
1112
+ },
1113
+ onStateChanged (listener) {
1114
+ return getOrCreateDefaultPeer().onStateChanged(listener);
1115
+ },
1116
+ onPeersChanged (listener) {
1117
+ return getOrCreateDefaultPeer().onPeersChanged(listener);
1118
+ }
1119
+ };