npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@kidlib/p2p

v0.5.6

Published

Signaling-agnostic WebRTC helpers.

Readme

@kidlib/p2p

Signaling-agnostic WebRTC helpers for group and 1:1 peer connections. No backend included — you provide the signaling transport.

The default configuration is STUN-only. That discovers direct paths but cannot relay traffic; production calls on symmetric NATs, restrictive mobile or corporate networks, and some CGNATs need a TURN service.

Install

pnpm add @kidlib/p2p

Group calls — P2PRoom

joinP2PRoom connects a local member into a mesh room. Each remote member gets its own 1:1 connection managed automatically.

import { joinP2PRoom } from '@kidlib/p2p';

const room = await joinP2PRoom({
  peerId: crypto.randomUUID(),
  presenceData: { displayName: 'Ada', callState: 'joined' },
  roomId,
  createSignaling: ({ roomId }) => createRoomSignalingForApp(roomId),
  getLocalStream: () =>
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }),
  onLocalStream: ({ stream }) => renderLocalPreview(stream),
});

const renderRemoteStreams = () => renderRemoteTiles(room.remoteMemberStreams);

room.on('memberStream', renderRemoteStreams);
room.on('memberLeft', renderRemoteStreams);
room.on('membersChanged', ({ memberCount, memberCapacity, memberPresence }) => {
  renderCapacity(memberCount, memberCapacity);
  renderRoster(memberPresence);
});

await room.setPresenceData({ displayName: 'Ada', muted: true });

await room.dispose();

For short-lived TURN credentials, provide one callback that calls your authenticated backend. A room fetches once before creating peer connections, shares the result across its pairs, and refreshes it before expiry:

const room = await joinP2PRoom({
  peerId,
  signaling,
  iceServersProvider: async ({ signal }) => {
    const response = await fetch('/api/turn-credentials', { signal });
    if (!response.ok) throw new Error('TURN credentials unavailable');
    return response.json(); // { iceServers: [...], expiresAt?: epochMs }
  },
});

Provider account secrets belong only on that backend, never in browser code. Static TURN remains supported through rtcConfig.iceServers.

Factory-created media is owned by the room: leave() and dispose() stop the local tracks. You can still pass signaling and localStream directly when an app needs to own setup, preview, device switching, or teardown itself.

Use watchP2PRoom to observe room presence before joining. This lets an app detect incoming calls or capacity without announcing the local peer.

import { watchP2PRoom } from '@kidlib/p2p';

const room = await watchP2PRoom({
  roomId,
  createSignaling: ({ roomId }) => createRoomSignalingForApp(roomId),
  getLocalStream: () =>
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }),
  peerId: crypto.randomUUID(),
  memberCapacity: 2,
});

room.on('full', ({ members, memberCapacity }) => {
  showRoomFull(members, memberCapacity);
});

// `alone` fires when the last remote member leaves. For 1:1 call flows,
// pass `autoDisposeWhenAlone: true` to dispose the room automatically instead.
room.on('alone', () => endCall());

// `memberStreamRemoved` fires whenever a remote stream is dropped (peer left,
// connection closed, failed, or aborted). `memberLeft` is unchanged.
room.on('memberStreamRemoved', ({ memberId }) => removeRemoteTile(memberId));

await room.join();  // enter presence and connect
await room.leave();   // leave presence, close sessions, keep watching
await room.dispose(); // leave presence and permanently tear down the room

Use leave() when the app wants to keep observing the same room after the local member exits. Use dispose() when the user is done with the room; it awaits explicit departure before tearing down subscriptions, peer connections, owned media, and signaling.

Lifecycle naming

Package-owned objects use dispose() for permanent, non-reusable teardown: P2PRoom, P2PSession, and Peer. Only rooms also expose leave(), which exits presence while keeping the room reusable. Low-level signaling transports and native WebRTC objects retain their conventional close() methods.

Reserved local media slots

Use localTrackSlots when a call must reserve a sender before initial SDP negotiation. Slots are keyed by caller-defined ID, so multiple slots may have the same media kind. A null slot needs no placeholder track or device permission and can later receive a same-kind track with setLocalTrack():

const localStream = await navigator.mediaDevices.getUserMedia({
  audio: true,
  video: isVideoCall,
});

const room = await joinP2PRoom({
  peerId,
  signaling,
  localStream,
  localTrackSlots: [
    {
      id: 'microphone',
      kind: 'audio',
      track: localStream.getAudioTracks()[0],
    },
    {
      id: 'primary-video',
      kind: 'video',
      track: localStream.getVideoTracks()[0] ?? null,
    },
  ],
});

// Camera on, camera switch, screen capture, camera off, and restore all use
// the same reserved sender and do not require SDP renegotiation.
await room.setLocalTrack('primary-video', cameraTrack);
await room.setLocalTrack('primary-video', backCameraTrack);
await room.setLocalTrack('primary-video', screenTrack);
await room.setLocalTrack('primary-video', null);

Slot tracks are caller-owned: replacement never stops the old or new track. The room adds/removes the current slot tracks from room.localStream and emits localStream so previews and Solid adapters can react. With getLocalStream, the room retains its existing whole-stream cleanup behavior, except that later slot replacement tracks remain caller-owned. If a slot still references a factory-owned track when the room releases that stream, the slot resets to null rather than retaining an ended track.

Unknown slot IDs and media-kind mismatches reject before changing state. For a room-wide replacement, the room commits the requested track as its desired state and attempts every active pair. If some replaceTrack() calls fail, setLocalTrack() rejects with LocalTrackReplacementError; its slotId and failures array identify each failed memberId and underlying error. Successful pairs and members joining later use the new track, while failed pairs retain their previous sender track. Calling setLocalTrack() again retries all active pairs. Overlapping calls for the same slot are not serialized; await each setLocalTrack() before issuing the next.

When localTrackSlots is omitted, publication continues to use the existing localStream/getLocalStream and audioOnly behavior unchanged. Slot mode is opt-in and its slots define which local tracks are published: tracks in localStream or a factory stream that no slot references appear in room.localStream but are never sent to remote members.

Because the video m-line is negotiated up front, a remote browser may expose a muted video receiver track before the camera is installed. Consumers should treat track mute/unmute and media availability as transport state rather than as a semantic camera label; this package intentionally adds no remote slot labeling or signaling protocol.

A peerId is a singleton identity: if a peer reloads or reconnects under the same id, the room tears down the old session and builds a fresh one. Your signaling adapter owns expiring peers that disappear without a clean leave() (e.g. a crash) — see docs/signaling.md.

Solid apps can use the @kidlib/p2p/solid adapter. See docs/solidjs.md.

Browser-native apps can use the @kidlib/p2p/components web components. See docs/web-components.md.

1:1 calls — P2PSession

For direct connections between exactly two peers.

import { startP2PSession, joinP2PSession } from '@kidlib/p2p';

// Initiator — sends the offer
const session = await startP2PSession({ signaling, localStream });

// Joiner — answers the offer
const session = await joinP2PSession({ signaling, localStream });

session.on('remoteStream', ({ stream }) => renderStream(stream));
session.dispose();

signaling must implement RtcSignalingSource — see docs/signaling.md.

Startup error codes

Startup failures from Peer.start(), the session factories, and P2PRoom (rejected promises and the room error event's error) carry a stable error.code. Match on the code, not the message.

import { P2P_ERROR_CODES } from '@kidlib/p2p';

room.on('error', ({ memberId, error }) => {
  if (error.code === P2P_ERROR_CODES.CONNECTION_TIMEOUT) retry(memberId);
});

| Code | Cause | |------|-------| | START_TIMEOUT | startTimeoutMs elapsed | | CONNECTION_TIMEOUT | connectedTimeoutMs elapsed | | CONNECTION_FAILED | Connection failed before start/data channel open completed | | CONNECTION_CLOSED | Connection closed before start/data channel open completed | | DATA_CHANNEL_OPEN_TIMEOUT | dataChannelOpenTimeoutMs elapsed | | DATA_CHANNEL_CLOSED | Data channel closed before opening | | START_CLOSED | Peer was disposed before start completed | | SIGNAL_BUFFER_LIMIT | Joiner's early-signal buffer overflowed | | ABORTED | signal aborted; error.name stays 'AbortError' |

Advanced: tuning senders / reading stats

For tuning the library doesn't cover, use the underlying RTCPeerConnection: session.peerConnection, room.getPeerConnection(memberId), or room.peerConnections() (a Map snapshot keyed by member ID). A room emits peerConnection with { memberId, peerConnection } once a member's connection is established and returned by getPeerConnection(). The entry is removed when the member leaves. A member who rejoins gets a new connection and a new event, so apply parameters from the event rather than once. A listed connection can still be failed or closed before the member leaves, so check connectionState before calling into it. The room does not catch errors from your handler; handle rejections from async listeners yourself.

Each connection is created once per member and is not replaced by ICE restarts. Senders for reserved local track slots stay the same for the connection's lifetime, and setLocalTrack() uses replaceTrack(), which keeps any parameters you set. You don't need to reapply them after a track switch.

room.on('peerConnection', async ({ peerConnection }) => {
  // Select by transceiver so empty slots (sender.track === null) are included.
  for (const { receiver, sender } of peerConnection.getTransceivers()) {
    if (receiver.track.kind !== 'video') continue;
    const params = sender.getParameters();
    if (!params.encodings?.length) continue;
    params.encodings[0].maxBitrate = 600_000;
    await sender.setParameters(params);
  }
});

for (const [memberId, pc] of room.peerConnections()) {
  if (pc.connectionState === 'closed') continue;
  const stats = await pc.getStats();
  stats.forEach((report) => {
    if (report.type === 'outbound-rtp' && report.kind === 'video') {
      console.log(memberId, report.qualityLimitationReason, report.frameHeight);
    }
  });
}

Lower-level exports

| Export | Description | Docs | |--------|-------------|------| | createPairSignaling | Normalize a 1:1 signaling source | docs/signaling.md | | createRelayPeerSignaling | Adapt a peer-addressed relay stream into 1:1 signaling | docs/signaling.md | | createRoomSignaling | Normalize a room signaling source | docs/signaling.md | | validateRoomSignaling | Validate a room signaling source | docs/signaling.md | | Peer | Direct RTCPeerConnection control | docs/peer.md | | P2P_ERROR_CODES | Stable startup error.code values | Startup error codes | | attachRemoteStream | Assemble remote tracks into a MediaStream | docs/peer.md | | setLogger | Wire a custom logger | docs/peer.md |

Development

pnpm install
pnpm test

Tests run in Vitest browser mode against real browser WebRTC APIs via Playwright Chromium.