baseconnection.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import type { Peer } from "./peer";
  2. import type { ServerMessage } from "./servermessage";
  3. import type { ConnectionType } from "./enums";
  4. import { BaseConnectionErrorType } from "./enums";
  5. import {
  6. EventEmitterWithError,
  7. type EventsWithError,
  8. PeerError,
  9. } from "./peerError";
  10. import type { ValidEventTypes } from "eventemitter3";
  11. export interface BaseConnectionEvents<
  12. ErrorType extends string = BaseConnectionErrorType,
  13. > extends EventsWithError<ErrorType> {
  14. /**
  15. * Emitted when either you or the remote peer closes the connection.
  16. *
  17. * ```ts
  18. * connection.on('close', () => { ... });
  19. * ```
  20. */
  21. close: () => void;
  22. /**
  23. * ```ts
  24. * connection.on('error', (error) => { ... });
  25. * ```
  26. */
  27. error: (error: PeerError<`${ErrorType}`>) => void;
  28. iceStateChanged: (state: RTCIceConnectionState) => void;
  29. }
  30. export abstract class BaseConnection<
  31. SubClassEvents extends ValidEventTypes,
  32. ErrorType extends string = never,
  33. > extends EventEmitterWithError<
  34. ErrorType | BaseConnectionErrorType,
  35. SubClassEvents & BaseConnectionEvents<BaseConnectionErrorType | ErrorType>
  36. > {
  37. protected _open = false;
  38. /**
  39. * Any type of metadata associated with the connection,
  40. * passed in by whoever initiated the connection.
  41. */
  42. readonly metadata: any;
  43. connectionId: string;
  44. peerConnection: RTCPeerConnection;
  45. dataChannel: RTCDataChannel;
  46. abstract get type(): ConnectionType;
  47. /**
  48. * The optional label passed in or assigned by PeerJS when the connection was initiated.
  49. */
  50. label: string;
  51. /**
  52. * Whether the media connection is active (e.g. your call has been answered).
  53. * You can check this if you want to set a maximum wait time for a one-sided call.
  54. */
  55. get open() {
  56. return this._open;
  57. }
  58. protected constructor(
  59. /**
  60. * The ID of the peer on the other end of this connection.
  61. */
  62. readonly peer: string,
  63. public provider: Peer,
  64. readonly options: any,
  65. ) {
  66. super();
  67. this.metadata = options.metadata;
  68. }
  69. abstract close(): void;
  70. /**
  71. * @internal
  72. */
  73. abstract handleMessage(message: ServerMessage): void;
  74. /**
  75. * Called by the Negotiator when the DataChannel is ready.
  76. * @internal
  77. * */
  78. abstract _initializeDataChannel(dc: RTCDataChannel): void;
  79. }