sip-connector 14.1.0-alpha.9 → 14.1.1

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 (132) hide show
  1. package/dist/SipConnector-DRjfFGAZ.js +1339 -0
  2. package/dist/SipConnector-EXAO9Z-2.cjs +1 -0
  3. package/dist/doMock.cjs +1 -1
  4. package/dist/doMock.js +162 -267
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +526 -577
  7. package/dist/src/SipConnector.d.ts +235 -0
  8. package/dist/{SipConnectorFacade → src/SipConnectorFacade}/SipConnectorFacade.d.ts +16 -7
  9. package/dist/{__fixtures__ → src/__fixtures__}/BaseSession.mock.d.ts +5 -5
  10. package/dist/{__fixtures__ → src/__fixtures__}/RTCSessionMock.d.ts +4 -9
  11. package/dist/{__fixtures__ → src/__fixtures__}/UA.mock.d.ts +14 -12
  12. package/dist/{__fixtures__ → src/__fixtures__}/index.d.ts +4 -4
  13. package/dist/{__fixtures__ → src/__fixtures__}/jssip.mock.d.ts +3 -3
  14. package/dist/src/causes.d.ts +23 -0
  15. package/dist/{doMock.d.ts → src/doMock.d.ts} +1 -2
  16. package/dist/{__fixtures__ → src}/eventNames.d.ts +1 -1
  17. package/dist/src/headers.d.ts +37 -0
  18. package/dist/src/index.d.ts +11 -0
  19. package/dist/{tools → src/tools}/__fixtures__/connectToServer.d.ts +2 -2
  20. package/dist/{tools → src/tools}/__fixtures__/processRequest.d.ts +1 -1
  21. package/dist/{tools → src/tools}/error/getLinkError.d.ts +1 -1
  22. package/dist/{tools → src/tools}/error/getTypeFromError.d.ts +1 -1
  23. package/dist/{tools → src/tools}/error/getValuesFromError.d.ts +1 -1
  24. package/dist/{tools → src/tools}/index.d.ts +1 -1
  25. package/dist/{tools → src/tools}/prepareMediaStream.d.ts +1 -1
  26. package/dist/{tools → src/tools}/setVideoTrackContentHints.d.ts +1 -1
  27. package/dist/{tools → src/tools}/syncMediaState/index.d.ts +1 -1
  28. package/dist/{tools → src/tools}/syncMediaState/resolveOnStartMainCam.d.ts +1 -1
  29. package/dist/{tools → src/tools}/syncMediaState/resolveOnStartMic.d.ts +1 -1
  30. package/dist/{tools → src/tools}/syncMediaState/resolveOnStopMainCam.d.ts +1 -1
  31. package/dist/{tools → src/tools}/syncMediaState/resolveOnStopMic.d.ts +1 -1
  32. package/dist/src/types.d.ts +69 -0
  33. package/dist/{videoSendingBalancer → src/videoSendingBalancer}/balance.d.ts +1 -1
  34. package/dist/{videoSendingBalancer → src/videoSendingBalancer}/index.d.ts +1 -1
  35. package/dist/{videoSendingBalancer → src/videoSendingBalancer}/processSender.d.ts +1 -1
  36. package/dist/src/videoSendingBalancer/scaleBitrate.d.ts +2 -0
  37. package/package.json +32 -26
  38. package/dist/@SipConnector-BOHJ000Z.cjs +0 -1
  39. package/dist/@SipConnector-BxitfweK.js +0 -2267
  40. package/dist/ApiManager/@ApiManager.d.ts +0 -58
  41. package/dist/ApiManager/constants.d.ts +0 -71
  42. package/dist/ApiManager/eventNames.d.ts +0 -33
  43. package/dist/ApiManager/index.d.ts +0 -3
  44. package/dist/ApiManager/types.d.ts +0 -99
  45. package/dist/CallManager/@CallManager.d.ts +0 -26
  46. package/dist/CallManager/AbstractCallStrategy.d.ts +0 -47
  47. package/dist/CallManager/MCUCallStrategy.d.ts +0 -30
  48. package/dist/CallManager/RemoteStreamsManager.d.ts +0 -8
  49. package/dist/CallManager/causes.d.ts +0 -13
  50. package/dist/CallManager/eventNames.d.ts +0 -45
  51. package/dist/CallManager/hasCanceledCallError.d.ts +0 -2
  52. package/dist/CallManager/index.d.ts +0 -7
  53. package/dist/CallManager/types.d.ts +0 -59
  54. package/dist/ConnectionManager/@ConnectionManager.d.ts +0 -48
  55. package/dist/ConnectionManager/ConfigurationManager.d.ts +0 -60
  56. package/dist/ConnectionManager/ConnectionFlow.d.ts +0 -84
  57. package/dist/ConnectionManager/ConnectionStateMachine.d.ts +0 -61
  58. package/dist/ConnectionManager/RegistrationManager.d.ts +0 -17
  59. package/dist/ConnectionManager/SipOperations.d.ts +0 -32
  60. package/dist/ConnectionManager/UAFactory.d.ts +0 -50
  61. package/dist/ConnectionManager/eventNames.d.ts +0 -16
  62. package/dist/ConnectionManager/index.d.ts +0 -3
  63. package/dist/IncomingCallManager/@IncomingCallManager.d.ts +0 -37
  64. package/dist/IncomingCallManager/eventNames.d.ts +0 -13
  65. package/dist/IncomingCallManager/index.d.ts +0 -2
  66. package/dist/PresentationManager/@PresentationManager.d.ts +0 -47
  67. package/dist/PresentationManager/constants.d.ts +0 -1
  68. package/dist/PresentationManager/eventNames.d.ts +0 -11
  69. package/dist/PresentationManager/index.d.ts +0 -2
  70. package/dist/PresentationManager/types.d.ts +0 -2
  71. package/dist/SipConnector/@SipConnector.d.ts +0 -96
  72. package/dist/SipConnector/eventNames.d.ts +0 -4
  73. package/dist/SipConnector/index.d.ts +0 -2
  74. package/dist/index.d.ts +0 -14
  75. package/dist/types.d.ts +0 -23
  76. package/dist/videoSendingBalancer/scaleBitrate.d.ts +0 -2
  77. /package/dist/{SipConnectorFacade → src/SipConnectorFacade}/index.d.ts +0 -0
  78. /package/dist/{__fixtures__ → src/__fixtures__}/RTCPeerConnectionMock.d.ts +0 -0
  79. /package/dist/{__fixtures__ → src/__fixtures__}/RTCRtpSenderMock.d.ts +0 -0
  80. /package/dist/{__fixtures__ → src/__fixtures__}/Registrator.mock.d.ts +0 -0
  81. /package/dist/{__fixtures__ → src/__fixtures__}/Request.mock.d.ts +0 -0
  82. /package/dist/{__fixtures__ → src/__fixtures__}/WebSocketInterface.mock.d.ts +0 -0
  83. /package/dist/{__fixtures__ → src/__fixtures__}/accountNotify.d.ts +0 -0
  84. /package/dist/{__fixtures__ → src/__fixtures__}/channels.d.ts +0 -0
  85. /package/dist/{__fixtures__ → src/__fixtures__}/channelsNotify.d.ts +0 -0
  86. /package/dist/{__fixtures__ → src/__fixtures__}/conferenceParticipantTokenIssuedNotify.d.ts +0 -0
  87. /package/dist/{__fixtures__ → src/__fixtures__}/delayPromise.d.ts +0 -0
  88. /package/dist/{__fixtures__ → src/__fixtures__}/enterRoom.d.ts +0 -0
  89. /package/dist/{__fixtures__ → src/__fixtures__}/mediaState.d.ts +0 -0
  90. /package/dist/{__fixtures__ → src/__fixtures__}/participantMoveRequests.d.ts +0 -0
  91. /package/dist/{__fixtures__ → src/__fixtures__}/participantNotify.d.ts +0 -0
  92. /package/dist/{__fixtures__ → src/__fixtures__}/remoteCallerData.d.ts +0 -0
  93. /package/dist/{__fixtures__ → src/__fixtures__}/utils.d.ts +0 -0
  94. /package/dist/{__fixtures__ → src/__fixtures__}/webcastNotify.d.ts +0 -0
  95. /package/dist/{__fixtures__ → src}/constants.d.ts +0 -0
  96. /package/dist/{ConnectionManager → src}/getExtraHeadersRemoteAddress.d.ts +0 -0
  97. /package/dist/{logger.d.ts → src/logger.d.ts} +0 -0
  98. /package/dist/{setParametersToSender → src/setParametersToSender}/configureDegradationPreference.d.ts +0 -0
  99. /package/dist/{setParametersToSender → src/setParametersToSender}/configureEmptyEncodings.d.ts +0 -0
  100. /package/dist/{setParametersToSender → src/setParametersToSender}/configureEncodings.d.ts +0 -0
  101. /package/dist/{setParametersToSender → src/setParametersToSender}/configureMaxBitrate.d.ts +0 -0
  102. /package/dist/{setParametersToSender → src/setParametersToSender}/configureScaleResolutionDownBy.d.ts +0 -0
  103. /package/dist/{setParametersToSender → src/setParametersToSender}/hasChangedRTCRtpSendParameters.d.ts +0 -0
  104. /package/dist/{setParametersToSender → src/setParametersToSender}/index.d.ts +0 -0
  105. /package/dist/{setParametersToSender → src/setParametersToSender}/resolveHasNeedToUpdateItemEncoding.d.ts +0 -0
  106. /package/dist/{setParametersToSender → src/setParametersToSender}/setParametersToSender.d.ts +0 -0
  107. /package/dist/{tools → src/tools}/__fixtures__/call.d.ts +0 -0
  108. /package/dist/{tools → src/tools}/__fixtures__/hasValidUri.d.ts +0 -0
  109. /package/dist/{tools → src/tools}/__fixtures__/permissions.d.ts +0 -0
  110. /package/dist/{tools → src/tools}/__tests-utils__/parseObject.d.ts +0 -0
  111. /package/dist/{tools → src/tools}/__tests-utils__/resolveParseArray.d.ts +0 -0
  112. /package/dist/{tools → src/tools}/error/index.d.ts +0 -0
  113. /package/dist/{tools → src/tools}/error/stringifyMessage.d.ts +0 -0
  114. /package/dist/{tools → src/tools}/generateSimulcastEncodings.d.ts +0 -0
  115. /package/dist/{tools → src/tools}/getExtraHeaders.d.ts +0 -0
  116. /package/dist/{tools → src/tools}/getUserAgent.d.ts +0 -0
  117. /package/dist/{tools → src/tools}/hasPurgatory.d.ts +0 -0
  118. /package/dist/{tools → src/tools}/resolveUpdateTransceiver.d.ts +0 -0
  119. /package/dist/{tools/sendDtmfFAccumulated.d.ts → src/tools/sendDTMFAccumulated.d.ts} +0 -0
  120. /package/dist/{utils → src/utils}/errors.d.ts +0 -0
  121. /package/dist/{utils → src/utils}/findSenderByStream.d.ts +0 -0
  122. /package/dist/{utils → src/utils}/findVideoSender.d.ts +0 -0
  123. /package/dist/{utils → src/utils}/findVideoTrack.d.ts +0 -0
  124. /package/dist/{utils → src/utils}/getCodecFromSender.d.ts +0 -0
  125. /package/dist/{utils → src/utils}/replaceForbiddenSymbolsWithUnderscore.d.ts +0 -0
  126. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/getMaxBitrateByWidth.d.ts +0 -0
  127. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/getMaxBitrateByWidthAndCodec.d.ts +0 -0
  128. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/hasAv1Codec.d.ts +0 -0
  129. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/hasIncludesString.d.ts +0 -0
  130. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/scaleBitrateByCodec.d.ts +0 -0
  131. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/scaleResolutionAndBitrate.d.ts +0 -0
  132. /package/dist/{videoSendingBalancer → src/videoSendingBalancer}/setEncodingsToSender.d.ts +0 -0
@@ -1,3 +1,3 @@
1
- import { TContentHint } from '../PresentationManager';
1
+ import { TContentHint } from '../types';
2
2
  declare const setVideoTrackContentHints: (stream: MediaStream, contentHint: TContentHint) => void;
3
3
  export default setVideoTrackContentHints;
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../../SipConnector';
1
+ import { default as SipConnector } from '../../SipConnector';
2
2
  type THandlers = {
3
3
  onStartMainCamForced: () => void;
4
4
  onStartMainCamNotForced: () => void;
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../../SipConnector';
1
+ import { default as SipConnector } from '../../SipConnector';
2
2
  declare const resolveOnStartMainCam: (sipConnector: SipConnector) => (handler: ({ isSyncForced }: {
3
3
  isSyncForced: boolean;
4
4
  }) => void) => (() => void);
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../../SipConnector';
1
+ import { default as SipConnector } from '../../SipConnector';
2
2
  declare const resolveOnStartMic: (sipConnector: SipConnector) => (handler: ({ isSyncForced }: {
3
3
  isSyncForced: boolean;
4
4
  }) => void) => (() => void);
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../../SipConnector';
1
+ import { default as SipConnector } from '../../SipConnector';
2
2
  declare const resolveOnStopMainCam: (sipConnector: SipConnector) => (handler: ({ isSyncForced }: {
3
3
  isSyncForced: boolean;
4
4
  }) => void) => (() => void);
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../../SipConnector';
1
+ import { default as SipConnector } from '../../SipConnector';
2
2
  declare const resolveOnStopMic: (sipConnector: SipConnector) => (handler: ({ isSyncForced }: {
3
3
  isSyncForced: boolean;
4
4
  }) => void) => (() => void);
@@ -0,0 +1,69 @@
1
+ import { UA, WebSocketInterface } from '@krivega/jssip';
2
+ import { Originator } from './constants';
3
+ export declare enum EEventsMainCAM {
4
+ PAUSE_MAIN_CAM = "PAUSEMAINCAM",
5
+ RESUME_MAIN_CAM = "RESUMEMAINCAM",
6
+ MAX_MAIN_CAM_RESOLUTION = "MAXMAINCAMRESOLUTION",
7
+ ADMIN_STOP_MAIN_CAM = "ADMINSTOPMAINCAM",
8
+ ADMIN_START_MAIN_CAM = "ADMINSTARTMAINCAM"
9
+ }
10
+ export declare enum EEventsMic {
11
+ ADMIN_STOP_MIC = "ADMINSTOPMIC",
12
+ ADMIN_START_MIC = "ADMINSTARTMIC"
13
+ }
14
+ export declare enum EEventsSyncMediaState {
15
+ ADMIN_SYNC_FORCED = "1",
16
+ ADMIN_SYNC_NOT_FORCED = "0"
17
+ }
18
+ export declare enum EUseLicense {
19
+ AUDIO = "AUDIO",
20
+ VIDEO = "VIDEO",
21
+ AUDIOPLUSPRESENTATION = "AUDIOPLUSPRESENTATION"
22
+ }
23
+ export type TCustomError = Error & {
24
+ originator?: Originator;
25
+ cause?: unknown;
26
+ message: unknown;
27
+ _ws?: unknown;
28
+ socket?: unknown;
29
+ url?: string;
30
+ code?: string;
31
+ };
32
+ export type TJsSIP = {
33
+ UA: typeof UA;
34
+ WebSocketInterface: typeof WebSocketInterface;
35
+ };
36
+ export type TGetServerUrl = (id: string) => string;
37
+ export type TParametersCreateUaConfiguration = {
38
+ sipWebSocketServerURL: string;
39
+ displayName?: string;
40
+ sipServerUrl: string;
41
+ user?: string;
42
+ register?: boolean;
43
+ password?: string;
44
+ sessionTimers?: boolean;
45
+ registerExpires?: number;
46
+ connectionRecoveryMinInterval?: number;
47
+ connectionRecoveryMaxInterval?: number;
48
+ userAgent?: string;
49
+ };
50
+ export type TOnAddedTransceiver = (transceiver: RTCRtpTransceiver, track: MediaStreamTrack, stream: MediaStream) => Promise<void>;
51
+ export type TContentHint = 'motion' | 'detail' | 'text' | 'none';
52
+ export type TRtpSendParameters = Partial<Omit<RTCRtpSendParameters, 'transactionId'>>;
53
+ export type TSize = {
54
+ width: number;
55
+ height: number;
56
+ };
57
+ export type TSimulcastEncoding = TSize & {
58
+ rid?: string;
59
+ scalabilityMode?: string;
60
+ };
61
+ export declare enum EMimeTypesVideoCodecs {
62
+ VP8 = "video/VP8",
63
+ VP9 = "video/VP9",
64
+ H264 = "video/H264",
65
+ AV1 = "video/AV1",
66
+ rtx = "video/rtx",
67
+ red = "video/red",
68
+ flexfec03 = "video/flexfec-03"
69
+ }
@@ -1,4 +1,4 @@
1
- import { EEventsMainCAM } from '../ApiManager';
1
+ import { EEventsMainCAM } from '../types';
2
2
  import { TOnSetParameters, TResult } from './setEncodingsToSender';
3
3
  declare const balance: ({ mainCam, resolutionMainCam, connection, onSetParameters, ignoreForCodec, }: {
4
4
  mainCam?: EEventsMainCAM;
@@ -1,4 +1,4 @@
1
- import { SipConnector } from '../SipConnector';
1
+ import { default as SipConnector } from '../SipConnector';
2
2
  import { TOnSetParameters } from './setEncodingsToSender';
3
3
  declare const resolveVideoSendingBalancer: (sipConnector: SipConnector, { ignoreForCodec, onSetParameters, }?: {
4
4
  ignoreForCodec?: string;
@@ -1,4 +1,4 @@
1
- import { EEventsMainCAM } from '../ApiManager';
1
+ import { EEventsMainCAM } from '../types';
2
2
  import { TOnSetParameters, TResult } from './setEncodingsToSender';
3
3
  declare const processSender: ({ mainCam, resolutionMainCam, sender, videoTrack, codec, }: {
4
4
  mainCam?: EEventsMainCAM;
@@ -0,0 +1,2 @@
1
+ declare const scaleBitrate: (senders: RTCRtpSender[], mediaStream: MediaStream, maxBitrate: number) => Promise<import('./setEncodingsToSender').TResult | undefined>;
2
+ export default scaleBitrate;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sip-connector",
3
- "version": "14.1.0-alpha.9",
3
+ "version": "14.1.1",
4
4
  "description": "Module for connect to Vinteo server",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -22,16 +22,24 @@
22
22
  "type": "module",
23
23
  "exports": {
24
24
  ".": {
25
- "types": "./dist/index.d.ts",
26
- "import": "./dist/index.js",
27
25
  "require": "./dist/index.cjs",
28
- "default": "./dist/index.js"
26
+ "import": "./dist/index.js"
29
27
  },
30
28
  "./doMock": {
31
- "types": "./dist/doMock.d.ts",
32
- "import": "./dist/doMock.js",
33
29
  "require": "./dist/doMock.cjs",
34
- "default": "./dist/doMock.js"
30
+ "import": "./dist/doMock.js"
31
+ }
32
+ },
33
+ "main": "./dist/index.cjs",
34
+ "types": "dist/index.d.ts",
35
+ "typesVersions": {
36
+ "*": {
37
+ "dist/index.d.ts": [
38
+ "dist/index.d.ts"
39
+ ],
40
+ "*": [
41
+ "dist/*"
42
+ ]
35
43
  }
36
44
  },
37
45
  "files": [
@@ -48,11 +56,10 @@
48
56
  "release": "standard-version && npm run release:publish",
49
57
  "release:major": "standard-version --release-as major && npm run release:publish",
50
58
  "release:pre": "standard-version --prerelease && npm run release:publish",
51
- "release:alpha": "standard-version --prerelease alpha && npm run release:publish",
52
59
  "release:publish": "git push --follow-tags origin master && npm publish --access=public",
53
60
  "test": "jest",
54
61
  "test:ci": "cross-env CI=true jest",
55
- "test:coverage": "yarn test:ci --no-cache --coverage",
62
+ "test:coverage": "yarn test:ci --coverage --reporters=default --reporters=jest-junit",
56
63
  "test:watch": "jest --watch"
57
64
  },
58
65
  "dependencies": {
@@ -60,36 +67,35 @@
60
67
  "@krivega/jssip": "^5.1.2",
61
68
  "debug": "^4.4.1",
62
69
  "events-constructor": "^1.3.0",
63
- "repeated-calls": "^2.3.4",
70
+ "repeated-calls": "^2.3.3",
64
71
  "sequent-promises": "^2.0.1",
65
72
  "stack-promises": "^2.0.3",
66
73
  "ts-debounce": "^4.0.0",
67
- "webrtc-mock": "^1.1.7",
68
- "xstate": "^5.20.1"
74
+ "webrtc-mock": "^1.1.7"
69
75
  },
70
76
  "devDependencies": {
71
77
  "@babel/preset-typescript": "^7.27.1",
72
78
  "@commitlint/cli": "^19.8.1",
73
79
  "@commitlint/config-conventional": "^19.8.1",
74
80
  "@eslint/compat": "^1.3.1",
75
- "@nabla/vite-plugin-eslint": "^2.0.6",
76
- "@stylistic/eslint-plugin": "^5.2.2",
81
+ "@nabla/vite-plugin-eslint": "^2.0.5",
82
+ "@stylistic/eslint-plugin": "^5.1.0",
77
83
  "@types/debug": "^4.1.12",
78
84
  "@types/dom-mediacapture-transform": "^0.1.11",
79
85
  "@types/jest": "^30.0.0",
80
- "@typescript-eslint/eslint-plugin": "^8.38.0",
81
- "@typescript-eslint/parser": "^8.38.0",
82
- "cross-env": "^10.0.0",
83
- "eslint": "^9.32.0",
86
+ "@typescript-eslint/eslint-plugin": "^8.36.0",
87
+ "@typescript-eslint/parser": "^8.36.0",
88
+ "cross-env": "^7.0.3",
89
+ "eslint": "^9.31.0",
84
90
  "eslint-import-resolver-typescript": "^4.4.4",
85
91
  "eslint-plugin-flowtype": "^8.0.3",
86
92
  "eslint-plugin-import": "^2.32.0",
87
93
  "eslint-plugin-jest": "^29.0.1",
88
- "eslint-plugin-prettier": "^5.5.3",
89
- "eslint-plugin-unicorn": "^60.0.0",
94
+ "eslint-plugin-prettier": "^5.5.1",
95
+ "eslint-plugin-unicorn": "^59.0.1",
90
96
  "husky": "^9.1.7",
91
- "jest": "^30.0.5",
92
- "jest-environment-jsdom": "^30.0.5",
97
+ "jest": "^30.0.4",
98
+ "jest-environment-jsdom": "^30.0.4",
93
99
  "jest-extended": "^6.0.0",
94
100
  "jest-junit": "^16.0.0",
95
101
  "lint-staged": "^16.1.2",
@@ -99,7 +105,7 @@
99
105
  "ts-node": "^10.9.2",
100
106
  "tsc-files": "^1.1.4",
101
107
  "typescript": "^5.8.3",
102
- "vite": "^7.0.6",
108
+ "vite": "^7.0.4",
103
109
  "vite-plugin-dts": "^4.5.4",
104
110
  "vite-tsconfig-paths": "^5.1.4"
105
111
  },
@@ -112,8 +118,8 @@
112
118
  "sequent-promises": "^2.0.1",
113
119
  "stack-promises": "^2.0.3",
114
120
  "ts-debounce": "^4.0.0",
115
- "webrtc-mock": "^1.1.7",
116
- "xstate": "^5.20.1"
121
+ "webrtc-mock": "^1.1.7"
117
122
  },
118
- "packageManager": "yarn@1.22.22"
123
+ "packageManager": "yarn@1.22.22",
124
+ "main:src": "src/index.ts"
119
125
  }
@@ -1 +0,0 @@
1
- "use strict";const f=require("events-constructor");require("@krivega/cancelable-promise");const k=require("debug"),W=require("repeated-calls"),G=require("xstate");var N=(n=>(n.PEER_CONNECTION="peerconnection",n.CONNECTING="connecting",n.SENDING="sending",n.PROGRESS="progress",n.ACCEPTED="accepted",n.CONFIRMED="confirmed",n.ENDED="ended",n.FAILED="failed",n.NEW_DTMF="newDTMF",n.NEW_INFO="newInfo",n.HOLD="hold",n.UNHOLD="unhold",n.MUTED="muted",n.UNMUTED="unmuted",n.REINVITE="reinvite",n.UPDATE="update",n.REFER="refer",n.REPLACES="replaces",n.SDP="sdp",n.ICE_CANDIDATE="icecandidate",n.GET_USER_MEDIA_FAILED="getusermediafailed",n.PEER_CONNECTION_CREATE_OFFER_FAILED="peerconnection:createofferfailed",n.PEER_CONNECTION_CREATE_ANSWER_FAILED="peerconnection:createanswerfailed",n.PEER_CONNECTION_SET_LOCAL_DESCRIPTION_FAILED="peerconnection:setlocaldescriptionfailed",n.PEER_CONNECTION_SET_REMOTE_DESCRIPTION_FAILED="peerconnection:setremotedescriptionfailed",n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n.PEER_CONNECTION_CONFIRMED="peerconnection:confirmed",n.PEER_CONNECTION_ONTRACK="peerconnection:ontrack",n.ENDED_FROM_SERVER="ended:fromserver",n))(N||{}),v=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))(v||{});const B=["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"],Z=["peerconnection:confirmed","peerconnection:ontrack","ended:fromserver"],q=[...B,...Z];function ee(n){return e=>`sip:${e}@${n}`}const te=(n,e)=>()=>Math.floor(Math.random()*(e-n))+n,x=n=>n.trim().replaceAll(" ","_"),ne=te(1e5,99999999),se=n=>n.some(t=>{const{kind:s}=t;return s==="video"}),ie=(n,e)=>{n.getVideoTracks().forEach(s=>{"contentHint"in s&&s.contentHint!==e&&(s.contentHint=e)})},y=(n,{directionVideo:e,directionAudio:t,contentHint:s}={})=>{if(!n||e==="recvonly"&&t==="recvonly")return;const i=t==="recvonly"?[]:n.getAudioTracks(),r=e==="recvonly"?[]:n.getVideoTracks(),a=[...i,...r],o=new MediaStream(a);return o.getTracks=()=>[...o.getAudioTracks(),...o.getVideoTracks()],s&&s!=="none"&&ie(o,s),o};class re{isPendingCall=!1;isPendingAnswer=!1;rtcSession;remoteStreams={};events;callConfiguration={};constructor(e){this.events=e}}var V=(n=>(n.BYE="Terminated",n.WEBRTC_ERROR="WebRTC Error",n.CANCELED="Canceled",n.REQUEST_TIMEOUT="Request Timeout",n.REJECTED="Rejected",n.REDIRECTED="Redirected",n.UNAVAILABLE="Unavailable",n.NOT_FOUND="Not Found",n.ADDRESS_INCOMPLETE="Address Incomplete",n.INCOMPATIBLE_SDP="Incompatible SDP",n.BAD_MEDIA_DESCRIPTION="Bad Media Description",n))(V||{});class ae{remoteStreams={};reset(){this.remoteStreams={}}generateStream(e,t){const{id:s}=e,i=this.remoteStreams[s]??new MediaStream;return t&&i.addTrack(t),i.addTrack(e),this.remoteStreams[s]=i,i}generateAudioStream(e){const{id:t}=e,s=this.remoteStreams[t]??new MediaStream;return s.addTrack(e),this.remoteStreams[t]=s,s}generateStreams(e){const t=[];return e.forEach((s,i)=>{if(s.kind==="audio")return;const r=s,a=e[i-1];let o;a?.kind==="audio"&&(o=a);const c=this.generateStream(r,o);t.push(c)}),t}generateAudioStreams(e){return e.map(t=>this.generateAudioStream(t))}}class oe extends re{remoteStreamsManager=new ae;disposers=new Set;constructor(e){super(e),e.on(N.FAILED,this.handleEnded),e.on(N.ENDED,this.handleEnded)}get requested(){return this.isPendingCall||this.isPendingAnswer}get connection(){return this.rtcSession?.connection}get isCallActive(){return this.rtcSession?.isEstablished()===!0}get establishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}startCall=async(e,t,{number:s,mediaStream:i,extraHeaders:r=[],ontrack:a,iceServers:o,directionVideo:c,directionAudio:g,contentHint:d,offerToReceiveAudio:E=!0,offerToReceiveVideo:l=!0,sendEncodings:S,onAddedTransceiver:I})=>(this.isPendingCall=!0,new Promise((C,P)=>{this.callConfiguration.number=s,this.callConfiguration.answer=!1,this.handleCall({ontrack:a}).then(C).catch(b=>{P(b)}),this.rtcSession=e.call(t(s),{extraHeaders:r,mediaStream:y(i,{directionVideo:c,directionAudio:g,contentHint:d}),directionVideo:c,directionAudio:g,pcConfig:{iceServers:o},rtcOfferConstraints:{offerToReceiveAudio:E,offerToReceiveVideo:l},sendEncodings:S,onAddedTransceiver:I}),this.subscribeToSessionEvents(this.rtcSession)}).finally(()=>{this.isPendingCall=!1}));async endCall(){const{rtcSession:e}=this;if(e&&!e.isEnded())return e.terminateAsync({cause:V.CANCELED}).finally(()=>{this.reset()});this.reset()}answerToIncomingCall=async(e,{mediaStream:t,ontrack:s,extraHeaders:i=[],iceServers:r,directionVideo:a,directionAudio:o,offerToReceiveAudio:c,offerToReceiveVideo:g,contentHint:d,sendEncodings:E,onAddedTransceiver:l})=>(this.isPendingAnswer=!0,new Promise((S,I)=>{try{const C=e();this.rtcSession=C,this.subscribeToSessionEvents(C),this.callConfiguration.answer=!0,this.callConfiguration.number=C.remote_identity.uri.user,this.handleCall({ontrack:s}).then(S).catch(b=>{I(b)});const P=y(t,{directionVideo:a,directionAudio:o,contentHint:d});C.answer({extraHeaders:i,directionVideo:a,directionAudio:o,mediaStream:P,pcConfig:{iceServers:r},rtcOfferConstraints:{offerToReceiveAudio:c,offerToReceiveVideo:g},sendEncodings:E,onAddedTransceiver:l})}catch(C){I(C)}}).finally(()=>{this.isPendingAnswer=!1}));getEstablishedRTCSession(){return this.rtcSession?.isEstablished()===!0?this.rtcSession:void 0}getCallConfiguration(){return{...this.callConfiguration}}getRemoteStreams(){if(!this.connection)return;const t=this.connection.getReceivers().map(({track:s})=>s);return se(t)?this.remoteStreamsManager.generateStreams(t):this.remoteStreamsManager.generateAudioStreams(t)}async replaceMediaStream(e,t){if(!this.rtcSession)throw new Error("No rtcSession established");const{contentHint:s}=t??{},i=y(e,{contentHint:s});if(i===void 0)throw new Error("No preparedMediaStream");return this.rtcSession.replaceMediaStream(i,t)}handleCall=async({ontrack:e})=>new Promise((t,s)=>{const i=()=>{this.events.on(N.PEER_CONNECTION,d),this.events.on(N.CONFIRMED,E)},r=()=>{this.events.off(N.PEER_CONNECTION,d),this.events.off(N.CONFIRMED,E)},a=()=>{this.events.on(N.FAILED,c),this.events.on(N.ENDED,c)},o=()=>{this.events.off(N.FAILED,c),this.events.off(N.ENDED,c)},c=l=>{r(),o(),s(l)};let g;const d=({peerconnection:l})=>{g=l;const S=I=>{this.events.trigger(N.PEER_CONNECTION_ONTRACK,l),e&&e(I)};l.ontrack=S,this.disposers.add(()=>{l.ontrack=null})},E=()=>{g!==void 0&&this.events.trigger(N.PEER_CONNECTION_CONFIRMED,g),r(),o(),t(g)};i(),a()});subscribeToSessionEvents(e){this.events.eachTriggers((t,s)=>{const i=B.find(r=>r===s);i&&(e.on(i,t),this.disposers.add(()=>{e.off(i,t)}))})}unsubscribeFromSessionEvents(){this.disposers.forEach(e=>{e()}),this.disposers.clear()}handleEnded=e=>{const{originator:t}=e;t===v.REMOTE&&this.events.trigger(N.ENDED_FROM_SERVER,e),this.reset()};reset=()=>{delete this.rtcSession,this.remoteStreamsManager.reset(),this.unsubscribeFromSessionEvents(),this.callConfiguration.number=void 0,this.callConfiguration.answer=!1}}class ce{events;strategy;constructor(e){this.events=new f(q),this.strategy=e??new oe(this.events)}get requested(){return this.strategy.requested}get connection(){return this.strategy.connection}get establishedRTCSession(){return this.strategy.establishedRTCSession}get isCallActive(){return this.strategy.isCallActive}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}setStrategy(e){this.strategy=e}startCall=async(...e)=>this.strategy.startCall(...e);endCall=async()=>this.strategy.endCall();answerToIncomingCall=async(...e)=>this.strategy.answerToIncomingCall(...e);getEstablishedRTCSession=()=>this.strategy.getEstablishedRTCSession();getCallConfiguration=()=>this.strategy.getCallConfiguration();getRemoteStreams=()=>this.strategy.getRemoteStreams();replaceMediaStream=async(...e)=>this.strategy.replaceMediaStream(...e)}const H="sip-connector",p=k(H),ge=()=>{k.enable(H)},Te=()=>{k.enable(`-${H}`)},he="Error decline with 603",de=1006,le=n=>typeof n=="object"&&n!==null&&"code"in n&&n.code===de,Ee=n=>n.message===he;var h=(n=>(n.CONTENT_TYPE="content-type",n.CONTENT_ENTER_ROOM="x-webrtc-enter-room",n.CONTENT_USE_LICENSE="X-WEBRTC-USE-LICENSE",n.PARTICIPANT_NAME="X-WEBRTC-PARTICIPANT-NAME",n.INPUT_CHANNELS="X-WEBRTC-INPUT-CHANNELS",n.OUTPUT_CHANNELS="X-WEBRTC-OUTPUT-CHANNELS",n.MAIN_CAM="X-WEBRTC-MAINCAM",n.MIC="X-WEBRTC-MIC",n.MEDIA_SYNC="X-WEBRTC-SYNC",n.MAIN_CAM_RESOLUTION="X-WEBRTC-MAINCAM-RESOLUTION",n.MEDIA_STATE="X-WEBRTC-MEDIA-STATE",n.MEDIA_TYPE="X-Vinteo-Media-Type",n.MAIN_CAM_STATE="X-Vinteo-MainCam-State",n.MIC_STATE="X-Vinteo-Mic-State",n.CONTENT_PARTICIPANT_STATE="X-WEBRTC-PARTSTATE",n.NOTIFY="X-VINTEO-NOTIFY",n.CONTENT_ENABLE_MEDIA_DEVICE="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE",n.CONTENT_SHARE_STATE="x-webrtc-share-state",n.MUST_STOP_PRESENTATION_P2P="x-webrtc-share-state: YOUMUSTSTOPSENDCONTENT",n.START_PRESENTATION_P2P="x-webrtc-share-state: YOUCANRECEIVECONTENT",n.STOP_PRESENTATION_P2P="x-webrtc-share-state: CONTENTEND",n.STOP_PRESENTATION="x-webrtc-share-state: STOPPRESENTATION",n.START_PRESENTATION="x-webrtc-share-state: LETMESTARTPRESENTATION",n.ENABLE_MAIN_CAM="X-WEBRTC-REQUEST-ENABLE-MEDIA-DEVICE: LETMESTARTMAINCAM",n))(h||{}),U=(n=>(n.AVAILABLE_SECOND_REMOTE_STREAM="YOUCANRECEIVECONTENT",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="CONTENTEND",n.MUST_STOP_PRESENTATION="YOUMUSTSTOPSENDCONTENT",n))(U||{}),w=(n=>(n.SPECTATOR="SPECTATOR",n.PARTICIPANT="PARTICIPANT",n))(w||{}),M=(n=>(n.ENTER_ROOM="application/vinteo.webrtc.roomname",n.MIC="application/vinteo.webrtc.mic",n.USE_LICENSE="application/vinteo.webrtc.uselic",n.PARTICIPANT_STATE="application/vinteo.webrtc.partstate",n.NOTIFY="application/vinteo.webrtc.notify",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(M||{}),_=(n=>(n.CHANNELS="application/vinteo.webrtc.channels",n.MEDIA_STATE="application/vinteo.webrtc.mediastate",n.REFUSAL="application/vinteo.webrtc.refusal",n.SHARE_STATE="application/vinteo.webrtc.sharedesktop",n.MAIN_CAM="application/vinteo.webrtc.maincam",n))(_||{}),m=(n=>(n.PAUSE_MAIN_CAM="PAUSEMAINCAM",n.RESUME_MAIN_CAM="RESUMEMAINCAM",n.MAX_MAIN_CAM_RESOLUTION="MAXMAINCAMRESOLUTION",n.ADMIN_STOP_MAIN_CAM="ADMINSTOPMAINCAM",n.ADMIN_START_MAIN_CAM="ADMINSTARTMAINCAM",n))(m||{}),L=(n=>(n.ADMIN_STOP_MIC="ADMINSTOPMIC",n.ADMIN_START_MIC="ADMINSTARTMIC",n))(L||{}),F=(n=>(n.ADMIN_SYNC_FORCED="1",n.ADMIN_SYNC_NOT_FORCED="0",n))(F||{}),Y=(n=>(n.AUDIO="AUDIO",n.VIDEO="VIDEO",n.AUDIOPLUSPRESENTATION="AUDIOPLUSPRESENTATION",n))(Y||{}),T=(n=>(n.CHANNELS_NOTIFY="channels:notify",n.PARTICIPANT_ADDED_TO_LIST_MODERATORS="participant:added-to-list-moderators",n.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS="participant:removed-from-list-moderators",n.PARTICIPANT_MOVE_REQUEST_TO_STREAM="participant:move-request-to-stream",n.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS="participant:move-request-to-spectators",n.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS="participant:move-request-to-participants",n.PARTICIPATION_ACCEPTING_WORD_REQUEST="participation:accepting-word-request",n.PARTICIPATION_CANCELLING_WORD_REQUEST="participation:cancelling-word-request",n.WEBCAST_STARTED="webcast:started",n.WEBCAST_STOPPED="webcast:stopped",n.ACCOUNT_CHANGED="account:changed",n.ACCOUNT_DELETED="account:deleted",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="conference:participant-token-issued",n.CHANNELS="channels",n.ENTER_ROOM="enterRoom",n.SHARE_STATE="shareState",n.MAIN_CAM_CONTROL="main-cam-control",n.USE_LICENSE="useLicense",n.ADMIN_START_MAIN_CAM="admin-start-main-cam",n.ADMIN_STOP_MAIN_CAM="admin-stop-main-cam",n.ADMIN_START_MIC="admin-start-mic",n.ADMIN_STOP_MIC="admin-stop-mic",n.ADMIN_FORCE_SYNC_MEDIA_STATE="admin-force-sync-media-state",n.AVAILABLE_SECOND_REMOTE_STREAM="availableSecondRemoteStream",n.NOT_AVAILABLE_SECOND_REMOTE_STREAM="notAvailableSecondRemoteStream",n.MUST_STOP_PRESENTATION="mustStopPresentation",n.NEW_DTMF="newDTMF",n))(T||{});const z=["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"];var A=(n=>(n.CHANNELS="channels",n.WEBCAST_STARTED="WebcastStarted",n.WEBCAST_STOPPED="WebcastStopped",n.ACCOUNT_CHANGED="accountChanged",n.ACCOUNT_DELETED="accountDeleted",n.ADDED_TO_LIST_MODERATORS="addedToListModerators",n.REMOVED_FROM_LIST_MODERATORS="removedFromListModerators",n.ACCEPTING_WORD_REQUEST="ParticipationRequestAccepted",n.CANCELLING_WORD_REQUEST="ParticipationRequestRejected",n.MOVE_REQUEST_TO_STREAM="ParticipantMovedToWebcast",n.CONFERENCE_PARTICIPANT_TOKEN_ISSUED="ConferenceParticipantTokenIssued",n))(A||{});class Se{events;connectionManager;callManager;constructor({connectionManager:e,callManager:t}){this.connectionManager=e,this.callManager=t,this.events=new f(z),this.subscribe()}async waitChannels(){return this.wait(T.CHANNELS)}async waitSyncMediaState(){return this.wait(T.ADMIN_FORCE_SYNC_MEDIA_STATE)}async sendDTMF(e){return new Promise((t,s)=>{const i=this.callManager.getEstablishedRTCSession();if(!i){s(new Error("No rtcSession established"));return}this.callManager.once("newDTMF",({originator:r})=>{r===v.LOCAL&&t()}),i.sendDTMF(e,{duration:120,interToneGap:600})})}async sendChannels({inputChannels:e,outputChannels:t}){const s=this.callManager.getEstablishedRTCSession();if(!s)throw new Error("No rtcSession established");const i=`${h.INPUT_CHANNELS}: ${e}`,r=`${h.OUTPUT_CHANNELS}: ${t}`,a=[i,r];return s.sendInfo(_.CHANNELS,void 0,{extraHeaders:a})}async sendMediaState({cam:e,mic:t},s={}){const i=this.callManager.getEstablishedRTCSession();if(!i)throw new Error("No rtcSession established");const r=`${h.MEDIA_STATE}: currentstate`,a=`${h.MAIN_CAM_STATE}: ${Number(e)}`,o=`${h.MIC_STATE}: ${Number(t)}`,c=[r,a,o];return i.sendInfo(_.MEDIA_STATE,void 0,{noTerminateWhenError:!0,...s,extraHeaders:c})}async sendRefusalToTurnOn(e,t={}){const s=this.callManager.getEstablishedRTCSession();if(!s)throw new Error("No rtcSession established");const a=e==="mic"?0:1,c=[`${h.MEDIA_TYPE}: ${a}`];return s.sendInfo(_.REFUSAL,void 0,{noTerminateWhenError:!0,...t,extraHeaders:c})}async sendRefusalToTurnOnMic(e={}){if(!this.callManager.getEstablishedRTCSession())throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("mic",{noTerminateWhenError:!0,...e})}async sendRefusalToTurnOnCam(e={}){if(!this.callManager.getEstablishedRTCSession())throw new Error("No rtcSession established");return this.sendRefusalToTurnOn("cam",{noTerminateWhenError:!0,...e})}async sendMustStopPresentationP2P(){const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");await e.sendInfo(_.SHARE_STATE,void 0,{extraHeaders:[h.MUST_STOP_PRESENTATION_P2P]})}async sendStoppedPresentationP2P(){const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");await e.sendInfo(_.SHARE_STATE,void 0,{extraHeaders:[h.STOP_PRESENTATION_P2P]})}async sendStoppedPresentation(){const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");await e.sendInfo(_.SHARE_STATE,void 0,{extraHeaders:[h.STOP_PRESENTATION]})}async askPermissionToStartPresentationP2P(){const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");await e.sendInfo(_.SHARE_STATE,void 0,{extraHeaders:[h.START_PRESENTATION_P2P]})}async askPermissionToStartPresentation(){const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");await e.sendInfo(_.SHARE_STATE,void 0,{extraHeaders:[h.START_PRESENTATION]})}async askPermissionToEnableCam(e={}){const t=this.callManager.getEstablishedRTCSession();if(!t)throw new Error("No rtcSession established");const s=[h.ENABLE_MAIN_CAM];return t.sendInfo(_.MAIN_CAM,void 0,{noTerminateWhenError:!0,...e,extraHeaders:s}).catch(i=>{if(Ee(i))throw i})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("sipEvent",this.handleSipEvent),this.callManager.on("newInfo",this.handleNewInfo),this.callManager.on("newDTMF",e=>{this.events.trigger("newDTMF",e)})}handleSipEvent=({request:e})=>{this.maybeHandleNotify(e)};maybeHandleNotify=e=>{try{const t=e.getHeader(h.NOTIFY);if(t){const s=JSON.parse(t);this.handleNotify(s)}}catch(t){p("error parse notify",t)}};handleNotify=e=>{switch(e.cmd){case A.CHANNELS:{const t=e;this.triggerChannelsNotify(t);break}case A.WEBCAST_STARTED:{const t=e;this.triggerWebcastStartedNotify(t);break}case A.WEBCAST_STOPPED:{const t=e;this.triggerWebcastStoppedNotify(t);break}case A.ADDED_TO_LIST_MODERATORS:{const t=e;this.triggerAddedToListModeratorsNotify(t);break}case A.REMOVED_FROM_LIST_MODERATORS:{const t=e;this.triggerRemovedFromListModeratorsNotify(t);break}case A.ACCEPTING_WORD_REQUEST:{const t=e;this.triggerParticipationAcceptingWordRequest(t);break}case A.CANCELLING_WORD_REQUEST:{const t=e;this.triggerParticipationCancellingWordRequest(t);break}case A.MOVE_REQUEST_TO_STREAM:{const t=e;this.triggerParticipantMoveRequestToStream(t);break}case A.ACCOUNT_CHANGED:{this.triggerAccountChangedNotify();break}case A.ACCOUNT_DELETED:{this.triggerAccountDeletedNotify();break}case A.CONFERENCE_PARTICIPANT_TOKEN_ISSUED:{const t=e;this.triggerConferenceParticipantTokenIssued(t);break}default:p("unknown cmd",e)}};handleNewInfo=e=>{const{originator:t}=e;if(t!==v.REMOTE)return;const{request:s}=e,i=s.getHeader(h.CONTENT_TYPE);if(i!==void 0)switch(i){case M.ENTER_ROOM:{this.triggerEnterRoom(s),this.maybeTriggerChannels(s);break}case M.NOTIFY:{this.maybeHandleNotify(s);break}case M.SHARE_STATE:{this.triggerShareState(s);break}case M.MAIN_CAM:{this.triggerMainCamControl(s);break}case M.MIC:{this.triggerMicControl(s);break}case M.USE_LICENSE:{this.triggerUseLicense(s);break}case M.PARTICIPANT_STATE:{this.maybeTriggerParticipantMoveRequest(s);break}}};triggerChannelsNotify=e=>{const t=e.input,s=e.output,i={inputChannels:t,outputChannels:s};this.events.trigger(T.CHANNELS_NOTIFY,i)};triggerWebcastStartedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(T.WEBCAST_STARTED,s)};triggerWebcastStoppedNotify=({body:{conference:e,type:t}})=>{const s={conference:e,type:t};this.events.trigger(T.WEBCAST_STOPPED,s)};triggerAddedToListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_ADDED_TO_LIST_MODERATORS,t)};triggerRemovedFromListModeratorsNotify=({conference:e})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_REMOVED_FROM_LIST_MODERATORS,t)};triggerParticipationAcceptingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPATION_ACCEPTING_WORD_REQUEST,t)};triggerParticipationCancellingWordRequest=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPATION_CANCELLING_WORD_REQUEST,t)};triggerParticipantMoveRequestToStream=({body:{conference:e}})=>{const t={conference:e};this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_STREAM,t)};triggerAccountChangedNotify=()=>{this.events.trigger(T.ACCOUNT_CHANGED,void 0)};triggerAccountDeletedNotify=()=>{this.events.trigger(T.ACCOUNT_DELETED,void 0)};triggerConferenceParticipantTokenIssued=({body:{conference:e,participant:t,jwt:s}})=>{const i={conference:e,participant:t,jwt:s};this.events.trigger(T.CONFERENCE_PARTICIPANT_TOKEN_ISSUED,i)};maybeTriggerChannels=e=>{const t=e.getHeader(h.INPUT_CHANNELS),s=e.getHeader(h.OUTPUT_CHANNELS);if(t&&s){const i={inputChannels:t,outputChannels:s};this.events.trigger(T.CHANNELS,i)}};triggerEnterRoom=e=>{const t=e.getHeader(h.CONTENT_ENTER_ROOM),s=e.getHeader(h.PARTICIPANT_NAME);this.events.trigger(T.ENTER_ROOM,{room:t,participantName:s})};triggerShareState=e=>{const t=e.getHeader(h.CONTENT_SHARE_STATE);if(t!==void 0)switch(t){case U.AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(T.AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case U.NOT_AVAILABLE_SECOND_REMOTE_STREAM:{this.events.trigger(T.NOT_AVAILABLE_SECOND_REMOTE_STREAM,void 0);break}case U.MUST_STOP_PRESENTATION:{this.events.trigger(T.MUST_STOP_PRESENTATION,void 0);break}}};maybeTriggerParticipantMoveRequest=e=>{const t=e.getHeader(h.CONTENT_PARTICIPANT_STATE);t===w.SPECTATOR&&this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_SPECTATORS,void 0),t===w.PARTICIPANT&&this.events.trigger(T.PARTICIPANT_MOVE_REQUEST_TO_PARTICIPANTS,void 0)};triggerMainCamControl=e=>{const t=e.getHeader(h.MAIN_CAM),s=e.getHeader(h.MEDIA_SYNC),i=s===F.ADMIN_SYNC_FORCED;if(t===m.ADMIN_START_MAIN_CAM){this.events.trigger(T.ADMIN_START_MAIN_CAM,{isSyncForced:i});return}if(t===m.ADMIN_STOP_MAIN_CAM){this.events.trigger(T.ADMIN_STOP_MAIN_CAM,{isSyncForced:i});return}(t===m.RESUME_MAIN_CAM||t===m.PAUSE_MAIN_CAM)&&s!==void 0&&this.events.trigger(T.ADMIN_FORCE_SYNC_MEDIA_STATE,{isSyncForced:i});const r=e.getHeader(h.MAIN_CAM_RESOLUTION);this.events.trigger(T.MAIN_CAM_CONTROL,{mainCam:t,resolutionMainCam:r})};triggerMicControl=e=>{const t=e.getHeader(h.MIC),i=e.getHeader(h.MEDIA_SYNC)===F.ADMIN_SYNC_FORCED;t===L.ADMIN_START_MIC?this.events.trigger(T.ADMIN_START_MIC,{isSyncForced:i}):t===L.ADMIN_STOP_MIC&&this.events.trigger(T.ADMIN_STOP_MIC,{isSyncForced:i})};triggerUseLicense=e=>{const t=e.getHeader(h.CONTENT_USE_LICENSE);this.events.trigger(T.USE_LICENSE,t)}}var R=(n=>(n.START_PRESENTATION="presentation:start",n.STARTED_PRESENTATION="presentation:started",n.END_PRESENTATION="presentation:end",n.ENDED_PRESENTATION="presentation:ended",n.FAILED_PRESENTATION="presentation:failed",n))(R||{});const Q=["presentation:start","presentation:started","presentation:end","presentation:ended","presentation:failed"],Ce=1,Ne=n=>W.hasCanceledError(n);class ue{events;promisePendingStartPresentation;promisePendingStopPresentation;streamPresentationCurrent;cancelableSendPresentationWithRepeatedCalls;callManager;constructor({callManager:e}){this.callManager=e,this.events=new f(Q),this.subscribe()}get isPendingPresentation(){return!!this.promisePendingStartPresentation||!!this.promisePendingStopPresentation}async startPresentation(e,t,{isNeedReinvite:s,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:o}={},c){const g=this.getRtcSessionProtected();if(this.streamPresentationCurrent)throw new Error("Presentation is already started");return this.sendPresentationWithDuplicatedCalls(e,{rtcSession:g,stream:t,presentationOptions:{isNeedReinvite:s,maxBitrate:i,contentHint:r,sendEncodings:a,onAddedTransceiver:o},options:c})}async stopPresentation(e){this.cancelSendPresentationWithRepeatedCalls();const t=this.streamPresentationCurrent;let s=this.promisePendingStartPresentation??Promise.resolve(void 0);const i=this.callManager.getEstablishedRTCSession();return i&&t?s=e().then(async()=>i.stopPresentation(t)).catch(r=>{throw this.events.trigger(R.FAILED_PRESENTATION,r),r}):t&&this.events.trigger(R.ENDED_PRESENTATION,t),this.promisePendingStopPresentation=s,s.finally(()=>{this.resetPresentation()})}async updatePresentation(e,t,{contentHint:s,sendEncodings:i,onAddedTransceiver:r}={}){const a=this.getRtcSessionProtected();if(!this.streamPresentationCurrent)throw new Error("Presentation has not started yet");return this.promisePendingStartPresentation&&await this.promisePendingStartPresentation,this.sendPresentation(e,a,t,{contentHint:s,isNeedReinvite:!1,sendEncodings:i,onAddedTransceiver:r})}cancelSendPresentationWithRepeatedCalls(){this.cancelableSendPresentationWithRepeatedCalls?.cancel()}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.callManager.on("presentation:start",e=>{this.events.trigger(R.START_PRESENTATION,e)}),this.callManager.on("presentation:started",e=>{this.events.trigger(R.STARTED_PRESENTATION,e)}),this.callManager.on("presentation:end",e=>{this.events.trigger(R.END_PRESENTATION,e)}),this.callManager.on("presentation:ended",e=>{this.events.trigger(R.ENDED_PRESENTATION,e)}),this.callManager.on("presentation:failed",e=>{this.events.trigger(R.FAILED_PRESENTATION,e)}),this.callManager.on("failed",this.handleEnded),this.callManager.on("ended",this.handleEnded)}async sendPresentationWithDuplicatedCalls(e,{rtcSession:t,stream:s,presentationOptions:i,options:r={callLimit:Ce}}){const a=async()=>this.sendPresentation(e,t,s,i),o=()=>!!this.streamPresentationCurrent;return this.cancelableSendPresentationWithRepeatedCalls=W.repeatedCallsAsync({targetFunction:a,isComplete:o,isRejectAsValid:!0,...r}),this.cancelableSendPresentationWithRepeatedCalls.then(c=>c)}async sendPresentation(e,t,s,{isNeedReinvite:i=!0,contentHint:r="detail",sendEncodings:a,onAddedTransceiver:o}){const c=y(s,{contentHint:r});if(c===void 0)throw new Error("No streamPresentationTarget");this.streamPresentationCurrent=c;const g=e().then(async()=>t.startPresentation(c,i,{sendEncodings:a,onAddedTransceiver:o})).then(()=>s).catch(d=>{throw this.removeStreamPresentationCurrent(),this.events.trigger(R.FAILED_PRESENTATION,d),d});return this.promisePendingStartPresentation=g,g.finally(()=>{this.promisePendingStartPresentation=void 0})}getRtcSessionProtected=()=>{const e=this.callManager.getEstablishedRTCSession();if(!e)throw new Error("No rtcSession established");return e};handleEnded=()=>{this.reset()};reset(){this.cancelSendPresentationWithRepeatedCalls(),this.resetPresentation()}resetPresentation(){this.removeStreamPresentationCurrent(),this.promisePendingStartPresentation=void 0,this.promisePendingStopPresentation=void 0}removeStreamPresentationCurrent(){delete this.streamPresentationCurrent}}class Ae{data={};getUa;constructor(e){this.getUa=e.getUa}isConfigured(){return this.getUa()!==void 0}get(){return{...this.data}}set(e){this.data={...e}}update(e,t){this.data[e]=t}clear(){this.data={}}isRegister(){return this.data.register===!0}getSipServerUrl(){return this.data.sipServerUrl}getDisplayName(){return this.data.displayName}getUser(){return this.data.user}getPassword(){return this.data.password}isRegisterEnabled(){return this.data.register===!0}}var u=(n=>(n.CONNECTING="connecting",n.CONNECTED="connected",n.DISCONNECTED="disconnected",n.NEW_RTC_SESSION="newRTCSession",n.REGISTERED="registered",n.UNREGISTERED="unregistered",n.REGISTRATION_FAILED="registrationFailed",n.NEW_MESSAGE="newMessage",n.SIP_EVENT="sipEvent",n))(u||{});const X=["connecting","connected","disconnected","newRTCSession","registered","unregistered","registrationFailed","newMessage","sipEvent"],J=[...X],_e=3;class Ie{cancelableConnectWithRepeatedCalls;JsSIP;events;uaFactory;stateMachine;registrationManager;getUa;setUa;getConnectionConfiguration;setConnectionConfiguration;updateConnectionConfiguration;setSipServerUrl;setSocket;constructor(e){this.JsSIP=e.JsSIP,this.events=e.events,this.uaFactory=e.uaFactory,this.stateMachine=e.stateMachine,this.registrationManager=e.registrationManager,this.getUa=e.getUa,this.setUa=e.setUa,this.getConnectionConfiguration=e.getConnectionConfiguration,this.setConnectionConfiguration=e.setConnectionConfiguration,this.updateConnectionConfiguration=e.updateConnectionConfiguration,this.setSipServerUrl=e.setSipServerUrl,this.setSocket=e.setSocket}connect=async(e,t)=>(this.cancelRequests(),this.connectWithDuplicatedCalls(e,t));set=async({displayName:e})=>new Promise((t,s)=>{const i=this.getUa();if(!i){s(new Error("this.ua is not initialized"));return}let r=!1;const a=this.getConnectionConfiguration();e!==void 0&&e!==a.displayName&&(r=i.set("display_name",x(e)),this.updateConnectionConfiguration("displayName",e));const o=r;o?t(o):s(new Error("nothing changed"))});disconnect=async()=>{const e=new Promise(s=>{this.events.once(u.DISCONNECTED,()=>{s()})}),t=this.getUa();return t?t.stop():this.events.trigger(u.DISCONNECTED,void 0),e.finally(()=>{this.setUa(void 0),this.stateMachine.reset()})};cancelRequests(){this.cancelConnectWithRepeatedCalls()}connectWithDuplicatedCalls=async(e,{callLimit:t=_e}={})=>{const s=async()=>this.connectInner(e),i=r=>{const c=this.getUa()?.isConnected()===!0&&this.hasEqualConnectionConfiguration(e),g=r!=null&&!le(r);return c||g};return this.stateMachine.startConnect(),this.cancelableConnectWithRepeatedCalls=W.repeatedCallsAsync({targetFunction:s,isComplete:i,callLimit:t,isRejectAsValid:!0,isCheckBeforeCall:!1}),this.cancelableConnectWithRepeatedCalls.then(r=>{if(r instanceof this.JsSIP.UA)return r;throw r})};hasEqualConnectionConfiguration(e){const{configuration:t}=this.uaFactory.createConfiguration(e),i=this.getUa()?.configuration;return i?i.password===t.password&&i.register===t.register&&i.uri.toString()===t.uri&&i.display_name===t.display_name&&i.user_agent===t.user_agent&&i.sockets===t.sockets&&i.session_timers===t.session_timers&&i.register_expires===t.register_expires&&i.connection_recovery_min_interval===t.connection_recovery_min_interval&&i.connection_recovery_max_interval===t.connection_recovery_max_interval:!1}connectInner=async e=>this.initUa(e).then(async()=>this.start());initUa=async({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:g,userAgent:d,displayName:E="",register:l=!1,extraHeaders:S=[]})=>{this.stateMachine.startInitUa(),this.setConnectionConfiguration({sipServerUrl:s,displayName:E,register:l,user:e,password:t}),this.getUa()&&await this.disconnect();const{ua:C,helpers:P}=this.uaFactory.createUAWithConfiguration({user:e,password:t,sipServerUrl:s,sipWebSocketServerURL:i,displayName:E,register:l,sessionTimers:a,registerExpires:o,connectionRecoveryMinInterval:c,connectionRecoveryMaxInterval:g,userAgent:d,remoteAddress:r,extraHeaders:S},this.events);return this.setUa(C),this.setSipServerUrl(P.getSipServerUrl),this.setSocket(P.socket),C};start=async()=>new Promise((e,t)=>{const s=this.getUa();if(!s){t(new Error("this.ua is not initialized"));return}let i;i=((c,g)=>{if(this.getConnectionConfiguration().register===!0)return this.registrationManager.subscribeToStartEvents(c,g);const E=u.CONNECTED,l=[u.DISCONNECTED];return this.events.on(E,c),l.forEach(S=>{this.events.on(S,g)}),()=>{this.events.off(E,c),l.forEach(S=>{this.events.off(S,g)})}})(()=>{i?.(),e(s)},c=>{i?.(),t(c)}),s.start()});cancelConnectWithRepeatedCalls(){this.cancelableConnectWithRepeatedCalls?.cancel()}}var K=(n=>(n.START_CONNECT="START_CONNECT",n.START_INIT_UA="START_INIT_UA",n.UA_CONNECTED="UA_CONNECTED",n.UA_REGISTERED="UA_REGISTERED",n.UA_UNREGISTERED="UA_UNREGISTERED",n.UA_DISCONNECTED="UA_DISCONNECTED",n.CONNECTION_FAILED="CONNECTION_FAILED",n.RESET="RESET",n))(K||{});const Re=G.setup({types:{context:{},events:{}},actions:{logTransition:(n,e)=>{p(`State transition: ${e.from} -> ${e.to} (${e.event})`)},logStateChange:(n,e)=>{p("ConnectionStateMachine state changed",e.state)}}}).createMachine({id:"connection",initial:"idle",context:{},states:{idle:{entry:{type:"logStateChange",params:{state:"idle"}},on:{START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"idle",to:"connecting",event:"START_CONNECT"}}}}},connecting:{entry:{type:"logStateChange",params:{state:"connecting"}},on:{START_INIT_UA:{target:"initializing",actions:{type:"logTransition",params:{from:"connecting",to:"initializing",event:"START_INIT_UA"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connecting",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connecting",to:"failed",event:"CONNECTION_FAILED"}}}}},initializing:{entry:{type:"logStateChange",params:{state:"initializing"}},on:{UA_CONNECTED:{target:"connected",actions:{type:"logTransition",params:{from:"initializing",to:"connected",event:"UA_CONNECTED"}}},UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"initializing",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"initializing",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"initializing",to:"failed",event:"CONNECTION_FAILED"}}}}},connected:{entry:{type:"logStateChange",params:{state:"connected"}},on:{UA_REGISTERED:{target:"registered",actions:{type:"logTransition",params:{from:"connected",to:"registered",event:"UA_REGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"connected",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"connected",to:"failed",event:"CONNECTION_FAILED"}}}}},registered:{entry:{type:"logStateChange",params:{state:"registered"}},on:{UA_UNREGISTERED:{target:"connected",actions:{type:"logTransition",params:{from:"registered",to:"connected",event:"UA_UNREGISTERED"}}},UA_DISCONNECTED:{target:"disconnected",actions:{type:"logTransition",params:{from:"registered",to:"disconnected",event:"UA_DISCONNECTED"}}},CONNECTION_FAILED:{target:"failed",actions:{type:"logTransition",params:{from:"registered",to:"failed",event:"CONNECTION_FAILED"}}}}},disconnected:{entry:{type:"logStateChange",params:{state:"disconnected"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"disconnected",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"disconnected",to:"connecting",event:"START_CONNECT"}}}}},failed:{entry:{type:"logStateChange",params:{state:"failed"}},on:{RESET:{target:"idle",actions:{type:"logTransition",params:{from:"failed",to:"idle",event:"RESET"}}},START_CONNECT:{target:"connecting",actions:{type:"logTransition",params:{from:"failed",to:"connecting",event:"START_CONNECT"}}}}}}});class Me{actor;stateChangeListeners=new Set;events;unsubscribeFromEvents;actorSubscription;constructor(e){this.events=e,this.actor=G.createActor(Re),this.actorSubscription=this.actor.subscribe(t=>{const s=t.value;this.stateChangeListeners.forEach(i=>{i(s)})}),this.actor.start(),this.subscribeToEvents()}get state(){return this.actor.getSnapshot().value}get isIdle(){return this.hasState("idle")}get isConnecting(){return this.hasState("connecting")}get isInitializing(){return this.hasState("initializing")}get isConnected(){return this.hasState("connected")}get isRegistered(){return this.hasState("registered")}get isDisconnected(){return this.hasState("disconnected")}get isFailed(){return this.hasState("failed")}get isPending(){return this.isConnecting||this.isInitializing}get isPendingConnect(){return this.isConnecting}get isPendingInitUa(){return this.isInitializing}get isActiveConnection(){return this.isConnected||this.isRegistered}startConnect(){this.toStartConnect()}startInitUa(){this.toStartInitUa()}reset(){this.toIdle()}destroy(){this.unsubscribeFromEvents?.(),this.actorSubscription?.unsubscribe(),this.actor.stop()}onStateChange(e){return this.stateChangeListeners.add(e),()=>{this.stateChangeListeners.delete(e)}}canTransition(e){return this.actor.getSnapshot().can({type:e})}getValidEvents(){return Object.values(K).filter(e=>this.canTransition(e))}hasState(e){return this.actor.getSnapshot().matches(e)}sendEvent(e){const t=this.actor.getSnapshot(),s={type:e};if(!t.can(s)){p(`Invalid transition: ${s.type} from ${this.state}. Event cannot be processed in current state.`);return}this.actor.send(s)}toStartConnect=()=>{this.sendEvent("START_CONNECT")};toStartInitUa=()=>{this.sendEvent("START_INIT_UA")};toConnected=()=>{this.sendEvent("UA_CONNECTED")};toRegistered=()=>{this.sendEvent("UA_REGISTERED")};toUnregistered=()=>{this.sendEvent("UA_UNREGISTERED")};toDisconnected=()=>{this.sendEvent("UA_DISCONNECTED")};toFailed=()=>{this.sendEvent("CONNECTION_FAILED")};toIdle=()=>{this.sendEvent("RESET")};subscribeToEvents(){this.events.on("connected",this.toConnected),this.events.on("registered",this.toRegistered),this.events.on("unregistered",this.toUnregistered),this.events.on("disconnected",this.toDisconnected),this.events.on("registrationFailed",this.toFailed),this.unsubscribeFromEvents=()=>{this.events.off("connected",this.toConnected),this.events.off("registered",this.toRegistered),this.events.off("unregistered",this.toUnregistered),this.events.off("disconnected",this.toDisconnected),this.events.off("registrationFailed",this.toFailed)}}}class pe{events;getUaProtected;constructor(e){this.events=e.events,this.getUaProtected=e.getUaProtected}async register(){const e=this.getUaProtected();return new Promise((t,s)=>{e.on(u.REGISTERED,t),e.on(u.REGISTRATION_FAILED,s),e.register()})}async unregister(){const e=this.getUaProtected();return new Promise(t=>{e.on(u.UNREGISTERED,t),e.unregister()})}async tryRegister(){try{await this.unregister()}catch(e){p("tryRegister",e)}return this.register()}subscribeToStartEvents(e,t){const s=u.REGISTERED,i=[u.REGISTRATION_FAILED,u.DISCONNECTED];return this.events.on(s,e),i.forEach(r=>{this.events.on(r,t)}),()=>{this.events.off(s,e),i.forEach(r=>{this.events.off(r,t)})}}}class Pe{uaFactory;getUaProtected;constructor(e){this.uaFactory=e.uaFactory,this.getUaProtected=e.getUaProtected}async sendOptions(e,t,s){const i=this.getUaProtected();return new Promise((r,a)=>{try{i.sendOptions(e,t,{extraHeaders:s,eventHandlers:{succeeded:()=>{r()},failed:a}})}catch(o){a(o)}})}async ping(e,t){const i=this.getUaProtected().configuration.uri;return this.sendOptions(i,e,t)}async checkTelephony({userAgent:e,displayName:t,sipServerUrl:s,sipWebSocketServerURL:i,remoteAddress:r,extraHeaders:a}){return new Promise((o,c)=>{const{configuration:g}=this.uaFactory.createConfiguration({sipWebSocketServerURL:i,displayName:t,userAgent:e,sipServerUrl:s}),d=this.uaFactory.createUA({...g,remoteAddress:r,extraHeaders:a}),E=()=>{const S=new Error("Telephony is not available");c(S)};d.once(u.DISCONNECTED,E);const l=()=>{d.removeAllListeners(),d.once(u.DISCONNECTED,()=>{o()}),d.stop()};d.once(u.CONNECTED,l),d.start()})}}const me=n=>{const e=[];return n!==void 0&&n!==""&&e.push(`X-Vinteo-Remote: ${n}`),e};class O{JsSIP;constructor(e){this.JsSIP=e}static isRegisteredUA(e){return!!e&&e.isRegistered()}static validateConfiguration({register:e,password:t,user:s,sipServerUrl:i,sipWebSocketServerURL:r}){if(!i)throw new Error("sipServerUrl is required");if(!r)throw new Error("sipWebSocketServerURL is required");if(e&&(t===void 0||t===""))throw new Error("password is required for authorized connection");if(e&&(s===void 0||s===""))throw new Error("user is required for authorized connection")}static resolveAuthorizationUser(e,t){return e&&t!==void 0&&t.trim()!==""?t.trim():`${ne()}`}static buildExtraHeaders(e,t){const s=e!==void 0&&e!==""?me(e):[];return t===void 0?s:[...s,...t]}createConfiguration({user:e,password:t,sipWebSocketServerURL:s,displayName:i="",sipServerUrl:r,register:a=!1,sessionTimers:o=!1,registerExpires:c=300,connectionRecoveryMinInterval:g=2,connectionRecoveryMaxInterval:d=6,userAgent:E}){O.validateConfiguration({register:a,password:t,user:e,sipServerUrl:r,sipWebSocketServerURL:s});const l=O.resolveAuthorizationUser(a,e),S=ee(r),I=S(l),C=new this.JsSIP.WebSocketInterface(s);return{configuration:{password:t,register:a,uri:I,display_name:x(i),user_agent:E,sdpSemantics:"unified-plan",sockets:[C],session_timers:o,register_expires:c,connection_recovery_min_interval:g,connection_recovery_max_interval:d},helpers:{socket:C,getSipServerUrl:S}}}createUA({remoteAddress:e,extraHeaders:t,...s}){const i=new this.JsSIP.UA(s),r=O.buildExtraHeaders(e,t);return r.length>0&&i.registrator().setExtraHeaders(r),i}createUAWithConfiguration(e,t){const{configuration:s,helpers:i}=this.createConfiguration(e),r=this.createUA({...s,remoteAddress:e.remoteAddress,extraHeaders:e.extraHeaders});return t.eachTriggers((a,o)=>{const c=X.find(g=>g===o);c&&r.on(c,a)}),{ua:r,helpers:i}}}class Oe{events;ua;socket;uaFactory;registrationManager;stateMachine;connectionFlow;sipOperations;configurationManager;JsSIP;constructor({JsSIP:e}){this.JsSIP=e,this.events=new f(J),this.uaFactory=new O(e),this.registrationManager=new pe({events:this.events,getUaProtected:this.getUaProtected}),this.stateMachine=new Me(this.events),this.configurationManager=new Ae({getUa:this.getUa}),this.sipOperations=new Pe({uaFactory:this.uaFactory,getUaProtected:this.getUaProtected}),this.connectionFlow=new Ie({JsSIP:this.JsSIP,events:this.events,uaFactory:this.uaFactory,stateMachine:this.stateMachine,registrationManager:this.registrationManager,getUa:this.getUa,getConnectionConfiguration:this.getConnectionConfiguration,setConnectionConfiguration:t=>{this.configurationManager.set(t)},updateConnectionConfiguration:(t,s)=>{this.configurationManager.update(t,s)},setUa:t=>{this.ua=t},setSipServerUrl:t=>{this.getSipServerUrl=t},setSocket:t=>{this.socket=t}})}get requested(){return this.stateMachine.isPending}get isPendingConnect(){return this.stateMachine.isPendingConnect}get isPendingInitUa(){return this.stateMachine.isPendingInitUa}get connectionState(){return this.stateMachine.state}get isRegistered(){return O.isRegisteredUA(this.ua)}get isRegisterConfig(){return this.configurationManager.isRegister()}connect=async(e,t)=>this.connectionFlow.connect(e,t);set=async({displayName:e})=>this.connectionFlow.set({displayName:e});disconnect=async()=>this.connectionFlow.disconnect();async register(){return this.registrationManager.register()}async unregister(){return this.registrationManager.unregister()}tryRegister=async()=>this.registrationManager.tryRegister();sendOptions=async(e,t,s)=>this.sipOperations.sendOptions(e,t,s);ping=async(e,t)=>this.sipOperations.ping(e,t);checkTelephony=async e=>this.sipOperations.checkTelephony(e);on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}isConfigured(){return this.configurationManager.isConfigured()}getConnectionConfiguration=()=>this.configurationManager.get();destroy(){this.stateMachine.destroy()}getSipServerUrl=e=>e;getUaProtected=()=>{if(!this.ua)throw new Error("UA not initialized");return this.ua};getUa=()=>this.ua}var D=(n=>(n.INCOMING_CALL="incomingCall",n.DECLINED_INCOMING_CALL="declinedIncomingCall",n.TERMINATED_INCOMING_CALL="terminatedIncomingCall",n.FAILED_INCOMING_CALL="failedIncomingCall",n))(D||{}),$=(n=>(n.LOCAL="local",n.REMOTE="remote",n.SYSTEM="system",n))($||{});const j=["incomingCall","declinedIncomingCall","terminatedIncomingCall","failedIncomingCall"],fe=486,De=487;class ve{events;incomingRTCSession;connectionManager;constructor(e){this.connectionManager=e,this.events=new f(j),this.start()}get remoteCallerData(){return{displayName:this.incomingRTCSession?.remote_identity.display_name,host:this.incomingRTCSession?.remote_identity.uri.host,incomingNumber:this.incomingRTCSession?.remote_identity.uri.user,rtcSession:this.incomingRTCSession}}get isAvailableIncomingCall(){return!!this.incomingRTCSession}start(){this.subscribe()}stop(){this.unsubscribe(),this.removeIncomingSession()}getIncomingRTCSession=()=>{const{incomingRTCSession:e}=this;if(!e)throw new Error("No incomingRTCSession");return e};extractIncomingRTCSession=()=>{const e=this.getIncomingRTCSession();return this.removeIncomingSession(),e};async declineToIncomingCall({statusCode:e=De}={}){return new Promise((t,s)=>{try{const i=this.getIncomingRTCSession(),r=this.remoteCallerData;this.removeIncomingSession(),this.events.trigger(D.DECLINED_INCOMING_CALL,r),i.terminate({status_code:e}),t()}catch(i){s(i)}})}async busyIncomingCall(){return this.declineToIncomingCall({statusCode:fe})}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}subscribe(){this.connectionManager.on("newRTCSession",this.handleNewRTCSession)}unsubscribe(){this.connectionManager.off("newRTCSession",this.handleNewRTCSession)}handleNewRTCSession=({originator:e,session:t})=>{e===$.REMOTE&&this.setIncomingSession(t)};setIncomingSession(e){this.incomingRTCSession=e;const t=this.remoteCallerData;e.on("failed",s=>{this.removeIncomingSession(),s.originator===$.LOCAL?this.events.trigger(D.TERMINATED_INCOMING_CALL,t):this.events.trigger(D.FAILED_INCOMING_CALL,t)}),this.events.trigger(D.INCOMING_CALL,t)}removeIncomingSession(){delete this.incomingRTCSession}}const ye=J.map(n=>`connection:${n}`),Ue=q.map(n=>`call:${n}`),be=z.map(n=>`api:${n}`),we=j.map(n=>`incoming-call:${n}`),Le=Q.map(n=>`presentation:${n}`),Fe=[...ye,...Ue,...be,...we,...Le];class $e{events;connectionManager;callManager;apiManager;incomingCallManager;presentationManager;constructor({JsSIP:e}){this.events=new f(Fe),this.connectionManager=new Oe({JsSIP:e}),this.callManager=new ce,this.apiManager=new Se({connectionManager:this.connectionManager,callManager:this.callManager}),this.incomingCallManager=new ve(this.connectionManager),this.presentationManager=new ue({callManager:this.callManager}),this.subscribe()}get requestedConnection(){return this.connectionManager.requested}get isPendingConnect(){return this.connectionManager.isPendingConnect}get isPendingInitUa(){return this.connectionManager.isPendingInitUa}get connectionState(){return this.connectionManager.connectionState}get isRegistered(){return this.connectionManager.isRegistered}get isRegisterConfig(){return this.connectionManager.isRegisterConfig}get socket(){return this.connectionManager.socket}get requestedCall(){return this.callManager.requested}get connection(){return this.callManager.connection}get establishedRTCSession(){return this.callManager.establishedRTCSession}get isCallActive(){return this.callManager.isCallActive}get remoteCallerData(){return this.incomingCallManager.remoteCallerData}get isAvailableIncomingCall(){return this.incomingCallManager.isAvailableIncomingCall}on(e,t){return this.events.on(e,t)}once(e,t){return this.events.once(e,t)}onceRace(e,t){return this.events.onceRace(e,t)}async wait(e){return this.events.wait(e)}off(e,t){this.events.off(e,t)}connect=async(...e)=>this.connectionManager.connect(...e);set=async(...e)=>this.connectionManager.set(...e);disconnect=async()=>this.connectionManager.disconnect();register=async()=>this.connectionManager.register();unregister=async()=>this.connectionManager.unregister();tryRegister=async()=>this.connectionManager.tryRegister();sendOptions=async(e,t,s)=>this.connectionManager.sendOptions(e,t,s);ping=async(e,t)=>this.connectionManager.ping(e,t);checkTelephony=async e=>this.connectionManager.checkTelephony(e);isConfigured=()=>this.connectionManager.isConfigured();getConnectionConfiguration=()=>this.connectionManager.getConnectionConfiguration();getSipServerUrl=e=>this.connectionManager.getSipServerUrl(e);call=async e=>this.callManager.startCall(this.connectionManager.getUaProtected(),this.getSipServerUrl,e);hangUp=async()=>this.callManager.endCall();answerToIncomingCall=async e=>this.callManager.answerToIncomingCall(this.incomingCallManager.extractIncomingRTCSession,e);declineToIncomingCall=async(...e)=>this.incomingCallManager.declineToIncomingCall(...e);getEstablishedRTCSession=()=>this.callManager.getEstablishedRTCSession();getCallConfiguration=()=>this.callManager.getCallConfiguration();getRemoteStreams=()=>this.callManager.getRemoteStreams();replaceMediaStream=async(...e)=>this.callManager.replaceMediaStream(...e);async startPresentation(e,t={}){const{isP2P:s,callLimit:i,...r}=t;return this.presentationManager.startPresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,r,i===void 0?void 0:{callLimit:i})}async stopPresentation(e={}){const{isP2P:t}=e;return this.presentationManager.stopPresentation(async()=>{t===!0?await this.apiManager.sendMustStopPresentationP2P():await this.apiManager.sendStoppedPresentation()})}async updatePresentation(e,t={}){const{isP2P:s,...i}=t;return this.presentationManager.updatePresentation(async()=>{s===!0?(await this.apiManager.sendMustStopPresentationP2P(),await this.apiManager.askPermissionToStartPresentationP2P()):await this.apiManager.askPermissionToStartPresentation()},e,i)}async waitChannels(...e){return this.apiManager.waitChannels(...e)}async waitSyncMediaState(...e){return this.apiManager.waitSyncMediaState(...e)}async sendDTMF(...e){return this.apiManager.sendDTMF(...e)}async sendChannels(...e){return this.apiManager.sendChannels(...e)}async sendMediaState(...e){return this.apiManager.sendMediaState(...e)}async sendRefusalToTurnOn(...e){return this.apiManager.sendRefusalToTurnOn(...e)}async sendRefusalToTurnOnMic(...e){return this.apiManager.sendRefusalToTurnOnMic(...e)}async sendRefusalToTurnOnCam(...e){return this.apiManager.sendRefusalToTurnOnCam(...e)}async sendMustStopPresentationP2P(...e){return this.apiManager.sendMustStopPresentationP2P(...e)}async sendStoppedPresentationP2P(...e){return this.apiManager.sendStoppedPresentationP2P(...e)}async sendStoppedPresentation(...e){return this.apiManager.sendStoppedPresentation(...e)}async askPermissionToStartPresentationP2P(...e){return this.apiManager.askPermissionToStartPresentationP2P(...e)}async askPermissionToStartPresentation(...e){return this.apiManager.askPermissionToStartPresentation(...e)}async askPermissionToEnableCam(...e){return this.apiManager.askPermissionToEnableCam(...e)}subscribe(){this.connectionManager.events.eachTriggers((e,t)=>{this.connectionManager.on(t,s=>{this.events.trigger(`connection:${t}`,s)})}),this.callManager.events.eachTriggers((e,t)=>{this.callManager.on(t,s=>{this.events.trigger(`call:${t}`,s)})}),this.apiManager.events.eachTriggers((e,t)=>{this.apiManager.on(t,s=>{this.events.trigger(`api:${t}`,s)})}),this.incomingCallManager.events.eachTriggers((e,t)=>{this.incomingCallManager.on(t,s=>{this.events.trigger(`incoming-call:${t}`,s)})}),this.presentationManager.events.eachTriggers((e,t)=>{this.presentationManager.on(t,s=>{this.events.trigger(`presentation:${t}`,s)})})}}exports.ECallCause=V;exports.EEventsMainCAM=m;exports.EUseLicense=Y;exports.Originator=v;exports.SipConnector=$e;exports.disableDebug=Te;exports.enableDebug=ge;exports.hasCanceledStartPresentationError=Ne;exports.logger=p;