sip-connector 17.0.0 → 18.0.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.
Files changed (29) hide show
  1. package/dist/@SipConnector-CFYT0HQB.cjs +1 -0
  2. package/dist/{@SipConnector-DADbRZIb.js → @SipConnector-UTHCoMXw.js} +882 -896
  3. package/dist/ApiManager/__tests-utils__/helpers.d.ts +2 -4
  4. package/dist/ApiManager/constants.d.ts +1 -2
  5. package/dist/ApiManager/eventNames.d.ts +1 -2
  6. package/dist/CallManager/@CallManager.d.ts +6 -7
  7. package/dist/CallManager/AbstractCallStrategy.d.ts +2 -6
  8. package/dist/CallManager/MCUCallStrategy.d.ts +1 -9
  9. package/dist/CallManager/eventNames.d.ts +42 -2
  10. package/dist/CallManager/index.d.ts +3 -3
  11. package/dist/CallManager/types.d.ts +1 -13
  12. package/dist/SipConnector/@SipConnector.d.ts +4 -2
  13. package/dist/SipConnector/eventNames.d.ts +1 -1
  14. package/dist/SipConnectorFacade/index.d.ts +1 -1
  15. package/dist/StatsPeerConnection/index.d.ts +1 -1
  16. package/dist/{CallManager/TransceiverManager.d.ts → TransceiverManager/@TransceiverManager.d.ts} +19 -0
  17. package/dist/TransceiverManager/index.d.ts +1 -0
  18. package/dist/TransceiverManager/types.d.ts +11 -0
  19. package/dist/VideoSendingBalancer/index.d.ts +1 -1
  20. package/dist/__fixtures__/eventNames.d.ts +1 -1
  21. package/dist/doMock.cjs +1 -1
  22. package/dist/doMock.js +1 -1
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.js +83 -83
  25. package/package.json +9 -9
  26. package/dist/@SipConnector-aB66gnC6.cjs +0 -1
  27. /package/dist/SipConnectorFacade/{SipConnectorFacade.d.ts → @SipConnectorFacade.d.ts} +0 -0
  28. /package/dist/StatsPeerConnection/{StatsPeerConnection.d.ts → @StatsPeerConnection.d.ts} +0 -0
  29. /package/dist/VideoSendingBalancer/{VideoSendingBalancer.d.ts → @VideoSendingBalancer.d.ts} +0 -0
@@ -1,9 +1,7 @@
1
+ import { IncomingInfoEvent, OutgoingInfoEvent } from '@krivega/jssip';
1
2
  export declare class MockRequest {
2
3
  private headers;
3
- static createInfoEvent(originator: string, request: MockRequest): {
4
- readonly originator: string;
5
- readonly request: MockRequest;
6
- };
4
+ static createInfoEvent(originator: 'local' | 'remote', request: MockRequest): IncomingInfoEvent | OutgoingInfoEvent;
7
5
  setHeader(name: string, value: string): void;
8
6
  getHeader(name: string): string | undefined;
9
7
  }
@@ -35,8 +35,7 @@ export declare enum EShareState {
35
35
  }
36
36
  export declare enum EParticipantType {
37
37
  SPECTATOR = "SPECTATOR",
38
- PARTICIPANT = "PARTICIPANT",
39
- SPECTATOR_OVER_SFU = "SPECTATOROVERSFU"
38
+ PARTICIPANT = "PARTICIPANT"
40
39
  }
41
40
  export declare enum EContentTypeReceived {
42
41
  ENTER_ROOM = "application/vinteo.webrtc.roomname",
@@ -6,7 +6,6 @@ export declare enum EEvent {
6
6
  PARTICIPANT_MOVE_REQUEST_TO_STREAM = "participant:move-request-to-stream",
7
7
  PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS = "participant:move-request-to-spectators",
8
8
  PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS = "participant:move-request-to-participants",
9
- PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS_OVER_SFU = "participant:move-request-to-spectators-over-sfu",
10
9
  PARTICIPATION_ACCEPTING_WORD_REQUEST = "participation:accepting-word-request",
11
10
  PARTICIPATION_CANCELLING_WORD_REQUEST = "participation:cancelling-word-request",
12
11
  WEBCAST_STARTED = "webcast:started",
@@ -30,6 +29,6 @@ export declare enum EEvent {
30
29
  NEW_DTMF = "newDTMF",
31
30
  RESTART = "restart"
32
31
  }
33
- export declare const EVENT_NAMES: readonly ["participation:accepting-word-request", "participation:cancelling-word-request", "participant:move-request-to-stream", "channels:notify", "conference:participant-token-issued", "account:changed", "account:deleted", "webcast:started", "webcast:stopped", "participant:added-to-list-moderators", "participant:removed-from-list-moderators", "participant:move-request-to-spectators", "participant:move-request-to-participants", "participant:move-request-to-spectators-over-sfu", "channels", "enterRoom", "shareState", "main-cam-control", "useLicense", "admin-start-main-cam", "admin-stop-main-cam", "admin-start-mic", "admin-stop-mic", "admin-force-sync-media-state", "availableSecondRemoteStream", "notAvailableSecondRemoteStream", "mustStopPresentation", "newDTMF", "restart"];
32
+ export declare const EVENT_NAMES: readonly ["participation:accepting-word-request", "participation:cancelling-word-request", "participant:move-request-to-stream", "channels:notify", "conference:participant-token-issued", "account:changed", "account:deleted", "webcast:started", "webcast:stopped", "participant:added-to-list-moderators", "participant:removed-from-list-moderators", "participant:move-request-to-spectators", "participant:move-request-to-participants", "channels", "enterRoom", "shareState", "main-cam-control", "useLicense", "admin-start-main-cam", "admin-stop-main-cam", "admin-start-mic", "admin-stop-mic", "admin-force-sync-media-state", "availableSecondRemoteStream", "notAvailableSecondRemoteStream", "mustStopPresentation", "newDTMF", "restart"];
34
33
  export type TEvent = (typeof EVENT_NAMES)[number];
35
34
  export type TEvents = Events<typeof EVENT_NAMES>;
@@ -1,5 +1,5 @@
1
1
  import { RTCSession } from '@krivega/jssip';
2
- import { TEvent, TEvents } from './eventNames';
2
+ import { TEvents, TEventMap } from './eventNames';
3
3
  import { ICallStrategy } from './types';
4
4
  declare class CallManager {
5
5
  readonly events: TEvents;
@@ -9,11 +9,11 @@ declare class CallManager {
9
9
  get connection(): RTCPeerConnection | undefined;
10
10
  get establishedRTCSession(): RTCSession | undefined;
11
11
  get isCallActive(): ICallStrategy['isCallActive'];
12
- on<T>(eventName: TEvent, handler: (data: T) => void): () => void;
13
- once<T>(eventName: TEvent, handler: (data: T) => void): () => void;
14
- onceRace<T>(eventNames: TEvent[], handler: (data: T, eventName: string) => void): () => void;
15
- wait<T>(eventName: TEvent): Promise<T>;
16
- off<T>(eventName: TEvent, handler: (data: T) => void): void;
12
+ on<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): () => void;
13
+ once<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): () => void;
14
+ onceRace<T extends keyof TEventMap>(eventNames: T[], handler: (data: TEventMap[T], eventName: string) => void): () => void;
15
+ wait<T extends keyof TEventMap>(eventName: T): Promise<TEventMap[T]>;
16
+ off<T extends keyof TEventMap>(eventName: T, handler: (data: TEventMap[T]) => void): void;
17
17
  setStrategy(strategy: ICallStrategy): void;
18
18
  startCall: ICallStrategy['startCall'];
19
19
  endCall: ICallStrategy['endCall'];
@@ -21,7 +21,6 @@ declare class CallManager {
21
21
  getEstablishedRTCSession: ICallStrategy['getEstablishedRTCSession'];
22
22
  getCallConfiguration: ICallStrategy['getCallConfiguration'];
23
23
  getRemoteStreams: ICallStrategy['getRemoteStreams'];
24
- getTransceivers: ICallStrategy['getTransceivers'];
25
24
  addTransceiver: ICallStrategy['addTransceiver'];
26
25
  replaceMediaStream: ICallStrategy['replaceMediaStream'];
27
26
  restartIce: ICallStrategy['restartIce'];
@@ -1,6 +1,6 @@
1
1
  import { RTCSession } from '@krivega/jssip';
2
2
  import { TEvents } from './eventNames';
3
- import { ICallStrategy, ITransceiverStorage, TCallConfiguration, TOntrack } from './types';
3
+ import { ICallStrategy, TCallConfiguration, TOntrack } from './types';
4
4
  export declare abstract class AbstractCallStrategy implements ICallStrategy {
5
5
  protected isPendingCall: boolean;
6
6
  protected isPendingAnswer: boolean;
@@ -16,7 +16,7 @@ export declare abstract class AbstractCallStrategy implements ICallStrategy {
16
16
  /**
17
17
  * Запуск исходящего звонка
18
18
  */
19
- abstract startCall(params: Parameters<ICallStrategy['startCall']>[0], ua: Parameters<ICallStrategy['startCall']>[1], getSipServerUrl: Parameters<ICallStrategy['startCall']>[2]): Promise<RTCPeerConnection>;
19
+ abstract startCall(ua: Parameters<ICallStrategy['startCall']>[0], getSipServerUrl: Parameters<ICallStrategy['startCall']>[1], params: Parameters<ICallStrategy['startCall']>[2]): Promise<RTCPeerConnection>;
20
20
  /**
21
21
  * Завершение звонка
22
22
  */
@@ -38,10 +38,6 @@ export declare abstract class AbstractCallStrategy implements ICallStrategy {
38
38
  * Получение удаленных медиа-потоков
39
39
  */
40
40
  abstract getRemoteStreams(): MediaStream[] | undefined;
41
- /**
42
- * Получение сохраненных transceiver'ов
43
- */
44
- abstract getTransceivers(): Readonly<ITransceiverStorage>;
45
41
  /**
46
42
  * Добавление нового transceiver'а
47
43
  */
@@ -1,14 +1,10 @@
1
1
  import { AbstractCallStrategy } from './AbstractCallStrategy';
2
2
  import { RTCSession } from '@krivega/jssip';
3
3
  import { TEvents } from './eventNames';
4
- import { ICallStrategy, ITransceiverStorage, TOntrack } from './types';
4
+ import { ICallStrategy, TOntrack } from './types';
5
5
  export declare class MCUCallStrategy extends AbstractCallStrategy {
6
6
  private readonly remoteStreamsManager;
7
7
  private readonly disposers;
8
- /**
9
- * Менеджер для управления transceiver'ами
10
- */
11
- private readonly transceiverManager;
12
8
  constructor(events: TEvents);
13
9
  get requested(): boolean;
14
10
  get connection(): RTCPeerConnection | undefined;
@@ -32,10 +28,6 @@ export declare class MCUCallStrategy extends AbstractCallStrategy {
32
28
  degradationPreference?: RTCDegradationPreference;
33
29
  }): Promise<boolean>;
34
30
  addTransceiver(kind: 'audio' | 'video', options?: RTCRtpTransceiverInit): Promise<RTCRtpTransceiver>;
35
- /**
36
- * Возвращает сохраненные transceiver'ы
37
- */
38
- getTransceivers(): Readonly<ITransceiverStorage>;
39
31
  protected readonly handleCall: ({ ontrack, }: {
40
32
  ontrack?: TOntrack;
41
33
  }) => Promise<RTCPeerConnection>;
@@ -1,4 +1,5 @@
1
- import { Events } from 'events-constructor';
1
+ import { IncomingInfoEvent, OutgoingInfoEvent, EndEvent } from '@krivega/jssip';
2
+ import { TypedEvents } from 'events-constructor';
2
3
  export declare enum EEvent {
3
4
  PEER_CONNECTION = "peerconnection",
4
5
  CONNECTING = "connecting",
@@ -41,5 +42,44 @@ export declare enum Originator {
41
42
  }
42
43
  export declare const SESSION_JSSIP_EVENT_NAMES: readonly ["peerconnection", "connecting", "sending", "progress", "accepted", "confirmed", "ended", "failed", "newInfo", "newDTMF", "presentation:start", "presentation:started", "presentation:end", "presentation:ended", "presentation:failed", "reinvite", "update", "refer", "replaces", "sdp", "icecandidate", "getusermediafailed", "peerconnection:createofferfailed", "peerconnection:createanswerfailed", "peerconnection:setlocaldescriptionfailed", "peerconnection:setremotedescriptionfailed"];
43
44
  export declare const EVENT_NAMES: readonly ["peerconnection", "connecting", "sending", "progress", "accepted", "confirmed", "ended", "failed", "newInfo", "newDTMF", "presentation:start", "presentation:started", "presentation:end", "presentation:ended", "presentation:failed", "reinvite", "update", "refer", "replaces", "sdp", "icecandidate", "getusermediafailed", "peerconnection:createofferfailed", "peerconnection:createanswerfailed", "peerconnection:setlocaldescriptionfailed", "peerconnection:setremotedescriptionfailed", "peerconnection:confirmed", "peerconnection:ontrack", "ended:fromserver"];
44
- export type TEvents = Events<typeof EVENT_NAMES>;
45
45
  export type TEvent = (typeof EVENT_NAMES)[number];
46
+ export type TEventMap = {
47
+ peerconnection: {
48
+ peerconnection: RTCPeerConnection;
49
+ };
50
+ connecting: unknown;
51
+ sending: unknown;
52
+ progress: unknown;
53
+ accepted: unknown;
54
+ confirmed: unknown;
55
+ ended: EndEvent;
56
+ failed: EndEvent;
57
+ newDTMF: {
58
+ originator: `${Originator}`;
59
+ };
60
+ newInfo: IncomingInfoEvent | OutgoingInfoEvent;
61
+ hold: unknown;
62
+ unhold: unknown;
63
+ muted: unknown;
64
+ unmuted: unknown;
65
+ reinvite: unknown;
66
+ update: unknown;
67
+ refer: unknown;
68
+ replaces: unknown;
69
+ sdp: unknown;
70
+ icecandidate: unknown;
71
+ getusermediafailed: unknown;
72
+ 'peerconnection:createofferfailed': unknown;
73
+ 'peerconnection:createanswerfailed': unknown;
74
+ 'peerconnection:setlocaldescriptionfailed': unknown;
75
+ 'peerconnection:setremotedescriptionfailed': unknown;
76
+ 'presentation:start': MediaStream;
77
+ 'presentation:started': MediaStream;
78
+ 'presentation:end': MediaStream;
79
+ 'presentation:ended': MediaStream;
80
+ 'presentation:failed': Error;
81
+ 'peerconnection:confirmed': RTCPeerConnection;
82
+ 'peerconnection:ontrack': RTCTrackEvent;
83
+ 'ended:fromserver': EndEvent;
84
+ };
85
+ export type TEvents = TypedEvents<TEventMap>;
@@ -1,8 +1,8 @@
1
1
  export { default as CallManager } from './@CallManager';
2
2
  export { ECallCause } from './causes';
3
- export { EEvent as ECallEvent, Originator } from './eventNames';
3
+ export type { TEventMap } from './eventNames';
4
+ export { EEvent as ECallEvent } from './eventNames';
4
5
  export type { TEvent as TCallEvent, TEvents as TCallEvents } from './eventNames';
5
6
  export { default as hasCanceledCallError } from './hasCanceledCallError';
6
7
  export { MCUCallStrategy } from './MCUCallStrategy';
7
- export { TransceiverManager } from './TransceiverManager';
8
- export type { TCustomError, TGetServerUrl, ITransceiverStorage } from './types';
8
+ export type { TCustomError, TGetServerUrl } from './types';
@@ -25,7 +25,7 @@ export type TParamsCall = TParamsAnswerToIncomingCall & {
25
25
  number: string;
26
26
  };
27
27
  export type TCustomError = Error & {
28
- originator?: Originator;
28
+ originator?: `${Originator}`;
29
29
  cause?: unknown;
30
30
  message: unknown;
31
31
  _ws?: unknown;
@@ -33,17 +33,6 @@ export type TCustomError = Error & {
33
33
  url?: string;
34
34
  code?: string;
35
35
  };
36
- /**
37
- * Интерфейс для хранения основных transceiver'ов
38
- */
39
- export interface ITransceiverStorage {
40
- /** Основной transceiver для видео */
41
- mainVideo?: RTCRtpTransceiver;
42
- /** Основной transceiver для аудио */
43
- mainAudio?: RTCRtpTransceiver;
44
- /** Transceiver для презентации видео */
45
- presentationVideo?: RTCRtpTransceiver;
46
- }
47
36
  export type TCallConfiguration = {
48
37
  answer?: boolean;
49
38
  number?: string;
@@ -59,7 +48,6 @@ export interface ICallStrategy {
59
48
  getEstablishedRTCSession: () => RTCSession | undefined;
60
49
  getCallConfiguration: () => TCallConfiguration;
61
50
  getRemoteStreams: () => MediaStream[] | undefined;
62
- getTransceivers: () => Readonly<ITransceiverStorage>;
63
51
  addTransceiver: (kind: 'audio' | 'video', options?: RTCRtpTransceiverInit) => Promise<RTCRtpTransceiver>;
64
52
  replaceMediaStream: (mediaStream: MediaStream, options?: {
65
53
  deleteExisting?: boolean;
@@ -6,6 +6,7 @@ import { ConnectionQueueManager } from '../ConnectionQueueManager';
6
6
  import { IncomingCallManager } from '../IncomingCallManager';
7
7
  import { PresentationManager, TContentHint, TOnAddedTransceiver } from '../PresentationManager';
8
8
  import { StatsManager } from '../StatsManager';
9
+ import { TransceiverManager } from '../TransceiverManager';
9
10
  import { VideoSendingBalancerManager } from '../VideoSendingBalancerManager';
10
11
  import { EVENT_NAMES, TEvent } from './eventNames';
11
12
  import { TGetServerUrl } from '../CallManager';
@@ -21,6 +22,7 @@ declare class SipConnector {
21
22
  readonly presentationManager: PresentationManager;
22
23
  readonly statsManager: StatsManager;
23
24
  readonly videoSendingBalancerManager: VideoSendingBalancerManager;
25
+ readonly transceiverManager: TransceiverManager;
24
26
  private readonly preferredMimeTypesVideoCodecs?;
25
27
  private readonly excludeMimeTypesVideoCodecs?;
26
28
  constructor({ JsSIP }: {
@@ -106,7 +108,7 @@ declare class SipConnector {
106
108
  askPermissionToEnableCam(...args: Parameters<ApiManager['askPermissionToEnableCam']>): Promise<void>;
107
109
  private setCodecPreferences;
108
110
  private subscribe;
109
- private readonly handleRestart;
110
- private readonly updateTransceivers;
111
+ private readonly bridgeEvents;
112
+ private readonly resolveHandleAddTransceiver;
111
113
  }
112
114
  export default SipConnector;
@@ -1,4 +1,4 @@
1
1
  import { Events } from 'events-constructor';
2
- export declare const EVENT_NAMES: readonly ("connection:connecting" | "connection:connected" | "connection:disconnected" | "connection:newRTCSession" | "connection:registered" | "connection:unregistered" | "connection:registrationFailed" | "connection:newMessage" | "connection:sipEvent" | "call:peerconnection" | "call:connecting" | "call:sending" | "call:progress" | "call:accepted" | "call:confirmed" | "call:ended" | "call:failed" | "call:newDTMF" | "call:newInfo" | "call:reinvite" | "call:update" | "call:refer" | "call:replaces" | "call:sdp" | "call:icecandidate" | "call:getusermediafailed" | "call:peerconnection:createofferfailed" | "call:peerconnection:createanswerfailed" | "call:peerconnection:setlocaldescriptionfailed" | "call:peerconnection:setremotedescriptionfailed" | "call:presentation:start" | "call:presentation:started" | "call:presentation:end" | "call:presentation:ended" | "call:presentation:failed" | "call:peerconnection:confirmed" | "call:peerconnection:ontrack" | "call:ended:fromserver" | "api:newDTMF" | "api:channels:notify" | "api:participant:added-to-list-moderators" | "api:participant:removed-from-list-moderators" | "api:participant:move-request-to-stream" | "api:participant:move-request-to-spectators" | "api:participant:move-request-to-participants" | "api:participant:move-request-to-spectators-over-sfu" | "api:participation:accepting-word-request" | "api:participation:cancelling-word-request" | "api:webcast:started" | "api:webcast:stopped" | "api:account:changed" | "api:account:deleted" | "api:conference:participant-token-issued" | "api:channels" | "api:enterRoom" | "api:shareState" | "api:main-cam-control" | "api:useLicense" | "api:admin-start-main-cam" | "api:admin-stop-main-cam" | "api:admin-start-mic" | "api:admin-stop-mic" | "api:admin-force-sync-media-state" | "api:availableSecondRemoteStream" | "api:notAvailableSecondRemoteStream" | "api:mustStopPresentation" | "api:restart" | "incoming-call:incomingCall" | "incoming-call:declinedIncomingCall" | "incoming-call:terminatedIncomingCall" | "incoming-call:failedIncomingCall" | "presentation:presentation:start" | "presentation:presentation:started" | "presentation:presentation:end" | "presentation:presentation:ended" | "presentation:presentation:failed" | "stats:collected" | "video-balancer:balancing-scheduled" | "video-balancer:balancing-started" | "video-balancer:balancing-stopped" | "video-balancer:parameters-updated")[];
2
+ export declare const EVENT_NAMES: readonly ("connection:connecting" | "connection:connected" | "connection:disconnected" | "connection:newRTCSession" | "connection:registered" | "connection:unregistered" | "connection:registrationFailed" | "connection:newMessage" | "connection:sipEvent" | "call:newDTMF" | "call:peerconnection" | "call:connecting" | "call:sending" | "call:progress" | "call:accepted" | "call:confirmed" | "call:ended" | "call:failed" | "call:newInfo" | "call:reinvite" | "call:update" | "call:refer" | "call:replaces" | "call:sdp" | "call:icecandidate" | "call:getusermediafailed" | "call:peerconnection:createofferfailed" | "call:peerconnection:createanswerfailed" | "call:peerconnection:setlocaldescriptionfailed" | "call:peerconnection:setremotedescriptionfailed" | "call:presentation:start" | "call:presentation:started" | "call:presentation:end" | "call:presentation:ended" | "call:presentation:failed" | "call:peerconnection:confirmed" | "call:peerconnection:ontrack" | "call:ended:fromserver" | "api:channels:notify" | "api:participant:added-to-list-moderators" | "api:participant:removed-from-list-moderators" | "api:participant:move-request-to-stream" | "api:participant:move-request-to-spectators" | "api:participant:move-request-to-participants" | "api:participation:accepting-word-request" | "api:participation:cancelling-word-request" | "api:webcast:started" | "api:webcast:stopped" | "api:account:changed" | "api:account:deleted" | "api:conference:participant-token-issued" | "api:channels" | "api:enterRoom" | "api:shareState" | "api:main-cam-control" | "api:useLicense" | "api:admin-start-main-cam" | "api:admin-stop-main-cam" | "api:admin-start-mic" | "api:admin-stop-mic" | "api:admin-force-sync-media-state" | "api:availableSecondRemoteStream" | "api:notAvailableSecondRemoteStream" | "api:mustStopPresentation" | "api:newDTMF" | "api:restart" | "incoming-call:incomingCall" | "incoming-call:declinedIncomingCall" | "incoming-call:terminatedIncomingCall" | "incoming-call:failedIncomingCall" | "presentation:presentation:start" | "presentation:presentation:started" | "presentation:presentation:end" | "presentation:presentation:ended" | "presentation:presentation:failed" | "stats:collected" | "video-balancer:balancing-scheduled" | "video-balancer:balancing-started" | "video-balancer:balancing-stopped" | "video-balancer:parameters-updated")[];
3
3
  export type TEvent = (typeof EVENT_NAMES)[number];
4
4
  export type TEvents = Events<typeof EVENT_NAMES>;
@@ -1 +1 @@
1
- export { default as SipConnectorFacade } from './SipConnectorFacade';
1
+ export { default as SipConnectorFacade } from './@SipConnectorFacade';
@@ -1,5 +1,5 @@
1
1
  export { EStatsTypes } from './constants';
2
2
  export type { TEventMap } from './eventNames';
3
- export { default as StatsPeerConnection } from './StatsPeerConnection';
3
+ export { default as StatsPeerConnection } from './@StatsPeerConnection';
4
4
  export type { TInboundStats, TOutboundStats } from './types';
5
5
  export { default as hasAvailableStats } from './utils/hasAvailableStats';
@@ -1,3 +1,5 @@
1
+ import { ApiManager, TRestartData } from '../ApiManager';
2
+ import { CallManager } from '../CallManager';
1
3
  import { ITransceiverStorage } from './types';
2
4
  /**
3
5
  * Менеджер для управления RTCRtpTransceiver'ами
@@ -11,6 +13,12 @@ export declare class TransceiverManager {
11
13
  * Хранилище основных transceiver'ов
12
14
  */
13
15
  private readonly transceivers;
16
+ private readonly callManager;
17
+ private readonly apiManager;
18
+ constructor({ callManager, apiManager, }: {
19
+ callManager: CallManager;
20
+ apiManager: ApiManager;
21
+ });
14
22
  /**
15
23
  * Сохраняет transceiver в соответствующем хранилище в зависимости от типа трека и mid
16
24
  */
@@ -47,5 +55,16 @@ export declare class TransceiverManager {
47
55
  * Проверяет, пустое ли хранилище
48
56
  */
49
57
  isEmpty(): boolean;
58
+ /**
59
+ * Обрабатывает событие restart от ApiManager
60
+ */
61
+ readonly handleRestart: (restartData: TRestartData) => void;
62
+ /**
63
+ * Обновляет transceiver'ы в соответствии с данными restart
64
+ */
65
+ private readonly updateTransceivers;
66
+ private subscribe;
67
+ private readonly handleTrack;
68
+ private readonly handleEnded;
50
69
  }
51
70
  export default TransceiverManager;
@@ -0,0 +1 @@
1
+ export { default as TransceiverManager } from './@TransceiverManager';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Интерфейс для хранения основных transceiver'ов
3
+ */
4
+ export interface ITransceiverStorage {
5
+ /** Основной transceiver для видео */
6
+ mainVideo?: RTCRtpTransceiver;
7
+ /** Основной transceiver для аудио */
8
+ mainAudio?: RTCRtpTransceiver;
9
+ /** Transceiver для презентации видео */
10
+ presentationVideo?: RTCRtpTransceiver;
11
+ }
@@ -1,2 +1,2 @@
1
1
  export type { IBalancerOptions } from './types';
2
- export { resolveVideoSendingBalancer, default as VideoSendingBalancer, } from './VideoSendingBalancer';
2
+ export { resolveVideoSendingBalancer, default as VideoSendingBalancer, } from './@VideoSendingBalancer';
@@ -2,7 +2,7 @@ export declare const UA_SYNTHETICS_EVENT_NAMES: readonly ["incomingCall", "decli
2
2
  export declare const UA_JSSIP_EVENT_NAMES: readonly ["connecting", "connected", "disconnected", "newRTCSession", "registered", "unregistered", "registrationFailed", "newMessage", "sipEvent"];
3
3
  export declare const SESSION_SYNTHETICS_EVENT_NAMES: readonly ["availableSecondRemoteStream", "notAvailableSecondRemoteStream", "mustStopPresentation", "shareState", "enterRoom", "useLicense", "peerconnection:confirmed", "peerconnection:ontrack", "channels", "ended:fromserver", "main-cam-control", "admin-start-main-cam", "admin-stop-main-cam", "admin-stop-mic", "admin-start-mic", "admin-force-sync-media-state", "participant:move-request-to-spectators", "participant:move-request-to-participants"];
4
4
  export declare const SESSION_JSSIP_EVENT_NAMES: readonly ["ended", "connecting", "sending", "reinvite", "replaces", "refer", "progress", "accepted", "confirmed", "peerconnection", "failed", "muted", "unmuted", "newDTMF", "newInfo", "hold", "unhold", "update", "sdp", "icecandidate", "getusermediafailed", "peerconnection:createofferfailed", "peerconnection:createanswerfailed", "peerconnection:setlocaldescriptionfailed", "peerconnection:setremotedescriptionfailed", "presentation:start", "presentation:started", "presentation:end", "presentation:ended", "presentation:failed"];
5
- export declare const UA_EVENT_NAMES: ("connecting" | "channels:notify" | "participant:added-to-list-moderators" | "participant:removed-from-list-moderators" | "participant:move-request-to-stream" | "participation:accepting-word-request" | "participation:cancelling-word-request" | "webcast:started" | "webcast:stopped" | "account:changed" | "account:deleted" | "conference:participant-token-issued" | "connected" | "disconnected" | "newRTCSession" | "registered" | "unregistered" | "registrationFailed" | "newMessage" | "sipEvent" | "incomingCall" | "declinedIncomingCall" | "terminatedIncomingCall" | "failedIncomingCall")[];
5
+ export declare const UA_EVENT_NAMES: ("channels:notify" | "participant:added-to-list-moderators" | "participant:removed-from-list-moderators" | "participant:move-request-to-stream" | "participation:accepting-word-request" | "participation:cancelling-word-request" | "webcast:started" | "webcast:stopped" | "account:changed" | "account:deleted" | "conference:participant-token-issued" | "connecting" | "connected" | "disconnected" | "newRTCSession" | "registered" | "unregistered" | "registrationFailed" | "newMessage" | "sipEvent" | "incomingCall" | "declinedIncomingCall" | "terminatedIncomingCall" | "failedIncomingCall")[];
6
6
  export declare const SESSION_EVENT_NAMES: readonly ["ended", "connecting", "sending", "reinvite", "replaces", "refer", "progress", "accepted", "confirmed", "peerconnection", "failed", "muted", "unmuted", "newDTMF", "newInfo", "hold", "unhold", "update", "sdp", "icecandidate", "getusermediafailed", "peerconnection:createofferfailed", "peerconnection:createanswerfailed", "peerconnection:setlocaldescriptionfailed", "peerconnection:setremotedescriptionfailed", "presentation:start", "presentation:started", "presentation:end", "presentation:ended", "presentation:failed", "availableSecondRemoteStream", "notAvailableSecondRemoteStream", "mustStopPresentation", "shareState", "enterRoom", "useLicense", "peerconnection:confirmed", "peerconnection:ontrack", "channels", "ended:fromserver", "main-cam-control", "admin-start-main-cam", "admin-stop-main-cam", "admin-stop-mic", "admin-start-mic", "admin-force-sync-media-state", "participant:move-request-to-spectators", "participant:move-request-to-participants"];
7
7
  export type TEventUA = (typeof UA_EVENT_NAMES)[number];
8
8
  export type TEventSession = (typeof SESSION_EVENT_NAMES)[number];
package/dist/doMock.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),H=require("@krivega/jssip/lib/URI"),q=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),D=require("./@SipConnector-aB66gnC6.cjs");class w extends q.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const G="incomingCall",x="declinedIncomingCall",z="failedIncomingCall",j="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",he="ended:fromserver",Ee="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",we="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ce="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",He="unmuted",qe="newDTMF",Ge="newInfo",xe="hold",ze="unhold",je="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[G,x,j,z,Ne,Ce,Ie,de,Oe,Ae,Me,Re,fe,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,he,Ee,me,ue,le,pe,ge,Se,we],_=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[..._,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class A{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class M{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}const at=["track"];class ct{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;events;constructor(e,t){this.events=new S.Events(at),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new A({track:e}),n=new M(r);return n.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r};addTrackWithMid=(e,t)=>{const r=new A({track:e}),n=new M(r);return t===void 0?n.mid=e.kind==="audio"?"0":"1":n.mid=t,this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r}}function dt(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const O=400,F="777",ht=o=>o.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},O)});replaceMediaStream=jest.fn(async e=>{});restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:n=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=n}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(ht(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new ct(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=dt(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:n=>n==="content-type"?"application/vinteo.webrtc.roomname":n==="x-webrtc-enter-room"?r:n==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},O),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t&&t.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",W="NAME_INCORRECT",E=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},P={status_code:200,reason_phrase:"OK"},v={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:n}=t;return this.session=new s({eventHandlers:n,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},E):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(L);const[t,r]=e.uri.split(":"),[n,c]=r.split("@"),p={...e,uri:new a.URI(t,n,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:P})},E)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:P})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ut{url;constructor(e){this.url=e}}class mt extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",lt=(o,e)=>{const t=new w(e),r={originator:I,request:t,info:new mt("","")};o.newInfo(r)},pt=(o,e)=>{const r={event:"sipEvent",request:new w(e)};o.newSipEvent(r)},gt=(o,{incomingNumber:e="1234",displayName:t,host:r})=>{const n=new s({originator:I,eventHandlers:{}}),c=new H("sip",e,r);n.remote_identity=new U(c,t);const p=new w([]);o.trigger("newRTCSession",{originator:I,session:n,request:p})},_t=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},N={triggerNewInfo:lt,triggerNewSipEvent:pt,triggerIncomingSession:gt,triggerFailIncomingSession:_t,WebSocketInterface:ut,UA:i,C:{INVITE:"INVITE"}},u="user",h="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",Tt=new N.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},It={...R},b={...R,user:u,password:d,register:!0},St={...b,displayName:h},wt={...R,displayName:h,register:!1},l={session_timers:!1,sockets:[Tt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},Ct={...l,password:d,uri:new a.URI("sip",u,m),display_name:h,register:!0},Rt={...l,display_name:h,register:!1},ft={...l,display_name:"",register:!1},k="10.10.10.10",At=[`X-Vinteo-Remote: ${k}`],Mt=()=>new D.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=St;exports.dataForConnectionWithoutAuthorization=wt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=It;exports.displayName=h;exports.doMockSipConnector=Mt;exports.extraHeadersRemoteAddress=At;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=Ct;exports.uaConfigurationWithoutAuthorization=Rt;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const V=require("node:events"),U=require("@krivega/jssip/lib/NameAddrHeader"),H=require("@krivega/jssip/lib/URI"),q=require("@krivega/jssip/lib/SIPMessage"),a=require("@krivega/jssip"),f=require("webrtc-mock"),S=require("events-constructor"),D=require("./@SipConnector-CFYT0HQB.cjs");class w extends q.IncomingRequest{headers;constructor(e){super(),this.headers=new Headers(e)}getHeader(e){return this.headers.get(e)??""}}const G="incomingCall",x="declinedIncomingCall",z="failedIncomingCall",j="terminatedIncomingCall",y="connecting",Y="connected",B="disconnected",K="newRTCSession",J="registered",$="unregistered",Q="registrationFailed",X="newMessage",Z="sipEvent",ee="availableSecondRemoteStream",te="notAvailableSecondRemoteStream",re="mustStopPresentation",ne="shareState",oe="enterRoom",ie="useLicense",se="peerconnection:confirmed",ae="peerconnection:ontrack",ce="channels",de="channels:notify",he="ended:fromserver",Ee="main-cam-control",ue="admin-stop-main-cam",me="admin-start-main-cam",le="admin-stop-mic",pe="admin-start-mic",ge="admin-force-sync-media-state",_e="participant:added-to-list-moderators",Te="participant:removed-from-list-moderators",Ie="participant:move-request-to-stream",Se="participant:move-request-to-spectators",we="participant:move-request-to-participants",Ne="participation:accepting-word-request",Ce="participation:cancelling-word-request",Re="webcast:started",fe="webcast:stopped",Ae="account:changed",Me="account:deleted",Oe="conference:participant-token-issued",Pe="ended",ve="sending",De="reinvite",ye="replaces",Le="refer",Fe="progress",We="accepted",be="confirmed",ke="peerconnection",Ve="failed",Ue="muted",He="unmuted",qe="newDTMF",Ge="newInfo",xe="hold",ze="unhold",je="update",Ye="sdp",Be="icecandidate",Ke="getusermediafailed",Je="peerconnection:createofferfailed",$e="peerconnection:createanswerfailed",Qe="peerconnection:setlocaldescriptionfailed",Xe="peerconnection:setremotedescriptionfailed",Ze="presentation:start",et="presentation:started",tt="presentation:end",rt="presentation:ended",nt="presentation:failed",ot=[G,x,j,z,Ne,Ce,Ie,de,Oe,Ae,Me,Re,fe,_e,Te],L=[y,Y,B,K,J,$,Q,X,Z],it=[ee,te,re,ne,oe,ie,se,ae,ce,he,Ee,me,ue,le,pe,ge,Se,we],_=[Pe,y,ve,De,ye,Le,Fe,We,be,ke,Ve,Ue,He,qe,Ge,xe,ze,je,Ye,Be,Ke,Je,$e,Qe,Xe,Ze,et,tt,rt,nt];[...L,...ot];[..._,...it];class st{originator;connection;events;remote_identity;mutedOptions={audio:!1,video:!1};constructor({originator:e="local",eventHandlers:t,remoteIdentity:r}){this.originator=e,this.events=new S.Events(_),this.initEvents(t),this.remote_identity=r}get contact(){throw new Error("Method not implemented.")}get direction(){throw new Error("Method not implemented.")}get local_identity(){throw new Error("Method not implemented.")}get start_time(){throw new Error("Method not implemented.")}get end_time(){throw new Error("Method not implemented.")}get status(){throw new Error("Method not implemented.")}get C(){throw new Error("Method not implemented.")}get causes(){throw new Error("Method not implemented.")}get id(){throw new Error("Method not implemented.")}get data(){throw new Error("Method not implemented.")}set data(e){throw new Error("Method not implemented.")}isInProgress(){throw new Error("Method not implemented.")}isEnded(){throw new Error("Method not implemented.")}isReadyToReOffer(){throw new Error("Method not implemented.")}answer(e){throw new Error("Method not implemented.")}terminate(e){throw new Error("Method not implemented.")}async sendInfo(e,t,r){throw new Error("Method not implemented.")}hold(e,t){throw new Error("Method not implemented.")}unhold(e,t){throw new Error("Method not implemented.")}async renegotiate(e,t){throw new Error("Method not implemented.")}isOnHold(){throw new Error("Method not implemented.")}mute(e){throw new Error("Method not implemented.")}unmute(e){throw new Error("Method not implemented.")}isMuted(){throw new Error("Method not implemented.")}refer(e,t){throw new Error("Method not implemented.")}resetLocalMedia(){throw new Error("Method not implemented.")}async replaceMediaStream(e,t){throw new Error("Method not implemented.")}addListener(e,t){throw new Error("Method not implemented.")}once(e,t){throw new Error("Method not implemented.")}removeListener(e,t){throw new Error("Method not implemented.")}off(e,t){return this.events.off(e,t),this}removeAllListeners(e){return console.warn("Method not implemented. Event:",e),this}setMaxListeners(e){throw new Error("Method not implemented.")}getMaxListeners(){throw new Error("Method not implemented.")}listeners(e){throw new Error("Method not implemented.")}rawListeners(e){throw new Error("Method not implemented.")}emit(e,...t){throw new Error("Method not implemented.")}listenerCount(e){throw new Error("Method not implemented.")}prependListener(e,t){throw new Error("Method not implemented.")}prependOnceListener(e,t){throw new Error("Method not implemented.")}eventNames(){throw new Error("Method not implemented.")}initEvents(e){e&&Object.entries(e).forEach(([t,r])=>{this.on(t,r)})}on(e,t){return _.includes(e)&&this.events.on(e,t),this}trigger(e,t){this.events.trigger(e,t)}sendDTMF(){this.trigger("newDTMF",{originator:this.originator})}async startPresentation(e){return this.trigger("presentation:start",e),this.trigger("presentation:started",e),e}async stopPresentation(e){return this.trigger("presentation:end",e),this.trigger("presentation:ended",e),e}isEstablished(){return!0}}class A{stats=new Map().set("codec",{mimeType:"video/h264"});dtmf=null;track=null;transport=null;transform=null;parameters={encodings:[{}],transactionId:"0",codecs:[],headerExtensions:[],rtcp:{}};parametersGets;constructor({track:e}={}){this.track=e??null}async getStats(){return this.stats}async replaceTrack(e){this.track=e??null}async setParameters(e){if(e!==this.parametersGets)throw new Error("Failed to execute 'setParameters' on 'RTCRtpSender': Read-only field modified in setParameters().");const{transactionId:t}=this.parameters;this.parameters={...this.parameters,...e,transactionId:`${Number(t)+1}`}}getParameters(){return this.parametersGets={...this.parameters},this.parametersGets}setStreams(){throw new Error("Method not implemented.")}}class M{currentDirection="sendrecv";direction="sendrecv";mid=null;receiver;sender;stopped=!1;constructor(e){this.sender=e}setCodecPreferences(e){}stop(){}}const at=["track"];class ct{senders=[];receivers=[];canTrickleIceCandidates;connectionState;currentLocalDescription;currentRemoteDescription;iceConnectionState;iceGatheringState;idpErrorInfo;idpLoginUrl;localDescription;onconnectionstatechange;ondatachannel;onicecandidate;onicecandidateerror=null;oniceconnectionstatechange;onicegatheringstatechange;onnegotiationneeded;onsignalingstatechange;ontrack;peerIdentity=void 0;pendingLocalDescription;pendingRemoteDescription;remoteDescription;sctp=null;signalingState;events;constructor(e,t){this.events=new S.Events(at),this.receivers=t.map(r=>({track:r}))}getRemoteStreams(){throw new Error("Method not implemented.")}async addIceCandidate(e){throw new Error("Method not implemented.")}addTransceiver(e,t){throw new Error("Method not implemented.")}close(){throw new Error("Method not implemented.")}restartIce(){throw new Error("Method not implemented.")}async createAnswer(e,t){throw new Error("Method not implemented.")}createDataChannel(e,t){throw new Error("Method not implemented.")}async createOffer(e,t,r){throw new Error("Method not implemented.")}getConfiguration(){throw new Error("Method not implemented.")}async getIdentityAssertion(){throw new Error("Method not implemented.")}async getStats(e){throw new Error("Method not implemented.")}getTransceivers(){throw new Error("Method not implemented.")}removeTrack(e){throw new Error("Method not implemented.")}setConfiguration(e){throw new Error("Method not implemented.")}async setLocalDescription(e){throw new Error("Method not implemented.")}async setRemoteDescription(e){throw new Error("Method not implemented.")}addEventListener(e,t,r){this.events.on(e,t)}removeEventListener(e,t,r){this.events.off(e,t)}dispatchEvent(e){throw new Error("Method not implemented.")}getReceivers=()=>this.receivers;getSenders=()=>this.senders;addTrack=(e,...t)=>{const r=new A({track:e}),n=new M(r);return n.mid=e.kind==="audio"?"0":"1",this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r};addTrackWithMid=(e,t)=>{const r=new A({track:e}),n=new M(r);return t===void 0?n.mid=e.kind==="audio"?"0":"1":n.mid=t,this.senders.push(r),this.events.trigger("track",{track:e,transceiver:n}),r}}function dt(o){const e=o.match(/(purgatory)|[\d.]+/g);if(!e)throw new Error("wrong sip url");return e[0]}const O=400,F="777",ht=o=>o.getVideoTracks().length>0;class s extends st{static presentationError;static startPresentationError;static countStartPresentationError=Number.POSITIVE_INFINITY;static countStartsPresentation=0;url;status_code;answer=jest.fn(({mediaStream:e})=>{if(this.originator!=="remote")throw new Error("answer available only for remote sessions");this.initPeerconnection(e),setTimeout(()=>{this.trigger("connecting"),setTimeout(()=>{this.trigger("accepted")},100),setTimeout(()=>{this.trigger("confirmed")},200)},O)});replaceMediaStream=jest.fn(async e=>{});restartIce=jest.fn(async e=>!0);isEndedInner=!1;delayStartPresentation=0;timeoutStartPresentation;timeoutConnect;timeoutNewInfo;timeoutAccepted;timeoutConfirmed;constructor({eventHandlers:e,originator:t,remoteIdentity:r=new a.NameAddrHeader(new a.URI("sip","caller1","test1.com",5060),"Test Caller 1"),delayStartPresentation:n=0}){super({originator:t,eventHandlers:e,remoteIdentity:r}),this.delayStartPresentation=n}static setPresentationError(e){this.presentationError=e}static resetPresentationError(){this.presentationError=void 0}static setStartPresentationError(e,{count:t=Number.POSITIVE_INFINITY}={}){this.startPresentationError=e,this.countStartPresentationError=t}static resetStartPresentationError(){this.startPresentationError=void 0,this.countStartPresentationError=Number.POSITIVE_INFINITY,this.countStartsPresentation=0}startPresentation=async e=>(s.countStartsPresentation+=1,new Promise((t,r)=>{this.timeoutStartPresentation=setTimeout(()=>{if(s.presentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.presentationError);return}if(s.startPresentationError&&s.countStartsPresentation<s.countStartPresentationError){this.trigger("presentation:start",e),this.trigger("presentation:failed",e),r(s.startPresentationError);return}t(super.startPresentation(e))},this.delayStartPresentation)}));stopPresentation=async e=>{if(s.presentationError)throw this.trigger("presentation:end",e),this.trigger("presentation:failed",e),s.presentationError;return super.stopPresentation(e)};initPeerconnection(e){return e?(this.createPeerconnection(e),!0):!1}createPeerconnection(e){const t=f.createAudioMediaStreamTrackMock();t.id="mainaudio1";const r=[t];if(ht(e)){const c=f.createVideoMediaStreamTrackMock();c.id="mainvideo1",r.push(c)}this.connection=new ct(void 0,r),this.addStream(e),this.trigger("peerconnection",{peerconnection:this.connection})}connect(e,{mediaStream:t}={}){const r=dt(e);return this.initPeerconnection(t),this.timeoutConnect=setTimeout(()=>{e.includes(F)?this.trigger("failed",{originator:"remote",message:"IncomingResponse",cause:"Rejected"}):(this.trigger("connecting"),this.timeoutNewInfo=setTimeout(()=>{this.newInfo({originator:D.Originator.REMOTE,request:{getHeader:n=>n==="content-type"?"application/vinteo.webrtc.roomname":n==="x-webrtc-enter-room"?r:n==="x-webrtc-participant-name"?"Test Caller 1":""}})},100),this.timeoutAccepted=setTimeout(()=>{this.trigger("accepted")},200),this.timeoutConfirmed=setTimeout(()=>{this.trigger("confirmed")},300))},O),this.connection}terminate({status_code:e,cause:t}={}){return this.status_code=e,this.trigger("ended",{status_code:e,cause:t,originator:"local"}),this.isEndedInner=!1,this}async terminateAsync({status_code:e,cause:t}={}){this.terminate({status_code:e,cause:t})}terminateRemote({status_code:e}={}){return this.status_code=e,this.trigger("ended",{status_code:e,originator:"remote"}),this}addStream(e,t="getTracks"){e[t]().forEach(r=>this.connection.addTrack(r))}forEachSenders(e){const t=this.connection.getSenders();for(const r of t)e(r);return t}toggleMuteAudio(e){this.forEachSenders(({track:t})=>{t&&t.kind==="audio"&&(t.enabled=!e)})}toggleMuteVideo(e){this.forEachSenders(({track:t})=>{t&&t.kind==="video"&&(t.enabled=!e)})}mute(e){e.audio&&(this.mutedOptions.audio=!0,this.toggleMuteAudio(this.mutedOptions.audio)),e.video&&(this.mutedOptions.video=!0,this.toggleMuteVideo(this.mutedOptions.video)),this.onmute(e)}unmute(e){e.audio&&(this.mutedOptions.audio=!1),e.video&&(this.mutedOptions.video=!1),this.trigger("unmuted",e)}isMuted(){return this.mutedOptions}onmute({audio:e,video:t}){this.trigger("muted",{audio:e,video:t})}async sendInfo(){}isEnded(){return this.isEndedInner}newInfo(e){this.trigger("newInfo",e)}clear(){clearTimeout(this.timeoutStartPresentation),clearTimeout(this.timeoutConnect),clearTimeout(this.timeoutNewInfo),clearTimeout(this.timeoutAccepted),clearTimeout(this.timeoutConfirmed)}}class Et{extraHeaders=[];setExtraHeaders(e){this.extraHeaders=e}setExtraContactParams(){}}const d="PASSWORD_CORRECT",T="PASSWORD_CORRECT_2",W="NAME_INCORRECT",E=400,g={url:"wss://sipServerUrl/webrtc/wss/",sip_uri:"sip:sipServerUrl;transport=ws",via_transport:"WSS"},P={status_code:200,reason_phrase:"OK"},v={status_code:401,reason_phrase:"Unauthorized"};class i{static isAvailableTelephony=!0;static startError;static countStartError=Number.POSITIVE_INFINITY;static countStarts=0;events;registratorInner;call=jest.fn((e,t)=>{const{mediaStream:r,eventHandlers:n}=t;return this.session=new s({eventHandlers:n,originator:"local"}),this.session.connect(e,{mediaStream:r}),this.session});sendOptions=jest.fn((e,t,r)=>{console.log("sendOptions",e,t,r)});start=jest.fn(()=>{if(i.countStarts+=1,i.startError&&i.countStarts<i.countStartError){this.trigger("disconnected",i.startError);return}this.register()});stop=jest.fn(()=>{this.startedTimeout&&clearTimeout(this.startedTimeout),this.stopedTimeout&&clearTimeout(this.stopedTimeout),this.unregister(),this.isStarted()?this.stopedTimeout=setTimeout(()=>{this.trigger("disconnected",{error:!0,socket:g})},E):this.trigger("disconnected",{error:!0,socket:g})});removeAllListeners=jest.fn(()=>(this.events.removeEventHandlers(),this));once=jest.fn((e,t)=>(this.events.once(e,t),this));startedTimeout;stopedTimeout;session;isRegisteredInner;isConnectedInner;configuration;constructor(e){this.events=new S.Events(L);const[t,r]=e.uri.split(":"),[n,c]=r.split("@"),p={...e,uri:new a.URI(t,n,c)};this.configuration=p,this.registratorInner=new Et}static setStartError(e,{count:t=Number.POSITIVE_INFINITY}={}){i.startError=e,i.countStartError=t}static resetStartError(){i.startError=void 0,i.countStartError=Number.POSITIVE_INFINITY,i.countStarts=0}static setAvailableTelephony(){i.isAvailableTelephony=!0}static setNotAvailableTelephony(){i.isAvailableTelephony=!1}static reset(){i.resetStartError(),i.setAvailableTelephony()}on(e,t){return this.events.on(e,t),this}off(e,t){return this.events.off(e,t),this}trigger(e,t){this.events.trigger(e,t)}terminateSessions(){this.session?.terminate()}set(e,t){return this.configuration[e]=t,!0}register(){this.startedTimeout&&clearTimeout(this.startedTimeout);const{password:e,register:t,uri:r}=this.configuration;t===!0&&r.user.includes(W)?(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)):!this.isRegistered()&&t===!0&&(e===d||e===T)?(this.isRegisteredInner=!0,this.startedTimeout=setTimeout(()=>{this.trigger("registered",{response:P})},E)):t===!0&&e!==d&&e!==T&&(this.isRegisteredInner=!1,this.isConnectedInner=!1,this.startedTimeout=setTimeout(()=>{this.trigger("registrationFailed",{response:v,cause:a.C.causes.REJECTED})},E)),i.isAvailableTelephony?(this.trigger("connected",{socket:g}),this.isConnectedInner=!0):this.stop()}unregister(){this.isRegisteredInner=!1,this.isConnectedInner=!1,this.trigger("unregistered",{response:P})}isRegistered(){return this.isRegisteredInner===!0}isConnected(){return this.isConnectedInner===!0}isStarted(){return this.configuration.register===!0&&this.isRegisteredInner===!0||this.configuration.register!==!0&&this.isConnectedInner===!0}newSipEvent(e){this.trigger("sipEvent",e)}registrator(){return this.registratorInner}}class ut{url;constructor(e){this.url=e}}class mt extends V.EventEmitter{contentType;body;constructor(e,t){super(),this.contentType=e,this.body=t}}const I="remote",lt=(o,e)=>{const t=new w(e),r={originator:I,request:t,info:new mt("","")};o.newInfo(r)},pt=(o,e)=>{const r={event:"sipEvent",request:new w(e)};o.newSipEvent(r)},gt=(o,{incomingNumber:e="1234",displayName:t,host:r})=>{const n=new s({originator:I,eventHandlers:{}}),c=new H("sip",e,r);n.remote_identity=new U(c,t);const p=new w([]);o.trigger("newRTCSession",{originator:I,session:n,request:p})},_t=(o,e)=>{e?o.trigger("failed",e):o.trigger("failed",o)},N={triggerNewInfo:lt,triggerNewSipEvent:pt,triggerIncomingSession:gt,triggerFailIncomingSession:_t,WebSocketInterface:ut,UA:i,C:{INVITE:"INVITE"}},u="user",h="displayName",m="SIP_SERVER_URL",C="SIP_WEB_SOCKET_SERVER_URL",Tt=new N.WebSocketInterface(C),R={userAgent:"Chrome",sipServerUrl:m,sipWebSocketServerURL:C},It={...R},b={...R,user:u,password:d,register:!0},St={...b,displayName:h},wt={...R,displayName:h,register:!1},l={session_timers:!1,sockets:[Tt],user_agent:"Chrome",sdpSemantics:"unified-plan",register_expires:300,connection_recovery_max_interval:6,connection_recovery_min_interval:2},Nt={...l,password:d,uri:new a.URI("sip",u,m),display_name:"",register:!0},Ct={...l,password:d,uri:new a.URI("sip",u,m),display_name:h,register:!0},Rt={...l,display_name:h,register:!1},ft={...l,display_name:"",register:!1},k="10.10.10.10",At=[`X-Vinteo-Remote: ${k}`],Mt=()=>new D.SipConnector({JsSIP:N});exports.FAILED_CONFERENCE_NUMBER=F;exports.JsSIP=N;exports.NAME_INCORRECT=W;exports.PASSWORD_CORRECT=d;exports.PASSWORD_CORRECT_2=T;exports.SIP_SERVER_URL=m;exports.SIP_WEB_SOCKET_SERVER_URL=C;exports.dataForConnectionWithAuthorization=b;exports.dataForConnectionWithAuthorizationWithDisplayName=St;exports.dataForConnectionWithoutAuthorization=wt;exports.dataForConnectionWithoutAuthorizationWithoutDisplayName=It;exports.displayName=h;exports.doMockSipConnector=Mt;exports.extraHeadersRemoteAddress=At;exports.remoteAddress=k;exports.uaConfigurationWithAuthorization=Nt;exports.uaConfigurationWithAuthorizationWithDisplayName=Ct;exports.uaConfigurationWithoutAuthorization=Rt;exports.uaConfigurationWithoutAuthorizationWithoutDisplayName=ft;exports.user=u;
package/dist/doMock.js CHANGED
@@ -5,7 +5,7 @@ import { IncomingRequest as k } from "@krivega/jssip/lib/SIPMessage";
5
5
  import { NameAddrHeader as V, URI as E, C as N } from "@krivega/jssip";
6
6
  import { createAudioMediaStreamTrackMock as W, createVideoMediaStreamTrackMock as U } from "webrtc-mock";
7
7
  import { Events as T } from "events-constructor";
8
- import { O as G, S as H } from "./@SipConnector-DADbRZIb.js";
8
+ import { O as G, S as H } from "./@SipConnector-UTHCoMXw.js";
9
9
  class _ extends k {
10
10
  headers;
11
11
  constructor(e) {
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const r=require("./@SipConnector-aB66gnC6.cjs"),x=require("@krivega/cancelable-promise"),j=require("repeated-calls"),K=require("ts-debounce"),X=require("ua-parser-js"),Y=require("sequent-promises"),G=n=>n instanceof Object&&("originator"in n||"cause"in n),J=n=>{if(x.isCanceledError(n))return!0;if(!G(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===r.ECallCause.REQUEST_TIMEOUT||t===r.ECallCause.REJECTED||e===r.Originator.LOCAL&&(t===r.ECallCause.CANCELED||t===r.ECallCause.BYE):!1},z=()=>globalThis.process?.versions?.electron!==void 0,B=()=>{const n=new X.UAParser,{name:e}=n.getBrowser(),t=z();return{isChrome:e==="Chrome"||t}},A=n=>{const{url:e,cause:t}=n;let o=e;return(t===r.ECallCause.BAD_MEDIA_DESCRIPTION||t===r.ECallCause.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var $=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))($||{});const Q=new Error("Unknown error"),Z=(n=Q)=>{const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case r.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case r.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(n)!==void 0&&A(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ee=n=>{let e="";try{e=JSON.stringify(n)}catch(t){r.logger("failed to stringify message",t)}return e},ne=new Error("Unknown error"),te=(n=ne)=>{const{code:e,cause:t,message:o}=n,a=A(n),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ee(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),e!==void 0&&e!==""&&(s.code=e),t!==void 0&&t!==""&&(s.cause=t),s},re=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:A,getTypeFromError:Z,getValuesFromError:te},Symbol.toStringTag,{value:"Module"})),oe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},se="[@*!|]",ae="_",ce=n=>{let e=n;return e=e.replaceAll(new RegExp(se,"g"),ae),e},ie=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const s=`${ce(n)} ${e}`;return`ChromeNew - ${t===void 0?s:`${t} ${o}, ${s}`}`},le=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:a})=>n?ie({appVersion:e,browserName:t,browserVersion:o,appName:a}):"Chrome",H="purgatory",D=n=>n===H,ue=n=>e=>[...e].map(o=>async()=>n(o)),de=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const a=ue(e)(n);return Y.sequentPromises(a,t)},ge=n=>t=>(r.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),Se=n=>t=>(r.logger("onStartMic"),n.on("api:admin-start-mic",t)),Ce=n=>t=>(r.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),me=n=>t=>(r.logger("onStopMic"),n.on("api:admin-stop-mic",t)),fe=({sipConnector:n})=>{const e=(g,C)=>({isSyncForced:S})=>{if(S===!0){g();return}C()},t=ge(n),o=Ce(n),a=Se(n),s=me(n);let c,l,u,f;const h=({onStartMainCamForced:g,onStartMainCamNotForced:C,onStopMainCamForced:S,onStopMainCamNotForced:p,onStartMicForced:E,onStartMicNotForced:b,onStopMicForced:O,onStopMicNotForced:v})=>{const T=e(g,C);c=t(T);const P=e(S,p);l=o(P);const _=e(E,b);u=a(_);const m=e(O,v);f=s(m)},d=()=>{c?.(),l?.(),u?.(),f?.()};return{start:g=>{h(g)},stop:()=>{d()}}},he=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:H,createSyncMediaState:fe,createUaParser:B,error:re,getExtraHeaders:oe,getUserAgent:le,hasPurgatory:D,prepareMediaStream:r.prepareMediaStream,sendDtmfAccumulated:de,setEncodingsToSender:r.setEncodingsToSender,setParametersToSender:r.setParametersToSender},Symbol.toStringTag,{value:"Module"})),pe=()=>B().isChrome,U=n=>{if(!x.isCanceledError(n)&&!j.hasCanceledError(n))throw n;return{isSuccessful:!1}},Re=({kind:n,readyState:e})=>n==="video"&&e==="live",k=(n,e,{onEnterPurgatory:t,onEnterConference:o})=>{D(n)?t&&t():o&&o({isSuccessProgressCall:e})},L=(n,e)=>{n(),e&&e()},V=(n,e,t)=>{throw n&&n(),e(),t},Ee=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class be{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;constructor(e){return this.sipConnector=e,new Proxy(this,{get:(t,o,a)=>{if(typeof o=="string"&&Ee.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(t,o,a);return typeof s=="function"?s.bind(t):s}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,name:l,password:u,isRegisteredUser:f,isDisconnectOnFail:h}=e;return r.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,password:u,user:l,register:f}).then(d=>(r.logger("connectToServer then"),{ua:d,isSuccessful:!0})).catch(async d=>(r.logger("connectToServer catch: error",d),h===!0?this.sipConnector.disconnect().then(()=>U(d)).catch(()=>U(d)):U(d)))};callToServer=async e=>{const{conference:t,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,setRemoteStreams:y,onBeforeProgressCall:g,onSuccessProgressCall:C,onEnterPurgatory:S,onEnterConference:p,onFailProgressCall:E,onFinishProgressCall:b,onEndedCall:O,onAddedTransceiver:v}=e,T=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:y}),P=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{T().catch(r.logger)}});r.logger("callToServer",e);const _=async()=>(r.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,degradationPreference:l,onAddedTransceiver:v,sendEncodings:u,number:t,ontrack:P}));let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",({room:i})=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(S??p)&&k(R,m,{onEnterPurgatory:S,onEnterConference:p})})),F=i=>(r.logger("onSuccess"),m=!0,T().catch(r.logger),C&&C({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,O)}),i),w=i=>(r.logger("onFail"),V(E,M,i)),I=()=>{r.logger("onFinish"),b&&b()};return r.logger("onBeforeProgressCall"),g&&g(t),_().then(F).catch(i=>w(i)).finally(I)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(r.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,setRemoteStreams:N,onBeforeProgressCall:y,onSuccessProgressCall:g,onEnterPurgatory:C,onEnterConference:S,onFailProgressCall:p,onFinishProgressCall:E,onEndedCall:b,onAddedTransceiver:O}=e,v=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:N}),T=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{v().catch(r.logger)}});r.logger("answerToIncomingCall",e);const P=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,degradationPreference:c,onAddedTransceiver:O,sendEncodings:l,ontrack:T}),_=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",i=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(C??S)&&k(R,m,{onEnterPurgatory:C,onEnterConference:S})})),F=i=>(r.logger("onSuccess"),m=!0,v().catch(r.logger),g&&g({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,b)}),i),w=i=>(r.logger("onFail"),V(p,M,i)),I=()=>{r.logger("onFinish"),E&&E()};if(r.logger("onBeforeProgressCall"),y){const i=_();y(i)}return P().then(F).catch(i=>w(i)).finally(I)};updatePresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(r.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(r.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:e=!1}={})=>(r.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{r.logger(t)}));sendRefusalToTurnOnMic=async()=>{r.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{r.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{r.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{r.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{r.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:u})=>(r.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:u,sendEncodings:l}));askPermissionToEnableCam=async()=>{r.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>K.debounce(()=>{const t=this.sipConnector.getRemoteStreams();r.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Re(t)&&e()};getRemoteStreams=()=>(r.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(r.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(r.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(r.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(r.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(r.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{r.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var W=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(W||{});exports.ECallCause=r.ECallCause;exports.EStatsTypes=r.EStatsTypes;exports.EUseLicense=r.EUseLicense;exports.SipConnector=r.SipConnector;exports.StatsPeerConnection=r.StatsPeerConnection;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.getCodecFromSender=r.getCodecFromSender;exports.hasCanceledStartPresentationError=r.hasCanceledStartPresentationError;exports.EMimeTypesVideoCodecs=W;exports.SipConnectorFacade=be;exports.hasAvailableStats=pe;exports.hasCanceledCallError=J;exports.tools=he;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("events-constructor");const r=require("./@SipConnector-CFYT0HQB.cjs"),x=require("@krivega/cancelable-promise"),j=require("repeated-calls"),K=require("ts-debounce"),X=require("ua-parser-js"),Y=require("sequent-promises"),G=n=>n instanceof Object&&("originator"in n||"cause"in n),J=n=>{if(x.isCanceledError(n))return!0;if(!G(n))return!1;const{originator:e,cause:t}=n;return typeof t=="string"?t===r.ECallCause.REQUEST_TIMEOUT||t===r.ECallCause.REJECTED||e==="local"&&(t===r.ECallCause.CANCELED||t===r.ECallCause.BYE):!1},z=()=>globalThis.process?.versions?.electron!==void 0,B=()=>{const n=new X.UAParser,{name:e}=n.getBrowser(),t=z();return{isChrome:e==="Chrome"||t}},A=n=>{const{url:e,cause:t}=n;let o=e;return(t===r.ECallCause.BAD_MEDIA_DESCRIPTION||t===r.ECallCause.NOT_FOUND)&&(o=`${n.message.to.uri.user}@${n.message.to.uri.host}`),o};var $=(n=>(n.CONNECT_SERVER_FAILED="CONNECT_SERVER_FAILED",n.WRONG_USER_OR_PASSWORD="WRONG_USER_OR_PASSWORD",n.BAD_MEDIA_ERROR="BAD_MEDIA_ERROR",n.NOT_FOUND_ERROR="NOT_FOUND_ERROR",n.WS_CONNECTION_FAILED="WS_CONNECTION_FAILED",n.CONNECT_SERVER_FAILED_BY_LINK="CONNECT_SERVER_FAILED_BY_LINK",n))($||{});const Q=new Error("Unknown error"),Z=(n=Q)=>{const{cause:e,socket:t}=n;let o="CONNECT_SERVER_FAILED";switch(e){case"Forbidden":{o="WRONG_USER_OR_PASSWORD";break}case r.ECallCause.BAD_MEDIA_DESCRIPTION:{o="BAD_MEDIA_ERROR";break}case r.ECallCause.NOT_FOUND:{o="NOT_FOUND_ERROR";break}default:t!==void 0&&t._ws?.readyState===3?o="WS_CONNECTION_FAILED":A(n)!==void 0&&A(n)!==""&&(o="CONNECT_SERVER_FAILED_BY_LINK")}return o},ee=n=>{let e="";try{e=JSON.stringify(n)}catch(t){r.logger("failed to stringify message",t)}return e},ne=new Error("Unknown error"),te=(n=ne)=>{const{code:e,cause:t,message:o}=n,a=A(n),s={code:"",cause:"",message:""};return typeof o=="object"&&o!==null?s.message=ee(o):o&&(s.message=String(o)),a!==void 0&&a!==""&&(s.link=a),e!==void 0&&e!==""&&(s.code=e),t!==void 0&&t!==""&&(s.cause=t),s},re=Object.freeze(Object.defineProperty({__proto__:null,EErrorTypes:$,getLinkError:A,getTypeFromError:Z,getValuesFromError:te},Symbol.toStringTag,{value:"Module"})),oe=({sessionId:n,remoteAddress:e,isMutedAudio:t,isMutedVideo:o,isRegistered:a,isPresentationCall:s})=>{const c=[],l=t?"0":"1",u=o?"0":"1";return c.push(`X-Vinteo-Mic-State: ${l}`,`X-Vinteo-MainCam-State: ${u}`),(a===!1||a===void 0)&&c.push("X-Vinteo-Purgatory-Call: yes"),n!==void 0&&n!==""&&c.push(`X-Vinteo-Session: ${n}`),s===!0&&c.push("X-Vinteo-Presentation-Call: yes"),e!==void 0&&e!==""&&c.push(`X-Vinteo-Remote: ${e}`),c},se="[@*!|]",ae="_",ce=n=>{let e=n;return e=e.replaceAll(new RegExp(se,"g"),ae),e},ie=({appName:n,appVersion:e,browserName:t,browserVersion:o})=>{const s=`${ce(n)} ${e}`;return`ChromeNew - ${t===void 0?s:`${t} ${o}, ${s}`}`},le=({isUnifiedSdpSemantic:n,appVersion:e,browserName:t,browserVersion:o,appName:a})=>n?ie({appVersion:e,browserName:t,browserVersion:o,appName:a}):"Chrome",H="purgatory",D=n=>n===H,ue=n=>e=>[...e].map(o=>async()=>n(o)),de=async({accumulatedKeys:n,sendKey:e,canRunTask:t})=>{const a=ue(e)(n);return Y.sequentPromises(a,t)},ge=n=>t=>(r.logger("onStartMainCam"),n.on("api:admin-start-main-cam",t)),Se=n=>t=>(r.logger("onStartMic"),n.on("api:admin-start-mic",t)),Ce=n=>t=>(r.logger("onStopMainCam"),n.on("api:admin-stop-main-cam",t)),me=n=>t=>(r.logger("onStopMic"),n.on("api:admin-stop-mic",t)),fe=({sipConnector:n})=>{const e=(g,C)=>({isSyncForced:S})=>{if(S===!0){g();return}C()},t=ge(n),o=Ce(n),a=Se(n),s=me(n);let c,l,u,f;const h=({onStartMainCamForced:g,onStartMainCamNotForced:C,onStopMainCamForced:S,onStopMainCamNotForced:p,onStartMicForced:E,onStartMicNotForced:b,onStopMicForced:P,onStopMicNotForced:v})=>{const T=e(g,C);c=t(T);const O=e(S,p);l=o(O);const _=e(E,b);u=a(_);const m=e(P,v);f=s(m)},d=()=>{c?.(),l?.(),u?.(),f?.()};return{start:g=>{h(g)},stop:()=>{d()}}},he=Object.freeze(Object.defineProperty({__proto__:null,PURGATORY_CONFERENCE_NUMBER:H,createSyncMediaState:fe,createUaParser:B,error:re,getExtraHeaders:oe,getUserAgent:le,hasPurgatory:D,prepareMediaStream:r.prepareMediaStream,sendDtmfAccumulated:de,setEncodingsToSender:r.setEncodingsToSender,setParametersToSender:r.setParametersToSender},Symbol.toStringTag,{value:"Module"})),pe=()=>B().isChrome,U=n=>{if(!x.isCanceledError(n)&&!j.hasCanceledError(n))throw n;return{isSuccessful:!1}},Re=({kind:n,readyState:e})=>n==="video"&&e==="live",k=(n,e,{onEnterPurgatory:t,onEnterConference:o})=>{D(n)?t&&t():o&&o({isSuccessProgressCall:e})},L=(n,e)=>{n(),e&&e()},V=(n,e,t)=>{throw n&&n(),e(),t},Ee=new Set(["on","once","onceRace","wait","off","sendDTMF","hangUp","declineToIncomingCall","sendChannels","checkTelephony","waitChannels","ping","connection","isConfigured","isRegistered"]);class be{on;once;onceRace;wait;off;sendDTMF;hangUp;declineToIncomingCall;sendChannels;checkTelephony;waitChannels;ping;connection;isConfigured;isRegistered;sipConnector;constructor(e){return this.sipConnector=e,new Proxy(this,{get:(t,o,a)=>{if(typeof o=="string"&&Ee.has(o)&&o in this.sipConnector){const c=Reflect.get(this.sipConnector,o,this.sipConnector);return typeof c=="function"?c.bind(this.sipConnector):c}const s=Reflect.get(t,o,a);return typeof s=="function"?s.bind(t):s}})}connectToServer=async e=>{const{userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,name:l,password:u,isRegisteredUser:f,isDisconnectOnFail:h}=e;return r.logger("connectToServer",e),this.sipConnector.connect({userAgent:t,sipWebSocketServerURL:o,sipServerUrl:a,remoteAddress:s,displayName:c,password:u,user:l,register:f}).then(d=>(r.logger("connectToServer then"),{ua:d,isSuccessful:!0})).catch(async d=>(r.logger("connectToServer catch: error",d),h===!0?this.sipConnector.disconnect().then(()=>U(d)).catch(()=>U(d)):U(d)))};callToServer=async e=>{const{conference:t,mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,degradationPreference:l,sendEncodings:u,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,setRemoteStreams:y,onBeforeProgressCall:g,onSuccessProgressCall:C,onEnterPurgatory:S,onEnterConference:p,onFailProgressCall:E,onFinishProgressCall:b,onEndedCall:P,onAddedTransceiver:v}=e,T=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:y}),O=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{T().catch(r.logger)}});r.logger("callToServer",e);const _=async()=>(r.logger("startCall"),this.sipConnector.call({mediaStream:o,extraHeaders:a,iceServers:s,contentHint:c,offerToReceiveAudio:f,offerToReceiveVideo:h,directionVideo:d,directionAudio:N,degradationPreference:l,onAddedTransceiver:v,sendEncodings:u,number:t,ontrack:O}));let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",p),this.sipConnector.on("api:enterRoom",({room:i})=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(S??p)&&k(R,m,{onEnterPurgatory:S,onEnterConference:p})})),F=i=>(r.logger("onSuccess"),m=!0,T().catch(r.logger),C&&C({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,P)}),i),w=i=>(r.logger("onFail"),V(E,M,i)),I=()=>{r.logger("onFinish"),b&&b()};return r.logger("onBeforeProgressCall"),g&&g(t),_().then(F).catch(i=>w(i)).finally(I)};disconnectFromServer=async()=>this.sipConnector.disconnect().then(()=>(r.logger("disconnectFromServer: then"),{isSuccessful:!0})).catch(e=>(r.logger("disconnectFromServer: catch",e),{isSuccessful:!1}));answerToIncomingCall=async e=>{const{mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,degradationPreference:c,sendEncodings:l,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,setRemoteStreams:N,onBeforeProgressCall:y,onSuccessProgressCall:g,onEnterPurgatory:C,onEnterConference:S,onFailProgressCall:p,onFinishProgressCall:E,onEndedCall:b,onAddedTransceiver:P}=e,v=this.resolveHandleReadyRemoteStreamsDebounced({onReadyRemoteStreams:N}),T=this.resolveHandleReadyRemoteStreams({onReadyRemoteStreams:()=>{v().catch(r.logger)}});r.logger("answerToIncomingCall",e);const O=async()=>this.sipConnector.answerToIncomingCall({mediaStream:t,extraHeaders:o,iceServers:a,contentHint:s,offerToReceiveAudio:u,offerToReceiveVideo:f,directionVideo:h,directionAudio:d,degradationPreference:c,onAddedTransceiver:P,sendEncodings:l,ontrack:T}),_=()=>{const{remoteCallerData:i}=this.sipConnector;return i.incomingNumber};let m=!1,R;const M=(r.logger("subscribeEnterConference: onEnterConference",S),this.sipConnector.on("api:enterRoom",i=>{r.logger("enterRoom",{_room:i,isSuccessProgressCall:m}),R=i,(C??S)&&k(R,m,{onEnterPurgatory:C,onEnterConference:S})})),F=i=>(r.logger("onSuccess"),m=!0,v().catch(r.logger),g&&g({isPurgatory:D(R)}),this.sipConnector.onceRace(["call:ended","call:failed"],()=>{L(M,b)}),i),w=i=>(r.logger("onFail"),V(p,M,i)),I=()=>{r.logger("onFinish"),E&&E()};if(r.logger("onBeforeProgressCall"),y){const i=_();y(i)}return O().then(F).catch(i=>w(i)).finally(I)};updatePresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,onAddedTransceiver:c})=>(r.logger("updatePresentation"),this.sipConnector.updatePresentation(e,{isP2P:t,contentHint:o,degradationPreference:a,onAddedTransceiver:c,sendEncodings:s}));startPresentation=async({mediaStream:e,isP2P:t,contentHint:o,degradationPreference:a,sendEncodings:s,callLimit:c,onAddedTransceiver:l})=>(r.logger("startPresentation"),this.sipConnector.startPresentation(e,{isP2P:t,contentHint:o,callLimit:c,degradationPreference:a,onAddedTransceiver:l,sendEncodings:s}));stopShareSipConnector=async({isP2P:e=!1}={})=>(r.logger("stopShareSipConnector"),this.sipConnector.stopPresentation({isP2P:e}).catch(t=>{r.logger(t)}));sendRefusalToTurnOnMic=async()=>{r.logger("sendRefusalToTurnOnMic"),await this.sipConnector.sendRefusalToTurnOnMic().catch(e=>{r.logger("sendRefusalToTurnOnMic: error",e)})};sendRefusalToTurnOnCam=async()=>{r.logger("sendRefusalToTurnOnCam"),await this.sipConnector.sendRefusalToTurnOnCam().catch(e=>{r.logger("sendRefusalToTurnOnCam: error",e)})};sendMediaState=async({isEnabledCam:e,isEnabledMic:t})=>{r.logger("sendMediaState"),await this.sipConnector.sendMediaState({cam:e,mic:t})};replaceMediaStream=async(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,sendEncodings:l,onAddedTransceiver:u})=>(r.logger("replaceMediaStream"),this.sipConnector.replaceMediaStream(e,{deleteExisting:t,addMissing:o,forceRenegotiation:a,contentHint:s,degradationPreference:c,onAddedTransceiver:u,sendEncodings:l}));askPermissionToEnableCam=async()=>{r.logger("askPermissionToEnableCam"),await this.sipConnector.askPermissionToEnableCam()};resolveHandleReadyRemoteStreamsDebounced=({onReadyRemoteStreams:e})=>K.debounce(()=>{const t=this.sipConnector.getRemoteStreams();r.logger("remoteStreams",t),t&&e(t)},200);resolveHandleReadyRemoteStreams=({onReadyRemoteStreams:e})=>({track:t})=>{Re(t)&&e()};getRemoteStreams=()=>(r.logger("getRemoteStreams"),this.sipConnector.getRemoteStreams());onUseLicense=e=>(r.logger("onUseLicense"),this.sipConnector.on("api:useLicense",e));onMustStopPresentation=e=>(r.logger("onMustStopPresentation"),this.sipConnector.on("api:mustStopPresentation",e));onMoveToSpectators=e=>(r.logger("onMoveToSpectators"),this.sipConnector.on("api:participant:move-request-to-spectators",e));onMoveToParticipants=e=>(r.logger("onMoveToParticipants"),this.sipConnector.on("api:participant:move-request-to-participants",e));onStats=e=>(r.logger("onStats"),this.sipConnector.on("stats:collected",e));offStats=e=>{r.logger("offStats"),this.sipConnector.off("stats:collected",e)}}var W=(n=>(n.VP8="video/VP8",n.VP9="video/VP9",n.H264="video/H264",n.AV1="video/AV1",n.rtx="video/rtx",n.red="video/red",n.flexfec03="video/flexfec-03",n))(W||{});exports.ECallCause=r.ECallCause;exports.EStatsTypes=r.EStatsTypes;exports.EUseLicense=r.EUseLicense;exports.SipConnector=r.SipConnector;exports.StatsPeerConnection=r.StatsPeerConnection;exports.disableDebug=r.disableDebug;exports.enableDebug=r.enableDebug;exports.getCodecFromSender=r.getCodecFromSender;exports.hasCanceledStartPresentationError=r.hasCanceledStartPresentationError;exports.EMimeTypesVideoCodecs=W;exports.SipConnectorFacade=be;exports.hasAvailableStats=pe;exports.hasCanceledCallError=J;exports.tools=he;