peerix - v0.8.0
    Preparing search index...

    Class Room<M>

    Manages WebRTC peer connections, media streams, and data channels.

    Type Parameters

    Index
    • Creates a new Room instance.

      Type Parameters

      Parameters

      • Optionaloptions: RoomOptions<M>

        Room configuration options.

      Returns Room<M>

      // create a new room with default options
      const room = new Room();

      In TypeScript, pass the metadata type to type join(), me, verify, and the metadata of peers in peers and events:

      const room = new Room<{ name: string }>({ id: "my-room" });
      room.on("connection:connected", (e) => console.log(e.peer.metadata?.name));
    • get active(): boolean

      Indicates whether the room is currently active (joined).

      Returns boolean

    • get id(): string

      Unique room identifier.

      Returns string

    • get peers(): ReadonlyMap<string, Peer<M>>

      Active peers indexed by peer id.

      Returns ReadonlyMap<string, Peer<M>>

    • Attaches an addon/extension to the Room instance. Attaching an addon that is already attached does nothing.

      Parameters

      • addon: Addon<any>

        Addon instance to attach.

      Returns Promise<void>

    • Closes a previously opened data channel with the given label and removes it from all peers.

      Parameters

      • options: string | { label?: string }

        Channel label or object containing label.

      Returns Promise<void>

      // close the channel with an explicit label
      await room.close({ label: "chat" });
    • Detaches a previously attached addon/extension from the Room instance. Detaching an addon that is not attached does nothing.

      Parameters

      • addon: Addon<any>

        Addon instance to detach.

      Returns Promise<void>

    • Joins a room and starts listening for incoming connections.

      If the room is already joined or joining, this method resolves with the existing local peer, and the given metadata is ignored. If the room is leaving, it joins again once the leave completes.

      Parameters

      • Optionalmetadata: M

        Metadata to associate with the peer.

      Returns Promise<PeerInfo<M>>

      The local peer with its id and optional metadata.

      // join a room with optional metadata
      const me = await room.join({ name: "Alice" });
      console.log(`I am ${me.metadata.name} (ID: ${me.id})`);

      If the driver fails to subscribe to the room.

    • Leaves the current room and closes all active connections.

      If the room is not currently active, this method returns immediately without error. If the room is still joining, it leaves once the join completes.

      Returns Promise<void>

      // leave the current room
      await room.leave();
    • Removes a previously registered event listener.

      Type Parameters

      Parameters

      • event: K

        Event name.

      • Optionalhandler: (...args: RoomEvents<M>[K]) => void

        Event handler to remove. If omitted, all handlers for the event will be removed.

      Returns void

    • Subscribes to a room event.

      Type Parameters

      Parameters

      • event: K

        Event name.

      • handler: (...args: RoomEvents<M>[K]) => void

        Event handler.

      • Optionaloptions: ListenerOptions

        Listener options, such as an AbortSignal that removes the handler.

      Returns () => void

      A function that removes the handler.

      // subscribe to the "connection" event
      room.on("connection", (e) => {
      console.log("Connection state has changed:", e.state);
      });
    • Subscribes to an event and auto-unsubscribes after first invocation.

      Type Parameters

      Parameters

      • event: K

        Event name.

      • handler: (...args: RoomEvents<M>[K]) => void

        Event handler.

      • Optionaloptions: ListenerOptions

        Listener options, such as an AbortSignal that removes the handler.

      Returns () => void

      A function that removes the handler.

    • Opens a data channel with the given label and options to all peers. If a channel with the same label already exists, it will be reused.

      You can open a channel with the same label on both local and remote peers or only on one side. In any case, only one channel will be created for each label. You can send data through the channel in both directions.

      It resolves once the channel is requested, not once it is open, so wait for channel:open before sending through it.

      Parameters

      Returns Promise<void>

      // open a channel with an explicit label
      await room.open({ label: "chat" });
    • Sends a message through data channels to all connected peers.

      If options is a string, it is treated as the channel label. If a label is not provided, it uses the default channel.

      The send method works only with open channels that match the specified label and are either ordered (reliable) without a protocol, or have a protocol, which makes them raw. A raw channel accepts only strings and binary data, and an unreliable one drops a message while its buffer is backed up.

      Without to, the message is sent to every peer whose channel is open, and peers that are still connecting are skipped. With to, every target must have an open channel, otherwise the send fails before anything is sent. Failures are PeerixError instances with the DATACHANNEL_ERROR code. A peer that fails mid-transfer doesn't stop the others, and the send rejects with its failure once every transfer ends. A transfer to a peer fails once the channel buffer stops draining for 10 seconds.

      A ReadableStream sent to several peers is read as fast as the fastest peer takes it, and its chunks are buffered for the slower ones.

      Parameters

      • message: unknown

        Message payload to send.

      • Optionaloptions: string | SendOptions

        Send options or channel label.

      Returns ReadableStream<TransferProgress> & Promise<void>

      An iterable aggregated transfer progress across all connections or a promise which resolves when all transfers complete or error.

      // send a message to default channel
      await room.send("Hello, all peers!");
      // send a message to specific peers only
      await room.send("Hello, Bob!", { label: "chat", to: bobId });
      // send large data with a progress handler
      const file = new File([new Uint8Array(1024 * 1024)], "example.dat");
      const transfer = room.send(file, {
      label: "chat", // channel label
      info: { filename: file.name }, // sent with the first chunk
      signal: AbortSignal.timeout(10000), // abort signal
      });
      // optionally handle the progress
      for await (const progress of transfer) {
      const { id, label, current, total } = progress;
      const percent = Math.round((current / total) * 100);
      console.log(`[${id}:${label}] Sending... ${percent}%`);
      }
    • Shares a new media stream or updates an existing one for all peers including new ones that join later.

      If you pass a MediaStream instance directly, it will be shared under a label equal to the stream id. Otherwise, you can specify an explicit label in the options object. If a stream with the same label already exists, it will be updated and its tracks will be added/removed as needed to minimize renegotiations.

      Parameters

      • options: MediaStream | StreamOptions

        Stream descriptor or MediaStream instance.

      Returns Promise<void>

      // get a media stream from the user's camera and microphone
      const stream = await navigator.mediaDevices.getUserMedia(
      { video: true, audio: true }
      );

      // share a media stream with an explicit label
      await room.share({ label: "camera", stream });
    • Serializes the room to a JSON-compatible object.

      Returns { active: boolean; id: string; me: PeerInfo<M> | null; peers: string[] }

      A serializable representation of the room.

    • Stops sharing a previously shared media stream with the given label and removes it from all peers.

      If you pass a MediaStream instance directly, it will be unshared using its id as the label. Otherwise, you can specify the label in the options object or pass it directly as a string.

      Parameters

      • options: string | MediaStream | { label?: string }

        A stream label, MediaStream instance, or an object containing a label.

      Returns Promise<void>

      // unshare a media stream with an explicit label
      await room.unshare({ label: "camera" });