@telperion/messenger 7.7.4 → 8.0.1

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm](https://img.shields.io/npm/v/@telperion/messenger.svg)](https://www.npmjs.com/package/@telperion/messenger)
4
4
  [![npm](https://img.shields.io/npm/dw/@telperion/messenger.svg)](https://www.npmjs.com/package/@telperion/messenger)
5
- [![codecov](https://codecov.io/gh/telperiontech/telperion/graph/badge.svg?token=dz46LY3onk&flag=messenger)](https://codecov.io/gh/telperiontech/telperion?flag=messenger)
5
+ [![codecov](https://codecov.io/gh/telperiontech/telperion/graph/badge.svg?token=dz46LY3onk&flag=messenger)](https://app.codecov.io/gh/telperiontech/telperion/tree/main?flags%5B0%5D=messenger)
6
6
  [![TypeScript](https://badges.frapsoft.com/typescript/version/typescript-next.svg?v=101)](https://www.typescriptlang.org/)
7
7
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
8
 
@@ -28,6 +28,7 @@ Messenger provides a unified, decorator-based API for cross-context messaging in
28
28
  - 🧩 **Chrome Extensions** - Background scripts, content scripts, and popups
29
29
  - 👷 **Web Workers** - Main thread and worker communication
30
30
  - 📡 **Broadcast Channel** - Tab-to-tab messaging
31
+ - 🔗 **WebRTC DataChannel** - Peer-to-peer messaging over RTCDataChannel
31
32
 
32
33
  ## Core Concepts
33
34
 
@@ -379,6 +380,130 @@ const tab2 = new Tab2('my-app-channel');
379
380
 
380
381
  ---
381
382
 
383
+ ### WebRTC (RTCDataChannel)
384
+
385
+ Communicate between peers over a negotiated RTCDataChannel. Both sides create the channel with the same name and a deterministic ID derived via FNV-1a hash, so there is no offer/answer asymmetry for the data channel itself — you only need to provide the `RTCPeerConnection`.
386
+
387
+ ![WebRTC Communication](docs/images/rtc-communication.svg)
388
+
389
+ #### Peer A (Client)
390
+
391
+ ```typescript
392
+ import { RTCMessageClient, Request } from '@telperion/messenger/rtc';
393
+ import { Observable } from 'rxjs';
394
+
395
+ class PeerA extends RTCMessageClient {
396
+ @Request('move')
397
+ sendMove(position: [number, number]): Observable<boolean> {
398
+ return null!; // Implementation handled by decorator
399
+ }
400
+ }
401
+
402
+ // Provide an RTCPeerConnection
403
+ const client = new PeerA(peerConnection);
404
+
405
+ // Optional: custom channel name
406
+ const clientWithChannel = new PeerA(peerConnection, 'game-events');
407
+
408
+ client.sendMove([3, 4]).subscribe(ok => {
409
+ console.log('Move accepted:', ok);
410
+ });
411
+ ```
412
+
413
+ #### Peer B (Host)
414
+
415
+ ```typescript
416
+ import { RTCMessageHost, Listen } from '@telperion/messenger/rtc';
417
+ import { of, Observable } from 'rxjs';
418
+
419
+ class PeerB extends RTCMessageHost {
420
+ @Listen('move')
421
+ handleMove({ data }: { data: [number, number] }): Observable<boolean> {
422
+ console.log('Move received:', data);
423
+ return of(true);
424
+ }
425
+ }
426
+
427
+ const host = new PeerB(peerConnection);
428
+
429
+ // Optional: custom channel name (must match the client)
430
+ const hostWithChannel = new PeerB(peerConnection, 'game-events');
431
+ ```
432
+
433
+ #### Bidirectional Communication (MessageService)
434
+
435
+ ```typescript
436
+ import { RTCMessageService, Request, Listen } from '@telperion/messenger/rtc';
437
+ import { of, Observable } from 'rxjs';
438
+
439
+ class GamePeer extends RTCMessageService {
440
+ @Request('move')
441
+ sendMove(position: [number, number]): Observable<boolean> {
442
+ return null!;
443
+ }
444
+
445
+ @Listen('move')
446
+ handleMove({ data }: { data: [number, number] }): Observable<boolean> {
447
+ console.log('Opponent moved:', data);
448
+ return of(true);
449
+ }
450
+ }
451
+
452
+ // Both peers use the same class with their own RTCPeerConnection
453
+ const peer = new GamePeer(peerConnection, 'game-events');
454
+ ```
455
+
456
+ ##### Flexible Connection Initialization
457
+
458
+ The connection parameter supports multiple initialization patterns:
459
+
460
+ ```typescript
461
+ // Direct RTCPeerConnection instance
462
+ const service1 = new GamePeer(peerConnection);
463
+
464
+ // Promise that resolves to an RTCPeerConnection
465
+ const connPromise = establishConnection();
466
+ const service2 = new GamePeer(connPromise);
467
+
468
+ // Factory function (lazy initialization)
469
+ const service3 = new GamePeer(() => createPeerConnection());
470
+
471
+ // Async factory function
472
+ const service4 = new GamePeer(async () => {
473
+ const conn = new RTCPeerConnection(config);
474
+ await negotiateOffer(conn);
475
+ return conn;
476
+ });
477
+ ```
478
+
479
+ ##### Dynamic Connection Management with `initialize()`
480
+
481
+ The `initialize()` method allows you to switch connections at runtime:
482
+
483
+ ```typescript
484
+ class GamePeer extends RTCMessageService {
485
+ // ... decorators and methods
486
+ }
487
+
488
+ // Start without a connection
489
+ const peer = new GamePeer();
490
+
491
+ // Connect later when RTCPeerConnection is ready
492
+ peer.initialize(peerConnection);
493
+
494
+ // Switch to a different connection
495
+ peer.initialize(newPeerConnection);
496
+
497
+ // Re-establish after ICE failure
498
+ peerConnection.oniceconnectionstatechange = () => {
499
+ if (peerConnection.iceConnectionState === 'failed') {
500
+ peer.initialize(createNewConnection());
501
+ }
502
+ };
503
+ ```
504
+
505
+ ---
506
+
382
507
  ## Advanced Features
383
508
 
384
509
  ### Streaming Responses
@@ -511,6 +636,34 @@ constructor(connectionName?: string)
511
636
  const client = new ChromeMessageClient('extension-port');
512
637
  ```
513
638
 
639
+ #### WebRTC
640
+
641
+ **`RTCMessageClient` / `RTCMessageHost` / `RTCMessageService`**
642
+
643
+ ```typescript
644
+ constructor(connection?: RTCConnectionArg, channelName?: string)
645
+ ```
646
+
647
+ - **`connection`** (optional): RTCPeerConnection to use for the data channel. Can be:
648
+ - `RTCPeerConnection`: Direct instance
649
+ - `Promise<RTCPeerConnection>`: Async connection
650
+ - `() => RTCPeerConnection | Promise<RTCPeerConnection>`: Factory function
651
+ - Omit to initialize later via `initialize()`
652
+ - **`channelName`** (optional): Name for the negotiated data channel. Default: `'MessengerRTCChannelDefault'`. A deterministic channel ID in [0, 1023] is derived from this name via FNV-1a hash.
653
+
654
+ **Examples:**
655
+ ```typescript
656
+ // Direct connection
657
+ const service = new RTCMessageService(peerConnection);
658
+
659
+ // With custom channel name
660
+ const service = new RTCMessageService(peerConnection, 'game-events');
661
+
662
+ // Lazy initialization
663
+ const service = new RTCMessageService();
664
+ service.initialize(peerConnection);
665
+ ```
666
+
514
667
  ## API Reference
515
668
 
516
669
  ### Classes
@@ -526,6 +679,9 @@ const client = new ChromeMessageClient('extension-port');
526
679
  - **`BroadcastMessageClient`** - Broadcast channel client
527
680
  - **`BroadcastMessageHost`** - Broadcast channel host
528
681
  - **`BroadcastMessageService`** - Bidirectional broadcast communication
682
+ - **`RTCMessageClient`** - WebRTC data channel client
683
+ - **`RTCMessageHost`** - WebRTC data channel host
684
+ - **`RTCMessageService`** - Bidirectional WebRTC data channel communication
529
685
 
530
686
  ### Decorators
531
687
 
@@ -560,6 +716,7 @@ pnpm nx run messenger:test/worker # Web Worker tests (Browser)
560
716
  pnpm nx run messenger:test/chrome # Chrome extension tests (Browser)
561
717
  pnpm nx run messenger:test/broadcast # Broadcast Channel tests (Browser)
562
718
  pnpm nx run messenger:test/iframe # Iframe communication tests (Browser)
719
+ pnpm nx run messenger:test/rtc # WebRTC DataChannel tests (Browser)
563
720
 
564
721
  # Run all tests with coverage and merge reports
565
722
  pnpm nx run messenger:test/coverage
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.IframeMessageHost = void 0;
4
4
  const unique_id_1 = require("@telperion/js-utils/unique-id");
5
5
  const noop_1 = require("@telperion/js-utils/function/noop");
6
+ const call_1 = require("@telperion/js-utils/function/call");
6
7
  const promisify_1 = require("@telperion/js-utils/promise/promisify");
7
8
  const timeout_1 = require("@telperion/js-utils/promise/timeout");
8
9
  const rxjs_1 = require("rxjs");
@@ -30,7 +31,7 @@ class IframeMessageHost extends message_host_1.MessageHost {
30
31
  this.#deinitialize,
31
32
  (0, timeout_1.timeout)(5000, noop_1.noop)
32
33
  ])
33
- .then(callback => callback())
34
+ .then(call_1.call)
34
35
  .then(() => {
35
36
  const _frame = typeof targetFrame === 'function' ? targetFrame() : targetFrame;
36
37
  return (0, promisify_1.promisify)(_frame);
@@ -44,7 +45,7 @@ class IframeMessageHost extends message_host_1.MessageHost {
44
45
  });
45
46
  }
46
47
  terminate() {
47
- this.#deinitialize.then(callback => callback()).catch(noop_1.noop);
48
+ this.#deinitialize.then(call_1.call).catch(noop_1.noop);
48
49
  }
49
50
  [selectors_1.RESPONSE](message) {
50
51
  const [sourceId, messageId] = message.id.split(source_id_splitter_1.SOURCE_ID_SPLITTER);
@@ -1,5 +1,6 @@
1
1
  import { uniqueId } from '@telperion/js-utils/unique-id';
2
2
  import { noop } from '@telperion/js-utils/function/noop';
3
+ import { call } from '@telperion/js-utils/function/call';
3
4
  import { promisify } from '@telperion/js-utils/promise/promisify';
4
5
  import { timeout } from '@telperion/js-utils/promise/timeout';
5
6
  import { Subject } from 'rxjs';
@@ -27,7 +28,7 @@ export class IframeMessageHost extends MessageHost {
27
28
  this.#deinitialize,
28
29
  timeout(5000, noop)
29
30
  ])
30
- .then(callback => callback())
31
+ .then(call)
31
32
  .then(() => {
32
33
  const _frame = typeof targetFrame === 'function' ? targetFrame() : targetFrame;
33
34
  return promisify(_frame);
@@ -41,7 +42,7 @@ export class IframeMessageHost extends MessageHost {
41
42
  });
42
43
  }
43
44
  terminate() {
44
- this.#deinitialize.then(callback => callback()).catch(noop);
45
+ this.#deinitialize.then(call).catch(noop);
45
46
  }
46
47
  [RESPONSE](message) {
47
48
  const [sourceId, messageId] = message.id.split(SOURCE_ID_SPLITTER);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../libs/messenger/src/iframe/message-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EAAE,OAAO,EAA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AAO,IAAI,KAAK,QAAQ,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,OAAO,IAAI,CAAC,EAAE,KAAK,WAAW,EAAE,CAAC;YACtF,OAAO;QACT,CAAC;QAED,IAAI,WAAW,IAAI,WAAW,CAAC,aAAa,KAAK,MAAM,EAAE,CAAC;YACxD,OAAO;QACT,CAAC;QAED,MAAM,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;QAE/D,IAAI,OAAO,KAAK,IAAI,CAAC,WAAW,EAAE,CAAC;YACjC,OAAO;QACT,CAAC;QAED,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,MAAM,CAAC,EAAE,CAAC;YACjD,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC,yBAAyB,CAAW,EAAE,MAAO,CAAC,CAAC,CAAC;QAC/E,CAAC;QAED,MAAM,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,MAAM,CAAE,CAAC;QAChE,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;YAClB,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;YACnE,EAAE,EAAE,GAAG,QAAQ,GAAG,kBAAkB,GAAG,IAAI,CAAC,EAAE,EAAE;YAChD,IAAI;SACL,CAAC,CAAC;IACL,CAAC,CAAC;CACH","file":"message-host.js","sourcesContent":["import { uniqueId } from '@telperion/js-utils/unique-id';\nimport { noop } from '@telperion/js-utils/function/noop';\nimport { promisify } from '@telperion/js-utils/promise/promisify';\nimport { timeout } from '@telperion/js-utils/promise/timeout';\nimport { Subject } from 'rxjs';\n\nimport { MessageHost } from '../message-host';\nimport { SuccessfulMessageResponse } from '../message-response.type';\nimport { Message } from '../message.interface';\nimport { CHANNEL_PATH_SPLITTER } from './channel-path-splitter';\nimport { DEFAULT_CHANNEL_NAME } from './default-channel-name';\nimport { SOURCE_ID_SPLITTER } from './source-id-splitter';\nimport { LISTEN, RESPONSE } from '../selectors';\nimport { IFrameArg, IFrameType } from './iframe.type';\n\nconst REQUESTS = Symbol('IframeMessageHost Requests');\nconst SOURCES = Symbol('IframeMessageHost Sources');\nconst HANDLER = Symbol('IframeMessageHost Handler');\n\nexport class IframeMessageHost extends MessageHost {\n private [REQUESTS] = new Subject<Message>();\n private [SOURCES]: Array<[string, MessageEventSource]> = [];\n\n #deinitialize = Promise.resolve(noop);\n\n constructor(\n private channelName = DEFAULT_CHANNEL_NAME,\n targetFrame?: IFrameArg\n ) {\n super();\n\n IframeMessageHost.prototype.initialize.call(this, targetFrame);\n\n this[LISTEN](this[REQUESTS]);\n }\n\n initialize(targetFrame: IFrameArg): void {\n this.#deinitialize = Promise.race([\n this.#deinitialize,\n timeout(5000, noop)\n ])\n .then(callback => callback())\n .then(() => {\n const _frame = typeof targetFrame === 'function' ? targetFrame() : targetFrame;\n return promisify(_frame);\n })\n .then(frame => {\n const handler = this[HANDLER](frame);\n window.addEventListener('message', handler);\n\n return () => {\n window.removeEventListener('message', handler);\n }\n });\n }\n\n public terminate(): void {\n this.#deinitialize.then(callback => callback()).catch(noop);\n }\n\n protected [RESPONSE](message: SuccessfulMessageResponse): void {\n const [sourceId, messageId] = message.id.split(SOURCE_ID_SPLITTER);\n const [, source] = this[SOURCES].find(([sId]) => sId === sourceId)!;\n\n message = {\n ...message,\n id: messageId,\n };\n\n (source as Window).postMessage(message, '*');\n }\n\n private [HANDLER] = (targetFrame: IFrameType) => ({ data, source }: MessageEvent<Message>) => {\n if (!data || typeof data !== 'object' || !data.path || typeof data.id === 'undefined') {\n return;\n }\n\n if (targetFrame && targetFrame.contentWindow !== source) {\n return;\n }\n\n const [channel, path] = data.path.split(CHANNEL_PATH_SPLITTER);\n\n if (channel !== this.channelName) {\n return;\n }\n\n if (!this[SOURCES].some(([, s]) => s === source)) {\n this[SOURCES].push([uniqueId('messenger-iframe-source') as string, source!]);\n }\n\n const [sourceId] = this[SOURCES].find(([, s]) => s === source)!;\n this[REQUESTS].next({\n body: targetFrame ? data.body : { data: data.body, sender: source },\n id: `${sourceId}${SOURCE_ID_SPLITTER}${data.id}`,\n path,\n });\n };\n}\n"]}
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/iframe/message-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,qCAAqC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAGhD,MAAM,QAAQ,GAAG,MAAM,CAAC,4BAA4B,CAAC,CAAC;AACtD,MAAM,OAAO,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AACpD,MAAM,OAAO,GAAG,MAAM,CAAC,2BAA2B,CAAC,CAAC;AAEpD,MAAM,OAAO,iBAAk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BAAyB,CAAW,EAAE,MAAO,CAAC,CAAC,CAAC;QAC/E,CAAC;QAED,MAAM,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,MAAM,CAAE,CAAC;QAChE,IAAI,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;YAClB,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE;YACnE,EAAE,EAAE,GAAG,QAAQ,GAAG,kBAAkB,GAAG,IAAI,CAAC,EAAE,EAAE;YAChD,IAAI;SACL,CAAC,CAAC;IACL,CAAC,CAAC;CACH","file":"message-host.js","sourcesContent":["import { uniqueId } from '@telperion/js-utils/unique-id';\nimport { noop } from '@telperion/js-utils/function/noop';\nimport { call } from '@telperion/js-utils/function/call';\nimport { promisify } from '@telperion/js-utils/promise/promisify';\nimport { timeout } from '@telperion/js-utils/promise/timeout';\nimport { Subject } from 'rxjs';\n\nimport { MessageHost } from '../message-host';\nimport { SuccessfulMessageResponse } from '../message-response.type';\nimport { Message } from '../message.interface';\nimport { CHANNEL_PATH_SPLITTER } from './channel-path-splitter';\nimport { DEFAULT_CHANNEL_NAME } from './default-channel-name';\nimport { SOURCE_ID_SPLITTER } from './source-id-splitter';\nimport { LISTEN, RESPONSE } from '../selectors';\nimport { IFrameArg, IFrameType } from './iframe.type';\n\nconst REQUESTS = Symbol('IframeMessageHost Requests');\nconst SOURCES = Symbol('IframeMessageHost Sources');\nconst HANDLER = Symbol('IframeMessageHost Handler');\n\nexport class IframeMessageHost extends MessageHost {\n private [REQUESTS] = new Subject<Message>();\n private [SOURCES]: Array<[string, MessageEventSource]> = [];\n\n #deinitialize = Promise.resolve(noop);\n\n constructor(\n private channelName = DEFAULT_CHANNEL_NAME,\n targetFrame?: IFrameArg\n ) {\n super();\n\n IframeMessageHost.prototype.initialize.call(this, targetFrame);\n\n this[LISTEN](this[REQUESTS]);\n }\n\n initialize(targetFrame: IFrameArg): void {\n this.#deinitialize = Promise.race([\n this.#deinitialize,\n timeout(5000, noop)\n ])\n .then(call)\n .then(() => {\n const _frame = typeof targetFrame === 'function' ? targetFrame() : targetFrame;\n return promisify(_frame);\n })\n .then(frame => {\n const handler = this[HANDLER](frame);\n window.addEventListener('message', handler);\n\n return () => {\n window.removeEventListener('message', handler);\n }\n });\n }\n\n public terminate(): void {\n this.#deinitialize.then(call).catch(noop);\n }\n\n protected [RESPONSE](message: SuccessfulMessageResponse): void {\n const [sourceId, messageId] = message.id.split(SOURCE_ID_SPLITTER);\n const [, source] = this[SOURCES].find(([sId]) => sId === sourceId)!;\n\n message = {\n ...message,\n id: messageId,\n };\n\n (source as Window).postMessage(message, '*');\n }\n\n private [HANDLER] = (targetFrame: IFrameType) => ({ data, source }: MessageEvent<Message>) => {\n if (!data || typeof data !== 'object' || !data.path || typeof data.id === 'undefined') {\n return;\n }\n\n if (targetFrame && targetFrame.contentWindow !== source) {\n return;\n }\n\n const [channel, path] = data.path.split(CHANNEL_PATH_SPLITTER);\n\n if (channel !== this.channelName) {\n return;\n }\n\n if (!this[SOURCES].some(([, s]) => s === source)) {\n this[SOURCES].push([uniqueId('messenger-iframe-source') as string, source!]);\n }\n\n const [sourceId] = this[SOURCES].find(([, s]) => s === source)!;\n this[REQUESTS].next({\n body: targetFrame ? data.body : { data: data.body, sender: source },\n id: `${sourceId}${SOURCE_ID_SPLITTER}${data.id}`,\n path,\n });\n };\n}\n"]}
package/package.json CHANGED
@@ -1,9 +1,11 @@
1
1
  {
2
2
  "name": "@telperion/messenger",
3
- "version": "7.7.4",
3
+ "version": "8.0.1",
4
4
  "description": "Javascript messaging library",
5
5
  "keywords": [
6
6
  "javascript",
7
+ "typescript",
8
+ "decorators",
7
9
  "messaging",
8
10
  "send",
9
11
  "message",
@@ -13,7 +15,11 @@
13
15
  "nodejs",
14
16
  "child",
15
17
  "process",
16
- "webworkers"
18
+ "webworkers",
19
+ "iframe",
20
+ "broadcast",
21
+ "rtc",
22
+ "webrtc"
17
23
  ],
18
24
  "homepage": "https://open-source.telperion.tr/messenger",
19
25
  "repository": {
@@ -153,6 +159,34 @@
153
159
  "node": "./worker/message-service.cjs",
154
160
  "require": "./worker/message-service.cjs",
155
161
  "types": "./worker/message-service.d.ts"
162
+ },
163
+ "./rtc": {
164
+ "default": "./rtc/index.cjs",
165
+ "import": "./rtc/index.js",
166
+ "node": "./rtc/index.cjs",
167
+ "require": "./rtc/index.cjs",
168
+ "types": "./rtc/index.d.ts"
169
+ },
170
+ "./rtc/message-client": {
171
+ "default": "./rtc/message-client.cjs",
172
+ "import": "./rtc/message-client.js",
173
+ "node": "./rtc/message-client.cjs",
174
+ "require": "./rtc/message-client.cjs",
175
+ "types": "./rtc/message-client.d.ts"
176
+ },
177
+ "./rtc/message-host": {
178
+ "default": "./rtc/message-host.cjs",
179
+ "import": "./rtc/message-host.js",
180
+ "node": "./rtc/message-host.cjs",
181
+ "require": "./rtc/message-host.cjs",
182
+ "types": "./rtc/message-host.d.ts"
183
+ },
184
+ "./rtc/message-service": {
185
+ "default": "./rtc/message-service.cjs",
186
+ "import": "./rtc/message-service.js",
187
+ "node": "./rtc/message-service.cjs",
188
+ "require": "./rtc/message-service.cjs",
189
+ "types": "./rtc/message-service.d.ts"
156
190
  }
157
191
  }
158
192
  }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.channelId = channelId;
4
+ /**
5
+ * Generates a deterministic integer in [0, 1023] from a channel name string.
6
+ * Used as the negotiated data channel ID for RTCDataChannel.
7
+ *
8
+ * Uses FNV-1a hash algorithm truncated to 10 bits.
9
+ *
10
+ * @param name - The channel name to hash
11
+ * @returns A deterministic channel ID in [0, 1023]
12
+ */
13
+ function channelId(name) {
14
+ let hash = 0x811c9dc5; // FNV offset basis (32-bit)
15
+ for (let i = 0; i < name.length; i++) {
16
+ hash ^= name.charCodeAt(i);
17
+ hash = (hash * 0x01000193) >>> 0; // FNV prime, keep as unsigned 32-bit
18
+ }
19
+ // Truncate to 10-bit range [0, 1023]
20
+ return hash % 1024;
21
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Generates a deterministic integer in [0, 1023] from a channel name string.
3
+ * Used as the negotiated data channel ID for RTCDataChannel.
4
+ *
5
+ * Uses FNV-1a hash algorithm truncated to 10 bits.
6
+ *
7
+ * @param name - The channel name to hash
8
+ * @returns A deterministic channel ID in [0, 1023]
9
+ */
10
+ export declare function channelId(name: string): number;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Generates a deterministic integer in [0, 1023] from a channel name string.
3
+ * Used as the negotiated data channel ID for RTCDataChannel.
4
+ *
5
+ * Uses FNV-1a hash algorithm truncated to 10 bits.
6
+ *
7
+ * @param name - The channel name to hash
8
+ * @returns A deterministic channel ID in [0, 1023]
9
+ */
10
+ export function channelId(name) {
11
+ let hash = 0x811c9dc5; // FNV offset basis (32-bit)
12
+ for (let i = 0; i < name.length; i++) {
13
+ hash ^= name.charCodeAt(i);
14
+ hash = (hash * 0x01000193) >>> 0; // FNV prime, keep as unsigned 32-bit
15
+ }
16
+ // Truncate to 10-bit range [0, 1023]
17
+ return hash % 1024;
18
+ }
19
+
20
+ //# sourceMappingURL=channel-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/channel-id.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,MAAM,UAAU,SAAS,CAAC,IAAY;IACpC,IAAI,IAAI,GAAG,UAAU,CAAC,CAAC,4BAA4B;IAEnD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,IAAI,IAAI,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;QAC3B,IAAI,GAAG,CAAC,IAAI,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,qCAAqC;IACzE,CAAC;IAED,qCAAqC;IACrC,OAAO,IAAI,GAAG,IAAI,CAAC;AACrB,CAAC","file":"channel-id.js","sourcesContent":["/**\r\n * Generates a deterministic integer in [0, 1023] from a channel name string.\r\n * Used as the negotiated data channel ID for RTCDataChannel.\r\n *\r\n * Uses FNV-1a hash algorithm truncated to 10 bits.\r\n *\r\n * @param name - The channel name to hash\r\n * @returns A deterministic channel ID in [0, 1023]\r\n */\r\nexport function channelId(name: string): number {\r\n let hash = 0x811c9dc5; // FNV offset basis (32-bit)\r\n\r\n for (let i = 0; i < name.length; i++) {\r\n hash ^= name.charCodeAt(i);\r\n hash = (hash * 0x01000193) >>> 0; // FNV prime, keep as unsigned 32-bit\r\n }\r\n\r\n // Truncate to 10-bit range [0, 1023]\r\n return hash % 1024;\r\n}\r\n"]}
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_CHANNEL_NAME = void 0;
4
+ /** Default negotiated RTCDataChannel name used when no custom name is provided. */
5
+ exports.DEFAULT_CHANNEL_NAME = 'MessengerRTCChannelDefault';
@@ -0,0 +1,2 @@
1
+ /** Default negotiated RTCDataChannel name used when no custom name is provided. */
2
+ export declare const DEFAULT_CHANNEL_NAME = "MessengerRTCChannelDefault";
@@ -0,0 +1,4 @@
1
+ /** Default negotiated RTCDataChannel name used when no custom name is provided. */
2
+ export const DEFAULT_CHANNEL_NAME = 'MessengerRTCChannelDefault';
3
+
4
+ //# sourceMappingURL=default-channel-name.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/default-channel-name.ts"],"names":[],"mappings":"AAAA,mFAAmF;AACnF,MAAM,CAAC,MAAM,oBAAoB,GAAG,4BAA4B,CAAC","file":"default-channel-name.js","sourcesContent":["/** Default negotiated RTCDataChannel name used when no custom name is provided. */\r\nexport const DEFAULT_CHANNEL_NAME = 'MessengerRTCChannelDefault';\r\n"]}
package/rtc/index.cjs ADDED
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Listen = exports.Request = exports.RTCMessageHost = exports.RTCMessageClient = exports.RTCMessageService = void 0;
4
+ var message_service_1 = require("./message-service");
5
+ Object.defineProperty(exports, "RTCMessageService", { enumerable: true, get: function () { return message_service_1.RTCMessageService; } });
6
+ var message_client_1 = require("./message-client");
7
+ Object.defineProperty(exports, "RTCMessageClient", { enumerable: true, get: function () { return message_client_1.RTCMessageClient; } });
8
+ var message_host_1 = require("./message-host");
9
+ Object.defineProperty(exports, "RTCMessageHost", { enumerable: true, get: function () { return message_host_1.RTCMessageHost; } });
10
+ var request_decorator_1 = require("../request.decorator");
11
+ Object.defineProperty(exports, "Request", { enumerable: true, get: function () { return request_decorator_1.Request; } });
12
+ var listen_decorator_1 = require("../listen.decorator");
13
+ Object.defineProperty(exports, "Listen", { enumerable: true, get: function () { return listen_decorator_1.Listen; } });
package/rtc/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ export { RTCMessageService } from './message-service';
2
+ export { RTCMessageClient } from './message-client';
3
+ export { RTCMessageHost } from './message-host';
4
+ export { Request } from '../request.decorator';
5
+ export { Listen } from '../listen.decorator';
package/rtc/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { RTCMessageService } from './message-service';
2
+ export { RTCMessageClient } from './message-client';
3
+ export { RTCMessageHost } from './message-host';
4
+ export { Request } from '../request.decorator';
5
+ export { Listen } from '../listen.decorator';
6
+
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC","file":"index.js","sourcesContent":["export { RTCMessageService } from './message-service';\r\nexport { RTCMessageClient } from './message-client';\r\nexport { RTCMessageHost } from './message-host';\r\nexport { Request } from '../request.decorator';\r\nexport { Listen } from '../listen.decorator';\r\n"]}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RTCMessageClient = void 0;
4
+ const unique_id_1 = require("@telperion/js-utils/unique-id");
5
+ const noop_1 = require("@telperion/js-utils/function/noop");
6
+ const promisify_1 = require("@telperion/js-utils/promise/promisify");
7
+ const timeout_1 = require("@telperion/js-utils/promise/timeout");
8
+ const rxjs_1 = require("rxjs");
9
+ const message_client_1 = require("../message-client");
10
+ const selectors_1 = require("../selectors");
11
+ const default_channel_name_1 = require("./default-channel-name");
12
+ const channel_id_1 = require("./channel-id");
13
+ const CONNECTION = Symbol('RTCMessageClient Connection');
14
+ /**
15
+ * Message client for WebRTC DataChannel communication.
16
+ *
17
+ * Sends request messages over a negotiated RTCDataChannel and receives responses
18
+ * on the same channel. Both peers must create the channel with identical
19
+ * name and negotiated ID (handled automatically via {@link channelId}).
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * class GameClient extends RTCMessageClient {
24
+ * @Request('move')
25
+ * sendMove(position: [number, number]): Observable<boolean> {
26
+ * return null!;
27
+ * }
28
+ * }
29
+ *
30
+ * const client = new GameClient(peerConnection, 'game-events');
31
+ * client.sendMove([3, 4]).subscribe(ok => console.log('Accepted:', ok));
32
+ * ```
33
+ */
34
+ class RTCMessageClient extends message_client_1.MessageClient {
35
+ channelName;
36
+ [selectors_1.RESPONSES$] = new rxjs_1.Subject();
37
+ [CONNECTION] = Promise.resolve([undefined, noop_1.noop]);
38
+ /**
39
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
40
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
41
+ */
42
+ constructor(connection, channelName = default_channel_name_1.DEFAULT_CHANNEL_NAME) {
43
+ super();
44
+ this.channelName = channelName;
45
+ RTCMessageClient.prototype.initialize.call(this, connection, channelName);
46
+ }
47
+ /**
48
+ * (Re)initializes the data channel with a new connection.
49
+ * Cleans up the previous channel before establishing a new one.
50
+ *
51
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
52
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
53
+ */
54
+ initialize(connection, channelName = this.channelName) {
55
+ this.channelName = channelName;
56
+ this[CONNECTION] = Promise.race([
57
+ this[CONNECTION],
58
+ (0, timeout_1.timeout)(5000, [null, noop_1.noop])
59
+ ])
60
+ .then(([_, deinitialize]) => deinitialize())
61
+ .catch(noop_1.noop)
62
+ .then(() => {
63
+ const _conn = typeof connection === 'function' ? connection() : connection;
64
+ return (0, promisify_1.promisify)(_conn);
65
+ })
66
+ .then(conn => {
67
+ if (!conn)
68
+ return [undefined, noop_1.noop];
69
+ const id = (0, channel_id_1.channelId)(channelName);
70
+ const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });
71
+ const listener = (event) => {
72
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
73
+ this[selectors_1.RESPONSES$].next(data);
74
+ };
75
+ dataChannel.addEventListener('message', listener);
76
+ return [dataChannel, () => {
77
+ dataChannel.removeEventListener('message', listener);
78
+ dataChannel.close();
79
+ }];
80
+ });
81
+ }
82
+ async [selectors_1.SEND](message) {
83
+ const [dataChannel] = await this[CONNECTION];
84
+ if (dataChannel?.readyState !== 'open')
85
+ return;
86
+ dataChannel.send(JSON.stringify(message));
87
+ }
88
+ [selectors_1.GET_NEW_ID]() {
89
+ return (0, unique_id_1.uniqueId)('messenger-rtc-message');
90
+ }
91
+ }
92
+ exports.RTCMessageClient = RTCMessageClient;
@@ -0,0 +1,48 @@
1
+ import { Subject } from 'rxjs';
2
+ import { MessageClient } from '../message-client';
3
+ import { MessageResponse } from '../message-response.type';
4
+ import { Message } from '../message.interface';
5
+ import { GET_NEW_ID, RESPONSES$, SEND } from '../selectors';
6
+ import { RTCConnectionArg } from './rtc.type';
7
+ declare const CONNECTION: unique symbol;
8
+ /**
9
+ * Message client for WebRTC DataChannel communication.
10
+ *
11
+ * Sends request messages over a negotiated RTCDataChannel and receives responses
12
+ * on the same channel. Both peers must create the channel with identical
13
+ * name and negotiated ID (handled automatically via {@link channelId}).
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * class GameClient extends RTCMessageClient {
18
+ * @Request('move')
19
+ * sendMove(position: [number, number]): Observable<boolean> {
20
+ * return null!;
21
+ * }
22
+ * }
23
+ *
24
+ * const client = new GameClient(peerConnection, 'game-events');
25
+ * client.sendMove([3, 4]).subscribe(ok => console.log('Accepted:', ok));
26
+ * ```
27
+ */
28
+ export declare class RTCMessageClient extends MessageClient {
29
+ private channelName;
30
+ [RESPONSES$]: Subject<MessageResponse>;
31
+ private [CONNECTION];
32
+ /**
33
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
34
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
35
+ */
36
+ constructor(connection?: RTCConnectionArg, channelName?: string);
37
+ /**
38
+ * (Re)initializes the data channel with a new connection.
39
+ * Cleans up the previous channel before establishing a new one.
40
+ *
41
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
42
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
43
+ */
44
+ initialize(connection?: RTCConnectionArg, channelName?: string): void;
45
+ [SEND]<T>(message: Message<T>): Promise<void>;
46
+ protected [GET_NEW_ID](): string;
47
+ }
48
+ export {};
@@ -0,0 +1,90 @@
1
+ import { uniqueId } from '@telperion/js-utils/unique-id';
2
+ import { noop } from '@telperion/js-utils/function/noop';
3
+ import { promisify } from '@telperion/js-utils/promise/promisify';
4
+ import { timeout } from '@telperion/js-utils/promise/timeout';
5
+ import { Subject } from 'rxjs';
6
+ import { MessageClient } from '../message-client';
7
+ import { GET_NEW_ID, RESPONSES$, SEND } from '../selectors';
8
+ import { DEFAULT_CHANNEL_NAME } from './default-channel-name';
9
+ import { channelId } from './channel-id';
10
+ const CONNECTION = Symbol('RTCMessageClient Connection');
11
+ /**
12
+ * Message client for WebRTC DataChannel communication.
13
+ *
14
+ * Sends request messages over a negotiated RTCDataChannel and receives responses
15
+ * on the same channel. Both peers must create the channel with identical
16
+ * name and negotiated ID (handled automatically via {@link channelId}).
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * class GameClient extends RTCMessageClient {
21
+ * @Request('move')
22
+ * sendMove(position: [number, number]): Observable<boolean> {
23
+ * return null!;
24
+ * }
25
+ * }
26
+ *
27
+ * const client = new GameClient(peerConnection, 'game-events');
28
+ * client.sendMove([3, 4]).subscribe(ok => console.log('Accepted:', ok));
29
+ * ```
30
+ */
31
+ export class RTCMessageClient extends MessageClient {
32
+ channelName;
33
+ [RESPONSES$] = new Subject();
34
+ [CONNECTION] = Promise.resolve([undefined, noop]);
35
+ /**
36
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
37
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
38
+ */
39
+ constructor(connection, channelName = DEFAULT_CHANNEL_NAME) {
40
+ super();
41
+ this.channelName = channelName;
42
+ RTCMessageClient.prototype.initialize.call(this, connection, channelName);
43
+ }
44
+ /**
45
+ * (Re)initializes the data channel with a new connection.
46
+ * Cleans up the previous channel before establishing a new one.
47
+ *
48
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
49
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
50
+ */
51
+ initialize(connection, channelName = this.channelName) {
52
+ this.channelName = channelName;
53
+ this[CONNECTION] = Promise.race([
54
+ this[CONNECTION],
55
+ timeout(5000, [null, noop])
56
+ ])
57
+ .then(([_, deinitialize]) => deinitialize())
58
+ .catch(noop)
59
+ .then(() => {
60
+ const _conn = typeof connection === 'function' ? connection() : connection;
61
+ return promisify(_conn);
62
+ })
63
+ .then(conn => {
64
+ if (!conn)
65
+ return [undefined, noop];
66
+ const id = channelId(channelName);
67
+ const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });
68
+ const listener = (event) => {
69
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
70
+ this[RESPONSES$].next(data);
71
+ };
72
+ dataChannel.addEventListener('message', listener);
73
+ return [dataChannel, () => {
74
+ dataChannel.removeEventListener('message', listener);
75
+ dataChannel.close();
76
+ }];
77
+ });
78
+ }
79
+ async [SEND](message) {
80
+ const [dataChannel] = await this[CONNECTION];
81
+ if (dataChannel?.readyState !== 'open')
82
+ return;
83
+ dataChannel.send(JSON.stringify(message));
84
+ }
85
+ [GET_NEW_ID]() {
86
+ return uniqueId('messenger-rtc-message');
87
+ }
88
+ }
89
+
90
+ //# sourceMappingURL=message-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/message-client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACzD,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,qCAAqC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAE/B,OAAO,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAGlD,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAE5D,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,MAAM,UAAU,GAAG,MAAM,C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,WAAW,CAAC,CAAC;YAClC,MAAM,WAAW,GAAG,IAAI,CAAC,iBAAiB,CAAC,WAAW,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC;YAElF,MAAM,QAAQ,GAAG,CAAC,KAAmB,EAAE,EAAE;gBACvC,MAAM,IAAI,GAAoB,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC;gBAEnG,IAAI,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;YAC9B,CAAC,CAAC;YAEF,WAAW,CAAC,gBAAgB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;YAElD,OAAO,CAAC,WAAW,EAAE,GAAG,EAAE;oBACxB,WAAW,CAAC,mBAAmB,CAAC,SAAS,EAAE,QAAQ,CAAC,CAAC;oBACrD,WAAW,CAAC,KAAK,EAAE,CAAC;gBACtB,CAAC,CAAU,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC;IAEM,KAAK,CAAC,CAAC,IAAI,CAAC,CAAI,OAAmB;QACxC,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC;QAE7C,IAAI,WAAW,EAAE,UAAU,KAAK,MAAM;YAAE,OAAO;QAE/C,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;IAC5C,CAAC;IAES,CAAC,UAAU,CAAC;QACpB,OAAO,QAAQ,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC;CACF","file":"message-client.js","sourcesContent":["import { uniqueId } from '@telperion/js-utils/unique-id';\r\nimport { noop } from '@telperion/js-utils/function/noop';\r\nimport { promisify } from '@telperion/js-utils/promise/promisify';\r\nimport { timeout } from '@telperion/js-utils/promise/timeout';\r\nimport { Subject } from 'rxjs';\r\n\r\nimport { MessageClient } from '../message-client';\r\nimport { MessageResponse } from '../message-response.type';\r\nimport { Message } from '../message.interface';\r\nimport { GET_NEW_ID, RESPONSES$, SEND } from '../selectors';\r\nimport { RTCConnectionArg } from './rtc.type';\r\nimport { DEFAULT_CHANNEL_NAME } from './default-channel-name';\r\nimport { channelId } from './channel-id';\r\n\r\nconst CONNECTION = Symbol('RTCMessageClient Connection');\r\n\r\n/**\r\n * Message client for WebRTC DataChannel communication.\r\n *\r\n * Sends request messages over a negotiated RTCDataChannel and receives responses\r\n * on the same channel. Both peers must create the channel with identical\r\n * name and negotiated ID (handled automatically via {@link channelId}).\r\n *\r\n * @example\r\n * ```typescript\r\n * class GameClient extends RTCMessageClient {\r\n * @Request('move')\r\n * sendMove(position: [number, number]): Observable<boolean> {\r\n * return null!;\r\n * }\r\n * }\r\n *\r\n * const client = new GameClient(peerConnection, 'game-events');\r\n * client.sendMove([3, 4]).subscribe(ok => console.log('Accepted:', ok));\r\n * ```\r\n */\r\nexport class RTCMessageClient extends MessageClient {\r\n public [RESPONSES$] = new Subject<MessageResponse>();\r\n private [CONNECTION] = Promise.resolve([undefined as RTCDataChannel | undefined, noop] as const);\r\n\r\n /**\r\n * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.\r\n * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.\r\n */\r\n constructor(\r\n connection?: RTCConnectionArg,\r\n private channelName = DEFAULT_CHANNEL_NAME\r\n ) {\r\n super();\r\n\r\n RTCMessageClient.prototype.initialize.call(this, connection, channelName);\r\n }\r\n\r\n /**\r\n * (Re)initializes the data channel with a new connection.\r\n * Cleans up the previous channel before establishing a new one.\r\n *\r\n * @param connection - RTCPeerConnection instance, promise, or factory function.\r\n * @param channelName - Optional new channel name. Defaults to the current channel name.\r\n */\r\n initialize(connection?: RTCConnectionArg, channelName: string = this.channelName): void {\r\n this.channelName = channelName;\r\n\r\n this[CONNECTION] = Promise.race([\r\n this[CONNECTION],\r\n timeout(5000, [null, noop] as const)\r\n ])\r\n .then(([_, deinitialize]) => deinitialize())\r\n .catch(noop)\r\n .then(() => {\r\n const _conn = typeof connection === 'function' ? connection() : connection;\r\n\r\n return promisify(_conn);\r\n })\r\n .then(conn => {\r\n if (!conn) return [undefined, noop] as const;\r\n\r\n const id = channelId(channelName);\r\n const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });\r\n\r\n const listener = (event: MessageEvent) => {\r\n const data: MessageResponse = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;\r\n\r\n this[RESPONSES$].next(data);\r\n };\r\n\r\n dataChannel.addEventListener('message', listener);\r\n\r\n return [dataChannel, () => {\r\n dataChannel.removeEventListener('message', listener);\r\n dataChannel.close();\r\n }] as const;\r\n });\r\n }\r\n\r\n public async [SEND]<T>(message: Message<T>) {\r\n const [dataChannel] = await this[CONNECTION];\r\n\r\n if (dataChannel?.readyState !== 'open') return;\r\n\r\n dataChannel.send(JSON.stringify(message));\r\n }\r\n\r\n protected [GET_NEW_ID](): string {\r\n return uniqueId('messenger-rtc-message');\r\n }\r\n}\r\n"]}
@@ -0,0 +1,93 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RTCMessageHost = void 0;
4
+ const noop_1 = require("@telperion/js-utils/function/noop");
5
+ const promisify_1 = require("@telperion/js-utils/promise/promisify");
6
+ const timeout_1 = require("@telperion/js-utils/promise/timeout");
7
+ const rxjs_1 = require("rxjs");
8
+ const message_host_1 = require("../message-host");
9
+ const selectors_1 = require("../selectors");
10
+ const default_channel_name_1 = require("./default-channel-name");
11
+ const channel_id_1 = require("./channel-id");
12
+ const CONNECTION = Symbol('RTCMessageHost Connection');
13
+ const REQUESTS = Symbol('RTCMessageHost Requests');
14
+ /**
15
+ * Message host for WebRTC DataChannel communication.
16
+ *
17
+ * Listens for incoming messages on a negotiated RTCDataChannel and sends responses
18
+ * back over the same channel. Both peers must create the channel with identical
19
+ * name and negotiated ID (handled automatically via {@link channelId}).
20
+ *
21
+ * @example
22
+ * ```typescript
23
+ * class GameHost extends RTCMessageHost {
24
+ * @Listen('move')
25
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
26
+ * return of(applyMove(data));
27
+ * }
28
+ * }
29
+ *
30
+ * const host = new GameHost(peerConnection, 'game-events');
31
+ * ```
32
+ */
33
+ class RTCMessageHost extends message_host_1.MessageHost {
34
+ channelName;
35
+ [REQUESTS] = new rxjs_1.Subject();
36
+ [CONNECTION] = Promise.resolve([undefined, noop_1.noop]);
37
+ /**
38
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
39
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
40
+ */
41
+ constructor(connection, channelName = default_channel_name_1.DEFAULT_CHANNEL_NAME) {
42
+ super();
43
+ this.channelName = channelName;
44
+ RTCMessageHost.prototype.initialize.call(this, connection, channelName);
45
+ this[selectors_1.LISTEN](this[REQUESTS]);
46
+ }
47
+ /**
48
+ * (Re)initializes the data channel with a new connection.
49
+ * Cleans up the previous channel before establishing a new one.
50
+ *
51
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
52
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
53
+ */
54
+ initialize(connection, channelName = this.channelName) {
55
+ this.channelName = channelName;
56
+ this[CONNECTION] = Promise.race([
57
+ this[CONNECTION],
58
+ (0, timeout_1.timeout)(5000, [null, noop_1.noop])
59
+ ])
60
+ .then(([_, deinitialize]) => deinitialize())
61
+ .catch(noop_1.noop)
62
+ .then(() => {
63
+ const _conn = typeof connection === 'function' ? connection() : connection;
64
+ return (0, promisify_1.promisify)(_conn);
65
+ })
66
+ .then(conn => {
67
+ if (!conn)
68
+ return [undefined, noop_1.noop];
69
+ const id = (0, channel_id_1.channelId)(channelName);
70
+ const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });
71
+ const handler = (event) => {
72
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
73
+ this[REQUESTS].next(data);
74
+ };
75
+ dataChannel.addEventListener('message', handler);
76
+ return [dataChannel, () => {
77
+ dataChannel.removeEventListener('message', handler);
78
+ dataChannel.close();
79
+ }];
80
+ });
81
+ }
82
+ /** Closes the data channel and removes event listeners. */
83
+ terminate() {
84
+ this[CONNECTION]
85
+ .then(([_, deinitialize]) => deinitialize())
86
+ .catch(noop_1.noop);
87
+ }
88
+ async [selectors_1.RESPONSE](message) {
89
+ const [dataChannel] = await this[CONNECTION];
90
+ dataChannel?.send(JSON.stringify(message));
91
+ }
92
+ }
93
+ exports.RTCMessageHost = RTCMessageHost;
@@ -0,0 +1,47 @@
1
+ import { MessageHost } from '../message-host';
2
+ import { MessageResponse } from '../message-response.type';
3
+ import { RESPONSE } from '../selectors';
4
+ import { RTCConnectionArg } from './rtc.type';
5
+ declare const CONNECTION: unique symbol;
6
+ declare const REQUESTS: unique symbol;
7
+ /**
8
+ * Message host for WebRTC DataChannel communication.
9
+ *
10
+ * Listens for incoming messages on a negotiated RTCDataChannel and sends responses
11
+ * back over the same channel. Both peers must create the channel with identical
12
+ * name and negotiated ID (handled automatically via {@link channelId}).
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * class GameHost extends RTCMessageHost {
17
+ * @Listen('move')
18
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
19
+ * return of(applyMove(data));
20
+ * }
21
+ * }
22
+ *
23
+ * const host = new GameHost(peerConnection, 'game-events');
24
+ * ```
25
+ */
26
+ export declare class RTCMessageHost extends MessageHost {
27
+ private channelName;
28
+ private [REQUESTS];
29
+ private [CONNECTION];
30
+ /**
31
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
32
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
33
+ */
34
+ constructor(connection?: RTCConnectionArg, channelName?: string);
35
+ /**
36
+ * (Re)initializes the data channel with a new connection.
37
+ * Cleans up the previous channel before establishing a new one.
38
+ *
39
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
40
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
41
+ */
42
+ initialize(connection: RTCConnectionArg, channelName?: string): void;
43
+ /** Closes the data channel and removes event listeners. */
44
+ terminate(): void;
45
+ protected [RESPONSE](message: MessageResponse): Promise<void>;
46
+ }
47
+ export {};
@@ -0,0 +1,91 @@
1
+ import { noop } from '@telperion/js-utils/function/noop';
2
+ import { promisify } from '@telperion/js-utils/promise/promisify';
3
+ import { timeout } from '@telperion/js-utils/promise/timeout';
4
+ import { Subject } from 'rxjs';
5
+ import { MessageHost } from '../message-host';
6
+ import { LISTEN, RESPONSE } from '../selectors';
7
+ import { DEFAULT_CHANNEL_NAME } from './default-channel-name';
8
+ import { channelId } from './channel-id';
9
+ const CONNECTION = Symbol('RTCMessageHost Connection');
10
+ const REQUESTS = Symbol('RTCMessageHost Requests');
11
+ /**
12
+ * Message host for WebRTC DataChannel communication.
13
+ *
14
+ * Listens for incoming messages on a negotiated RTCDataChannel and sends responses
15
+ * back over the same channel. Both peers must create the channel with identical
16
+ * name and negotiated ID (handled automatically via {@link channelId}).
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * class GameHost extends RTCMessageHost {
21
+ * @Listen('move')
22
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
23
+ * return of(applyMove(data));
24
+ * }
25
+ * }
26
+ *
27
+ * const host = new GameHost(peerConnection, 'game-events');
28
+ * ```
29
+ */
30
+ export class RTCMessageHost extends MessageHost {
31
+ channelName;
32
+ [REQUESTS] = new Subject();
33
+ [CONNECTION] = Promise.resolve([undefined, noop]);
34
+ /**
35
+ * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.
36
+ * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.
37
+ */
38
+ constructor(connection, channelName = DEFAULT_CHANNEL_NAME) {
39
+ super();
40
+ this.channelName = channelName;
41
+ RTCMessageHost.prototype.initialize.call(this, connection, channelName);
42
+ this[LISTEN](this[REQUESTS]);
43
+ }
44
+ /**
45
+ * (Re)initializes the data channel with a new connection.
46
+ * Cleans up the previous channel before establishing a new one.
47
+ *
48
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
49
+ * @param channelName - Optional new channel name. Defaults to the current channel name.
50
+ */
51
+ initialize(connection, channelName = this.channelName) {
52
+ this.channelName = channelName;
53
+ this[CONNECTION] = Promise.race([
54
+ this[CONNECTION],
55
+ timeout(5000, [null, noop])
56
+ ])
57
+ .then(([_, deinitialize]) => deinitialize())
58
+ .catch(noop)
59
+ .then(() => {
60
+ const _conn = typeof connection === 'function' ? connection() : connection;
61
+ return promisify(_conn);
62
+ })
63
+ .then(conn => {
64
+ if (!conn)
65
+ return [undefined, noop];
66
+ const id = channelId(channelName);
67
+ const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });
68
+ const handler = (event) => {
69
+ const data = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;
70
+ this[REQUESTS].next(data);
71
+ };
72
+ dataChannel.addEventListener('message', handler);
73
+ return [dataChannel, () => {
74
+ dataChannel.removeEventListener('message', handler);
75
+ dataChannel.close();
76
+ }];
77
+ });
78
+ }
79
+ /** Closes the data channel and removes event listeners. */
80
+ terminate() {
81
+ this[CONNECTION]
82
+ .then(([_, deinitialize]) => deinitialize())
83
+ .catch(noop);
84
+ }
85
+ async [RESPONSE](message) {
86
+ const [dataChannel] = await this[CONNECTION];
87
+ dataChannel?.send(JSON.stringify(message));
88
+ }
89
+ }
90
+
91
+ //# sourceMappingURL=message-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/message-host.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mCAAmC,CAAC;AACzD,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EAAE,OAAO,EAAE,MAAM,qCAAqC,CAAC;AAC9D,OAA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AAE,EAAE,CAAC,YAAY,EAAE,CAAC;aAC3C,KAAK,CAAC,IAAI,CAAC,CAAC;IACjB,CAAC;IAES,KAAK,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAwB;QACjD,MAAM,CAAC,WAAW,CAAC,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC;QAE7C,WAAW,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC;IAC7C,CAAC;CACF","file":"message-host.js","sourcesContent":["import { noop } from '@telperion/js-utils/function/noop';\r\nimport { promisify } from '@telperion/js-utils/promise/promisify';\r\nimport { timeout } from '@telperion/js-utils/promise/timeout';\r\nimport { Subject } from 'rxjs';\r\n\r\nimport { MessageHost } from '../message-host';\r\nimport { MessageResponse } from '../message-response.type';\r\nimport { Message } from '../message.interface';\r\nimport { LISTEN, RESPONSE } from '../selectors';\r\nimport { RTCConnectionArg } from './rtc.type';\r\nimport { DEFAULT_CHANNEL_NAME } from './default-channel-name';\r\nimport { channelId } from './channel-id';\r\n\r\nconst CONNECTION = Symbol('RTCMessageHost Connection');\r\nconst REQUESTS = Symbol('RTCMessageHost Requests');\r\n\r\n/**\r\n * Message host for WebRTC DataChannel communication.\r\n *\r\n * Listens for incoming messages on a negotiated RTCDataChannel and sends responses\r\n * back over the same channel. Both peers must create the channel with identical\r\n * name and negotiated ID (handled automatically via {@link channelId}).\r\n *\r\n * @example\r\n * ```typescript\r\n * class GameHost extends RTCMessageHost {\r\n * @Listen('move')\r\n * handleMove({ data }: { data: [number, number] }): Observable<boolean> {\r\n * return of(applyMove(data));\r\n * }\r\n * }\r\n *\r\n * const host = new GameHost(peerConnection, 'game-events');\r\n * ```\r\n */\r\nexport class RTCMessageHost extends MessageHost {\r\n private [REQUESTS] = new Subject<Message>();\r\n private [CONNECTION] = Promise.resolve([undefined as RTCDataChannel | undefined, noop] as const);\r\n\r\n /**\r\n * @param connection - RTCPeerConnection instance, promise, or factory function. Omit to initialize later via {@link initialize}.\r\n * @param channelName - Name for the negotiated data channel. Determines the channel ID via FNV-1a hash.\r\n */\r\n constructor(\r\n connection?: RTCConnectionArg,\r\n private channelName = DEFAULT_CHANNEL_NAME\r\n ) {\r\n super();\r\n\r\n RTCMessageHost.prototype.initialize.call(this, connection, channelName);\r\n\r\n this[LISTEN](this[REQUESTS]);\r\n }\r\n\r\n /**\r\n * (Re)initializes the data channel with a new connection.\r\n * Cleans up the previous channel before establishing a new one.\r\n *\r\n * @param connection - RTCPeerConnection instance, promise, or factory function.\r\n * @param channelName - Optional new channel name. Defaults to the current channel name.\r\n */\r\n initialize(connection: RTCConnectionArg, channelName: string = this.channelName): void {\r\n this.channelName = channelName;\r\n\r\n this[CONNECTION] = Promise.race([\r\n this[CONNECTION],\r\n timeout(5000, [null, noop] as const)\r\n ])\r\n .then(([_, deinitialize]) => deinitialize())\r\n .catch(noop)\r\n .then(() => {\r\n const _conn = typeof connection === 'function' ? connection() : connection;\r\n\r\n return promisify(_conn);\r\n })\r\n .then(conn => {\r\n if (!conn) return [undefined, noop] as const;\r\n\r\n const id = channelId(channelName);\r\n const dataChannel = conn.createDataChannel(channelName, { negotiated: true, id });\r\n\r\n const handler = (event: MessageEvent) => {\r\n const data: Message = typeof event.data === 'string' ? JSON.parse(event.data) : event.data;\r\n\r\n this[REQUESTS].next(data);\r\n };\r\n\r\n dataChannel.addEventListener('message', handler);\r\n\r\n return [dataChannel, () => {\r\n dataChannel.removeEventListener('message', handler);\r\n dataChannel.close();\r\n }] as const;\r\n });\r\n }\r\n\r\n /** Closes the data channel and removes event listeners. */\r\n public terminate(): void {\r\n this[CONNECTION]\r\n .then(([_, deinitialize]) => deinitialize())\r\n .catch(noop);\r\n }\r\n\r\n protected async [RESPONSE](message: MessageResponse) {\r\n const [dataChannel] = await this[CONNECTION];\r\n\r\n dataChannel?.send(JSON.stringify(message));\r\n }\r\n}\r\n"]}
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RTCMessageService = void 0;
4
+ const mixin_1 = require("@telperion/js-utils/class/mixin");
5
+ const message_client_1 = require("./message-client");
6
+ const message_host_1 = require("./message-host");
7
+ const default_channel_name_1 = require("./default-channel-name");
8
+ /**
9
+ * Bidirectional message service for WebRTC DataChannel communication.
10
+ *
11
+ * Combines {@link RTCMessageHost} and {@link RTCMessageClient} via mixin,
12
+ * enabling both `@Listen` and `@Request` decorators on the same class.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * class GamePeer extends RTCMessageService {
17
+ * @Request('move')
18
+ * sendMove(pos: [number, number]): Observable<boolean> { return null!; }
19
+ *
20
+ * @Listen('move')
21
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
22
+ * return of(applyMove(data));
23
+ * }
24
+ * }
25
+ *
26
+ * const peer = new GamePeer(peerConnection, 'game-events');
27
+ * ```
28
+ */
29
+ class RTCMessageService extends (0, mixin_1.mixin)(message_host_1.RTCMessageHost, message_client_1.RTCMessageClient) {
30
+ /**
31
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
32
+ * @param channelName - Name for the negotiated data channel.
33
+ */
34
+ constructor(connection, channelName = default_channel_name_1.DEFAULT_CHANNEL_NAME) {
35
+ super([connection, `${channelName}H`], [connection, `${channelName}C`]);
36
+ }
37
+ initialize = (connection, channelName) => {
38
+ message_host_1.RTCMessageHost.prototype.initialize.call(this, connection, channelName);
39
+ message_client_1.RTCMessageClient.prototype.initialize.call(this, connection, channelName);
40
+ };
41
+ }
42
+ exports.RTCMessageService = RTCMessageService;
@@ -0,0 +1,36 @@
1
+ import { RTCMessageClient } from "./message-client";
2
+ import { RTCConnectionArg } from "./rtc.type";
3
+ declare const RTCMessageService_base: new (args_0: [connection?: RTCConnectionArg, channelName?: string | undefined], args_1: [connection?: RTCConnectionArg, channelName?: string | undefined]) => {
4
+ initialize: (connection?: RTCConnectionArg, channelName?: string) => void;
5
+ terminate: () => void;
6
+ } & RTCMessageClient;
7
+ /**
8
+ * Bidirectional message service for WebRTC DataChannel communication.
9
+ *
10
+ * Combines {@link RTCMessageHost} and {@link RTCMessageClient} via mixin,
11
+ * enabling both `@Listen` and `@Request` decorators on the same class.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * class GamePeer extends RTCMessageService {
16
+ * @Request('move')
17
+ * sendMove(pos: [number, number]): Observable<boolean> { return null!; }
18
+ *
19
+ * @Listen('move')
20
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
21
+ * return of(applyMove(data));
22
+ * }
23
+ * }
24
+ *
25
+ * const peer = new GamePeer(peerConnection, 'game-events');
26
+ * ```
27
+ */
28
+ export declare class RTCMessageService extends RTCMessageService_base {
29
+ /**
30
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
31
+ * @param channelName - Name for the negotiated data channel.
32
+ */
33
+ constructor(connection?: RTCConnectionArg, channelName?: string);
34
+ initialize: (connection: RTCConnectionArg, channelName?: string) => void;
35
+ }
36
+ export {};
@@ -0,0 +1,40 @@
1
+ import { mixin } from "@telperion/js-utils/class/mixin";
2
+ import { RTCMessageClient } from "./message-client";
3
+ import { RTCMessageHost } from "./message-host";
4
+ import { DEFAULT_CHANNEL_NAME } from "./default-channel-name";
5
+ /**
6
+ * Bidirectional message service for WebRTC DataChannel communication.
7
+ *
8
+ * Combines {@link RTCMessageHost} and {@link RTCMessageClient} via mixin,
9
+ * enabling both `@Listen` and `@Request` decorators on the same class.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * class GamePeer extends RTCMessageService {
14
+ * @Request('move')
15
+ * sendMove(pos: [number, number]): Observable<boolean> { return null!; }
16
+ *
17
+ * @Listen('move')
18
+ * handleMove({ data }: { data: [number, number] }): Observable<boolean> {
19
+ * return of(applyMove(data));
20
+ * }
21
+ * }
22
+ *
23
+ * const peer = new GamePeer(peerConnection, 'game-events');
24
+ * ```
25
+ */
26
+ export class RTCMessageService extends mixin(RTCMessageHost, RTCMessageClient) {
27
+ /**
28
+ * @param connection - RTCPeerConnection instance, promise, or factory function.
29
+ * @param channelName - Name for the negotiated data channel.
30
+ */
31
+ constructor(connection, channelName = DEFAULT_CHANNEL_NAME) {
32
+ super([connection, `${channelName}H`], [connection, `${channelName}C`]);
33
+ }
34
+ initialize = (connection, channelName) => {
35
+ RTCMessageHost.prototype.initialize.call(this, connection, channelName);
36
+ RTCMessageClient.prototype.initialize.call(this, connection, channelName);
37
+ };
38
+ }
39
+
40
+ //# sourceMappingURL=message-service.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/message-service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AACxD,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAEhD,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAE9D;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,OAAO,iBAAkB,SAAQ,KAAK,CAAC,cAAc,EAAE,gBAAgB,CAAC;IAC5E;;;OAGG;IACH,YAAY,UAA6B,EAAE,WAAW,GAAG,oBAAoB;QAC3E,KAAK,CAAC,CAAC,UAAU,EAAE,GAAG,WAAW,GAAG,CAAC,EAAE,CAAC,UAAU,EAAE,GAAG,WAAW,GAAG,CAAC,CAAC,CAAC;IAC1E,CAAC;IAEe,UAAU,GAAG,CAAC,UAA4B,EAAE,WAAoB,EAAQ,EAAE;QACxF,cAAc,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;QACxE,gBAAgB,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,EAAE,WAAW,CAAC,CAAC;IAC5E,CAAC,CAAC;CACH","file":"message-service.js","sourcesContent":["import { mixin } from \"@telperion/js-utils/class/mixin\";\r\nimport { RTCMessageClient } from \"./message-client\";\r\nimport { RTCMessageHost } from \"./message-host\";\r\nimport { RTCConnectionArg } from \"./rtc.type\";\r\nimport { DEFAULT_CHANNEL_NAME } from \"./default-channel-name\";\r\n\r\n/**\r\n * Bidirectional message service for WebRTC DataChannel communication.\r\n *\r\n * Combines {@link RTCMessageHost} and {@link RTCMessageClient} via mixin,\r\n * enabling both `@Listen` and `@Request` decorators on the same class.\r\n *\r\n * @example\r\n * ```typescript\r\n * class GamePeer extends RTCMessageService {\r\n * @Request('move')\r\n * sendMove(pos: [number, number]): Observable<boolean> { return null!; }\r\n *\r\n * @Listen('move')\r\n * handleMove({ data }: { data: [number, number] }): Observable<boolean> {\r\n * return of(applyMove(data));\r\n * }\r\n * }\r\n *\r\n * const peer = new GamePeer(peerConnection, 'game-events');\r\n * ```\r\n */\r\nexport class RTCMessageService extends mixin(RTCMessageHost, RTCMessageClient) {\r\n /**\r\n * @param connection - RTCPeerConnection instance, promise, or factory function.\r\n * @param channelName - Name for the negotiated data channel.\r\n */\r\n constructor(connection?: RTCConnectionArg, channelName = DEFAULT_CHANNEL_NAME) {\r\n super([connection, `${channelName}H`], [connection, `${channelName}C`]);\r\n }\r\n\r\n public override initialize = (connection: RTCConnectionArg, channelName?: string): void => {\r\n RTCMessageHost.prototype.initialize.call(this, connection, channelName);\r\n RTCMessageClient.prototype.initialize.call(this, connection, channelName);\r\n };\r\n}\r\n"]}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
1
+ /** An RTCPeerConnection instance or `undefined` if not yet available. */
2
+ export type RTCConnectionType = RTCPeerConnection | undefined;
3
+ /** A promise that resolves to an RTCPeerConnection (or `undefined`). */
4
+ export type RTCConnectionPromise = Promise<RTCConnectionType>;
5
+ /** A factory function that returns an RTCPeerConnection synchronously or asynchronously. */
6
+ export type RTCConnectionFactory = () => RTCConnectionType | RTCConnectionPromise;
7
+ /**
8
+ * Flexible connection argument accepted by RTC message classes.
9
+ *
10
+ * Supports direct instances, promises, and factory functions for lazy or async initialization.
11
+ */
12
+ export type RTCConnectionArg = RTCConnectionType | RTCConnectionPromise | RTCConnectionFactory;
@@ -0,0 +1,3 @@
1
+ export {};
2
+
3
+ //# sourceMappingURL=rtc.type.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../libs/messenger/src/rtc/rtc.type.ts"],"names":[],"mappings":"","file":"rtc.type.js","sourcesContent":["/** An RTCPeerConnection instance or `undefined` if not yet available. */\r\nexport type RTCConnectionType = RTCPeerConnection | undefined;\r\n\r\n/** A promise that resolves to an RTCPeerConnection (or `undefined`). */\r\nexport type RTCConnectionPromise = Promise<RTCConnectionType>;\r\n\r\n/** A factory function that returns an RTCPeerConnection synchronously or asynchronously. */\r\nexport type RTCConnectionFactory = () => RTCConnectionType | RTCConnectionPromise;\r\n\r\n/**\r\n * Flexible connection argument accepted by RTC message classes.\r\n *\r\n * Supports direct instances, promises, and factory functions for lazy or async initialization.\r\n */\r\nexport type RTCConnectionArg = RTCConnectionType | RTCConnectionPromise | RTCConnectionFactory;\r\n"]}