peerix - v0.5.0
    Preparing search index...

    Class Peer

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

    // create a new peer
    // using default in-memory signaling driver
    const peer = new Peer();

    // listen for connection state changes
    peer.on("connection", (e) => {
    const { remote, state } = e;
    console.log(`Peer "${remote.id}" state changed to "${state}"`);
    });

    // listen for open channel event
    peer.on("channel:open", (e) => {
    const { remote, label } = e;
    console.log(`Channel "${label}" opened with peer "${remote.id}"`);
    // send a message to the remote peer
    remote.send("Hello, peer!", { label });
    });

    // listen for incoming messages
    peer.on("channel:message", async (e) => {
    const { remote, data, label } = e;
    const message = await data;
    console.log(`Message from peer "${remote.id}" on channel "${label}":`, message);
    });

    // open a data channel
    await peer.open({ label: "default" });

    // join a room
    await peer.join({ room: "room-id" });
    Index

    Constructors

    • Creates a new Peer instance.

      Parameters

      • Optionaloptions: PeerOptions

        Peer configuration options.

      Returns Peer

      // create a new peer with default options
      const peer = new Peer();

    Accessors

    • get active(): boolean

      Indicates whether the peer is currently active (joined a room).

      Returns boolean

    • get id(): string

      Unique identifier for the local peer. Empty until join() is called.

      Returns string

    • get metadata(): unknown

      Optional metadata announced to other peers in signaling messages. Undefined until join() is called.

      Returns unknown

    • get room(): string

      Current room name. Empty until join() is called.

      Returns string

    Methods

    • Attaches an addon/extension to the peer instance.

      Parameters

      • addon: Addon

        Addon instance to attach.

      Returns Promise<void>

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

      Parameters

      • options: string | { label: string }

        Channel label or object containing label.

      Returns Promise<void>

      // close the channel with label "chat"
      await peer.close({ label: "chat" });
    • Detaches a previously attached addon/extension from the peer instance.

      Parameters

      • addon: Addon

        Addon instance to detach.

      Returns Promise<void>

    • Emits one or more events. Usually you would not call this method directly.

      Type Parameters

      Parameters

      • event: K | K[]

        Event name or list of event names.

      • ...args: PeerEvents[K]

        Event payload.

      Returns void

    • Joins a room and starts listening for incoming connections.

      Parameters

      Returns Promise<void>

      // join a room with ID "room-id" and custom metadata
      await peer.join({ room: "room-id", metadata: { name: "Alice" } });
    • Leaves the current room and closes all active remote connections.

      Returns Promise<void>

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

      Type Parameters

      Parameters

      • event: K | K[]

        Event name or list of event names.

      • Optionalhandler: (...args: PeerEvents[K]) => void

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

      Returns void

    • Subscribes to one or more peer events.

      Type Parameters

      Parameters

      Returns void

      // subscribe to the "connection" event
      peer.on("connection", (e) => {
      console.log("Connection state is changed:", e.state);
      });

      @param event Event name or list of event names. @param handler Event handler.

    • Subscribes to an event and auto-unsubscribes after first invocation.

      Type Parameters

      Parameters

      • event: K | K[]

        Event name or list of event names.

      • handler: (...args: PeerEvents[K]) => void

        Event handler.

      Returns void

    • Opens a data channel with the given label and options to all remote 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.

      Parameters

      Returns Promise<void>

      // open a channel with label "chat"
      await peer.open({ label: "chat" });
    • Sends a message through data channels to all connected remote 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 have no protocol, are ordered (reliable), and match the specified label.

      Parameters

      • message: unknown

        Message payload to send.

      • Optionaloptions: string | SendOptions

        Send options or channel label.

      Returns ReadableStream<TransferProgress> & Promise<void>

      A ReadableStream of aggregated transfer progress across all connections. The returned value also implements Promise, which resolves when all transfers complete or error.

      // send a message to default channel
      await peer.send("Hello, all peers!");
      // send large data with a progress handler
      const file = new File([new Uint8Array(1024 * 1024)], "example.dat");
      const transfer = peer.send(file, {
      label: "chat", // channel label
      info: { filename: file.name }, // metadata
      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 remote 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.

      If the stream is shared with the managed option, its tracks will be automatically stopped when the stream is unshared or replaced with a new stream.

      Parameters

      • options: MediaStream | StreamOptions

        Stream descriptor or MediaStream instance.

      Returns Promise<void | MediaStream>

      The shared MediaStream instance if successful, or undefined.

      // 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
      const sharedStream = await peer.share({ label: "camera", stream, managed: true });
    • Serializes the peer to a JSON-compatible object.

      Returns {
          active: boolean;
          channels: string[];
          connections: string[];
          id: string;
          metadata: unknown;
          room: string;
          streams: string[];
      }

      A serializable representation of the peer.

    • Stops sharing a previously shared media stream with the given label and removes it from all remote 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.

      If the stream was shared with the managed option, its tracks will be stopped automatically.

      Parameters

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

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

      Returns Promise<void | MediaStream>

      The unshared MediaStream instance, or undefined.

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