@poolse/sdk 2.1.6 → 2.2.0

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/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { Channel } from 'phoenix';
1
+ import { Channel, Socket } from 'phoenix';
2
2
 
3
3
  type Uuid = string;
4
4
  type IsoDateTime = string;
@@ -435,6 +435,302 @@ interface ResolvedConfig {
435
435
  userResolver: PoolseConfig['userResolver'];
436
436
  }
437
437
 
438
+ /**
439
+ * Voice types shared by the room (Discord-style "join voice") and call
440
+ * (WhatsApp-style ringing) surfaces.
441
+ *
442
+ * The WebRTC pieces are declared structurally rather than as the DOM's
443
+ * concrete `RTCPeerConnection`, so React Native can hand us
444
+ * `react-native-webrtc` — API-compatible, different classes — through
445
+ * {@link WebRtcAdapter} without the SDK importing anything native.
446
+ */
447
+ /** Connection lifecycle for a voice room. */
448
+ type VoiceStatus = 'idle' | 'connecting' | 'connected' | 'error';
449
+ /** Someone currently in a voice room, including yourself. */
450
+ interface VoiceParticipant {
451
+ userId: string;
452
+ muted: boolean;
453
+ speaking: boolean;
454
+ /** ms epoch from presence metadata; stable ordering key for rosters. */
455
+ joinedAt: number;
456
+ /** True for the local participant. */
457
+ isSelf: boolean;
458
+ }
459
+ /** The subset of `MediaStreamTrack` the SDK touches. */
460
+ interface VoiceTrack {
461
+ kind: string;
462
+ enabled: boolean;
463
+ stop(): void;
464
+ }
465
+ /** The subset of `MediaStream` the SDK touches. */
466
+ interface VoiceStream {
467
+ id: string;
468
+ getTracks(): VoiceTrack[];
469
+ getAudioTracks(): VoiceTrack[];
470
+ }
471
+ /** Session description exchanged during negotiation. */
472
+ interface VoiceDescription {
473
+ type: string;
474
+ sdp?: string | undefined;
475
+ }
476
+ /** ICE candidate in its wire (JSON) form. */
477
+ interface VoiceCandidate {
478
+ candidate?: string | undefined;
479
+ sdpMid?: string | null | undefined;
480
+ sdpMLineIndex?: number | null | undefined;
481
+ usernameFragment?: string | null | undefined;
482
+ }
483
+ /** The subset of `RTCPeerConnection` the SDK drives. */
484
+ interface VoicePeerConnection {
485
+ addTrack(track: VoiceTrack, stream: VoiceStream): unknown;
486
+ createOffer(): Promise<VoiceDescription>;
487
+ createAnswer(): Promise<VoiceDescription>;
488
+ setLocalDescription(description: VoiceDescription): Promise<void>;
489
+ setRemoteDescription(description: VoiceDescription): Promise<void>;
490
+ addIceCandidate(candidate: VoiceCandidate): Promise<void>;
491
+ close(): void;
492
+ readonly remoteDescription: VoiceDescription | null;
493
+ onicecandidate: ((event: {
494
+ candidate: VoiceCandidate | null;
495
+ }) => void) | null;
496
+ ontrack: ((event: {
497
+ streams: readonly VoiceStream[];
498
+ }) => void) | null;
499
+ onconnectionstatechange: (() => void) | null;
500
+ readonly connectionState: string;
501
+ }
502
+ /**
503
+ * Platform binding for WebRTC. The browser default is built in; React
504
+ * Native supplies one backed by `react-native-webrtc`.
505
+ */
506
+ interface WebRtcAdapter {
507
+ createPeerConnection(iceServers: VoiceIceServer[]): VoicePeerConnection;
508
+ getUserMedia(): Promise<VoiceStream>;
509
+ /**
510
+ * Attach a remote stream to a playback sink. The browser adapter
511
+ * creates a hidden `<audio>` element; React Native returns the stream
512
+ * URL for an `<RTCView>`. Returning a disposer keeps the room from
513
+ * leaking sinks when a peer leaves.
514
+ */
515
+ playRemoteStream(peerId: string, stream: VoiceStream): () => void;
516
+ }
517
+ interface VoiceIceServer {
518
+ urls: string | string[];
519
+ username?: string;
520
+ credential?: string;
521
+ }
522
+ interface VoiceRoomOptions {
523
+ /**
524
+ * ICE servers for peer connections. Defaults to a public STUN server,
525
+ * which is enough when peers can reach each other directly — add a
526
+ * TURN server for participants behind symmetric NAT.
527
+ */
528
+ iceServers?: VoiceIceServer[];
529
+ /** Platform WebRTC binding. Defaults to the browser implementation. */
530
+ webrtc?: WebRtcAdapter;
531
+ /**
532
+ * Disable local speaking detection. On by default; turn it off if the
533
+ * host app drives the indicator itself.
534
+ */
535
+ detectSpeaking?: boolean;
536
+ }
537
+ /** An inbound ring, delivered on the user's own channel. */
538
+ interface IncomingCall {
539
+ callId: string;
540
+ conversationId: string;
541
+ callerUserId: string;
542
+ }
543
+ /** The far side answered; both parties should now join the room. */
544
+ interface CallAccepted {
545
+ callId: string;
546
+ conversationId: string;
547
+ /** Who accepted. */
548
+ userId: string;
549
+ }
550
+ /** The far side declined. */
551
+ interface CallDeclined {
552
+ callId: string;
553
+ conversationId: string;
554
+ userId: string;
555
+ }
556
+ /** The callee is already on another call. */
557
+ interface CallBusy {
558
+ callId: string;
559
+ conversationId: string;
560
+ /** Who is busy. */
561
+ userId: string;
562
+ }
563
+ /** The caller hung up before anyone answered. */
564
+ interface CallCancelled {
565
+ callId: string;
566
+ conversationId: string;
567
+ callerUserId: string;
568
+ }
569
+ /** Result of placing a call. */
570
+ interface OutgoingCall {
571
+ callId: string;
572
+ conversationId: string;
573
+ /** Everyone who was rung — the conversation's members, minus you. */
574
+ calleeUserIds: string[];
575
+ }
576
+
577
+ /**
578
+ * WhatsApp-style call invitations.
579
+ *
580
+ * {@link VoiceRoom} is room-shaped: you're only reachable once you've
581
+ * already joined. Ringing somebody who is sitting idle needs a channel
582
+ * they're always on, which is their own `user:<id>` topic — so that's
583
+ * where the invite half of a call lives.
584
+ *
585
+ * const call = await poolse.calls.invite(conversationId);
586
+ * // …callee's client fires onIncoming, shows a ring screen…
587
+ * poolse.calls.onAccepted(({ callId }) => {
588
+ * if (callId === call.callId) void room.join();
589
+ * });
590
+ *
591
+ * Media never touches this class. Once both sides have accepted they
592
+ * join the voice room and negotiate exactly as the Discord-style flow
593
+ * does.
594
+ *
595
+ * There is no ring timeout here on purpose: only the UI knows when it
596
+ * gave up, and it can call {@link cancel} at that point.
597
+ */
598
+
599
+ type Unsubscribe$2 = () => void;
600
+ declare class CallsResource {
601
+ /** Resolves the user channel lazily — it may not be joined yet. */
602
+ private readonly getChannel;
603
+ private readonly incoming;
604
+ private readonly accepted;
605
+ private readonly declined;
606
+ private readonly busy;
607
+ private readonly cancelled;
608
+ private bound;
609
+ constructor(getChannel: () => Channel);
610
+ /**
611
+ * Ring every other member of a conversation. Resolves once the server
612
+ * has fanned the invite out, with the minted call id and who was rung
613
+ * — not when anyone answers; that arrives via {@link onAccepted}.
614
+ */
615
+ invite(conversationId: string): Promise<OutgoingCall>;
616
+ /**
617
+ * Answer a ringing call. This only tells the caller you picked up —
618
+ * join the voice room yourself to actually connect audio.
619
+ */
620
+ accept(call: IncomingCall): Promise<void>;
621
+ /** Reject a ringing call without joining the room. */
622
+ decline(call: IncomingCall): Promise<void>;
623
+ /**
624
+ * Tell the caller you are already on another call.
625
+ *
626
+ * Distinct from {@link decline}: nobody chose anything, so clients
627
+ * send this automatically when a ring arrives mid-call. `useCalls`
628
+ * does it for you.
629
+ */
630
+ markBusy(call: IncomingCall): Promise<void>;
631
+ /** Withdraw an invite you placed — hung up before anyone answered. */
632
+ cancel(call: OutgoingCall): Promise<void>;
633
+ /** Somebody is ringing you. */
634
+ onIncoming(fn: (call: IncomingCall) => void): Unsubscribe$2;
635
+ /** Your outbound call was answered — join the room now. */
636
+ onAccepted(fn: (call: CallAccepted) => void): Unsubscribe$2;
637
+ /** Your outbound call was rejected. */
638
+ onDeclined(fn: (call: CallDeclined) => void): Unsubscribe$2;
639
+ /** The person you called is already on another call. */
640
+ onBusy(fn: (call: CallBusy) => void): Unsubscribe$2;
641
+ /** An inbound ring was withdrawn before you answered. */
642
+ onCancelled(fn: (call: CallCancelled) => void): Unsubscribe$2;
643
+ /**
644
+ * One Phoenix binding per event regardless of listener count; we fan
645
+ * out ourselves, matching how the conversation channels do it.
646
+ */
647
+ private bind;
648
+ private request;
649
+ }
650
+
651
+ /**
652
+ * A voice room bound to one conversation.
653
+ *
654
+ * Wraps poolse's `voice:conversation:<id>` channel and drives a WebRTC
655
+ * mesh over it: one peer connection per participant, negotiated with
656
+ * offer / answer / ICE relayed by the server.
657
+ *
658
+ * Two shapes are built on this:
659
+ *
660
+ * * Discord-style — call `join()` directly and everyone in the room
661
+ * hears each other.
662
+ * * WhatsApp-style — ring first via `poolse.calls`, then both sides
663
+ * `join()` once the callee accepts.
664
+ *
665
+ * A mesh costs each participant N-1 upstreams, which is fine for small
666
+ * rooms and wrong past roughly six concurrent speakers; that's where an
667
+ * SFU belongs.
668
+ */
669
+
670
+ type Unsubscribe$1 = () => void;
671
+ declare class VoiceRoom {
672
+ readonly conversationId: string;
673
+ private readonly socket;
674
+ private readonly webrtc;
675
+ private readonly iceServers;
676
+ private readonly detectSpeaking;
677
+ private channel;
678
+ private localStream;
679
+ private selfId;
680
+ private status;
681
+ private muted;
682
+ private readonly peers;
683
+ private readonly sinks;
684
+ /** Candidates that landed before their offer/answer did. */
685
+ private readonly pendingIce;
686
+ private readonly roster;
687
+ private speakingTimer;
688
+ private stopSpeakingDetection;
689
+ private readonly statusListeners;
690
+ private readonly rosterListeners;
691
+ private readonly errorListeners;
692
+ constructor(conversationId: string, socket: Socket, opts?: VoiceRoomOptions);
693
+ getStatus(): VoiceStatus;
694
+ isMuted(): boolean;
695
+ /** Everyone in the room, oldest join first. */
696
+ getParticipants(): VoiceParticipant[];
697
+ onStatus(fn: (status: VoiceStatus) => void): Unsubscribe$1;
698
+ onParticipants(fn: (participants: VoiceParticipant[]) => void): Unsubscribe$1;
699
+ onError(fn: (err: Error) => void): Unsubscribe$1;
700
+ /** Acquire the mic, join the channel, and start negotiating. */
701
+ join(): Promise<void>;
702
+ /** Announce departure, then drop every peer connection and the mic. */
703
+ leave(): void;
704
+ /** Mute or unmute the local mic. Returns the new muted state. */
705
+ setMuted(muted: boolean): boolean;
706
+ toggleMute(): boolean;
707
+ private bindChannel;
708
+ /**
709
+ * Glare control: both sides learn about each other simultaneously, so
710
+ * without a rule both would offer at once. The lexicographically lower
711
+ * user id offers and the higher answers — deterministic, no extra
712
+ * round trip.
713
+ */
714
+ private shouldOffer;
715
+ private startNegotiation;
716
+ private ensurePeer;
717
+ private handleSignal;
718
+ private flushIce;
719
+ /**
720
+ * Every signal body travels under `data` — the server's
721
+ * `validate_signal_data/1` rejects the push outright when that key is
722
+ * missing or empty, and a rejected signal is never relayed.
723
+ */
724
+ private sendSignal;
725
+ private startSpeakingDetection;
726
+ private closePeer;
727
+ private teardown;
728
+ private patchParticipant;
729
+ private setStatus;
730
+ private emitRoster;
731
+ private emitError;
732
+ }
733
+
438
734
  type Fetcher = PoolseConfig['getToken'];
439
735
  interface GetTokenOptions {
440
736
  /** Bypass the cache and force a fresh call to the consumer's `getToken`. */
@@ -564,7 +860,9 @@ declare class PoolseRealtime {
564
860
  private readonly wsUrl;
565
861
  private socket;
566
862
  private readonly conversations;
863
+ private readonly voiceRooms;
567
864
  private userChannel;
865
+ private callsResource;
568
866
  private status;
569
867
  private readonly statusListeners;
570
868
  constructor(config: ResolvedConfig, tokenCache: TokenCache, opts?: RealtimeOptions);
@@ -611,6 +909,25 @@ declare class PoolseRealtime {
611
909
  * matching the JWT can join — poolse's UserChannel enforces this.
612
910
  */
613
911
  user(userId: string): UserChannel;
912
+ /**
913
+ * Voice room for a conversation — the Discord-style surface. Call
914
+ * `join()` on the returned handle to acquire the mic and connect;
915
+ * reusing the same id returns the same room rather than opening a
916
+ * second one.
917
+ *
918
+ * Ringing somebody who hasn't joined is a separate concern; see
919
+ * `poolse.calls`.
920
+ */
921
+ voice(conversationId: string, opts?: VoiceRoomOptions): VoiceRoom;
922
+ /**
923
+ * Call invitations for a user — the WhatsApp-style surface. Rides the
924
+ * `user:<id>` topic, the one channel a client is always joined to, so
925
+ * a ring reaches somebody who hasn't opened a voice room yet.
926
+ *
927
+ * Takes the user id explicitly, mirroring `user(userId)`; the SDK
928
+ * never assumes whose token it is holding.
929
+ */
930
+ calls(userId: string): CallsResource;
614
931
  /** Drop a conversation handle and leave the channel. */
615
932
  leave(conversationId: string): void;
616
933
  private setStatus;
@@ -659,6 +976,13 @@ declare class UserChannel {
659
976
  private conversationCreatedBound;
660
977
  private conversationUpdatedBound;
661
978
  constructor(userId: string, channel: Channel);
979
+ /**
980
+ * The underlying Phoenix channel, for surfaces that push their own
981
+ * events on this topic (the calls resource does).
982
+ *
983
+ * @internal
984
+ */
985
+ _channel(): Channel;
662
986
  onMention(fn: (evt: MentionEvent) => void): Unsubscribe;
663
987
  /**
664
988
  * Subscribe to "you've been added to a conversation" notifications.
@@ -1066,8 +1390,18 @@ declare class AuthError extends ApiError {
1066
1390
  constructor(envelope: ErrorEnvelope['error']);
1067
1391
  }
1068
1392
 
1069
- declare const version = "2.0.10";
1393
+ /**
1394
+ * Browser WebRTC binding. Used automatically when no adapter is passed
1395
+ * to {@link VoiceRoom}; React Native supplies its own via
1396
+ * `@poolse/react-native`.
1397
+ */
1398
+
1399
+ /** True when this runtime can actually negotiate WebRTC. */
1400
+ declare function isWebRtcAvailable(): boolean;
1401
+ declare function createBrowserWebRtcAdapter(): WebRtcAdapter;
1402
+
1403
+ declare const version = "2.2.0";
1070
1404
 
1071
1405
  declare function safeUuid(): string;
1072
1406
 
1073
- export { type AddMemberOptions, ApiError, type Attachment, type AttachmentDownloadResponse, AttachmentHandle, type AttachmentOptions, type AttachmentProgressEvent, type AttachmentStatus, type AttachmentUploadInput, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsResource, AuthError, type Conversation, ConversationChannel, type ConversationCreateRequest, type ConversationCreatedEvent, ConversationHandle, type ConversationList, ConversationMessages, type ConversationType, type ConversationUpdateRequest, type ConversationUpdatedEvent, ConversationsResource, type ErrorEnvelope, type IsoDateTime, type Me, MeResource, type MemberReadEvent, type MemberRole, type Membership, type MembershipCreateRequest, type MembershipList, type MentionEvent, type Message, type MessageCreateRequest, type MessageDeletedEvent, MessageHandle, type MessageList, type MessageNewEvent, type MessageType, type MessageUpdateRequest, type MessageUpdatedEvent, MessagesResource, NetworkError, POOLSE_API_URL, Poolse, type PoolseConfig, PoolseError, PoolseRealtime, type PoolseUserProfile, type PresenceSnapshot, type QuotedMessagePreview, RateLimitedError, type ReactionEvent, type ReactionRequest, type ReadRequest, type RealtimeStatus, type TypingEvent, type Unsubscribe, UserChannel, UsersResource, type Uuid, safeUuid, version };
1407
+ export { type AddMemberOptions, ApiError, type Attachment, type AttachmentDownloadResponse, AttachmentHandle, type AttachmentOptions, type AttachmentProgressEvent, type AttachmentStatus, type AttachmentUploadInput, type AttachmentUploadRequest, type AttachmentUploadResponse, AttachmentsResource, AuthError, type CallAccepted, type CallBusy, type CallCancelled, type CallDeclined, CallsResource, type Conversation, ConversationChannel, type ConversationCreateRequest, type ConversationCreatedEvent, ConversationHandle, type ConversationList, ConversationMessages, type ConversationType, type ConversationUpdateRequest, type ConversationUpdatedEvent, ConversationsResource, type ErrorEnvelope, type IncomingCall, type IsoDateTime, type Me, MeResource, type MemberReadEvent, type MemberRole, type Membership, type MembershipCreateRequest, type MembershipList, type MentionEvent, type Message, type MessageCreateRequest, type MessageDeletedEvent, MessageHandle, type MessageList, type MessageNewEvent, type MessageType, type MessageUpdateRequest, type MessageUpdatedEvent, MessagesResource, NetworkError, type OutgoingCall, POOLSE_API_URL, Poolse, type PoolseConfig, PoolseError, PoolseRealtime, type PoolseUserProfile, type PresenceSnapshot, type QuotedMessagePreview, RateLimitedError, type ReactionEvent, type ReactionRequest, type ReadRequest, type RealtimeStatus, type TypingEvent, type Unsubscribe, UserChannel, UsersResource, type Uuid, type VoiceCandidate, type VoiceDescription, type VoiceIceServer, type VoiceParticipant, type VoicePeerConnection, VoiceRoom, type VoiceRoomOptions, type VoiceStatus, type VoiceStream, type VoiceTrack, type WebRtcAdapter, createBrowserWebRtcAdapter, isWebRtcAvailable, safeUuid, version };