@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/index.js ADDED
@@ -0,0 +1,662 @@
1
+ import { base64ToBytes, bytesToBase64, ConnektError, DEFAULT_STREAM_CHUNK_SIZE, Payload, Target, textEncoder, toRawBytes } from "./common.js";
2
+ export { ConnektError, DEFAULT_STREAM_CHUNK_SIZE, Payload, Target };
3
+ function encodeOutbound(input) {
4
+ if (Payload.isPayload(input)) {
5
+ if (input.encoding === "utf8") {
6
+ return {
7
+ payload_encoding: "utf8",
8
+ payload: input.text
9
+ };
10
+ }
11
+ return {
12
+ payload_encoding: "base64",
13
+ payload: bytesToBase64(input.bytes)
14
+ };
15
+ }
16
+ if (typeof input === "string") {
17
+ return {
18
+ payload_encoding: "utf8",
19
+ payload: input
20
+ };
21
+ }
22
+ return {
23
+ payload_encoding: "base64",
24
+ payload: bytesToBase64(input)
25
+ };
26
+ }
27
+ function decodeInbound(raw, encoding) {
28
+ if (encoding === "base64") {
29
+ return new Payload(base64ToBytes(raw), "base64");
30
+ }
31
+ return new Payload(textEncoder.encode(raw), "utf8", raw);
32
+ }
33
+ export class OutboundStream {
34
+ streamId;
35
+ channel;
36
+ client;
37
+ closed = false;
38
+ remoteError = null;
39
+ constructor(client, streamId, channel){
40
+ this.client = client;
41
+ this.streamId = streamId;
42
+ this.channel = channel;
43
+ }
44
+ get isClosed() {
45
+ return this.closed;
46
+ }
47
+ _onRemoteClose(code, message) {
48
+ this.closed = true;
49
+ this.remoteError = new ConnektError(code, message);
50
+ }
51
+ async write(data) {
52
+ if (this.closed) {
53
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream is already closed");
54
+ }
55
+ const bytes = toRawBytes(data);
56
+ for(let offset = 0; offset < bytes.byteLength; offset += DEFAULT_STREAM_CHUNK_SIZE){
57
+ if (this.closed) {
58
+ throw this.remoteError ?? new ConnektError("STREAM_CANCELLED", "Stream closed mid-write");
59
+ }
60
+ const slice = bytes.subarray(offset, Math.min(offset + DEFAULT_STREAM_CHUNK_SIZE, bytes.byteLength));
61
+ this.client._sendStreamChunk(this.streamId, slice);
62
+ }
63
+ }
64
+ tryWrite(data) {
65
+ if (this.closed) return false;
66
+ if (!this.client._canSendStreamChunk()) return false;
67
+ const bytes = toRawBytes(data);
68
+ for(let offset = 0; offset < bytes.byteLength; offset += DEFAULT_STREAM_CHUNK_SIZE){
69
+ const slice = bytes.subarray(offset, Math.min(offset + DEFAULT_STREAM_CHUNK_SIZE, bytes.byteLength));
70
+ this.client._sendStreamChunk(this.streamId, slice);
71
+ }
72
+ return true;
73
+ }
74
+ close() {
75
+ if (this.closed) return;
76
+ this.closed = true;
77
+ this.client._closeOutboundStream(this.streamId, true);
78
+ }
79
+ abort(reason = "aborted") {
80
+ if (this.closed) return;
81
+ this.closed = true;
82
+ this.client._closeOutboundStream(this.streamId, false, "HANDLER_ERROR", reason);
83
+ }
84
+ }
85
+ export class InboundStream {
86
+ streamId;
87
+ src;
88
+ channel;
89
+ meta;
90
+ client;
91
+ queue = [];
92
+ waiter = null;
93
+ finished = false;
94
+ constructor(client, streamId, src, channel, meta){
95
+ this.client = client;
96
+ this.streamId = streamId;
97
+ this.src = src;
98
+ this.channel = channel;
99
+ this.meta = meta;
100
+ }
101
+ get isFinished() {
102
+ return this.finished;
103
+ }
104
+ _pushChunk(bytes) {
105
+ if (this.finished) return;
106
+ this.enqueue({
107
+ kind: "chunk",
108
+ payload: new Payload(bytes, "base64")
109
+ });
110
+ }
111
+ _pushClose(ok, errCode, errMsg) {
112
+ if (this.finished) return;
113
+ this.finished = true;
114
+ if (ok) {
115
+ this.enqueue({
116
+ kind: "eof"
117
+ });
118
+ } else {
119
+ this.enqueue({
120
+ kind: "error",
121
+ err: new ConnektError(errCode ?? "INTERNAL_ERROR", errMsg ?? "stream closed with error")
122
+ });
123
+ }
124
+ }
125
+ enqueue(item) {
126
+ if (this.waiter) {
127
+ const resolve = this.waiter;
128
+ this.waiter = null;
129
+ resolve(item);
130
+ } else {
131
+ this.queue.push(item);
132
+ }
133
+ }
134
+ nextItem() {
135
+ const queued = this.queue.shift();
136
+ if (queued) return Promise.resolve(queued);
137
+ return new Promise((resolve)=>{
138
+ this.waiter = resolve;
139
+ });
140
+ }
141
+ reject(reason = "rejected") {
142
+ if (this.finished) return;
143
+ this.finished = true;
144
+ this.queue.length = 0;
145
+ this.enqueue({
146
+ kind: "eof"
147
+ });
148
+ this.client._terminateInboundStream(this.streamId, "STREAM_REJECTED", reason);
149
+ }
150
+ cancel(reason = "cancelled") {
151
+ if (this.finished) return;
152
+ this.finished = true;
153
+ this.queue.length = 0;
154
+ this.enqueue({
155
+ kind: "eof"
156
+ });
157
+ this.client._terminateInboundStream(this.streamId, "STREAM_CANCELLED", reason);
158
+ }
159
+ async *[Symbol.asyncIterator]() {
160
+ try {
161
+ while(true){
162
+ const item = await this.nextItem();
163
+ if (item.kind === "chunk") {
164
+ yield item.payload;
165
+ } else if (item.kind === "eof") {
166
+ return;
167
+ } else {
168
+ throw item.err;
169
+ }
170
+ }
171
+ } finally{
172
+ if (!this.finished) {
173
+ this.cancel("iterator exited before EOF");
174
+ }
175
+ }
176
+ }
177
+ }
178
+ export class ConnektChannel {
179
+ name;
180
+ client;
181
+ constructor(client, name){
182
+ this.client = client;
183
+ this.name = name;
184
+ }
185
+ send(to, data) {
186
+ return this.client._send(to, this.name, data);
187
+ }
188
+ request(to, data = Payload.EMPTY, timeoutMs) {
189
+ return this.client._request(to, this.name, data, timeoutMs);
190
+ }
191
+ openStream(to, meta = {}) {
192
+ return this.client._openStream(to, this.name, meta);
193
+ }
194
+ onMessage(listener) {
195
+ return this.client._onMessage(this.name, listener);
196
+ }
197
+ onRequest(handler) {
198
+ return this.client._onRequest(this.name, handler);
199
+ }
200
+ onStream(handler) {
201
+ return this.client._onStream(this.name, handler);
202
+ }
203
+ }
204
+ export class ConnektClient {
205
+ baseUrl;
206
+ defaultTimeoutMs;
207
+ ws = null;
208
+ peersCache = [];
209
+ callSeq = 1;
210
+ streamSeq = 1;
211
+ messageListeners = new Map();
212
+ anyMessageListeners = new Set();
213
+ requestHandlers = new Map();
214
+ streamHandlers = new Map();
215
+ outboundStreams = new Map();
216
+ inboundStreams = new Map();
217
+ peersListeners = new Set();
218
+ pendingCalls = new Map();
219
+ constructor(options = {}){
220
+ this.baseUrl = (options.baseUrl ?? "http://127.0.0.1:9527").replace(/\/+$/, "");
221
+ this.defaultTimeoutMs = options.defaultTimeoutMs ?? 5_000;
222
+ }
223
+ static async connect(options = {}) {
224
+ const client = new ConnektClient(options);
225
+ await client.connect();
226
+ return client;
227
+ }
228
+ get peers() {
229
+ return this.peersCache;
230
+ }
231
+ channel(name) {
232
+ return new ConnektChannel(this, name);
233
+ }
234
+ connect() {
235
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
236
+ return Promise.resolve();
237
+ }
238
+ const wsUrl = this.baseUrl.replace(/^http/, "ws") + "/api/v1/control";
239
+ return new Promise((resolve, reject)=>{
240
+ let settled = false;
241
+ const ws = new WebSocket(wsUrl);
242
+ ws.binaryType = "arraybuffer";
243
+ this.ws = ws;
244
+ ws.addEventListener("open", ()=>{
245
+ for (const ch of this.streamHandlers.keys()){
246
+ ws.send(JSON.stringify({
247
+ action: "register_stream",
248
+ ch
249
+ }));
250
+ }
251
+ });
252
+ ws.addEventListener("error", ()=>{
253
+ if (!settled) {
254
+ settled = true;
255
+ reject(new ConnektError("INTERNAL_ERROR", `Failed to connect to ${wsUrl}`));
256
+ }
257
+ });
258
+ ws.addEventListener("close", ()=>{
259
+ if (this.ws === ws) this.ws = null;
260
+ for (const [id, pending] of this.pendingCalls){
261
+ clearTimeout(pending.timer);
262
+ pending.reject(new ConnektError("INTERNAL_ERROR", "Control WebSocket closed"));
263
+ this.pendingCalls.delete(id);
264
+ }
265
+ for (const [sid, stream] of this.outboundStreams){
266
+ stream._onRemoteClose("PEER_OFFLINE", "Control WebSocket closed");
267
+ this.outboundStreams.delete(sid);
268
+ }
269
+ for (const [sid, stream] of this.inboundStreams){
270
+ stream._pushClose(false, "PEER_OFFLINE", "Control WebSocket closed");
271
+ this.inboundStreams.delete(sid);
272
+ }
273
+ });
274
+ ws.addEventListener("message", (event)=>{
275
+ if (event.data instanceof ArrayBuffer) {
276
+ const buf = new Uint8Array(event.data);
277
+ if (buf.byteLength >= 4) {
278
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
279
+ const streamId = view.getUint32(0, false);
280
+ const inbound = this.inboundStreams.get(streamId);
281
+ if (inbound) {
282
+ inbound._pushChunk(buf.subarray(4));
283
+ }
284
+ }
285
+ return;
286
+ }
287
+ const msg = JSON.parse(String(event.data));
288
+ if (msg.event === "peer_list") {
289
+ this.peersCache = msg.peers ?? [];
290
+ this.emitPeers();
291
+ if (!settled) {
292
+ settled = true;
293
+ resolve();
294
+ }
295
+ return;
296
+ }
297
+ this.handleServerEvent(msg);
298
+ });
299
+ });
300
+ }
301
+ close() {
302
+ if (this.ws) {
303
+ this.ws.close();
304
+ this.ws = null;
305
+ }
306
+ }
307
+ async health() {
308
+ const resp = await fetch(`${this.baseUrl}/api/v1/health`);
309
+ if (!resp.ok) {
310
+ throw new ConnektError("INTERNAL_ERROR", `Health check failed with HTTP ${resp.status}`);
311
+ }
312
+ return await resp.json();
313
+ }
314
+ async refreshPeers() {
315
+ const resp = await fetch(`${this.baseUrl}/api/v1/peers`);
316
+ if (!resp.ok) {
317
+ throw new ConnektError("INTERNAL_ERROR", `refreshPeers failed with HTTP ${resp.status}`);
318
+ }
319
+ const data = await resp.json();
320
+ this.peersCache = data.peers;
321
+ return data.peers;
322
+ }
323
+ onPeersChanged(listener) {
324
+ this.peersListeners.add(listener);
325
+ return {
326
+ cancel: ()=>this.peersListeners.delete(listener)
327
+ };
328
+ }
329
+ onAnyMessage(listener) {
330
+ this.anyMessageListeners.add(listener);
331
+ return {
332
+ cancel: ()=>this.anyMessageListeners.delete(listener)
333
+ };
334
+ }
335
+ subscribeFilter(channels = [], peers = []) {
336
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
337
+ throw new ConnektError("INTERNAL_ERROR", "Control WebSocket is not connected");
338
+ }
339
+ this.ws.send(JSON.stringify({
340
+ action: "subscribe",
341
+ channels,
342
+ peers
343
+ }));
344
+ }
345
+ async _send(dst, ch, input) {
346
+ const encoded = encodeOutbound(input);
347
+ const resp = await fetch(`${this.baseUrl}/api/v1/send`, {
348
+ method: "POST",
349
+ headers: {
350
+ "content-type": "application/json"
351
+ },
352
+ body: JSON.stringify({
353
+ dst,
354
+ ch,
355
+ ...encoded
356
+ })
357
+ });
358
+ const data = await resp.json();
359
+ if (!data.ok) {
360
+ throw new ConnektError(data.err_code ?? "INTERNAL_ERROR", data.err_msg ?? "send failed");
361
+ }
362
+ return data.delivered_count ?? 0;
363
+ }
364
+ async _request(dst, ch, input, timeoutMs = this.defaultTimeoutMs) {
365
+ const encoded = encodeOutbound(input);
366
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
367
+ const callId = `ts-${this.callSeq++}`;
368
+ return new Promise((resolve, reject)=>{
369
+ const timer = setTimeout(()=>{
370
+ this.pendingCalls.delete(callId);
371
+ reject(new ConnektError("TIMEOUT", `Request timed out after ${timeoutMs}ms`));
372
+ }, timeoutMs + 500);
373
+ this.pendingCalls.set(callId, {
374
+ resolve,
375
+ reject,
376
+ timer
377
+ });
378
+ this.ws.send(JSON.stringify({
379
+ action: "request",
380
+ call_id: callId,
381
+ dst,
382
+ ch,
383
+ ...encoded,
384
+ timeout_ms: timeoutMs
385
+ }));
386
+ });
387
+ }
388
+ const resp = await fetch(`${this.baseUrl}/api/v1/request`, {
389
+ method: "POST",
390
+ headers: {
391
+ "content-type": "application/json"
392
+ },
393
+ body: JSON.stringify({
394
+ dst,
395
+ ch,
396
+ ...encoded,
397
+ timeout_ms: timeoutMs
398
+ })
399
+ });
400
+ const data = await resp.json();
401
+ if (!data.ok) {
402
+ throw new ConnektError(data.err_code ?? "INTERNAL_ERROR", data.err_msg ?? "request failed");
403
+ }
404
+ return decodeInbound(data.payload ?? "", data.payload_encoding ?? "utf8");
405
+ }
406
+ _onMessage(channel, listener) {
407
+ let set = this.messageListeners.get(channel);
408
+ if (!set) {
409
+ set = new Set();
410
+ this.messageListeners.set(channel, set);
411
+ }
412
+ set.add(listener);
413
+ return {
414
+ cancel: ()=>set.delete(listener)
415
+ };
416
+ }
417
+ _onRequest(channel, handler) {
418
+ this.requestHandlers.set(channel, handler);
419
+ return {
420
+ cancel: ()=>{
421
+ if (this.requestHandlers.get(channel) === handler) {
422
+ this.requestHandlers.delete(channel);
423
+ }
424
+ }
425
+ };
426
+ }
427
+ _openStream(dst, ch, meta) {
428
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
429
+ throw new ConnektError("PEER_OFFLINE", "Control WebSocket is not connected");
430
+ }
431
+ const streamId = this.streamSeq++;
432
+ const stream = new OutboundStream(this, streamId, ch);
433
+ this.outboundStreams.set(streamId, stream);
434
+ this.ws.send(JSON.stringify({
435
+ action: "stream_open",
436
+ stream_id: streamId,
437
+ dst,
438
+ ch,
439
+ meta
440
+ }));
441
+ return stream;
442
+ }
443
+ _canSendStreamChunk() {
444
+ return !!this.ws && this.ws.readyState === WebSocket.OPEN && this.ws.bufferedAmount < 4 * 1024 * 1024;
445
+ }
446
+ _sendStreamChunk(streamId, payload) {
447
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
448
+ throw new ConnektError("PEER_OFFLINE", "Control WebSocket is not connected");
449
+ }
450
+ const frame = new Uint8Array(4 + payload.byteLength);
451
+ new DataView(frame.buffer).setUint32(0, streamId, false);
452
+ frame.set(payload, 4);
453
+ this.ws.send(frame);
454
+ }
455
+ _closeOutboundStream(streamId, ok, errCode, errMsg) {
456
+ this.outboundStreams.delete(streamId);
457
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
458
+ this.ws.send(JSON.stringify({
459
+ action: "stream_close",
460
+ stream_id: streamId,
461
+ ok,
462
+ err_code: errCode,
463
+ err_msg: errMsg
464
+ }));
465
+ }
466
+ }
467
+ _onStream(channel, handler) {
468
+ this.streamHandlers.set(channel, handler);
469
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
470
+ this.ws.send(JSON.stringify({
471
+ action: "register_stream",
472
+ ch: channel
473
+ }));
474
+ }
475
+ return {
476
+ cancel: ()=>{
477
+ if (this.streamHandlers.get(channel) === handler) {
478
+ this.streamHandlers.delete(channel);
479
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
480
+ this.ws.send(JSON.stringify({
481
+ action: "unregister_stream",
482
+ ch: channel
483
+ }));
484
+ }
485
+ }
486
+ }
487
+ };
488
+ }
489
+ _terminateInboundStream(streamId, errCode, errMsg) {
490
+ this.inboundStreams.delete(streamId);
491
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
492
+ this.ws.send(JSON.stringify({
493
+ action: "stream_close",
494
+ stream_id: streamId,
495
+ ok: false,
496
+ err_code: errCode,
497
+ err_msg: errMsg
498
+ }));
499
+ }
500
+ }
501
+ emitPeers() {
502
+ const snapshot = [
503
+ ...this.peersCache
504
+ ];
505
+ for (const listener of this.peersListeners){
506
+ listener(snapshot);
507
+ }
508
+ }
509
+ handleServerEvent(msg) {
510
+ switch(msg.event){
511
+ case "peer_online":
512
+ {
513
+ const peer = msg.peer;
514
+ this.peersCache = this.peersCache.filter((p)=>p.peer_id !== peer.peer_id).concat([
515
+ peer
516
+ ]);
517
+ this.emitPeers();
518
+ break;
519
+ }
520
+ case "peer_updated":
521
+ {
522
+ const peer = msg.peer;
523
+ this.peersCache = this.peersCache.map((p)=>p.peer_id === peer.peer_id ? peer : p);
524
+ this.emitPeers();
525
+ break;
526
+ }
527
+ case "peer_offline":
528
+ {
529
+ const id = String(msg.peer_id);
530
+ this.peersCache = this.peersCache.filter((p)=>p.peer_id !== id);
531
+ this.emitPeers();
532
+ break;
533
+ }
534
+ case "message":
535
+ {
536
+ const encoding = msg.payload_encoding ?? "utf8";
537
+ const payload = decodeInbound(String(msg.payload ?? ""), encoding);
538
+ const incoming = {
539
+ src: String(msg.src),
540
+ dst: String(msg.dst),
541
+ channel: String(msg.ch),
542
+ payload,
543
+ text: payload.text,
544
+ bytes: payload.bytes,
545
+ tsMs: Number(msg.ts_ms ?? 0)
546
+ };
547
+ for (const l of this.anyMessageListeners)l(incoming);
548
+ const set = this.messageListeners.get(incoming.channel);
549
+ if (set) {
550
+ for (const l of set)l(incoming);
551
+ }
552
+ break;
553
+ }
554
+ case "request":
555
+ {
556
+ const encoding = msg.payload_encoding ?? "utf8";
557
+ const payload = decodeInbound(String(msg.payload ?? ""), encoding);
558
+ const incoming = {
559
+ reqId: Number(msg.req_id),
560
+ src: String(msg.src),
561
+ channel: String(msg.ch),
562
+ payload,
563
+ text: payload.text,
564
+ bytes: payload.bytes,
565
+ tsMs: Number(msg.ts_ms ?? 0)
566
+ };
567
+ void this.dispatchIncomingRequest(incoming);
568
+ break;
569
+ }
570
+ case "request_result":
571
+ {
572
+ const callId = String(msg.call_id);
573
+ const pending = this.pendingCalls.get(callId);
574
+ if (!pending) break;
575
+ clearTimeout(pending.timer);
576
+ this.pendingCalls.delete(callId);
577
+ if (msg.ok) {
578
+ const encoding = msg.payload_encoding ?? "utf8";
579
+ pending.resolve(decodeInbound(String(msg.payload ?? ""), encoding));
580
+ } else {
581
+ pending.reject(new ConnektError(String(msg.err_code ?? "INTERNAL_ERROR"), String(msg.err_msg ?? "request failed")));
582
+ }
583
+ break;
584
+ }
585
+ case "stream_open":
586
+ {
587
+ const sid = Number(msg.stream_id);
588
+ const src = String(msg.src ?? "");
589
+ const ch = String(msg.ch ?? "");
590
+ const meta = msg.meta ?? {};
591
+ const stream = new InboundStream(this, sid, src, ch, meta);
592
+ this.inboundStreams.set(sid, stream);
593
+ const handler = this.streamHandlers.get(ch);
594
+ if (!handler) {
595
+ stream.reject(`no stream handler registered for channel '${ch}'`);
596
+ break;
597
+ }
598
+ void Promise.resolve(handler(stream)).catch(()=>{
599
+ if (!stream.isFinished) stream.cancel("stream handler threw");
600
+ }).finally(()=>{
601
+ if (!stream.isFinished) stream.cancel("stream handler returned before EOF");
602
+ });
603
+ break;
604
+ }
605
+ case "stream_close":
606
+ {
607
+ const sid = Number(msg.stream_id);
608
+ const ok = Boolean(msg.ok);
609
+ const errCode = msg.err_code ? String(msg.err_code) : undefined;
610
+ const errMsg = msg.err_msg ? String(msg.err_msg) : undefined;
611
+ const inbound = this.inboundStreams.get(sid);
612
+ if (inbound) {
613
+ this.inboundStreams.delete(sid);
614
+ inbound._pushClose(ok, errCode, errMsg);
615
+ break;
616
+ }
617
+ const outbound = this.outboundStreams.get(sid);
618
+ if (outbound && !ok) {
619
+ this.outboundStreams.delete(sid);
620
+ outbound._onRemoteClose(errCode ?? "INTERNAL_ERROR", errMsg ?? "stream closed with error");
621
+ }
622
+ break;
623
+ }
624
+ default:
625
+ break;
626
+ }
627
+ }
628
+ async dispatchIncomingRequest(req) {
629
+ const handler = this.requestHandlers.get(req.channel);
630
+ if (!handler || !this.ws || this.ws.readyState !== WebSocket.OPEN) {
631
+ return;
632
+ }
633
+ try {
634
+ const result = await handler(req);
635
+ const encoded = encodeOutbound(result);
636
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
637
+ this.ws.send(JSON.stringify({
638
+ action: "respond",
639
+ req_id: req.reqId,
640
+ dst: req.src,
641
+ ch: req.channel,
642
+ ok: true,
643
+ ...encoded
644
+ }));
645
+ }
646
+ } catch (err) {
647
+ const message = err instanceof Error ? err.message : String(err);
648
+ const code = err instanceof ConnektError ? err.code : "HANDLER_ERROR";
649
+ if (this.ws && this.ws.readyState === WebSocket.OPEN) {
650
+ this.ws.send(JSON.stringify({
651
+ action: "respond",
652
+ req_id: req.reqId,
653
+ dst: req.src,
654
+ ch: req.channel,
655
+ ok: false,
656
+ err_code: code,
657
+ err_msg: message
658
+ }));
659
+ }
660
+ }
661
+ }
662
+ }